https://gcc.gnu.org/bugzilla/show_bug.cgi?id=128686
Bug ID: 128686
Summary: [ranger] wrong code with -frounding-math: reverse
range of MULT_EXPR assumes overflow rounds to +-inf,
so |y| <= 2^127 is derived from a finite y * 2.0
although FLT_MAX * 2 rounds to FLT_MAX under
FE_TOWARDZERO
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 with -frounding-math at -O1 and above. Ranger assumes
an
* overflowing y * 2.0 (from y + y) always gives +-inf, so from the finite t it
derives
* |y| <= 2^127 and folds y > 2e38f to false. Under FE_TOWARDZERO (or
FE_DOWNWARD for
* positive y) FLT_MAX + FLT_MAX rounds to FLT_MAX, which is finite.
* Godbolt: x86-64 gcc (trunk), flags: -O2 -frounding-math -lm (correct: -O0;
GCC 11.4; clang -O2)
* EXPECTED: prints 1, exit 0. BUGGY: prints 0, exit 1.
*/
#include <stdio.h>
#include <fenv.h>
__attribute__((noinline)) int f(float y) {
float t = y + y; /* FLT_MAX + FLT_MAX == FLT_MAX when rounding
toward zero */
if (t - t == 0.0f) /* false only if t is inf or NaN */
return y > 2e38f;
return 7;
}
int main(void) {
volatile float y = 3.4028234663852886e38f; /* FLT_MAX */
fesetround (FE_TOWARDZERO);
int r = f(y);
fesetround (FE_TONEAREST);
printf("%d\n", r);
return r != 1;
}
```
Resulted in this output:
```
$ gcc -O2 -frounding-math repro.c -lm && ./a.out (also -O1, -O3)
0
(exit 1; gcc -O0 -frounding-math, GCC 11.4 -O2 -frounding-math and clang -O2
-frounding-math print 1)
```
Trunk: https://godbolt.org/z/Pn7sreY1M (x86-64 gcc trunk, -O2 -frounding-math
-lm, executed; reproduces as of 2026-11-12)
Root cause: `y + y` is canonicalized to `t = y * 2.0`. On the edge where `t - t
== 0.0f` holds, `t` is finite, `[-FLT_MAX, FLT_MAX]`, and
`operator_mult::op1_range` (gcc/range-op-float.cc) computes `y` from the
widened lhs (`frange::widen`) divided by 2. `float_widen_bound`
(gcc/value-range.cc) widens a `+-MAX` bound only to "one ulp past MAX"
(`2^(emax)`, see its comment), also with `-frounding-math`, so `y = [-2^127,
2^127]`. That is only valid when an overflowing result rounds to +-inf, i.e. in
round-to-nearest. With `-frounding-math` the rounding mode is dynamic: under
FE_TOWARDZERO (and FE_DOWNWARD/FE_UPWARD for one sign) any value beyond FLT_MAX
rounds to FLT_MAX, which is finite. evrp then folds `y > 2e38f` to 0, while `y
== FLT_MAX` reaches the branch. The same widening is used by all reverse float
operations (also hit through float conversions, e.g. `(float) d` finite
implying `|d| < 2^128`).
Suggested fix: in `float_widen_bound`, when `flag_rounding_math` and the bound
is +-MAX (the next value is +-INF), return +-INF instead of the "one ulp
larger" value. This fixes the reproducer and the conversion variant we found.