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