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