Implement the hashing scheme in an attempt to speed up the "slow" case in
[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 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
530 /// back to itself.
531 static bool TypeHasCycleThroughItself(const Type *Ty) {
532   std::set<const Type*> VisitedTypes;
533   for (Type::subtype_iterator I = Ty->subtype_begin(),
534          E = Ty->subtype_end(); I != E; ++I)
535     for (df_ext_iterator<const Type *, std::set<const Type*> > 
536            DFI = df_ext_begin(I->get(), VisitedTypes),
537            E = df_ext_end(I->get(), VisitedTypes); DFI != E; ++DFI)
538       if (*DFI == Ty)
539         return true;    // Found a cycle through ty!
540   return false;
541 }
542
543
544 //===----------------------------------------------------------------------===//
545 //                       Derived Type Factory Functions
546 //===----------------------------------------------------------------------===//
547
548 // TypeMap - Make sure that only one instance of a particular type may be
549 // created on any given run of the compiler... note that this involves updating
550 // our map if an abstract type gets refined somehow.
551 //
552 namespace llvm {
553 template<class ValType, class TypeClass>
554 class TypeMap {
555   std::map<ValType, PATypeHolder> Map;
556
557   /// TypesByHash - Keep track of each type by its structure hash value.
558   ///
559   std::multimap<unsigned, PATypeHolder> TypesByHash;
560 public:
561   typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
562   ~TypeMap() { print("ON EXIT"); }
563
564   inline TypeClass *get(const ValType &V) {
565     iterator I = Map.find(V);
566     return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
567   }
568
569   inline void add(const ValType &V, TypeClass *Ty) {
570     Map.insert(std::make_pair(V, Ty));
571
572     // If this type has a cycle, remember it.
573     TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
574     print("add");
575   }
576
577   void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
578     std::multimap<unsigned, PATypeHolder>::iterator I = 
579       TypesByHash.lower_bound(Hash);
580     while (I->second != Ty) {
581       ++I;
582       assert(I != TypesByHash.end() && I->first == Hash);
583     }
584     TypesByHash.erase(I);
585   }
586
587   /// finishRefinement - This method is called after we have updated an existing
588   /// type with its new components.  We must now either merge the type away with
589   /// some other type or reinstall it in the map with it's new configuration.
590   /// The specified iterator tells us what the type USED to look like.
591   void finishRefinement(TypeClass *Ty, const DerivedType *OldType,
592                         const Type *NewType) {
593     assert((Ty->isAbstract() || !OldType->isAbstract()) &&
594            "Refining a non-abstract type!");
595 #ifdef DEBUG_MERGE_TYPES
596     std::cerr << "refineAbstractTy(" << (void*)OldType << "[" << *OldType
597               << "], " << (void*)NewType << " [" << *NewType << "])\n";
598 #endif
599
600     // Make a temporary type holder for the type so that it doesn't disappear on
601     // us when we erase the entry from the map.
602     PATypeHolder TyHolder = Ty;
603
604     // The old record is now out-of-date, because one of the children has been
605     // updated.  Remove the obsolete entry from the map.
606     Map.erase(ValType::get(Ty));
607
608     // Remember the structural hash for the type before we start hacking on it,
609     // in case we need it later.  Also, check to see if the type HAD a cycle
610     // through it, if so, we know it will when we hack on it.
611     unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
612
613     // Find the type element we are refining... and change it now!
614     for (unsigned i = 0, e = Ty->ContainedTys.size(); i != e; ++i)
615       if (Ty->ContainedTys[i] == OldType) {
616         Ty->ContainedTys[i].removeUserFromConcrete();
617         Ty->ContainedTys[i] = NewType;
618       }
619
620     unsigned TypeHash = ValType::hashTypeStructure(Ty);
621     
622     // If there are no cycles going through this node, we can do a simple,
623     // efficient lookup in the map, instead of an inefficient nasty linear
624     // lookup.
625     bool TypeHasCycle = TypeHasCycleThroughItself(Ty);
626     if (!TypeHasCycle) {
627       iterator I = Map.find(ValType::get(Ty));
628       if (I != Map.end()) {
629         // We already have this type in the table.  Get rid of the newly refined
630         // type.
631         assert(Ty->isAbstract() && "Replacing a non-abstract type?");
632         TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
633         
634         // Refined to a different type altogether?
635         RemoveFromTypesByHash(TypeHash, Ty);
636         Ty->refineAbstractTypeTo(NewTy);
637         return;
638       }
639       
640     } else {
641       ++NumSlowTypes;
642
643       // Now we check to see if there is an existing entry in the table which is
644       // structurally identical to the newly refined type.  If so, this type
645       // gets refined to the pre-existing type.
646       //
647       std::multimap<unsigned, PATypeHolder>::iterator I,E, Entry;
648       tie(I, E) = TypesByHash.equal_range(TypeHash);
649       Entry = E;
650       for (; I != E; ++I) {
651         ++NumTypeEqualsCalls;
652         if (I->second != Ty) {
653           if (TypesEqual(Ty, I->second)) {
654             ++NumTypeEquals;
655             
656             assert(Ty->isAbstract() && "Replacing a non-abstract type?");
657             TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
658             
659             if (Entry == E) {
660               // Find the location of Ty in the TypesByHash structure.
661               while (I->second != Ty) {
662                 ++I;
663                 assert(I != E && "Structure doesn't contain type??");
664               }
665               Entry = I;
666             }
667
668             TypesByHash.erase(Entry);
669             Ty->refineAbstractTypeTo(NewTy);
670             return;
671           }
672         } else {
673           // Remember the position of 
674           Entry = I;
675         }
676       }
677     }
678
679     // If we succeeded, we need to insert the type into the cycletypes table.
680     // There are several cases here, depending on whether the original type
681     // had the same hash code and was itself cyclic.
682     if (TypeHash != OldTypeHash) {
683       RemoveFromTypesByHash(OldTypeHash, Ty);
684       TypesByHash.insert(std::make_pair(TypeHash, Ty));
685     }
686
687     // If there is no existing type of the same structure, we reinsert an
688     // updated record into the map.
689     Map.insert(std::make_pair(ValType::get(Ty), Ty));
690
691     // If the type is currently thought to be abstract, rescan all of our
692     // subtypes to see if the type has just become concrete!
693     if (Ty->isAbstract()) {
694       Ty->setAbstract(Ty->isTypeAbstract());
695
696       // If the type just became concrete, notify all users!
697       if (!Ty->isAbstract())
698         Ty->notifyUsesThatTypeBecameConcrete();
699     }
700   }
701   
702   void print(const char *Arg) const {
703 #ifdef DEBUG_MERGE_TYPES
704     std::cerr << "TypeMap<>::" << Arg << " table contents:\n";
705     unsigned i = 0;
706     for (typename std::map<ValType, PATypeHolder>::const_iterator I
707            = Map.begin(), E = Map.end(); I != E; ++I)
708       std::cerr << " " << (++i) << ". " << (void*)I->second.get() << " " 
709                 << *I->second.get() << "\n";
710 #endif
711   }
712
713   void dump() const { print("dump output"); }
714 };
715 }
716
717
718 //===----------------------------------------------------------------------===//
719 // Function Type Factory and Value Class...
720 //
721
722 // FunctionValType - Define a class to hold the key that goes into the TypeMap
723 //
724 namespace llvm {
725 class FunctionValType {
726   const Type *RetTy;
727   std::vector<const Type*> ArgTypes;
728   bool isVarArg;
729 public:
730   FunctionValType(const Type *ret, const std::vector<const Type*> &args,
731                   bool IVA) : RetTy(ret), isVarArg(IVA) {
732     for (unsigned i = 0; i < args.size(); ++i)
733       ArgTypes.push_back(args[i]);
734   }
735
736   static FunctionValType get(const FunctionType *FT);
737
738   static unsigned hashTypeStructure(const FunctionType *FT) {
739     return FT->getNumParams()*2+FT->isVarArg();
740   }
741
742   // Subclass should override this... to update self as usual
743   void doRefinement(const DerivedType *OldType, const Type *NewType) {
744     if (RetTy == OldType) RetTy = NewType;
745     for (unsigned i = 0, e = ArgTypes.size(); i != e; ++i)
746       if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
747   }
748
749   inline bool operator<(const FunctionValType &MTV) const {
750     if (RetTy < MTV.RetTy) return true;
751     if (RetTy > MTV.RetTy) return false;
752
753     if (ArgTypes < MTV.ArgTypes) return true;
754     return ArgTypes == MTV.ArgTypes && isVarArg < MTV.isVarArg;
755   }
756 };
757 }
758
759 // Define the actual map itself now...
760 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
761
762 FunctionValType FunctionValType::get(const FunctionType *FT) {
763   // Build up a FunctionValType
764   std::vector<const Type *> ParamTypes;
765   ParamTypes.reserve(FT->getNumParams());
766   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
767     ParamTypes.push_back(FT->getParamType(i));
768   return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
769 }
770
771
772 // FunctionType::get - The factory function for the FunctionType class...
773 FunctionType *FunctionType::get(const Type *ReturnType, 
774                                 const std::vector<const Type*> &Params,
775                                 bool isVarArg) {
776   FunctionValType VT(ReturnType, Params, isVarArg);
777   FunctionType *MT = FunctionTypes.get(VT);
778   if (MT) return MT;
779
780   FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
781
782 #ifdef DEBUG_MERGE_TYPES
783   std::cerr << "Derived new type: " << MT << "\n";
784 #endif
785   return MT;
786 }
787
788 //===----------------------------------------------------------------------===//
789 // Array Type Factory...
790 //
791 namespace llvm {
792 class ArrayValType {
793   const Type *ValTy;
794   unsigned Size;
795 public:
796   ArrayValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
797
798   static ArrayValType get(const ArrayType *AT) {
799     return ArrayValType(AT->getElementType(), AT->getNumElements());
800   }
801
802   static unsigned hashTypeStructure(const ArrayType *AT) {
803     return AT->getNumElements();
804   }
805
806   // Subclass should override this... to update self as usual
807   void doRefinement(const DerivedType *OldType, const Type *NewType) {
808     assert(ValTy == OldType);
809     ValTy = NewType;
810   }
811
812   inline bool operator<(const ArrayValType &MTV) const {
813     if (Size < MTV.Size) return true;
814     return Size == MTV.Size && ValTy < MTV.ValTy;
815   }
816 };
817 }
818 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
819
820
821 ArrayType *ArrayType::get(const Type *ElementType, unsigned NumElements) {
822   assert(ElementType && "Can't get array of null types!");
823
824   ArrayValType AVT(ElementType, NumElements);
825   ArrayType *AT = ArrayTypes.get(AVT);
826   if (AT) return AT;           // Found a match, return it!
827
828   // Value not found.  Derive a new type!
829   ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
830
831 #ifdef DEBUG_MERGE_TYPES
832   std::cerr << "Derived new type: " << *AT << "\n";
833 #endif
834   return AT;
835 }
836
837 //===----------------------------------------------------------------------===//
838 // Struct Type Factory...
839 //
840
841 namespace llvm {
842 // StructValType - Define a class to hold the key that goes into the TypeMap
843 //
844 class StructValType {
845   std::vector<const Type*> ElTypes;
846 public:
847   StructValType(const std::vector<const Type*> &args) : ElTypes(args) {}
848
849   static StructValType get(const StructType *ST) {
850     std::vector<const Type *> ElTypes;
851     ElTypes.reserve(ST->getNumElements());
852     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
853       ElTypes.push_back(ST->getElementType(i));
854     
855     return StructValType(ElTypes);
856   }
857
858   static unsigned hashTypeStructure(const StructType *ST) {
859     return ST->getNumElements();
860   }
861
862   // Subclass should override this... to update self as usual
863   void doRefinement(const DerivedType *OldType, const Type *NewType) {
864     for (unsigned i = 0; i < ElTypes.size(); ++i)
865       if (ElTypes[i] == OldType) ElTypes[i] = NewType;
866   }
867
868   inline bool operator<(const StructValType &STV) const {
869     return ElTypes < STV.ElTypes;
870   }
871 };
872 }
873
874 static TypeMap<StructValType, StructType> StructTypes;
875
876 StructType *StructType::get(const std::vector<const Type*> &ETypes) {
877   StructValType STV(ETypes);
878   StructType *ST = StructTypes.get(STV);
879   if (ST) return ST;
880
881   // Value not found.  Derive a new type!
882   StructTypes.add(STV, ST = new StructType(ETypes));
883
884 #ifdef DEBUG_MERGE_TYPES
885   std::cerr << "Derived new type: " << *ST << "\n";
886 #endif
887   return ST;
888 }
889
890
891
892 //===----------------------------------------------------------------------===//
893 // Pointer Type Factory...
894 //
895
896 // PointerValType - Define a class to hold the key that goes into the TypeMap
897 //
898 namespace llvm {
899 class PointerValType {
900   const Type *ValTy;
901 public:
902   PointerValType(const Type *val) : ValTy(val) {}
903
904   static PointerValType get(const PointerType *PT) {
905     return PointerValType(PT->getElementType());
906   }
907
908   static unsigned hashTypeStructure(const PointerType *PT) {
909     return 0;
910   }
911
912   // Subclass should override this... to update self as usual
913   void doRefinement(const DerivedType *OldType, const Type *NewType) {
914     assert(ValTy == OldType);
915     ValTy = NewType;
916   }
917
918   bool operator<(const PointerValType &MTV) const {
919     return ValTy < MTV.ValTy;
920   }
921 };
922 }
923
924 static TypeMap<PointerValType, PointerType> PointerTypes;
925
926 PointerType *PointerType::get(const Type *ValueType) {
927   assert(ValueType && "Can't get a pointer to <null> type!");
928   PointerValType PVT(ValueType);
929
930   PointerType *PT = PointerTypes.get(PVT);
931   if (PT) return PT;
932
933   // Value not found.  Derive a new type!
934   PointerTypes.add(PVT, PT = new PointerType(ValueType));
935
936 #ifdef DEBUG_MERGE_TYPES
937   std::cerr << "Derived new type: " << *PT << "\n";
938 #endif
939   return PT;
940 }
941
942
943 //===----------------------------------------------------------------------===//
944 //                     Derived Type Refinement Functions
945 //===----------------------------------------------------------------------===//
946
947 // removeAbstractTypeUser - Notify an abstract type that a user of the class
948 // no longer has a handle to the type.  This function is called primarily by
949 // the PATypeHandle class.  When there are no users of the abstract type, it
950 // is annihilated, because there is no way to get a reference to it ever again.
951 //
952 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
953   // Search from back to front because we will notify users from back to
954   // front.  Also, it is likely that there will be a stack like behavior to
955   // users that register and unregister users.
956   //
957   unsigned i;
958   for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
959     assert(i != 0 && "AbstractTypeUser not in user list!");
960
961   --i;  // Convert to be in range 0 <= i < size()
962   assert(i < AbstractTypeUsers.size() && "Index out of range!");  // Wraparound?
963
964   AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
965       
966 #ifdef DEBUG_MERGE_TYPES
967   std::cerr << "  remAbstractTypeUser[" << (void*)this << ", "
968             << *this << "][" << i << "] User = " << U << "\n";
969 #endif
970     
971   if (AbstractTypeUsers.empty() && RefCount == 0 && isAbstract()) {
972 #ifdef DEBUG_MERGE_TYPES
973     std::cerr << "DELETEing unused abstract type: <" << *this
974               << ">[" << (void*)this << "]" << "\n";
975 #endif
976     delete this;                  // No users of this abstract type!
977   }
978 }
979
980
981 // refineAbstractTypeTo - This function is used to when it is discovered that
982 // the 'this' abstract type is actually equivalent to the NewType specified.
983 // This causes all users of 'this' to switch to reference the more concrete type
984 // NewType and for 'this' to be deleted.
985 //
986 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
987   assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
988   assert(this != NewType && "Can't refine to myself!");
989   assert(ForwardType == 0 && "This type has already been refined!");
990
991   // The descriptions may be out of date.  Conservatively clear them all!
992   AbstractTypeDescriptions.clear();
993
994 #ifdef DEBUG_MERGE_TYPES
995   std::cerr << "REFINING abstract type [" << (void*)this << " "
996             << *this << "] to [" << (void*)NewType << " "
997             << *NewType << "]!\n";
998 #endif
999
1000   // Make sure to put the type to be refined to into a holder so that if IT gets
1001   // refined, that we will not continue using a dead reference...
1002   //
1003   PATypeHolder NewTy(NewType);
1004
1005   // Any PATypeHolders referring to this type will now automatically forward to
1006   // the type we are resolved to.
1007   ForwardType = NewType;
1008   if (NewType->isAbstract())
1009     cast<DerivedType>(NewType)->addRef();
1010
1011   // Add a self use of the current type so that we don't delete ourself until
1012   // after the function exits.
1013   //
1014   PATypeHolder CurrentTy(this);
1015
1016   // To make the situation simpler, we ask the subclass to remove this type from
1017   // the type map, and to replace any type uses with uses of non-abstract types.
1018   // This dramatically limits the amount of recursive type trouble we can find
1019   // ourselves in.
1020   dropAllTypeUses();
1021
1022   // Iterate over all of the uses of this type, invoking callback.  Each user
1023   // should remove itself from our use list automatically.  We have to check to
1024   // make sure that NewTy doesn't _become_ 'this'.  If it does, resolving types
1025   // will not cause users to drop off of the use list.  If we resolve to ourself
1026   // we succeed!
1027   //
1028   while (!AbstractTypeUsers.empty() && NewTy != this) {
1029     AbstractTypeUser *User = AbstractTypeUsers.back();
1030
1031     unsigned OldSize = AbstractTypeUsers.size();
1032 #ifdef DEBUG_MERGE_TYPES
1033     std::cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
1034               << "] of abstract type [" << (void*)this << " "
1035               << *this << "] to [" << (void*)NewTy.get() << " "
1036               << *NewTy << "]!\n";
1037 #endif
1038     User->refineAbstractType(this, NewTy);
1039
1040     assert(AbstractTypeUsers.size() != OldSize &&
1041            "AbsTyUser did not remove self from user list!");
1042   }
1043
1044   // If we were successful removing all users from the type, 'this' will be
1045   // deleted when the last PATypeHolder is destroyed or updated from this type.
1046   // This may occur on exit of this function, as the CurrentTy object is
1047   // destroyed.
1048 }
1049
1050 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1051 // the current type has transitioned from being abstract to being concrete.
1052 //
1053 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1054 #ifdef DEBUG_MERGE_TYPES
1055   std::cerr << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1056 #endif
1057
1058   unsigned OldSize = AbstractTypeUsers.size();
1059   while (!AbstractTypeUsers.empty()) {
1060     AbstractTypeUser *ATU = AbstractTypeUsers.back();
1061     ATU->typeBecameConcrete(this);
1062
1063     assert(AbstractTypeUsers.size() < OldSize-- &&
1064            "AbstractTypeUser did not remove itself from the use list!");
1065   }
1066 }
1067   
1068
1069
1070
1071 // refineAbstractType - Called when a contained type is found to be more
1072 // concrete - this could potentially change us from an abstract type to a
1073 // concrete type.
1074 //
1075 void FunctionType::refineAbstractType(const DerivedType *OldType,
1076                                       const Type *NewType) {
1077   FunctionTypes.finishRefinement(this, OldType, NewType);
1078 }
1079
1080 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1081   refineAbstractType(AbsTy, AbsTy);
1082 }
1083
1084
1085 // refineAbstractType - Called when a contained type is found to be more
1086 // concrete - this could potentially change us from an abstract type to a
1087 // concrete type.
1088 //
1089 void ArrayType::refineAbstractType(const DerivedType *OldType,
1090                                    const Type *NewType) {
1091   ArrayTypes.finishRefinement(this, OldType, NewType);
1092 }
1093
1094 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1095   refineAbstractType(AbsTy, AbsTy);
1096 }
1097
1098
1099 // refineAbstractType - Called when a contained type is found to be more
1100 // concrete - this could potentially change us from an abstract type to a
1101 // concrete type.
1102 //
1103 void StructType::refineAbstractType(const DerivedType *OldType,
1104                                     const Type *NewType) {
1105   StructTypes.finishRefinement(this, OldType, NewType);
1106 }
1107
1108 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1109   refineAbstractType(AbsTy, AbsTy);
1110 }
1111
1112 // refineAbstractType - Called when a contained type is found to be more
1113 // concrete - this could potentially change us from an abstract type to a
1114 // concrete type.
1115 //
1116 void PointerType::refineAbstractType(const DerivedType *OldType,
1117                                      const Type *NewType) {
1118   PointerTypes.finishRefinement(this, OldType, NewType);
1119 }
1120
1121 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1122   refineAbstractType(AbsTy, AbsTy);
1123 }