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