[llvm] [SPIRV] Emit intrinsics for globals only in function that references them (PR #178143)

Juan Manuel Martinez CaamaƱo via llvm-commits llvm-commits at lists.llvm.org
Tue Jan 27 08:51:17 PST 2026


================
@@ -62,6 +62,75 @@ namespace llvm::SPIRV {
 } // namespace llvm::SPIRV
 
 namespace {
+// This class keeps track of which functions reference which global variables.
+class GlobalVariableReferences {
+  template <typename T1, typename T2>
+  using OneToManyMapTy = DenseMap<T1, SmallPtrSet<T2, 4>>;
+
+  OneToManyMapTy<GlobalVariable *, Function *> GlobalIsReferencedByFun;
+
+  void collectGlobalReferences(
+      GlobalVariable *GV,
+      OneToManyMapTy<GlobalVariable *, GlobalVariable *> &Global2Global,
+      OneToManyMapTy<GlobalVariable *, Function *> &Global2Function) {
+    SmallVector<Value *> Stack = {GV->user_begin(), GV->user_end()};
+    while (!Stack.empty()) {
+      Value *V = Stack.pop_back_val();
+
+      if (Instruction *I = dyn_cast<Instruction>(V)) {
+        Global2Function[GV].insert(I->getFunction());
+        continue;
+      }
+
+      if (GlobalVariable *UserGV = dyn_cast<GlobalVariable>(V)) {
+        Global2Global[GV].insert(UserGV);
+        continue;
+      }
+
+      if (Constant *C = dyn_cast<Constant>(V))
+        Stack.append(C->user_begin(), C->user_end());
+    }
+  }
+
+public:
+  void init(Module &M) {
+    // Collect which global variables are referenced by which global variables
+    // and which functions reference each global variables.
+    OneToManyMapTy<GlobalVariable *, GlobalVariable *>
+        GlobalIsReferencedByGlobal;
+    GlobalIsReferencedByGlobal.clear();
+    for (GlobalVariable &GV : M.globals()) {
+      GlobalIsReferencedByGlobal.try_emplace(&GV);
----------------
jmmartinez wrote:

Fixed. I was lazy: this was done to avoid reallocations when iterating over `ReferencedBy`.

Now we only create entries if and only if its associated set is not empty. And we use find to guard against creating entries during iteration.

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


More information about the llvm-commits mailing list