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