spirv-reader: track module scope variables

Bug: tint:1041 tint:1643
Change-Id: Ifc0aed85eae758e674e90bb73693503888847f76
Reviewed-on: https://dawn-review.googlesource.com/c/dawn/+/104761
Auto-Submit: David Neto <dneto@google.com>
Commit-Queue: David Neto <dneto@google.com>
Reviewed-by: Dan Sinclair <dsinclair@chromium.org>
Kokoro: Kokoro <noreply+kokoro@google.com>
diff --git a/src/tint/reader/spirv/parser_impl.cc b/src/tint/reader/spirv/parser_impl.cc
index 3c64c5b..5aa68eb 100644
--- a/src/tint/reader/spirv/parser_impl.cc
+++ b/src/tint/reader/spirv/parser_impl.cc
@@ -1494,6 +1494,7 @@
         // TODO(dneto): initializers (a.k.a. constructor expression)
         if (ast_var) {
             builder_.AST().AddGlobalVariable(ast_var);
+            module_variable_.GetOrCreate(var.result_id(), [ast_var] { return ast_var; });
         }
     }
 
@@ -1526,6 +1527,8 @@
                     ConvertType(builtin_position_.position_member_type_id), ast_constructor, {});
 
         builder_.AST().AddGlobalVariable(ast_var);
+        module_variable_.GetOrCreate(builtin_position_.per_vertex_var_id,
+                                     [ast_var] { return ast_var; });
     }
     return success_;
 }
diff --git a/src/tint/reader/spirv/parser_impl.h b/src/tint/reader/spirv/parser_impl.h
index 11cbe7c..401a285 100644
--- a/src/tint/reader/spirv/parser_impl.h
+++ b/src/tint/reader/spirv/parser_impl.h
@@ -23,6 +23,7 @@
 #include <vector>
 
 #include "src/tint/utils/compiler_macros.h"
+#include "src/tint/utils/hashmap.h"
 
 #if TINT_BUILD_SPV_READER
 TINT_BEGIN_DISABLE_WARNING(NEWLINE_EOF);
@@ -656,6 +657,15 @@
     /// error
     const Pointer* GetTypeForHandleVar(const spvtools::opt::Instruction& var);
 
+    /// Returns the AST variable for the SPIR-V ID of a module-scope variable,
+    /// or null if there isn't one.
+    /// @param id a SPIR-V ID
+    /// @returns the AST variable or null.
+    const ast::Var* GetModuleVariable(uint32_t id) {
+        auto* entry = module_variable_.Find(id);
+        return entry ? *entry : nullptr;
+    }
+
     /// Returns the channel component type corresponding to the given image
     /// format.
     /// @param format image texel format
@@ -871,6 +881,9 @@
     // The inferred pointer type for the given handle variable.
     std::unordered_map<const spvtools::opt::Instruction*, const Pointer*> handle_type_;
 
+    /// Maps the SPIR-V ID of a module-scope variable to its AST variable.
+    utils::Hashmap<uint32_t, ast::Var*, 16> module_variable_;
+
     // Set of symbols of declared type that have been added, used to avoid
     // adding duplicates.
     std::unordered_set<Symbol> declared_types_;