cpp
cpp

Reputation: 331

Why -O2 has more number of instructions than compilation without optimization

I tried out following codes in https://godbolt.org/z/9xWvzcdbq without optimization option and https://godbolt.org/z/9WTocce97 with optimization option -O2

The without optimization option version generating 43 lines of assembly instructions with instruction bl std::atomic<int*>::load(std::memory_order) const while the version with -O2 optimization option generating 49 lines of assembly instructions with data memory barrier dmb ish.

Is that expected and why? Is it partly because the version with -O2 optimization option optimizing the instruction bl std::atomic<int*>::load(std::memory_order) const by breaking it down in to more instructions?

#include <atomic>
#include <iostream>
 
void print(int* val)
{
    std::cout << *val << std::endl;
}
 
int main()
{
    int x{42};
    std::atomic<int*> p = &x;
    int* local = p.load(std::memory_order_consume);
    print(local);
}

Upvotes: 0

Views: 218

Answers (1)

cpplearner
cpplearner

Reputation: 15928

Compiler Explorer hides library function definitions by default. If you deselect 'Filter > Library functions', you will notice that the non-optimized version actually generates 143 lines of assembly, while the optimized version has only 52 lines of assembly. The library function definitions are optimized out in -O2 due to function inlining.

Upvotes: 4

Related Questions