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