Add notes
[oota-llvm.git] / lib / VMCore / Type.cpp
1 //===-- Type.cpp - Implement the Type class ----------------------*- C++ -*--=//
2 //
3 // This file implements the Type class for the VMCore library.
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "llvm/DerivedTypes.h"
8 #include "llvm/Support/StringExtras.h"
9 #include "llvm/SymbolTable.h"
10 #include "llvm/Support/STLExtras.h"
11
12 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
13 // created and later destroyed, all in an effort to make sure that there is only
14 // a single cannonical version of a type.
15 //
16 //#define DEBUG_MERGE_TYPES 1
17
18
19
20 //===----------------------------------------------------------------------===//
21 //                         Type Class Implementation
22 //===----------------------------------------------------------------------===//
23
24 static unsigned CurUID = 0;
25 static vector<const Type *> UIDMappings;
26
27 Type::Type(const string &name, PrimitiveID id)
28   : Value(Type::TypeTy, Value::TypeVal) {
29   setDescription(name);
30   ID = id;
31   Abstract = Recursive = false;
32   UID = CurUID++;       // Assign types UID's as they are created
33   UIDMappings.push_back(this);
34 }
35
36 void Type::setName(const string &Name, SymbolTable *ST) {
37   assert(ST && "Type::setName - Must provide symbol table argument!");
38
39   if (Name.size()) ST->insert(Name, this);
40 }
41
42
43 const Type *Type::getUniqueIDType(unsigned UID) {
44   assert(UID < UIDMappings.size() && 
45          "Type::getPrimitiveType: UID out of range!");
46   return UIDMappings[UID];
47 }
48
49 const Type *Type::getPrimitiveType(PrimitiveID IDNumber) {
50   switch (IDNumber) {
51   case VoidTyID  : return VoidTy;
52   case BoolTyID  : return BoolTy;
53   case UByteTyID : return UByteTy;
54   case SByteTyID : return SByteTy;
55   case UShortTyID: return UShortTy;
56   case ShortTyID : return ShortTy;
57   case UIntTyID  : return UIntTy;
58   case IntTyID   : return IntTy;
59   case ULongTyID : return ULongTy;
60   case LongTyID  : return LongTy;
61   case FloatTyID : return FloatTy;
62   case DoubleTyID: return DoubleTy;
63   case TypeTyID  : return TypeTy;
64   case LabelTyID : return LabelTy;
65   default:
66     return 0;
67   }
68 }
69
70 //===----------------------------------------------------------------------===//
71 //                           Auxilliary classes
72 //===----------------------------------------------------------------------===//
73 //
74 // These classes are used to implement specialized behavior for each different
75 // type.
76 //
77 class SignedIntType : public Type {
78   int Size;
79 public:
80   SignedIntType(const string &Name, PrimitiveID id, int size) : Type(Name, id) {
81     Size = size;
82   }
83
84   // isSigned - Return whether a numeric type is signed.
85   virtual bool isSigned() const { return 1; }
86
87   // isIntegral - Equivalent to isSigned() || isUnsigned, but with only a single
88   // virtual function invocation.
89   //
90   virtual bool isIntegral() const { return 1; }
91 };
92
93 class UnsignedIntType : public Type {
94   uint64_t Size;
95 public:
96   UnsignedIntType(const string &N, PrimitiveID id, int size) : Type(N, id) {
97     Size = size;
98   }
99
100   // isUnsigned - Return whether a numeric type is signed.
101   virtual bool isUnsigned() const { return 1; }
102
103   // isIntegral - Equivalent to isSigned() || isUnsigned, but with only a single
104   // virtual function invocation.
105   //
106   virtual bool isIntegral() const { return 1; }
107 };
108
109 static struct TypeType : public Type {
110   TypeType() : Type("type", TypeTyID) {}
111 } TheTypeType;   // Implement the type that is global.
112
113
114 //===----------------------------------------------------------------------===//
115 //                           Static 'Type' data
116 //===----------------------------------------------------------------------===//
117
118 Type *Type::VoidTy   = new            Type("void"  , VoidTyID),
119      *Type::BoolTy   = new            Type("bool"  , BoolTyID),
120      *Type::SByteTy  = new   SignedIntType("sbyte" , SByteTyID, 1),
121      *Type::UByteTy  = new UnsignedIntType("ubyte" , UByteTyID, 1),
122      *Type::ShortTy  = new   SignedIntType("short" ,  ShortTyID, 2),
123      *Type::UShortTy = new UnsignedIntType("ushort", UShortTyID, 2),
124      *Type::IntTy    = new   SignedIntType("int"   ,  IntTyID, 4), 
125      *Type::UIntTy   = new UnsignedIntType("uint"  , UIntTyID, 4),
126      *Type::LongTy   = new   SignedIntType("long"  ,  LongTyID, 8),
127      *Type::ULongTy  = new UnsignedIntType("ulong" , ULongTyID, 8),
128      *Type::FloatTy  = new            Type("float" , FloatTyID),
129      *Type::DoubleTy = new            Type("double", DoubleTyID),
130      *Type::TypeTy   =        &TheTypeType,
131      *Type::LabelTy  = new            Type("label" , LabelTyID);
132
133
134 //===----------------------------------------------------------------------===//
135 //                          Derived Type Constructors
136 //===----------------------------------------------------------------------===//
137
138 MethodType::MethodType(const Type *Result, const vector<const Type*> &Params, 
139                        bool IsVarArgs) : DerivedType("", MethodTyID), 
140     ResultType(PATypeHandle<Type>(Result, this)),
141     isVarArgs(IsVarArgs) {
142   ParamTys.reserve(Params.size());
143   for (unsigned i = 0; i < Params.size(); ++i)
144     ParamTys.push_back(PATypeHandle<Type>(Params[i], this));
145
146   setDerivedTypeProperties();
147 }
148
149 ArrayType::ArrayType(const Type *ElType, int NumEl)
150   : DerivedType("", ArrayTyID), ElementType(PATypeHandle<Type>(ElType, this)) {
151   NumElements = NumEl;
152   setDerivedTypeProperties();
153 }
154
155 StructType::StructType(const vector<const Type*> &Types)
156   : DerivedType("", StructTyID) {
157   ETypes.reserve(Types.size());
158   for (unsigned i = 0; i < Types.size(); ++i) {
159     assert(Types[i] != Type::VoidTy && "Void type in method prototype!!");
160     ETypes.push_back(PATypeHandle<Type>(Types[i], this));
161   }
162   setDerivedTypeProperties();
163 }
164
165 PointerType::PointerType(const Type *E) : DerivedType("", PointerTyID),
166                           ValueType(PATypeHandle<Type>(E, this)) {
167   setDerivedTypeProperties();
168 }
169
170 OpaqueType::OpaqueType() : DerivedType("", OpaqueTyID) {
171   setAbstract(true);
172   setDescription("opaque"+utostr(getUniqueID()));
173 #ifdef DEBUG_MERGE_TYPES
174   cerr << "Derived new type: " << getDescription() << endl;
175 #endif
176 }
177
178
179
180
181 //===----------------------------------------------------------------------===//
182 //               Derived Type setDerivedTypeProperties Function
183 //===----------------------------------------------------------------------===//
184
185 // getTypeProps - This is a recursive function that walks a type hierarchy
186 // calculating the description for a type and whether or not it is abstract or
187 // recursive.  Worst case it will have to do a lot of traversing if you have
188 // some whacko opaque types, but in most cases, it will do some simple stuff
189 // when it hits non-abstract types that aren't recursive.
190 //
191 static string getTypeProps(const Type *Ty, vector<const Type *> &TypeStack,
192                            bool &isAbstract, bool &isRecursive) {
193   string Result;
194   if (!Ty->isAbstract() && !Ty->isRecursive() && // Base case for the recursion
195       Ty->getDescription().size()) {
196     Result = Ty->getDescription();               // Primitive = leaf type
197   } else if (isa<OpaqueType>(Ty)) {              // Base case for the recursion
198     Result = Ty->getDescription();               // Opaque = leaf type
199     isAbstract = true;                           // This whole type is abstract!
200   } else {
201     // Check to see if the Type is already on the stack...
202     unsigned Slot = 0, CurSize = TypeStack.size();
203     while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
204     
205     // This is another base case for the recursion.  In this case, we know 
206     // that we have looped back to a type that we have previously visited.
207     // Generate the appropriate upreference to handle this.
208     // 
209     if (Slot < CurSize) {
210       Result = "\\" + utostr(CurSize-Slot);       // Here's the upreference
211       isRecursive = true;                         // We know we are recursive
212     } else {                      // Recursive case: abstract derived type...
213       TypeStack.push_back(Ty);    // Add us to the stack..
214       
215       switch (Ty->getPrimitiveID()) {
216       case Type::MethodTyID: {
217         const MethodType *MTy = cast<const MethodType>(Ty);
218         Result = getTypeProps(MTy->getReturnType(), TypeStack,
219                               isAbstract, isRecursive)+" (";
220         for (MethodType::ParamTypes::const_iterator
221                I = MTy->getParamTypes().begin(),
222                E = MTy->getParamTypes().end(); I != E; ++I) {
223           if (I != MTy->getParamTypes().begin())
224             Result += ", ";
225           Result += getTypeProps(*I, TypeStack, isAbstract, isRecursive);
226         }
227         if (MTy->isVarArg()) {
228           if (!MTy->getParamTypes().empty()) Result += ", ";
229           Result += "...";
230         }
231         Result += ")";
232         break;
233       }
234       case Type::StructTyID: {
235         const StructType *STy = cast<const StructType>(Ty);
236         Result = "{ ";
237         for (StructType::ElementTypes::const_iterator
238                I = STy->getElementTypes().begin(),
239                E = STy->getElementTypes().end(); I != E; ++I) {
240           if (I != STy->getElementTypes().begin())
241             Result += ", ";
242           Result += getTypeProps(*I, TypeStack, isAbstract, isRecursive);
243         }
244         Result += " }";
245         break;
246       }
247       case Type::PointerTyID: {
248         const PointerType *PTy = cast<const PointerType>(Ty);
249         Result = getTypeProps(PTy->getValueType(), TypeStack,
250                               isAbstract, isRecursive) + " *";
251         break;
252       }
253       case Type::ArrayTyID: {
254         const ArrayType *ATy = cast<const ArrayType>(Ty);
255         int NumElements = ATy->getNumElements();
256         Result = "[";
257         if (NumElements != -1) Result += itostr(NumElements) + " x ";
258         Result += getTypeProps(ATy->getElementType(), TypeStack,
259                                isAbstract, isRecursive) + "]";
260         break;
261       }
262       default:
263         assert(0 && "Unhandled case in getTypeProps!");
264         Result = "<error>";
265       }
266
267       TypeStack.pop_back();       // Remove self from stack...
268     }
269   }
270   return Result;
271 }
272
273
274 // setDerivedTypeProperties - This function is used to calculate the
275 // isAbstract, isRecursive, and the Description settings for a type.  The
276 // getTypeProps function does all the dirty work.
277 //
278 void DerivedType::setDerivedTypeProperties() {
279   vector<const Type *> TypeStack;
280   bool isAbstract = false, isRecursive = false;
281   
282   setDescription(getTypeProps(this, TypeStack, isAbstract, isRecursive));
283   setAbstract(isAbstract);
284   setRecursive(isRecursive);
285 }
286
287
288 //===----------------------------------------------------------------------===//
289 //                      Type Structural Equality Testing
290 //===----------------------------------------------------------------------===//
291
292 // TypesEqual - Two types are considered structurally equal if they have the
293 // same "shape": Every level and element of the types have identical primitive
294 // ID's, and the graphs have the same edges/nodes in them.  Nodes do not have to
295 // be pointer equals to be equivalent though.  This uses an optimistic algorithm
296 // that assumes that two graphs are the same until proven otherwise.
297 //
298 static bool TypesEqual(const Type *Ty, const Type *Ty2,
299                        map<const Type *, const Type *> &EqTypes) {
300   if (Ty == Ty2) return true;
301   if (Ty->getPrimitiveID() != Ty2->getPrimitiveID()) return false;
302   if (Ty->isPrimitiveType()) return true;
303   if (isa<OpaqueType>(Ty))
304     return false;  // Two nonequal opaque types are never equal
305
306   map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
307   if (It != EqTypes.end())
308     return It->second == Ty2;    // Looping back on a type, check for equality
309
310   // Otherwise, add the mapping to the table to make sure we don't get
311   // recursion on the types...
312   EqTypes.insert(make_pair(Ty, Ty2));
313
314   // Iterate over the types and make sure the the contents are equivalent...
315   Type::subtype_iterator I  = Ty ->subtype_begin(), IE  = Ty ->subtype_end();
316   Type::subtype_iterator I2 = Ty2->subtype_begin(), IE2 = Ty2->subtype_end();
317   for (; I != IE && I2 != IE2; ++I, ++I2)
318     if (!TypesEqual(*I, *I2, EqTypes)) return false;
319
320   // Two really annoying special cases that breaks an otherwise nice simple
321   // algorithm is the fact that arraytypes have sizes that differentiates types,
322   // and that method types can be varargs or not.  Consider this now.
323   if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
324     if (ATy->getNumElements() != cast<const ArrayType>(Ty2)->getNumElements())
325       return false;
326   } else if (const MethodType *MTy = dyn_cast<MethodType>(Ty)) {
327     if (MTy->isVarArg() != cast<const MethodType>(Ty2)->isVarArg())
328       return false;
329   }
330
331   return I == IE && I2 == IE2;    // Types equal if both iterators are done
332 }
333
334 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
335   map<const Type *, const Type *> EqTypes;
336   return TypesEqual(Ty, Ty2, EqTypes);
337 }
338
339
340
341 //===----------------------------------------------------------------------===//
342 //                       Derived Type Factory Functions
343 //===----------------------------------------------------------------------===//
344
345 // TypeMap - Make sure that only one instance of a particular type may be
346 // created on any given run of the compiler... note that this involves updating
347 // our map if an abstract type gets refined somehow...
348 //
349 template<class ValType, class TypeClass>
350 class TypeMap : public AbstractTypeUser {
351   typedef map<ValType, PATypeHandle<TypeClass> > MapTy;
352   MapTy Map;
353 public:
354
355   ~TypeMap() { print("ON EXIT"); }
356
357   inline TypeClass *get(const ValType &V) {
358     map<ValType, PATypeHandle<TypeClass> >::iterator I = Map.find(V);
359     // TODO: FIXME: When Types are not CONST.
360     return (I != Map.end()) ? (TypeClass*)I->second.get() : 0;
361   }
362
363   inline void add(const ValType &V, TypeClass *T) {
364     Map.insert(make_pair(V, PATypeHandle<TypeClass>(T, this)));
365     print("add");
366   }
367
368   // containsEquivalent - Return true if the typemap contains a type that is
369   // structurally equivalent to the specified type.
370   //
371   inline const TypeClass *containsEquivalent(const TypeClass *Ty) {
372     for (MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
373       if (I->second.get() != Ty && TypesEqual(Ty, I->second.get()))
374         return (TypeClass*)I->second.get();  // FIXME TODO when types not const
375     return 0;
376   }
377
378   // refineAbstractType - This is called when one of the contained abstract
379   // types gets refined... this simply removes the abstract type from our table.
380   // We expect that whoever refined the type will add it back to the table,
381   // corrected.
382   //
383   virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
384     if (OldTy == NewTy) {
385       if (!OldTy->isAbstract()) {
386         // Check to see if the type just became concrete.
387         // If so, remove self from user list.
388         for (MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
389           if (I->second == OldTy)
390             I->second.removeUserFromConcrete();
391       }
392       return;
393     }
394 #ifdef DEBUG_MERGE_TYPES
395     cerr << "Removing Old type from Tab: " << (void*)OldTy << ", "
396          << OldTy->getDescription() << "  replacement == " << (void*)NewTy
397          << ", " << NewTy->getDescription() << endl;
398 #endif
399     for (MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
400       if (I->second == OldTy) {
401         Map.erase(I);
402         print("refineAbstractType after");
403         return;
404       }
405     assert(0 && "Abstract type not found in table!");
406   }
407
408   void remove(const ValType &OldVal) {
409     MapTy::iterator I = Map.find(OldVal);
410     assert(I != Map.end() && "TypeMap::remove, element not found!");
411     Map.erase(I);
412   }
413
414   void print(const char *Arg) {
415 #ifdef DEBUG_MERGE_TYPES
416     cerr << "TypeMap<>::" << Arg << " table contents:\n";
417     unsigned i = 0;
418     for (MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
419       cerr << " " << (++i) << ". " << I->second << " " 
420            << I->second->getDescription() << endl;
421 #endif
422   }
423 };
424
425
426 // ValTypeBase - This is the base class that is used by the various
427 // instantiations of TypeMap.  This class is an AbstractType user that notifies
428 // the underlying TypeMap when it gets modified.
429 //
430 template<class ValType, class TypeClass>
431 class ValTypeBase : public AbstractTypeUser {
432   TypeMap<ValType, TypeClass> &MyTable;
433 protected:
434   inline ValTypeBase(TypeMap<ValType, TypeClass> &tab) : MyTable(tab) {}
435
436   // Subclass should override this... to update self as usual
437   virtual void doRefinement(const DerivedType *OldTy, const Type *NewTy) = 0;
438
439   // typeBecameConcrete - This callback occurs when a contained type refines
440   // to itself, but becomes concrete in the process.  Our subclass should remove
441   // itself from the ATU list of the specified type.
442   //
443   virtual void typeBecameConcrete(const DerivedType *Ty) = 0;
444   
445   virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
446     if (OldTy == NewTy) {
447       if (!OldTy->isAbstract())
448         typeBecameConcrete(OldTy);
449       return;
450     }
451     TypeMap<ValType, TypeClass> &Table = MyTable;     // Copy MyTable reference
452     ValType Tmp(*(ValType*)this);                     // Copy this.
453     PATypeHandle<TypeClass> OldType(Table.get(*(ValType*)this), this);
454     Table.remove(*(ValType*)this);                    // Destroy's this!
455 #if 1
456     // Refine temporary to new state...
457     Tmp.doRefinement(OldTy, NewTy); 
458
459     Table.add((ValType&)Tmp, (TypeClass*)OldType.get());
460 #endif
461   }
462 };
463
464
465
466 //===----------------------------------------------------------------------===//
467 // Method Type Factory and Value Class...
468 //
469
470 // MethodValType - Define a class to hold the key that goes into the TypeMap
471 //
472 class MethodValType : public ValTypeBase<MethodValType, MethodType> {
473   PATypeHandle<Type> RetTy;
474   vector<PATypeHandle<Type> > ArgTypes;
475   bool isVarArg;
476 public:
477   MethodValType(const Type *ret, const vector<const Type*> &args,
478                 bool IVA, TypeMap<MethodValType, MethodType> &Tab)
479     : ValTypeBase<MethodValType, MethodType>(Tab), RetTy(ret, this),
480       isVarArg(IVA) {
481     for (unsigned i = 0; i < args.size(); ++i)
482       ArgTypes.push_back(PATypeHandle<Type>(args[i], this));
483   }
484
485   // We *MUST* have an explicit copy ctor so that the TypeHandles think that
486   // this MethodValType owns them, not the old one!
487   //
488   MethodValType(const MethodValType &MVT) 
489     : ValTypeBase<MethodValType, MethodType>(MVT), RetTy(MVT.RetTy, this),
490       isVarArg(MVT.isVarArg) {
491     ArgTypes.reserve(MVT.ArgTypes.size());
492     for (unsigned i = 0; i < MVT.ArgTypes.size(); ++i)
493       ArgTypes.push_back(PATypeHandle<Type>(MVT.ArgTypes[i], this));
494   }
495
496   // Subclass should override this... to update self as usual
497   virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
498     if (RetTy == OldType) RetTy = NewType;
499     for (unsigned i = 0; i < ArgTypes.size(); ++i)
500       if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
501   }
502
503   virtual void typeBecameConcrete(const DerivedType *Ty) {
504     if (RetTy == Ty) RetTy.removeUserFromConcrete();
505
506     for (unsigned i = 0; i < ArgTypes.size(); ++i)
507       if (ArgTypes[i] == Ty) ArgTypes[i].removeUserFromConcrete();
508   }
509
510   inline bool operator<(const MethodValType &MTV) const {
511     if (RetTy.get() < MTV.RetTy.get()) return true;
512     if (RetTy.get() > MTV.RetTy.get()) return false;
513
514     if (ArgTypes < MTV.ArgTypes) return true;
515     return (ArgTypes == MTV.ArgTypes) && isVarArg < MTV.isVarArg;
516   }
517 };
518
519 // Define the actual map itself now...
520 static TypeMap<MethodValType, MethodType> MethodTypes;
521
522 // MethodType::get - The factory function for the MethodType class...
523 MethodType *MethodType::get(const Type *ReturnType, 
524                             const vector<const Type*> &Params,
525                             bool isVarArg) {
526   MethodValType VT(ReturnType, Params, isVarArg, MethodTypes);
527   MethodType *MT = MethodTypes.get(VT);
528   if (MT) return MT;
529
530   MethodTypes.add(VT, MT = new MethodType(ReturnType, Params, isVarArg));
531
532 #ifdef DEBUG_MERGE_TYPES
533   cerr << "Derived new type: " << MT << endl;
534 #endif
535   return MT;
536 }
537
538 //===----------------------------------------------------------------------===//
539 // Array Type Factory...
540 //
541 class ArrayValType : public ValTypeBase<ArrayValType, ArrayType> {
542   PATypeHandle<Type> ValTy;
543   int Size;
544 public:
545   ArrayValType(const Type *val, int sz, TypeMap<ArrayValType, ArrayType> &Tab)
546     : ValTypeBase<ArrayValType, ArrayType>(Tab), ValTy(val, this), Size(sz) {}
547
548   // We *MUST* have an explicit copy ctor so that the ValTy thinks that this
549   // ArrayValType owns it, not the old one!
550   //
551   ArrayValType(const ArrayValType &AVT) 
552     : ValTypeBase<ArrayValType, ArrayType>(AVT), ValTy(AVT.ValTy, this),
553       Size(AVT.Size) {}
554
555   // Subclass should override this... to update self as usual
556   virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
557     if (ValTy == OldType) ValTy = NewType;
558   }
559
560   virtual void typeBecameConcrete(const DerivedType *Ty) {
561     assert(ValTy == Ty &&
562            "Contained type became concrete but we're not using it!");
563     ValTy.removeUserFromConcrete();
564   }
565
566   inline bool operator<(const ArrayValType &MTV) const {
567     if (Size < MTV.Size) return true;
568     return Size == MTV.Size && ValTy.get() < MTV.ValTy.get();
569   }
570 };
571
572 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
573
574 ArrayType *ArrayType::get(const Type *ElementType, int NumElements = -1) {
575   assert(ElementType && "Can't get array of null types!");
576
577   ArrayValType AVT(ElementType, NumElements, ArrayTypes);
578   ArrayType *AT = ArrayTypes.get(AVT);
579   if (AT) return AT;           // Found a match, return it!
580
581   // Value not found.  Derive a new type!
582   ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
583
584 #ifdef DEBUG_MERGE_TYPES
585   cerr << "Derived new type: " << AT->getDescription() << endl;
586 #endif
587   return AT;
588 }
589
590 //===----------------------------------------------------------------------===//
591 // Struct Type Factory...
592 //
593
594 // StructValType - Define a class to hold the key that goes into the TypeMap
595 //
596 class StructValType : public ValTypeBase<StructValType, StructType> {
597   vector<PATypeHandle<Type> > ElTypes;
598 public:
599   StructValType(const vector<const Type*> &args,
600                 TypeMap<StructValType, StructType> &Tab)
601     : ValTypeBase<StructValType, StructType>(Tab) {
602     for (unsigned i = 0; i < args.size(); ++i)
603       ElTypes.push_back(PATypeHandle<Type>(args[i], this));
604   }
605
606   // We *MUST* have an explicit copy ctor so that the TypeHandles think that
607   // this StructValType owns them, not the old one!
608   //
609   StructValType(const StructValType &SVT) 
610     : ValTypeBase<StructValType, StructType>(SVT){
611     ElTypes.reserve(SVT.ElTypes.size());
612     for (unsigned i = 0; i < SVT.ElTypes.size(); ++i)
613       ElTypes.push_back(PATypeHandle<Type>(SVT.ElTypes[i], this));
614   }
615
616   // Subclass should override this... to update self as usual
617   virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
618     for (unsigned i = 0; i < ElTypes.size(); ++i)
619       if (ElTypes[i] == OldType) ElTypes[i] = NewType;
620   }
621
622   virtual void typeBecameConcrete(const DerivedType *Ty) {
623     for (unsigned i = 0; i < ElTypes.size(); ++i)
624       if (ElTypes[i] == Ty) ElTypes[i].removeUserFromConcrete();
625   }
626
627   inline bool operator<(const StructValType &STV) const {
628     return ElTypes < STV.ElTypes;
629   }
630 };
631
632 static TypeMap<StructValType, StructType> StructTypes;
633
634 StructType *StructType::get(const vector<const Type*> &ETypes) {
635   StructValType STV(ETypes, StructTypes);
636   StructType *ST = StructTypes.get(STV);
637   if (ST) return ST;
638
639   // Value not found.  Derive a new type!
640   StructTypes.add(STV, ST = new StructType(ETypes));
641
642 #ifdef DEBUG_MERGE_TYPES
643   cerr << "Derived new type: " << ST->getDescription() << endl;
644 #endif
645   return ST;
646 }
647
648 //===----------------------------------------------------------------------===//
649 // Pointer Type Factory...
650 //
651
652 // PointerValType - Define a class to hold the key that goes into the TypeMap
653 //
654 class PointerValType : public ValTypeBase<PointerValType, PointerType> {
655   PATypeHandle<Type> ValTy;
656 public:
657   PointerValType(const Type *val, TypeMap<PointerValType, PointerType> &Tab)
658     : ValTypeBase<PointerValType, PointerType>(Tab), ValTy(val, this) {}
659
660   // We *MUST* have an explicit copy ctor so that the ValTy thinks that this
661   // PointerValType owns it, not the old one!
662   //
663   PointerValType(const PointerValType &PVT) 
664     : ValTypeBase<PointerValType, PointerType>(PVT), ValTy(PVT.ValTy, this) {}
665
666   // Subclass should override this... to update self as usual
667   virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
668     if (ValTy == OldType) ValTy = NewType;
669   }
670
671   virtual void typeBecameConcrete(const DerivedType *Ty) {
672     assert(ValTy == Ty &&
673            "Contained type became concrete but we're not using it!");
674     ValTy.removeUserFromConcrete();
675   }
676
677   inline bool operator<(const PointerValType &MTV) const {
678     return ValTy.get() < MTV.ValTy.get();
679   }
680 };
681
682 static TypeMap<PointerValType, PointerType> PointerTypes;
683
684 PointerType *PointerType::get(const Type *ValueType) {
685   assert(ValueType && "Can't get a pointer to <null> type!");
686   PointerValType PVT(ValueType, PointerTypes);
687
688   PointerType *PT = PointerTypes.get(PVT);
689   if (PT) return PT;
690
691   // Value not found.  Derive a new type!
692   PointerTypes.add(PVT, PT = new PointerType(ValueType));
693
694 #ifdef DEBUG_MERGE_TYPES
695   cerr << "Derived new type: " << PT->getDescription() << endl;
696 #endif
697   return PT;
698 }
699
700
701
702 //===----------------------------------------------------------------------===//
703 //                     Derived Type Refinement Functions
704 //===----------------------------------------------------------------------===//
705
706 // removeAbstractTypeUser - Notify an abstract type that a user of the class
707 // no longer has a handle to the type.  This function is called primarily by
708 // the PATypeHandle class.  When there are no users of the abstract type, it
709 // is anihilated, because there is no way to get a reference to it ever again.
710 //
711 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
712   // Search from back to front because we will notify users from back to
713   // front.  Also, it is likely that there will be a stack like behavior to
714   // users that register and unregister users.
715   //
716   for (unsigned i = AbstractTypeUsers.size(); i > 0; --i) {
717     if (AbstractTypeUsers[i-1] == U) {
718       AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i-1);
719       
720 #ifdef DEBUG_MERGE_TYPES
721       cerr << "  removeAbstractTypeUser<" << (void*)this << ", "
722            << getDescription() << ">[" << i << "] User = " << U << endl;
723 #endif
724
725       if (AbstractTypeUsers.empty() && isAbstract()) {
726 #ifdef DEBUG_MERGE_TYPES
727         cerr << "DELETEing unused abstract type: <" << getDescription()
728              << ">[" << (void*)this << "]" << endl;
729 #endif
730         delete this;                  // No users of this abstract type!
731       }
732       return;
733     }
734   }
735   assert(0 && "AbstractTypeUser not in user list!");
736 }
737
738
739 // refineAbstractTypeTo - This function is used to when it is discovered that
740 // the 'this' abstract type is actually equivalent to the NewType specified.
741 // This causes all users of 'this' to switch to reference the more concrete
742 // type NewType and for 'this' to be deleted.
743 //
744 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
745   assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
746   assert(this != NewType && "Can't refine to myself!");
747
748 #ifdef DEBUG_MERGE_TYPES
749   cerr << "REFINING abstract type [" << (void*)this << " " << getDescription()
750        << "] to [" << (void*)NewType << " " << NewType->getDescription()
751        << "]!\n";
752 #endif
753
754
755   // Make sure to put the type to be refined to into a holder so that if IT gets
756   // refined, that we will not continue using a dead reference...
757   //
758   PATypeHolder<Type> NewTy(NewType);
759
760   // Add a self use of the current type so that we don't delete ourself until
761   // after this while loop.  We are careful to never invoke refine on ourself,
762   // so this extra reference shouldn't be a problem.  Note that we must only
763   // remove a single reference at the end, but we must tolerate multiple self
764   // references because we could be refineAbstractTypeTo'ing recursively on the
765   // same type.
766   //
767   addAbstractTypeUser(this);
768
769   // Count the number of self uses.  Stop looping when sizeof(list) == NSU.
770   unsigned NumSelfUses = 0;
771
772   // Iterate over all of the uses of this type, invoking callback.  Each user
773   // should remove itself from our use list automatically.
774   //
775   while (AbstractTypeUsers.size() > NumSelfUses) {
776     AbstractTypeUser *User = AbstractTypeUsers.back();
777
778     if (User == this) {
779       // Move self use to the start of the list.  Increment NSU.
780       swap(AbstractTypeUsers.back(), AbstractTypeUsers[NumSelfUses++]);
781     } else {
782       unsigned OldSize = AbstractTypeUsers.size();
783 #ifdef DEBUG_MERGE_TYPES
784       cerr << " REFINING user " << OldSize-1 << " of abstract type ["
785            << (void*)this << " " << getDescription() << "] to [" 
786            << (void*)NewTy.get() << " " << NewTy->getDescription() << "]!\n";
787 #endif
788       User->refineAbstractType(this, NewTy);
789
790       if (AbstractTypeUsers.size() == OldSize) {
791         User->refineAbstractType(this, NewTy);
792       }
793       assert(AbstractTypeUsers.size() != OldSize &&
794              "AbsTyUser did not remove self from user list!");
795     }
796   }
797
798   // Remove a single self use, even though there may be several here. This will
799   // probably 'delete this', so no instance variables may be used after this
800   // occurs...
801   assert(AbstractTypeUsers.back() == this && "Only self uses should be left!");
802   removeAbstractTypeUser(this);
803 }
804
805
806 // typeIsRefined - Notify AbstractTypeUsers of this type that the current type
807 // has been refined a bit.  The pointer is still valid and still should be
808 // used, but the subtypes have changed.
809 //
810 void DerivedType::typeIsRefined() {
811   assert(isRefining >= 0 && isRefining <= 2 && "isRefining out of bounds!");
812   if (isRefining == 1) return;  // Kill recursion here...
813   ++isRefining;
814
815 #ifdef DEBUG_MERGE_TYPES
816   cerr << "typeIsREFINED type: " << (void*)this <<" "<<getDescription() << endl;
817 #endif
818   for (unsigned i = 0; i < AbstractTypeUsers.size(); ) {
819     AbstractTypeUser *ATU = AbstractTypeUsers[i];
820 #ifdef DEBUG_MERGE_TYPES
821     cerr << " typeIsREFINED user " << i << " of abstract type ["
822          << (void*)this << " " << getDescription() << "]\n";
823 #endif
824     ATU->refineAbstractType(this, this);
825     
826     // If the user didn't remove itself from the list, continue...
827     if (AbstractTypeUsers.size() > i && AbstractTypeUsers[i] == ATU) {
828       ++i;
829     }
830   }
831
832   --isRefining;
833
834 #ifndef _NDEBUG
835   if (!(isAbstract() || AbstractTypeUsers.empty()))
836     for (unsigned i = 0; i < AbstractTypeUsers.size(); ++i) {
837       if (AbstractTypeUsers[i] != this) {
838         // Debugging hook
839         cerr << "FOUND FAILURE\n";
840         AbstractTypeUsers[i]->refineAbstractType(this, this);
841         assert(0 && "Type became concrete,"
842                " but it still has abstract type users hanging around!");
843       }
844   }
845 #endif
846 }
847   
848
849
850
851 // refineAbstractType - Called when a contained type is found to be more
852 // concrete - this could potentially change us from an abstract type to a
853 // concrete type.
854 //
855 void MethodType::refineAbstractType(const DerivedType *OldType,
856                                     const Type *NewType) {
857 #ifdef DEBUG_MERGE_TYPES
858   cerr << "MethodTy::refineAbstractTy(" << (void*)OldType << "[" 
859        << OldType->getDescription() << "], " << (void*)NewType << " [" 
860        << NewType->getDescription() << "])\n";
861 #endif
862
863   if (!OldType->isAbstract()) {
864     if (ResultType == OldType) ResultType.removeUserFromConcrete();
865     for (unsigned i = 0; i < ParamTys.size(); ++i)
866       if (ParamTys[i] == OldType) ParamTys[i].removeUserFromConcrete();
867   }
868
869   if (OldType != NewType) {
870     if (ResultType == OldType) ResultType = NewType;
871
872     for (unsigned i = 0; i < ParamTys.size(); ++i)
873       if (ParamTys[i] == OldType) ParamTys[i] = NewType;
874   }
875
876   const MethodType *MT = MethodTypes.containsEquivalent(this);
877   if (MT && MT != this) {
878     refineAbstractTypeTo(MT);            // Different type altogether...
879   } else {
880     setDerivedTypeProperties();          // Update the name and isAbstract
881     typeIsRefined();                     // Same type, different contents...
882   }
883 }
884
885
886 // refineAbstractType - Called when a contained type is found to be more
887 // concrete - this could potentially change us from an abstract type to a
888 // concrete type.
889 //
890 void ArrayType::refineAbstractType(const DerivedType *OldType,
891                                    const Type *NewType) {
892 #ifdef DEBUG_MERGE_TYPES
893   cerr << "ArrayTy::refineAbstractTy(" << (void*)OldType << "[" 
894        << OldType->getDescription() << "], " << (void*)NewType << " [" 
895        << NewType->getDescription() << "])\n";
896 #endif
897
898   if (!OldType->isAbstract()) {
899     assert(ElementType == OldType);
900     ElementType.removeUserFromConcrete();
901   }
902
903   ElementType = NewType;
904   const ArrayType *AT = ArrayTypes.containsEquivalent(this);
905   if (AT && AT != this) {
906     refineAbstractTypeTo(AT);          // Different type altogether...
907   } else {
908     setDerivedTypeProperties();        // Update the name and isAbstract
909     typeIsRefined();                   // Same type, different contents...
910   }
911 }
912
913
914 // refineAbstractType - Called when a contained type is found to be more
915 // concrete - this could potentially change us from an abstract type to a
916 // concrete type.
917 //
918 void StructType::refineAbstractType(const DerivedType *OldType,
919                                     const Type *NewType) {
920 #ifdef DEBUG_MERGE_TYPES
921   cerr << "StructTy::refineAbstractTy(" << (void*)OldType << "[" 
922        << OldType->getDescription() << "], " << (void*)NewType << " [" 
923        << NewType->getDescription() << "])\n";
924 #endif
925   if (!OldType->isAbstract()) {
926     for (unsigned i = 0; i < ETypes.size(); ++i)
927       if (ETypes[i] == OldType)
928         ETypes[i].removeUserFromConcrete();
929   }
930
931   if (OldType != NewType) {
932     // Update old type to new type in the array...
933     for (unsigned i = 0; i < ETypes.size(); ++i)
934       if (ETypes[i] == OldType)
935         ETypes[i] = NewType;
936   } 
937
938   const StructType *ST = StructTypes.containsEquivalent(this);
939   if (ST && ST != this) {
940     refineAbstractTypeTo(ST);          // Different type altogether...
941   } else {
942     setDerivedTypeProperties();        // Update the name and isAbstract
943     typeIsRefined();                   // Same type, different contents...
944   }
945 }
946
947 // refineAbstractType - Called when a contained type is found to be more
948 // concrete - this could potentially change us from an abstract type to a
949 // concrete type.
950 //
951 void PointerType::refineAbstractType(const DerivedType *OldType,
952                                      const Type *NewType) {
953 #ifdef DEBUG_MERGE_TYPES
954   cerr << "PointerTy::refineAbstractTy(" << (void*)OldType << "[" 
955        << OldType->getDescription() << "], " << (void*)NewType << " [" 
956        << NewType->getDescription() << "])\n";
957 #endif
958
959   if (!OldType->isAbstract()) {
960     assert(ValueType == OldType);
961     ValueType.removeUserFromConcrete();
962   }
963
964   ValueType = NewType;
965   const PointerType *PT = PointerTypes.containsEquivalent(this);
966
967   if (PT && PT != this) {
968     refineAbstractTypeTo(PT);          // Different type altogether...
969   } else {
970     setDerivedTypeProperties();        // Update the name and isAbstract
971     typeIsRefined();                   // Same type, different contents...
972   }
973 }
974