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