[llvm] [InstCombine] Fold icmp with clamp into unsigned bound check (PR #161303)
Yingwei Zheng via llvm-commits
llvm-commits at lists.llvm.org
Tue Sep 30 09:16:07 PDT 2025
================
@@ -5780,6 +5780,47 @@ Instruction *InstCombinerImpl::foldICmpWithMinMax(Instruction &I,
return nullptr;
}
+// Transform patterns like:
+// icmp eq/ne X, min(max(X, Lo), Hi)
+// Into:
+// (X - Lo) u< (Hi - Lo + 1)
+Instruction *InstCombinerImpl::foldICmpWithClamp(ICmpInst &I, Value *X,
+ MinMaxIntrinsic *Min) {
+ if (!I.isEquality() || !Min->hasOneUse())
+ return nullptr;
+
+ const APInt *Lo = nullptr, *Hi = nullptr;
+ if (Min->isSigned()) {
+ if (!match(Min->getLHS(), m_OneUse(m_SMax(m_Specific(X), m_APInt(Lo)))) ||
+ !match(Min->getRHS(), m_APInt(Hi)) || !Lo->slt(*Hi))
+ return nullptr;
+ } else {
+ if (!match(Min->getLHS(), m_OneUse(m_UMax(m_Specific(X), m_APInt(Lo)))) ||
+ !match(Min->getRHS(), m_APInt(Hi)) || !Lo->ult(*Hi))
+ return nullptr;
+ }
+
+ // If Hi is the maximum value, the min operation becomes redundant and
+ // will be removed by other optimizations.
+ if ((Min->isSigned() && (Lo->isMinSignedValue() || Hi->isMaxSignedValue())) ||
+ (!Min->isSigned() && (Lo->isMinValue() || Hi->isMaxValue())))
+ return nullptr;
----------------
dtcxzyw wrote:
Does it affect the correctness or cause regressions? IIRC these checks are unnecessary.
https://github.com/llvm/llvm-project/pull/161303
More information about the llvm-commits
mailing list