| Issue |
241894
|
| Summary |
[flang] SCALE/IEEE_SCALB constant folding gives +Inf for SCALE(0.5, 128) and wrong subnormals for SCALE(1.5, -150)
|
| Labels |
flang
|
| Assignees |
|
| Reporter |
0z5a
|
When the scale factor 2**I lies just outside the representable range, folding SCALE (and IEEE_SCALB, which is a rename of SCALE) gives a different result from the run-time library.
```fortran
program repro
use ieee_arithmetic, only: ieee_scalb
implicit none
real, parameter :: f(4) = [scale(0.5, 128), ieee_scalb(0.5, 128), &
scale(1.0, -150), scale(1.5, -150)]
real(8), parameter :: g(2) = [scale(0.5d0, 1024), scale(1.5d0, -1075)]
real, volatile :: h, one, x15
real(8), volatile :: dh, dx15
h = 0.5; _one_ = 1.0; x15 = 1.5; dh = 0.5d0; dx15 = 1.5d0
print '(a,4z9.8)', 'folded r4:', transfer(f, [0])
print '(a,4z9.8)', 'runtime r4:', transfer([scale(h, 128), ieee_scalb(h, 128), &
scale(one, -150), scale(x15, -150)], [0])
print '(a,2z17.16)', 'folded r8:', transfer(g, [0_8])
print '(a,2z17.16)', 'runtime r8:', transfer([scale(dh, 1024), scale(dx15, -1075)], [0_8])
end program
```
flang trunk (x86-64, Compiler Explorer) warns `SCALE/IEEE_SCALB intrinsic folding overflow` three times and prints:
```
folded r4: 7F800000 7F800000 00000001 00000002
runtime r4: 7F000000 7F000000 00000000 00000001
folded r8: 7FF0000000000000 0000000000000002
runtime r8: 7FE0000000000000 0000000000000001
```
The run-time values are the correct ones:
- 0.5 * 2**128 = 2**127 is a finite normal number. F2023 16.9.178 says SCALE returns X * b**I when it is representable, and 17.11.37 case (i) says the same for IEEE_SCALB. Folding returns +Inf and reports an overflow. gfortran folds `scale(0.5,128)` to 7F000000.
- 1.5 * 2**-150 is 0.75 of the least subnormal, so the nearest representable value is the least subnormal (00000001), not 00000002. In the same way, 1.0 * 2**-150 is a tie that rounds to zero.
The same thing happens for every kind, at I = MAXEXPONENT(X) and at I = -(bias + DIGITS(X) - 1), i.e. -150 for REAL(4), -1075 for REAL(8) and -25 for REAL(2). A sweep of 600 random cases near both edges, checked against an exactly rounded reference, shows wrong folded values only at those two exponents. The behaviour goes back to at least flang 17.
Cause: `Real::SCALE` in flang/include/flang/Evaluate/real.h builds 2**I with `Normalize()` from a fraction with only its LSB set. The guards `expo > maxCoeffExpo` and `expo < 0` are off by one. At `expo == maxCoeffExpo` the factor becomes +Inf. At `expo == 0` Normalize encodes 2**-149 instead of 2**-150. In addition, the underflow two-step path only covers |X| >= 2.
A fix with a regression test is ready. I can open a pull request for it.
Assisted-by: Claude (claude-opus-5-5). I reviewed the change and this text.
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs