[llvm] [InstCombine] Convert load from LUT into a select (PR #98339)

Yingwei Zheng via llvm-commits llvm-commits at lists.llvm.org
Wed Jul 10 23:04:12 PDT 2024


================
@@ -998,6 +998,105 @@ static bool canSimplifyNullLoadOrGEP(LoadInst &LI, Value *Op) {
   return false;
 }
 
+static Value *foldLoadFromIndexedGlobal(LoadInst &LI, IRBuilderBase &Builder) {
+  if (LI.isVolatile())
+    return nullptr;
+
+  auto *GEP = dyn_cast<GetElementPtrInst>(LI.getPointerOperand());
+  if (!GEP)
+    return nullptr;
+
+  auto *GV = dyn_cast<GlobalVariable>(GEP->getPointerOperand());
+  if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
+    return nullptr;
+
+  Constant *Init = GV->getInitializer();
+  if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
+    return nullptr;
+
+  Type *EltTy = Init->getType()->getArrayElementType();
+  if (EltTy != LI.getType())
+    return nullptr;
+
+  uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
+  // Don't blow up on huge arrays.
+  // This threshold is chosen based on statistics on a dataset
+  // which is collected from real-world applications.
+  constexpr uint64_t MaxArraySize = 16;
+  if (ArrayElementCount > MaxArraySize)
+    return nullptr;
+
+  auto &DL = LI.getDataLayout();
+  uint64_t IndexBW = DL.getIndexTypeSizeInBits(GEP->getType());
+  APInt ConstOffset(IndexBW, 0);
+  MapVector<Value *, APInt> VariableOffsets;
+  if (!GEP->collectOffset(DL, IndexBW, VariableOffsets, ConstOffset))
+    return nullptr;
+
+  if (!ConstOffset.isZero() || VariableOffsets.size() != 1 ||
----------------
dtcxzyw wrote:

> Doesn't seem that much of a stretch to test if `ConstOffset % DL.getTypeAllocSize(EltTy).getFixedValue() == 0` to just start from `ConstOffset / DL.getTypeAllocSize(EltTy).getFixedValue()` (you can also use this to essentially shrink `ArrayElementCount`)

I haven't seen a non-zero constant offset in this pattern :) I will post a follow-up patch if it pays off.

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


More information about the llvm-commits mailing list