File scope variables in C++ optimised differently in gcc and clang

Viewed 92

I was playing around with Godbolt and I was surprised to see that the following simple C++ code had different compiled outputs on x86-64 gcc 10.2 and x86-64 clang 11.0.0 with -O2 level optimization.

static int x = 0;
int const y = x;

int main()
{
    x = 0; // should be optimised out?
}

gcc:

main:
        mov     DWORD PTR x[rip], 0
        xor     eax, eax
        ret
_GLOBAL__sub_I_main:
        ret

clang:

main:                                   # @main
        xor     eax, eax
        ret

Why can clang prove that x is unused and optimise it out but not gcc?

1 Answers

Optimizers only optimize whatever got implemented into them.

In this case, I believe that Clang is correct with the optimization as the initialization in main is the very first assignment happening to a global. This global can't be touched, as initialization of globals over multiple compilation units can't rely on globals from another compilation unit.

Since you don't initialize any other global that is changing a, the value was 0 before the assignment and it ain't needed.

I think this is just an edge case where the modeling of clang causes this to optimize the code. If you are using more complex code, this kind of optimizations will most likely not even be measurable.

Related