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