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