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