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