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