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

            Bug ID: 96392
           Summary: Optimize x+0.0 if x is an integer
           Product: gcc
           Version: 10.1.1
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: tree-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: hugo_musso_gualandi at hotmail dot com
  Target Milestone: ---

One way to convert an integer to a floating point number in C is to multiply it
by 1.0. In this case, gcc is clever enough to optimize away the multiplication.

Another way is to add 0.0. However, in this case, GCC does not optimize away
the addition. 

Example C code:

    double times1(int x)
    {
        return x * 1.0;
    }

    double plus0(int x)
    {
        return x + 0.0;
    }

Output of objdump -d after compiling with gcc -O2 -c:

    0000000000000000 <times1>:
       0:       66 0f ef c0             pxor   %xmm0,%xmm0
       4:       f2 0f 2a c7             cvtsi2sd %edi,%xmm0
       8:       c3                      retq   
       9:       0f 1f 80 00 00 00 00    nopl   0x0(%rax)

    0000000000000010 <plus0>:
      10:       66 0f ef c0             pxor   %xmm0,%xmm0
      14:       f2 0f 2a c7             cvtsi2sd %edi,%xmm0
      18:       f2 0f 58 05 00 00 00    addsd  0x0(%rip),%xmm0
      1f:       00 
      20:       c3                      retq   

I believe that the reason that GCC does not optimize x+0.0 is that it is
worried that x could be negative zero. However, promoting an integer to
floating point can never yield negative zero so it should be possible to
optimize in this particular case. (For the matter, Clang does optimize it.)

Reply via email to