Convert to SymbolTable's new iteration interface.
[oota-llvm.git] / lib / VMCore / Type.cpp
index e5549693ca132044ff4a44ff9a6bbcb12e9b6c3a..b7d71812400dcf403515e0e63c3fbda2c2e6c202 100644 (file)
 #include "Support/DepthFirstIterator.h"
 #include "Support/StringExtras.h"
 #include "Support/STLExtras.h"
-#include "Support/Statistic.h"
 #include <algorithm>
-
 using namespace llvm;
 
-static Statistic<> NumSlowTypes("type", "numslowtypes");
-static Statistic<> NumTypeEquals("type", "numtypeequals");
-
 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
 // created and later destroyed, all in an effort to make sure that there is only
 // a single canonical version of a type.
 //
 //#define DEBUG_MERGE_TYPES 1
 
+AbstractTypeUser::~AbstractTypeUser() {}
 
 //===----------------------------------------------------------------------===//
 //                         Type Class Implementation
@@ -47,7 +43,7 @@ static std::map<const Type*, std::string> ConcreteTypeDescriptions;
 static std::map<const Type*, std::string> AbstractTypeDescriptions;
 
 Type::Type(const std::string &name, PrimitiveID id)
-  : Value(Type::TypeTy, Value::TypeVal), ForwardType(0) {
+  : Value(Type::TypeTy, Value::TypeVal), RefCount(0), ForwardType(0) {
   if (!name.empty())
     ConcreteTypeDescriptions[this] = name;
   ID = id;
@@ -117,6 +113,41 @@ bool Type::isLosslesslyConvertibleTo(const Type *Ty) const {
   }
 }
 
+/// getUnsignedVersion - If this is an integer type, return the unsigned
+/// variant of this type.  For example int -> uint.
+const Type *Type::getUnsignedVersion() const {
+  switch (getPrimitiveID()) {
+  default:
+    assert(isInteger()&&"Type::getUnsignedVersion is only valid for integers!");
+  case Type::UByteTyID:   
+  case Type::SByteTyID:   return Type::UByteTy;
+  case Type::UShortTyID:  
+  case Type::ShortTyID:   return Type::UShortTy;
+  case Type::UIntTyID:    
+  case Type::IntTyID:     return Type::UIntTy;
+  case Type::ULongTyID:   
+  case Type::LongTyID:    return Type::ULongTy;
+  }
+}
+
+/// getSignedVersion - If this is an integer type, return the signed variant
+/// of this type.  For example uint -> int.
+const Type *Type::getSignedVersion() const {
+  switch (getPrimitiveID()) {
+  default:
+    assert(isInteger() && "Type::getSignedVersion is only valid for integers!");
+  case Type::UByteTyID:   
+  case Type::SByteTyID:   return Type::SByteTy;
+  case Type::UShortTyID:  
+  case Type::ShortTyID:   return Type::ShortTy;
+  case Type::UIntTyID:    
+  case Type::IntTyID:     return Type::IntTy;
+  case Type::ULongTyID:   
+  case Type::LongTyID:    return Type::LongTy;
+  }
+}
+
+
 // getPrimitiveSize - Return the basic size of this type if it is a primitive
 // type.  These are fixed by LLVM and are not target dependent.  This will
 // return zero if the type does not have a size or is not a primitive type.
@@ -264,8 +295,9 @@ const std::string &Type::getDescription() const {
 
 bool StructType::indexValid(const Value *V) const {
   // Structure indexes require unsigned integer constants.
-  if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(V))
-    return CU->getValue() < ContainedTys.size();
+  if (V->getType() == Type::UIntTy)
+    if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(V))
+      return CU->getValue() < ContainedTys.size();
   return false;
 }
 
