[llvm] [LoopBoundSplit] Bail out when the recurrence is not this loop's IV (PR #221604)

Timur Baidusenov via llvm-commits llvm-commits at lists.llvm.org
Wed Sep 9 20:54:11 PDT 2026


https://github.com/bai-tim updated https://github.com/llvm/llvm-project/pull/221604

>From 865a4c0ac0411cedb724256618abaec6985a670b Mon Sep 17 00:00:00 2001
From: Timur Baidusenov <timurbaidusenov at gmail.com>
Date: Sun, 6 Sep 2026 22:34:28 +0300
Subject: [PATCH 1/2] [LoopBoundSplit][NFC] Merge analyzeICmp() into
 hasProcessableCondition()

analyzeICmp() filled ConditionInfo in place and reported nothing back, so a
condition it could not describe left partially initialized fields behind for
hasProcessableCondition() to reject afterwards. Fold it into its only caller,
analyze into locals, and write ConditionInfo only once every check has passed.

The early return on a failed match is not reachable: both callers of
hasProcessableCondition() run isProcessableCondBI() first, which already
requires the branch condition to be an ICmp. The reordered checks are pure
predicates that all have to hold, so the set of accepted conditions is
unchanged.

Suggested in the review of #167227.

Assisted-by: Claude (Anthropic)
---
 llvm/lib/Transforms/Scalar/LoopBoundSplit.cpp | 80 ++++++++++---------
 1 file changed, 41 insertions(+), 39 deletions(-)

diff --git a/llvm/lib/Transforms/Scalar/LoopBoundSplit.cpp b/llvm/lib/Transforms/Scalar/LoopBoundSplit.cpp
index 1eb528551e3fd..6f16736315952 100644
--- a/llvm/lib/Transforms/Scalar/LoopBoundSplit.cpp
+++ b/llvm/lib/Transforms/Scalar/LoopBoundSplit.cpp
@@ -35,7 +35,7 @@ struct ConditionInfo {
   /// AddRec llvm value
   Value *AddRecValue = nullptr;
   /// Non PHI AddRec llvm value
-  Value *NonPHIAddRecValue;
+  Value *NonPHIAddRecValue = nullptr;
   /// Bound llvm value
   Value *BoundValue = nullptr;
   /// AddRec SCEV
@@ -47,35 +47,6 @@ struct ConditionInfo {
 };
 } // namespace
 
