[llvm] [InstCombine] Fold mul (lshr exact (X, N)), 2^N + 1 -> add (X , lshr exact (X, N)) (PR #95042)

Nikita Popov via llvm-commits llvm-commits at lists.llvm.org
Thu Jun 20 08:35:28 PDT 2024


================
@@ -255,6 +255,38 @@ Instruction *InstCombinerImpl::visitMul(BinaryOperator &I) {
     }
   }
 
+  {
+    // mul (lshr exact X, N), (2^N + 1) -> add (X , lshr (X, N))
+    Value *NewOp;
+    const APInt *ShiftC;
+    const APInt *MulAP;
+    if ((HasNSW || HasNUW) &&
+        match(&I, m_Mul(m_CombineOr(m_LShr(m_Value(NewOp), m_APInt(ShiftC)),
+                                    m_AShr(m_Value(NewOp), m_APInt(ShiftC))),
+                        m_APInt(MulAP)))) {
+      if (BitWidth > 2 && (*MulAP - 1).isPowerOf2() &&
+          MulAP->logBase2() == ShiftC->getZExtValue()) {
+        BinaryOperator *OpBO = cast<BinaryOperator>(Op0);
+        if (OpBO->isExact()) {
+          Value *BinOp = Op0;
+          if (HasNUW && OpBO->getOpcode() == Instruction::AShr &&
+              OpBO->hasOneUse())
+            BinOp = Builder.CreateLShr(
+                NewOp, ConstantInt::get(Ty, ShiftC->getZExtValue()), "",
----------------
nikic wrote:

```suggestion
                NewOp, ConstantInt::get(Ty, ShiftC), "",
```

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


More information about the llvm-commits mailing list