Fix a bug in my previous change. Unfortunately this reverts most of the
[oota-llvm.git] / lib / VMCore / Type.cpp
1 //===-- Type.cpp - Implement the Type class -------------------------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Type class for the VMCore library.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/AbstractTypeUser.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/SymbolTable.h"
17 #include "llvm/Constants.h"
18 #include "llvm/ADT/DepthFirstIterator.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include <algorithm>
22 #include <iostream>
23 using namespace llvm;
24
25 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
26 // created and later destroyed, all in an effort to make sure that there is only
27 // a single canonical version of a type.
28 //
29 //#define DEBUG_MERGE_TYPES 1
30
31 AbstractTypeUser::~AbstractTypeUser() {}
32
33 //===----------------------------------------------------------------------===//
34 //                         Type Class Implementation
35 //===----------------------------------------------------------------------===//
36
37 // Concrete/Abstract TypeDescriptions - We lazily calculate type descriptions
38 // for types as they are needed.  Because resolution of types must invalidate
39 // all of the abstract type descriptions, we keep them in a seperate map to make
40 // this easy.
41 static std::map<const Type*, std::string> ConcreteTypeDescriptions;
42 static std::map<const Type*, std::string> AbstractTypeDescriptions;
43
44 Type::Type( const std::string& name, TypeID id )
45   : RefCount(0), ForwardType(0) {
46   if (!name.empty())
47     ConcreteTypeDescriptions[this] = name;
48   ID = id;
49   Abstract = false;
50 }
51
52 const Type *Type::getPrimitiveType(TypeID IDNumber) {
53   switch (IDNumber) {
54   case VoidTyID  : return VoidTy;
55   case BoolTyID  : return BoolTy;
56   case UByteTyID : return UByteTy;
57   case SByteTyID : return SByteTy;
58   case UShortTyID: return UShortTy;
59   case ShortTyID : return ShortTy;
60   case UIntTyID  : return UIntTy;
61   case IntTyID   : return IntTy;
62   case ULongTyID : return ULongTy;
63   case LongTyID  : return LongTy;
64   case FloatTyID : return FloatTy;
65   case DoubleTyID: return DoubleTy;
66   case LabelTyID : return LabelTy;
67   default:
68     return 0;
69   }
70 }
71
72 // isLosslesslyConvertibleTo - Return true if this type can be converted to
73 // 'Ty' without any reinterpretation of bits.  For example, uint to int.
74 //
75 bool Type::isLosslesslyConvertibleTo(const Type *Ty) const {
76   if (this == Ty) return true;
77   if ((!isPrimitiveType()    && !isa<PointerType>(this)) ||
78       (!isa<PointerType>(Ty) && !Ty->isPrimitiveType())) return false;
79
80   if (getTypeID() == Ty->getTypeID())
81     return true;  // Handles identity cast, and cast of differing pointer types
82
83   // Now we know that they are two differing primitive or pointer types
84   switch (getTypeID()) {
85   case Type::UByteTyID:   return Ty == Type::SByteTy;
86   case Type::SByteTyID:   return Ty == Type::UByteTy;
87   case Type::UShortTyID:  return Ty == Type::ShortTy;
88   case Type::ShortTyID:   return Ty == Type::UShortTy;
89   case Type::UIntTyID:    return Ty == Type::IntTy;
90   case Type::IntTyID:     return Ty == Type::UIntTy;
91   case Type::ULongTyID:   return Ty == Type::LongTy;
92   case Type::LongTyID:    return Ty == Type::ULongTy;
93   case Type::PointerTyID: return isa<PointerType>(Ty);
94   default:
95     return false;  // Other types have no identity values
96   }
97 }
98
99 /// getUnsignedVersion - If this is an integer type, return the unsigned
100 /// variant of this type.  For example int -> uint.
101 const Type *Type::getUnsignedVersion() const {
102   switch (getTypeID()) {
103   default:
104     assert(isInteger()&&"Type::getUnsignedVersion is only valid for integers!");
105   case Type::UByteTyID:   
106   case Type::SByteTyID:   return Type::UByteTy;
107   case Type::UShortTyID:  
108   case Type::ShortTyID:   return Type::UShortTy;
109   case Type::UIntTyID:    
110   case Type::IntTyID:     return Type::UIntTy;
111   case Type::ULongTyID:   
112   case Type::LongTyID:    return Type::ULongTy;
113   }
114 }
115
116 /// getSignedVersion - If this is an integer type, return the signed variant
117 /// of this type.  For example uint -> int.
118 const Type *Type::getSignedVersion() const {
119   switch (getTypeID()) {
120   default:
121     assert(isInteger() && "Type::getSignedVersion is only valid for integers!");
122   case Type::UByteTyID:   
123   case Type::SByteTyID:   return Type::SByteTy;
124   case Type::UShortTyID:  
125   case Type::ShortTyID:   return Type::ShortTy;
126   case Type::UIntTyID:    
127   case Type::IntTyID:     return Type::IntTy;
128   case Type::ULongTyID:   
129   case Type::LongTyID:    return Type::LongTy;
130   }
131 }
132
133
134 // getPrimitiveSize - Return the basic size of this type if it is a primitive
135 // type.  These are fixed by LLVM and are not target dependent.  This will
136 // return zero if the type does not have a size or is not a primitive type.
137 //
138 unsigned Type::getPrimitiveSize() const {
139   switch (getTypeID()) {
140 #define HANDLE_PRIM_TYPE(TY,SIZE)  case TY##TyID: return SIZE;
141 #include "llvm/Type.def"
142   default: return 0;
143   }
144 }
145
146 /// isSizedDerivedType - Derived types like structures and arrays are sized
147 /// iff all of the members of the type are sized as well.  Since asking for
148 /// their size is relatively uncommon, move this operation out of line.
149 bool Type::isSizedDerivedType() const {
150   if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
151     return ATy->getElementType()->isSized();
152
153   if (!isa<StructType>(this)) return false;
154
155   // Okay, our struct is sized if all of the elements are...
156   for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I)
157     if (!(*I)->isSized()) return false;
158
159   return true;
160 }
161
162 /// getForwardedTypeInternal - This method is used to implement the union-find
163 /// algorithm for when a type is being forwarded to another type.
164 const Type *Type::getForwardedTypeInternal() const {
165   assert(ForwardType && "This type is not being forwarded to another type!");
166   
167   // Check to see if the forwarded type has been forwarded on.  If so, collapse
168   // the forwarding links.
169   const Type *RealForwardedType = ForwardType->getForwardedType();
170   if (!RealForwardedType)
171     return ForwardType;  // No it's not forwarded again
172
173   // Yes, it is forwarded again.  First thing, add the reference to the new
174   // forward type.
175   if (RealForwardedType->isAbstract())
176     cast<DerivedType>(RealForwardedType)->addRef();
177
178   // Now drop the old reference.  This could cause ForwardType to get deleted.
179   cast<DerivedType>(ForwardType)->dropRef();
180   
181   // Return the updated type.
182   ForwardType = RealForwardedType;
183   return ForwardType;
184 }
185
186 // getTypeDescription - This is a recursive function that walks a type hierarchy
187 // calculating the description for a type.
188 //
189 static std::string getTypeDescription(const Type *Ty,
190                                       std::vector<const Type *> &TypeStack) {
191   if (isa<OpaqueType>(Ty)) {                     // Base case for the recursion
192     std::map<const Type*, std::string>::iterator I =
193       AbstractTypeDescriptions.lower_bound(Ty);
194     if (I != AbstractTypeDescriptions.end() && I->first == Ty)
195       return I->second;
196     std::string Desc = "opaque";
197     AbstractTypeDescriptions.insert(std::make_pair(Ty, Desc));
198     return Desc;
199   }
200   
201   if (!Ty->isAbstract()) {                       // Base case for the recursion
202     std::map<const Type*, std::string>::iterator I =
203       ConcreteTypeDescriptions.find(Ty);
204     if (I != ConcreteTypeDescriptions.end()) return I->second;
205   }
206       
207   // Check to see if the Type is already on the stack...
208   unsigned Slot = 0, CurSize = TypeStack.size();
209   while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
210   
211   // This is another base case for the recursion.  In this case, we know 
212   // that we have looped back to a type that we have previously visited.
213   // Generate the appropriate upreference to handle this.
214   // 
215   if (Slot < CurSize)
216     return "\\" + utostr(CurSize-Slot);         // Here's the upreference
217
218   // Recursive case: derived types...
219   std::string Result;
220   TypeStack.push_back(Ty);    // Add us to the stack..
221       
222   switch (Ty->getTypeID()) {
223   case Type::FunctionTyID: {
224     const FunctionType *FTy = cast<FunctionType>(Ty);
225     Result = getTypeDescription(FTy->getReturnType(), TypeStack) + " (";
226     for (FunctionType::param_iterator I = FTy->param_begin(),
227            E = FTy->param_end(); I != E; ++I) {
228       if (I != FTy->param_begin())
229         Result += ", ";
230       Result += getTypeDescription(*I, TypeStack);
231     }
232     if (FTy->isVarArg()) {
233       if (FTy->getNumParams()) Result += ", ";
234       Result += "...";
235     }
236     Result += ")";
237     break;
238   }
239   case Type::StructTyID: {
240     const StructType *STy = cast<StructType>(Ty);
241     Result = "{ ";
242     for (StructType::element_iterator I = STy->element_begin(),
243            E = STy->element_end(); I != E; ++I) {
244       if (I != STy->element_begin())
245         Result += ", ";
246       Result += getTypeDescription(*I, TypeStack);
247     }
248     Result += " }";
249     break;
250   }
251   case Type::PointerTyID: {
252     const PointerType *PTy = cast<PointerType>(Ty);
253     Result = getTypeDescription(PTy->getElementType(), TypeStack) + " *";
254     break;
255   }
256   case Type::ArrayTyID: {
257     const ArrayType *ATy = cast<ArrayType>(Ty);
258     unsigned NumElements = ATy->getNumElements();
259     Result = "[";
260     Result += utostr(NumElements) + " x ";
261     Result += getTypeDescription(ATy->getElementType(), TypeStack) + "]";
262     break;
263   }
264   case Type::PackedTyID: {
265     const PackedType *PTy = cast<PackedType>(Ty);
266     unsigned NumElements = PTy->getNumElements();
267     Result = "<";
268     Result += utostr(NumElements) + " x ";
269     Result += getTypeDescription(PTy->getElementType(), TypeStack) + ">";
270     break;
271   }
272   default:
273     Result = "<error>";
274     assert(0 && "Unhandled type in getTypeDescription!");
275   }
276
277   TypeStack.pop_back();       // Remove self from stack...
278
279   return Result;
280 }
281
282
283
284 static const std::string &getOrCreateDesc(std::map<const Type*,std::string>&Map,
285                                           const Type *Ty) {
286   std::map<const Type*, std::string>::iterator I = Map.find(Ty);
287   if (I != Map.end()) return I->second;
288     
289   std::vector<const Type *> TypeStack;
290   return Map[Ty] = getTypeDescription(Ty, TypeStack);
291 }
292
293
294 const std::string &Type::getDescription() const {
295   if (isAbstract())
296     return getOrCreateDesc(AbstractTypeDescriptions, this);
297   else
298     return getOrCreateDesc(ConcreteTypeDescriptions, this);
299 }
300
301
302 bool StructType::indexValid(const Value *V) const {
303   // Structure indexes require unsigned integer constants.
304   if (V->getType() == Type::UIntTy)
305     if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(V))
306       return CU->getValue() < ContainedTys.size();
307   return false;
308 }
309
310 // getTypeAtIndex - Given an index value into the type, return the type of the
311 // element.  For a structure type, this must be a constant value...
312 //
313 const Type *StructType::getTypeAtIndex(const Value *V) const {
314   assert(indexValid(V) && "Invalid structure index!");
315   unsigned Idx = (unsigned)cast<ConstantUInt>(V)->getValue();
316   return ContainedTys[Idx];
317 }
318
319
320 //===----------------------------------------------------------------------===//
321 //                           Static 'Type' data
322 //===----------------------------------------------------------------------===//
323
324 namespace {
325   struct PrimType : public Type {
326     PrimType(const char *S, TypeID ID) : Type(S, ID) {}
327   };
328 }
329
330 static PrimType TheVoidTy  ("void"  , Type::VoidTyID);
331 static PrimType TheBoolTy  ("bool"  , Type::BoolTyID);
332 static PrimType TheSByteTy ("sbyte" , Type::SByteTyID);
333 static PrimType TheUByteTy ("ubyte" , Type::UByteTyID);
334 static PrimType TheShortTy ("short" , Type::ShortTyID);
335 static PrimType TheUShortTy("ushort", Type::UShortTyID);
336 static PrimType TheIntTy   ("int"   , Type::IntTyID);
337 static PrimType TheUIntTy  ("uint"  , Type::UIntTyID);
338 static PrimType TheLongTy  ("long"  , Type::LongTyID);
339 static PrimType TheULongTy ("ulong" , Type::ULongTyID);
340 static PrimType TheFloatTy ("float" , Type::FloatTyID);
341 static PrimType TheDoubleTy("double", Type::DoubleTyID);
342 static PrimType TheLabelTy ("label" , Type::LabelTyID);
343
344 Type *Type::VoidTy   = &TheVoidTy;
345 Type *Type::BoolTy   = &TheBoolTy;
346 Type *Type::SByteTy  = &TheSByteTy;
347 Type *Type::UByteTy  = &TheUByteTy;
348 Type *Type::ShortTy  = &TheShortTy;
349 Type *Type::UShortTy = &TheUShortTy;
350 Type *Type::IntTy    = &TheIntTy;
351 Type *Type::UIntTy   = &TheUIntTy;
352 Type *Type::LongTy   = &TheLongTy;
353 Type *Type::ULongTy  = &TheULongTy;
354 Type *Type::FloatTy  = &TheFloatTy;
355 Type *Type::DoubleTy = &TheDoubleTy;
356 Type *Type::LabelTy  = &TheLabelTy;
357
358
359 //===----------------------------------------------------------------------===//
360 //                          Derived Type Constructors
361 //===----------------------------------------------------------------------===//
362
363 FunctionType::FunctionType(const Type *Result,
364                            const std::vector<const Type*> &Params, 
365                            bool IsVarArgs) : DerivedType(FunctionTyID), 
366                                              isVarArgs(IsVarArgs) {
367   assert((Result->isFirstClassType() || Result == Type::VoidTy ||
368          isa<OpaqueType>(Result)) && 
369          "LLVM functions cannot return aggregates");
370   bool isAbstract = Result->isAbstract();
371   ContainedTys.reserve(Params.size()+1);
372   ContainedTys.push_back(PATypeHandle(Result, this));
373
374   for (unsigned i = 0; i != Params.size(); ++i) {
375     assert((Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])) &&
376            "Function arguments must be value types!");
377
378     ContainedTys.push_back(PATypeHandle(Params[i], this));
379     isAbstract |= Params[i]->isAbstract();
380   }
381
382   // Calculate whether or not this type is abstract
383   setAbstract(isAbstract);
384 }
385
386 StructType::StructType(const std::vector<const Type*> &Types)
387   : CompositeType(StructTyID) {
388   ContainedTys.reserve(Types.size());
389   bool isAbstract = false;
390   for (unsigned i = 0; i < Types.size(); ++i) {
391     assert(Types[i] != Type::VoidTy && "Void type for structure field!!");
392     ContainedTys.push_back(PATypeHandle(Types[i], this));
393     isAbstract |= Types[i]->isAbstract();
394   }
395
396   // Calculate whether or not this type is abstract
397   setAbstract(isAbstract);
398 }
399
400 ArrayType::ArrayType(const Type *ElType, unsigned NumEl)
401   : SequentialType(ArrayTyID, ElType) {
402   NumElements = NumEl;
403
404   // Calculate whether or not this type is abstract
405   setAbstract(ElType->isAbstract());
406 }
407
408 PackedType::PackedType(const Type *ElType, unsigned NumEl)
409   : SequentialType(PackedTyID, ElType) {
410   NumElements = NumEl;
411
412   assert(NumEl > 0 && "NumEl of a PackedType must be greater than 0");
413   assert((ElType->isIntegral() || ElType->isFloatingPoint()) && 
414          "Elements of a PackedType must be a primitive type");
415 }
416
417
418 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
419   // Calculate whether or not this type is abstract
420   setAbstract(E->isAbstract());
421 }
422
423 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
424   setAbstract(true);
425 #ifdef DEBUG_MERGE_TYPES
426   std::cerr << "Derived new type: " << *this << "\n";
427 #endif
428 }
429
430 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
431 // another (more concrete) type, we must eliminate all references to other
432 // types, to avoid some circular reference problems.
433 void DerivedType::dropAllTypeUses() {
434   if (!ContainedTys.empty()) {
435     while (ContainedTys.size() > 1)
436       ContainedTys.pop_back();
437     
438     // The type must stay abstract.  To do this, we insert a pointer to a type
439     // that will never get resolved, thus will always be abstract.
440     static Type *AlwaysOpaqueTy = OpaqueType::get();
441     static PATypeHolder Holder(AlwaysOpaqueTy);
442     ContainedTys[0] = AlwaysOpaqueTy;
443   }
444 }
445
446 // PromoteAbstractToConcrete - This is a recursive function that walks a type
447 // graph calculating whether or not a type is abstract.
448 //
449 // This method returns true if the type is found to still be abstract.
450 //
451 bool Type::PromoteAbstractToConcrete(void *Ptr) {
452   if (!isAbstract())                           // Base case for the recursion
453     return false;                              // Primitive = leaf type
454   
455   if (isa<OpaqueType>(this))                   // Base case for the recursion
456     return true;                               // This whole type is abstract!
457
458   /// KnownAbstractTypes - This set contains all of the types that we know for
459   /// sure are abstract.  Once we discover that a type really is abstract, we
460   /// remember this so we don't have to do potentially exponential amounts of
461   /// checking in some cases.
462   std::set<Type*> &KnownAbstractTypes = *(std::set<Type*>*)Ptr;
463   if (KnownAbstractTypes.count(this))
464     return true;    // We already know this type is abstract!
465
466   // We have to guard against recursion.  To do this, we temporarily mark this
467   // type as concrete, so that if we get back to here recursively we will think
468   // it's not abstract, and thus not scan it again.
469   setAbstract(false);
470
471   // Scan all of the sub-types.  If any of them are abstract, than so is this
472   // one!
473   for (Type::subtype_iterator I = subtype_begin(), E = subtype_end(); 
474        I != E; ++I)
475     if (const_cast<Type*>(I->get())->PromoteAbstractToConcrete(Ptr)) {
476       KnownAbstractTypes.insert(this);
477       setAbstract(true);        // Restore the abstract bit.
478       return true;              // This type is abstract if subtype is abstract!
479     }
480   
481   // Nothing looks abstract here.  Restore the abstract flag.
482   setAbstract(true);
483   return false;
484 }
485
486
487 //===----------------------------------------------------------------------===//
488 //                      Type Structural Equality Testing
489 //===----------------------------------------------------------------------===//
490
491 // TypesEqual - Two types are considered structurally equal if they have the
492 // same "shape": Every level and element of the types have identical primitive
493 // ID's, and the graphs have the same edges/nodes in them.  Nodes do not have to
494 // be pointer equals to be equivalent though.  This uses an optimistic algorithm
495 // that assumes that two graphs are the same until proven otherwise.
496 //
497 static bool TypesEqual(const Type *Ty, const Type *Ty2,
498                        std::map<const Type *, const Type *> &EqTypes) {
499   if (Ty == Ty2) return true;
500   if (Ty->getTypeID() != Ty2->getTypeID()) return false;
501   if (isa<OpaqueType>(Ty))
502     return false;  // Two unequal opaque types are never equal
503
504   std::map<const Type*, const Type*>::iterator It = EqTypes.lower_bound(Ty);
505   if (It != EqTypes.end() && It->first == Ty)
506     return It->second == Ty2;    // Looping back on a type, check for equality
507
508   // Otherwise, add the mapping to the table to make sure we don't get
509   // recursion on the types...
510   EqTypes.insert(It, std::make_pair(Ty, Ty2));
511
512   // Two really annoying special cases that breaks an otherwise nice simple
513   // algorithm is the fact that arraytypes have sizes that differentiates types,
514   // and that function types can be varargs or not.  Consider this now.
515   //
516   if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
517     return TypesEqual(PTy->getElementType(),
518                       cast<PointerType>(Ty2)->getElementType(), EqTypes);
519   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
520     const StructType *STy2 = cast<StructType>(Ty2);
521     if (STy->getNumElements() != STy2->getNumElements()) return false;
522     for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
523       if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
524         return false;
525     return true;
526   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
527     const ArrayType *ATy2 = cast<ArrayType>(Ty2);
528     return ATy->getNumElements() == ATy2->getNumElements() &&
529            TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
530   } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
531     const PackedType *PTy2 = cast<PackedType>(Ty2);
532     return PTy->getNumElements() == PTy2->getNumElements() &&
533            TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
534   } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
535     const FunctionType *FTy2 = cast<FunctionType>(Ty2);
536     if (FTy->isVarArg() != FTy2->isVarArg() ||
537         FTy->getNumParams() != FTy2->getNumParams() ||
538         !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
539       return false;
540     for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i)
541       if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
542         return false;
543     return true;
544   } else {
545     assert(0 && "Unknown derived type!");
546     return false;
547   }
548 }
549
550 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
551   std::map<const Type *, const Type *> EqTypes;
552   return TypesEqual(Ty, Ty2, EqTypes);
553 }
554
555 // TypeHasCycleThrough - Return true there is a path from CurTy to TargetTy in
556 // the type graph.  We know that Ty is an abstract type, so if we ever reach a
557 // non-abstract type, we know that we don't need to search the subgraph.
558 static bool TypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
559                                 std::set<const Type*> &VisitedTypes) {
560   if (TargetTy == CurTy) return true;
561   if (!CurTy->isAbstract()) return false;
562
563   std::set<const Type*>::iterator VTI = VisitedTypes.lower_bound(CurTy);
564   if (VTI != VisitedTypes.end() && *VTI == CurTy)
565     return false;
566   VisitedTypes.insert(VTI, CurTy);
567
568   for (Type::subtype_iterator I = CurTy->subtype_begin(), 
569        E = CurTy->subtype_end(); I != E; ++I)
570     if (TypeHasCycleThrough(TargetTy, *I, VisitedTypes))
571       return true;
572   return false;
573 }
574
575
576 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
577 /// back to itself.
578 static bool TypeHasCycleThroughItself(const Type *Ty) {
579   assert(Ty->isAbstract() && "This code assumes that Ty was abstract!");
580   std::set<const Type*> VisitedTypes;
581   for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end(); 
582        I != E; ++I)
583     if (TypeHasCycleThrough(Ty, *I, VisitedTypes))
584       return true;
585   return false;
586 }
587
588
589 //===----------------------------------------------------------------------===//
590 //                       Derived Type Factory Functions
591 //===----------------------------------------------------------------------===//
592
593 // TypeMap - Make sure that only one instance of a particular type may be
594 // created on any given run of the compiler... note that this involves updating
595 // our map if an abstract type gets refined somehow.
596 //
597 namespace llvm {
598 template<class ValType, class TypeClass>
599 class TypeMap {
600   std::map<ValType, PATypeHolder> Map;
601
602   /// TypesByHash - Keep track of each type by its structure hash value.
603   ///
604   std::multimap<unsigned, PATypeHolder> TypesByHash;
605 public:
606   typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
607   ~TypeMap() { print("ON EXIT"); }
608
609   inline TypeClass *get(const ValType &V) {
610     iterator I = Map.find(V);
611     return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
612   }
613
614   inline void add(const ValType &V, TypeClass *Ty) {
615     Map.insert(std::make_pair(V, Ty));
616
617     // If this type has a cycle, remember it.
618     TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
619     print("add");
620   }
621
622   void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
623     std::multimap<unsigned, PATypeHolder>::iterator I = 
624       TypesByHash.lower_bound(Hash);
625     while (I->second != Ty) {
626       ++I;
627       assert(I != TypesByHash.end() && I->first == Hash);
628     }
629     TypesByHash.erase(I);
630   }
631
632   /// finishRefinement - This method is called after we have updated an existing
633   /// type with its new components.  We must now either merge the type away with
634   /// some other type or reinstall it in the map with it's new configuration.
635   /// The specified iterator tells us what the type USED to look like.
636   void finishRefinement(TypeClass *Ty, const DerivedType *OldType,
637                         const Type *NewType) {
638     assert((Ty->isAbstract() || !OldType->isAbstract()) &&
639            "Refining a non-abstract type!");
640 #ifdef DEBUG_MERGE_TYPES
641     std::cerr << "refineAbstractTy(" << (void*)OldType << "[" << *OldType
642               << "], " << (void*)NewType << " [" << *NewType << "])\n";
643 #endif
644
645     // Make a temporary type holder for the type so that it doesn't disappear on
646     // us when we erase the entry from the map.
647     PATypeHolder TyHolder = Ty;
648
649     // The old record is now out-of-date, because one of the children has been
650     // updated.  Remove the obsolete entry from the map.
651     Map.erase(ValType::get(Ty));
652
653     // Remember the structural hash for the type before we start hacking on it,
654     // in case we need it later.  Also, check to see if the type HAD a cycle
655     // through it, if so, we know it will when we hack on it.
656     unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
657
658     // Find the type element we are refining... and change it now!
659     for (unsigned i = 0, e = Ty->ContainedTys.size(); i != e; ++i)
660       if (Ty->ContainedTys[i] == OldType) {
661         Ty->ContainedTys[i].removeUserFromConcrete();
662         Ty->ContainedTys[i] = NewType;
663       }
664
665     unsigned TypeHash = ValType::hashTypeStructure(Ty);
666     
667     // If there are no cycles going through this node, we can do a simple,
668     // efficient lookup in the map, instead of an inefficient nasty linear
669     // lookup.
670     bool TypeHasCycle = Ty->isAbstract() && TypeHasCycleThroughItself(Ty);
671     if (!TypeHasCycle) {
672       iterator I = Map.find(ValType::get(Ty));
673       if (I != Map.end()) {
674         // We already have this type in the table.  Get rid of the newly refined
675         // type.
676         assert(Ty->isAbstract() && "Replacing a non-abstract type?");
677         TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
678         
679         // Refined to a different type altogether?
680         RemoveFromTypesByHash(TypeHash, Ty);
681         Ty->refineAbstractTypeTo(NewTy);
682         return;
683       }
684       
685     } else {
686       // Now we check to see if there is an existing entry in the table which is
687       // structurally identical to the newly refined type.  If so, this type
688       // gets refined to the pre-existing type.
689       //
690       std::multimap<unsigned, PATypeHolder>::iterator I,E, Entry;
691       tie(I, E) = TypesByHash.equal_range(TypeHash);
692       Entry = E;
693       for (; I != E; ++I) {
694         if (I->second != Ty) {
695           if (TypesEqual(Ty, I->second)) {
696             assert(Ty->isAbstract() && "Replacing a non-abstract type?");
697             TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
698             
699             if (Entry == E) {
700               // Find the location of Ty in the TypesByHash structure.
701               while (I->second != Ty) {
702                 ++I;
703                 assert(I != E && "Structure doesn't contain type??");
704               }
705               Entry = I;
706             }
707
708             TypesByHash.erase(Entry);
709             Ty->refineAbstractTypeTo(NewTy);
710             return;
711           }
712         } else {
713           // Remember the position of 
714           Entry = I;
715         }
716       }
717     }
718
719     // If we succeeded, we need to insert the type into the cycletypes table.
720     // There are several cases here, depending on whether the original type
721     // had the same hash code and was itself cyclic.
722     if (TypeHash != OldTypeHash) {
723       RemoveFromTypesByHash(OldTypeHash, Ty);
724       TypesByHash.insert(std::make_pair(TypeHash, Ty));
725     }
726
727     // If there is no existing type of the same structure, we reinsert an
728     // updated record into the map.
729     Map.insert(std::make_pair(ValType::get(Ty), Ty));
730
731     // If the type is currently thought to be abstract, rescan all of our
732     // subtypes to see if the type has just become concrete!
733     if (Ty->isAbstract()) {
734       std::set<Type*> KnownAbstractTypes;
735       if (!Ty->PromoteAbstractToConcrete(&KnownAbstractTypes))
736         Ty->setAbstract(false);
737
738       // If the type just became concrete, notify all users!
739       if (!Ty->isAbstract())
740         Ty->notifyUsesThatTypeBecameConcrete();
741     }
742   }
743   
744   void print(const char *Arg) const {
745 #ifdef DEBUG_MERGE_TYPES
746     std::cerr << "TypeMap<>::" << Arg << " table contents:\n";
747     unsigned i = 0;
748     for (typename std::map<ValType, PATypeHolder>::const_iterator I
749            = Map.begin(), E = Map.end(); I != E; ++I)
750       std::cerr << " " << (++i) << ". " << (void*)I->second.get() << " " 
751                 << *I->second.get() << "\n";
752 #endif
753   }
754
755   void dump() const { print("dump output"); }
756 };
757 }
758
759
760 //===----------------------------------------------------------------------===//
761 // Function Type Factory and Value Class...
762 //
763
764 // FunctionValType - Define a class to hold the key that goes into the TypeMap
765 //
766 namespace llvm {
767 class FunctionValType {
768   const Type *RetTy;
769   std::vector<const Type*> ArgTypes;
770   bool isVarArg;
771 public:
772   FunctionValType(const Type *ret, const std::vector<const Type*> &args,
773                   bool IVA) : RetTy(ret), isVarArg(IVA) {
774     for (unsigned i = 0; i < args.size(); ++i)
775       ArgTypes.push_back(args[i]);
776   }
777
778   static FunctionValType get(const FunctionType *FT);
779
780   static unsigned hashTypeStructure(const FunctionType *FT) {
781     return FT->getNumParams()*2+FT->isVarArg();
782   }
783
784   // Subclass should override this... to update self as usual
785   void doRefinement(const DerivedType *OldType, const Type *NewType) {
786     if (RetTy == OldType) RetTy = NewType;
787     for (unsigned i = 0, e = ArgTypes.size(); i != e; ++i)
788       if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
789   }
790
791   inline bool operator<(const FunctionValType &MTV) const {
792     if (RetTy < MTV.RetTy) return true;
793     if (RetTy > MTV.RetTy) return false;
794
795     if (ArgTypes < MTV.ArgTypes) return true;
796     return ArgTypes == MTV.ArgTypes && isVarArg < MTV.isVarArg;
797   }
798 };
799 }
800
801 // Define the actual map itself now...
802 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
803
804 FunctionValType FunctionValType::get(const FunctionType *FT) {
805   // Build up a FunctionValType
806   std::vector<const Type *> ParamTypes;
807   ParamTypes.reserve(FT->getNumParams());
808   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
809     ParamTypes.push_back(FT->getParamType(i));
810   return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
811 }
812
813
814 // FunctionType::get - The factory function for the FunctionType class...
815 FunctionType *FunctionType::get(const Type *ReturnType, 
816                                 const std::vector<const Type*> &Params,
817                                 bool isVarArg) {
818   FunctionValType VT(ReturnType, Params, isVarArg);
819   FunctionType *MT = FunctionTypes.get(VT);
820   if (MT) return MT;
821
822   FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
823
824 #ifdef DEBUG_MERGE_TYPES
825   std::cerr << "Derived new type: " << MT << "\n";
826 #endif
827   return MT;
828 }
829
830 //===----------------------------------------------------------------------===//
831 // Array Type Factory...
832 //
833 namespace llvm {
834 class ArrayValType {
835   const Type *ValTy;
836   unsigned Size;
837 public:
838   ArrayValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
839
840   static ArrayValType get(const ArrayType *AT) {
841     return ArrayValType(AT->getElementType(), AT->getNumElements());
842   }
843
844   static unsigned hashTypeStructure(const ArrayType *AT) {
845     return AT->getNumElements();
846   }
847
848   // Subclass should override this... to update self as usual
849   void doRefinement(const DerivedType *OldType, const Type *NewType) {
850     assert(ValTy == OldType);
851     ValTy = NewType;
852   }
853
854   inline bool operator<(const ArrayValType &MTV) const {
855     if (Size < MTV.Size) return true;
856     return Size == MTV.Size && ValTy < MTV.ValTy;
857   }
858 };
859 }
860 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
861
862
863 ArrayType *ArrayType::get(const Type *ElementType, unsigned NumElements) {
864   assert(ElementType && "Can't get array of null types!");
865
866   ArrayValType AVT(ElementType, NumElements);
867   ArrayType *AT = ArrayTypes.get(AVT);
868   if (AT) return AT;           // Found a match, return it!
869
870   // Value not found.  Derive a new type!
871   ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
872
873 #ifdef DEBUG_MERGE_TYPES
874   std::cerr << "Derived new type: " << *AT << "\n";
875 #endif
876   return AT;
877 }
878
879
880 //===----------------------------------------------------------------------===//
881 // Packed Type Factory...
882 //
883 namespace llvm {
884 class PackedValType {
885   const Type *ValTy;
886   unsigned Size;
887 public:
888   PackedValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
889
890   static PackedValType get(const PackedType *PT) {
891     return PackedValType(PT->getElementType(), PT->getNumElements());
892   }
893
894   static unsigned hashTypeStructure(const PackedType *PT) {
895     return PT->getNumElements();
896   }
897
898   // Subclass should override this... to update self as usual
899   void doRefinement(const DerivedType *OldType, const Type *NewType) {
900     assert(ValTy == OldType);
901     ValTy = NewType;
902   }
903
904   inline bool operator<(const PackedValType &MTV) const {
905     if (Size < MTV.Size) return true;
906     return Size == MTV.Size && ValTy < MTV.ValTy;
907   }
908 };
909 }
910 static TypeMap<PackedValType, PackedType> PackedTypes;
911
912
913 PackedType *PackedType::get(const Type *ElementType, unsigned NumElements) {
914   assert(ElementType && "Can't get packed of null types!");
915
916   PackedValType PVT(ElementType, NumElements);
917   PackedType *PT = PackedTypes.get(PVT);
918   if (PT) return PT;           // Found a match, return it!
919
920   // Value not found.  Derive a new type!
921   PackedTypes.add(PVT, PT = new PackedType(ElementType, NumElements));
922
923 #ifdef DEBUG_MERGE_TYPES
924   std::cerr << "Derived new type: " << *PT << "\n";
925 #endif
926   return PT;
927 }
928
929 //===----------------------------------------------------------------------===//
930 // Struct Type Factory...
931 //
932
933 namespace llvm {
934 // StructValType - Define a class to hold the key that goes into the TypeMap
935 //
936 class StructValType {
937   std::vector<const Type*> ElTypes;
938 public:
939   StructValType(const std::vector<const Type*> &args) : ElTypes(args) {}
940
941   static StructValType get(const StructType *ST) {
942     std::vector<const Type *> ElTypes;
943     ElTypes.reserve(ST->getNumElements());
944     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
945       ElTypes.push_back(ST->getElementType(i));
946     
947     return StructValType(ElTypes);
948   }
949
950   static unsigned hashTypeStructure(const StructType *ST) {
951     return ST->getNumElements();
952   }
953
954   // Subclass should override this... to update self as usual
955   void doRefinement(const DerivedType *OldType, const Type *NewType) {
956     for (unsigned i = 0; i < ElTypes.size(); ++i)
957       if (ElTypes[i] == OldType) ElTypes[i] = NewType;
958   }
959
960   inline bool operator<(const StructValType &STV) const {
961     return ElTypes < STV.ElTypes;
962   }
963 };
964 }
965
966 static TypeMap<StructValType, StructType> StructTypes;
967
968 StructType *StructType::get(const std::vector<const Type*> &ETypes) {
969   StructValType STV(ETypes);
970   StructType *ST = StructTypes.get(STV);
971   if (ST) return ST;
972
973   // Value not found.  Derive a new type!
974   StructTypes.add(STV, ST = new StructType(ETypes));
975
976 #ifdef DEBUG_MERGE_TYPES
977   std::cerr << "Derived new type: " << *ST << "\n";
978 #endif
979   return ST;
980 }
981
982
983
984 //===----------------------------------------------------------------------===//
985 // Pointer Type Factory...
986 //
987
988 // PointerValType - Define a class to hold the key that goes into the TypeMap
989 //
990 namespace llvm {
991 class PointerValType {
992   const Type *ValTy;
993 public:
994   PointerValType(const Type *val) : ValTy(val) {}
995
996   static PointerValType get(const PointerType *PT) {
997     return PointerValType(PT->getElementType());
998   }
999
1000   static unsigned hashTypeStructure(const PointerType *PT) {
1001     return 0;
1002   }
1003
1004   // Subclass should override this... to update self as usual
1005   void doRefinement(const DerivedType *OldType, const Type *NewType) {
1006     assert(ValTy == OldType);
1007     ValTy = NewType;
1008   }
1009
1010   bool operator<(const PointerValType &MTV) const {
1011     return ValTy < MTV.ValTy;
1012   }
1013 };
1014 }
1015
1016 static TypeMap<PointerValType, PointerType> PointerTypes;
1017
1018 PointerType *PointerType::get(const Type *ValueType) {
1019   assert(ValueType && "Can't get a pointer to <null> type!");
1020   PointerValType PVT(ValueType);
1021
1022   PointerType *PT = PointerTypes.get(PVT);
1023   if (PT) return PT;
1024
1025   // Value not found.  Derive a new type!
1026   PointerTypes.add(PVT, PT = new PointerType(ValueType));
1027
1028 #ifdef DEBUG_MERGE_TYPES
1029   std::cerr << "Derived new type: " << *PT << "\n";
1030 #endif
1031   return PT;
1032 }
1033
1034
1035 //===----------------------------------------------------------------------===//
1036 //                     Derived Type Refinement Functions
1037 //===----------------------------------------------------------------------===//
1038
1039 // removeAbstractTypeUser - Notify an abstract type that a user of the class
1040 // no longer has a handle to the type.  This function is called primarily by
1041 // the PATypeHandle class.  When there are no users of the abstract type, it
1042 // is annihilated, because there is no way to get a reference to it ever again.
1043 //
1044 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
1045   // Search from back to front because we will notify users from back to
1046   // front.  Also, it is likely that there will be a stack like behavior to
1047   // users that register and unregister users.
1048   //
1049   unsigned i;
1050   for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1051     assert(i != 0 && "AbstractTypeUser not in user list!");
1052
1053   --i;  // Convert to be in range 0 <= i < size()
1054   assert(i < AbstractTypeUsers.size() && "Index out of range!");  // Wraparound?
1055
1056   AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1057       
1058 #ifdef DEBUG_MERGE_TYPES
1059   std::cerr << "  remAbstractTypeUser[" << (void*)this << ", "
1060             << *this << "][" << i << "] User = " << U << "\n";
1061 #endif
1062     
1063   if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1064 #ifdef DEBUG_MERGE_TYPES
1065     std::cerr << "DELETEing unused abstract type: <" << *this
1066               << ">[" << (void*)this << "]" << "\n";
1067 #endif
1068     delete this;                  // No users of this abstract type!
1069   }
1070 }
1071
1072
1073 // refineAbstractTypeTo - This function is used to when it is discovered that
1074 // the 'this' abstract type is actually equivalent to the NewType specified.
1075 // This causes all users of 'this' to switch to reference the more concrete type
1076 // NewType and for 'this' to be deleted.
1077 //
1078 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1079   assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1080   assert(this != NewType && "Can't refine to myself!");
1081   assert(ForwardType == 0 && "This type has already been refined!");
1082
1083   // The descriptions may be out of date.  Conservatively clear them all!
1084   AbstractTypeDescriptions.clear();
1085
1086 #ifdef DEBUG_MERGE_TYPES
1087   std::cerr << "REFINING abstract type [" << (void*)this << " "
1088             << *this << "] to [" << (void*)NewType << " "
1089             << *NewType << "]!\n";
1090 #endif
1091
1092   // Make sure to put the type to be refined to into a holder so that if IT gets
1093   // refined, that we will not continue using a dead reference...
1094   //
1095   PATypeHolder NewTy(NewType);
1096
1097   // Any PATypeHolders referring to this type will now automatically forward to
1098   // the type we are resolved to.
1099   ForwardType = NewType;
1100   if (NewType->isAbstract())
1101     cast<DerivedType>(NewType)->addRef();
1102
1103   // Add a self use of the current type so that we don't delete ourself until
1104   // after the function exits.
1105   //
1106   PATypeHolder CurrentTy(this);
1107
1108   // To make the situation simpler, we ask the subclass to remove this type from
1109   // the type map, and to replace any type uses with uses of non-abstract types.
1110   // This dramatically limits the amount of recursive type trouble we can find
1111   // ourselves in.
1112   dropAllTypeUses();
1113
1114   // Iterate over all of the uses of this type, invoking callback.  Each user
1115   // should remove itself from our use list automatically.  We have to check to
1116   // make sure that NewTy doesn't _become_ 'this'.  If it does, resolving types
1117   // will not cause users to drop off of the use list.  If we resolve to ourself
1118   // we succeed!
1119   //
1120   while (!AbstractTypeUsers.empty() && NewTy != this) {
1121     AbstractTypeUser *User = AbstractTypeUsers.back();
1122
1123     unsigned OldSize = AbstractTypeUsers.size();
1124 #ifdef DEBUG_MERGE_TYPES
1125     std::cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
1126               << "] of abstract type [" << (void*)this << " "
1127               << *this << "] to [" << (void*)NewTy.get() << " "
1128               << *NewTy << "]!\n";
1129 #endif
1130     User->refineAbstractType(this, NewTy);
1131
1132     assert(AbstractTypeUsers.size() != OldSize &&
1133            "AbsTyUser did not remove self from user list!");
1134   }
1135
1136   // If we were successful removing all users from the type, 'this' will be
1137   // deleted when the last PATypeHolder is destroyed or updated from this type.
1138   // This may occur on exit of this function, as the CurrentTy object is
1139   // destroyed.
1140 }
1141
1142 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1143 // the current type has transitioned from being abstract to being concrete.
1144 //
1145 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1146 #ifdef DEBUG_MERGE_TYPES
1147   std::cerr << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1148 #endif
1149
1150   unsigned OldSize = AbstractTypeUsers.size();
1151   while (!AbstractTypeUsers.empty()) {
1152     AbstractTypeUser *ATU = AbstractTypeUsers.back();
1153     ATU->typeBecameConcrete(this);
1154
1155     assert(AbstractTypeUsers.size() < OldSize-- &&
1156            "AbstractTypeUser did not remove itself from the use list!");
1157   }
1158 }
1159   
1160
1161
1162
1163 // refineAbstractType - Called when a contained type is found to be more
1164 // concrete - this could potentially change us from an abstract type to a
1165 // concrete type.
1166 //
1167 void FunctionType::refineAbstractType(const DerivedType *OldType,
1168                                       const Type *NewType) {
1169   FunctionTypes.finishRefinement(this, OldType, NewType);
1170 }
1171
1172 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1173   refineAbstractType(AbsTy, AbsTy);
1174 }
1175
1176
1177 // refineAbstractType - Called when a contained type is found to be more
1178 // concrete - this could potentially change us from an abstract type to a
1179 // concrete type.
1180 //
1181 void ArrayType::refineAbstractType(const DerivedType *OldType,
1182                                    const Type *NewType) {
1183   ArrayTypes.finishRefinement(this, OldType, NewType);
1184 }
1185
1186 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1187   refineAbstractType(AbsTy, AbsTy);
1188 }
1189
1190 // refineAbstractType - Called when a contained type is found to be more
1191 // concrete - this could potentially change us from an abstract type to a
1192 // concrete type.
1193 //
1194 void PackedType::refineAbstractType(const DerivedType *OldType,
1195                                    const Type *NewType) {
1196   PackedTypes.finishRefinement(this, OldType, NewType);
1197 }
1198
1199 void PackedType::typeBecameConcrete(const DerivedType *AbsTy) {
1200   refineAbstractType(AbsTy, AbsTy);
1201 }
1202
1203 // refineAbstractType - Called when a contained type is found to be more
1204 // concrete - this could potentially change us from an abstract type to a
1205 // concrete type.
1206 //
1207 void StructType::refineAbstractType(const DerivedType *OldType,
1208                                     const Type *NewType) {
1209   StructTypes.finishRefinement(this, OldType, NewType);
1210 }
1211
1212 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1213   refineAbstractType(AbsTy, AbsTy);
1214 }
1215
1216 // refineAbstractType - Called when a contained type is found to be more
1217 // concrete - this could potentially change us from an abstract type to a
1218 // concrete type.
1219 //
1220 void PointerType::refineAbstractType(const DerivedType *OldType,
1221                                      const Type *NewType) {
1222   PointerTypes.finishRefinement(this, OldType, NewType);
1223 }
1224
1225 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1226   refineAbstractType(AbsTy, AbsTy);
1227 }
1228
1229 bool SequentialType::indexValid(const Value *V) const {
1230   const Type *Ty = V->getType();
1231   switch (Ty->getTypeID()) {
1232   case Type::IntTyID:
1233   case Type::UIntTyID:
1234   case Type::LongTyID:
1235   case Type::ULongTyID:
1236     return true;
1237   default:
1238     return false;
1239   }
1240 }
1241
1242 namespace llvm {
1243 std::ostream &operator<<(std::ostream &OS, const Type *T) {
1244   if (T == 0)
1245     OS << "<null> value!\n";
1246   else
1247     T->print(OS);
1248   return OS;
1249 }
1250
1251 std::ostream &operator<<(std::ostream &OS, const Type &T) {
1252   T.print(OS);
1253   return OS;
1254 }
1255 }
1256
1257 // vim: sw=2