Issue 235317
Summary [GlobalISel] Constant folding llvm.sqrt.f80 through double loses extended precision
Labels miscompilation, llvm:globalisel, generated by fuzzer
Assignees
Reporter ChoKyuWon
    ### reproducer
godbolt: https://godbolt.org/z/3M67KzKbz

```llvm
declare x86_fp80 @llvm.sqrt.f80(x86_fp80)

define i32 @main() {
  %root = call x86_fp80 @llvm.sqrt.f80(x86_fp80 0xK40008000000000000000)
  %correct = fcmp oeq x86_fp80 %root, 0xK3FFFB504F333F9DE6484
  %result = zext i1 %correct to i32
  ret i32 %result
}
```

```console
$ opt -passes=verify -disable-output repro.ll

$ llc -O2 -global-isel -mtriple=x86_64-unknown-linux-gnu repro.ll -o - | sed -n '/^\.LCPI0_0:/,+3p'
.LCPI0_0:
        .quad   0xb504f333f9de6800 # x86_fp80 1.41421356237309514547
        .short  0x3fff
        .zero 6

$ llc -O2 -mtriple=x86_64-unknown-linux-gnu repro.ll -o dag.s
$ clang -no-pie dag.s -o dag
$ ./dag; echo $?
1
$ llc -O2 -global-isel -mtriple=x86_64-unknown-linux-gnu repro.ll -o gisel.s
$ clang -no-pie gisel.s -o gisel
$ ./gisel; echo $?
0

$ python3 -I -c 'import math; n = 1 << 127; r = math.isqrt(n); r += 4*n > (2*r+1)**2; print("Correctly rounded sqrt(2): 0xK3FFF%016X" % r)'
Correctly rounded sqrt(2): 0xK3FFFB504F333F9DE6484
```

### suggested fix
`constantFoldFpUnary` in `llvm/lib/CodeGen/GlobalISel/CombinerHelper.cpp` evaluates `G_FSQRT`/`G_FLOG2` via host `double` and widens the result, violating `llvm.sqrt.f80`'s libm-compatible accuracy without `afn`.
Inspect the constant's existing APFloat semantics before any LLT-to-semantics conversion; reject folds with greater precision or exponent range than IEEE double unless evaluation preserves the original semantics.
Make the unary fold fallible or add a match guard to retain the original instruction; coordinate with the overlapping work in https://github.com/llvm/llvm-project/pull/220876

_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to