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