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