| Issue |
241266
|
| Summary |
[DAGCombiner] combineFMulOrFDivWithIntPow2 does not check that 2^n is finite (half) (miscompile at -O3)
|
| Labels |
new issue
|
| Assignees |
|
| Reporter |
jeffchen006
|
`fdiv half C, uitofp(1 << n)` is folded into an exponent subtraction. For `half`, `(_Float16)65536` is +inf, so the right result is 0, but the fold gives 0.125.
**Reproducer** (`repro.c`)
```c
/* For n == 16, (_Float16)65536 is +inf (the largest finite _Float16 is 65504),
so h = 8192 / inf = 0: the program must print 0. Clang -O3 prints 0.125. */
int printf(const char *, ...);
volatile unsigned n = 16;
int main(void) {
_Float16 h = (_Float16)8192.0 / (_Float16)(1u << (n & 16));
printf("%g\n", (double)h);
return 0;
}
```
**Commands and output** (clang version 24.0.0git (https://github.com/llvm/llvm-project.git 8207e9143575), Target: x86_64-unknown-linux-gnu):
```console
$ clang -O0 repro.c -o o0
$ ./o0
0
$ clang -O3 repro.c -o o3
$ ./o3
0.125
```
Expected (as `-O0`): `0`. `-O3` prints `0.125`.
**Why the expected output is right**
`1u << 16` is defined. `_Float16` has infinity, so `(_Float16)65536` rounds to +inf (IEEE, C23 Annex H); `8192 / inf = +0`. UBSan/ASan/MSan at -O0 are clean. (gcc 11 has no x86 `_Float16`.)
**Potential Root cause**
`llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp`, `combineFMulOrFDivWithIntPow2`: `MaxExpChange = countMaxActiveBits(Pow2Op)` (17 here). `IsFPConstValid` checks only that the exponent of the result stays in range. It never checks that 2^n itself is finite in VT. For half, 2^16 > 65504. The fmul form has the same hole. llc folds at every level; InstCombine makes the matched shape at -O3.
**Possible Proposed fix**
```diff
+ // uitofp/sitofp of 2^n must not overflow to inf in VT.
+ if (MaxExpChange - 1 > APFloat::semanticsMaxExponent(VT.getFltSemantics()))
+ return false;
```
**Reduced IR**
```llvm
target triple = "x86_64-unknown-linux-gnu"
; as in -O3 IR of case.c: fold fires
define half @h(i32 %0) noinline {
%2 = and i32 %0, 16
%3 = shl nuw nsw i32 1, %2
%4 = uitofp nneg i32 %3 to half
%5 = fdiv half 8.192000e+03, %4
ret half %5
}
; same value, but the divisor is not a UINT_TO_FP node (what the fold would leave alone)
define half @h_nofold(i32 %0) noinline {
%2 = and i32 %0, 16
%3 = shl nuw nsw i32 1, %2
%f = uitofp nneg i32 %3 to float
%4 = fptrunc float %f to half
%5 = fdiv half 8.192000e+03, %4
ret half %5
}
; FMUL twin: 2^-10 * (half)65536 = 2^-10 * inf = inf
define half @m(i32 %0) noinline {
%2 = and i32 %0, 16
%3 = shl nuw nsw i32 1, %2
%4 = uitofp nneg i32 %3 to half
%5 = fmul half 0xH1400, %4
ret half %5
}
```
`llc -O2` on `@h(16)` returns 0.125 (the fold fires); `@h_nofold` gives 0. `@m` is the fmul form (64, expected inf).
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs