Eliminate the SignedType and UnsignedType classes.
[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 //                           Static 'Type' data
330 //===----------------------------------------------------------------------===//
331
332 namespace {
333   struct PrimType : public Type {
334     PrimType(const char *S, TypeID ID) : Type(S, ID) {}
335   };
336 }
337
338 static PrimType TheVoidTy  ("void"  , Type::VoidTyID);
339 static PrimType TheBoolTy  ("bool"  , Type::BoolTyID);
340 static PrimType TheSByteTy ("sbyte" , Type::SByteTyID);
341 static PrimType TheUByteTy ("ubyte" , Type::UByteTyID);
342 static PrimType TheShortTy ("short" , Type::ShortTyID);
343 static PrimType TheUShortTy("ushort", Type::UShortTyID);
344 static PrimType TheIntTy   ("int"   , Type::IntTyID);
345 static PrimType TheUIntTy  ("uint"  , Type::UIntTyID);
346 static PrimType TheLongTy  ("long"  , Type::LongTyID);
347 static PrimType TheULongTy ("ulong" , Type::ULongTyID);
348 static PrimType TheFloatTy ("float" , Type::FloatTyID);
349 static PrimType TheDoubleTy("double", Type::DoubleTyID);
350 static PrimType TheLabelTy ("label" , Type::LabelTyID);
351
352 Type *Type::VoidTy   = &TheVoidTy;
353 Type *Type::BoolTy   = &TheBoolTy;
354 Type *Type::SByteTy  = &TheSByteTy;
355 Type *Type::UByteTy  = &TheUByteTy;
356 Type *Type::ShortTy  = &TheShortTy;
357 Type *Type::UShortTy = &TheUShortTy;
358 Type *Type::IntTy    = &TheIntTy;
359 Type *Type::UIntTy   = &TheUIntTy;
360 Type *Type::LongTy   = &TheLongTy;
361 Type *Type::ULongTy  = &TheULongTy;
362 Type *Type::FloatTy  = &TheFloatTy;
363 Type *Type::DoubleTy = &TheDoubleTy;
364 Type *Type::LabelTy  = &TheLabelTy;
365
366
367 //===----------------------------------------------------------------------===//
368 //                          Derived Type Constructors
369 //===----------------------------------------------------------------------===//
370
371 FunctionType::FunctionType(const Type *Result,
372                            const std::vector<const Type*> &Params, 
373                            bool IsVarArgs) : DerivedType(FunctionTyID), 
374                                              isVarArgs(IsVarArgs) {
375   assert((Result->isFirstClassType() || Result == Type::VoidTy ||
376          isa<OpaqueType>(Result)) && 
377          "LLVM functions cannot return aggregates");
378   bool isAbstract = Result->isAbstract();
379   ContainedTys.reserve(Params.size()+1);
380   ContainedTys.push_back(PATypeHandle(Result, this));
381
382   for (unsigned i = 0; i != Params.size(); ++i) {
383     ContainedTys.push_back(PATypeHandle(Params[i], this));
384     isAbstract |= Params[i]->isAbstract();
385   }
386
387   // Calculate whether or not this type is abstract
388   setAbstract(isAbstract);
389 }
390
391 StructType::StructType(const std::vector<const Type*> &Types)
392   : CompositeType(StructTyID) {
393   ContainedTys.reserve(Types.size());
394   bool isAbstract = false;
395   for (unsigned i = 0; i < Types.size(); ++i) {
396     assert(Types[i] != Type::VoidTy && "Void type for structure field!!");
397     ContainedTys.push_back(PATypeHandle(Types[i], this));
398     isAbstract |= Types[i]->isAbstract();
399   }
400
401   // Calculate whether or not this type is abstract
402   setAbstract(isAbstract);
403 }
404
405 ArrayType::ArrayType(const Type *ElType, unsigned NumEl)
406   : SequentialType(ArrayTyID, ElType) {
407   NumElements = NumEl;
408
409   // Calculate whether or not this type is abstract
410   setAbstract(ElType->isAbstract());
411 }
412
413 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
414   // Calculate whether or not this type is abstract
415   setAbstract(E->isAbstract());
416 }
417
418 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
419   setAbstract(true);
420 #ifdef DEBUG_MERGE_TYPES
421   std::cerr << "Derived new type: " << *this << "\n";
422 #endif
423 }
424
425 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
426 // another (more concrete) type, we must eliminate all references to other
427 // types, to avoid some circular reference problems.
428 void DerivedType::dropAllTypeUses() {
429   if (!ContainedTys.empty()) {
430     while (ContainedTys.size() > 1)
431       ContainedTys.pop_back();
432     
433     // The type must stay abstract.  To do this, we insert a pointer to a type
434     // that will never get resolved, thus will always be abstract.
435     static Type *AlwaysOpaqueTy = OpaqueType::get();
436     static PATypeHolder Holder(AlwaysOpaqueTy);
437     ContainedTys[0] = AlwaysOpaqueTy;
438   }
439 }
440
441 // isTypeAbstract - This is a recursive function that walks a type hierarchy
442 // calculating whether or not a type is abstract.  Worst case it will have to do
443 // a lot of traversing if you have some whacko opaque types, but in most cases,
444 // it will do some simple stuff when it hits non-abstract types that aren't
445 // recursive.
446 //
447 bool Type::isTypeAbstract() {
448   if (!isAbstract())                           // Base case for the recursion
449     return false;                              // Primitive = leaf type
450   
451   if (isa<OpaqueType>(this))                   // Base case for the recursion
452     return true;                               // This whole type is abstract!
453
454   // We have to guard against recursion.  To do this, we temporarily mark this
455   // type as concrete, so that if we get back to here recursively we will think
456   // it's not abstract, and thus not scan it again.
457   setAbstract(false);
458
459   // Scan all of the sub-types.  If any of them are abstract, than so is this
460   // one!
461   for (Type::subtype_iterator I = subtype_begin(), E = subtype_end(); 
462        I != E; ++I)
463     if (const_cast<Type*>(I->get())->isTypeAbstract()) {
464       setAbstract(true);        // Restore the abstract bit.
465       return true;              // This type is abstract if subtype is abstract!
466     }
467   
468   // Restore the abstract bit.
469   setAbstract(true);
470
471   // Nothing looks abstract here...
472   return false;
473 }
474
475
476 //===----------------------------------------------------------------------===//
477 //                      Type Structural Equality Testing
478 //===----------------------------------------------------------------------===//
479
480 // TypesEqual - Two types are considered structurally equal if they have the
481 // same "shape": Every level and element of the types have identical primitive
482 // ID's, and the graphs have the same edges/nodes in them.  Nodes do not have to
483 // be pointer equals to be equivalent though.  This uses an optimistic algorithm
484 // that assumes that two graphs are the same until proven otherwise.
485 //
486 static bool TypesEqual(const Type *Ty, const Type *Ty2,
487                        std::map<const Type *, const Type *> &EqTypes) {
488   if (Ty == Ty2) return true;
489   if (Ty->getTypeID() != Ty2->getTypeID()) return false;
490   if (isa<OpaqueType>(Ty))
491     return false;  // Two unequal opaque types are never equal
492
493   std::map<const Type*, const Type*>::iterator It = EqTypes.lower_bound(Ty);
494   if (It != EqTypes.end() && It->first == Ty)
495     return It->second == Ty2;    // Looping back on a type, check for equality
496
497   // Otherwise, add the mapping to the table to make sure we don't get
498   // recursion on the types...
499   EqTypes.insert(It, std::make_pair(Ty, Ty2));
500
501   // Two really annoying special cases that breaks an otherwise nice simple
502   // algorithm is the fact that arraytypes have sizes that differentiates types,
503   // and that function types can be varargs or not.  Consider this now.
504   //
505   if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
506     return TypesEqual(PTy->getElementType(),
507                       cast<PointerType>(Ty2)->getElementType(), EqTypes);
508   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
509     const StructType *STy2 = cast<StructType>(Ty2);
510     if (STy->getNumElements() != STy2->getNumElements()) return false;
511     for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
512       if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
513         return false;
514     return true;
515   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
516     const ArrayType *ATy2 = cast<ArrayType>(Ty2);
517     return ATy->getNumElements() == ATy2->getNumElements() &&
518            TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
519   } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
520     const FunctionType *FTy2 = cast<FunctionType>(Ty2);
521     if (FTy->isVarArg() != FTy2->isVarArg() ||
522         FTy->getNumParams() != FTy2->getNumParams() ||
523         !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
524       return false;
525     for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i)
526       if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
527         return false;
528     return true;
529   } else {
530     assert(0 && "Unknown derived type!");
531     return false;
532   }
533 }
534
535 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
536   std::map<const Type *, const Type *> EqTypes;
537   return TypesEqual(Ty, Ty2, EqTypes);
538 }
539
540 // TypeHasCycleThrough - Return true there is a path from CurTy to TargetTy in
541 // the type graph.  We know that Ty is an abstract type, so if we ever reach a
542 // non-abstract type, we know that we don't need to search the subgraph.
543 static bool TypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
544                                 std::set<const Type*> &VisitedTypes) {
545   if (TargetTy == CurTy) return true;
546   if (!CurTy->isAbstract()) return false;
547
548   std::set<const Type*>::iterator VTI = VisitedTypes.lower_bound(CurTy);
549   if (VTI != VisitedTypes.end() && *VTI == CurTy)
550     return false;
551   VisitedTypes.insert(VTI, CurTy);
552
553   for (Type::subtype_iterator I = CurTy->subtype_begin(), 
554        E = CurTy->subtype_end(); I != E; ++I)
555     if (TypeHasCycleThrough(TargetTy, *I, VisitedTypes))
556       return true;
557   return false;
558 }
559
560
561 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
562 /// back to itself.
563 static bool TypeHasCycleThroughItself(const Type *Ty) {
564   assert(Ty->isAbstract() && "This code assumes that Ty was abstract!");
565   std::set<const Type*> VisitedTypes;
566   for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end(); 
567        I != E; ++I)
568     if (TypeHasCycleThrough(Ty, *I, VisitedTypes))
569       return true;
570   return false;
571 }
572
573
574 //===----------------------------------------------------------------------===//
575 //                       Derived Type Factory Functions
576 //===----------------------------------------------------------------------===//
577
578 // TypeMap - Make sure that only one instance of a particular type may be
579 // created on any given run of the compiler... note that this involves updating
580 // our map if an abstract type gets refined somehow.
581 //
582 namespace llvm {
583 template<class ValType, class TypeClass>
584 class TypeMap {
585   std::map<ValType, PATypeHolder> Map;
586
587   /// TypesByHash - Keep track of each type by its structure hash value.
588   ///
589   std::multimap<unsigned, PATypeHolder> TypesByHash;
590 public:
591   typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
592   ~TypeMap() { print("ON EXIT"); }
593
594   inline TypeClass *get(const ValType &V) {
595     iterator I = Map.find(V);
596     return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
597   }
598
599   inline void add(const ValType &V, TypeClass *Ty) {
600     Map.insert(std::make_pair(V, Ty));
601
602     // If this type has a cycle, remember it.
603     TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
604     print("add");
605   }
606
607   void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
608     std::multimap<unsigned, PATypeHolder>::iterator I = 
609       TypesByHash.lower_bound(Hash);
610     while (I->second != Ty) {
611       ++I;
612       assert(I != TypesByHash.end() && I->first == Hash);
613     }
614     TypesByHash.erase(I);
615   }
616
617   /// finishRefinement - This method is called after we have updated an existing
618   /// type with its new components.  We must now either merge the type away with
619   /// some other type or reinstall it in the map with it's new configuration.
620   /// The specified iterator tells us what the type USED to look like.
621   void finishRefinement(TypeClass *Ty, const DerivedType *OldType,
622                         const Type *NewType) {
623     assert((Ty->isAbstract() || !OldType->isAbstract()) &&
624            "Refining a non-abstract type!");
625 #ifdef DEBUG_MERGE_TYPES
626     std::cerr << "refineAbstractTy(" << (void*)OldType << "[" << *OldType
627               << "], " << (void*)NewType << " [" << *NewType << "])\n";
628 #endif
629
630     // Make a temporary type holder for the type so that it doesn't disappear on
631     // us when we erase the entry from the map.
632     PATypeHolder TyHolder = Ty;
633
634     // The old record is now out-of-date, because one of the children has been
635     // updated.  Remove the obsolete entry from the map.
636     Map.erase(ValType::get(Ty));
637
638     // Remember the structural hash for the type before we start hacking on it,
639     // in case we need it later.  Also, check to see if the type HAD a cycle
640     // through it, if so, we know it will when we hack on it.
641     unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
642
643     // Find the type element we are refining... and change it now!
644     for (unsigned i = 0, e = Ty->ContainedTys.size(); i != e; ++i)
645       if (Ty->ContainedTys[i] == OldType) {
646         Ty->ContainedTys[i].removeUserFromConcrete();
647         Ty->ContainedTys[i] = NewType;
648       }
649
650     unsigned TypeHash = ValType::hashTypeStructure(Ty);
651     
652     // If there are no cycles going through this node, we can do a simple,
653     // efficient lookup in the map, instead of an inefficient nasty linear
654     // lookup.
655     bool TypeHasCycle = Ty->isAbstract() && TypeHasCycleThroughItself(Ty);
656     if (!TypeHasCycle) {
657       iterator I = Map.find(ValType::get(Ty));
658       if (I != Map.end()) {
659         // We already have this type in the table.  Get rid of the newly refined
660         // type.
661         assert(Ty->isAbstract() && "Replacing a non-abstract type?");
662         TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
663         
664         // Refined to a different type altogether?
665         RemoveFromTypesByHash(TypeHash, Ty);
666         Ty->refineAbstractTypeTo(NewTy);
667         return;
668       }
669       
670     } else {
671       // Now we check to see if there is an existing entry in the table which is
672       // structurally identical to the newly refined type.  If so, this type
673       // gets refined to the pre-existing type.
674       //
675       std::multimap<unsigned, PATypeHolder>::iterator I,E, Entry;
676       tie(I, E) = TypesByHash.equal_range(TypeHash);
677       Entry = E;
678       for (; I != E; ++I) {
679         if (I->second != Ty) {
680           if (TypesEqual(Ty, I->second)) {
681             assert(Ty->isAbstract() && "Replacing a non-abstract type?");
682             TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
683             
684             if (Entry == E) {
685               // Find the location of Ty in the TypesByHash structure.
686               while (I->second != Ty) {
687                 ++I;
688                 assert(I != E && "Structure doesn't contain type??");
689               }
690               Entry = I;
691             }
692
693             TypesByHash.erase(Entry);
694             Ty->refineAbstractTypeTo(NewTy);
695             return;
696           }
697         } else {
698           // Remember the position of 
699           Entry = I;
700         }
701       }
702     }
703
704     // If we succeeded, we need to insert the type into the cycletypes table.
705     // There are several cases here, depending on whether the original type
706     // had the same hash code and was itself cyclic.
707     if (TypeHash != OldTypeHash) {
708       RemoveFromTypesByHash(OldTypeHash, Ty);
709       TypesByHash.insert(std::make_pair(TypeHash, Ty));
710     }
711
712     // If there is no existing type of the same structure, we reinsert an
713     // updated record into the map.
714     Map.insert(std::make_pair(ValType::get(Ty), Ty));
715
716     // If the type is currently thought to be abstract, rescan all of our
717     // subtypes to see if the type has just become concrete!
718     if (Ty->isAbstract()) {
719       Ty->setAbstract(Ty->isTypeAbstract());
720
721       // If the type just became concrete, notify all users!
722       if (!Ty->isAbstract())
723         Ty->notifyUsesThatTypeBecameConcrete();
724     }
725   }
726   
727   void print(const char *Arg) const {
728 #ifdef DEBUG_MERGE_TYPES
729     std::cerr << "TypeMap<>::" << Arg << " table contents:\n";
730     unsigned i = 0;
731     for (typename std::map<ValType, PATypeHolder>::const_iterator I
732            = Map.begin(), E = Map.end(); I != E; ++I)
733       std::cerr << " " << (++i) << ". " << (void*)I->second.get() << " " 
734                 << *I->second.get() << "\n";
735 #endif
736   }
737
738   void dump() const { print("dump output"); }
739 };
740 }
741
742
743 //===----------------------------------------------------------------------===//
744 // Function Type Factory and Value Class...
745 //
746
747 // FunctionValType - Define a class to hold the key that goes into the TypeMap
748 //
749 namespace llvm {
750 class FunctionValType {
751   const Type *RetTy;
752   std::vector<const Type*> ArgTypes;
753   bool isVarArg;
754 public:
755   FunctionValType(const Type *ret, const std::vector<const Type*> &args,
756                   bool IVA) : RetTy(ret), isVarArg(IVA) {
757     for (unsigned i = 0; i < args.size(); ++i)
758       ArgTypes.push_back(args[i]);
759   }
760
761   static FunctionValType get(const FunctionType *FT);
762
763   static unsigned hashTypeStructure(const FunctionType *FT) {
764     return FT->getNumParams()*2+FT->isVarArg();
765   }
766
767   // Subclass should override this... to update self as usual
768   void doRefinement(const DerivedType *OldType, const Type *NewType) {
769     if (RetTy == OldType) RetTy = NewType;
770     for (unsigned i = 0, e = ArgTypes.size(); i != e; ++i)
771       if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
772   }
773
774   inline bool operator<(const FunctionValType &MTV) const {
775     if (RetTy < MTV.RetTy) return true;
776     if (RetTy > MTV.RetTy) return false;
777
778     if (ArgTypes < MTV.ArgTypes) return true;
779     return ArgTypes == MTV.ArgTypes && isVarArg < MTV.isVarArg;
780   }
781 };
782 }
783
784 // Define the actual map itself now...
785 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
786
787 FunctionValType FunctionValType::get(const FunctionType *FT) {
788   // Build up a FunctionValType
789   std::vector<const Type *> ParamTypes;
790   ParamTypes.reserve(FT->getNumParams());
791   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
792     ParamTypes.push_back(FT->getParamType(i));
793   return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
794 }
795
796
797 // FunctionType::get - The factory function for the FunctionType class...
798 FunctionType *FunctionType::get(const Type *ReturnType, 
799                                 const std::vector<const Type*> &Params,
800                                 bool isVarArg) {
801   FunctionValType VT(ReturnType, Params, isVarArg);
802   FunctionType *MT = FunctionTypes.get(VT);
803   if (MT) return MT;
804
805   FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
806
807 #ifdef DEBUG_MERGE_TYPES
808   std::cerr << "Derived new type: " << MT << "\n";
809 #endif
810   return MT;
811 }
812
813 //===----------------------------------------------------------------------===//
814 // Array Type Factory...
815 //
816 namespace llvm {
817 class ArrayValType {
818   const Type *ValTy;
819   unsigned Size;
820 public:
821   ArrayValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
822
823   static ArrayValType get(const ArrayType *AT) {
824     return ArrayValType(AT->getElementType(), AT->getNumElements());
825   }
826
827   static unsigned hashTypeStructure(const ArrayType *AT) {
828     return AT->getNumElements();
829   }
830
831   // Subclass should override this... to update self as usual
832   void doRefinement(const DerivedType *OldType, const Type *NewType) {
833     assert(ValTy == OldType);
834     ValTy = NewType;
835   }
836
837   inline bool operator<(const ArrayValType &MTV) const {
838     if (Size < MTV.Size) return true;
839     return Size == MTV.Size && ValTy < MTV.ValTy;
840   }
841 };
842 }
843 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
844
845
846 ArrayType *ArrayType::get(const Type *ElementType, unsigned NumElements) {
847   assert(ElementType && "Can't get array of null types!");
848
849   ArrayValType AVT(ElementType, NumElements);
850   ArrayType *AT = ArrayTypes.get(AVT);
851   if (AT) return AT;           // Found a match, return it!
852
853   // Value not found.  Derive a new type!
854   ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
855
856 #ifdef DEBUG_MERGE_TYPES
857   std::cerr << "Derived new type: " << *AT << "\n";
858 #endif
859   return AT;
860 }
861
862 //===----------------------------------------------------------------------===//
863 // Struct Type Factory...
864 //
865
866 namespace llvm {
867 // StructValType - Define a class to hold the key that goes into the TypeMap
868 //
869 class StructValType {
870   std::vector<const Type*> ElTypes;
871 public:
872   StructValType(const std::vector<const Type*> &args) : ElTypes(args) {}
873
874   static StructValType get(const StructType *ST) {
875     std::vector<const Type *> ElTypes;
876     ElTypes.reserve(ST->getNumElements());
877     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
878       ElTypes.push_back(ST->getElementType(i));
879     
880     return StructValType(ElTypes);
881   }
882
883   static unsigned hashTypeStructure(const StructType *ST) {
884     return ST->getNumElements();
885   }
886
887   // Subclass should override this... to update self as usual
888   void doRefinement(const DerivedType *OldType, const Type *NewType) {
889     for (unsigned i = 0; i < ElTypes.size(); ++i)
890       if (ElTypes[i] == OldType) ElTypes[i] = NewType;
891   }
892
893   inline bool operator<(const StructValType &STV) const {
894     return ElTypes < STV.ElTypes;
895   }
896 };
897 }
898
899 static TypeMap<StructValType, StructType> StructTypes;
900
901 StructType *StructType::get(const std::vector<const Type*> &ETypes) {
902   StructValType STV(ETypes);
903   StructType *ST = StructTypes.get(STV);
904   if (ST) return ST;
905
906   // Value not found.  Derive a new type!
907   StructTypes.add(STV, ST = new StructType(ETypes));
908
909 #ifdef DEBUG_MERGE_TYPES
910   std::cerr << "Derived new type: " << *ST << "\n";
911 #endif
912   return ST;
913 }
914
915
916
917 //===----------------------------------------------------------------------===//
918 // Pointer Type Factory...
919 //
920
921 // PointerValType - Define a class to hold the key that goes into the TypeMap
922 //
923 namespace llvm {
924 class PointerValType {
925   const Type *ValTy;
926 public:
927   PointerValType(const Type *val) : ValTy(val) {}
928
929   static PointerValType get(const PointerType *PT) {
930     return PointerValType(PT->getElementType());
931   }
932
933   static unsigned hashTypeStructure(const PointerType *PT) {
934     return 0;
935   }
936
937   // Subclass should override this... to update self as usual
938   void doRefinement(const DerivedType *OldType, const Type *NewType) {
939     assert(ValTy == OldType);
940     ValTy = NewType;
941   }
942
943   bool operator<(const PointerValType &MTV) const {
944     return ValTy < MTV.ValTy;
945   }
946 };
947 }
948
949 static TypeMap<PointerValType, PointerType> PointerTypes;
950
951 PointerType *PointerType::get(const Type *ValueType) {
952   assert(ValueType && "Can't get a pointer to <null> type!");
953   PointerValType PVT(ValueType);
954
955   PointerType *PT = PointerTypes.get(PVT);
956   if (PT) return PT;
957
958   // Value not found.  Derive a new type!
959   PointerTypes.add(PVT, PT = new PointerType(ValueType));
960
961 #ifdef DEBUG_MERGE_TYPES
962   std::cerr << "Derived new type: " << *PT << "\n";
963 #endif
964   return PT;
965 }
966
967
968 //===----------------------------------------------------------------------===//
969 //                     Derived Type Refinement Functions
970 //===----------------------------------------------------------------------===//
971
972 // removeAbstractTypeUser - Notify an abstract type that a user of the class
973 // no longer has a handle to the type.  This function is called primarily by
974 // the PATypeHandle class.  When there are no users of the abstract type, it
975 // is annihilated, because there is no way to get a reference to it ever again.
976 //
977 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
978   // Search from back to front because we will notify users from back to
979   // front.  Also, it is likely that there will be a stack like behavior to
980   // users that register and unregister users.
981   //
982   unsigned i;
983   for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
984     assert(i != 0 && "AbstractTypeUser not in user list!");
985
986   --i;  // Convert to be in range 0 <= i < size()
987   assert(i < AbstractTypeUsers.size() && "Index out of range!");  // Wraparound?
988
989   AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
990       
991 #ifdef DEBUG_MERGE_TYPES
992   std::cerr << "  remAbstractTypeUser[" << (void*)this << ", "
993             << *this << "][" << i << "] User = " << U << "\n";
994 #endif
995     
996   if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
997 #ifdef DEBUG_MERGE_TYPES
998     std::cerr << "DELETEing unused abstract type: <" << *this
999               << ">[" << (void*)this << "]" << "\n";
1000 #endif
1001     delete this;                  // No users of this abstract type!
1002   }
1003 }
1004
1005
1006 // refineAbstractTypeTo - This function is used to when it is discovered that
1007 // the 'this' abstract type is actually equivalent to the NewType specified.
1008 // This causes all users of 'this' to switch to reference the more concrete type
1009 // NewType and for 'this' to be deleted.
1010 //
1011 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1012   assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1013   assert(this != NewType && "Can't refine to myself!");
1014   assert(ForwardType == 0 && "This type has already been refined!");
1015
1016   // The descriptions may be out of date.  Conservatively clear them all!
1017   AbstractTypeDescriptions.clear();
1018
1019 #ifdef DEBUG_MERGE_TYPES
1020   std::cerr << "REFINING abstract type [" << (void*)this << " "
1021             << *this << "] to [" << (void*)NewType << " "
1022             << *NewType << "]!\n";
1023 #endif
1024
1025   // Make sure to put the type to be refined to into a holder so that if IT gets
1026   // refined, that we will not continue using a dead reference...
1027   //
1028   PATypeHolder NewTy(NewType);
1029
1030   // Any PATypeHolders referring to this type will now automatically forward to
1031   // the type we are resolved to.
1032   ForwardType = NewType;
1033   if (NewType->isAbstract())
1034     cast<DerivedType>(NewType)->addRef();
1035
1036   // Add a self use of the current type so that we don't delete ourself until
1037   // after the function exits.
1038   //
1039   PATypeHolder CurrentTy(this);
1040
1041   // To make the situation simpler, we ask the subclass to remove this type from
1042   // the type map, and to replace any type uses with uses of non-abstract types.
1043   // This dramatically limits the amount of recursive type trouble we can find
1044   // ourselves in.
1045   dropAllTypeUses();
1046
1047   // Iterate over all of the uses of this type, invoking callback.  Each user
1048   // should remove itself from our use list automatically.  We have to check to
1049   // make sure that NewTy doesn't _become_ 'this'.  If it does, resolving types
1050   // will not cause users to drop off of the use list.  If we resolve to ourself
1051   // we succeed!
1052   //
1053   while (!AbstractTypeUsers.empty() && NewTy != this) {
1054     AbstractTypeUser *User = AbstractTypeUsers.back();
1055
1056     unsigned OldSize = AbstractTypeUsers.size();
1057 #ifdef DEBUG_MERGE_TYPES
1058     std::cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
1059               << "] of abstract type [" << (void*)this << " "
1060               << *this << "] to [" << (void*)NewTy.get() << " "
1061               << *NewTy << "]!\n";
1062 #endif
1063     User->refineAbstractType(this, NewTy);
1064
1065     assert(AbstractTypeUsers.size() != OldSize &&
1066            "AbsTyUser did not remove self from user list!");
1067   }
1068
1069   // If we were successful removing all users from the type, 'this' will be
1070   // deleted when the last PATypeHolder is destroyed or updated from this type.
1071   // This may occur on exit of this function, as the CurrentTy object is
1072   // destroyed.
1073 }
1074
1075 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1076 // the current type has transitioned from being abstract to being concrete.
1077 //
1078 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1079 #ifdef DEBUG_MERGE_TYPES
1080   std::cerr << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1081 #endif
1082
1083   unsigned OldSize = AbstractTypeUsers.size();
1084   while (!AbstractTypeUsers.empty()) {
1085     AbstractTypeUser *ATU = AbstractTypeUsers.back();
1086     ATU->typeBecameConcrete(this);
1087
1088     assert(AbstractTypeUsers.size() < OldSize-- &&
1089            "AbstractTypeUser did not remove itself from the use list!");
1090   }
1091 }
1092   
1093
1094
1095
1096 // refineAbstractType - Called when a contained type is found to be more
1097 // concrete - this could potentially change us from an abstract type to a
1098 // concrete type.
1099 //
1100 void FunctionType::refineAbstractType(const DerivedType *OldType,
1101                                       const Type *NewType) {
1102   FunctionTypes.finishRefinement(this, OldType, NewType);
1103 }
1104
1105 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1106   refineAbstractType(AbsTy, AbsTy);
1107 }
1108
1109
1110 // refineAbstractType - Called when a contained type is found to be more
1111 // concrete - this could potentially change us from an abstract type to a
1112 // concrete type.
1113 //
1114 void ArrayType::refineAbstractType(const DerivedType *OldType,
1115                                    const Type *NewType) {
1116   ArrayTypes.finishRefinement(this, OldType, NewType);
1117 }
1118
1119 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1120   refineAbstractType(AbsTy, AbsTy);
1121 }
1122
1123
1124 // refineAbstractType - Called when a contained type is found to be more
1125 // concrete - this could potentially change us from an abstract type to a
1126 // concrete type.
1127 //
1128 void StructType::refineAbstractType(const DerivedType *OldType,
1129                                     const Type *NewType) {
1130   StructTypes.finishRefinement(this, OldType, NewType);
1131 }
1132
1133 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1134   refineAbstractType(AbsTy, AbsTy);
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 PointerType::refineAbstractType(const DerivedType *OldType,
1142                                      const Type *NewType) {
1143   PointerTypes.finishRefinement(this, OldType, NewType);
1144 }
1145
1146 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1147   refineAbstractType(AbsTy, AbsTy);
1148 }
1149
1150 bool SequentialType::indexValid(const Value *V) const {
1151   const Type *Ty = V->getType();
1152   switch (Ty->getTypeID()) {
1153   case Type::IntTyID:
1154   case Type::UIntTyID:
1155   case Type::LongTyID:
1156   case Type::ULongTyID:
1157     return true;
1158   default:
1159     return false;
1160   }
1161 }
1162
1163 namespace llvm {
1164 std::ostream &operator<<(std::ostream &OS, const Type *T) {
1165   if (T == 0)
1166     OS << "<null> value!\n";
1167   else
1168     T->print(OS);
1169   return OS;
1170 }
1171
1172 std::ostream &operator<<(std::ostream &OS, const Type &T) {
1173   T.print(OS);
1174   return OS;
1175 }
1176 }
1177
1178 // vim: sw=2