[llvm] Simplify `(a % b) lt/ge (b-1)` into `(a % b) eq/ne (b-1)` (PR #72504)

via llvm-commits llvm-commits at lists.llvm.org
Thu Jan 4 04:14:05 PST 2024


================
@@ -6855,6 +6855,47 @@ Instruction *InstCombinerImpl::visitICmpInst(ICmpInst &I) {
   if (Value *V = simplifyICmpInst(I.getPredicate(), Op0, Op1, Q))
     return replaceInstUsesWith(I, V);
 
+  {
+    Value *X;
+    const APInt *C1, *C2;
+    ICmpInst::Predicate Pred;
+    if ((match(&I, m_ICmp(Pred, m_SRem(m_Value(X), m_NonNegative(C1)),
+                          m_APInt(C2))) &&
+         *C2 == *C1 - 1 &&
+         (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE)) ||
+        (match(&I,
+               m_ICmp(Pred, m_SRem(m_Value(X), m_Negative(C1)), m_APInt(C2))) &&
+         *C2 == *C1 + 1 &&
+         (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE))) {
+      // icmp slt (X s% C), (C - 1) --> icmp ne (X s% C), (C - 1), if C >= 0
+      // icmp sge (X s% C), (C - 1) --> icmp eq (X s% C), (C - 1), if C >= 0
+      // icmp sgt (X s% C), (C + 1) --> icmp ne (X s% C), (C + 1), if C < 0
+      // icmp sle (X s% C), (C + 1) --> icmp eq (X s% C), (C + 1), if C < 0
+      auto *NewCmp = Builder.CreateICmp(
+          (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT)
+              ? ICmpInst::ICMP_NE
+              : ICmpInst::ICMP_EQ,
+          Op0, Op1);
+      return replaceInstUsesWith(I, NewCmp);
+    }
+
+    if (match(&I, m_ICmp(Pred, m_URem(m_Value(X), m_NonNegative(C1)),
+                         m_APInt(C2))) &&
+        (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE ||
+         Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT)) {
+      // icmp slt (X u% C), (C - 1) --> icmp ne (X u% C), (C - 1), if C >= 0
+      // icmp ult (X u% C), (C - 1) --> icmp eq (X u% C), (C - 1), if C >= 0
+      // icmp sge (X u% C), (C - 1) --> icmp eq (X u% C), (C - 1), if C >= 0
+      // icmp uge (X u% C), (C - 1) --> icmp ne (X u% C), (C - 1), if C >= 0
+      auto *NewCmp = Builder.CreateICmp(
+          (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT)
+              ? ICmpInst::ICMP_NE
+              : ICmpInst::ICMP_EQ,
+          Op0, Op1);
+      return replaceInstUsesWith(I, NewCmp);
----------------
elhewaty wrote:

@dtcxzyw 

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


More information about the llvm-commits mailing list