[llvm] [InstCombine] Canonicalize `gep T, (gep i8, base, C1), (Index +nsw C2)` into `gep T, (gep i8, base, C1 + C2 * sizeof(T)), Index` (PR #76177)

Nikita Popov via llvm-commits llvm-commits at lists.llvm.org
Thu Dec 21 12:21:59 PST 2023


================
@@ -2038,6 +2038,54 @@ static Instruction *foldSelectGEP(GetElementPtrInst &GEP,
   return SelectInst::Create(Cond, NewTrueC, NewFalseC, "", nullptr, Sel);
 }
 
+// Canonicalization:
+// gep T, (gep i8, base, C1), (Index +nsw C2) into
+// gep T, (gep i8, base, C1 + C2 * sizeof(T)), Index
+static Instruction *canonicalizeGEPOfConstGEPI8(GetElementPtrInst &GEP,
+                                                GEPOperator *Src,
+                                                InstCombinerImpl &IC) {
+  if (GEP.getNumIndices() != 1)
+    return nullptr;
+  auto &DL = IC.getDataLayout();
+  if (!Src->getSourceElementType()->isIntegerTy(8) ||
+      !Src->hasAllConstantIndices())
+    return nullptr;
+  Value *VarIndex;
+  const APInt *C2;
+  Type *PtrTy = Src->getType()->getScalarType();
+  unsigned IndexSizeInBits = DL.getIndexTypeSizeInBits(PtrTy);
+  if (!(GEP.getOperand(1)->getType()->getScalarSizeInBits() >=
----------------
nikic wrote:

No need to check this, the GEP indices are guaranteed to be canonicalized at this point (for the outer GEP, but for the inner GEP it doesn't matter anyway).

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


More information about the llvm-commits mailing list