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