jeudi 27 juin 2019

Is gcc missing an opportunity to optimize ctor initializer lists?

Consider these two structs (legal C++11 and beyond):

struct A {
    unsigned int a = 5;
} a;

struct B {
    unsigned int b;
    B() : b(5) {}
} b;

As far as I understood, a and b should produce exactly the same code.

clang (8.0.0) does what I expect and produces the following assembly:

a:
        .long   5                       # 0x5
b:
        .long   5                       # 0x5

g++ (9.1) seems to miss this optimization opportunity:

_GLOBAL__sub_I_a:
        mov     DWORD PTR b[rip], 5
        ret
b:
        .zero   4
a:
        .long   5

See the code on godbolt. What g++ compiles to is equivalent to this:

struct C {
    unsigned int c;
    C() { c = 5; } // initialize + assign
} c;

which I would not expect, especially because I compile with -O3. Is this an "optimization bug"?

Aucun commentaire:

Enregistrer un commentaire