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