[llvm] [InstCombine] Match intrinsic recurrences when known to be hoisted (PR #149858)

Antonio Frighetto via llvm-commits llvm-commits at lists.llvm.org
Mon Jul 28 00:46:34 PDT 2025


================
@@ -1532,6 +1532,41 @@ static Instruction *foldBitOrderCrossLogicOp(Value *V,
   return nullptr;
 }
 
+static Value *foldBinaryIntrinsicRecurrence(InstCombinerImpl &IC,
+                                            IntrinsicInst *II) {
+  PHINode *PN;
+  Value *Init, *OtherOp;
+
+  // A binary intrinsic recurrence with loop-invariant operands is equivalent to
+  // `call @llvm.binary.intrinsic(Init, OtherOp)`.
+  if (!matchSimpleBinaryIntrinsicRecurrence(II, PN, Init, OtherOp) ||
+      !IC.getDominatorTree().dominates(OtherOp, PN))
+    return nullptr;
+
+  auto IID = II->getIntrinsicID();
+  switch (IID) {
+  case Intrinsic::maxnum:
+  case Intrinsic::minnum:
+  case Intrinsic::maximum:
+  case Intrinsic::minimum:
+  case Intrinsic::maximumnum:
+  case Intrinsic::minimumnum:
+  case Intrinsic::smax:
+  case Intrinsic::smin:
+  case Intrinsic::umax:
+  case Intrinsic::umin:
+    break;
+  default:
+    return nullptr;
+  }
+
+  auto *InvariantBinaryInst =
+      IC.Builder.CreateBinaryIntrinsic(IID, Init, OtherOp);
+  if (isa<FPMathOperator>(InvariantBinaryInst))
+    cast<Instruction>(InvariantBinaryInst)->copyFastMathFlags(II);
----------------
antoniofrighetto wrote:

In this case, I think you'd need another `dyn_cast<Instruction>(InvariantBinaryInst)` to check that `CreateBinaryIntrinsic` didn't constant-fold, as copyFastMathFlags is private to FPMathOperator. Think the current one may be cleaner. 

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


More information about the llvm-commits mailing list