3c1a67f3a1c90e26a57e1304453db8e608ce409a
[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 "LLVMContextImpl.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Constants.h"
17 #include "llvm/Assembly/Writer.h"
18 #include "llvm/LLVMContext.h"
19 #include "llvm/Metadata.h"
20 #include "llvm/ADT/DepthFirstIterator.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/SCCIterator.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/System/Mutex.h"
31 #include "llvm/System/RWMutex.h"
32 #include "llvm/System/Threading.h"
33 #include <algorithm>
34 #include <cstdarg>
35 using namespace llvm;
36
37 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
38 // created and later destroyed, all in an effort to make sure that there is only
39 // a single canonical version of a type.
40 //
41 // #define DEBUG_MERGE_TYPES 1
42
43 AbstractTypeUser::~AbstractTypeUser() {}
44
45
46 //===----------------------------------------------------------------------===//
47 //                         Type Class Implementation
48 //===----------------------------------------------------------------------===//
49
50 // Lock used for guarding access to the type maps.
51 static ManagedStatic<sys::SmartMutex<true> > TypeMapLock;
52
53 // Recursive lock used for guarding access to AbstractTypeUsers.
54 // NOTE: The true template parameter means this will no-op when we're not in
55 // multithreaded mode.
56 static ManagedStatic<sys::SmartMutex<true> > AbstractTypeUsersLock;
57
58 // Concrete/Abstract TypeDescriptions - We lazily calculate type descriptions
59 // for types as they are needed.  Because resolution of types must invalidate
60 // all of the abstract type descriptions, we keep them in a seperate map to make
61 // this easy.
62 static ManagedStatic<TypePrinting> ConcreteTypeDescriptions;
63 static ManagedStatic<TypePrinting> 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       static_cast<const FunctionType*>(this)->FunctionType::~FunctionType();
88     else
89       static_cast<const StructType*>(this)->StructType::~StructType();
90
91     // Finally, remove the memory as an array deallocation of the chars it was
92     // constructed from.
93     operator delete(const_cast<Type *>(this));
94
95     return;
96   }
97
98   // For all the other type subclasses, there is either no contained types or 
99   // just one (all Sequentials). For Sequentials, the PATypeHandle is not
100   // allocated past the type object, its included directly in the SequentialType
101   // class. This means we can safely just do "normal" delete of this object and
102   // all the destructors that need to run will be run.
103   delete this; 
104 }
105
106 const Type *Type::getPrimitiveType(TypeID IDNumber) {
107   switch (IDNumber) {
108   case VoidTyID      : return VoidTy;
109   case FloatTyID     : return FloatTy;
110   case DoubleTyID    : return DoubleTy;
111   case X86_FP80TyID  : return X86_FP80Ty;
112   case FP128TyID     : return FP128Ty;
113   case PPC_FP128TyID : return PPC_FP128Ty;
114   case LabelTyID     : return LabelTy;
115   case MetadataTyID  : return MetadataTy;
116   default:
117     return 0;
118   }
119 }
120
121 const Type *Type::getVAArgsPromotedType() const {
122   if (ID == IntegerTyID && getSubclassData() < 32)
123     return Type::Int32Ty;
124   else if (ID == FloatTyID)
125     return Type::DoubleTy;
126   else
127     return this;
128 }
129
130 /// getScalarType - If this is a vector type, return the element type,
131 /// otherwise return this.
132 const Type *Type::getScalarType() const {
133   if (const VectorType *VTy = dyn_cast<VectorType>(this))
134     return VTy->getElementType();
135   return this;
136 }
137
138 /// isIntOrIntVector - Return true if this is an integer type or a vector of
139 /// integer types.
140 ///
141 bool Type::isIntOrIntVector() const {
142   if (isInteger())
143     return true;
144   if (ID != Type::VectorTyID) return false;
145   
146   return cast<VectorType>(this)->getElementType()->isInteger();
147 }
148
149 /// isFPOrFPVector - Return true if this is a FP type or a vector of FP types.
150 ///
151 bool Type::isFPOrFPVector() const {
152   if (ID == Type::FloatTyID || ID == Type::DoubleTyID || 
153       ID == Type::FP128TyID || ID == Type::X86_FP80TyID || 
154       ID == Type::PPC_FP128TyID)
155     return true;
156   if (ID != Type::VectorTyID) return false;
157   
158   return cast<VectorType>(this)->getElementType()->isFloatingPoint();
159 }
160
161 // canLosslesslyBitCastTo - Return true if this type can be converted to
162 // 'Ty' without any reinterpretation of bits.  For example, i8* to i32*.
163 //
164 bool Type::canLosslesslyBitCastTo(const Type *Ty) const {
165   // Identity cast means no change so return true
166   if (this == Ty) 
167     return true;
168   
169   // They are not convertible unless they are at least first class types
170   if (!this->isFirstClassType() || !Ty->isFirstClassType())
171     return false;
172
173   // Vector -> Vector conversions are always lossless if the two vector types
174   // have the same size, otherwise not.
175   if (const VectorType *thisPTy = dyn_cast<VectorType>(this))
176     if (const VectorType *thatPTy = dyn_cast<VectorType>(Ty))
177       return thisPTy->getBitWidth() == thatPTy->getBitWidth();
178
179   // At this point we have only various mismatches of the first class types
180   // remaining and ptr->ptr. Just select the lossless conversions. Everything
181   // else is not lossless.
182   if (isa<PointerType>(this))
183     return isa<PointerType>(Ty);
184   return false;  // Other types have no identity values
185 }
186
187 unsigned Type::getPrimitiveSizeInBits() const {
188   switch (getTypeID()) {
189   case Type::FloatTyID: return 32;
190   case Type::DoubleTyID: return 64;
191   case Type::X86_FP80TyID: return 80;
192   case Type::FP128TyID: return 128;
193   case Type::PPC_FP128TyID: return 128;
194   case Type::IntegerTyID: return cast<IntegerType>(this)->getBitWidth();
195   case Type::VectorTyID:  return cast<VectorType>(this)->getBitWidth();
196   default: return 0;
197   }
198 }
199
200 /// getScalarSizeInBits - If this is a vector type, return the
201 /// getPrimitiveSizeInBits value for the element type. Otherwise return the
202 /// getPrimitiveSizeInBits value for this type.
203 unsigned Type::getScalarSizeInBits() const {
204   return getScalarType()->getPrimitiveSizeInBits();
205 }
206
207 /// getFPMantissaWidth - Return the width of the mantissa of this type.  This
208 /// is only valid on floating point types.  If the FP type does not
209 /// have a stable mantissa (e.g. ppc long double), this method returns -1.
210 int Type::getFPMantissaWidth() const {
211   if (const VectorType *VTy = dyn_cast<VectorType>(this))
212     return VTy->getElementType()->getFPMantissaWidth();
213   assert(isFloatingPoint() && "Not a floating point type!");
214   if (ID == FloatTyID) return 24;
215   if (ID == DoubleTyID) return 53;
216   if (ID == X86_FP80TyID) return 64;
217   if (ID == FP128TyID) return 113;
218   assert(ID == PPC_FP128TyID && "unknown fp type");
219   return -1;
220 }
221
222 /// isSizedDerivedType - Derived types like structures and arrays are sized
223 /// iff all of the members of the type are sized as well.  Since asking for
224 /// their size is relatively uncommon, move this operation out of line.
225 bool Type::isSizedDerivedType() const {
226   if (isa<IntegerType>(this))
227     return true;
228
229   if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
230     return ATy->getElementType()->isSized();
231
232   if (const VectorType *PTy = dyn_cast<VectorType>(this))
233     return PTy->getElementType()->isSized();
234
235   if (!isa<StructType>(this)) 
236     return false;
237
238   // Okay, our struct is sized if all of the elements are...
239   for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I)
240     if (!(*I)->isSized()) 
241       return false;
242
243   return true;
244 }
245
246 /// getForwardedTypeInternal - This method is used to implement the union-find
247 /// algorithm for when a type is being forwarded to another type.
248 const Type *Type::getForwardedTypeInternal() const {
249   assert(ForwardType && "This type is not being forwarded to another type!");
250
251   // Check to see if the forwarded type has been forwarded on.  If so, collapse
252   // the forwarding links.
253   const Type *RealForwardedType = ForwardType->getForwardedType();
254   if (!RealForwardedType)
255     return ForwardType;  // No it's not forwarded again
256
257   // Yes, it is forwarded again.  First thing, add the reference to the new
258   // forward type.
259   if (RealForwardedType->isAbstract())
260     cast<DerivedType>(RealForwardedType)->addRef();
261
262   // Now drop the old reference.  This could cause ForwardType to get deleted.
263   cast<DerivedType>(ForwardType)->dropRef();
264
265   // Return the updated type.
266   ForwardType = RealForwardedType;
267   return ForwardType;
268 }
269
270 void Type::refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
271   llvm_unreachable("Attempting to refine a derived type!");
272 }
273 void Type::typeBecameConcrete(const DerivedType *AbsTy) {
274   llvm_unreachable("DerivedType is already a concrete type!");
275 }
276
277
278 std::string Type::getDescription() const {
279   TypePrinting &Map =
280     isAbstract() ? *AbstractTypeDescriptions : *ConcreteTypeDescriptions;
281   
282   std::string DescStr;
283   raw_string_ostream DescOS(DescStr);
284   Map.print(this, DescOS);
285   return DescOS.str();
286 }
287
288
289 bool StructType::indexValid(const Value *V) const {
290   // Structure indexes require 32-bit integer constants.
291   if (V->getType() == Type::Int32Ty)
292     if (const ConstantInt *CU = dyn_cast<ConstantInt>(V))
293       return indexValid(CU->getZExtValue());
294   return false;
295 }
296
297 bool StructType::indexValid(unsigned V) const {
298   return V < NumContainedTys;
299 }
300
301 // getTypeAtIndex - Given an index value into the type, return the type of the
302 // element.  For a structure type, this must be a constant value...
303 //
304 const Type *StructType::getTypeAtIndex(const Value *V) const {
305   unsigned Idx = (unsigned)cast<ConstantInt>(V)->getZExtValue();
306   return getTypeAtIndex(Idx);
307 }
308
309 const Type *StructType::getTypeAtIndex(unsigned Idx) const {
310   assert(indexValid(Idx) && "Invalid structure index!");
311   return ContainedTys[Idx];
312 }
313
314 //===----------------------------------------------------------------------===//
315 //                          Primitive 'Type' data
316 //===----------------------------------------------------------------------===//
317
318 const Type *Type::VoidTy       = new Type(Type::VoidTyID);
319 const Type *Type::FloatTy      = new Type(Type::FloatTyID);
320 const Type *Type::DoubleTy     = new Type(Type::DoubleTyID);
321 const Type *Type::X86_FP80Ty   = new Type(Type::X86_FP80TyID);
322 const Type *Type::FP128Ty      = new Type(Type::FP128TyID);
323 const Type *Type::PPC_FP128Ty  = new Type(Type::PPC_FP128TyID);
324 const Type *Type::LabelTy      = new Type(Type::LabelTyID);
325 const Type *Type::MetadataTy   = new Type(Type::MetadataTyID);
326
327 namespace {
328   struct BuiltinIntegerType : public IntegerType {
329     explicit BuiltinIntegerType(unsigned W) : IntegerType(W) {}
330   };
331 }
332 const IntegerType *Type::Int1Ty  = new BuiltinIntegerType(1);
333 const IntegerType *Type::Int8Ty  = new BuiltinIntegerType(8);
334 const IntegerType *Type::Int16Ty = new BuiltinIntegerType(16);
335 const IntegerType *Type::Int32Ty = new BuiltinIntegerType(32);
336 const IntegerType *Type::Int64Ty = new BuiltinIntegerType(64);
337
338 //===----------------------------------------------------------------------===//
339 //                          Derived Type Constructors
340 //===----------------------------------------------------------------------===//
341
342 /// isValidReturnType - Return true if the specified type is valid as a return
343 /// type.
344 bool FunctionType::isValidReturnType(const Type *RetTy) {
345   if (RetTy->isFirstClassType()) {
346     if (const PointerType *PTy = dyn_cast<PointerType>(RetTy))
347       return PTy->getElementType() != Type::MetadataTy;
348     return true;
349   }
350   if (RetTy == Type::VoidTy || RetTy == Type::MetadataTy ||
351       isa<OpaqueType>(RetTy))
352     return true;
353   
354   // If this is a multiple return case, verify that each return is a first class
355   // value and that there is at least one value.
356   const StructType *SRetTy = dyn_cast<StructType>(RetTy);
357   if (SRetTy == 0 || SRetTy->getNumElements() == 0)
358     return false;
359   
360   for (unsigned i = 0, e = SRetTy->getNumElements(); i != e; ++i)
361     if (!SRetTy->getElementType(i)->isFirstClassType())
362       return false;
363   return true;
364 }
365
366 /// isValidArgumentType - Return true if the specified type is valid as an
367 /// argument type.
368 bool FunctionType::isValidArgumentType(const Type *ArgTy) {
369   if ((!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy)) ||
370       (isa<PointerType>(ArgTy) &&
371        cast<PointerType>(ArgTy)->getElementType() == Type::MetadataTy))
372     return false;
373
374   return true;
375 }
376
377 FunctionType::FunctionType(const Type *Result,
378                            const std::vector<const Type*> &Params,
379                            bool IsVarArgs)
380   : DerivedType(FunctionTyID), isVarArgs(IsVarArgs) {
381   ContainedTys = reinterpret_cast<PATypeHandle*>(this+1);
382   NumContainedTys = Params.size() + 1; // + 1 for result type
383   assert(isValidReturnType(Result) && "invalid return type for function");
384
385
386   bool isAbstract = Result->isAbstract();
387   new (&ContainedTys[0]) PATypeHandle(Result, this);
388
389   for (unsigned i = 0; i != Params.size(); ++i) {
390     assert(isValidArgumentType(Params[i]) &&
391            "Not a valid type for function argument!");
392     new (&ContainedTys[i+1]) PATypeHandle(Params[i], this);
393     isAbstract |= Params[i]->isAbstract();
394   }
395
396   // Calculate whether or not this type is abstract
397   setAbstract(isAbstract);
398 }
399
400 StructType::StructType(const std::vector<const Type*> &Types, bool isPacked)
401   : CompositeType(StructTyID) {
402   ContainedTys = reinterpret_cast<PATypeHandle*>(this + 1);
403   NumContainedTys = Types.size();
404   setSubclassData(isPacked);
405   bool isAbstract = false;
406   for (unsigned i = 0; i < Types.size(); ++i) {
407     assert(Types[i] && "<null> type for structure field!");
408     assert(isValidElementType(Types[i]) &&
409            "Invalid type for structure element!");
410     new (&ContainedTys[i]) PATypeHandle(Types[i], this);
411     isAbstract |= Types[i]->isAbstract();
412   }
413
414   // Calculate whether or not this type is abstract
415   setAbstract(isAbstract);
416 }
417
418 ArrayType::ArrayType(const Type *ElType, uint64_t NumEl)
419   : SequentialType(ArrayTyID, ElType) {
420   NumElements = NumEl;
421
422   // Calculate whether or not this type is abstract
423   setAbstract(ElType->isAbstract());
424 }
425
426 VectorType::VectorType(const Type *ElType, unsigned NumEl)
427   : SequentialType(VectorTyID, ElType) {
428   NumElements = NumEl;
429   setAbstract(ElType->isAbstract());
430   assert(NumEl > 0 && "NumEl of a VectorType must be greater than 0");
431   assert(isValidElementType(ElType) &&
432          "Elements of a VectorType must be a primitive type");
433
434 }
435
436
437 PointerType::PointerType(const Type *E, unsigned AddrSpace)
438   : SequentialType(PointerTyID, E) {
439   AddressSpace = AddrSpace;
440   // Calculate whether or not this type is abstract
441   setAbstract(E->isAbstract());
442 }
443
444 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
445   setAbstract(true);
446 #ifdef DEBUG_MERGE_TYPES
447   DOUT << "Derived new type: " << *this << "\n";
448 #endif
449 }
450
451 void PATypeHolder::destroy() {
452   Ty = 0;
453 }
454
455 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
456 // another (more concrete) type, we must eliminate all references to other
457 // types, to avoid some circular reference problems.
458 void DerivedType::dropAllTypeUses() {
459   if (NumContainedTys != 0) {
460     // The type must stay abstract.  To do this, we insert a pointer to a type
461     // that will never get resolved, thus will always be abstract.
462     static Type *AlwaysOpaqueTy = 0;
463     static PATypeHolder* Holder = 0;
464     Type *tmp = AlwaysOpaqueTy;
465     if (llvm_is_multithreaded()) {
466       sys::MemoryFence();
467       if (!tmp) {
468         llvm_acquire_global_lock();
469         tmp = AlwaysOpaqueTy;
470         if (!tmp) {
471           tmp = OpaqueType::get();
472           PATypeHolder* tmp2 = new PATypeHolder(AlwaysOpaqueTy);
473           sys::MemoryFence();
474           AlwaysOpaqueTy = tmp;
475           Holder = tmp2;
476         }
477       
478         llvm_release_global_lock();
479       }
480     } else {
481       AlwaysOpaqueTy = OpaqueType::get();
482       Holder = new PATypeHolder(AlwaysOpaqueTy);
483     } 
484         
485     ContainedTys[0] = AlwaysOpaqueTy;
486
487     // Change the rest of the types to be Int32Ty's.  It doesn't matter what we
488     // pick so long as it doesn't point back to this type.  We choose something
489     // concrete to avoid overhead for adding to AbstracTypeUser lists and stuff.
490     for (unsigned i = 1, e = NumContainedTys; i != e; ++i)
491       ContainedTys[i] = Type::Int32Ty;
492   }
493 }
494
495
496 namespace {
497
498 /// TypePromotionGraph and graph traits - this is designed to allow us to do
499 /// efficient SCC processing of type graphs.  This is the exact same as
500 /// GraphTraits<Type*>, except that we pretend that concrete types have no
501 /// children to avoid processing them.
502 struct TypePromotionGraph {
503   Type *Ty;
504   TypePromotionGraph(Type *T) : Ty(T) {}
505 };
506
507 }
508
509 namespace llvm {
510   template <> struct GraphTraits<TypePromotionGraph> {
511     typedef Type NodeType;
512     typedef Type::subtype_iterator ChildIteratorType;
513
514     static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
515     static inline ChildIteratorType child_begin(NodeType *N) {
516       if (N->isAbstract())
517         return N->subtype_begin();
518       else           // No need to process children of concrete types.
519         return N->subtype_end();
520     }
521     static inline ChildIteratorType child_end(NodeType *N) {
522       return N->subtype_end();
523     }
524   };
525 }
526
527
528 // PromoteAbstractToConcrete - This is a recursive function that walks a type
529 // graph calculating whether or not a type is abstract.
530 //
531 void Type::PromoteAbstractToConcrete() {
532   if (!isAbstract()) return;
533
534   scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
535   scc_iterator<TypePromotionGraph> SE = scc_end  (TypePromotionGraph(this));
536
537   for (; SI != SE; ++SI) {
538     std::vector<Type*> &SCC = *SI;
539
540     // Concrete types are leaves in the tree.  Since an SCC will either be all
541     // abstract or all concrete, we only need to check one type.
542     if (SCC[0]->isAbstract()) {
543       if (isa<OpaqueType>(SCC[0]))
544         return;     // Not going to be concrete, sorry.
545
546       // If all of the children of all of the types in this SCC are concrete,
547       // then this SCC is now concrete as well.  If not, neither this SCC, nor
548       // any parent SCCs will be concrete, so we might as well just exit.
549       for (unsigned i = 0, e = SCC.size(); i != e; ++i)
550         for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
551                E = SCC[i]->subtype_end(); CI != E; ++CI)
552           if ((*CI)->isAbstract())
553             // If the child type is in our SCC, it doesn't make the entire SCC
554             // abstract unless there is a non-SCC abstract type.
555             if (std::find(SCC.begin(), SCC.end(), *CI) == SCC.end())
556               return;               // Not going to be concrete, sorry.
557
558       // Okay, we just discovered this whole SCC is now concrete, mark it as
559       // such!
560       for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
561         assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
562
563         SCC[i]->setAbstract(false);
564       }
565
566       for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
567         assert(!SCC[i]->isAbstract() && "Concrete type became abstract?");
568         // The type just became concrete, notify all users!
569         cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
570       }
571     }
572   }
573 }
574
575
576 //===----------------------------------------------------------------------===//
577 //                      Type Structural Equality Testing
578 //===----------------------------------------------------------------------===//
579
580 // TypesEqual - Two types are considered structurally equal if they have the
581 // same "shape": Every level and element of the types have identical primitive
582 // ID's, and the graphs have the same edges/nodes in them.  Nodes do not have to
583 // be pointer equals to be equivalent though.  This uses an optimistic algorithm
584 // that assumes that two graphs are the same until proven otherwise.
585 //
586 static bool TypesEqual(const Type *Ty, const Type *Ty2,
587                        std::map<const Type *, const Type *> &EqTypes) {
588   if (Ty == Ty2) return true;
589   if (Ty->getTypeID() != Ty2->getTypeID()) return false;
590   if (isa<OpaqueType>(Ty))
591     return false;  // Two unequal opaque types are never equal
592
593   std::map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
594   if (It != EqTypes.end())
595     return It->second == Ty2;    // Looping back on a type, check for equality
596
597   // Otherwise, add the mapping to the table to make sure we don't get
598   // recursion on the types...
599   EqTypes.insert(It, std::make_pair(Ty, Ty2));
600
601   // Two really annoying special cases that breaks an otherwise nice simple
602   // algorithm is the fact that arraytypes have sizes that differentiates types,
603   // and that function types can be varargs or not.  Consider this now.
604   //
605   if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
606     const IntegerType *ITy2 = cast<IntegerType>(Ty2);
607     return ITy->getBitWidth() == ITy2->getBitWidth();
608   } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
609     const PointerType *PTy2 = cast<PointerType>(Ty2);
610     return PTy->getAddressSpace() == PTy2->getAddressSpace() &&
611            TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
612   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
613     const StructType *STy2 = cast<StructType>(Ty2);
614     if (STy->getNumElements() != STy2->getNumElements()) return false;
615     if (STy->isPacked() != STy2->isPacked()) return false;
616     for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
617       if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
618         return false;
619     return true;
620   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
621     const ArrayType *ATy2 = cast<ArrayType>(Ty2);
622     return ATy->getNumElements() == ATy2->getNumElements() &&
623            TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
624   } else if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
625     const VectorType *PTy2 = cast<VectorType>(Ty2);
626     return PTy->getNumElements() == PTy2->getNumElements() &&
627            TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
628   } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
629     const FunctionType *FTy2 = cast<FunctionType>(Ty2);
630     if (FTy->isVarArg() != FTy2->isVarArg() ||
631         FTy->getNumParams() != FTy2->getNumParams() ||
632         !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
633       return false;
634     for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i) {
635       if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
636         return false;
637     }
638     return true;
639   } else {
640     llvm_unreachable("Unknown derived type!");
641     return false;
642   }
643 }
644
645 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
646   std::map<const Type *, const Type *> EqTypes;
647   return TypesEqual(Ty, Ty2, EqTypes);
648 }
649
650 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
651 // TargetTy in the type graph.  We know that Ty is an abstract type, so if we
652 // ever reach a non-abstract type, we know that we don't need to search the
653 // subgraph.
654 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
655                                 SmallPtrSet<const Type*, 128> &VisitedTypes) {
656   if (TargetTy == CurTy) return true;
657   if (!CurTy->isAbstract()) return false;
658
659   if (!VisitedTypes.insert(CurTy))
660     return false;  // Already been here.
661
662   for (Type::subtype_iterator I = CurTy->subtype_begin(),
663        E = CurTy->subtype_end(); I != E; ++I)
664     if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
665       return true;
666   return false;
667 }
668
669 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
670                                 SmallPtrSet<const Type*, 128> &VisitedTypes) {
671   if (TargetTy == CurTy) return true;
672
673   if (!VisitedTypes.insert(CurTy))
674     return false;  // Already been here.
675
676   for (Type::subtype_iterator I = CurTy->subtype_begin(),
677        E = CurTy->subtype_end(); I != E; ++I)
678     if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
679       return true;
680   return false;
681 }
682
683 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
684 /// back to itself.
685 static bool TypeHasCycleThroughItself(const Type *Ty) {
686   SmallPtrSet<const Type*, 128> VisitedTypes;
687
688   if (Ty->isAbstract()) {  // Optimized case for abstract types.
689     for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
690          I != E; ++I)
691       if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
692         return true;
693   } else {
694     for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
695          I != E; ++I)
696       if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
697         return true;
698   }
699   return false;
700 }
701
702 //===----------------------------------------------------------------------===//
703 // Function Type Factory and Value Class...
704 //
705
706 static ManagedStatic<TypeMap<IntegerValType, IntegerType> > IntegerTypes;
707
708 const IntegerType *IntegerType::get(unsigned NumBits) {
709   assert(NumBits >= MIN_INT_BITS && "bitwidth too small");
710   assert(NumBits <= MAX_INT_BITS && "bitwidth too large");
711
712   // Check for the built-in integer types
713   switch (NumBits) {
714     case  1: return cast<IntegerType>(Type::Int1Ty);
715     case  8: return cast<IntegerType>(Type::Int8Ty);
716     case 16: return cast<IntegerType>(Type::Int16Ty);
717     case 32: return cast<IntegerType>(Type::Int32Ty);
718     case 64: return cast<IntegerType>(Type::Int64Ty);
719     default: 
720       break;
721   }
722   
723   IntegerValType IVT(NumBits);
724   IntegerType *ITy = 0;
725   
726   // First, see if the type is already in the table, for which
727   // a reader lock suffices.
728   sys::SmartScopedLock<true> L(*TypeMapLock);
729   ITy = IntegerTypes->get(IVT);
730     
731   if (!ITy) {
732     // Value not found.  Derive a new type!
733     ITy = new IntegerType(NumBits);
734     IntegerTypes->add(IVT, ITy);
735   }
736 #ifdef DEBUG_MERGE_TYPES
737   DOUT << "Derived new type: " << *ITy << "\n";
738 #endif
739   return ITy;
740 }
741
742 bool IntegerType::isPowerOf2ByteWidth() const {
743   unsigned BitWidth = getBitWidth();
744   return (BitWidth > 7) && isPowerOf2_32(BitWidth);
745 }
746
747 APInt IntegerType::getMask() const {
748   return APInt::getAllOnesValue(getBitWidth());
749 }
750
751 // Define the actual map itself now...
752 static ManagedStatic<TypeMap<FunctionValType, FunctionType> > FunctionTypes;
753
754 FunctionValType FunctionValType::get(const FunctionType *FT) {
755   // Build up a FunctionValType
756   std::vector<const Type *> ParamTypes;
757   ParamTypes.reserve(FT->getNumParams());
758   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
759     ParamTypes.push_back(FT->getParamType(i));
760   return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
761 }
762
763
764 // FunctionType::get - The factory function for the FunctionType class...
765 FunctionType *FunctionType::get(const Type *ReturnType,
766                                 const std::vector<const Type*> &Params,
767                                 bool isVarArg) {
768   FunctionValType VT(ReturnType, Params, isVarArg);
769   FunctionType *FT = 0;
770   
771   sys::SmartScopedLock<true> L(*TypeMapLock);
772   FT = FunctionTypes->get(VT);
773   
774   if (!FT) {
775     FT = (FunctionType*) operator new(sizeof(FunctionType) +
776                                     sizeof(PATypeHandle)*(Params.size()+1));
777     new (FT) FunctionType(ReturnType, Params, isVarArg);
778     FunctionTypes->add(VT, FT);
779   }
780
781 #ifdef DEBUG_MERGE_TYPES
782   DOUT << "Derived new type: " << FT << "\n";
783 #endif
784   return FT;
785 }
786
787 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
788   assert(ElementType && "Can't get array of <null> types!");
789   assert(isValidElementType(ElementType) && "Invalid type for array element!");
790
791   ArrayValType AVT(ElementType, NumElements);
792   ArrayType *AT = 0;
793
794   LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
795   
796   sys::SmartScopedLock<true> L(*TypeMapLock);
797   AT = pImpl->ArrayTypes.get(AVT);
798       
799   if (!AT) {
800     // Value not found.  Derive a new type!
801     pImpl->ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
802   }
803 #ifdef DEBUG_MERGE_TYPES
804   DOUT << "Derived new type: " << *AT << "\n";
805 #endif
806   return AT;
807 }
808
809 bool ArrayType::isValidElementType(const Type *ElemTy) {
810   if (ElemTy == Type::VoidTy || ElemTy == Type::LabelTy ||
811       ElemTy == Type::MetadataTy)
812     return false;
813
814   if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
815     if (PTy->getElementType() == Type::MetadataTy)
816       return false;
817
818   return true;
819 }
820
821 static ManagedStatic<TypeMap<VectorValType, VectorType> > VectorTypes;
822
823 VectorType *VectorType::get(const Type *ElementType, unsigned NumElements) {
824   assert(ElementType && "Can't get vector of <null> types!");
825
826   VectorValType PVT(ElementType, NumElements);
827   VectorType *PT = 0;
828   
829   sys::SmartScopedLock<true> L(*TypeMapLock);
830   PT = VectorTypes->get(PVT);
831     
832   if (!PT) {
833     VectorTypes->add(PVT, PT = new VectorType(ElementType, NumElements));
834   }
835 #ifdef DEBUG_MERGE_TYPES
836   DOUT << "Derived new type: " << *PT << "\n";
837 #endif
838   return PT;
839 }
840
841 bool VectorType::isValidElementType(const Type *ElemTy) {
842   if (ElemTy->isInteger() || ElemTy->isFloatingPoint() ||
843       isa<OpaqueType>(ElemTy))
844     return true;
845
846   return false;
847 }
848
849 //===----------------------------------------------------------------------===//
850 // Struct Type Factory...
851 //
852
853 static ManagedStatic<TypeMap<StructValType, StructType> > StructTypes;
854
855 StructType *StructType::get(const std::vector<const Type*> &ETypes, 
856                             bool isPacked) {
857   StructValType STV(ETypes, isPacked);
858   StructType *ST = 0;
859   
860   sys::SmartScopedLock<true> L(*TypeMapLock);
861   ST = StructTypes->get(STV);
862     
863   if (!ST) {
864     // Value not found.  Derive a new type!
865     ST = (StructType*) operator new(sizeof(StructType) +
866                                     sizeof(PATypeHandle) * ETypes.size());
867     new (ST) StructType(ETypes, isPacked);
868     StructTypes->add(STV, ST);
869   }
870 #ifdef DEBUG_MERGE_TYPES
871   DOUT << "Derived new type: " << *ST << "\n";
872 #endif
873   return ST;
874 }
875
876 StructType *StructType::get(const Type *type, ...) {
877   va_list ap;
878   std::vector<const llvm::Type*> StructFields;
879   va_start(ap, type);
880   while (type) {
881     StructFields.push_back(type);
882     type = va_arg(ap, llvm::Type*);
883   }
884   return llvm::StructType::get(StructFields);
885 }
886
887 bool StructType::isValidElementType(const Type *ElemTy) {
888   if (ElemTy == Type::VoidTy || ElemTy == Type::LabelTy ||
889       ElemTy == Type::MetadataTy)
890     return false;
891
892   if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
893     if (PTy->getElementType() == Type::MetadataTy)
894       return false;
895
896   return true;
897 }
898
899
900 //===----------------------------------------------------------------------===//
901 // Pointer Type Factory...
902 //
903
904 static ManagedStatic<TypeMap<PointerValType, PointerType> > PointerTypes;
905
906 PointerType *PointerType::get(const Type *ValueType, unsigned AddressSpace) {
907   assert(ValueType && "Can't get a pointer to <null> type!");
908   assert(ValueType != Type::VoidTy &&
909          "Pointer to void is not valid, use i8* instead!");
910   assert(isValidElementType(ValueType) && "Invalid type for pointer element!");
911   PointerValType PVT(ValueType, AddressSpace);
912
913   PointerType *PT = 0;
914   
915   sys::SmartScopedLock<true> L(*TypeMapLock);
916   PT = PointerTypes->get(PVT);
917   
918   if (!PT) {
919     // Value not found.  Derive a new type!
920     PointerTypes->add(PVT, PT = new PointerType(ValueType, AddressSpace));
921   }
922 #ifdef DEBUG_MERGE_TYPES
923   DOUT << "Derived new type: " << *PT << "\n";
924 #endif
925   return PT;
926 }
927
928 PointerType *Type::getPointerTo(unsigned addrs) const {
929   return PointerType::get(this, addrs);
930 }
931
932 bool PointerType::isValidElementType(const Type *ElemTy) {
933   if (ElemTy == Type::VoidTy || ElemTy == Type::LabelTy)
934     return false;
935
936   if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
937     if (PTy->getElementType() == Type::MetadataTy)
938       return false;
939
940   return true;
941 }
942
943
944 //===----------------------------------------------------------------------===//
945 //                     Derived Type Refinement Functions
946 //===----------------------------------------------------------------------===//
947
948 // addAbstractTypeUser - Notify an abstract type that there is a new user of
949 // it.  This function is called primarily by the PATypeHandle class.
950 void Type::addAbstractTypeUser(AbstractTypeUser *U) const {
951   assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
952   AbstractTypeUsersLock->acquire();
953   AbstractTypeUsers.push_back(U);
954   AbstractTypeUsersLock->release();
955 }
956
957
958 // removeAbstractTypeUser - Notify an abstract type that a user of the class
959 // no longer has a handle to the type.  This function is called primarily by
960 // the PATypeHandle class.  When there are no users of the abstract type, it
961 // is annihilated, because there is no way to get a reference to it ever again.
962 //
963 void Type::removeAbstractTypeUser(AbstractTypeUser *U) const {
964   AbstractTypeUsersLock->acquire();
965   
966   // Search from back to front because we will notify users from back to
967   // front.  Also, it is likely that there will be a stack like behavior to
968   // users that register and unregister users.
969   //
970   unsigned i;
971   for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
972     assert(i != 0 && "AbstractTypeUser not in user list!");
973
974   --i;  // Convert to be in range 0 <= i < size()
975   assert(i < AbstractTypeUsers.size() && "Index out of range!");  // Wraparound?
976
977   AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
978
979 #ifdef DEBUG_MERGE_TYPES
980   DOUT << "  remAbstractTypeUser[" << (void*)this << ", "
981        << *this << "][" << i << "] User = " << U << "\n";
982 #endif
983
984   if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
985 #ifdef DEBUG_MERGE_TYPES
986     DOUT << "DELETEing unused abstract type: <" << *this
987          << ">[" << (void*)this << "]" << "\n";
988 #endif
989   
990   this->destroy();
991   }
992   
993   AbstractTypeUsersLock->release();
994 }
995
996 // unlockedRefineAbstractTypeTo - This function is used when it is discovered
997 // that the 'this' abstract type is actually equivalent to the NewType
998 // specified. This causes all users of 'this' to switch to reference the more 
999 // concrete type NewType and for 'this' to be deleted.  Only used for internal
1000 // callers.
1001 //
1002 void DerivedType::unlockedRefineAbstractTypeTo(const Type *NewType) {
1003   assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1004   assert(this != NewType && "Can't refine to myself!");
1005   assert(ForwardType == 0 && "This type has already been refined!");
1006
1007   // The descriptions may be out of date.  Conservatively clear them all!
1008   if (AbstractTypeDescriptions.isConstructed())
1009     AbstractTypeDescriptions->clear();
1010
1011 #ifdef DEBUG_MERGE_TYPES
1012   DOUT << "REFINING abstract type [" << (void*)this << " "
1013        << *this << "] to [" << (void*)NewType << " "
1014        << *NewType << "]!\n";
1015 #endif
1016
1017   // Make sure to put the type to be refined to into a holder so that if IT gets
1018   // refined, that we will not continue using a dead reference...
1019   //
1020   PATypeHolder NewTy(NewType);
1021   // Any PATypeHolders referring to this type will now automatically forward o
1022   // the type we are resolved to.
1023   ForwardType = NewType;
1024   if (NewType->isAbstract())
1025     cast<DerivedType>(NewType)->addRef();
1026
1027   // Add a self use of the current type so that we don't delete ourself until
1028   // after the function exits.
1029   //
1030   PATypeHolder CurrentTy(this);
1031
1032   // To make the situation simpler, we ask the subclass to remove this type from
1033   // the type map, and to replace any type uses with uses of non-abstract types.
1034   // This dramatically limits the amount of recursive type trouble we can find
1035   // ourselves in.
1036   dropAllTypeUses();
1037
1038   // Iterate over all of the uses of this type, invoking callback.  Each user
1039   // should remove itself from our use list automatically.  We have to check to
1040   // make sure that NewTy doesn't _become_ 'this'.  If it does, resolving types
1041   // will not cause users to drop off of the use list.  If we resolve to ourself
1042   // we succeed!
1043   //
1044   AbstractTypeUsersLock->acquire();
1045   while (!AbstractTypeUsers.empty() && NewTy != this) {
1046     AbstractTypeUser *User = AbstractTypeUsers.back();
1047
1048     unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1049 #ifdef DEBUG_MERGE_TYPES
1050     DOUT << " REFINING user " << OldSize-1 << "[" << (void*)User
1051          << "] of abstract type [" << (void*)this << " "
1052          << *this << "] to [" << (void*)NewTy.get() << " "
1053          << *NewTy << "]!\n";
1054 #endif
1055     User->refineAbstractType(this, NewTy);
1056
1057     assert(AbstractTypeUsers.size() != OldSize &&
1058            "AbsTyUser did not remove self from user list!");
1059   }
1060   AbstractTypeUsersLock->release();
1061
1062   // If we were successful removing all users from the type, 'this' will be
1063   // deleted when the last PATypeHolder is destroyed or updated from this type.
1064   // This may occur on exit of this function, as the CurrentTy object is
1065   // destroyed.
1066 }
1067
1068 // refineAbstractTypeTo - This function is used by external callers to notify
1069 // us that this abstract type is equivalent to another type.
1070 //
1071 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1072   // All recursive calls will go through unlockedRefineAbstractTypeTo,
1073   // to avoid deadlock problems.
1074   sys::SmartScopedLock<true> L(*TypeMapLock);
1075   unlockedRefineAbstractTypeTo(NewType);
1076 }
1077
1078 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1079 // the current type has transitioned from being abstract to being concrete.
1080 //
1081 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1082 #ifdef DEBUG_MERGE_TYPES
1083   DOUT << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1084 #endif
1085
1086   AbstractTypeUsersLock->acquire();
1087   unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1088   while (!AbstractTypeUsers.empty()) {
1089     AbstractTypeUser *ATU = AbstractTypeUsers.back();
1090     ATU->typeBecameConcrete(this);
1091
1092     assert(AbstractTypeUsers.size() < OldSize-- &&
1093            "AbstractTypeUser did not remove itself from the use list!");
1094   }
1095   AbstractTypeUsersLock->release();
1096 }
1097
1098 // refineAbstractType - Called when a contained type is found to be more
1099 // concrete - this could potentially change us from an abstract type to a
1100 // concrete type.
1101 //
1102 void FunctionType::refineAbstractType(const DerivedType *OldType,
1103                                       const Type *NewType) {
1104   FunctionTypes->RefineAbstractType(this, OldType, NewType);
1105 }
1106
1107 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1108   FunctionTypes->TypeBecameConcrete(this, AbsTy);
1109 }
1110
1111
1112 // refineAbstractType - Called when a contained type is found to be more
1113 // concrete - this could potentially change us from an abstract type to a
1114 // concrete type.
1115 //
1116 void ArrayType::refineAbstractType(const DerivedType *OldType,
1117                                    const Type *NewType) {
1118   LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1119   pImpl->ArrayTypes.RefineAbstractType(this, OldType, NewType);
1120 }
1121
1122 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1123   LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1124   pImpl->ArrayTypes.TypeBecameConcrete(this, AbsTy);
1125 }
1126
1127 // refineAbstractType - Called when a contained type is found to be more
1128 // concrete - this could potentially change us from an abstract type to a
1129 // concrete type.
1130 //
1131 void VectorType::refineAbstractType(const DerivedType *OldType,
1132                                    const Type *NewType) {
1133   VectorTypes->RefineAbstractType(this, OldType, NewType);
1134 }
1135
1136 void VectorType::typeBecameConcrete(const DerivedType *AbsTy) {
1137   VectorTypes->TypeBecameConcrete(this, AbsTy);
1138 }
1139
1140 // refineAbstractType - Called when a contained type is found to be more
1141 // concrete - this could potentially change us from an abstract type to a
1142 // concrete type.
1143 //
1144 void StructType::refineAbstractType(const DerivedType *OldType,
1145                                     const Type *NewType) {
1146   StructTypes->RefineAbstractType(this, OldType, NewType);
1147 }
1148
1149 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1150   StructTypes->TypeBecameConcrete(this, AbsTy);
1151 }
1152
1153 // refineAbstractType - Called when a contained type is found to be more
1154 // concrete - this could potentially change us from an abstract type to a
1155 // concrete type.
1156 //
1157 void PointerType::refineAbstractType(const DerivedType *OldType,
1158                                      const Type *NewType) {
1159   PointerTypes->RefineAbstractType(this, OldType, NewType);
1160 }
1161
1162 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1163   PointerTypes->TypeBecameConcrete(this, AbsTy);
1164 }
1165
1166 bool SequentialType::indexValid(const Value *V) const {
1167   if (isa<IntegerType>(V->getType())) 
1168     return true;
1169   return false;
1170 }
1171
1172 namespace llvm {
1173 std::ostream &operator<<(std::ostream &OS, const Type *T) {
1174   if (T == 0)
1175     OS << "<null> value!\n";
1176   else
1177     T->print(OS);
1178   return OS;
1179 }
1180
1181 std::ostream &operator<<(std::ostream &OS, const Type &T) {
1182   T.print(OS);
1183   return OS;
1184 }
1185
1186 raw_ostream &operator<<(raw_ostream &OS, const Type &T) {
1187   T.print(OS);
1188   return OS;
1189 }
1190 }