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

            Bug ID: 61725
           Summary: [4.9 Regression] __builtin_ffs(0) leads to bad code
                    generation
           Product: gcc
           Version: 4.9.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: middle-end
          Assignee: unassigned at gcc dot gnu.org
          Reporter: jtaylor.debian at googlemail dot com

__builtin_ffs is well defined for 0 according to the gcc documentation:

Returns one plus the index of the least significant 1-bit of x, or if x is
zero, returns zero.

yet for following program gcc 4.9 and gcc-4.10 20140627 optimizes away the
conditional on the result value for zero inputs.


#include <stdio.h>

int main(int argc, char *argv[])
{
    int x;
    for (x = -128; x <= 128; x++) {
        int a = __builtin_ffs(x);
        if (x == 0 && a != 0)
            printf("%#x: %u\n", x, a); 
    }   
    return 0;
}

gcc test.c -O2
./a.out
# this should not print:
0: 0


disassembly:


  10:    83 c3 01                 add    $0x1,%ebx
  13:    81 fb 81 00 00 00        cmp    $0x81,%ebx
  19:    74 26                    je     41 <main+0x41>
  1b:    0f bc d3                 bsf    %ebx,%edx
  1e:    0f 44 d5                 cmove  %ebp,%edx
  21:    83 c2 01                 add    $0x1,%edx
  24:    85 db                    test   %ebx,%ebx       <<<<<<<< test on ebx
but not edx
  26:    75 e8                    jne    10 <main+0x10>

  28:    31 f6                    xor    %esi,%esi
  2a:    31 c0                    xor    %eax,%eax
  2c:    bf 00 00 00 00           mov    $0x0,%edi
  31:    83 c3 01                 add    $0x1,%ebx
  34:    e8 00 00 00 00           callq  39 <main+0x39>
  39:    81 fb 81 00 00 00        cmp    $0x81,%ebx

/tmp$ gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/tmp/gcc/libexec/gcc/x86_64-unknown-linux-gnu/4.10.0/lto-wrapper
Target: x86_64-unknown-linux-gnu
Configured with: ./configure --enable-languages=c --disable-bootstrap --prefix
/tmp/gcc CFLAGS='-g3 -O0' CXXFLAGS='-g3 -O0'
Thread model: posix
gcc version 4.10.0 20140627 (experimental) (GCC) 

gcc 4.8.2 appears to work fine

Reply via email to