[llvm] [GlobalOpt] Add range metadata to loads from constant global variables (PR #127695)

via llvm-commits llvm-commits at lists.llvm.org
Tue Feb 18 13:21:16 PST 2025


================
@@ -2498,6 +2499,102 @@ OptimizeGlobalAliases(Module &M,
   return Changed;
 }
 
+static bool AddRangeMetadata(Module &M) {
+  const DataLayout &DL = M.getDataLayout();
+  bool Changed = false;
+
+  for (GlobalValue &Global : M.global_values()) {
+
+    auto *GV = dyn_cast<GlobalVariable>(&Global);
+    if (!GV || !GV->hasDefinitiveInitializer())
+      continue;
+
+    // To be able to go to the next GlobalVariable with a return
+    [&] {
+      uint64_t GlobalByteSize = DL.getTypeAllocSize(GV->getValueType());
+      unsigned BW = DL.getIndexTypeSizeInBits(GV->getType());
+
+      SmallVector<LoadInst *> ArrayLikeLoads;
+      Type *ElemTy = nullptr;
+
+      for (User *U : GV->users()) {
+        if (auto *GEP = dyn_cast<GetElementPtrInst>(U)) {
+          Type *GEPElemTy = GEP->getResultElementType();
+          if (!GEP->isInBounds() || !GEPElemTy->isIntegerTy())
+            continue;
+
+          // This restriction that all accesses use the same type could be
+          // lifted
+          if (!ElemTy)
+            ElemTy = GEPElemTy;
+          else if (ElemTy != GEPElemTy)
+            return;
+
+          SmallMapVector<Value *, APInt, 4> Index;
+          APInt CstOffset(BW, 0);
+          GEP->collectOffset(DL, BW, Index, CstOffset);
+
+          // This check is needed for correctness of the code below.
+          // Be we could only traverse the range starting at the constant offset
+          if (!CstOffset.isAligned(DL.getPrefTypeAlign(GEPElemTy)))
----------------
Ralender wrote:

The idea is if a GEP has a constant offset that is not a multiple of its alignment, it will read different values from the one we will read below.
for example if its the alignment is 4 and the constant offset is 1, the loads would read 3 byte from one element and 1 byte from another.

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


More information about the llvm-commits mailing list