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

            Bug ID: 129043
           Summary: [niter] wrong code at -O2: loop_niter_by_eval inverts
                    a float exit test with invert_tree_comparison (code,
                    false), turning !(x >= x) into x < x instead of UNLT,
                    so a NaN makes brute-force evaluation "prove" the loop
                    exits
           Product: gcc
           Version: 17.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c
          Assignee: unassigned at gcc dot gnu.org
          Reporter: 0599jiangyc at gmail dot com
  Target Milestone: ---

The following code:

```c
/* GCC trunk: wrong code at -O2 / -O3 / -Os (default flags); correct at -O0,
-O1, GCC 11.4 -O2, clang -O2.
 * loop_niter_by_eval (tree-ssa-loop-niter.cc) turns the exit test "x >= x"
(exit on the true edge)
 * into the stay-in-loop test with invert_tree_comparison (GE_EXPR, false) =
LT_EXPR instead of
 * UNLT_EXPR.  x is NaN, so "x < x" folds to false and cunrolli "proves" the
loop iterates 0 times
 * by brute force; the loop is removed and f returns 0.
 * Godbolt: x86-64 gcc (trunk), flags: -O2
 * EXPECTED: prints 5, exit 0.   BUGGY: prints 0, exit 1.
 */
#include <stdio.h>

__attribute__((noipa)) int f(int n) {
  double x = __builtin_nan ("");
  int i;
  for (i = 0; i < n; i++)
    if (x >= x)          /* never true: x is NaN */
      break;
  return i;
}

int main(void) {
  int r = f(5);
  printf("%d\n", r);
  return r != 5;
}
```

Resulted in this output:
```
$ gcc -O2 repro.c && ./a.out        (also -O3, -Os)
0
(exit 1; gcc -O0, -O1, GCC 11.4 -O2 and clang -O2 print 5)
```

Trunk: https://godbolt.org/z/aGMMveEsh (x86-64 gcc trunk, -O2, executed;
reproduces as of 2026-11-12)

Reply via email to