The noreturn GCC extension is now supported.
[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/AbstractTypeUser.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/SymbolTable.h"
17 #include "llvm/Constants.h"
18 #include "llvm/ADT/DepthFirstIterator.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/SCCIterator.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include <algorithm>
23 #include <iostream>
24 using namespace llvm;
25
26 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
27 // created and later destroyed, all in an effort to make sure that there is only
28 // a single canonical version of a type.
29 //
30 //#define DEBUG_MERGE_TYPES 1
31
32 AbstractTypeUser::~AbstractTypeUser() {}
33
34 //===----------------------------------------------------------------------===//
35 //                         Type Class Implementation
36 //===----------------------------------------------------------------------===//
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, TypeID id )
46   : RefCount(0), ForwardType(0) {
47   if (!name.empty())
48     ConcreteTypeDescriptions[this] = name;
49   ID = id;
50   Abstract = false;
51 }
52
53 const Type *Type::getPrimitiveType(TypeID IDNumber) {
54   switch (IDNumber) {
55   case VoidTyID  : return VoidTy;
56   case BoolTyID  : return BoolTy;
57   case UByteTyID : return UByteTy;
58   case SByteTyID : return SByteTy;
59   case UShortTyID: return UShortTy;
60   case ShortTyID : return ShortTy;
61   case UIntTyID  : return UIntTy;
62   case IntTyID   : return IntTy;
63   case ULongTyID : return ULongTy;
64   case LongTyID  : return LongTy;
65   case FloatTyID : return FloatTy;
66   case DoubleTyID: return DoubleTy;
67   case LabelTyID : return LabelTy;
68   default:
69     return 0;
70   }
71 }
72
73 // isLosslesslyConvertibleTo - Return true if this type can be converted to
74 // 'Ty' without any reinterpretation of bits.  For example, uint to int.
75 //
76 bool Type::isLosslesslyConvertibleTo(const Type *Ty) const {
77   if (this == Ty) return true;
78   if ((!isPrimitiveType()    && !isa<PointerType>(this)) ||
79       (!isa<PointerType>(Ty) && !Ty->isPrimitiveType())) return false;
80
81   if (getTypeID() == Ty->getTypeID())
82     return true;  // Handles identity cast, and cast of differing pointer types
83
84   // Now we know that they are two differing primitive or pointer types
85   switch (getTypeID()) {
86   case Type::UByteTyID:   return Ty == Type::SByteTy;
87   case Type::SByteTyID:   return Ty == Type::UByteTy;
88   case Type::UShortTyID:  return Ty == Type::ShortTy;
89   case Type::ShortTyID:   return Ty == Type::UShortTy;
90   case Type::UIntTyID:    return Ty == Type::IntTy;
91   case Type::IntTyID:     return Ty == Type::UIntTy;
92   case Type::ULongTyID:   return Ty == Type::LongTy;
93   case Type::LongTyID:    return Ty == Type::ULongTy;
94   case Type::PointerTyID: return isa<PointerType>(Ty);
95   default:
96     return false;  // Other types have no identity values
97   }
98 }
99
100 /// getUnsignedVersion - If this is an integer type, return the unsigned
101 /// variant of this type.  For example int -> uint.
102 const Type *Type::getUnsignedVersion() const {
103   switch (getTypeID()) {
104   default:
105     assert(isInteger()&&"Type::getUnsignedVersion is only valid for integers!");
106   case Type::UByteTyID:   
107   case Type::SByteTyID:   return Type::UByteTy;
108   case Type::UShortTyID:  
109   case Type::ShortTyID:   return Type::UShortTy;
110   case Type::UIntTyID:    
111   case Type::IntTyID:     return Type::UIntTy;
112   case Type::ULongTyID:   
113   case Type::LongTyID:    return Type::ULongTy;
114   }
115 }
116
117 /// getSignedVersion - If this is an integer type, return the signed variant
118 /// of this type.  For example uint -> int.
119 const Type *Type::getSignedVersion() const {
120   switch (getTypeID()) {
121   default:
122     assert(isInteger() && "Type::getSignedVersion is only valid for integers!");
123   case Type::UByteTyID:   
124   case Type::SByteTyID:   return Type::SByteTy;
125   case Type::UShortTyID:  
126   case Type::ShortTyID:   return Type::ShortTy;
127   case Type::UIntTyID:    
128   case Type::IntTyID:     return Type::IntTy;
129   case Type::ULongTyID:   
130   case Type::LongTyID:    return Type::LongTy;
131   }
132 }
133
134
135 // getPrimitiveSize - Return the basic size of this type if it is a primitive
136 // type.  These are fixed by LLVM and are not target dependent.  This will
137 // return zero if the type does not have a size or is not a primitive type.
138 //
139 unsigned Type::getPrimitiveSize() const {
140   switch (getTypeID()) {
141 #define HANDLE_PRIM_TYPE(TY,SIZE)  case TY##TyID: return SIZE;
142 #include "llvm/Type.def"
143   default: return 0;
144   }
145 }
146
147 /// isSizedDerivedType - Derived types like structures and arrays are sized
148 /// iff all of the members of the type are sized as well.  Since asking for
149 /// their size is relatively uncommon, move this operation out of line.
150 bool Type::isSizedDerivedType() const {
151   if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
152     return ATy->getElementType()->isSized();
153
154   if (const PackedType *PTy = dyn_cast<PackedType>(this))
155     return PTy->getElementType()->isSized();
156
157   if (!isa<StructType>(this)) return false;
158
159   // Okay, our struct is sized if all of the elements are...
160   for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I)
161     if (!(*I)->isSized()) return false;
162
163   return true;
164 }
165
166 /// getForwardedTypeInternal - This method is used to implement the union-find
167 /// algorithm for when a type is being forwarded to another type.
168 const Type *Type::getForwardedTypeInternal() const {
169   assert(ForwardType && "This type is not being forwarded to another type!");
170   
171   // Check to see if the forwarded type has been forwarded on.  If so, collapse
172   // the forwarding links.
173   const Type *RealForwardedType = ForwardType->getForwardedType();
174   if (!RealForwardedType)
175     return ForwardType;  // No it's not forwarded again
176
177   // Yes, it is forwarded again.  First thing, add the reference to the new
178   // forward type.
179   if (RealForwardedType->isAbstract())
180     cast<DerivedType>(RealForwardedType)->addRef();
181
182   // Now drop the old reference.  This could cause ForwardType to get deleted.
183   cast<DerivedType>(ForwardType)->dropRef();
184   
185   // Return the updated type.
186   ForwardType = RealForwardedType;
187   return ForwardType;
188 }
189
190 // getTypeDescription - This is a recursive function that walks a type hierarchy
191 // calculating the description for a type.
192 //
193 static std::string getTypeDescription(const Type *Ty,
194                                       std::vector<const Type *> &TypeStack) {
195   if (isa<OpaqueType>(Ty)) {                     // Base case for the recursion
196     std::map<const Type*, std::string>::iterator I =
197       AbstractTypeDescriptions.lower_bound(Ty);
198     if (I != AbstractTypeDescriptions.end() && I->first == Ty)
199       return I->second;
200     std::string Desc = "opaque";
201     AbstractTypeDescriptions.insert(std::make_pair(Ty, Desc));
202     return Desc;
203   }
204   
205   if (!Ty->isAbstract()) {                       // Base case for the recursion
206     std::map<const Type*, std::string>::iterator I =
207       ConcreteTypeDescriptions.find(Ty);
208     if (I != ConcreteTypeDescriptions.end()) return I->second;
209   }
210       
211   // Check to see if the Type is already on the stack...
212   unsigned Slot = 0, CurSize = TypeStack.size();
213   while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
214   
215   // This is another base case for the recursion.  In this case, we know 
216   // that we have looped back to a type that we have previously visited.
217   // Generate the appropriate upreference to handle this.
218   // 
219   if (Slot < CurSize)
220     return "\\" + utostr(CurSize-Slot);         // Here's the upreference
221
222   // Recursive case: derived types...
223   std::string Result;
224   TypeStack.push_back(Ty);    // Add us to the stack..
225       
226   switch (Ty->getTypeID()) {
227   case Type::FunctionTyID: {
228     const FunctionType *FTy = cast<FunctionType>(Ty);
229     Result = getTypeDescription(FTy->getReturnType(), TypeStack) + " (";
230     for (FunctionType::param_iterator I = FTy->param_begin(),
231            E = FTy->param_end(); I != E; ++I) {
232       if (I != FTy->param_begin())
233         Result += ", ";
234       Result += getTypeDescription(*I, TypeStack);
235     }
236     if (FTy->isVarArg()) {
237       if (FTy->getNumParams()) Result += ", ";
238       Result += "...";
239     }
240     Result += ")";
241     break;
242   }
243   case Type::StructTyID: {
244     const StructType *STy = cast<StructType>(Ty);
245     Result = "{ ";
246     for (StructType::element_iterator I = STy->element_begin(),
247            E = STy->element_end(); I != E; ++I) {
248       if (I != STy->element_begin())
249         Result += ", ";
250       Result += getTypeDescription(*I, TypeStack);
251     }
252     Result += " }";
253     break;
254   }
255   case Type::PointerTyID: {
256     const PointerType *PTy = cast<PointerType>(Ty);
257     Result = getTypeDescription(PTy->getElementType(), TypeStack) + " *";
258     break;
259   }
260   case Type::ArrayTyID: {
261     const ArrayType *ATy = cast<ArrayType>(Ty);
262     unsigned NumElements = ATy->getNumElements();
263     Result = "[";
264     Result += utostr(NumElements) + " x ";
265     Result += getTypeDescription(ATy->getElementType(), TypeStack) + "]";
266     break;
267   }
268   case Type::PackedTyID: {
269     const PackedType *PTy = cast<PackedType>(Ty);
270     unsigned NumElements = PTy->getNumElements();
271     Result = "<";
272     Result += utostr(NumElements) + " x ";
273     Result += getTypeDescription(PTy->getElementType(), TypeStack) + ">";
274     break;
275   }
276   default:
277     Result = "<error>";
278     assert(0 && "Unhandled type in getTypeDescription!");
279   }
280
281   TypeStack.pop_back();       // Remove self from stack...
282
283   return Result;
284 }
285
286
287
288 static const std::string &getOrCreateDesc(std::map<const Type*,std::string>&Map,
289                                           const Type *Ty) {
290   std::map<const Type*, std::string>::iterator I = Map.find(Ty);
291   if (I != Map.end()) return I->second;
292     
293   std::vector<const Type *> TypeStack;
294   return Map[Ty] = getTypeDescription(Ty, TypeStack);
295 }
296
297
298 const std::string &Type::getDescription() const {
299   if (isAbstract())
300     return getOrCreateDesc(AbstractTypeDescriptions, this);
301   else
302     return getOrCreateDesc(ConcreteTypeDescriptions, this);
303 }
304
305
306 bool StructType::indexValid(const Value *V) const {
307   // Structure indexes require unsigned integer constants.
308   if (V->getType() == Type::UIntTy)
309     if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(V))
310       return CU->getValue() < ContainedTys.size();
311   return false;
312 }
313
314 // getTypeAtIndex - Given an index value into the type, return the type of the
315 // element.  For a structure type, this must be a constant value...
316 //
317 const Type *StructType::getTypeAtIndex(const Value *V) const {
318   assert(indexValid(V) && "Invalid structure index!");
319   unsigned Idx = (unsigned)cast<ConstantUInt>(V)->getValue();
320   return ContainedTys[Idx];
321 }
322
323
324 //===----------------------------------------------------------------------===//
325 //                           Static 'Type' data
326 //===----------------------------------------------------------------------===//
327
328 namespace {
329   struct PrimType : public Type {
330     PrimType(const char *S, TypeID ID) : Type(S, ID) {}
331   };
332 }
333
334 static PrimType TheVoidTy  ("void"  , Type::VoidTyID);
335 static PrimType TheBoolTy  ("bool"  , Type::BoolTyID);
336 static PrimType TheSByteTy ("sbyte" , Type::SByteTyID);
337 static PrimType TheUByteTy ("ubyte" , Type::UByteTyID);
338 static PrimType TheShortTy ("short" , Type::ShortTyID);
339 static PrimType TheUShortTy("ushort", Type::UShortTyID);
340 static PrimType TheIntTy   ("int"   , Type::IntTyID);
341 static PrimType TheUIntTy  ("uint"  , Type::UIntTyID);
342 static PrimType TheLongTy  ("long"  , Type::LongTyID);
343 static PrimType TheULongTy ("ulong" , Type::ULongTyID);
344 static PrimType TheFloatTy ("float" , Type::FloatTyID);
345 static PrimType TheDoubleTy("double", Type::DoubleTyID);
346 static PrimType TheLabelTy ("label" , Type::LabelTyID);
347
348 Type *Type::VoidTy   = &TheVoidTy;
349 Type *Type::BoolTy   = &TheBoolTy;
350 Type *Type::SByteTy  = &TheSByteTy;
351 Type *Type::UByteTy  = &TheUByteTy;
352 Type *Type::ShortTy  = &TheShortTy;
353 Type *Type::UShortTy = &TheUShortTy;
354 Type *Type::IntTy    = &TheIntTy;
355 Type *Type::UIntTy   = &TheUIntTy;
356 Type *Type::LongTy   = &TheLongTy;
357 Type *Type::ULongTy  = &TheULongTy;
358 Type *Type::FloatTy  = &TheFloatTy;
359 Type *Type::DoubleTy = &TheDoubleTy;
360 Type *Type::LabelTy  = &TheLabelTy;
361
362
363 //===----------------------------------------------------------------------===//
364 //                          Derived Type Constructors
365 //===----------------------------------------------------------------------===//
366
367 FunctionType::FunctionType(const Type *Result,
368                            const std::vector<const Type*> &Params, 
369                            bool IsVarArgs) : DerivedType(FunctionTyID), 
370                                              isVarArgs(IsVarArgs) {
371   assert((Result->isFirstClassType() || Result == Type::VoidTy ||
372          isa<OpaqueType>(Result)) && 
373          "LLVM functions cannot return aggregates");
374   bool isAbstract = Result->isAbstract();
375   ContainedTys.reserve(Params.size()+1);
376   ContainedTys.push_back(PATypeHandle(Result, this));
377
378   for (unsigned i = 0; i != Params.size(); ++i) {
379     assert((Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])) &&
380            "Function arguments must be value types!");
381
382     ContainedTys.push_back(PATypeHandle(Params[i], this));
383     isAbstract |= Params[i]->isAbstract();
384   }
385
386   // Calculate whether or not this type is abstract
387   setAbstract(isAbstract);
388 }
389
390 StructType::StructType(const std::vector<const Type*> &Types)
391   : CompositeType(StructTyID) {
392   ContainedTys.reserve(Types.size());
393   bool isAbstract = false;
394   for (unsigned i = 0; i < Types.size(); ++i) {
395     assert(Types[i] != Type::VoidTy && "Void type for structure field!!");
396     ContainedTys.push_back(PATypeHandle(Types[i], this));
397     isAbstract |= Types[i]->isAbstract();
398   }
399
400   // Calculate whether or not this type is abstract
401   setAbstract(isAbstract);
402 }
403
404 ArrayType::ArrayType(const Type *ElType, unsigned NumEl)
405   : SequentialType(ArrayTyID, ElType) {
406   NumElements = NumEl;
407
408   // Calculate whether or not this type is abstract
409   setAbstract(ElType->isAbstract());
410 }
411
412 PackedType::PackedType(const Type *ElType, unsigned NumEl)
413   : SequentialType(PackedTyID, ElType) {
414   NumElements = NumEl;
415
416   assert(NumEl > 0 && "NumEl of a PackedType must be greater than 0");
417   assert((ElType->isIntegral() || ElType->isFloatingPoint()) && 
418          "Elements of a PackedType must be a primitive type");
419 }
420
421
422 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
423   // Calculate whether or not this type is abstract
424   setAbstract(E->isAbstract());
425 }
426
427 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
428   setAbstract(true);
429 #ifdef DEBUG_MERGE_TYPES
430   std::cerr << "Derived new type: " << *this << "\n";
431 #endif
432 }
433
434 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
435 // another (more concrete) type, we must eliminate all references to other
436 // types, to avoid some circular reference problems.
437 void DerivedType::dropAllTypeUses() {
438   if (!ContainedTys.empty()) {
439     while (ContainedTys.size() > 1)
440       ContainedTys.pop_back();
441     
442     // The type must stay abstract.  To do this, we insert a pointer to a type
443     // that will never get resolved, thus will always be abstract.
444     static Type *AlwaysOpaqueTy = OpaqueType::get();
445     static PATypeHolder Holder(AlwaysOpaqueTy);
446     ContainedTys[0] = AlwaysOpaqueTy;
447   }
448 }
449
450
451
452 /// TypePromotionGraph and graph traits - this is designed to allow us to do
453 /// efficient SCC processing of type graphs.  This is the exact same as
454 /// GraphTraits<Type*>, except that we pretend that concrete types have no
455 /// children to avoid processing them.
456 struct TypePromotionGraph {
457   Type *Ty;
458   TypePromotionGraph(Type *T) : Ty(T) {}
459 };
460
461 namespace llvm {
462   template <> struct GraphTraits<TypePromotionGraph> {
463     typedef Type NodeType;
464     typedef Type::subtype_iterator ChildIteratorType;
465     
466     static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
467     static inline ChildIteratorType child_begin(NodeType *N) { 
468       if (N->isAbstract())
469         return N->subtype_begin(); 
470       else           // No need to process children of concrete types.
471         return N->subtype_end(); 
472     }
473     static inline ChildIteratorType child_end(NodeType *N) { 
474       return N->subtype_end();
475     }
476   };
477 }
478
479
480 // PromoteAbstractToConcrete - This is a recursive function that walks a type
481 // graph calculating whether or not a type is abstract.
482 //
483 // This method returns true if the type is found to still be abstract.
484 //
485 void Type::PromoteAbstractToConcrete() {
486   if (!isAbstract()) return;
487
488   scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
489   scc_iterator<TypePromotionGraph> SE = scc_end  (TypePromotionGraph(this));
490
491   for (; SI != SE; ++SI) {
492     std::vector<Type*> &SCC = *SI;
493
494     // Concrete types are leaves in the tree.  Since an SCC will either be all
495     // abstract or all concrete, we only need to check one type.
496     if (SCC[0]->isAbstract()) {
497       if (isa<OpaqueType>(SCC[0]))
498         return;     // Not going to be concrete, sorry.
499
500       // If all of the children of all of the types in this SCC are concrete,
501       // then this SCC is now concrete as well.  If not, neither this SCC, nor
502       // any parent SCCs will be concrete, so we might as well just exit.
503       for (unsigned i = 0, e = SCC.size(); i != e; ++i)
504         for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
505                E = SCC[i]->subtype_end(); CI != E; ++CI)
506           if ((*CI)->isAbstract())
507             return;               // Not going to be concrete, sorry.
508       
509       // Okay, we just discovered this whole SCC is now concrete, mark it as
510       // such!
511       for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
512         assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
513         
514         SCC[i]->setAbstract(false);
515         // The type just became concrete, notify all users!
516         cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
517       }
518     }
519   }
520 }
521
522
523 //===----------------------------------------------------------------------===//
524 //                      Type Structural Equality Testing
525 //===----------------------------------------------------------------------===//
526
527 // TypesEqual - Two types are considered structurally equal if they have the
528 // same "shape": Every level and element of the types have identical primitive
529 // ID's, and the graphs have the same edges/nodes in them.  Nodes do not have to
530 // be pointer equals to be equivalent though.  This uses an optimistic algorithm
531 // that assumes that two graphs are the same until proven otherwise.
532 //
533 static bool TypesEqual(const Type *Ty, const Type *Ty2,
534                        std::map<const Type *, const Type *> &EqTypes) {
535   if (Ty == Ty2) return true;
536   if (Ty->getTypeID() != Ty2->getTypeID()) return false;
537   if (isa<OpaqueType>(Ty))
538     return false;  // Two unequal opaque types are never equal
539
540   std::map<const Type*, const Type*>::iterator It = EqTypes.lower_bound(Ty);
541   if (It != EqTypes.end() && It->first == Ty)
542     return It->second == Ty2;    // Looping back on a type, check for equality
543
544   // Otherwise, add the mapping to the table to make sure we don't get
545   // recursion on the types...
546   EqTypes.insert(It, std::make_pair(Ty, Ty2));
547
548   // Two really annoying special cases that breaks an otherwise nice simple
549   // algorithm is the fact that arraytypes have sizes that differentiates types,
550   // and that function types can be varargs or not.  Consider this now.
551   //
552   if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
553     return TypesEqual(PTy->getElementType(),
554                       cast<PointerType>(Ty2)->getElementType(), EqTypes);
555   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
556     const StructType *STy2 = cast<StructType>(Ty2);
557     if (STy->getNumElements() != STy2->getNumElements()) return false;
558     for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
559       if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
560         return false;
561     return true;
562   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
563     const ArrayType *ATy2 = cast<ArrayType>(Ty2);
564     return ATy->getNumElements() == ATy2->getNumElements() &&
565            TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
566   } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
567     const PackedType *PTy2 = cast<PackedType>(Ty2);
568     return PTy->getNumElements() == PTy2->getNumElements() &&
569            TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
570   } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
571     const FunctionType *FTy2 = cast<FunctionType>(Ty2);
572     if (FTy->isVarArg() != FTy2->isVarArg() ||
573         FTy->getNumParams() != FTy2->getNumParams() ||
574         !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
575       return false;
576     for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i)
577       if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
578         return false;
579     return true;
580   } else {
581     assert(0 && "Unknown derived type!");
582     return false;
583   }
584 }
585
586 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
587   std::map<const Type *, const Type *> EqTypes;
588   return TypesEqual(Ty, Ty2, EqTypes);
589 }
590
591 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
592 // TargetTy in the type graph.  We know that Ty is an abstract type, so if we
593 // ever reach a non-abstract type, we know that we don't need to search the
594 // subgraph.
595 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
596                                 std::set<const Type*> &VisitedTypes) {
597   if (TargetTy == CurTy) return true;
598   if (!CurTy->isAbstract()) return false;
599
600   if (!VisitedTypes.insert(CurTy).second)
601     return false;  // Already been here.
602
603   for (Type::subtype_iterator I = CurTy->subtype_begin(), 
604        E = CurTy->subtype_end(); I != E; ++I)
605     if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
606       return true;
607   return false;
608 }
609
610 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
611                                         std::set<const Type*> &VisitedTypes) {
612   if (TargetTy == CurTy) return true;
613
614   if (!VisitedTypes.insert(CurTy).second)
615     return false;  // Already been here.
616
617   for (Type::subtype_iterator I = CurTy->subtype_begin(), 
618        E = CurTy->subtype_end(); I != E; ++I)
619     if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
620       return true;
621   return false;
622 }
623
624 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
625 /// back to itself.
626 static bool TypeHasCycleThroughItself(const Type *Ty) {
627   std::set<const Type*> VisitedTypes;
628
629   if (Ty->isAbstract()) {  // Optimized case for abstract types.
630     for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end(); 
631          I != E; ++I)
632       if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
633         return true;
634   } else {
635     for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
636          I != E; ++I)
637       if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
638         return true;
639   }
640   return false;
641 }
642
643
644 //===----------------------------------------------------------------------===//
645 //                       Derived Type Factory Functions
646 //===----------------------------------------------------------------------===//
647
648 // TypeMap - Make sure that only one instance of a particular type may be
649 // created on any given run of the compiler... note that this involves updating
650 // our map if an abstract type gets refined somehow.
651 //
652 namespace llvm {
653 template<class ValType, class TypeClass>
654 class TypeMap {
655   std::map<ValType, PATypeHolder> Map;
656
657   /// TypesByHash - Keep track of types by their structure hash value.  Note
658   /// that we only keep track of types that have cycles through themselves in
659   /// this map.
660   ///
661   std::multimap<unsigned, PATypeHolder> TypesByHash;
662
663   friend void Type::clearAllTypeMaps();
664
665 private:
666   void clear(std::vector<Type *> &DerivedTypes) {
667     for (typename std::map<ValType, PATypeHolder>::iterator I = Map.begin(), 
668          E = Map.end(); I != E; ++I)
669       DerivedTypes.push_back(I->second.get());
670     TypesByHash.clear();
671     Map.clear();
672   }
673 public:
674   typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
675   ~TypeMap() { print("ON EXIT"); }
676
677   inline TypeClass *get(const ValType &V) {
678     iterator I = Map.find(V);
679     return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
680   }
681
682   inline void add(const ValType &V, TypeClass *Ty) {
683     Map.insert(std::make_pair(V, Ty));
684
685     // If this type has a cycle, remember it.
686     TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
687     print("add");
688   }
689
690   void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
691     std::multimap<unsigned, PATypeHolder>::iterator I = 
692       TypesByHash.lower_bound(Hash);
693     while (I->second != Ty) {
694       ++I;
695       assert(I != TypesByHash.end() && I->first == Hash);
696     }
697     TypesByHash.erase(I);
698   }
699
700   /// finishRefinement - This method is called after we have updated an existing
701   /// type with its new components.  We must now either merge the type away with
702   /// some other type or reinstall it in the map with it's new configuration.
703   /// The specified iterator tells us what the type USED to look like.
704   void finishRefinement(TypeClass *Ty, const DerivedType *OldType,
705                         const Type *NewType) {
706     assert((Ty->isAbstract() || !OldType->isAbstract()) &&
707            "Refining a non-abstract type!");
708 #ifdef DEBUG_MERGE_TYPES
709     std::cerr << "refineAbstractTy(" << (void*)OldType << "[" << *OldType
710               << "], " << (void*)NewType << " [" << *NewType << "])\n";
711 #endif
712
713     // Make a temporary type holder for the type so that it doesn't disappear on
714     // us when we erase the entry from the map.
715     PATypeHolder TyHolder = Ty;
716
717     // The old record is now out-of-date, because one of the children has been
718     // updated.  Remove the obsolete entry from the map.
719     Map.erase(ValType::get(Ty));
720
721     // Remember the structural hash for the type before we start hacking on it,
722     // in case we need it later.
723     unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
724
725     // Find the type element we are refining... and change it now!
726     for (unsigned i = 0, e = Ty->ContainedTys.size(); i != e; ++i)
727       if (Ty->ContainedTys[i] == OldType) {
728         Ty->ContainedTys[i].removeUserFromConcrete();
729         Ty->ContainedTys[i] = NewType;
730       }
731
732     unsigned TypeHash = ValType::hashTypeStructure(Ty);
733     
734     // If there are no cycles going through this node, we can do a simple,
735     // efficient lookup in the map, instead of an inefficient nasty linear
736     // lookup.
737     if (!Ty->isAbstract() || !TypeHasCycleThroughItself(Ty)) {
738       typename std::map<ValType, PATypeHolder>::iterator I;
739       bool Inserted;
740
741       ValType V = ValType::get(Ty);
742       tie(I, Inserted) = Map.insert(std::make_pair(V, Ty));
743       if (!Inserted) {
744         // Refined to a different type altogether?
745         RemoveFromTypesByHash(TypeHash, Ty);
746
747         // We already have this type in the table.  Get rid of the newly refined
748         // type.
749         TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
750         Ty->refineAbstractTypeTo(NewTy);
751         return;
752       }
753       
754     } else {
755       // Now we check to see if there is an existing entry in the table which is
756       // structurally identical to the newly refined type.  If so, this type
757       // gets refined to the pre-existing type.
758       //
759       std::multimap<unsigned, PATypeHolder>::iterator I, E, Entry;
760       tie(I, E) = TypesByHash.equal_range(OldTypeHash);
761       Entry = E;
762       for (; I != E; ++I) {
763         if (I->second != Ty) {
764           if (TypesEqual(Ty, I->second)) {
765             assert(Ty->isAbstract() && "Replacing a non-abstract type?");
766             TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
767             
768             if (Entry == E) {
769               // Find the location of Ty in the TypesByHash structure.
770               while (I->second != Ty) {
771                 ++I;
772                 assert(I != E && "Structure doesn't contain type??");
773               }
774               Entry = I;
775             }
776
777             TypesByHash.erase(Entry);
778             Ty->refineAbstractTypeTo(NewTy);
779             return;
780           }
781         } else {
782           // Remember the position of 
783           Entry = I;
784         }
785       }
786
787
788       // If there is no existing type of the same structure, we reinsert an
789       // updated record into the map.
790       Map.insert(std::make_pair(ValType::get(Ty), Ty));
791     }
792
793     // If the hash codes differ, update TypesByHash
794     if (TypeHash != OldTypeHash) {
795       RemoveFromTypesByHash(OldTypeHash, Ty);
796       TypesByHash.insert(std::make_pair(TypeHash, Ty));
797     }
798
799     // If the type is currently thought to be abstract, rescan all of our
800     // subtypes to see if the type has just become concrete!
801     if (Ty->isAbstract())
802       Ty->PromoteAbstractToConcrete();
803   }
804   
805   void print(const char *Arg) const {
806 #ifdef DEBUG_MERGE_TYPES
807     std::cerr << "TypeMap<>::" << Arg << " table contents:\n";
808     unsigned i = 0;
809     for (typename std::map<ValType, PATypeHolder>::const_iterator I
810            = Map.begin(), E = Map.end(); I != E; ++I)
811       std::cerr << " " << (++i) << ". " << (void*)I->second.get() << " " 
812                 << *I->second.get() << "\n";
813 #endif
814   }
815
816   void dump() const { print("dump output"); }
817 };
818 }
819
820
821 //===----------------------------------------------------------------------===//
822 // Function Type Factory and Value Class...
823 //
824
825 // FunctionValType - Define a class to hold the key that goes into the TypeMap
826 //
827 namespace llvm {
828 class FunctionValType {
829   const Type *RetTy;
830   std::vector<const Type*> ArgTypes;
831   bool isVarArg;
832 public:
833   FunctionValType(const Type *ret, const std::vector<const Type*> &args,
834                   bool IVA) : RetTy(ret), isVarArg(IVA) {
835     for (unsigned i = 0; i < args.size(); ++i)
836       ArgTypes.push_back(args[i]);
837   }
838
839   static FunctionValType get(const FunctionType *FT);
840
841   static unsigned hashTypeStructure(const FunctionType *FT) {
842     return FT->getNumParams()*2+FT->isVarArg();
843   }
844
845   // Subclass should override this... to update self as usual
846   void doRefinement(const DerivedType *OldType, const Type *NewType) {
847     if (RetTy == OldType) RetTy = NewType;
848     for (unsigned i = 0, e = ArgTypes.size(); i != e; ++i)
849       if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
850   }
851
852   inline bool operator<(const FunctionValType &MTV) const {
853     if (RetTy < MTV.RetTy) return true;
854     if (RetTy > MTV.RetTy) return false;
855
856     if (ArgTypes < MTV.ArgTypes) return true;
857     return ArgTypes == MTV.ArgTypes && isVarArg < MTV.isVarArg;
858   }
859 };
860 }
861
862 // Define the actual map itself now...
863 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
864
865 FunctionValType FunctionValType::get(const FunctionType *FT) {
866   // Build up a FunctionValType
867   std::vector<const Type *> ParamTypes;
868   ParamTypes.reserve(FT->getNumParams());
869   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
870     ParamTypes.push_back(FT->getParamType(i));
871   return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
872 }
873
874
875 // FunctionType::get - The factory function for the FunctionType class...
876 FunctionType *FunctionType::get(const Type *ReturnType, 
877                                 const std::vector<const Type*> &Params,
878                                 bool isVarArg) {
879   FunctionValType VT(ReturnType, Params, isVarArg);
880   FunctionType *MT = FunctionTypes.get(VT);
881   if (MT) return MT;
882
883   FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
884
885 #ifdef DEBUG_MERGE_TYPES
886   std::cerr << "Derived new type: " << MT << "\n";
887 #endif
888   return MT;
889 }
890
891 //===----------------------------------------------------------------------===//
892 // Array Type Factory...
893 //
894 namespace llvm {
895 class ArrayValType {
896   const Type *ValTy;
897   unsigned Size;
898 public:
899   ArrayValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
900
901   static ArrayValType get(const ArrayType *AT) {
902     return ArrayValType(AT->getElementType(), AT->getNumElements());
903   }
904
905   static unsigned hashTypeStructure(const ArrayType *AT) {
906     return AT->getNumElements();
907   }
908
909   // Subclass should override this... to update self as usual
910   void doRefinement(const DerivedType *OldType, const Type *NewType) {
911     assert(ValTy == OldType);
912     ValTy = NewType;
913   }
914
915   inline bool operator<(const ArrayValType &MTV) const {
916     if (Size < MTV.Size) return true;
917     return Size == MTV.Size && ValTy < MTV.ValTy;
918   }
919 };
920 }
921 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
922
923
924 ArrayType *ArrayType::get(const Type *ElementType, unsigned NumElements) {
925   assert(ElementType && "Can't get array of null types!");
926
927   ArrayValType AVT(ElementType, NumElements);
928   ArrayType *AT = ArrayTypes.get(AVT);
929   if (AT) return AT;           // Found a match, return it!
930
931   // Value not found.  Derive a new type!
932   ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
933
934 #ifdef DEBUG_MERGE_TYPES
935   std::cerr << "Derived new type: " << *AT << "\n";
936 #endif
937   return AT;
938 }
939
940
941 //===----------------------------------------------------------------------===//
942 // Packed Type Factory...
943 //
944 namespace llvm {
945 class PackedValType {
946   const Type *ValTy;
947   unsigned Size;
948 public:
949   PackedValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
950
951   static PackedValType get(const PackedType *PT) {
952     return PackedValType(PT->getElementType(), PT->getNumElements());
953   }
954
955   static unsigned hashTypeStructure(const PackedType *PT) {
956     return PT->getNumElements();
957   }
958
959   // Subclass should override this... to update self as usual
960   void doRefinement(const DerivedType *OldType, const Type *NewType) {
961     assert(ValTy == OldType);
962     ValTy = NewType;
963   }
964
965   inline bool operator<(const PackedValType &MTV) const {
966     if (Size < MTV.Size) return true;
967     return Size == MTV.Size && ValTy < MTV.ValTy;
968   }
969 };
970 }
971 static TypeMap<PackedValType, PackedType> PackedTypes;
972
973
974 PackedType *PackedType::get(const Type *ElementType, unsigned NumElements) {
975   assert(ElementType && "Can't get packed of null types!");
976
977   PackedValType PVT(ElementType, NumElements);
978   PackedType *PT = PackedTypes.get(PVT);
979   if (PT) return PT;           // Found a match, return it!
980
981   // Value not found.  Derive a new type!
982   PackedTypes.add(PVT, PT = new PackedType(ElementType, NumElements));
983
984 #ifdef DEBUG_MERGE_TYPES
985   std::cerr << "Derived new type: " << *PT << "\n";
986 #endif
987   return PT;
988 }
989
990 //===----------------------------------------------------------------------===//
991 // Struct Type Factory...
992 //
993
994 namespace llvm {
995 // StructValType - Define a class to hold the key that goes into the TypeMap
996 //
997 class StructValType {
998   std::vector<const Type*> ElTypes;
999 public:
1000   StructValType(const std::vector<const Type*> &args) : ElTypes(args) {}
1001
1002   static StructValType get(const StructType *ST) {
1003     std::vector<const Type *> ElTypes;
1004     ElTypes.reserve(ST->getNumElements());
1005     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
1006       ElTypes.push_back(ST->getElementType(i));
1007     
1008     return StructValType(ElTypes);
1009   }
1010
1011   static unsigned hashTypeStructure(const StructType *ST) {
1012     return ST->getNumElements();
1013   }
1014
1015   // Subclass should override this... to update self as usual
1016   void doRefinement(const DerivedType *OldType, const Type *NewType) {
1017     for (unsigned i = 0; i < ElTypes.size(); ++i)
1018       if (ElTypes[i] == OldType) ElTypes[i] = NewType;
1019   }
1020
1021   inline bool operator<(const StructValType &STV) const {
1022     return ElTypes < STV.ElTypes;
1023   }
1024 };
1025 }
1026
1027 static TypeMap<StructValType, StructType> StructTypes;
1028
1029 StructType *StructType::get(const std::vector<const Type*> &ETypes) {
1030   StructValType STV(ETypes);
1031   StructType *ST = StructTypes.get(STV);
1032   if (ST) return ST;
1033
1034   // Value not found.  Derive a new type!
1035   StructTypes.add(STV, ST = new StructType(ETypes));
1036
1037 #ifdef DEBUG_MERGE_TYPES
1038   std::cerr << "Derived new type: " << *ST << "\n";
1039 #endif
1040   return ST;
1041 }
1042
1043
1044
1045 //===----------------------------------------------------------------------===//
1046 // Pointer Type Factory...
1047 //
1048
1049 // PointerValType - Define a class to hold the key that goes into the TypeMap
1050 //
1051 namespace llvm {
1052 class PointerValType {
1053   const Type *ValTy;
1054 public:
1055   PointerValType(const Type *val) : ValTy(val) {}
1056
1057   static PointerValType get(const PointerType *PT) {
1058     return PointerValType(PT->getElementType());
1059   }
1060
1061   static unsigned hashTypeStructure(const PointerType *PT) {
1062     return 0;
1063   }
1064
1065   // Subclass should override this... to update self as usual
1066   void doRefinement(const DerivedType *OldType, const Type *NewType) {
1067     assert(ValTy == OldType);
1068     ValTy = NewType;
1069   }
1070
1071   bool operator<(const PointerValType &MTV) const {
1072     return ValTy < MTV.ValTy;
1073   }
1074 };
1075 }
1076
1077 static TypeMap<PointerValType, PointerType> PointerTypes;
1078
1079 PointerType *PointerType::get(const Type *ValueType) {
1080   assert(ValueType && "Can't get a pointer to <null> type!");
1081   PointerValType PVT(ValueType);
1082
1083   PointerType *PT = PointerTypes.get(PVT);
1084   if (PT) return PT;
1085
1086   // Value not found.  Derive a new type!
1087   PointerTypes.add(PVT, PT = new PointerType(ValueType));
1088
1089 #ifdef DEBUG_MERGE_TYPES
1090   std::cerr << "Derived new type: " << *PT << "\n";
1091 #endif
1092   return PT;
1093 }
1094
1095
1096 //===----------------------------------------------------------------------===//
1097 //                     Derived Type Refinement Functions
1098 //===----------------------------------------------------------------------===//
1099
1100 // removeAbstractTypeUser - Notify an abstract type that a user of the class
1101 // no longer has a handle to the type.  This function is called primarily by
1102 // the PATypeHandle class.  When there are no users of the abstract type, it
1103 // is annihilated, because there is no way to get a reference to it ever again.
1104 //
1105 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
1106   // Search from back to front because we will notify users from back to
1107   // front.  Also, it is likely that there will be a stack like behavior to
1108   // users that register and unregister users.
1109   //
1110   unsigned i;
1111   for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1112     assert(i != 0 && "AbstractTypeUser not in user list!");
1113
1114   --i;  // Convert to be in range 0 <= i < size()
1115   assert(i < AbstractTypeUsers.size() && "Index out of range!");  // Wraparound?
1116
1117   AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1118       
1119 #ifdef DEBUG_MERGE_TYPES
1120   std::cerr << "  remAbstractTypeUser[" << (void*)this << ", "
1121             << *this << "][" << i << "] User = " << U << "\n";
1122 #endif
1123     
1124   if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1125 #ifdef DEBUG_MERGE_TYPES
1126     std::cerr << "DELETEing unused abstract type: <" << *this
1127               << ">[" << (void*)this << "]" << "\n";
1128 #endif
1129     delete this;                  // No users of this abstract type!
1130   }
1131 }
1132
1133
1134 // refineAbstractTypeTo - This function is used to when it is discovered that
1135 // the 'this' abstract type is actually equivalent to the NewType specified.
1136 // This causes all users of 'this' to switch to reference the more concrete type
1137 // NewType and for 'this' to be deleted.
1138 //
1139 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1140   assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1141   assert(this != NewType && "Can't refine to myself!");
1142   assert(ForwardType == 0 && "This type has already been refined!");
1143
1144   // The descriptions may be out of date.  Conservatively clear them all!
1145   AbstractTypeDescriptions.clear();
1146
1147 #ifdef DEBUG_MERGE_TYPES
1148   std::cerr << "REFINING abstract type [" << (void*)this << " "
1149             << *this << "] to [" << (void*)NewType << " "
1150             << *NewType << "]!\n";
1151 #endif
1152
1153   // Make sure to put the type to be refined to into a holder so that if IT gets
1154   // refined, that we will not continue using a dead reference...
1155   //
1156   PATypeHolder NewTy(NewType);
1157
1158   // Any PATypeHolders referring to this type will now automatically forward to
1159   // the type we are resolved to.
1160   ForwardType = NewType;
1161   if (NewType->isAbstract())
1162     cast<DerivedType>(NewType)->addRef();
1163
1164   // Add a self use of the current type so that we don't delete ourself until
1165   // after the function exits.
1166   //
1167   PATypeHolder CurrentTy(this);
1168
1169   // To make the situation simpler, we ask the subclass to remove this type from
1170   // the type map, and to replace any type uses with uses of non-abstract types.
1171   // This dramatically limits the amount of recursive type trouble we can find
1172   // ourselves in.
1173   dropAllTypeUses();
1174
1175   // Iterate over all of the uses of this type, invoking callback.  Each user
1176   // should remove itself from our use list automatically.  We have to check to
1177   // make sure that NewTy doesn't _become_ 'this'.  If it does, resolving types
1178   // will not cause users to drop off of the use list.  If we resolve to ourself
1179   // we succeed!
1180   //
1181   while (!AbstractTypeUsers.empty() && NewTy != this) {
1182     AbstractTypeUser *User = AbstractTypeUsers.back();
1183
1184     unsigned OldSize = AbstractTypeUsers.size();
1185 #ifdef DEBUG_MERGE_TYPES
1186     std::cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
1187               << "] of abstract type [" << (void*)this << " "
1188               << *this << "] to [" << (void*)NewTy.get() << " "
1189               << *NewTy << "]!\n";
1190 #endif
1191     User->refineAbstractType(this, NewTy);
1192
1193     assert(AbstractTypeUsers.size() != OldSize &&
1194            "AbsTyUser did not remove self from user list!");
1195   }
1196
1197   // If we were successful removing all users from the type, 'this' will be
1198   // deleted when the last PATypeHolder is destroyed or updated from this type.
1199   // This may occur on exit of this function, as the CurrentTy object is
1200   // destroyed.
1201 }
1202
1203 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1204 // the current type has transitioned from being abstract to being concrete.
1205 //
1206 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1207 #ifdef DEBUG_MERGE_TYPES
1208   std::cerr << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1209 #endif
1210
1211   unsigned OldSize = AbstractTypeUsers.size();
1212   while (!AbstractTypeUsers.empty()) {
1213     AbstractTypeUser *ATU = AbstractTypeUsers.back();
1214     ATU->typeBecameConcrete(this);
1215
1216     assert(AbstractTypeUsers.size() < OldSize-- &&
1217            "AbstractTypeUser did not remove itself from the use list!");
1218   }
1219 }
1220   
1221
1222
1223
1224 // refineAbstractType - Called when a contained type is found to be more
1225 // concrete - this could potentially change us from an abstract type to a
1226 // concrete type.
1227 //
1228 void FunctionType::refineAbstractType(const DerivedType *OldType,
1229                                       const Type *NewType) {
1230   FunctionTypes.finishRefinement(this, OldType, NewType);
1231 }
1232
1233 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1234   refineAbstractType(AbsTy, AbsTy);
1235 }
1236
1237
1238 // refineAbstractType - Called when a contained type is found to be more
1239 // concrete - this could potentially change us from an abstract type to a
1240 // concrete type.
1241 //
1242 void ArrayType::refineAbstractType(const DerivedType *OldType,
1243                                    const Type *NewType) {
1244   ArrayTypes.finishRefinement(this, OldType, NewType);
1245 }
1246
1247 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1248   refineAbstractType(AbsTy, AbsTy);
1249 }
1250
1251 // refineAbstractType - Called when a contained type is found to be more
1252 // concrete - this could potentially change us from an abstract type to a
1253 // concrete type.
1254 //
1255 void PackedType::refineAbstractType(const DerivedType *OldType,
1256                                    const Type *NewType) {
1257   PackedTypes.finishRefinement(this, OldType, NewType);
1258 }
1259
1260 void PackedType::typeBecameConcrete(const DerivedType *AbsTy) {
1261   refineAbstractType(AbsTy, AbsTy);
1262 }
1263
1264 // refineAbstractType - Called when a contained type is found to be more
1265 // concrete - this could potentially change us from an abstract type to a
1266 // concrete type.
1267 //
1268 void StructType::refineAbstractType(const DerivedType *OldType,
1269                                     const Type *NewType) {
1270   StructTypes.finishRefinement(this, OldType, NewType);
1271 }
1272
1273 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1274   refineAbstractType(AbsTy, AbsTy);
1275 }
1276
1277 // refineAbstractType - Called when a contained type is found to be more
1278 // concrete - this could potentially change us from an abstract type to a
1279 // concrete type.
1280 //
1281 void PointerType::refineAbstractType(const DerivedType *OldType,
1282                                      const Type *NewType) {
1283   PointerTypes.finishRefinement(this, OldType, NewType);
1284 }
1285
1286 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1287   refineAbstractType(AbsTy, AbsTy);
1288 }
1289
1290 bool SequentialType::indexValid(const Value *V) const {
1291   const Type *Ty = V->getType();
1292   switch (Ty->getTypeID()) {
1293   case Type::IntTyID:
1294   case Type::UIntTyID:
1295   case Type::LongTyID:
1296   case Type::ULongTyID:
1297     return true;
1298   default:
1299     return false;
1300   }
1301 }
1302
1303 namespace llvm {
1304 std::ostream &operator<<(std::ostream &OS, const Type *T) {
1305   if (T == 0)
1306     OS << "<null> value!\n";
1307   else
1308     T->print(OS);
1309   return OS;
1310 }
1311
1312 std::ostream &operator<<(std::ostream &OS, const Type &T) {
1313   T.print(OS);
1314   return OS;
1315 }
1316 }
1317
1318 /// clearAllTypeMaps - This method frees all internal memory used by the
1319 /// type subsystem, which can be used in environments where this memory is
1320 /// otherwise reported as a leak.
1321 void Type::clearAllTypeMaps() {
1322   std::vector<Type *> DerivedTypes;
1323
1324   FunctionTypes.clear(DerivedTypes);
1325   PointerTypes.clear(DerivedTypes);
1326   StructTypes.clear(DerivedTypes);
1327   ArrayTypes.clear(DerivedTypes);
1328   PackedTypes.clear(DerivedTypes);
1329
1330   for(std::vector<Type *>::iterator I = DerivedTypes.begin(), 
1331       E = DerivedTypes.end(); I != E; ++I)
1332     (*I)->ContainedTys.clear();
1333   for(std::vector<Type *>::iterator I = DerivedTypes.begin(),
1334       E = DerivedTypes.end(); I != E; ++I)
1335     delete *I;
1336   DerivedTypes.clear();
1337 }
1338
1339 // vim: sw=2