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

Yingwei Zheng via llvm-commits llvm-commits at lists.llvm.org
Wed Jul 17 22:16:30 PDT 2024


================
@@ -1003,6 +1003,106 @@ static bool canSimplifyNullLoadOrGEP(LoadInst &LI, Value *Op) {
   return false;
 }
 
+static Value *foldLoadFromIndexedGlobal(LoadInst &LI, IRBuilderBase &Builder,
+                                        TargetLibraryInfo &TLI) {
+  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();
+  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)
+    return nullptr;
+
+  auto &Step = VariableOffsets.front().second;
+  if (Step.isNonPositive())
+    return nullptr;
+  uint64_t ArraySize = DL.getTypeAllocSize(Init->getType()).getFixedValue();
+  // 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 (ArraySize > MaxArraySize * Step.getZExtValue())
----------------
dtcxzyw wrote:

I mean to use `if (DL.getTypeAllocSize(Init->getType()).getFixedValue() > Threshold)` here.


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


More information about the llvm-commits mailing list