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