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