[llvm] [SROA] Unfold gep of index phi (PR #83087)

Artem Belevich via llvm-commits llvm-commits at lists.llvm.org
Mon Feb 26 17:54:14 PST 2024


================
@@ -4023,64 +4023,88 @@ class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
     Visited.insert(NSelI);
     enqueueUsers(*NSelI);
 
-    LLVM_DEBUG(dbgs() << "\n          to: " << *NTrue
-                      << "\n              " << *NFalse
-                      << "\n              " << *NSel << '\n');
+    LLVM_DEBUG(dbgs() << "\n          to: " << *NTrue << "\n              "
+                      << *NFalse << "\n              " << *NSel << '\n');
 
     return true;
   }
 
-  // Fold gep (phi ptr1, ptr2) => phi gep(ptr1), gep(ptr2)
+  // Fold gep (phi ptr1, ptr2), idx
+  //   => phi ((gep ptr1, idx), (gep ptr2, idx))
+  // and  gep ptr, (phi idx1, idx2)
+  //   => phi ((gep ptr, idx1), (gep ptr, idx2))
   bool foldGEPPhi(GetElementPtrInst &GEPI) {
-    if (!GEPI.hasAllConstantIndices())
+    // Check whether the GEP has exactly one phi operand and all indices
+    // will become constant after the transform.
+    PHINode *Phi = dyn_cast<PHINode>(GEPI.getPointerOperand());
+    // To prevent infinitely expanding recursive phis, bail if the GEP pointer
+    // operand is the phi and any of its incoming values is not an alloca or a
+    // constant.
+    if (Phi && any_of(Phi->operands(), [](Value *V) {
+          return isa<Instruction>(V) && !isa<AllocaInst>(V);
----------------
Artem-B wrote:

> any of its incoming values is not an alloca or a constant.

- restricting it to `alloca` only is too conservative. E.g. we may have a chain of `GEP`s of an `alloca`. I'm not sure if we're guaranteed that instcombine will always be able to collapse it for us into alloca+offset. There may also be various shenanigans with int/pointer conversions.
- Does  negation of `isa<Instruction>(V)` guarantee that what we've got is a constant? E.g. what if we get a function argument as an incoming value? Can we ever get an operator?


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


More information about the llvm-commits mailing list