[llvm] [IRCE] Eliminate inverted range checks (PR #230222)

via llvm-commits llvm-commits at lists.llvm.org
Sat Oct 10 10:17:21 PDT 2026


https://github.com/CosmicalBit updated https://github.com/llvm/llvm-project/pull/230222

>From 6adee930dd639a8e0fa67e353d2488df2926b13f Mon Sep 17 00:00:00 2001
From: CosmicalBit <326617346+CosmicalBit at users.noreply.github.com>
Date: Thu, 8 Oct 2026 17:43:18 +0100
Subject: [PATCH] [IRCE] Eliminate inverted range checks

---
 .../Scalar/InductiveRangeCheckElimination.cpp |  44 +++--
 llvm/test/Transforms/IRCE/inverted-checks.ll  | 156 ++++++++++++++++++
 2 files changed, 188 insertions(+), 12 deletions(-)
 create mode 100644 llvm/test/Transforms/IRCE/inverted-checks.ll

diff --git a/llvm/lib/Transforms/Scalar/InductiveRangeCheckElimination.cpp b/llvm/lib/Transforms/Scalar/InductiveRangeCheckElimination.cpp
index 6d4d16825e6fc..7ccdcc23e080e 100644
--- a/llvm/lib/Transforms/Scalar/InductiveRangeCheckElimination.cpp
+++ b/llvm/lib/Transforms/Scalar/InductiveRangeCheckElimination.cpp
@@ -142,15 +142,17 @@ class InductiveRangeCheck {
   const SCEV *Step = nullptr;
   const SCEV *End = nullptr;
   Use *CheckUse = nullptr;
+  bool PassingDirection = true;
 
-  static bool parseRangeCheckICmp(Loop *L, ICmpInst *ICI, ScalarEvolution &SE,
+  static bool parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
+                                  ICmpInst::Predicate Pred, ScalarEvolution &SE,
                                   const SCEVAddRecExpr *&Index,
                                   const SCEV *&End);
 
   static void
   extractRangeChecksFromCond(Loop *L, ScalarEvolution &SE, Use &ConditionUse,
                              SmallVectorImpl<InductiveRangeCheck> &Checks,
-                             SmallPtrSetImpl<Value *> &Visited);
+                             SmallPtrSetImpl<Value *> &Visited, bool Negated);
 
   static bool parseIvAgaisntLimit(Loop *L, Value *LHS, Value *RHS,
                                   ICmpInst::Predicate Pred, ScalarEvolution &SE,
@@ -213,7 +215,7 @@ class InductiveRangeCheck {
 
   /// This is the value the condition of the branch needs to evaluate to for the
   /// branch to take the hot successor (see (1) above).
-  bool getPassingDirection() { return true; }
+  bool getPassingDirection() const { return PassingDirection; }
 
   /// Computes a range for the induction variable (IndVar) in which the range
   /// check is redundant and can be constant-folded away.  The induction
@@ -263,6 +265,7 @@ class InductiveRangeCheckElimination {
 /// SCEV being range checked, and set `End` to the upper or lower limit `Index`
 /// is being range checked.
 bool InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
+                                              ICmpInst::Predicate Pred,
                                               ScalarEvolution &SE,
                                               const SCEVAddRecExpr *&Index,
                                               const SCEV *&End) {
@@ -270,7 +273,6 @@ bool InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
     return SE.isLoopInvariant(SE.getSCEV(V), L);
   };
 
-  ICmpInst::Predicate Pred = ICI->getPredicate();
   Value *LHS = ICI->getOperand(0);
   Value *RHS = ICI->getOperand(1);
 
@@ -477,17 +479,31 @@ bool InductiveRangeCheck::reassociateSubLHS(
 void InductiveRangeCheck::extractRangeChecksFromCond(
     Loop *L, ScalarEvolution &SE, Use &ConditionUse,
     SmallVectorImpl<InductiveRangeCheck> &Checks,
-    SmallPtrSetImpl<Value *> &Visited) {
+    SmallPtrSetImpl<Value *> &Visited, bool Negated) {
   Value *Condition = ConditionUse.get();
   if (!Visited.insert(Condition).second)
     return;
 
-  // TODO: Do the same for OR, XOR, NOT etc?
-  if (match(Condition, m_LogicalAnd(m_Value(), m_Value()))) {
+  Value *Inner = nullptr;
+  if (match(Condition, m_Not(m_Value(Inner)))) {
+    User *Not = cast<User>(Condition);
+    unsigned InnerOp = Not->getOperand(0) == Inner ? 0 : 1;
+    extractRangeChecksFromCond(L, SE, Not->getOperandUse(InnerOp), Checks,
+                               Visited, !Negated);
+    return;
+  }
+
+  // De Morgan's law lets us treat the negation of an OR as a conjunction of
+  // negated checks. Each check may then be replaced independently.
+  if ((Negated && match(Condition, m_LogicalOr(m_Value(), m_Value()))) ||
+      (!Negated && match(Condition, m_LogicalAnd(m_Value(), m_Value())))) {
+    // Logical OR may also be a select of the form A ? true : B.
+    unsigned SecondOp = Negated && isa<SelectInst>(Condition) ? 2 : 1;
     extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(0),
-                               Checks, Visited);
-    extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(1),
-                               Checks, Visited);
+                               Checks, Visited, Negated);
+    extractRangeChecksFromCond(L, SE,
+                               cast<User>(Condition)->getOperandUse(SecondOp),
+                               Checks, Visited, Negated);
     return;
   }
 
@@ -497,7 +513,10 @@ void InductiveRangeCheck::extractRangeChecksFromCond(
 
   const SCEV *End = nullptr;
   const SCEVAddRecExpr *IndexAddRec = nullptr;
-  if (!parseRangeCheckICmp(L, ICI, SE, IndexAddRec, End))
+  ICmpInst::Predicate Pred = ICI->getPredicate();
+  if (Negated)
+    Pred = ICmpInst::getInversePredicate(Pred);
+  if (!parseRangeCheckICmp(L, ICI, Pred, SE, IndexAddRec, End))
     return;
 
   assert(IndexAddRec && "IndexAddRec was not computed");
@@ -511,6 +530,7 @@ void InductiveRangeCheck::extractRangeChecksFromCond(
   IRC.Begin = IndexAddRec->getStart();
   IRC.Step = IndexAddRec->getStepRecurrence(SE);
   IRC.CheckUse = &ConditionUse;
+  IRC.PassingDirection = !Negated;
   Checks.push_back(IRC);
 }
 
@@ -563,7 +583,7 @@ void InductiveRangeCheck::extractRangeChecksFromBranch(
 
   SmallPtrSet<Value *, 8> Visited;
   InductiveRangeCheck::extractRangeChecksFromCond(L, SE, BI->getOperandUse(0),
-                                                  Checks, Visited);
+                                                  Checks, Visited, false);
 }
 
 /// If the type of \p S matches with \p Ty, return \p S. Otherwise, return
diff --git a/llvm/test/Transforms/IRCE/inverted-checks.ll b/llvm/test/Transforms/IRCE/inverted-checks.ll
new file mode 100644
index 0000000000000..4e575930d046e
--- /dev/null
+++ b/llvm/test/Transforms/IRCE/inverted-checks.ll
@@ -0,0 +1,156 @@
+; RUN: opt -passes=irce -verify-loop-info -S %s | FileCheck %s
+; RUN: opt -passes='require<branch-prob>,irce' -verify-loop-info -S %s | FileCheck %s
+
+; The branch enters the loop on the false edge of an OR of failing checks.
+; Both comparisons should be false in the constrained main loop.
+define void @or_of_failing_checks(ptr %arr, i32 %n, i32 %len) {
+; CHECK-LABEL: define void @or_of_failing_checks(
+; CHECK: loop:
+; CHECK: %bad = or i1 false, false
+; CHECK: br i1 %bad.not, label %in.bounds, label %out.of.bounds
+entry:
+  %has.iterations = icmp sgt i32 %n, 0
+  br i1 %has.iterations, label %loop, label %exit
+
+loop:
+  %idx = phi i32 [ 0, %entry ], [ %idx.next, %in.bounds ]
+  %below = icmp slt i32 %idx, 0
+  %above = icmp sge i32 %idx, %len
+  %bad = or i1 %below, %above
+  br i1 %bad, label %out.of.bounds, label %in.bounds, !prof !0
+
+in.bounds:
+  %addr = getelementptr i32, ptr %arr, i32 %idx
+  store i32 0, ptr %addr
+  %idx.next = add nsw i32 %idx, 1
+  %continue = icmp slt i32 %idx.next, %n
+  br i1 %continue, label %loop, label %exit
+
+out.of.bounds:
+  ret void
+
+exit:
+  ret void
+}
+
+; A negated failing comparison is also a passing range check.
+define void @not_of_failing_check(ptr %arr, i32 %n, i32 %len) {
+; CHECK-LABEL: define void @not_of_failing_check(
+; CHECK: loop:
+; CHECK: %safe = xor i1 false, true
+; CHECK: br i1 %safe, label %in.bounds, label %out.of.bounds
+entry:
+  %has.iterations = icmp sgt i32 %n, 0
+  br i1 %has.iterations, label %loop, label %exit
+
+loop:
+  %idx = phi i32 [ 0, %entry ], [ %idx.next, %in.bounds ]
+  %above = icmp uge i32 %idx, %len
+  %safe = xor i1 %above, true
+  br i1 %safe, label %in.bounds, label %out.of.bounds, !prof !1
+
+in.bounds:
+  %addr = getelementptr i32, ptr %arr, i32 %idx
+  store i32 0, ptr %addr
+  %idx.next = add nsw i32 %idx, 1
+  %continue = icmp slt i32 %idx.next, %n
+  br i1 %continue, label %loop, label %exit
+
+out.of.bounds:
+  ret void
+
+exit:
+  ret void
+}
+
+; Logical OR can be represented by a select. Its second condition is operand 2.
+define void @select_of_failing_checks(ptr %arr, i32 %n, i32 %len) {
+; CHECK-LABEL: define void @select_of_failing_checks(
+; CHECK: loop:
+; CHECK: %bad = select i1 false, i1 true, i1 false
+entry:
+  %has.iterations = icmp sgt i32 %n, 0
+  br i1 %has.iterations, label %loop, label %exit
+
+loop:
+  %idx = phi i32 [ 0, %entry ], [ %idx.next, %in.bounds ]
+  %below = icmp slt i32 %idx, 0
+  %above = icmp sge i32 %idx, %len
+  %bad = select i1 %below, i1 true, i1 %above
+  br i1 %bad, label %out.of.bounds, label %in.bounds, !prof !0
+
+in.bounds:
+  %addr = getelementptr i32, ptr %arr, i32 %idx
+  store i32 0, ptr %addr
+  %idx.next = add nsw i32 %idx, 1
+  %continue = icmp slt i32 %idx.next, %n
+  br i1 %continue, label %loop, label %exit
+
+out.of.bounds:
+  ret void
+
+exit:
+  ret void
+}
+
+; The all-ones operand of a NOT can appear first in an XOR.
+define void @commuted_not(ptr %arr, i32 %n, i32 %len) {
+; CHECK-LABEL: define void @commuted_not(
+; CHECK: loop:
+; CHECK: %safe = xor i1 true, false
+entry:
+  %has.iterations = icmp sgt i32 %n, 0
+  br i1 %has.iterations, label %loop, label %exit
+
+loop:
+  %idx = phi i32 [ 0, %entry ], [ %idx.next, %in.bounds ]
+  %above = icmp uge i32 %idx, %len
+  %safe = xor i1 true, %above
+  br i1 %safe, label %in.bounds, label %out.of.bounds, !prof !1
+
+in.bounds:
+  %addr = getelementptr i32, ptr %arr, i32 %idx
+  store i32 0, ptr %addr
+  %idx.next = add nsw i32 %idx, 1
+  %continue = icmp slt i32 %idx.next, %n
+  br i1 %continue, label %loop, label %exit
+
+out.of.bounds:
+  ret void
+
+exit:
+  ret void
+}
+
+; An OR of passing checks does not imply that either check is true.
+define void @or_of_passing_checks(ptr %arr, i32 %n, i32 %len) {
+; CHECK-LABEL: define void @or_of_passing_checks(
+; CHECK: loop:
+; CHECK: %safe = or i1 %below, %above
+entry:
+  %has.iterations = icmp sgt i32 %n, 0
+  br i1 %has.iterations, label %loop, label %exit
+
+loop:
+  %idx = phi i32 [ 0, %entry ], [ %idx.next, %in.bounds ]
+  %below = icmp slt i32 %idx, %len
+  %above = icmp slt i32 %idx, %n
+  %safe = or i1 %below, %above
+  br i1 %safe, label %in.bounds, label %out.of.bounds, !prof !1
+
+in.bounds:
+  %addr = getelementptr i32, ptr %arr, i32 %idx
+  store i32 0, ptr %addr
+  %idx.next = add nsw i32 %idx, 1
+  %continue = icmp slt i32 %idx.next, %n
+  br i1 %continue, label %loop, label %exit
+
+out.of.bounds:
+  ret void
+
+exit:
+  ret void
+}
+
+!0 = !{!"branch_weights", i32 4, i32 64}
+!1 = !{!"branch_weights", i32 64, i32 4}



More information about the llvm-commits mailing list