@@ -273,10 +305,8 @@ bool StructType::indexValid(const Value *V) const {
 // element.  For a structure type, this must be a constant value...
 //
 const Type *StructType::getTypeAtIndex(const Value *V) const {
-  assert(isa<Constant>(V) && "Structure index must be a constant!!");
+  assert(indexValid(V) && "Invalid structure index!");
   unsigned Idx = cast<ConstantUInt>(V)->getValue();
-  assert(Idx < ContainedTys.size() && "Structure index out of range!");
-  assert(indexValid(V) && "Invalid structure index!"); // Duplicate check
   return ContainedTys[Idx];
 }
 
@@ -381,7 +411,7 @@ StructType::StructType(const std::vector<const Type*> &Types)
   ContainedTys.reserve(Types.size());
   bool isAbstract = false;
   for (unsigned i = 0; i < Types.size(); ++i) {
-    assert(Types[i] != Type::VoidTy && "Void type in method prototype!!");
+    assert(Types[i] != Type::VoidTy && "Void type for structure field!!");
     ContainedTys.push_back(PATypeHandle(Types[i], this));
     isAbstract |= Types[i]->isAbstract();
   }
@@ -525,17 +555,36 @@ static bool TypesEqual(const Type *Ty, const Type *Ty2) {
   return TypesEqual(Ty, Ty2, EqTypes);
 }
 
+// TypeHasCycleThrough - Return true there is a path from CurTy to TargetTy in
+// the type graph.  We know that Ty is an abstract type, so if we ever reach a
+// non-abstract type, we know that we don't need to search the subgraph.
+static bool TypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
+                                std::set<const Type*> &VisitedTypes) {
+  if (TargetTy == CurTy) return true;
+  if (!CurTy->isAbstract()) return false;
+
+  std::set<const Type*>::iterator VTI = VisitedTypes.lower_bound(CurTy);
+  if (VTI != VisitedTypes.end() && *VTI == CurTy)
+    return false;
+  VisitedTypes.insert(VTI, CurTy);
+
+  for (Type::subtype_iterator I = CurTy->subtype_begin(),
+         E = CurTy->subtype_end(); I != E; ++I)
+    if (TypeHasCycleThrough(TargetTy, *I, VisitedTypes))
+      return true;
+  return false;
+}
+
+
 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
 /// back to itself.
 static bool TypeHasCycleThroughItself(const Type *Ty) {
+  assert(Ty->isAbstract() && "This code assumes that Ty was abstract!");
   std::set<const Type*> VisitedTypes;
-  for (Type::subtype_iterator I = Ty->subtype_begin(),
-         E = Ty->subtype_end(); I != E; ++I)
-    for (df_ext_iterator<const Type *, std::set<const Type*> > 
-           DFI = df_ext_begin(I->get(), VisitedTypes),
-           E = df_ext_end(I->get(), VisitedTypes); DFI != E; ++DFI)
-      if (*DFI == Ty)
-        return true;    // Found a cycle through ty!
+  for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
+       I != E; ++I)
+    if (TypeHasCycleThrough(Ty, *I, VisitedTypes))
+      return true;
   return false;
 }
 
@@ -553,6 +602,9 @@ template<class ValType, class TypeClass>
 class TypeMap {
   std::map<ValType, PATypeHolder> Map;
 
+  /// TypesByHash - Keep track of each type by its structure hash value.
+  ///
+  std::multimap<unsigned, PATypeHolder> TypesByHash;
 public:
   typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
   ~TypeMap() { print("ON EXIT"); }
@@ -562,17 +614,22 @@ public:
     return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
   }
 
