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