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