[llvm] [InstCombine] Fold icmp with clamp into unsigned bound check (PR #161303)

Nikita Popov via llvm-commits llvm-commits at lists.llvm.org
Wed Oct 1 00:02:25 PDT 2025


================
@@ -5780,6 +5780,44 @@ Instruction *InstCombinerImpl::foldICmpWithMinMax(Instruction &I,
   return nullptr;
 }
 
+/// Match and fold patterns like:
+///   icmp eq/ne X, min(max(X, Lo), Hi)
+/// which represents a range check and can be repsented as a ConstantRange.
+///
+/// For icmp eq, build ConstantRange [Lo, Hi + 1) and convert to:
+///   (X - Lo) u< (Hi + 1 - Lo)
+/// For icmp ne, build ConstantRange [Hi + 1, Lo) and convert to:
+///   (X - (Hi + 1)) u< (Lo - (Hi + 1))
+Instruction *InstCombinerImpl::foldICmpWithClamp(ICmpInst &I, Value *X,
+                                                 MinMaxIntrinsic *Min) {
+  if (!I.isEquality() || !Min->hasOneUse())
----------------
nikic wrote:

Shouldn't we also check that this is actually a min and not a max intrinsic?

I guess the max one will get folded away, but better not rely on it due to worklist order issues.

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


More information about the llvm-commits mailing list