[llvm] [ValueTracking] Clarify KnownBits recurrence code (PR #222266)

Nikita Popov via llvm-commits llvm-commits at lists.llvm.org
Wed Sep 9 03:05:01 PDT 2026


================
@@ -1889,22 +1889,20 @@ static void computeKnownBitsFromOperator(const Operator *I,
         // D69571).
         SimplifyQuery RecQ = Q.getWithoutCondContext();
 
-        unsigned OpNum = P->getOperand(0) == R ? 0 : 1;
-        Instruction *RInst = P->getIncomingBlock(OpNum)->getTerminator();
-        Instruction *LInst = P->getIncomingBlock(1 - OpNum)->getTerminator();
+        unsigned OpNum = P->getOperand(0) == Start ? 0 : 1;
+        Instruction *StartTerm = P->getIncomingBlock(OpNum)->getTerminator();
 
-        // Ok, we have a PHI of the form L op= R. Check for low
+        // Ok, we have a recurrence of the form {Start,op,Step}. Check for low
         // zero bits.
-        RecQ.CxtI = RInst;
-        computeKnownBits(R, DemandedElts, Known2, RecQ, Depth + 1);
+        RecQ.CxtI = StartTerm;
+        computeKnownBits(Start, DemandedElts, Known2, RecQ, Depth + 1);
 
         // We need to take the minimum number of known bits
-        KnownBits Known3(BitWidth);
-        RecQ.CxtI = LInst;
-        computeKnownBits(L, DemandedElts, Known3, RecQ, Depth + 1);
+        KnownBits KnownStep(BitWidth);
+        computeKnownBits(Step, DemandedElts, KnownStep, Q, Depth + 1);
----------------
nikic wrote:

Here is an example:
```llvm
declare i32 @get_step()

define i1 @test() {
entry:
  br label %loop

loop:
  %iv = phi i32 [0, %entry], [%iv.next, %latch]
  %step = call i32 @get_step()
  %iv.next = add nsw i32 %iv, %step
  %c = icmp sge i32 %step, 0
  br i1 %c, label %exit, label %latch

latch:
  br label %loop

exit:
  %result = icmp sge i32 %iv, 0
  ret i1 %result
}
```
This fold to true with this patch, which is incorrect.

https://github.com/llvm/llvm-project/pull/222266


More information about the llvm-commits mailing list