Make sure that at least one virtual method is defined in a .cpp file to avoid
[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 using namespace llvm;
22
23 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
24 // created and later destroyed, all in an effort to make sure that there is only
25 // a single canonical version of a type.
26 //
27 //#define DEBUG_MERGE_TYPES 1
28
29 AbstractTypeUser::~AbstractTypeUser() {}
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), RefCount(0), 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::param_iterator I = FTy->param_begin(),
194            E = FTy->param_end(); I != E; ++I) {
195       if (I != FTy->param_begin())
196         Result += ", ";
197       Result += getTypeDescription(*I, TypeStack);
198     }
199     if (FTy->isVarArg()) {
200       if (FTy->getNumParams()) Result += ", ";
201       Result += "...";
202     }
203     Result += ")";
204     break;
205   }
206   case Type::StructTyID: {
207     const StructType *STy = cast<StructType>(Ty);
208     Result = "{ ";
209     for (StructType::element_iterator I = STy->element_begin(),
210            E = STy->element_end(); I != E; ++I) {
211       if (I != STy->element_begin())
212         Result += ", ";
213       Result += getTypeDescription(*I, TypeStack);
214     }
215     Result += " }";
216     break;
217   }
218   case Type::PointerTyID: {
219     const PointerType *PTy = cast<PointerType>(Ty);
220     Result = getTypeDescription(PTy->getElementType(), TypeStack) + " *";
221     break;
222   }
223   case Type::ArrayTyID: {
224     const ArrayType *ATy = cast<ArrayType>(Ty);
225     unsigned NumElements = ATy->getNumElements();
226     Result = "[";
227     Result += utostr(NumElements) + " x ";
228     Result += getTypeDescription(ATy->getElementType(), TypeStack) + "]";
229     break;
230   }
231   default:
232     Result = "<error>";
233     assert(0 && "Unhandled type in getTypeDescription!");
234   }
235
236   TypeStack.pop_back();       // Remove self from stack...
237
238   return Result;
239 }
240
241
242
243 static const std::string &getOrCreateDesc(std::map<const Type*,std::string>&Map,
244                                           const Type *Ty) {
245   std::map<const Type*, std::string>::iterator I = Map.find(Ty);
246   if (I != Map.end()) return I->second;
247     
248   std::vector<const Type *> TypeStack;
249   return Map[Ty] = getTypeDescription(Ty, TypeStack);
250 }
251
252
253 const std::string &Type::getDescription() const {
254   if (isAbstract())
255     return getOrCreateDesc(AbstractTypeDescriptions, this);
256   else
257     return getOrCreateDesc(ConcreteTypeDescriptions, this);
258 }
259
260
261 bool StructType::indexValid(const Value *V) const {
262   // Structure indexes require unsigned integer constants.
263   if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(V))
264     return CU->getValue() < ContainedTys.size();
265   return false;
266 }
267
268 // getTypeAtIndex - Given an index value into the type, return the type of the
269 // element.  For a structure type, this must be a constant value...
270 //
271 const Type *StructType::getTypeAtIndex(const Value *V) const {
272   assert(isa<Constant>(V) && "Structure index must be a constant!!");
273   unsigned Idx = cast<ConstantUInt>(V)->getValue();
274   assert(Idx < ContainedTys.size() && "Structure index out of range!");
275   assert(indexValid(V) && "Invalid structure index!"); // Duplicate check
276   return ContainedTys[Idx];
277 }
278
279
280 //===----------------------------------------------------------------------===//
281 //                           Auxiliary classes
282 //===----------------------------------------------------------------------===//
283 //
284 // These classes are used to implement specialized behavior for each different
285 // type.
286 //
287 struct SignedIntType : public Type {
288   SignedIntType(const std::string &Name, PrimitiveID id) : Type(Name, id) {}
289
290   // isSigned - Return whether a numeric type is signed.
291   virtual bool isSigned() const { return 1; }
292
293   // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
294   // virtual function invocation.
295   //
296   virtual bool isInteger() const { return 1; }
297 };
298
299 struct UnsignedIntType : public Type {
300   UnsignedIntType(const std::string &N, PrimitiveID id) : Type(N, id) {}
301
302   // isUnsigned - Return whether a numeric type is signed.
303   virtual bool isUnsigned() const { return 1; }
304
305   // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
306   // virtual function invocation.
307   //
308   virtual bool isInteger() const { return 1; }
309 };
310
311 struct OtherType : public Type {
312   OtherType(const std::string &N, PrimitiveID id) : Type(N, id) {}
313 };
314
315 static struct TypeType : public Type {
316   TypeType() : Type("type", TypeTyID) {}
317 } TheTypeTy;   // Implement the type that is global.
318
319
320 //===----------------------------------------------------------------------===//
321 //                           Static 'Type' data
322 //===----------------------------------------------------------------------===//
323
324 static OtherType       TheVoidTy  ("void"  , Type::VoidTyID);
325 static OtherType       TheBoolTy  ("bool"  , Type::BoolTyID);
326 static SignedIntType   TheSByteTy ("sbyte" , Type::SByteTyID);
327 static UnsignedIntType TheUByteTy ("ubyte" , Type::UByteTyID);
328 static SignedIntType   TheShortTy ("short" , Type::ShortTyID);
329 static UnsignedIntType TheUShortTy("ushort", Type::UShortTyID);
330 static SignedIntType   TheIntTy   ("int"   , Type::IntTyID); 
331 static UnsignedIntType TheUIntTy  ("uint"  , Type::UIntTyID);
332 static SignedIntType   TheLongTy  ("long"  , Type::LongTyID);
333 static UnsignedIntType TheULongTy ("ulong" , Type::ULongTyID);
334 static OtherType       TheFloatTy ("float" , Type::FloatTyID);
335 static OtherType       TheDoubleTy("double", Type::DoubleTyID);
336 static OtherType       TheLabelTy ("label" , Type::LabelTyID);
337
338 Type *Type::VoidTy   = &TheVoidTy;
339 Type *Type::BoolTy   = &TheBoolTy;
340 Type *Type::SByteTy  = &TheSByteTy;
341 Type *Type::UByteTy  = &TheUByteTy;
342 Type *Type::ShortTy  = &TheShortTy;
343 Type *Type::UShortTy = &TheUShortTy;
344 Type *Type::IntTy    = &TheIntTy;
345 Type *Type::UIntTy   = &TheUIntTy;
346 Type *Type::LongTy   = &TheLongTy;
347 Type *Type::ULongTy  = &TheULongTy;
348 Type *Type::FloatTy  = &TheFloatTy;
349 Type *Type::DoubleTy = &TheDoubleTy;
350 Type *Type::TypeTy   = &TheTypeTy;
351 Type *Type::LabelTy  = &TheLabelTy;
352
353
354 //===----------------------------------------------------------------------===//
355 //                          Derived Type Constructors
356 //===----------------------------------------------------------------------===//
357
358 FunctionType::FunctionType(const Type *Result,
359                            const std::vector<const Type*> &Params, 
360                            bool IsVarArgs) : DerivedType(FunctionTyID), 
361                                              isVarArgs(IsVarArgs) {
362   bool isAbstract = Result->isAbstract();
363   ContainedTys.reserve(Params.size()+1);
364   ContainedTys.push_back(PATypeHandle(Result, this));
365
366   for (unsigned i = 0; i != Params.size(); ++i) {
367     ContainedTys.push_back(PATypeHandle(Params[i], this));
368     isAbstract |= Params[i]->isAbstract();
369   }
370
371   // Calculate whether or not this type is abstract
372   setAbstract(isAbstract);
373 }
374
375 StructType::StructType(const std::vector<const Type*> &Types)
376   : CompositeType(StructTyID) {
377   ContainedTys.reserve(Types.size());
378   bool isAbstract = false;
379   for (unsigned i = 0; i < Types.size(); ++i) {
380     assert(Types[i] != Type::VoidTy && "Void type in method prototype!!");
381     ContainedTys.push_back(PATypeHandle(Types[i], this));
382     isAbstract |= Types[i]->isAbstract();
383   }
384
385   // Calculate whether or not this type is abstract
386   setAbstract(isAbstract);
387 }
388
389 ArrayType::ArrayType(const Type *ElType, unsigned NumEl)
390   : SequentialType(ArrayTyID, ElType) {
391   NumElements = NumEl;
392
393   // Calculate whether or not this type is abstract
394   setAbstract(ElType->isAbstract());
395 }
396
397 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
398   // Calculate whether or not this type is abstract
399   setAbstract(E->isAbstract());
400 }
401
402 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
403   setAbstract(true);
404 #ifdef DEBUG_MERGE_TYPES
405   std::cerr << "Derived new type: " << *this << "\n";
406 #endif
407 }
408
409 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
410 // another (more concrete) type, we must eliminate all references to other
411 // types, to avoid some circular reference problems.
412 void DerivedType::dropAllTypeUses() {
413   if (!ContainedTys.empty()) {
414     while (ContainedTys.size() > 1)
415       ContainedTys.pop_back();
416     
417     // The type must stay abstract.  To do this, we insert a pointer to a type
418     // that will never get resolved, thus will always be abstract.
419     static Type *AlwaysOpaqueTy = OpaqueType::get();
420     static PATypeHolder Holder(AlwaysOpaqueTy);
421     ContainedTys[0] = AlwaysOpaqueTy;
422   }
423 }
424
425 // isTypeAbstract - This is a recursive function that walks a type hierarchy
426 // calculating whether or not a type is abstract.  Worst case it will have to do
427 // a lot of traversing if you have some whacko opaque types, but in most cases,
428 // it will do some simple stuff when it hits non-abstract types that aren't
429 // recursive.
430 //
431 bool Type::isTypeAbstract() {
432   if (!isAbstract())                           // Base case for the recursion
433     return false;                              // Primitive = leaf type
434   
435   if (isa<OpaqueType>(this))                   // Base case for the recursion
436     return true;                               // This whole type is abstract!
437
438   // We have to guard against recursion.  To do this, we temporarily mark this
439   // type as concrete, so that if we get back to here recursively we will think
440   // it's not abstract, and thus not scan it again.
441   setAbstract(false);
442
443   // Scan all of the sub-types.  If any of them are abstract, than so is this
444   // one!
445   for (Type::subtype_iterator I = subtype_begin(), E = subtype_end();
446        I != E; ++I)
447     if (const_cast<Type*>(I->get())->isTypeAbstract()) {
448       setAbstract(true);        // Restore the abstract bit.
449       return true;              // This type is abstract if subtype is abstract!
450     }
451   
452   // Restore the abstract bit.
453   setAbstract(true);
454
455   // Nothing looks abstract here...
456   return false;
457 }
458
459
460 //===----------------------------------------------------------------------===//
461 //                      Type Structural Equality Testing
462 //===----------------------------------------------------------------------===//
463
464 // TypesEqual - Two types are considered structurally equal if they have the
465 // same "shape": Every level and element of the types have identical primitive
466 // ID's, and the graphs have the same edges/nodes in them.  Nodes do not have to
467 // be pointer equals to be equivalent though.  This uses an optimistic algorithm
468 // that assumes that two graphs are the same until proven otherwise.
469 //
470 static bool TypesEqual(const Type *Ty, const Type *Ty2,
471                        std::map<const Type *, const Type *> &EqTypes) {
472   if (Ty == Ty2) return true;
473   if (Ty->getPrimitiveID() != Ty2->getPrimitiveID()) return false;
474   if (isa<OpaqueType>(Ty))
475     return false;  // Two unequal opaque types are never equal
476
477   std::map<const Type*, const Type*>::iterator It = EqTypes.lower_bound(Ty);
478   if (It != EqTypes.end() && It->first == Ty)
479     return It->second == Ty2;    // Looping back on a type, check for equality
480
481   // Otherwise, add the mapping to the table to make sure we don't get
482   // recursion on the types...
483   EqTypes.insert(It, std::make_pair(Ty, Ty2));
484
485   // Two really annoying special cases that breaks an otherwise nice simple
486   // algorithm is the fact that arraytypes have sizes that differentiates types,
487   // and that function types can be varargs or not.  Consider this now.
488   //
489   if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
490     return TypesEqual(PTy->getElementType(),
491                       cast<PointerType>(Ty2)->getElementType(), EqTypes);
492   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
493     const StructType *STy2 = cast<StructType>(Ty2);
494     if (STy->getNumElements() != STy2->getNumElements()) return false;
495     for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
496       if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
497         return false;
498     return true;
499   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
500     const ArrayType *ATy2 = cast<ArrayType>(Ty2);
501     return ATy->getNumElements() == ATy2->getNumElements() &&
502            TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
503   } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
504     const FunctionType *FTy2 = cast<FunctionType>(Ty2);
505     if (FTy->isVarArg() != FTy2->isVarArg() ||
506         FTy->getNumParams() != FTy2->getNumParams() ||
507         !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
508       return false;
509     for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i)
510       if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
511         return false;
512     return true;
513   } else {
514     assert(0 && "Unknown derived type!");
515     return false;
516   }
517 }
518
519 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
520   std::map<const Type *, const Type *> EqTypes;
521   return TypesEqual(Ty, Ty2, EqTypes);
522 }
523
524 // TypeHasCycleThrough - Return true there is a path from CurTy to TargetTy in
525 // the type graph.  We know that Ty is an abstract type, so if we ever reach a
526 // non-abstract type, we know that we don't need to search the subgraph.
527 static bool TypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
528                                 std::set<const Type*> &VisitedTypes) {
529   if (TargetTy == CurTy) return true;
530   if (!CurTy->isAbstract()) return false;
531
532   std::set<const Type*>::iterator VTI = VisitedTypes.lower_bound(CurTy);
533   if (VTI != VisitedTypes.end() && *VTI == CurTy)
534     return false;
535   VisitedTypes.insert(VTI, CurTy);
536
537   for (Type::subtype_iterator I = CurTy->subtype_begin(),
538          E = CurTy->subtype_end(); I != E; ++I)
539     if (TypeHasCycleThrough(TargetTy, *I, VisitedTypes))
540       return true;
541   return false;
542 }
543
544
545 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
546 /// back to itself.
547 static bool TypeHasCycleThroughItself(const Type *Ty) {
548   assert(Ty->isAbstract() && "This code assumes that Ty was abstract!");
549   std::set<const Type*> VisitedTypes;
550   for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
551        I != E; ++I)
552     if (TypeHasCycleThrough(Ty, *I, VisitedTypes))
553       return true;
554   return false;
555 }
556
557
558 //===----------------------------------------------------------------------===//
559 //                       Derived Type Factory Functions
560 //===----------------------------------------------------------------------===//
561
562 // TypeMap - Make sure that only one instance of a particular type may be
563 // created on any given run of the compiler... note that this involves updating
564 // our map if an abstract type gets refined somehow.
565 //
566 namespace llvm {
567 template<class ValType, class TypeClass>
568 class TypeMap {
569   std::map<ValType, PATypeHolder> Map;
570
571   /// TypesByHash - Keep track of each type by its structure hash value.
572   ///
573   std::multimap<unsigned, PATypeHolder> TypesByHash;
574 public:
575   typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
576   ~TypeMap() { print("ON EXIT"); }
577
578   inline TypeClass *get(const ValType &V) {
579     iterator I = Map.find(V);
580     return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
581   }
582
583   inline void add(const ValType &V, TypeClass *Ty) {
584     Map.insert(std::make_pair(V, Ty));
585
586     // If this type has a cycle, remember it.
587     TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
588     print("add");
589   }
590
591   void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
592     std::multimap<unsigned, PATypeHolder>::iterator I = 
593       TypesByHash.lower_bound(Hash);
594     while (I->second != Ty) {
595       ++I;
596       assert(I != TypesByHash.end() && I->first == Hash);
597     }
598     TypesByHash.erase(I);
599   }
600
601   /// finishRefinement - This method is called after we have updated an existing
602   /// type with its new components.  We must now either merge the type away with
603   /// some other type or reinstall it in the map with it's new configuration.
604   /// The specified iterator tells us what the type USED to look like.
605   void finishRefinement(TypeClass *Ty, const DerivedType *OldType,
606                         const Type *NewType) {
607     assert((Ty->isAbstract() || !OldType->isAbstract()) &&
608            "Refining a non-abstract type!");
609 #ifdef DEBUG_MERGE_TYPES
610     std::cerr << "refineAbstractTy(" << (void*)OldType << "[" << *OldType
611               << "], " << (void*)NewType << " [" << *NewType << "])\n";
612 #endif
613
614     // Make a temporary type holder for the type so that it doesn't disappear on
615     // us when we erase the entry from the map.
616     PATypeHolder TyHolder = Ty;
617
618     // The old record is now out-of-date, because one of the children has been
619     // updated.  Remove the obsolete entry from the map.
620     Map.erase(ValType::get(Ty));
621
622     // Remember the structural hash for the type before we start hacking on it,
623     // in case we need it later.  Also, check to see if the type HAD a cycle
624     // through it, if so, we know it will when we hack on it.
625     unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
626
627     // Find the type element we are refining... and change it now!
628     for (unsigned i = 0, e = Ty->ContainedTys.size(); i != e; ++i)
629       if (Ty->ContainedTys[i] == OldType) {
630         Ty->ContainedTys[i].removeUserFromConcrete();
631         Ty->ContainedTys[i] = NewType;
632       }
633
634     unsigned TypeHash = ValType::hashTypeStructure(Ty);
635     
636     // If there are no cycles going through this node, we can do a simple,
637     // efficient lookup in the map, instead of an inefficient nasty linear
638     // lookup.
639     bool TypeHasCycle = Ty->isAbstract() && TypeHasCycleThroughItself(Ty);
640     if (!TypeHasCycle) {
641       iterator I = Map.find(ValType::get(Ty));
642       if (I != Map.end()) {
643         // We already have this type in the table.  Get rid of the newly refined
644         // type.
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         RemoveFromTypesByHash(TypeHash, Ty);
650         Ty->refineAbstractTypeTo(NewTy);
651         return;
652       }
653       
654     } else {
655       // Now we check to see if there is an existing entry in the table which is
656       // structurally identical to the newly refined type.  If so, this type
657       // gets refined to the pre-existing type.
658       //
659       std::multimap<unsigned, PATypeHolder>::iterator I,E, Entry;
660       tie(I, E) = TypesByHash.equal_range(TypeHash);
661       Entry = E;
662       for (; I != E; ++I) {
663         if (I->second != Ty) {
664           if (TypesEqual(Ty, I->second)) {
665             assert(Ty->isAbstract() && "Replacing a non-abstract type?");
666             TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
667             
668             if (Entry == E) {
669               // Find the location of Ty in the TypesByHash structure.
670               while (I->second != Ty) {
671                 ++I;
672                 assert(I != E && "Structure doesn't contain type??");
673               }
674               Entry = I;
675             }
676
677             TypesByHash.erase(Entry);
678             Ty->refineAbstractTypeTo(NewTy);
679             return;
680           }
681         } else {
682           // Remember the position of 
683           Entry = I;
684         }
685       }
686     }
687
688     // If we succeeded, we need to insert the type into the cycletypes table.
689     // There are several cases here, depending on whether the original type
690     // had the same hash code and was itself cyclic.
691     if (TypeHash != OldTypeHash) {
692       RemoveFromTypesByHash(OldTypeHash, Ty);
693       TypesByHash.insert(std::make_pair(TypeHash, Ty));
694     }
695
696     // If there is no existing type of the same structure, we reinsert an
697     // updated record into the map.
698     Map.insert(std::make_pair(ValType::get(Ty), Ty));
699
700     // If the type is currently thought to be abstract, rescan all of our
701     // subtypes to see if the type has just become concrete!
702     if (Ty->isAbstract()) {
703       Ty->setAbstract(Ty->isTypeAbstract());
704
705       // If the type just became concrete, notify all users!
706       if (!Ty->isAbstract())
707         Ty->notifyUsesThatTypeBecameConcrete();
708     }
709   }
710   
711   void print(const char *Arg) const {
712 #ifdef DEBUG_MERGE_TYPES
713     std::cerr << "TypeMap<>::" << Arg << " table contents:\n";
714     unsigned i = 0;
715     for (typename std::map<ValType, PATypeHolder>::const_iterator I
716            = Map.begin(), E = Map.end(); I != E; ++I)
717       std::cerr << " " << (++i) << ". " << (void*)I->second.get() << " " 
718                 << *I->second.get() << "\n";
719 #endif
720   }
721
722   void dump() const { print("dump output"); }
723 };
724 }
725
726
727 //===----------------------------------------------------------------------===//
728 // Function Type Factory and Value Class...
729 //
730
731 // FunctionValType - Define a class to hold the key that goes into the TypeMap
732 //
733 namespace llvm {
734 class FunctionValType {
735   const Type *RetTy;
736   std::vector<const Type*> ArgTypes;
737   bool isVarArg;
738 public:
739   FunctionValType(const Type *ret, const std::vector<const Type*> &args,
740                   bool IVA) : RetTy(ret), isVarArg(IVA) {
741     for (unsigned i = 0; i < args.size(); ++i)
742       ArgTypes.push_back(args[i]);
743   }
744
745   static FunctionValType get(const FunctionType *FT);
746
747   static unsigned hashTypeStructure(const FunctionType *FT) {
748     return FT->getNumParams()*2+FT->isVarArg();
749   }
750
751   // Subclass should override this... to update self as usual
752   void doRefinement(const DerivedType *OldType, const Type *NewType) {
753     if (RetTy == OldType) RetTy = NewType;
754     for (unsigned i = 0, e = ArgTypes.size(); i != e; ++i)
755       if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
756   }
757
758   inline bool operator<(const FunctionValType &MTV) const {
759     if (RetTy < MTV.RetTy) return true;
760     if (RetTy > MTV.RetTy) return false;
761
762     if (ArgTypes < MTV.ArgTypes) return true;
763     return ArgTypes == MTV.ArgTypes && isVarArg < MTV.isVarArg;
764   }
765 };
766 }
767
768 // Define the actual map itself now...
769 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
770
771 FunctionValType FunctionValType::get(const FunctionType *FT) {
772   // Build up a FunctionValType
773   std::vector<const Type *> ParamTypes;
774   ParamTypes.reserve(FT->getNumParams());
775   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
776     ParamTypes.push_back(FT->getParamType(i));
777   return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
778 }
779
780
781 // FunctionType::get - The factory function for the FunctionType class...
782 FunctionType *FunctionType::get(const Type *ReturnType, 
783                                 const std::vector<const Type*> &Params,
784                                 bool isVarArg) {
785   FunctionValType VT(ReturnType, Params, isVarArg);
786   FunctionType *MT = FunctionTypes.get(VT);
787   if (MT) return MT;
788
789   FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
790
791 #ifdef DEBUG_MERGE_TYPES
792   std::cerr << "Derived new type: " << MT << "\n";
793 #endif
794   return MT;
795 }
796
797 //===----------------------------------------------------------------------===//
798 // Array Type Factory...
799 //
800 namespace llvm {
801 class ArrayValType {
802   const Type *ValTy;
803   unsigned Size;
804 public:
805   ArrayValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
806
807   static ArrayValType get(const ArrayType *AT) {
808     return ArrayValType(AT->getElementType(), AT->getNumElements());
809   }
810
811   static unsigned hashTypeStructure(const ArrayType *AT) {
812     return AT->getNumElements();
813   }
814
815   // Subclass should override this... to update self as usual
816   void doRefinement(const DerivedType *OldType, const Type *NewType) {
817     assert(ValTy == OldType);
818     ValTy = NewType;
819   }
820
821   inline bool operator<(const ArrayValType &MTV) const {
822     if (Size < MTV.Size) return true;
823     return Size == MTV.Size && ValTy < MTV.ValTy;
824   }
825 };
826 }
827 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
828
829
830 ArrayType *ArrayType::get(const Type *ElementType, unsigned NumElements) {
831   assert(ElementType && "Can't get array of null types!");
832
833   ArrayValType AVT(ElementType, NumElements);
834   ArrayType *AT = ArrayTypes.get(AVT);
835   if (AT) return AT;           // Found a match, return it!
836
837   // Value not found.  Derive a new type!
838   ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
839
840 #ifdef DEBUG_MERGE_TYPES
841   std::cerr << "Derived new type: " << *AT << "\n";
842 #endif
843   return AT;
844 }
845
846 //===----------------------------------------------------------------------===//
847 // Struct Type Factory...
848 //
849
850 namespace llvm {
851 // StructValType - Define a class to hold the key that goes into the TypeMap
852 //
853 class StructValType {
854   std::vector<const Type*> ElTypes;
855 public:
856   StructValType(const std::vector<const Type*> &args) : ElTypes(args) {}
857
858   static StructValType get(const StructType *ST) {
859     std::vector<const Type *> ElTypes;
860     ElTypes.reserve(ST->getNumElements());
861     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
862       ElTypes.push_back(ST->getElementType(i));
863     
864     return StructValType(ElTypes);
865   }
866
867   static unsigned hashTypeStructure(const StructType *ST) {
868     return ST->getNumElements();
869   }
870
871   // Subclass should override this... to update self as usual
872   void doRefinement(const DerivedType *OldType, const Type *NewType) {
873     for (unsigned i = 0; i < ElTypes.size(); ++i)
874       if (ElTypes[i] == OldType) ElTypes[i] = NewType;
875   }
876
877   inline bool operator<(const StructValType &STV) const {
878     return ElTypes < STV.ElTypes;
879   }
880 };
881 }
882
883 static TypeMap<StructValType, StructType> StructTypes;
884
885 StructType *StructType::get(const std::vector<const Type*> &ETypes) {
886   StructValType STV(ETypes);
887   StructType *ST = StructTypes.get(STV);
888   if (ST) return ST;
889
890   // Value not found.  Derive a new type!
891   StructTypes.add(STV, ST = new StructType(ETypes));
892
893 #ifdef DEBUG_MERGE_TYPES
894   std::cerr << "Derived new type: " << *ST << "\n";
895 #endif
896   return ST;
897 }
898
899
900
901 //===----------------------------------------------------------------------===//
902 // Pointer Type Factory...
903 //
904
905 // PointerValType - Define a class to hold the key that goes into the TypeMap
906 //
907 namespace llvm {
908 class PointerValType {
909   const Type *ValTy;
910 public:
911   PointerValType(const Type *val) : ValTy(val) {}
912
913   static PointerValType get(const PointerType *PT) {
914     return PointerValType(PT->getElementType());
915   }
916
917   static unsigned hashTypeStructure(const PointerType *PT) {
918     return 0;
919   }
920
921   // Subclass should override this... to update self as usual
922   void doRefinement(const DerivedType *OldType, const Type *NewType) {
923     assert(ValTy == OldType);
924     ValTy = NewType;
925   }
926
927   bool operator<(const PointerValType &MTV) const {
928     return ValTy < MTV.ValTy;
929   }
930 };
931 }
932
933 static TypeMap<PointerValType, PointerType> PointerTypes;
934
935 PointerType *PointerType::get(const Type *ValueType) {
936   assert(ValueType && "Can't get a pointer to <null> type!");
937   PointerValType PVT(ValueType);
938
939   PointerType *PT = PointerTypes.get(PVT);
940   if (PT) return PT;
941
942   // Value not found.  Derive a new type!
943   PointerTypes.add(PVT, PT = new PointerType(ValueType));
944
945 #ifdef DEBUG_MERGE_TYPES
946   std::cerr << "Derived new type: " << *PT << "\n";
947 #endif
948   return PT;
949 }
950
951
952 //===----------------------------------------------------------------------===//
953 //                     Derived Type Refinement Functions
954 //===----------------------------------------------------------------------===//
955
956 // removeAbstractTypeUser - Notify an abstract type that a user of the class
957 // no longer has a handle to the type.  This function is called primarily by
958 // the PATypeHandle class.  When there are no users of the abstract type, it
959 // is annihilated, because there is no way to get a reference to it ever again.
960 //
961 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
962   // Search from back to front because we will notify users from back to
963   // front.  Also, it is likely that there will be a stack like behavior to
964   // users that register and unregister users.
965   //
966   unsigned i;
967   for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
968     assert(i != 0 && "AbstractTypeUser not in user list!");
969
970   --i;  // Convert to be in range 0 <= i < size()
971   assert(i < AbstractTypeUsers.size() && "Index out of range!");  // Wraparound?
972
973   AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
974       
975 #ifdef DEBUG_MERGE_TYPES
976   std::cerr << "  remAbstractTypeUser[" << (void*)this << ", "
977             << *this << "][" << i << "] User = " << U << "\n";
978 #endif
979     
980   if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
981 #ifdef DEBUG_MERGE_TYPES
982     std::cerr << "DELETEing unused abstract type: <" << *this
983               << ">[" << (void*)this << "]" << "\n";
984 #endif
985     delete this;                  // No users of this abstract type!
986   }
987 }
988
989
990 // refineAbstractTypeTo - This function is used to when it is discovered that
991 // the 'this' abstract type is actually equivalent to the NewType specified.
992 // This causes all users of 'this' to switch to reference the more concrete type
993 // NewType and for 'this' to be deleted.
994 //
995 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
996   assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
997   assert(this != NewType && "Can't refine to myself!");
998   assert(ForwardType == 0 && "This type has already been refined!");
999
1000   // The descriptions may be out of date.  Conservatively clear them all!
1001   AbstractTypeDescriptions.clear();
1002
1003 #ifdef DEBUG_MERGE_TYPES
1004   std::cerr << "REFINING abstract type [" << (void*)this << " "
1005             << *this << "] to [" << (void*)NewType << " "
1006             << *NewType << "]!\n";
1007 #endif
1008
1009   // Make sure to put the type to be refined to into a holder so that if IT gets
1010   // refined, that we will not continue using a dead reference...
1011   //
1012   PATypeHolder NewTy(NewType);
1013
1014   // Any PATypeHolders referring to this type will now automatically forward to
1015   // the type we are resolved to.
1016   ForwardType = NewType;
1017   if (NewType->isAbstract())
1018     cast<DerivedType>(NewType)->addRef();
1019
1020   // Add a self use of the current type so that we don't delete ourself until
1021   // after the function exits.
1022   //
1023   PATypeHolder CurrentTy(this);
1024
1025   // To make the situation simpler, we ask the subclass to remove this type from
1026   // the type map, and to replace any type uses with uses of non-abstract types.
1027   // This dramatically limits the amount of recursive type trouble we can find
1028   // ourselves in.
1029   dropAllTypeUses();
1030
1031   // Iterate over all of the uses of this type, invoking callback.  Each user
1032   // should remove itself from our use list automatically.  We have to check to
1033   // make sure that NewTy doesn't _become_ 'this'.  If it does, resolving types
1034   // will not cause users to drop off of the use list.  If we resolve to ourself
1035   // we succeed!
1036   //
1037   while (!AbstractTypeUsers.empty() && NewTy != this) {
1038     AbstractTypeUser *User = AbstractTypeUsers.back();
1039
1040     unsigned OldSize = AbstractTypeUsers.size();
1041 #ifdef DEBUG_MERGE_TYPES
1042     std::cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
1043               << "] of abstract type [" << (void*)this << " "
1044               << *this << "] to [" << (void*)NewTy.get() << " "
1045               << *NewTy << "]!\n";
1046 #endif
1047     User->refineAbstractType(this, NewTy);
1048
1049     assert(AbstractTypeUsers.size() != OldSize &&
1050            "AbsTyUser did not remove self from user list!");
1051   }
1052
1053   // If we were successful removing all users from the type, 'this' will be
1054   // deleted when the last PATypeHolder is destroyed or updated from this type.
1055   // This may occur on exit of this function, as the CurrentTy object is
1056   // destroyed.
1057 }
1058
1059 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1060 // the current type has transitioned from being abstract to being concrete.
1061 //
1062 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1063 #ifdef DEBUG_MERGE_TYPES
1064   std::cerr << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1065 #endif
1066
1067   unsigned OldSize = AbstractTypeUsers.size();
1068   while (!AbstractTypeUsers.empty()) {
1069     AbstractTypeUser *ATU = AbstractTypeUsers.back();
1070     ATU->typeBecameConcrete(this);
1071
1072     assert(AbstractTypeUsers.size() < OldSize-- &&
1073            "AbstractTypeUser did not remove itself from the use list!");
1074   }
1075 }
1076   
1077
1078
1079
1080 // refineAbstractType - Called when a contained type is found to be more
1081 // concrete - this could potentially change us from an abstract type to a
1082 // concrete type.
1083 //
1084 void FunctionType::refineAbstractType(const DerivedType *OldType,
1085                                       const Type *NewType) {
1086   FunctionTypes.finishRefinement(this, OldType, NewType);
1087 }
1088
1089 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1090   refineAbstractType(AbsTy, AbsTy);
1091 }
1092
1093
1094 // refineAbstractType - Called when a contained type is found to be more
1095 // concrete - this could potentially change us from an abstract type to a
1096 // concrete type.
1097 //
1098 void ArrayType::refineAbstractType(const DerivedType *OldType,
1099                                    const Type *NewType) {
1100   ArrayTypes.finishRefinement(this, OldType, NewType);
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   StructTypes.finishRefinement(this, OldType, NewType);
1115 }
1116
1117 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1118   refineAbstractType(AbsTy, AbsTy);
1119 }
1120
1121 // refineAbstractType - Called when a contained type is found to be more
1122 // concrete - this could potentially change us from an abstract type to a
1123 // concrete type.
1124 //
1125 void PointerType::refineAbstractType(const DerivedType *OldType,
1126                                      const Type *NewType) {
1127   PointerTypes.finishRefinement(this, OldType, NewType);
1128 }
1129
1130 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1131   refineAbstractType(AbsTy, AbsTy);
1132 }