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