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