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