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