[llvm] [SCEV] Try to re-use pointer LCSSA phis when expanding SCEVs. (PR #147824)

Florian Hahn via llvm-commits llvm-commits at lists.llvm.org
Fri Jul 25 02:29:05 PDT 2025


================
@@ -1224,18 +1224,37 @@ Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
 }
 
 Value *SCEVExpander::tryToReuseLCSSAPhi(const SCEVAddRecExpr *S) {
+  Type *STy = S->getType();
   const Loop *L = S->getLoop();
   BasicBlock *EB = L->getExitBlock();
   if (!EB || !EB->getSinglePredecessor() ||
       !SE.DT.dominates(EB, Builder.GetInsertBlock()))
     return nullptr;
 
   for (auto &PN : EB->phis()) {
-    if (!SE.isSCEVable(PN.getType()) || PN.getType() != S->getType())
+    if (!SE.isSCEVable(PN.getType()))
       continue;
-    auto *ExitV = SE.getSCEV(&PN);
-    if (S == ExitV)
-      return &PN;
+    auto *ExitSCEV = SE.getSCEV(&PN);
+    Type *PhiTy = PN.getType();
+    if (STy->isIntegerTy() && PhiTy->isPointerTy())
+      ExitSCEV = SE.getPtrToIntExpr(ExitSCEV, STy);
+    else if (S->getType() != PN.getType())
+      continue;
+
+    // Check if we can re-use the existing PN, by adjusting it with an expanded
+    // offset, if the offset is simpler (for now just checks if it is
+    // AddRec-free).
+    const SCEV *Diff = SE.getMinusSCEV(S, ExitSCEV);
+    if (isa<SCEVCouldNotCompute>(Diff) ||
+        SCEVExprContains(Diff,
+                         [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); }))
+      continue;
----------------
fhahn wrote:

Agreed that checking just for not containing add-recs might be a bit over-optimistic. Restricting to constant difference on the other hand would mean we miss other profitable cases.

I added a restricted this now to only allow SCEVConstant/SCEVUnknown values, and PtrToInt/negations of those. This should cover all cases I found for now, on a large test set with vectorization enabled .

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


More information about the llvm-commits mailing list