[llvm] [InstCombinePHI] Enable gep arg fold transform with constant indices (PR #174981)

Yingwei Zheng via llvm-commits llvm-commits at lists.llvm.org
Sun Jan 11 04:34:40 PST 2026


================
@@ -570,13 +571,24 @@ Instruction *InstCombinerImpl::foldPHIArgGEPIntoPHI(PHINode &PN) {
       if (FirstInst->getOperand(Op) == GEP->getOperand(Op))
         continue;
 
-      // Don't merge two GEPs when two operands differ (introducing phi nodes)
-      // if one of the PHIs has a constant for the index.  The index may be
-      // substantially cheaper to compute for the constants, so making it a
-      // variable index could pessimize the path.  This also handles the case
-      // for struct indices, which must always be constant.
-      if (isa<Constant>(FirstInst->getOperand(Op)) ||
-          isa<Constant>(GEP->getOperand(Op)))
+      // Don't merge two GEPs if the GEP indices a struct, because struct
+      // indices must be constant.
+
+      if (Op > 0) // skip base pointer for indeces
+        GEPIndices.push_back(GEP->getOperand(Op));
+
+      if (GEP->getIndexedType(GEP->getSourceElementType(), GEPIndices)
+              ->isStructTy())
+        return nullptr;
+
+      // Don't merge if there is a mixture of constant and variable indeces for
+      // the same operand. If all the indeces are constant, the chance is higher
+      // that we can create a lookup table. Otherwise, we could pessimize the
+      // path.
+      if ((isa<Constant>(FirstInst->getOperand(Op)) &&
+           !isa<Constant>(GEP->getOperand(Op))) ||
+          (!isa<Constant>(FirstInst->getOperand(Op)) &&
+           isa<Constant>(GEP->getOperand(Op))))
----------------
dtcxzyw wrote:

```suggestion
      if (isa<Constant>(FirstInst->getOperand(Op)) !=
           !isa<Constant>(GEP->getOperand(Op)))
```

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


More information about the llvm-commits mailing list