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

            Bug ID: 128687
           Summary: [ranger] wrong code at -O1 and above: range_of_phi
                    drops PHI arguments related by VREL_EQ for floats, but
                    -0.0 == +0.0, so signbit of a loop PHI is folded to 0
           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 -O1 and above (also -O2/-O3/-Os); correct at -O0,
GCC 11.4, clang.
 * Ranger's range_of_phi drops the latch argument y because the edge of !(y !=
x) registered
 * VREL_EQ (y, x); for floats equality does not imply identical values (-0.0 ==
+0.0), so the
 * PHI for x gets [+0.0, +0.0] and __builtin_signbit (x) is folded to 0.
 * Godbolt: x86-64 gcc (trunk), flags: -O2
 * EXPECTED: prints 1, exit 0.   BUGGY: prints 0, exit 1.
 */
#include <stdio.h>

__attribute__((noipa)) int f(int n, double m) {
  double x = 0.0;
  int s = 0;
  for (int i = 0; i < n; i++) {
    double y = x * m;            /* m = -1: x is +0.0, then -0.0 */
    if (y != x)
      break;
    s += __builtin_signbit (x) != 0;
    x = y;
  }
  return s;
}

int main(void) {
  int r = f(2, -1.0);            /* second iteration has x == -0.0 */
  printf("%d\n", r);
  return r != 1;
}
```

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

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

Root cause: `fold_using_range::range_of_phi` (gcc/gimple-range-fold.cc) puts
every PHI argument with `oracle->query (e, arg, phi_def) == VREL_EQ` into
`equiv_range` instead of the PHI's range, on the assumption that an equivalent
argument provides no new values. For the loop PHI `x = PHI <0.0 (preheader), y
(latch)>`, the latch edge is reached only when `!(y != x)`, which registers
`VREL_EQ (y, x)`. For floating-point types equality does not mean the same
value: `y` can be `-0.0` while `x` is `+0.0`. So the latch argument is dropped,
`x` gets `[+0.0, +0.0]`, and `__builtin_signbit (x)` is folded to 0 (dom2 at
-O1; evrp/vrp at -O2). The equivalence path in the ranger cache already
accounts for this (`adjust_equivalence_range` adds both zeros), but
`range_of_phi` does not.

Suggested fix: in `range_of_phi`, for floating-point types that honor signed
zeros, do not treat VREL_EQ arguments as providing no information; either union
them normally, or union `arg_range` with both zeros added (as
`adjust_equivalence_range` does) before putting it into `equiv_range`.

Reply via email to