Two things:
[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 = 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   if (Ty != Ty2) {
307     map<const Type*, const Type*>::iterator I = EqTypes.find(Ty);
308     if (I != EqTypes.end())
309       return I->second == Ty2;    // Looping back on a type, check for equality
310
311     // Otherwise, add the mapping to the table to make sure we don't get
312     // recursion on the types...
313     EqTypes.insert(make_pair(Ty, Ty2));
314   }
315
316   // Iterate over the types and make sure the the contents are equivalent...
317   Type::subtype_iterator I  = Ty ->subtype_begin(), IE  = Ty ->subtype_end();
318   Type::subtype_iterator I2 = Ty2->subtype_begin(), IE2 = Ty2->subtype_end();
319   for (; I != IE && I2 != IE2; ++I, ++I2)
320     if (!TypesEqual(*I, *I2, EqTypes)) return false;
321
322   // Two really annoying special cases that breaks an otherwise nice simple
323   // algorithm is the fact that arraytypes have sizes that differentiates types,
324   // and that method types can be varargs or not.  Consider this now.
325   if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
326     if (ATy->getNumElements() != cast<const ArrayType>(Ty2)->getNumElements())
327       return false;
328   } else if (const MethodType *MTy = dyn_cast<MethodType>(Ty)) {
329     if (MTy->isVarArg() != cast<const MethodType>(Ty2)->isVarArg())
330       return false;
331   }
332
333
334   return I == IE && I2 == IE2;    // Types equal if both iterators are done
335 }
336
337 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
338   map<const Type *, const Type *> EqTypes;
339   return TypesEqual(Ty, Ty2, EqTypes);
340 }
341
342
343
344 //===----------------------------------------------------------------------===//
345 //                       Derived Type Factory Functions
346 //===----------------------------------------------------------------------===//
347
348 // TypeMap - Make sure that only one instance of a particular type may be
349 // created on any given run of the compiler... note that this involves updating
350 // our map if an abstract type gets refined somehow...
351 //
352 template<class ValType, class TypeClass>
353 class TypeMap : public AbstractTypeUser {
354   typedef map<ValType, PATypeHandle<TypeClass> > MapTy;
355   MapTy Map;
356 public:
357
358   ~TypeMap() { print("ON EXIT"); }
359
360   inline TypeClass *get(const ValType &V) {
361     map<ValType, PATypeHandle<TypeClass> >::iterator I = Map.find(V);
362     // TODO: FIXME: When Types are not CONST.
363     return (I != Map.end()) ? (TypeClass*)I->second.get() : 0;
364   }
365
366   inline void add(const ValType &V, TypeClass *T) {
367     Map.insert(make_pair(V, PATypeHandle<TypeClass>(T, this)));
368     print("add");
369   }
370
371   // containsEquivalent - Return true if the typemap contains a type that is
372   // structurally equivalent to the specified type.
373   //
374   inline const TypeClass *containsEquivalent(const TypeClass *Ty) {
375     for (MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
376       if (I->second.get() != Ty && TypesEqual(Ty, I->second.get()))
377         return (TypeClass*)I->second.get();  // FIXME TODO when types not const
378     return 0;
379   }
380
381   // refineAbstractType - This is called when one of the contained abstract
382   // types gets refined... this simply removes the abstract type from our table.
383   // We expect that whoever refined the type will add it back to the table,
384   // corrected.
385   //
386   virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
387     if (OldTy == NewTy) return;
388 #ifdef DEBUG_MERGE_TYPES
389     cerr << "Removing Old type from Tab: " << (void*)OldTy << ", "
390          << OldTy->getDescription() << "  replacement == " << (void*)NewTy
391          << ", " << NewTy->getDescription() << endl;
392 #endif
393     for (MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
394       if (I->second == OldTy) {
395         Map.erase(I);
396         print("refineAbstractType after");
397         return;
398       }
399     assert(0 && "Abstract type not found in table!");
400   }
401
402   void remove(const ValType &OldVal) {
403     MapTy::iterator I = Map.find(OldVal);
404     assert(I != Map.end() && "TypeMap::remove, element not found!");
405     Map.erase(I);
406   }
407
408   void print(const char *Arg) {
409 #ifdef DEBUG_MERGE_TYPES
410     cerr << "TypeMap<>::" << Arg << " table contents:\n";
411     unsigned i = 0;
412     for (MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
413       cerr << " " << (++i) << ". " << I->second << " " 
414            << I->second->getDescription() << endl;
415 #endif
416   }
417 };
418
419
420 // ValTypeBase - This is the base class that is used by the various
421 // instantiations of TypeMap.  This class is an AbstractType user that notifies
422 // the underlying TypeMap when it gets modified.
423 //
424 template<class ValType, class TypeClass>
425 class ValTypeBase : public AbstractTypeUser {
426   TypeMap<ValType, TypeClass> &MyTable;
427 protected:
428   inline ValTypeBase(TypeMap<ValType, TypeClass> &tab) : MyTable(tab) {}
429
430   // Subclass should override this... to update self as usual
431   virtual void doRefinement(const DerivedType *OldTy, const Type *NewTy) = 0;
432   
433   virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
434     if (OldTy == NewTy) return;
435     TypeMap<ValType, TypeClass> &Table = MyTable;     // Copy MyTable reference
436     ValType Tmp(*(ValType*)this);                     // Copy this.
437     PATypeHandle<TypeClass> OldType(Table.get(*(ValType*)this), this);
438     Table.remove(*(ValType*)this);                    // Destroy's this!
439
440     // Refine temporary to new state...
441     Tmp.doRefinement(OldTy, NewTy); 
442
443     Table.add((ValType&)Tmp, (TypeClass*)OldType.get());
444   }
445 };
446
447
448
449 //===----------------------------------------------------------------------===//
450 // Method Type Factory and Value Class...
451 //
452
453 // MethodValType - Define a class to hold the key that goes into the TypeMap
454 //
455 class MethodValType : public ValTypeBase<MethodValType, MethodType> {
456   PATypeHandle<Type> RetTy;
457   vector<PATypeHandle<Type> > ArgTypes;
458   bool isVarArg;
459 public:
460   MethodValType(const Type *ret, const vector<const Type*> &args,
461                 bool IVA, TypeMap<MethodValType, MethodType> &Tab)
462     : ValTypeBase<MethodValType, MethodType>(Tab), RetTy(ret, this),
463       isVarArg(IVA) {
464     for (unsigned i = 0; i < args.size(); ++i)
465       ArgTypes.push_back(PATypeHandle<Type>(args[i], this));
466   }
467
468   // We *MUST* have an explicit copy ctor so that the TypeHandles think that
469   // this MethodValType owns them, not the old one!
470   //
471   MethodValType(const MethodValType &MVT) 
472     : ValTypeBase<MethodValType, MethodType>(MVT), RetTy(MVT.RetTy, this),
473       isVarArg(MVT.isVarArg) {
474     ArgTypes.reserve(MVT.ArgTypes.size());
475     for (unsigned i = 0; i < MVT.ArgTypes.size(); ++i)
476       ArgTypes.push_back(PATypeHandle<Type>(MVT.ArgTypes[i], this));
477   }
478
479   // Subclass should override this... to update self as usual
480   virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
481     if (RetTy == OldType) RetTy = NewType;
482     for (unsigned i = 0; i < ArgTypes.size(); ++i)
483       if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
484   }
485
486   inline bool operator<(const MethodValType &MTV) const {
487     if (RetTy.get() < MTV.RetTy.get()) return true;
488     if (RetTy.get() > MTV.RetTy.get()) return false;
489
490     if (ArgTypes < MTV.ArgTypes) return true;
491     return (ArgTypes == MTV.ArgTypes) && isVarArg < MTV.isVarArg;
492   }
493 };
494
495 // Define the actual map itself now...
496 static TypeMap<MethodValType, MethodType> MethodTypes;
497
498 // MethodType::get - The factory function for the MethodType class...
499 MethodType *MethodType::get(const Type *ReturnType, 
500                             const vector<const Type*> &Params,
501                             bool isVarArg) {
502   MethodValType VT(ReturnType, Params, isVarArg, MethodTypes);
503   MethodType *MT = MethodTypes.get(VT);
504   if (MT) return MT;
505
506   MethodTypes.add(VT, MT = new MethodType(ReturnType, Params, isVarArg));
507
508 #ifdef DEBUG_MERGE_TYPES
509   cerr << "Derived new type: " << MT << endl;
510 #endif
511   return MT;
512 }
513
514 //===----------------------------------------------------------------------===//
515 // Array Type Factory...
516 //
517 class ArrayValType : public ValTypeBase<ArrayValType, ArrayType> {
518   PATypeHandle<Type> ValTy;
519   int Size;
520 public:
521   ArrayValType(const Type *val, int sz, TypeMap<ArrayValType, ArrayType> &Tab)
522     : ValTypeBase<ArrayValType, ArrayType>(Tab), ValTy(val, this), Size(sz) {}
523
524   // We *MUST* have an explicit copy ctor so that the ValTy thinks that this
525   // ArrayValType owns it, not the old one!
526   //
527   ArrayValType(const ArrayValType &AVT) 
528     : ValTypeBase<ArrayValType, ArrayType>(AVT), ValTy(AVT.ValTy, this),
529       Size(AVT.Size) {}
530
531   // Subclass should override this... to update self as usual
532   virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
533     if (ValTy == OldType) ValTy = NewType;
534   }
535
536   inline bool operator<(const ArrayValType &MTV) const {
537     if (Size < MTV.Size) return true;
538     return Size == MTV.Size && ValTy.get() < MTV.ValTy.get();
539   }
540 };
541
542 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
543
544 ArrayType *ArrayType::get(const Type *ElementType, int NumElements = -1) {
545   assert(ElementType && "Can't get array of null types!");
546
547   ArrayValType AVT(ElementType, NumElements, ArrayTypes);
548   ArrayType *AT = ArrayTypes.get(AVT);
549   if (AT) return AT;           // Found a match, return it!
550
551   // Value not found.  Derive a new type!
552   ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
553
554 #ifdef DEBUG_MERGE_TYPES
555   cerr << "Derived new type: " << AT->getDescription() << endl;
556 #endif
557   return AT;
558 }
559
560 //===----------------------------------------------------------------------===//
561 // Struct Type Factory...
562 //
563
564 // StructValType - Define a class to hold the key that goes into the TypeMap
565 //
566 class StructValType : public ValTypeBase<StructValType, StructType> {
567   vector<PATypeHandle<Type> > ElTypes;
568 public:
569   StructValType(const vector<const Type*> &args,
570                 TypeMap<StructValType, StructType> &Tab)
571     : ValTypeBase<StructValType, StructType>(Tab) {
572     for (unsigned i = 0; i < args.size(); ++i)
573       ElTypes.push_back(PATypeHandle<Type>(args[i], this));
574   }
575
576   // We *MUST* have an explicit copy ctor so that the TypeHandles think that
577   // this StructValType owns them, not the old one!
578   //
579   StructValType(const StructValType &SVT) 
580     : ValTypeBase<StructValType, StructType>(SVT){
581     ElTypes.reserve(SVT.ElTypes.size());
582     for (unsigned i = 0; i < SVT.ElTypes.size(); ++i)
583       ElTypes.push_back(PATypeHandle<Type>(SVT.ElTypes[i], this));
584   }
585
586   // Subclass should override this... to update self as usual
587   virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
588     for (unsigned i = 0; i < ElTypes.size(); ++i)
589       if (ElTypes[i] == OldType) ElTypes[i] = NewType;
590   }
591
592   inline bool operator<(const StructValType &STV) const {
593     return ElTypes < STV.ElTypes;
594   }
595 };
596
597 static TypeMap<StructValType, StructType> StructTypes;
598
599 StructType *StructType::get(const vector<const Type*> &ETypes) {
600   StructValType STV(ETypes, StructTypes);
601   StructType *ST = StructTypes.get(STV);
602   if (ST) return ST;
603
604   // Value not found.  Derive a new type!
605   StructTypes.add(STV, ST = new StructType(ETypes));
606
607 #ifdef DEBUG_MERGE_TYPES
608   cerr << "Derived new type: " << ST->getDescription() << endl;
609 #endif
610   return ST;
611 }
612
613 //===----------------------------------------------------------------------===//
614 // Pointer Type Factory...
615 //
616
617 // PointerValType - Define a class to hold the key that goes into the TypeMap
618 //
619 class PointerValType : public ValTypeBase<PointerValType, PointerType> {
620   PATypeHandle<Type> ValTy;
621 public:
622   PointerValType(const Type *val, TypeMap<PointerValType, PointerType> &Tab)
623     : ValTypeBase<PointerValType, PointerType>(Tab), ValTy(val, this) {}
624
625   // We *MUST* have an explicit copy ctor so that the ValTy thinks that this
626   // PointerValType owns it, not the old one!
627   //
628   PointerValType(const PointerValType &PVT) 
629     : ValTypeBase<PointerValType, PointerType>(PVT), ValTy(PVT.ValTy, this) {}
630
631   // Subclass should override this... to update self as usual
632   virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
633     if (ValTy == OldType) ValTy = NewType;
634   }
635
636   inline bool operator<(const PointerValType &MTV) const {
637     return ValTy.get() < MTV.ValTy.get();
638   }
639 };
640
641 static TypeMap<PointerValType, PointerType> PointerTypes;
642
643 PointerType *PointerType::get(const Type *ValueType) {
644   assert(ValueType && "Can't get a pointer to <null> type!");
645   PointerValType PVT(ValueType, PointerTypes);
646
647   PointerType *PT = PointerTypes.get(PVT);
648   if (PT) return PT;
649
650   // Value not found.  Derive a new type!
651   PointerTypes.add(PVT, PT = new PointerType(ValueType));
652
653 #ifdef DEBUG_MERGE_TYPES
654   cerr << "Derived new type: " << PT->getDescription() << endl;
655 #endif
656   return PT;
657 }
658
659
660
661 //===----------------------------------------------------------------------===//
662 //                     Derived Type Refinement Functions
663 //===----------------------------------------------------------------------===//
664
665 // removeAbstractTypeUser - Notify an abstract type that a user of the class
666 // no longer has a handle to the type.  This function is called primarily by
667 // the PATypeHandle class.  When there are no users of the abstract type, it
668 // is anihilated, because there is no way to get a reference to it ever again.
669 //
670 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
671   // Search from back to front because we will notify users from back to
672   // front.  Also, it is likely that there will be a stack like behavior to
673   // users that register and unregister users.
674   //
675   for (unsigned i = AbstractTypeUsers.size(); i > 0; --i) {
676     if (AbstractTypeUsers[i-1] == U) {
677       AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i-1);
678       
679 #ifdef DEBUG_MERGE_TYPES
680       cerr << "  removeAbstractTypeUser[" << (void*)this << ", "
681            << getDescription() << "][" << AbstractTypeUsers.size()
682            << "] User = " << U << endl;
683 #endif
684
685       if (AbstractTypeUsers.empty()) {
686 #ifdef DEBUG_MERGE_TYPES
687         cerr << "DELETEing unused abstract type: " << getDescription()
688              << " " << (void*)this << endl;
689 #endif
690         delete this;                  // No users of this abstract type!
691       }
692       return;
693     }
694   }
695   assert(isAbstract() && "removeAbstractTypeUser: Type not abstract!");
696   assert(0 && "AbstractTypeUser not in user list!");
697 }
698
699
700 // refineAbstractTypeTo - This function is used to when it is discovered that
701 // the 'this' abstract type is actually equivalent to the NewType specified.
702 // This causes all users of 'this' to switch to reference the more concrete
703 // type NewType and for 'this' to be deleted.
704 //
705 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
706   assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
707   assert(this != NewType && "Can't refine to myself!");
708
709 #ifdef DEBUG_MERGE_TYPES
710   cerr << "REFINING abstract type [" << (void*)this << " " << getDescription()
711        << "] to [" << (void*)NewType << " " << NewType->getDescription()
712        << "]!\n";
713 #endif
714
715
716   // Make sure to put the type to be refined to into a holder so that if IT gets
717   // refined, that we will not continue using a dead reference...
718   //
719   PATypeHolder<Type> NewTy(NewType);
720
721   // Add a self use of the current type so that we don't delete ourself until
722   // after this while loop.  We are careful to never invoke refine on ourself,
723   // so this extra reference shouldn't be a problem.  Note that we must only
724   // remove a single reference at the end, but we must tolerate multiple self
725   // references because we could be refineAbstractTypeTo'ing recursively on the
726   // same type.
727   //
728   addAbstractTypeUser(this);
729
730   // Count the number of self uses.  Stop looping when sizeof(list) == NSU.
731   unsigned NumSelfUses = 0;
732
733   // Iterate over all of the uses of this type, invoking callback.  Each user
734   // should remove itself from our use list automatically.
735   //
736   while (AbstractTypeUsers.size() > NumSelfUses) {
737     AbstractTypeUser *User = AbstractTypeUsers.back();
738
739     if (User == this) {
740       // Move self use to the start of the list.  Increment NSU.
741       swap(AbstractTypeUsers.back(), AbstractTypeUsers[NumSelfUses++]);
742     } else {
743       unsigned OldSize = AbstractTypeUsers.size();
744 #ifdef DEBUG_MERGE_TYPES
745       cerr << " REFINING user " << OldSize-1 << " of abstract type ["
746            << (void*)this << " " << getDescription() << "] to [" 
747            << (void*)NewTy.get() << " " << NewTy->getDescription() << "]!\n";
748 #endif
749       User->refineAbstractType(this, NewTy);
750
751       assert(AbstractTypeUsers.size() != OldSize &&
752              "AbsTyUser did not remove self from user list!");
753     }
754   }
755
756   // Remove a single self use, even though there may be several here. This will
757   // probably 'delete this', so no instance variables may be used after this
758   // occurs...
759   assert(AbstractTypeUsers.back() == this && "Only self uses should be left!");
760   removeAbstractTypeUser(this);
761 }
762
763
764 // typeIsRefined - Notify AbstractTypeUsers of this type that the current type
765 // has been refined a bit.  The pointer is still valid and still should be
766 // used, but the subtypes have changed.
767 //
768 void DerivedType::typeIsRefined() {
769   assert(isRefining >= 0 && isRefining <= 2 && "isRefining out of bounds!");
770   if (isRefining == 2) return;  // Kill recursion here...
771   ++isRefining;
772
773 #ifdef DEBUG_MERGE_TYPES
774   cerr << "typeIsREFINED type: " << (void*)this <<" "<<getDescription() << endl;
775 #endif
776   for (unsigned i = 0; i < AbstractTypeUsers.size(); ) {
777     AbstractTypeUser *ATU = AbstractTypeUsers[i];
778 #ifdef DEBUG_MERGE_TYPES
779     cerr << " typeIsREFINED user " << i << " of abstract type ["
780          << (void*)this << " " << getDescription() << "]\n";
781 #endif
782     ATU->refineAbstractType(this, this);
783     
784     // If the user didn't remove itself from the list, continue...
785     if (AbstractTypeUsers.size() > i && AbstractTypeUsers[i] == ATU)
786       ++i;
787   }
788
789   --isRefining;
790 }
791   
792
793
794
795 // refineAbstractType - Called when a contained type is found to be more
796 // concrete - this could potentially change us from an abstract type to a
797 // concrete type.
798 //
799 void MethodType::refineAbstractType(const DerivedType *OldType,
800                                     const Type *NewType) {
801 #ifdef DEBUG_MERGE_TYPES
802   cerr << "MethodTy::refineAbstractTy(" << (void*)OldType << "[" 
803        << OldType->getDescription() << "], " << (void*)NewType << " [" 
804        << NewType->getDescription() << "])\n";
805 #endif
806
807   if (OldType == ResultType) {
808     ResultType = NewType;
809   } else {
810     unsigned i;
811     for (i = 0; i < ParamTys.size(); ++i)
812       if (OldType == ParamTys[i]) {
813         ParamTys[i] = NewType;
814         break;
815       }
816     assert(i != ParamTys.size() && "Did not contain oldtype!");
817   }
818
819
820   // Notify everyone that I have changed!
821   if (const MethodType *MTy = MethodTypes.containsEquivalent(this)) {
822 #ifndef _NDEBUG
823     // Calculate accurate name for debugging purposes
824     vector<const Type *> TypeStack;
825     bool isAbstract = false, isRecursive = false;
826     setDescription(getTypeProps(this, TypeStack, isAbstract, isRecursive));
827 #endif
828
829 #ifdef DEBUG_MERGE_TYPES
830     cerr << "Type " << (void*)this << " equilivant to existing " << (void*)MTy
831          << " - destroying!\n";
832 #endif
833     refineAbstractTypeTo(MTy);      // Different type altogether...
834     return;
835   }
836   setDerivedTypeProperties();  // Update the name and isAbstract
837   typeIsRefined();
838 }
839
840
841 // refineAbstractType - Called when a contained type is found to be more
842 // concrete - this could potentially change us from an abstract type to a
843 // concrete type.
844 //
845 void ArrayType::refineAbstractType(const DerivedType *OldType,
846                                    const Type *NewType) {
847 #ifdef DEBUG_MERGE_TYPES
848   cerr << "ArrayTy::refineAbstractTy(" << (void*)OldType << "[" 
849        << OldType->getDescription() << "], " << (void*)NewType << " [" 
850        << NewType->getDescription() << "])\n";
851 #endif
852   assert(OldType == ElementType && "Cannot refine from OldType!");
853   ElementType = NewType;
854
855   // Notify everyone that I have changed!
856   if (const ArrayType *ATy = ArrayTypes.containsEquivalent(this)) {
857 #ifndef _NDEBUG
858     // Calculate accurate name for debugging purposes
859     vector<const Type *> TypeStack;
860     bool isAbstract = false, isRecursive = false;
861     setDescription(getTypeProps(this, TypeStack, isAbstract, isRecursive));
862 #endif
863
864 #ifdef DEBUG_MERGE_TYPES
865     cerr << "Type " << (void*)this << " equilivant to existing " << (void*)ATy
866          << " - destroying!\n";
867 #endif
868     refineAbstractTypeTo(ATy);      // Different type altogether...
869     return;
870   }
871   setDerivedTypeProperties();   // Update the name and isAbstract
872   typeIsRefined();              // Same type, different contents...
873 }
874
875
876 // refineAbstractType - Called when a contained type is found to be more
877 // concrete - this could potentially change us from an abstract type to a
878 // concrete type.
879 //
880 void StructType::refineAbstractType(const DerivedType *OldType,
881                                     const Type *NewType) {
882 #ifdef DEBUG_MERGE_TYPES
883   cerr << "StructTy::refineAbstractTy(" << (void*)OldType << "[" 
884        << OldType->getDescription() << "], " << (void*)NewType << " [" 
885        << NewType->getDescription() << "])\n";
886 #endif
887
888   if (OldType != NewType) {
889     unsigned i;
890     for (i = 0; i < ETypes.size(); ++i)
891       if (OldType == ETypes[i]) {
892         ETypes[i] = NewType;
893         break;
894       }
895     assert(i != ETypes.size() && "Did not contain oldtype!");
896   }
897
898   vector<const Type *> ElTypes(
899       map_iterator(ETypes.begin(), mem_fun_ref(&PATypeHandle<Type>::get)),
900       map_iterator(ETypes.end()  , mem_fun_ref(&PATypeHandle<Type>::get)));
901
902
903   // Notify everyone that I have changed!
904   if (const StructType *STy = StructTypes.containsEquivalent(this)) {
905 #ifndef _NDEBUG
906     // Calculate accurate name for debugging purposes
907     vector<const Type *> TypeStack;
908     bool isAbstract = false, isRecursive = false;
909     setDescription(getTypeProps(this, TypeStack, isAbstract, isRecursive));
910 #endif
911
912 #ifdef DEBUG_MERGE_TYPES
913     cerr << "Type " << (void*)this << " equilivant to existing " << (void*)STy
914          << " - destroying!\n";
915 #endif
916     refineAbstractTypeTo(STy);      // Different type altogether...
917     return;
918   }
919   setDerivedTypeProperties();          // Update the name and isAbstract
920   typeIsRefined();                   // Same type, different contents...
921 }
922
923 // refineAbstractType - Called when a contained type is found to be more
924 // concrete - this could potentially change us from an abstract type to a
925 // concrete type.
926 //
927 void PointerType::refineAbstractType(const DerivedType *OldType,
928                                      const Type *NewType) {
929 #ifdef DEBUG_MERGE_TYPES
930   cerr << "PointerTy::refineAbstractTy(" << (void*)OldType << "[" 
931        << OldType->getDescription() << "], " << (void*)NewType << " [" 
932        << NewType->getDescription() << "])\n";
933 #endif
934   assert(OldType == ValueType && "Cannot refine from OldType!");
935   ValueType = NewType;
936
937   // Notify everyone that I have changed!
938   if (const PointerType *PTy = PointerTypes.containsEquivalent(this)) {
939 #ifndef _NDEBUG
940     // Calculate accurate name for debugging purposes
941     vector<const Type *> TypeStack;
942     bool isAbstract = false, isRecursive = false;
943     setDescription(getTypeProps(this, TypeStack, isAbstract, isRecursive));
944 #endif
945
946 #ifdef DEBUG_MERGE_TYPES
947     cerr << "Type " << (void*)this << " equilivant to existing " << (void*)PTy
948          << " - destroying!\n";
949 #endif
950     refineAbstractTypeTo(PTy);      // Different type altogether...
951     return;
952   }
953   setDerivedTypeProperties();  // Update the name and isAbstract
954   typeIsRefined();                   // Same type, different contents...
955 }
956