-  inline void add(const ValType &V, TypeClass *T) {
-    Map.insert(std::make_pair(V, T));
+  inline void add(const ValType &V, TypeClass *Ty) {
+    Map.insert(std::make_pair(V, Ty));
+
+    // If this type has a cycle, remember it.
+    TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
     print("add");
   }
 
-  iterator getEntryForType(TypeClass *Ty) {
-    iterator I = Map.find(ValType::get(Ty));
-    if (I == Map.end()) print("ERROR!");
-    assert(I != Map.end() && "Didn't find type entry!");
-    assert(I->second.get() == (const Type*)Ty && "Type entry wrong?");
-    return I;
+  void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
+    std::multimap<unsigned, PATypeHolder>::iterator I = 
+      TypesByHash.lower_bound(Hash);
+    while (I->second != Ty) {
+      ++I;
+      assert(I != TypesByHash.end() && I->first == Hash);
+    }
+    TypesByHash.erase(I);
   }
 
   /// finishRefinement - This method is called after we have updated an existing
@@ -592,24 +649,28 @@ public:
     // us when we erase the entry from the map.
     PATypeHolder TyHolder = Ty;
 
-    // Look up our current type map entry..
-    iterator TyIt = getEntryForType(Ty);
-
     // The old record is now out-of-date, because one of the children has been
     // updated.  Remove the obsolete entry from the map.
-    Map.erase(TyIt);
+    Map.erase(ValType::get(Ty));
 
-    // Find the type element we are refining...
+    // Remember the structural hash for the type before we start hacking on it,
+    // in case we need it later.  Also, check to see if the type HAD a cycle
+    // through it, if so, we know it will when we hack on it.
+    unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
+
+    // Find the type element we are refining... and change it now!
     for (unsigned i = 0, e = Ty->ContainedTys.size(); i != e; ++i)
       if (Ty->ContainedTys[i] == OldType) {
         Ty->ContainedTys[i].removeUserFromConcrete();
         Ty->ContainedTys[i] = NewType;
       }
+
+    unsigned TypeHash = ValType::hashTypeStructure(Ty);
     
     // If there are no cycles going through this node, we can do a simple,
     // efficient lookup in the map, instead of an inefficient nasty linear
     // lookup.
-    bool TypeHasCycle = TypeHasCycleThroughItself(Ty);
+    bool TypeHasCycle = Ty->isAbstract() && TypeHasCycleThroughItself(Ty);
     if (!TypeHasCycle) {
       iterator I = Map.find(ValType::get(Ty));
       if (I != Map.end()) {
@@ -619,34 +680,53 @@ public:
         TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
         
         // Refined to a different type altogether?
+        RemoveFromTypesByHash(TypeHash, Ty);
         Ty->refineAbstractTypeTo(NewTy);
         return;
       }
       
     } else {
-      ++NumSlowTypes;
-
-      unsigned TypeHash = ValType::hashTypeStructure(Ty);
-
-
-
       // Now we check to see if there is an existing entry in the table which is
       // structurally identical to the newly refined type.  If so, this type
       // gets refined to the pre-existing type.
       //
-      for (iterator I = Map.begin(), E = Map.end(); I != E; ++I) {
-        ++NumTypeEquals;
-        if (TypesEqual(Ty, I->second)) {
-          assert(Ty->isAbstract() && "Replacing a non-abstract type?");
-          TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
-          
-          // Refined to a different type altogether?
-          Ty->refineAbstractTypeTo(NewTy);
-          return;
+      std::multimap<unsigned, PATypeHolder>::iterator I,E, Entry;
+      tie(I, E) = TypesByHash.equal_range(TypeHash);
+      Entry = E;
+      for (; I != E; ++I) {
+        if (I->second != Ty) {
+          if (TypesEqual(Ty, I->second)) {
+            assert(Ty->isAbstract() && "Replacing a non-abstract type?");
+            TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
+            
+            if (Entry == E) {
+              // Find the location of Ty in the TypesByHash structure.
+              while (I->second != Ty) {
+                ++I;
+                assert(I != E && "Structure doesn't contain type??");
+              }
+              Entry = I;
+            }
+
+            TypesByHash.erase(Entry);
+            Ty->refineAbstractTypeTo(NewTy);
+            return;
+          }
+        } else {
+          // Remember the position of 
+          Entry = I;
         }
       }
     }
 
+    // If we succeeded, we need to insert the type into the cycletypes table.
+    // There are several cases here, depending on whether the original type
+    // had the same hash code and was itself cyclic.
+    if (TypeHash != OldTypeHash) {
+      RemoveFromTypesByHash(OldTypeHash, Ty);
+      TypesByHash.insert(std::make_pair(TypeHash, Ty));
+    }
+
     // If there is no existing type of the same structure, we reinsert an
     // updated record into the map.
     Map.insert(std::make_pair(ValType::get(Ty), Ty));
@@ -662,17 +742,6 @@ public:
     }
   }
   
-  void remove(const ValType &OldVal) {
-    iterator I = Map.find(OldVal);
-    assert(I != Map.end() && "TypeMap::remove, element not found!");
-    Map.erase(I);
-  }
-
-  void remove(iterator I) {
-    assert(I != Map.end() && "Cannot remove invalid iterator pointer!");
-    Map.erase(I);
-  }
-
   void print(const char *Arg) const {
 #ifdef DEBUG_MERGE_TYPES
     std::cerr << "TypeMap<>::" << Arg << " table contents:\n";
@@ -710,7 +779,7 @@ public:
   static FunctionValType get(const FunctionType *FT);
 
   static unsigned hashTypeStructure(const FunctionType *FT) {
-    return 0;
+    return FT->getNumParams()*2+FT->isVarArg();
   }
 
   // Subclass should override this... to update self as usual
@@ -774,7 +843,7 @@ public:
   }
 
   static unsigned hashTypeStructure(const ArrayType *AT) {
-    return 0;
+    return AT->getNumElements();
   }
 
   // Subclass should override this... to update self as usual
@@ -830,7 +899,7 @@ public:
   }
 
   static unsigned hashTypeStructure(const StructType *ST) {
-    return 0;
+    return ST->getNumElements();
   }
 
   // Subclass should override this... to update self as usual
@@ -913,14 +982,6 @@ PointerType *PointerType::get(const Type *ValueType) {
   return PT;
 }
 
-namespace llvm {
-void debug_type_tables() {
-  FunctionTypes.dump();
-  ArrayTypes.dump();
-  StructTypes.dump();
-  PointerTypes.dump();
-}
-}
 
 //===----------------------------------------------------------------------===//
 //                     Derived Type Refinement Functions
@@ -950,7 +1011,7 @@ void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
             << *this << "][" << i << "] User = " << U << "\n";
 #endif
     
-  if (AbstractTypeUsers.empty() && RefCount == 0 && isAbstract()) {
+  if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
 #ifdef DEBUG_MERGE_TYPES
     std::cerr << "DELETEing unused abstract type: <" << *this
               << ">[" << (void*)this << "]" << "\n";