[llvm] [SCEV] Simplify SCEVExpr for PHI to SCEV for operand if operands are identical (PR #115945)

Nikita Popov via llvm-commits llvm-commits at lists.llvm.org
Tue Nov 26 03:31:09 PST 2024


================
@@ -6019,6 +6019,42 @@ const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
   return nullptr;
 }
 
+/// Returns SCEV for the first operand of a phi if all phi operands have
+/// identical opcodes and operands
+/// eg.
+/// a: %add = %a + %b
+///    br %c
+/// b: %add1 = %a + %b
+///    br %c
+/// c: %phi = phi [%add, a], [%add1, b]
+/// scev(%phi) => scev(%add)
+const SCEV *
+ScalarEvolution::createNodeForPHIWithIdenticalOperands(PHINode *PN) {
+  BinaryOperator *CommonInst = nullptr;
+  // check if instructions are identical
+  for (Value *Incoming : PN->incoming_values()) {
+    auto *IncomingInst = dyn_cast<BinaryOperator>(Incoming);
+    if (!IncomingInst)
+      return nullptr;
+    if (CommonInst) {
+      if (!CommonInst->isIdenticalToWhenDefined(IncomingInst))
+        return nullptr; // Not identical, give up
+    } else {
+      // Remember binary operator
+      CommonInst = IncomingInst;
+    }
+  }
+  if (!CommonInst)
+    return nullptr;
+
+  // check if SCEV exprs for instructions are identical
+  const SCEV *CommonSCEV = getSCEV(CommonInst);
+  bool SCEVExprsIdentical = std::all_of(
+      PN->incoming_values().begin(), PN->incoming_values().end(),
----------------
nikic wrote:

```suggestion
  bool SCEVExprsIdentical = all_of(
      drop_begin(PN->incoming_values()),
```
Can save comparing the first one.

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


More information about the llvm-commits mailing list