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

            Bug ID: 128942
           Summary: wrong code at -Os: (int)((unsigned)x + 100) / 4 after
                    a loop adding x + 100 that runs zero times
           Product: gcc
           Version: 17.0
            Status: UNCONFIRMED
          Keywords: wrong-code
          Severity: normal
          Priority: P3
         Component: tree-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: shimizu2486 at gmail dot com
  Target Milestone: ---

Live reproducer: https://godbolt.org/z/b6ahPYP3e

$ cat t1.c
#include <stdio.h>
int x = 2147483647, n, acc;
int main(void) {
  x &= 2147483647;
  while (n--)
    acc += x + 2;
  printf("%d\n", (int)((unsigned)x + 2) / 2);
}

n is 0, so the loop does not run.
x is INT_MAX, so (unsigned)x + 2 is 0x80000001, which is -2147483647 as int,
and -2147483647 / 2 is -1073741823.  The program should print -1073741823.

$ gcc -O2 t1.c -o t1 && ./t1
-1073741823                         (correct)
$ gcc -Os t1.c -o t1 && ./t1
1073741824                          (wrong)

  x86_64 trunk (cdb8a10e1a82)            wrong (1073741824)
  x86_64 16.2.0, 15.3.0, 14.4.0          wrong (1073741824)
  x86_64 13.5.0, 12.5.0, 11.5.0, 10.5.0  wrong (-1073741824)
  x86_64 9.5.0                           correct

-Os is wrong. -O0, -O1, -O2, -O3 and -Og are correct, but -O2 -fno-tree-ch is
wrong too.
-fno-tree-scev-cprop or -fno-tree-fre makes -Os print -1073741823 correctly.

Reply via email to