Here's my original test code

  typedef struct P 
  { 
    unsigned long long r; 
    unsigned char e; 
  } P;

  P foo(void)
  {
    unsigned long long r = rand();
    return (P) { r, r % 2 };
  }

The x86 code GCC generates in -O3 mode is surprisingly weird

  "foo":
        sub     rsp, 24
        call    "rand"
        mov     DWORD PTR [rsp], 0
        movsxd  rsi, eax
        mov     DWORD PTR [rsp+3], 0
        movabs  rax, 72057594037927935
        and     rax, QWORD PTR [rsp]
        sal     rax, 8
        add     rsp, 24
        mov     rdx, rax
        mov     rax, rsi
        mov     dl, sil
        and     dl, 1
        ret

As you can see, GCC expectedly intends to return the result in rax:rdx pair. 
And GCC intends to zero-out 
the padding bytes in rdx (not required by the standard, but apparently an ABI 
requirement). So, in order 
to achieve that GCC prepares a 7-byte all-zeroes area on the stack to later 
load and shift it into the 
intended location inside the register by means of 'and' and 'sal' instructions. 
This also involves a 
7-byte mask loaded by means of 'movabs' instruction.

And it insists on making that memory area 7 bytes long specifically. 7, not 8. 
For which it even resorts 
to unaligned access.

And it all happens before the register received any meaningful data, meaning 
that there is no valuable data in 
it to dance around.

Why is it jumping through all these hoops?! The idea to prepare a zeroed-out 
memory area just to 
initialize a register with it is beyond weird.

The issue is somehow specific to compound literals. The following versions of 
the function

  P bar(void)
  {
    P p = { 0 };
    p.r = rand();
    p.e = p.r % 2;
    return p;
  }

  P baz(void)
  {
    unsigned long long r = rand();
    P p = { r, r % 2 };
    return p;
  }

produce more reasonable and efficient code (identical for 'bar' and 'baz')

  "bar":
        sub     rsp, 8
        call    "rand"
        add     rsp, 8
        mov     ecx, eax
        cdqe
        movzx   edx, cl
        and     dl, 1
        ret

The same issue is present in C++ code as well. Compound literals (as an 
extension) or simple 'return' 
with '{ ... }' initializer both produce the "weird" version of the code.

Apparently, compound-literal-like contexts still are overlooked children in GCC 
back end. What perplexes 
me most is that their semantics is expected to be basically the same as 
"variable with an {} initializer, 
just unnamed". But GCC's code generator behavior is quite different for named 
variables (as in 'baz') and 
unnamed ones (i.e. compound literals).

-- 
Best regards,
Andrey

Reply via email to