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