[llvm] [SCCP] Simplify general icmp instructions (PR #165976)
Kunqiu Chen via llvm-commits
llvm-commits at lists.llvm.org
Sat Nov 1 00:26:05 PDT 2025
https://github.com/Camsyn created https://github.com/llvm/llvm-project/pull/165976
If we know X ∈ R1, the range check x ∈ R2 can be relaxed into X ∈ R1 ∩ R2 or X ∈ R2 ∪ Inverse(R1).
The relaxed one may be more efficient if we can represent it with one icmp eq, which could motivate more optimization like SimplifyCFG.
This optimization is a more generic version of InstCombine's `foldICmpWithDominatingICmp`, which only works on those CmpBB with ONE DomBB, i.e., cannot handle the following case:
```cpp
if (x == 0) return false;
if (x == 1) return false;
// Could be simplified as x == 2;
return x <u 3);
```
Alive2 Proof : https://alive2.llvm.org/ce/z/HMgkuu
>From b72103e73d0544e018fea890385b7d957759fa26 Mon Sep 17 00:00:00 2001
From: Camsyn <camsyn at foxmail.com>
Date: Fri, 31 Oct 2025 22:34:36 +0800
Subject: [PATCH] [SCCP] Simplify general icmp instructions
---
llvm/lib/Transforms/Utils/SCCPSolver.cpp | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)
diff --git a/llvm/lib/Transforms/Utils/SCCPSolver.cpp b/llvm/lib/Transforms/Utils/SCCPSolver.cpp
index 4947d03a2dc66..21cd21f214d67 100644
--- a/llvm/lib/Transforms/Utils/SCCPSolver.cpp
+++ b/llvm/lib/Transforms/Utils/SCCPSolver.cpp
@@ -299,6 +299,7 @@ static Value *simplifyInstruction(SCCPSolver &Solver,
Value *LHS = ICmp->getOperand(0);
ICmpInst::Predicate Pred = ICmp->getPredicate();
const APInt *Offset;
+ // Match icmp X + Offset, C
if (match(LHS, m_OneUse(m_AddLike(m_Value(X), m_APInt(Offset)))))
return ConstantRange::makeExactICmpRegion(Pred, *RHSC).sub(*Offset);
// Match icmp eq/ne X & NegPow2, C
@@ -310,7 +311,10 @@ static Value *simplifyInstruction(SCCPSolver &Solver,
return Pred == ICmpInst::ICMP_EQ ? CR : CR.inverse();
}
}
- return std::nullopt;
+ // Fallback: Match icmp X, C
+ // E.g., if X ∈ [0, 4], this can simplify icmp uge X, 4 to icmp eq X, 4
+ X = LHS;
+ return ConstantRange::makeExactICmpRegion(Pred, *RHSC);
};
if (auto CR = MatchTwoInstructionExactRangeCheck()) {
More information about the llvm-commits
mailing list