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