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

            Bug ID: 129209
           Summary: [17 Regression] wrong code at -O2: ivopts replaces the
                    exit test i == b by 4 * i == 4 * b
           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: jeffchen006 at gmail dot com
  Target Milestone: ---
            Target: x86_64-pc-linux-gnu

int printf(const char *, ...);
__attribute__((noipa)) unsigned long f(long b) {
  unsigned long s = 0;
  long i = 9223372036854775800;
  int g = 0;
  do {
    if (++g > 30) break;
    s += (unsigned long)i * 4;
    if (i == b) break;
    i = (long)((unsigned long)i - 5);
  } while (i > b);
  return s + (unsigned long)i;
}
int main(void) {
  printf("%lu\n", f(-128));
  return 0;
}

$ gcc -O1 t.c && ./a.out
9223372036854765990
$ gcc -O2 t.c && ./a.out
18446744073709544688

Wrong at -O2, -O3. -fno-ivopts gives 9223372036854765990.

Bisected to r17-2277-g6d975812860 ("ivopts: Set register pressure cost to zero
if there are enough registers"); it only changes the candidate choice.
ivopts uses the wrapping candidate 4 * i for the exit test b == i and rewrites
it as ivtmp == b * 4. Multiplication by 4 is not injective modulo 2^64, so the
loop leaves through this exit with a wrong i.

Clean with -fsanitize=address,undefined (gcc and clang).

gcc version 17.0.0 20261201 (experimental), r17-6987-gdeb313acd22,
x86_64-pc-linux-gnu
Configured with: --enable-languages=c,c++ --disable-multilib
--disable-bootstrap --enable-checking=release

Reply via email to