https://gcc.gnu.org/bugzilla/show_bug.cgi?id=81533

            Bug ID: 81533
           Summary: g++ pops up a constructor for objects that could be
                    initialized at load-time
           Product: gcc
           Version: 8.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: gjl at gcc dot gnu.org
  Target Milestone: ---

Created attachment 41817
  --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=41817&action=edit
foo.cpp: C++ test case

When compiling the following module with g++ from v8 trunk

$ g++ foo.cpp -S -O2 -save-temps

then it pops a constructor to initialize s:

struct S { int id; const char *labl; };

const S* get_S_B()
{
  static const S s =
    { 456,
      (__extension__({
          static char ccc[] = "TextB";
          &ccc[0];
        })) };
  return &s;
}


The generated assembly reads (x86_64):

_Z7get_S_Bv:
.LFB0:
        .cfi_startproc
        movzbl  _ZGVZ7get_S_BvE1s(%rip), %eax
        testb   %al, %al
        je      .L13
        movl    $_ZZ7get_S_BvE1s, %eax
        ret
        .p2align 4,,10
        .p2align 3
.L13:
        subq    $8, %rsp
        .cfi_def_cfa_offset 16
        movl    $_ZGVZ7get_S_BvE1s, %edi
        call    __cxa_guard_acquire
        testl   %eax, %eax
        jne     .L14
        movl    $_ZZ7get_S_BvE1s, %eax
        addq    $8, %rsp
        .cfi_remember_state
        .cfi_def_cfa_offset 8
        ret


The code could be just as smart as with the following test case

struct S { int id; const char *labl; };

const S* get_S_A()
{
  static const S s = { 123, "TextA" };
  return &s;
}

which generates:

_Z7get_S_Av:
        movl    $_ZZ7get_S_AvE1s, %eax
        ret

        .section        .rodata.str1.1,"aMS",@progbits,1
.LC0:
        .string "TextA"

        .section        .rodata
_ZZ7get_S_AvE1s:
        .long   123
        .zero   4
        .quad   .LC0
        .ident  "GCC: (GNU) 8.0.0 20170724 (experimental)"


The first version with the "TextB" assignment to ccc is useful when ccc needs a
variable attribute.

Reply via email to