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