Add GetId(Type* type) API to the type manager
authorqining <qining@google.com>
Thu, 11 Aug 2016 19:10:09 +0000 (15:10 -0400)
committerqining <qining@google.com>
Thu, 11 Aug 2016 19:10:09 +0000 (15:10 -0400)
source/opt/type_manager.cpp
source/opt/type_manager.h
test/opt/test_type_manager.cpp

index 80c18f9..22941c6 100644 (file)
@@ -39,6 +39,11 @@ Type* TypeManager::GetType(uint32_t id) const {
   return nullptr;
 }
 
+uint32_t TypeManager::GetId(Type* type) const {
+  if (type_to_id_.count(type) != 0) return type_to_id_.at(type);
+  return 0;
+}
+
 ForwardPointer* TypeManager::GetForwardPointer(uint32_t index) const {
   if (index >= forward_pointers_.size()) return nullptr;
   return forward_pointers_.at(index).get();
@@ -176,6 +181,7 @@ Type* TypeManager::RecordIfTypeDefinition(const spvtools::ir::Instruction& inst)
   } else {
     assert(type != nullptr && "type should not be nullptr at this point");
     id_to_type_[id].reset(type);
+    type_to_id_[type] = id;
   }
   return type;
 }
index be85bda..4d5dbd9 100644 (file)
@@ -42,6 +42,7 @@ namespace analysis {
 class TypeManager {
  public:
   using IdToTypeMap = std::unordered_map<uint32_t, std::unique_ptr<Type>>;
+  using TypeToIdMap = std::unordered_map<Type*, uint32_t>;
   using ForwardPointerVector = std::vector<std::unique_ptr<ForwardPointer>>;
 
   TypeManager(const spvtools::ir::Module& module) { AnalyzeTypes(module); }
@@ -53,6 +54,9 @@ class TypeManager {
   // Returns the type for the given type |id|. Returns nullptr if the given |id|
   // does not define a type.
   Type* GetType(uint32_t id) const;
+  // Returns the id for the given |type|. Returns 0 if can not find the given
+  // |type|.
+  uint32_t GetId(Type* type) const;
   // Returns the number of types hold in this manager.
   size_t NumTypes() const { return id_to_type_.size(); }
 
@@ -73,6 +77,7 @@ class TypeManager {
   void AttachIfTypeDecoration(const spvtools::ir::Instruction& inst);
 
   IdToTypeMap id_to_type_;  // Mapping from ids to their type representations.
+  TypeToIdMap type_to_id_;  // Mapping from types to their defining ids.
   ForwardPointerVector forward_pointers_;  // All forward pointer declarations.
   // All unresolved forward pointer declarations.
   // Refers the contents in the above vector.
index 3c0bd24..fc9966f 100644 (file)
@@ -109,6 +109,7 @@ TEST(TypeManager, TypeStrings) {
 
   for (const auto& p : type_id_strs) {
     EXPECT_EQ(p.second, manager.GetType(p.first)->str());
+    EXPECT_EQ(p.first, manager.GetId(manager.GetType(p.first)));
   }
   EXPECT_EQ("forward_pointer({uint32}*)", manager.GetForwardPointer(0)->str());
   EXPECT_EQ("forward_pointer(10000)", manager.GetForwardPointer(1)->str());