Speed up type resolution some more. On the testcase in PR224, for example,
[oota-llvm.git] / lib / VMCore / Type.cpp
1 //===-- Type.cpp - Implement the Type class -------------------------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Type class for the VMCore library.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/DerivedTypes.h"
15 #include "llvm/SymbolTable.h"
16 #include "llvm/Constants.h"
17 #include "Support/DepthFirstIterator.h"
18 #include "Support/StringExtras.h"
19 #include "Support/STLExtras.h"
20 #include "Support/Statistic.h"
21 #include <algorithm>
22
23 using namespace llvm;
24
25 static Statistic<> NumSlowTypes("type", "num slow types");
26 static Statistic<> NumTypeEqualsCalls("type", "num typeequals calls");
27 static Statistic<> NumTypeEquals("type", "num types actually equal");
28
29 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
30 // created and later destroyed, all in an effort to make sure that there is only
31 // a single canonical version of a type.
32 //
33 //#define DEBUG_MERGE_TYPES 1
34
35
36 //===----------------------------------------------------------------------===//
37 //                         Type Class Implementation
38 //===----------------------------------------------------------------------===//
39
40 static unsigned CurUID = 0;
41 static std::vector<const Type *> UIDMappings;
42
43 // Concrete/Abstract TypeDescriptions - We lazily calculate type descriptions
44 // for types as they are needed.  Because resolution of types must invalidate
45 // all of the abstract type descriptions, we keep them in a seperate map to make
46 // this easy.
47 static std::map<const Type*, std::string> ConcreteTypeDescriptions;
48 static std::map<const Type*, std::string> AbstractTypeDescriptions;
49
50 Type::Type(const std::string &name, PrimitiveID id)
51   : Value(Type::TypeTy, Value::TypeVal), ForwardType(0) {
52   if (!name.empty())
53     ConcreteTypeDescriptions[this] = name;
54   ID = id;
55   Abstract = false;
56   UID = CurUID++;       // Assign types UID's as they are created
57   UIDMappings.push_back(this);
58 }
59
60 void Type::setName(const std::string &Name, SymbolTable *ST) {
61   assert(ST && "Type::setName - Must provide symbol table argument!");
62
63   if (Name.size()) ST->insert(Name, this);
64 }
65
66
67 const Type *Type::getUniqueIDType(unsigned UID) {
68   assert(UID < UIDMappings.size() && 
69          "Type::getPrimitiveType: UID out of range!");
70   return UIDMappings[UID];
71 }
72
73 const Type *Type::getPrimitiveType(PrimitiveID IDNumber) {
74   switch (IDNumber) {
75   case VoidTyID  : return VoidTy;
76   case BoolTyID  : return BoolTy;
77   case UByteTyID : return UByteTy;
78   case SByteTyID : return SByteTy;
79   case UShortTyID: return UShortTy;
80   case ShortTyID : return ShortTy;
81   case UIntTyID  : return UIntTy;
82   case IntTyID   : return IntTy;
83   case ULongTyID : return ULongTy;
84   case LongTyID  : return LongTy;
85   case FloatTyID : return FloatTy;
86   case DoubleTyID: return DoubleTy;
87   case TypeTyID  : return TypeTy;
88   case LabelTyID : return LabelTy;
89   default:
90     return 0;
91   }
92 }
93
94 // isLosslesslyConvertibleTo - Return true if this type can be converted to
95 // 'Ty' without any reinterpretation of bits.  For example, uint to int.
96 //
97 bool Type::isLosslesslyConvertibleTo(const Type *Ty) const {
98   if (this == Ty) return true;
99   if ((!isPrimitiveType()    && !isa<PointerType>(this)) ||
100       (!isa<PointerType>(Ty) && !Ty->isPrimitiveType())) return false;
101
102   if (getPrimitiveID() == Ty->getPrimitiveID())
103     return true;  // Handles identity cast, and cast of differing pointer types
104
105   // Now we know that they are two differing primitive or pointer types
106   switch (getPrimitiveID()) {
107   case Type::UByteTyID:   return Ty == Type::SByteTy;
108   case Type::SByteTyID:   return Ty == Type::UByteTy;
109   case Type::UShortTyID:  return Ty == Type::ShortTy;
110   case Type::ShortTyID:   return Ty == Type::UShortTy;
111   case Type::UIntTyID:    return Ty == Type::IntTy;
112   case Type::IntTyID:     return Ty == Type::UIntTy;
113   case Type::ULongTyID:   return Ty == Type::LongTy;
114   case Type::LongTyID:    return Ty == Type::ULongTy;
115   case Type::PointerTyID: return isa<PointerType>(Ty);
116   default:
117     return false;  // Other types have no identity values
118   }
119 }
120
121 // getPrimitiveSize - Return the basic size of this type if it is a primitive
122 // type.  These are fixed by LLVM and are not target dependent.  This will
123 // return zero if the type does not have a size or is not a primitive type.
124 //
125 unsigned Type::getPrimitiveSize() const {
126   switch (getPrimitiveID()) {
127 #define HANDLE_PRIM_TYPE(TY,SIZE)  case TY##TyID: return SIZE;
128 #include "llvm/Type.def"
129   default: return 0;
130   }
131 }
132
133
134 /// getForwardedTypeInternal - This method is used to implement the union-find
135 /// algorithm for when a type is being forwarded to another type.
136 const Type *Type::getForwardedTypeInternal() const {
137   assert(ForwardType && "This type is not being forwarded to another type!");
138   
139   // Check to see if the forwarded type has been forwarded on.  If so, collapse
140   // the forwarding links.
141   const Type *RealForwardedType = ForwardType->getForwardedType();
142   if (!RealForwardedType)
143     return ForwardType;  // No it's not forwarded again
144
145   // Yes, it is forwarded again.  First thing, add the reference to the new
146   // forward type.
147   if (RealForwardedType->isAbstract())
148     cast<DerivedType>(RealForwardedType)->addRef();
149
150   // Now drop the old reference.  This could cause ForwardType to get deleted.
151   cast<DerivedType>(ForwardType)->dropRef();
152   
153   // Return the updated type.
154   ForwardType = RealForwardedType;
155   return ForwardType;
156 }
157
158 // getTypeDescription - This is a recursive function that walks a type hierarchy
159 // calculating the description for a type.
160 //
161 static std::string getTypeDescription(const Type *Ty,
162                                       std::vector<const Type *> &TypeStack) {
163   if (isa<OpaqueType>(Ty)) {                     // Base case for the recursion
164     std::map<const Type*, std::string>::iterator I =
165       AbstractTypeDescriptions.lower_bound(Ty);
166     if (I != AbstractTypeDescriptions.end() && I->first == Ty)
167       return I->second;
168     std::string Desc = "opaque"+utostr(Ty->getUniqueID());
169     AbstractTypeDescriptions.insert(std::make_pair(Ty, Desc));
170     return Desc;
171   }
172   
173   if (!Ty->isAbstract()) {                       // Base case for the recursion
174     std::map<const Type*, std::string>::iterator I =
175       ConcreteTypeDescriptions.find(Ty);
176     if (I != ConcreteTypeDescriptions.end()) return I->second;
177   }
178       
179   // Check to see if the Type is already on the stack...
180   unsigned Slot = 0, CurSize = TypeStack.size();
181   while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
182   
183   // This is another base case for the recursion.  In this case, we know 
184   // that we have looped back to a type that we have previously visited.
185   // Generate the appropriate upreference to handle this.
186   // 
187   if (Slot < CurSize)
188     return "\\" + utostr(CurSize-Slot);         // Here's the upreference
189
190   // Recursive case: derived types...
191   std::string Result;
192   TypeStack.push_back(Ty);    // Add us to the stack..
193       
194   switch (Ty->getPrimitiveID()) {
195   case Type::FunctionTyID: {
196     const FunctionType *FTy = cast<FunctionType>(Ty);
197     Result = getTypeDescription(FTy->getReturnType(), TypeStack) + " (";
198     for (FunctionType::param_iterator I = FTy->param_begin(),
199            E = FTy->param_end(); I != E; ++I) {
200       if (I != FTy->param_begin())
201         Result += ", ";
202       Result += getTypeDescription(*I, TypeStack);
203     }
204     if (FTy->isVarArg()) {
205       if (FTy->getNumParams()) Result += ", ";
206       Result += "...";
207     }
208     Result += ")";
209     break;
210   }
211   case Type::StructTyID: {
212     const StructType *STy = cast<StructType>(Ty);
213     Result = "{ ";
214     for (StructType::element_iterator I = STy->element_begin(),
215            E = STy->element_end(); I != E; ++I) {
216       if (I != STy->element_begin())
217         Result += ", ";
218       Result += getTypeDescription(*I, TypeStack);
219     }
220     Result += " }";
221     break;
222   }
223   case Type::PointerTyID: {
224     const PointerType *PTy = cast<PointerType>(Ty);
225     Result = getTypeDescription(PTy->getElementType(), TypeStack) + " *";
226     break;
227   }
228   case Type::ArrayTyID: {
229     const ArrayType *ATy = cast<ArrayType>(Ty);
230     unsigned NumElements = ATy->getNumElements();
231     Result = "[";
232     Result += utostr(NumElements) + " x ";
233     Result += getTypeDescription(ATy->getElementType(), TypeStack) + "]";
234     break;
235   }
236   default:
237     Result = "<error>";
238     assert(0 && "Unhandled type in getTypeDescription!");
239   }
240
241   TypeStack.pop_back();       // Remove self from stack...
242
243   return Result;
244 }
245
246
247
248 static const std::string &getOrCreateDesc(std::map<const Type*,std::string>&Map,
249                                           const Type *Ty) {
250   std::map<const Type*, std::string>::iterator I = Map.find(Ty);
251   if (I != Map.end()) return I->second;
252     
253   std::vector<const Type *> TypeStack;
254   return Map[Ty] = getTypeDescription(Ty, TypeStack);
255 }
256
257
258 const std::string &Type::getDescription() const {
259   if (isAbstract())
260     return getOrCreateDesc(AbstractTypeDescriptions, this);
261   else
262     return getOrCreateDesc(ConcreteTypeDescriptions, this);
263 }
264
265
266 bool StructType::indexValid(const Value *V) const {
267   // Structure indexes require unsigned integer constants.
268   if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(V))
269     return CU->getValue() < ContainedTys.size();
270   return false;
271 }
272
273 // getTypeAtIndex - Given an index value into the type, return the type of the
274 // element.  For a structure type, this must be a constant value...
275 //
276 const Type *StructType::getTypeAtIndex(const Value *V) const {
277   assert(isa<Constant>(V) && "Structure index must be a constant!!");
278   unsigned Idx = cast<ConstantUInt>(V)->getValue();
279   assert(Idx < ContainedTys.size() && "Structure index out of range!");
280   assert(indexValid(V) && "Invalid structure index!"); // Duplicate check
281   return ContainedTys[Idx];
282 }
283
284
285 //===----------------------------------------------------------------------===//
286 //                           Auxiliary classes
287 //===----------------------------------------------------------------------===//
288 //
289 // These classes are used to implement specialized behavior for each different
290 // type.
291 //
292 struct SignedIntType : public Type {
293   SignedIntType(const std::string &Name, PrimitiveID id) : Type(Name, id) {}
294
295   // isSigned - Return whether a numeric type is signed.
296   virtual bool isSigned() const { return 1; }
297
298   // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
299   // virtual function invocation.
300   //
301   virtual bool isInteger() const { return 1; }
302 };
303
304 struct UnsignedIntType : public Type {
305   UnsignedIntType(const std::string &N, PrimitiveID id) : Type(N, id) {}
306
307   // isUnsigned - Return whether a numeric type is signed.
308   virtual bool isUnsigned() const { return 1; }
309
310   // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
311   // virtual function invocation.
312   //
313   virtual bool isInteger() const { return 1; }
314 };
315
316 struct OtherType : public Type {
317   OtherType(const std::string &N, PrimitiveID id) : Type(N, id) {}
318 };
319
320 static struct TypeType : public Type {
321   TypeType() : Type("type", TypeTyID) {}
322 } TheTypeTy;   // Implement the type that is global.
323
324
325 //===----------------------------------------------------------------------===//
326 //                           Static 'Type' data
327 //===----------------------------------------------------------------------===//
328
329 static OtherType       TheVoidTy  ("void"  , Type::VoidTyID);
330 static OtherType       TheBoolTy  ("bool"  , Type::BoolTyID);
331 static SignedIntType   TheSByteTy ("sbyte" , Type::SByteTyID);
332 static UnsignedIntType TheUByteTy ("ubyte" , Type::UByteTyID);
333 static SignedIntType   TheShortTy ("short" , Type::ShortTyID);
334 static UnsignedIntType TheUShortTy("ushort", Type::UShortTyID);
335 static SignedIntType   TheIntTy   ("int"   , Type::IntTyID); 
336 static UnsignedIntType TheUIntTy  ("uint"  , Type::UIntTyID);
337 static SignedIntType   TheLongTy  ("long"  , Type::LongTyID);
338 static UnsignedIntType TheULongTy ("ulong" , Type::ULongTyID);
339 static OtherType       TheFloatTy ("float" , Type::FloatTyID);
340 static OtherType       TheDoubleTy("double", Type::DoubleTyID);
341 static OtherType       TheLabelTy ("label" , Type::LabelTyID);
342
343 Type *Type::VoidTy   = &TheVoidTy;
344 Type *Type::BoolTy   = &TheBoolTy;
345 Type *Type::SByteTy  = &TheSByteTy;
346 Type *Type::UByteTy  = &TheUByteTy;
347 Type *Type::ShortTy  = &TheShortTy;
348 Type *Type::UShortTy = &TheUShortTy;
349 Type *Type::IntTy    = &TheIntTy;
350 Type *Type::UIntTy   = &TheUIntTy;
351 Type *Type::LongTy   = &TheLongTy;
352 Type *Type::ULongTy  = &TheULongTy;
353 Type *Type::FloatTy  = &TheFloatTy;
354 Type *Type::DoubleTy = &TheDoubleTy;
355 Type *Type::TypeTy   = &TheTypeTy;
356 Type *Type::LabelTy  = &TheLabelTy;
357
358
359 //===----------------------------------------------------------------------===//
360 //                          Derived Type Constructors
361 //===----------------------------------------------------------------------===//
362
363 FunctionType::FunctionType(const Type *Result,
364                            const std::vector<const Type*> &Params, 
365                            bool IsVarArgs) : DerivedType(FunctionTyID), 
366                                              isVarArgs(IsVarArgs) {
367   bool isAbstract = Result->isAbstract();
368   ContainedTys.reserve(Params.size()+1);
369   ContainedTys.push_back(PATypeHandle(Result, this));
370
371   for (unsigned i = 0; i != Params.size(); ++i) {
372     ContainedTys.push_back(PATypeHandle(Params[i], this));
373     isAbstract |= Params[i]->isAbstract();
374   }
375
376   // Calculate whether or not this type is abstract
377   setAbstract(isAbstract);
378 }
379
380 StructType::StructType(const std::vector<const Type*> &Types)
381   : CompositeType(StructTyID) {
382   ContainedTys.reserve(Types.size());
383   bool isAbstract = false;
384   for (unsigned i = 0; i < Types.size(); ++i) {
385     assert(Types[i] != Type::VoidTy && "Void type in method prototype!!");
386     ContainedTys.push_back(PATypeHandle(Types[i], this));
387     isAbstract |= Types[i]->isAbstract();
388   }
389
390   // Calculate whether or not this type is abstract
391   setAbstract(isAbstract);
392 }
393
394 ArrayType::ArrayType(const Type *ElType, unsigned NumEl)
395   : SequentialType(ArrayTyID, ElType) {
396   NumElements = NumEl;
397
398   // Calculate whether or not this type is abstract
399   setAbstract(ElType->isAbstract());
400 }
401
402 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
403   // Calculate whether or not this type is abstract
404   setAbstract(E->isAbstract());
405 }
406
407 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
408   setAbstract(true);
409 #ifdef DEBUG_MERGE_TYPES
410   std::cerr << "Derived new type: " << *this << "\n";
411 #endif
412 }
413
414 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
415 // another (more concrete) type, we must eliminate all references to other
416 // types, to avoid some circular reference problems.
417 void DerivedType::dropAllTypeUses() {
418   if (!ContainedTys.empty()) {
419     while (ContainedTys.size() > 1)
420       ContainedTys.pop_back();
421     
422     // The type must stay abstract.  To do this, we insert a pointer to a type
423     // that will never get resolved, thus will always be abstract.
424     static Type *AlwaysOpaqueTy = OpaqueType::get();
425     static PATypeHolder Holder(AlwaysOpaqueTy);
426     ContainedTys[0] = AlwaysOpaqueTy;
427   }
428 }
429
430 // isTypeAbstract - This is a recursive function that walks a type hierarchy
431 // calculating whether or not a type is abstract.  Worst case it will have to do
432 // a lot of traversing if you have some whacko opaque types, but in most cases,
433 // it will do some simple stuff when it hits non-abstract types that aren't
434 // recursive.
435 //
436 bool Type::isTypeAbstract() {
437   if (!isAbstract())                           // Base case for the recursion
438     return false;                              // Primitive = leaf type
439   
440   if (isa<OpaqueType>(this))                   // Base case for the recursion
441     return true;                               // This whole type is abstract!
442
443   // We have to guard against recursion.  To do this, we temporarily mark this
444   // type as concrete, so that if we get back to here recursively we will think
445   // it's not abstract, and thus not scan it again.
446   setAbstract(false);
447
448   // Scan all of the sub-types.  If any of them are abstract, than so is this
449   // one!
450   for (Type::subtype_iterator I = subtype_begin(), E = subtype_end();
451        I != E; ++I)
452     if (const_cast<Type*>(I->get())->isTypeAbstract()) {
453       setAbstract(true);        // Restore the abstract bit.
454       return true;              // This type is abstract if subtype is abstract!
455     }
456   
457   // Restore the abstract bit.
458   setAbstract(true);
459
460   // Nothing looks abstract here...
461   return false;
462 }
463
464
465 //===----------------------------------------------------------------------===//
466 //                      Type Structural Equality Testing
467 //===----------------------------------------------------------------------===//
468
469 // TypesEqual - Two types are considered structurally equal if they have the
470 // same "shape": Every level and element of the types have identical primitive
471 // ID's, and the graphs have the same edges/nodes in them.  Nodes do not have to
472 // be pointer equals to be equivalent though.  This uses an optimistic algorithm
473 // that assumes that two graphs are the same until proven otherwise.
474 //
475 static bool TypesEqual(const Type *Ty, const Type *Ty2,
476                        std::map<const Type *, const Type *> &EqTypes) {
477   if (Ty == Ty2) return true;
478   if (Ty->getPrimitiveID() != Ty2->getPrimitiveID()) return false;
479   if (isa<OpaqueType>(Ty))
480     return false;  // Two unequal opaque types are never equal
481
482   std::map<const Type*, const Type*>::iterator It = EqTypes.lower_bound(Ty);
483   if (It != EqTypes.end() && It->first == Ty)
484     return It->second == Ty2;    // Looping back on a type, check for equality
485
486   // Otherwise, add the mapping to the table to make sure we don't get
487   // recursion on the types...
488   EqTypes.insert(It, std::make_pair(Ty, Ty2));
489
490   // Two really annoying special cases that breaks an otherwise nice simple
491   // algorithm is the fact that arraytypes have sizes that differentiates types,
492   // and that function types can be varargs or not.  Consider this now.
493   //
494   if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
495     return TypesEqual(PTy->getElementType(),
496                       cast<PointerType>(Ty2)->getElementType(), EqTypes);
497   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
498     const StructType *STy2 = cast<StructType>(Ty2);
499     if (STy->getNumElements() != STy2->getNumElements()) return false;
500     for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
501       if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
502         return false;
503     return true;
504   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
505     const ArrayType *ATy2 = cast<ArrayType>(Ty2);
506     return ATy->getNumElements() == ATy2->getNumElements() &&
507            TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
508   } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
509     const FunctionType *FTy2 = cast<FunctionType>(Ty2);
510     if (FTy->isVarArg() != FTy2->isVarArg() ||
511         FTy->getNumParams() != FTy2->getNumParams() ||
512         !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
513       return false;
514     for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i)
515       if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
516         return false;
517     return true;
518   } else {
519     assert(0 && "Unknown derived type!");
520     return false;
521   }
522 }
523
524 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
525   std::map<const Type *, const Type *> EqTypes;
526   return TypesEqual(Ty, Ty2, EqTypes);
527 }
528
529 // TypeHasCycleThrough - Return true there is a path from CurTy to TargetTy in
530 // the type graph.  We know that Ty is an abstract type, so if we ever reach a
531 // non-abstract type, we know that we don't need to search the subgraph.
532 static bool TypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
533                                 std::set<const Type*> &VisitedTypes) {
534   if (TargetTy == CurTy) return true;
535   if (!CurTy->isAbstract()) return false;
536
537   std::set<const Type*>::iterator VTI = VisitedTypes.lower_bound(CurTy);
538   if (VTI != VisitedTypes.end() && *VTI == CurTy)
539     return false;
540   VisitedTypes.insert(VTI, CurTy);
541
542   for (Type::subtype_iterator I = CurTy->subtype_begin(),
543          E = CurTy->subtype_end(); I != E; ++I)
544     if (TypeHasCycleThrough(TargetTy, *I, VisitedTypes))
545       return true;
546   return false;
547 }
548
549
550 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
551 /// back to itself.
552 static bool TypeHasCycleThroughItself(const Type *Ty) {
553   assert(Ty->isAbstract() && "This code assumes that Ty was abstract!");
554   std::set<const Type*> VisitedTypes;
555   for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
556        I != E; ++I)
557     if (TypeHasCycleThrough(Ty, *I, VisitedTypes))
558       return true;
559   return false;
560 }
561
562
563 //===----------------------------------------------------------------------===//
564 //                       Derived Type Factory Functions
565 //===----------------------------------------------------------------------===//
566
567 // TypeMap - Make sure that only one instance of a particular type may be
568 // created on any given run of the compiler... note that this involves updating
569 // our map if an abstract type gets refined somehow.
570 //
571 namespace llvm {
572 template<class ValType, class TypeClass>
573 class TypeMap {
574   std::map<ValType, PATypeHolder> Map;
575
576   /// TypesByHash - Keep track of each type by its structure hash value.
577   ///
578   std::multimap<unsigned, PATypeHolder> TypesByHash;
579 public:
580   typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
581   ~TypeMap() { print("ON EXIT"); }
582
583   inline TypeClass *get(const ValType &V) {
584     iterator I = Map.find(V);
585     return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
586   }
587
588   inline void add(const ValType &V, TypeClass *Ty) {
589     Map.insert(std::make_pair(V, Ty));
590
591     // If this type has a cycle, remember it.
592     TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
593     print("add");
594   }
595
596   void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
597     std::multimap<unsigned, PATypeHolder>::iterator I = 
598       TypesByHash.lower_bound(Hash);
599     while (I->second != Ty) {
600       ++I;
601       assert(I != TypesByHash.end() && I->first == Hash);
602     }
603     TypesByHash.erase(I);
604   }
605
606   /// finishRefinement - This method is called after we have updated an existing
607   /// type with its new components.  We must now either merge the type away with
608   /// some other type or reinstall it in the map with it's new configuration.
609   /// The specified iterator tells us what the type USED to look like.
610   void finishRefinement(TypeClass *Ty, const DerivedType *OldType,
611                         const Type *NewType) {
612     assert((Ty->isAbstract() || !OldType->isAbstract()) &&
613            "Refining a non-abstract type!");
614 #ifdef DEBUG_MERGE_TYPES
615     std::cerr << "refineAbstractTy(" << (void*)OldType << "[" << *OldType
616               << "], " << (void*)NewType << " [" << *NewType << "])\n";
617 #endif
618
619     // Make a temporary type holder for the type so that it doesn't disappear on
620     // us when we erase the entry from the map.
621     PATypeHolder TyHolder = Ty;
622
623     // The old record is now out-of-date, because one of the children has been
624     // updated.  Remove the obsolete entry from the map.
625     Map.erase(ValType::get(Ty));
626
627     // Remember the structural hash for the type before we start hacking on it,
628     // in case we need it later.  Also, check to see if the type HAD a cycle
629     // through it, if so, we know it will when we hack on it.
630     unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
631
632     // Find the type element we are refining... and change it now!
633     for (unsigned i = 0, e = Ty->ContainedTys.size(); i != e; ++i)
634       if (Ty->ContainedTys[i] == OldType) {
635         Ty->ContainedTys[i].removeUserFromConcrete();
636         Ty->ContainedTys[i] = NewType;
637       }
638
639     unsigned TypeHash = ValType::hashTypeStructure(Ty);
640     
641     // If there are no cycles going through this node, we can do a simple,
642     // efficient lookup in the map, instead of an inefficient nasty linear
643     // lookup.
644     bool TypeHasCycle = Ty->isAbstract() && TypeHasCycleThroughItself(Ty);
645     if (!TypeHasCycle) {
646       iterator I = Map.find(ValType::get(Ty));
647       if (I != Map.end()) {
648         // We already have this type in the table.  Get rid of the newly refined
649         // type.
650         assert(Ty->isAbstract() && "Replacing a non-abstract type?");
651         TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
652         
653         // Refined to a different type altogether?
654         RemoveFromTypesByHash(TypeHash, Ty);
655         Ty->refineAbstractTypeTo(NewTy);
656         return;
657       }
658       
659     } else {
660       ++NumSlowTypes;
661
662       // Now we check to see if there is an existing entry in the table which is
663       // structurally identical to the newly refined type.  If so, this type
664       // gets refined to the pre-existing type.
665       //
666       std::multimap<unsigned, PATypeHolder>::iterator I,E, Entry;
667       tie(I, E) = TypesByHash.equal_range(TypeHash);
668       Entry = E;
669       for (; I != E; ++I) {
670         ++NumTypeEqualsCalls;
671         if (I->second != Ty) {
672           if (TypesEqual(Ty, I->second)) {
673             ++NumTypeEquals;
674             
675             assert(Ty->isAbstract() && "Replacing a non-abstract type?");
676             TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
677             
678             if (Entry == E) {
679               // Find the location of Ty in the TypesByHash structure.
680               while (I->second != Ty) {
681                 ++I;
682                 assert(I != E && "Structure doesn't contain type??");
683               }
684               Entry = I;
685             }
686
687             TypesByHash.erase(Entry);
688             Ty->refineAbstractTypeTo(NewTy);
689             return;
690           }
691         } else {
692           // Remember the position of 
693           Entry = I;
694         }
695       }
696     }
697
698     // If we succeeded, we need to insert the type into the cycletypes table.
699     // There are several cases here, depending on whether the original type
700     // had the same hash code and was itself cyclic.
701     if (TypeHash != OldTypeHash) {
702       RemoveFromTypesByHash(OldTypeHash, Ty);
703       TypesByHash.insert(std::make_pair(TypeHash, Ty));
704     }
705
706     // If there is no existing type of the same structure, we reinsert an
707     // updated record into the map.
708     Map.insert(std::make_pair(ValType::get(Ty), Ty));
709
710     // If the type is currently thought to be abstract, rescan all of our
711     // subtypes to see if the type has just become concrete!
712     if (Ty->isAbstract()) {
713       Ty->setAbstract(Ty->isTypeAbstract());
714
715       // If the type just became concrete, notify all users!
716       if (!Ty->isAbstract())
717         Ty->notifyUsesThatTypeBecameConcrete();
718     }
719   }
720   
721   void print(const char *Arg) const {
722 #ifdef DEBUG_MERGE_TYPES
723     std::cerr << "TypeMap<>::" << Arg << " table contents:\n";
724     unsigned i = 0;
725     for (typename std::map<ValType, PATypeHolder>::const_iterator I
726            = Map.begin(), E = Map.end(); I != E; ++I)
727       std::cerr << " " << (++i) << ". " << (void*)I->second.get() << " " 
728                 << *I->second.get() << "\n";
729 #endif
730   }
731
732   void dump() const { print("dump output"); }
733 };
734 }
735
736
737 //===----------------------------------------------------------------------===//
738 // Function Type Factory and Value Class...
739 //
740
741 // FunctionValType - Define a class to hold the key that goes into the TypeMap
742 //
743 namespace llvm {
744 class FunctionValType {
745   const Type *RetTy;
746   std::vector<const Type*> ArgTypes;
747   bool isVarArg;
748 public:
749   FunctionValType(const Type *ret, const std::vector<const Type*> &args,
750                   bool IVA) : RetTy(ret), isVarArg(IVA) {
751     for (unsigned i = 0; i < args.size(); ++i)
752       ArgTypes.push_back(args[i]);
753   }
754
755   static FunctionValType get(const FunctionType *FT);
756
757   static unsigned hashTypeStructure(const FunctionType *FT) {
758     return FT->getNumParams()*2+FT->isVarArg();
759   }
760
761   // Subclass should override this... to update self as usual
762   void doRefinement(const DerivedType *OldType, const Type *NewType) {
763     if (RetTy == OldType) RetTy = NewType;
764     for (unsigned i = 0, e = ArgTypes.size(); i != e; ++i)
765       if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
766   }
767
768   inline bool operator<(const FunctionValType &MTV) const {
769     if (RetTy < MTV.RetTy) return true;
770     if (RetTy > MTV.RetTy) return false;
771
772     if (ArgTypes < MTV.ArgTypes) return true;
773     return ArgTypes == MTV.ArgTypes && isVarArg < MTV.isVarArg;
774   }
775 };
776 }
777
778 // Define the actual map itself now...
779 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
780
781 FunctionValType FunctionValType::get(const FunctionType *FT) {
782   // Build up a FunctionValType
783   std::vector<const Type *> ParamTypes;
784   ParamTypes.reserve(FT->getNumParams());
785   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
786     ParamTypes.push_back(FT->getParamType(i));
787   return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
788 }
789
790
791 // FunctionType::get - The factory function for the FunctionType class...
792 FunctionType *FunctionType::get(const Type *ReturnType, 
793                                 const std::vector<const Type*> &Params,
794                                 bool isVarArg) {
795   FunctionValType VT(ReturnType, Params, isVarArg);
796   FunctionType *MT = FunctionTypes.get(VT);
797   if (MT) return MT;
798
799   FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
800
801 #ifdef DEBUG_MERGE_TYPES
802   std::cerr << "Derived new type: " << MT << "\n";
803 #endif
804   return MT;
805 }
806
807 //===----------------------------------------------------------------------===//
808 // Array Type Factory...
809 //
810 namespace llvm {
811 class ArrayValType {
812   const Type *ValTy;
813   unsigned Size;
814 public:
815   ArrayValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
816
817   static ArrayValType get(const ArrayType *AT) {
818     return ArrayValType(AT->getElementType(), AT->getNumElements());
819   }
820
821   static unsigned hashTypeStructure(const ArrayType *AT) {
822     return AT->getNumElements();
823   }
824
825   // Subclass should override this... to update self as usual
826   void doRefinement(const DerivedType *OldType, const Type *NewType) {
827     assert(ValTy == OldType);
828     ValTy = NewType;
829   }
830
831   inline bool operator<(const ArrayValType &MTV) const {
832     if (Size < MTV.Size) return true;
833     return Size == MTV.Size && ValTy < MTV.ValTy;
834   }
835 };
836 }
837 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
838
839
840 ArrayType *ArrayType::get(const Type *ElementType, unsigned NumElements) {
841   assert(ElementType && "Can't get array of null types!");
842
843   ArrayValType AVT(ElementType, NumElements);
844   ArrayType *AT = ArrayTypes.get(AVT);
845   if (AT) return AT;           // Found a match, return it!
846
847   // Value not found.  Derive a new type!
848   ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
849
850 #ifdef DEBUG_MERGE_TYPES
851   std::cerr << "Derived new type: " << *AT << "\n";
852 #endif
853   return AT;
854 }
855
856 //===----------------------------------------------------------------------===//
857 // Struct Type Factory...
858 //
859
860 namespace llvm {
861 // StructValType - Define a class to hold the key that goes into the TypeMap
862 //
863 class StructValType {
864   std::vector<const Type*> ElTypes;
865 public:
866   StructValType(const std::vector<const Type*> &args) : ElTypes(args) {}
867
868   static StructValType get(const StructType *ST) {
869     std::vector<const Type *> ElTypes;
870     ElTypes.reserve(ST->getNumElements());
871     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
872       ElTypes.push_back(ST->getElementType(i));
873     
874     return StructValType(ElTypes);
875   }
876
877   static unsigned hashTypeStructure(const StructType *ST) {
878     return ST->getNumElements();
879   }
880
881   // Subclass should override this... to update self as usual
882   void doRefinement(const DerivedType *OldType, const Type *NewType) {
883     for (unsigned i = 0; i < ElTypes.size(); ++i)
884       if (ElTypes[i] == OldType) ElTypes[i] = NewType;
885   }
886
887   inline bool operator<(const StructValType &STV) const {
888     return ElTypes < STV.ElTypes;
889   }
890 };
891 }
892
893 static TypeMap<StructValType, StructType> StructTypes;
894
895 StructType *StructType::get(const std::vector<const Type*> &ETypes) {
896   StructValType STV(ETypes);
897   StructType *ST = StructTypes.get(STV);
898   if (ST) return ST;
899
900   // Value not found.  Derive a new type!
901   StructTypes.add(STV, ST = new StructType(ETypes));
902
903 #ifdef DEBUG_MERGE_TYPES
904   std::cerr << "Derived new type: " << *ST << "\n";
905 #endif
906   return ST;
907 }
908
909
910
911 //===----------------------------------------------------------------------===//
912 // Pointer Type Factory...
913 //
914
915 // PointerValType - Define a class to hold the key that goes into the TypeMap
916 //
917 namespace llvm {
918 class PointerValType {
919   const Type *ValTy;
920 public:
921   PointerValType(const Type *val) : ValTy(val) {}
922
923   static PointerValType get(const PointerType *PT) {
924     return PointerValType(PT->getElementType());
925   }
926
927   static unsigned hashTypeStructure(const PointerType *PT) {
928     return 0;
929   }
930
931   // Subclass should override this... to update self as usual
932   void doRefinement(const DerivedType *OldType, const Type *NewType) {
933     assert(ValTy == OldType);
934     ValTy = NewType;
935   }
936
937   bool operator<(const PointerValType &MTV) const {
938     return ValTy < MTV.ValTy;
939   }
940 };
941 }
942
943 static TypeMap<PointerValType, PointerType> PointerTypes;
944
945 PointerType *PointerType::get(const Type *ValueType) {
946   assert(ValueType && "Can't get a pointer to <null> type!");
947   PointerValType PVT(ValueType);
948
949   PointerType *PT = PointerTypes.get(PVT);
950   if (PT) return PT;
951
952   // Value not found.  Derive a new type!
953   PointerTypes.add(PVT, PT = new PointerType(ValueType));
954
955 #ifdef DEBUG_MERGE_TYPES
956   std::cerr << "Derived new type: " << *PT << "\n";
957 #endif
958   return PT;
959 }
960
961
962 //===----------------------------------------------------------------------===//
963 //                     Derived Type Refinement Functions
964 //===----------------------------------------------------------------------===//
965
966 // removeAbstractTypeUser - Notify an abstract type that a user of the class
967 // no longer has a handle to the type.  This function is called primarily by
968 // the PATypeHandle class.  When there are no users of the abstract type, it
969 // is annihilated, because there is no way to get a reference to it ever again.
970 //
971 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
972   // Search from back to front because we will notify users from back to
973   // front.  Also, it is likely that there will be a stack like behavior to
974   // users that register and unregister users.
975   //
976   unsigned i;
977   for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
978     assert(i != 0 && "AbstractTypeUser not in user list!");
979
980   --i;  // Convert to be in range 0 <= i < size()
981   assert(i < AbstractTypeUsers.size() && "Index out of range!");  // Wraparound?
982
983   AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
984       
985 #ifdef DEBUG_MERGE_TYPES
986   std::cerr << "  remAbstractTypeUser[" << (void*)this << ", "
987             << *this << "][" << i << "] User = " << U << "\n";
988 #endif
989     
990   if (AbstractTypeUsers.empty() && RefCount == 0 && isAbstract()) {
991 #ifdef DEBUG_MERGE_TYPES
992     std::cerr << "DELETEing unused abstract type: <" << *this
993               << ">[" << (void*)this << "]" << "\n";
994 #endif
995     delete this;                  // No users of this abstract type!
996   }
997 }
998
999
1000 // refineAbstractTypeTo - This function is used to when it is discovered that
1001 // the 'this' abstract type is actually equivalent to the NewType specified.
1002 // This causes all users of 'this' to switch to reference the more concrete type
1003 // NewType and for 'this' to be deleted.
1004 //
1005 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1006   assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1007   assert(this != NewType && "Can't refine to myself!");
1008   assert(ForwardType == 0 && "This type has already been refined!");
1009
1010   // The descriptions may be out of date.  Conservatively clear them all!
1011   AbstractTypeDescriptions.clear();
1012
1013 #ifdef DEBUG_MERGE_TYPES
1014   std::cerr << "REFINING abstract type [" << (void*)this << " "
1015             << *this << "] to [" << (void*)NewType << " "
1016             << *NewType << "]!\n";
1017 #endif
1018
1019   // Make sure to put the type to be refined to into a holder so that if IT gets
1020   // refined, that we will not continue using a dead reference...
1021   //
1022   PATypeHolder NewTy(NewType);
1023
1024   // Any PATypeHolders referring to this type will now automatically forward to
1025   // the type we are resolved to.
1026   ForwardType = NewType;
1027   if (NewType->isAbstract())
1028     cast<DerivedType>(NewType)->addRef();
1029
1030   // Add a self use of the current type so that we don't delete ourself until
1031   // after the function exits.
1032   //
1033   PATypeHolder CurrentTy(this);
1034
1035   // To make the situation simpler, we ask the subclass to remove this type from
1036   // the type map, and to replace any type uses with uses of non-abstract types.
1037   // This dramatically limits the amount of recursive type trouble we can find
1038   // ourselves in.
1039   dropAllTypeUses();
1040
1041   // Iterate over all of the uses of this type, invoking callback.  Each user
1042   // should remove itself from our use list automatically.  We have to check to
1043   // make sure that NewTy doesn't _become_ 'this'.  If it does, resolving types
1044   // will not cause users to drop off of the use list.  If we resolve to ourself
1045   // we succeed!
1046   //
1047   while (!AbstractTypeUsers.empty() && NewTy != this) {
1048     AbstractTypeUser *User = AbstractTypeUsers.back();
1049
1050     unsigned OldSize = AbstractTypeUsers.size();
1051 #ifdef DEBUG_MERGE_TYPES
1052     std::cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
1053               << "] of abstract type [" << (void*)this << " "
1054               << *this << "] to [" << (void*)NewTy.get() << " "
1055               << *NewTy << "]!\n";
1056 #endif
1057     User->refineAbstractType(this, NewTy);
1058
1059     assert(AbstractTypeUsers.size() != OldSize &&
1060            "AbsTyUser did not remove self from user list!");
1061   }
1062
1063   // If we were successful removing all users from the type, 'this' will be
1064   // deleted when the last PATypeHolder is destroyed or updated from this type.
1065   // This may occur on exit of this function, as the CurrentTy object is
1066   // destroyed.
1067 }
1068
1069 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1070 // the current type has transitioned from being abstract to being concrete.
1071 //
1072 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1073 #ifdef DEBUG_MERGE_TYPES
1074   std::cerr << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1075 #endif
1076
1077   unsigned OldSize = AbstractTypeUsers.size();
1078   while (!AbstractTypeUsers.empty()) {
1079     AbstractTypeUser *ATU = AbstractTypeUsers.back();
1080     ATU->typeBecameConcrete(this);
1081
1082     assert(AbstractTypeUsers.size() < OldSize-- &&
1083            "AbstractTypeUser did not remove itself from the use list!");
1084   }
1085 }
1086   
1087
1088
1089
1090 // refineAbstractType - Called when a contained type is found to be more
1091 // concrete - this could potentially change us from an abstract type to a
1092 // concrete type.
1093 //
1094 void FunctionType::refineAbstractType(const DerivedType *OldType,
1095                                       const Type *NewType) {
1096   FunctionTypes.finishRefinement(this, OldType, NewType);
1097 }
1098
1099 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1100   refineAbstractType(AbsTy, AbsTy);
1101 }
1102
1103
1104 // refineAbstractType - Called when a contained type is found to be more
1105 // concrete - this could potentially change us from an abstract type to a
1106 // concrete type.
1107 //
1108 void ArrayType::refineAbstractType(const DerivedType *OldType,
1109                                    const Type *NewType) {
1110   ArrayTypes.finishRefinement(this, OldType, NewType);
1111 }
1112
1113 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1114   refineAbstractType(AbsTy, AbsTy);
1115 }
1116
1117
1118 // refineAbstractType - Called when a contained type is found to be more
1119 // concrete - this could potentially change us from an abstract type to a
1120 // concrete type.
1121 //
1122 void StructType::refineAbstractType(const DerivedType *OldType,
1123                                     const Type *NewType) {
1124   StructTypes.finishRefinement(this, OldType, NewType);
1125 }
1126
1127 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1128   refineAbstractType(AbsTy, AbsTy);
1129 }
1130
1131 // refineAbstractType - Called when a contained type is found to be more
1132 // concrete - this could potentially change us from an abstract type to a
1133 // concrete type.
1134 //
1135 void PointerType::refineAbstractType(const DerivedType *OldType,
1136                                      const Type *NewType) {
1137   PointerTypes.finishRefinement(this, OldType, NewType);
1138 }
1139
1140 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1141   refineAbstractType(AbsTy, AbsTy);
1142 }