-static void analyzeICmp(ScalarEvolution &SE, ICmpInst *ICmp,
-                        ConditionInfo &Cond, const Loop &L) {
-  Cond.ICmp = ICmp;
-  if (match(ICmp, m_ICmp(Cond.Pred, m_Value(Cond.AddRecValue),
-                         m_Value(Cond.BoundValue)))) {
-    const SCEV *AddRecSCEV = SE.getSCEV(Cond.AddRecValue);
-    const SCEV *BoundSCEV = SE.getSCEV(Cond.BoundValue);
-    const SCEVAddRecExpr *LHSAddRecSCEV = dyn_cast<SCEVAddRecExpr>(AddRecSCEV);
-    const SCEVAddRecExpr *RHSAddRecSCEV = dyn_cast<SCEVAddRecExpr>(BoundSCEV);
-    // Locate AddRec in LHSSCEV and Bound in RHSSCEV.
-    if (!LHSAddRecSCEV && RHSAddRecSCEV) {
-      std::swap(Cond.AddRecValue, Cond.BoundValue);
-      std::swap(AddRecSCEV, BoundSCEV);
-      Cond.Pred = ICmpInst::getSwappedPredicate(Cond.Pred);
-    }
-
-    Cond.AddRecSCEV = dyn_cast<SCEVAddRecExpr>(AddRecSCEV);
-    Cond.BoundSCEV = BoundSCEV;
-    Cond.NonPHIAddRecValue = Cond.AddRecValue;
-
-    // If the Cond.AddRecValue is PHI node, update Cond.NonPHIAddRecValue with
-    // value from backedge.
-    if (Cond.AddRecSCEV && isa<PHINode>(Cond.AddRecValue)) {
-      PHINode *PN = cast<PHINode>(Cond.AddRecValue);
-      Cond.NonPHIAddRecValue = PN->getIncomingValueForBlock(L.getLoopLatch());
-    }
-  }
-}
-
 static bool calculateUpperBound(const Loop &L, ScalarEvolution &SE,
                                 ConditionInfo &Cond, bool IsExitCond) {
   if (IsExitCond) {
@@ -121,33 +92,64 @@ static bool calculateUpperBound(const Loop &L, ScalarEvolution &SE,
   return false;
 }
 
+/// Check whether \p ICmp compares an induction variable of \p L against a
+/// bound this pass can split on, and describe it in \p Cond if so. \p Cond is
+/// left untouched unless the condition is processable.
 static bool hasProcessableCondition(const Loop &L, ScalarEvolution &SE,
                                     ICmpInst *ICmp, ConditionInfo &Cond,
                                     bool IsExitCond) {
-  analyzeICmp(SE, ICmp, Cond, L);
-
-  // The BoundSCEV should be evaluated at loop entry.
-  if (!SE.isAvailableAtLoopEntry(Cond.BoundSCEV, &L))
+  CmpPredicate Pred;
+  Value *AddRecValue, *BoundValue;
+  if (!match(ICmp, m_ICmp(Pred, m_Value(AddRecValue), m_Value(BoundValue))))
     return false;
 
+  const SCEV *AddRecSCEV = SE.getSCEV(AddRecValue);
+  const SCEV *BoundSCEV = SE.getSCEV(BoundValue);
+  // Locate the recurrence in AddRecSCEV and the bound in BoundSCEV.
+  if (!isa<SCEVAddRecExpr>(AddRecSCEV) && isa<SCEVAddRecExpr>(BoundSCEV)) {
+    std::swap(AddRecValue, BoundValue);
+    std::swap(AddRecSCEV, BoundSCEV);
+    Pred = ICmpInst::getSwappedPredicate(Pred);
+  }
+
   // Allowed AddRec as induction variable.
-  if (!Cond.AddRecSCEV)
+  const auto *AddRec = dyn_cast<SCEVAddRecExpr>(AddRecSCEV);
+  if (!AddRec)
     return false;
 
-  if (!Cond.AddRecSCEV->isAffine())
+  // If the induction variable is a PHI node, the value from the backedge is
+  // used instead.
+  Value *NonPHIAddRecValue = AddRecValue;
+  if (auto *PN = dyn_cast<PHINode>(AddRecValue))
+    NonPHIAddRecValue = PN->getIncomingValueForBlock(L.getLoopLatch());
+
+  // The BoundSCEV should be evaluated at loop entry.
+  if (!SE.isAvailableAtLoopEntry(BoundSCEV, &L))
+    return false;
+
+  if (!AddRec->isAffine())
     return false;
 
-  const SCEV *StepRecSCEV = Cond.AddRecSCEV->getStepRecurrence(SE);
   // Allowed constant step.
-  if (!isa<SCEVConstant>(StepRecSCEV))
+  const auto *StepRecSCEV =
+      dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(SE));
+  if (!StepRecSCEV)
     return false;
 
-  ConstantInt *StepCI = cast<SCEVConstant>(StepRecSCEV)->getValue();
   // Allowed positive step for now.
   // TODO: Support negative step.
+  ConstantInt *StepCI = StepRecSCEV->getValue();
   if (StepCI->isNegative() || StepCI->isZero())
     return false;
 
+  Cond.ICmp = ICmp;
+  Cond.Pred = Pred;
+  Cond.AddRecValue = AddRecValue;
+  Cond.NonPHIAddRecValue = NonPHIAddRecValue;
+  Cond.BoundValue = BoundValue;
+  Cond.AddRecSCEV = AddRec;
+  Cond.BoundSCEV = BoundSCEV;
+
   // Calculate upper bound.
   if (!calculateUpperBound(L, SE, Cond, IsExitCond))
     return false;

>From 9d36d7c3eace108cf7f7519585948c40f10b5fb9 Mon Sep 17 00:00:00 2001
From: Timur Baidusenov <timurbaidusenov at gmail.com>
Date: Sun, 6 Sep 2026 22:36:05 +0300
Subject: [PATCH 2/2] [LoopBoundSplit] Bail out when the recurrence is not this
 loop's IV

hasProcessableCondition() treats an ICmp operand as the induction variable
whenever its SCEV is an add-recurrence, and then looks up the value coming
from the backedge:

  PN->getIncomingValueForBlock(L.getLoopLatch())

Two shapes reach that call with a PHI that has no incoming value from the
latch, and both assert with "Invalid basic block argument!":

 - the header PHI of a different loop;
 - a PHI in this loop other than the header PHI. SCEV looks through a PHI
   that merely forwards the induction variable, so a recurrence of this loop
   is reported for it too.

Reject both.

Only guarding the getIncomingValueForBlock() call, as the closed #167227 did,
would silence the assertion but let the pass split the loop on a condition
that is invariant in it. On the reproducer of #156793 that changes the
program: the condition depends only on the outer loop's induction variable,
yet the split folds the branch to true for the first iterations of the inner
loop, so the calls come out in a different order.

Fixes #61655.
Fixes #156793.

Assisted-by: Claude (Anthropic)
---
 llvm/lib/Transforms/Scalar/LoopBoundSplit.cpp | 15 +++-
 .../LoopBoundSplit/addrec-of-outer-loop.ll    | 75 +++++++++++++++++++
 .../LoopBoundSplit/addrec-of-sibling-loop.ll  | 44 +++++++++++
 .../LoopBoundSplit/non-header-phi.ll          | 64 ++++++++++++++++
 4 files changed, 194 insertions(+), 4 deletions(-)
 create mode 100644 llvm/test/Transforms/LoopBoundSplit/addrec-of-outer-loop.ll
 create mode 100644 llvm/test/Transforms/LoopBoundSplit/addrec-of-sibling-loop.ll
 create mode 100644 llvm/test/Transforms/LoopBoundSplit/non-header-phi.ll

diff --git a/llvm/lib/Transforms/Scalar/LoopBoundSplit.cpp b/llvm/lib/Transforms/Scalar/LoopBoundSplit.cpp
index 6f16736315952..ed5dbd5c0280b 100644
--- a/llvm/lib/Transforms/Scalar/LoopBoundSplit.cpp
+++ b/llvm/lib/Transforms/Scalar/LoopBoundSplit.cpp
@@ -112,16 +112,23 @@ static bool hasProcessableCondition(const Loop &L, ScalarEvolution &SE,
     Pred = ICmpInst::getSwappedPredicate(Pred);
   }
 
-  // Allowed AddRec as induction variable.
+  // Allowed AddRec as induction variable, and only one of this loop: a
+  // recurrence of another loop does not evolve with this loop's latch, and the
+  // bound calculated from it would not refer to this loop either.
   const auto *AddRec = dyn_cast<SCEVAddRecExpr>(AddRecSCEV);
-  if (!AddRec)
+  if (!AddRec || AddRec->getLoop() != &L)
     return false;
 
   // If the induction variable is a PHI node, the value from the backedge is
-  // used instead.
+  // used instead. Only the header PHI has one: a recurrence of this loop is
+  // also reported for a PHI that merely forwards it, such as a single-entry
+  // PHI elsewhere in the loop.
   Value *NonPHIAddRecValue = AddRecValue;
-  if (auto *PN = dyn_cast<PHINode>(AddRecValue))
+  if (auto *PN = dyn_cast<PHINode>(AddRecValue)) {
+    if (PN->getParent() != L.getHeader())
+      return false;
     NonPHIAddRecValue = PN->getIncomingValueForBlock(L.getLoopLatch());
+  }
 
   // The BoundSCEV should be evaluated at loop entry.
   if (!SE.isAvailableAtLoopEntry(BoundSCEV, &L))
diff --git a/llvm/test/Transforms/LoopBoundSplit/addrec-of-outer-loop.ll b/llvm/test/Transforms/LoopBoundSplit/addrec-of-outer-loop.ll
new file mode 100644
index 0000000000000..d20392d0e9e25
--- /dev/null
+++ b/llvm/test/Transforms/LoopBoundSplit/addrec-of-outer-loop.ll
@@ -0,0 +1,75 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py UTC_ARGS: --version 6
+; RUN: opt -passes=loop-bound-split -S < %s | FileCheck %s
+
+; Reduced from https://github.com/llvm/llvm-project/issues/156793
+
+; %cmp1 compares %j, the induction variable of the *outer* loop, so it is
+; invariant inside %for.body and does not switch from true to false there.
+; The inner loop must not be split on it: doing so would force the branch to
+; true for the first iterations and call @f1() where the original calls @f2().
+
+declare void @f1()
+declare void @f2()
+
+define void @addrec_of_outer_loop(i32 %k) {
+; CHECK-LABEL: define void @addrec_of_outer_loop(
+; CHECK-SAME: i32 [[K:%.*]]) {
+; CHECK-NEXT:  [[ENTRY:.*]]:
+; CHECK-NEXT:    br label %[[OUTER_HEADER:.*]]
+; CHECK:       [[OUTER_HEADER]]:
+; CHECK-NEXT:    [[J:%.*]] = phi i32 [ 0, %[[ENTRY]] ], [ [[J_INC:%.*]], %[[OUTER_INC:.*]] ]
+; CHECK-NEXT:    br label %[[FOR_BODY:.*]]
+; CHECK:       [[FOR_BODY]]:
+; CHECK-NEXT:    [[I_05:%.*]] = phi i32 [ 0, %[[OUTER_HEADER]] ], [ [[INC:%.*]], %[[FOR_INC:.*]] ]
+; CHECK-NEXT:    [[CMP1:%.*]] = icmp ult i32 [[J]], 2
+; CHECK-NEXT:    br i1 [[CMP1]], label %[[IF_THEN:.*]], label %[[IF_ELSE:.*]]
+; CHECK:       [[IF_THEN]]:
+; CHECK-NEXT:    call void @f1()
+; CHECK-NEXT:    br label %[[FOR_INC]]
+; CHECK:       [[IF_ELSE]]:
+; CHECK-NEXT:    call void @f2()
+; CHECK-NEXT:    br label %[[FOR_INC]]
+; CHECK:       [[FOR_INC]]:
+; CHECK-NEXT:    [[INC]] = add nsw i32 [[I_05]], 1
+; CHECK-NEXT:    [[CMP:%.*]] = icmp slt i32 [[INC]], [[K]]
+; CHECK-NEXT:    br i1 [[CMP]], label %[[FOR_BODY]], label %[[OUTER_INC]]
+; CHECK:       [[OUTER_INC]]:
+; CHECK-NEXT:    [[J_INC]] = add nsw i32 [[J]], 1
+; CHECK-NEXT:    [[OUTER_CMP:%.*]] = icmp slt i32 [[J_INC]], [[K]]
+; CHECK-NEXT:    br i1 [[OUTER_CMP]], label %[[OUTER_HEADER]], label %[[FOR_END:.*]]
+; CHECK:       [[FOR_END]]:
+; CHECK-NEXT:    ret void
+;
+entry:
+  br label %outer.header
+
+outer.header:
+  %j = phi i32 [ 0, %entry ], [ %j.inc, %outer.inc ]
+  br label %for.body
+
+for.body:
+  %i.05 = phi i32 [ 0, %outer.header ], [ %inc, %for.inc ]
+  %cmp1 = icmp ult i32 %j, 2
+  br i1 %cmp1, label %if.then, label %if.else
+
+if.then:
+  call void @f1()
+  br label %for.inc
+
+if.else:
+  call void @f2()
+  br label %for.inc
+
+for.inc:
+  %inc = add nsw i32 %i.05, 1
+  %cmp = icmp slt i32 %inc, %k
+  br i1 %cmp, label %for.body, label %outer.inc
+
+outer.inc:
+  %j.inc = add nsw i32 %j, 1
+  %outer.cmp = icmp slt i32 %j.inc, %k
+  br i1 %outer.cmp, label %outer.header, label %for.end
+
+for.end:
+  ret void
+}
diff --git a/llvm/test/Transforms/LoopBoundSplit/addrec-of-sibling-loop.ll b/llvm/test/Transforms/LoopBoundSplit/addrec-of-sibling-loop.ll
new file mode 100644
index 0000000000000..2ac433fe600d1
--- /dev/null
+++ b/llvm/test/Transforms/LoopBoundSplit/addrec-of-sibling-loop.ll
@@ -0,0 +1,44 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py UTC_ARGS: --version 6
+; RUN: opt -passes=loop-bound-split -S < %s | FileCheck %s
+
+; Reduced from https://github.com/llvm/llvm-project/issues/61655
+
+; The exit condition of %second.inner compares %iv, which is a recurrence of
+; the *other* inner loop %first.inner. LoopBoundSplit used to assume that an
+; add-recurrence operand of the condition belongs to the loop being processed,
+; and crashed while looking up the value coming from that loop's latch.
+
+define i8 @addrec_of_sibling_loop() {
+; CHECK-LABEL: define i8 @addrec_of_sibling_loop() {
+; CHECK-NEXT:  [[ENTRY:.*:]]
+; CHECK-NEXT:    br label %[[OUTER_HEADER:.*]]
+; CHECK:       [[OUTER_HEADER_LOOPEXIT:.*]]:
+; CHECK-NEXT:    br label %[[OUTER_HEADER]]
+; CHECK:       [[OUTER_HEADER]]:
+; CHECK-NEXT:    br label %[[FIRST_INNER:.*]]
+; CHECK:       [[FIRST_INNER]]:
+; CHECK-NEXT:    [[IV:%.*]] = phi i8 [ 0, %[[OUTER_HEADER]] ], [ [[IV_NEXT:%.*]], %[[FIRST_INNER]] ]
+; CHECK-NEXT:    [[IV_NEXT]] = add i8 [[IV]], 1
+; CHECK-NEXT:    br i1 false, label %[[FIRST_INNER]], label %[[SECOND_INNER_PREHEADER:.*]]
+; CHECK:       [[SECOND_INNER_PREHEADER]]:
+; CHECK-NEXT:    [[IV_LCSSA:%.*]] = phi i8 [ [[IV]], %[[FIRST_INNER]] ]
+; CHECK-NEXT:    br label %[[SECOND_INNER:.*]]
+; CHECK:       [[SECOND_INNER]]:
+; CHECK-NEXT:    [[CMP:%.*]] = icmp sle i8 [[IV_LCSSA]], 0
+; CHECK-NEXT:    br i1 [[CMP]], label %[[SECOND_INNER]], label %[[OUTER_HEADER_LOOPEXIT]]
+;
+entry:
+  br label %outer.header
+
+outer.header:
+  br label %first.inner
+
+first.inner:
+  %iv = phi i8 [ 0, %outer.header ], [ %iv.next, %first.inner ]
+  %iv.next = add i8 %iv, 1
+  br i1 false, label %first.inner, label %second.inner
+
+second.inner:
+  %cmp = icmp sle i8 %iv, 0
+  br i1 %cmp, label %second.inner, label %outer.header
+}
diff --git a/llvm/test/Transforms/LoopBoundSplit/non-header-phi.ll b/llvm/test/Transforms/LoopBoundSplit/non-header-phi.ll
new file mode 100644
index 0000000000000..4cddaa5c69c81
--- /dev/null
+++ b/llvm/test/Transforms/LoopBoundSplit/non-header-phi.ll
@@ -0,0 +1,64 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py UTC_ARGS: --version 6
+; RUN: opt -passes=loop-bound-split -S < %s | FileCheck %s
+
+; SCEV reports a recurrence of this loop for %p as well, because a single-entry
+; PHI just forwards the SCEV of its operand. %p is not the header PHI, so it
+; has no value coming from the latch and must not be treated as the induction
+; variable.
+
+declare void @f1()
+declare void @f2()
+
+define void @non_header_phi(i32 %k) {
+; CHECK-LABEL: define void @non_header_phi(
+; CHECK-SAME: i32 [[K:%.*]]) {
+; CHECK-NEXT:  [[ENTRY:.*]]:
+; CHECK-NEXT:    br label %[[HEADER:.*]]
+; CHECK:       [[HEADER]]:
+; CHECK-NEXT:    [[I:%.*]] = phi i32 [ 0, %[[ENTRY]] ], [ [[I_NEXT:%.*]], %[[LATCH:.*]] ]
+; CHECK-NEXT:    br label %[[BODY:.*]]
+; CHECK:       [[BODY]]:
+; CHECK-NEXT:    [[P:%.*]] = phi i32 [ [[I]], %[[HEADER]] ]
+; CHECK-NEXT:    [[C:%.*]] = icmp slt i32 [[P]], 42
+; CHECK-NEXT:    br i1 [[C]], label %[[IF_THEN:.*]], label %[[IF_ELSE:.*]]
+; CHECK:       [[IF_THEN]]:
+; CHECK-NEXT:    call void @f1()
+; CHECK-NEXT:    br label %[[LATCH]]
+; CHECK:       [[IF_ELSE]]:
+; CHECK-NEXT:    call void @f2()
+; CHECK-NEXT:    br label %[[LATCH]]
+; CHECK:       [[LATCH]]:
+; CHECK-NEXT:    [[I_NEXT]] = add nsw i32 [[I]], 1
+; CHECK-NEXT:    [[CMP:%.*]] = icmp slt i32 [[I_NEXT]], [[K]]
+; CHECK-NEXT:    br i1 [[CMP]], label %[[HEADER]], label %[[EXIT:.*]]
+; CHECK:       [[EXIT]]:
+; CHECK-NEXT:    ret void
+;
+entry:
+  br label %header
+
+header:
+  %i = phi i32 [ 0, %entry ], [ %i.next, %latch ]
+  br label %body
+
+body:
+  %p = phi i32 [ %i, %header ]
+  %c = icmp slt i32 %p, 42
+  br i1 %c, label %if.then, label %if.else
+
+if.then:
+  call void @f1()
+  br label %latch
+
+if.else:
+  call void @f2()
+  br label %latch
+
+latch:
+  %i.next = add nsw i32 %i, 1
+  %cmp = icmp slt i32 %i.next, %k
+  br i1 %cmp, label %header, label %exit
+
+exit:
+  ret void
+}



More information about the llvm-commits mailing list