[InstCombine] Folding dependent IVs copies `nnan` onto the new first-iteration value
reproducer
godbolt: https://godbolt.org/z/vbdTr37x9 alive: https://alive2.llvm.org/ce/z/A6ycs6
define float @f(float %start, i1 %c) {
entry:
br label %loop
loop:
%iv = phi float [ %start, %entry ], [ %iv.next, %loop ]
%iv2 = phi float [ -0.0, %entry ], [ %iv2.next, %loop ]
%iv2.next = fadd float %iv2, 1.0
%iv.next = fadd nnan float %start, %iv2.next
br i1 %c, label %exit, label %loop
exit:
ret float %iv
}
$ opt -S -passes=instcombine repro.ll
define float @f(float %start, i1 %c) {
entry:
br label %loop
loop:
%iv2 = phi float [ -0.000000e+00, %entry ], [ %iv2.next, %loop ]
%iv2.next = fadd float %iv2, 1.000000e+00
br i1 %c, label %exit, label %loop
exit:
%iv = fadd nnan float %iv2, %start
ret float %iv
}
$ alive-tv --disable-undef-input --disable-poison-input --passes=instcombine --src-unroll=2 --tgt-unroll=2 repro.ll
ERROR: Target is more poisonous than source
Example:
float %start = #x7f880000 (SNaN)
i1 %c = #x1 (1)
Source value: #x7f880000 (SNaN)
Target value: poison
suggested fix
foldDependentIVs (InstCombinePHI.cpp) builds %iv = %iv2 op %start and calls copyIRFlags(BO) from %iv.next. On the first iteration that instruction computes identity op %start, which the source never evaluates (it yields %start itself), so nnan/ninf make it poison for a NaN/Inf %start.
Do not copy fast-math flags onto the new instruction (the integer wrap flags and the GEP path are fine: 0 + x and 1 * x never wrap, and a GEP with a zero index is always inbounds/nusw/nuw).
Disclaimer: This test case was generated by a fuzzer, and the report was written with LLM assistance.
Hi! We are a 2-student team participating in the CS3423 Compilers II hackathon at IIT Hyderabad, and We would like to work on this issue.
We read the reproducer and the explanation involving foldDependentIVs and the fast-math flags. We'd like to understand the transformation, investigate the miscompilation, and add regression tests.
Could you please let us know, We request assignment
Thank you!
Hello @ChoKyuWon @dtcxzyw ! I checked the output of the suggested fix.
I got the output for the following changes as suggested above:
define float @f(float %start, i1 %c) {
entry:
br label %loop
loop: ; preds = %loop, %entry
%iv2 = phi float [ -0.000000e+00, %entry ], [ %iv2.next, %loop ]
%iv2.next = fadd float %iv2, 1.000000e+00
br i1 %c, label %exit, label %loop
exit: ; preds = %loop
%iv = fadd float %iv2, %start
ret float %iv
}
I checked it in alive2 and it doesn't verify. It's in the %exit BB where there's a fadd and %start could possibly be poison. Behaviour of floating point operation on NaN values is non-deterministic(LLVM ref).