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