Issue 237541
Summary [DAGCombiner] `(fadd (fmul x, c), x) -> (fmul x, c+1)` checks `reassoc` only on the fadd, turning `+Inf * 0.0 + +Inf` into +Inf instead of NaN
Labels miscompilation, llvm:SelectionDAG, generated by fuzzer
Assignees
Reporter ChoKyuWon
    ### reproducer
godbolt: https://godbolt.org/z/PEK7zn1Ed

```llvm
target triple = "x86_64-unknown-linux-gnu"

define float @f(float %x) {
  %m = fmul float %x, 0.0
  %a = fadd reassoc nsz float %m, %x
  ret float %a
}

define i32 @main() {
  %r = call float @f(float 0x7FF0000000000000)
  %isnan = fcmp uno float %r, 0.0
  %z = zext i1 %isnan to i32
  %exit_code = xor i32 %z, 1
  ret i32 %exit_code
}
```

```console
$ llc -O3 -o - issue-repro.ll
...
f: # @f
        .cfi_startproc
# %bb.0:
 retq
...

$ cat issue-repro-control.ll
target triple = "x86_64-unknown-linux-gnu"

define float @f(float %x) {
  %m = fmul float %x, 0.0
  %a = fadd nsz float %m, %x
  ret float %a
}

define i32 @main() {
  %r = call float @f(float 0x7FF0000000000000)
  %isnan = fcmp uno float %r, 0.0
  %z = zext i1 %isnan to i32
  %exit_code = xor i32 %z, 1
  ret i32 %exit_code
}

$ llc -O3 -o - issue-repro-control.ll
...
f: # @f
        .cfi_startproc
# %bb.0:
 xorps   %xmm1, %xmm1
        mulss   %xmm0, %xmm1
        addss %xmm1, %xmm0
        retq
...
```

### suggested fix
`DAGCombiner::visitFADD` gates its "If reassoc and nsz, fold lots of things" block (DAGCombiner.cpp:19642 on main) on `N`'s flags only, but `(fadd (fmul x, c), x) -> (fmul x, c+1)` also rewrites the inner `fmul`, which has no `reassoc`; LangRef's rewrite-based flags require the flag on every instruction of the rewritten _expression_.
Also require `reassoc` on the FMUL/FADD operand each fold looks through (`N0->getFlags().hasAllowReassociation()` or `N1->...`); the block's `fadd (fadd x, c1), c2` and `c+2` folds skip that check the same way (the `3.0`/`4.0` chains are exact and need no flag).
InstCombine's `(X * MulC) + X --> X * (MulC + 1.0)` in `visitFAdd` has the same gap (`opt -passes=instcombine` folds `@f` to `ret float %x`); #70561 asked about the `X - X * 0.0` form before LangRef #99557 made the inner flag a requirement.

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

Reply via email to