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