1 //===-- Type.cpp - Implement the Type class ----------------------*- C++ -*--=//
3 // This file implements the Type class for the VMCore library.
5 //===----------------------------------------------------------------------===//
7 #include "llvm/DerivedTypes.h"
8 #include "llvm/SymbolTable.h"
9 #include "Support/StringExtras.h"
10 #include "Support/STLExtras.h"
12 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
13 // created and later destroyed, all in an effort to make sure that there is only
14 // a single cannonical version of a type.
16 //#define DEBUG_MERGE_TYPES 1
20 //===----------------------------------------------------------------------===//
21 // Type Class Implementation
22 //===----------------------------------------------------------------------===//
24 static unsigned CurUID = 0;
25 static vector<const Type *> UIDMappings;
27 Type::Type(const string &name, PrimitiveID id)
28 : Value(Type::TypeTy, Value::TypeVal) {
31 Abstract = Recursive = false;
32 UID = CurUID++; // Assign types UID's as they are created
33 UIDMappings.push_back(this);
36 void Type::setName(const string &Name, SymbolTable *ST) {
37 assert(ST && "Type::setName - Must provide symbol table argument!");
39 if (Name.size()) ST->insert(Name, this);
43 const Type *Type::getUniqueIDType(unsigned UID) {
44 assert(UID < UIDMappings.size() &&
45 "Type::getPrimitiveType: UID out of range!");
46 return UIDMappings[UID];
49 const Type *Type::getPrimitiveType(PrimitiveID IDNumber) {
51 case VoidTyID : return VoidTy;
52 case BoolTyID : return BoolTy;
53 case UByteTyID : return UByteTy;
54 case SByteTyID : return SByteTy;
55 case UShortTyID: return UShortTy;
56 case ShortTyID : return ShortTy;
57 case UIntTyID : return UIntTy;
58 case IntTyID : return IntTy;
59 case ULongTyID : return ULongTy;
60 case LongTyID : return LongTy;
61 case FloatTyID : return FloatTy;
62 case DoubleTyID: return DoubleTy;
63 case TypeTyID : return TypeTy;
64 case LabelTyID : return LabelTy;
70 // isLosslesslyConvertableTo - Return true if this type can be converted to
71 // 'Ty' without any reinterpretation of bits. For example, uint to int.
73 bool Type::isLosslesslyConvertableTo(const Type *Ty) const {
74 if (this == Ty) return true;
75 if ((!isPrimitiveType() && !Ty->isPointerType()) ||
76 (!isPointerType() && !Ty->isPrimitiveType())) return false;
78 if (getPrimitiveID() == Ty->getPrimitiveID())
79 return true; // Handles identity cast, and cast of differing pointer types
81 // Now we know that they are two differing primitive or pointer types
82 switch (getPrimitiveID()) {
83 case Type::UByteTyID: return Ty == Type::SByteTy;
84 case Type::SByteTyID: return Ty == Type::UByteTy;
85 case Type::UShortTyID: return Ty == Type::ShortTy;
86 case Type::ShortTyID: return Ty == Type::UShortTy;
87 case Type::UIntTyID: return Ty == Type::IntTy;
88 case Type::IntTyID: return Ty == Type::UIntTy;
91 case Type::PointerTyID:
92 return Ty == Type::ULongTy || Ty == Type::LongTy ||
93 Ty->getPrimitiveID() == Type::PointerTyID;
95 return false; // Other types have no identity values
100 bool StructType::indexValid(const Value *V) const {
101 if (!isa<Constant>(V)) return false;
102 if (V->getType() != Type::UByteTy) return false;
103 unsigned Idx = cast<ConstantUInt>(V)->getValue();
104 return Idx < ETypes.size();
107 // getTypeAtIndex - Given an index value into the type, return the type of the
108 // element. For a structure type, this must be a constant value...
110 const Type *StructType::getTypeAtIndex(const Value *V) const {
111 assert(isa<Constant>(V) && "Structure index must be a constant!!");
112 assert(V->getType() == Type::UByteTy && "Structure index must be ubyte!");
113 unsigned Idx = cast<ConstantUInt>(V)->getValue();
114 assert(Idx < ETypes.size() && "Structure index out of range!");
115 assert(indexValid(V) && "Invalid structure index!"); // Duplicate check
121 //===----------------------------------------------------------------------===//
122 // Auxilliary classes
123 //===----------------------------------------------------------------------===//
125 // These classes are used to implement specialized behavior for each different
128 class SignedIntType : public Type {
131 SignedIntType(const string &Name, PrimitiveID id, int size) : Type(Name, id) {
135 // isSigned - Return whether a numeric type is signed.
136 virtual bool isSigned() const { return 1; }
138 // isIntegral - Equivalent to isSigned() || isUnsigned, but with only a single
139 // virtual function invocation.
141 virtual bool isIntegral() const { return 1; }
144 class UnsignedIntType : public Type {
147 UnsignedIntType(const string &N, PrimitiveID id, int size) : Type(N, id) {
151 // isUnsigned - Return whether a numeric type is signed.
152 virtual bool isUnsigned() const { return 1; }
154 // isIntegral - Equivalent to isSigned() || isUnsigned, but with only a single
155 // virtual function invocation.
157 virtual bool isIntegral() const { return 1; }
160 static struct TypeType : public Type {
161 TypeType() : Type("type", TypeTyID) {}
162 } TheTypeType; // Implement the type that is global.
165 //===----------------------------------------------------------------------===//
166 // Static 'Type' data
167 //===----------------------------------------------------------------------===//
169 Type *Type::VoidTy = new Type("void" , VoidTyID),
170 *Type::BoolTy = new Type("bool" , BoolTyID),
171 *Type::SByteTy = new SignedIntType("sbyte" , SByteTyID, 1),
172 *Type::UByteTy = new UnsignedIntType("ubyte" , UByteTyID, 1),
173 *Type::ShortTy = new SignedIntType("short" , ShortTyID, 2),
174 *Type::UShortTy = new UnsignedIntType("ushort", UShortTyID, 2),
175 *Type::IntTy = new SignedIntType("int" , IntTyID, 4),
176 *Type::UIntTy = new UnsignedIntType("uint" , UIntTyID, 4),
177 *Type::LongTy = new SignedIntType("long" , LongTyID, 8),
178 *Type::ULongTy = new UnsignedIntType("ulong" , ULongTyID, 8),
179 *Type::FloatTy = new Type("float" , FloatTyID),
180 *Type::DoubleTy = new Type("double", DoubleTyID),
181 *Type::TypeTy = &TheTypeType,
182 *Type::LabelTy = new Type("label" , LabelTyID);
185 //===----------------------------------------------------------------------===//
186 // Derived Type Constructors
187 //===----------------------------------------------------------------------===//
189 MethodType::MethodType(const Type *Result, const vector<const Type*> &Params,
190 bool IsVarArgs) : DerivedType("", MethodTyID),
191 ResultType(PATypeHandle<Type>(Result, this)),
192 isVarArgs(IsVarArgs) {
193 ParamTys.reserve(Params.size());
194 for (unsigned i = 0; i < Params.size(); ++i)
195 ParamTys.push_back(PATypeHandle<Type>(Params[i], this));
197 setDerivedTypeProperties();
200 ArrayType::ArrayType(const Type *ElType, int NumEl)
201 : CompositeType("", ArrayTyID), ElementType(PATypeHandle<Type>(ElType, this)){
203 setDerivedTypeProperties();
206 StructType::StructType(const vector<const Type*> &Types)
207 : CompositeType("", StructTyID) {
208 ETypes.reserve(Types.size());
209 for (unsigned i = 0; i < Types.size(); ++i) {
210 assert(Types[i] != Type::VoidTy && "Void type in method prototype!!");
211 ETypes.push_back(PATypeHandle<Type>(Types[i], this));
213 setDerivedTypeProperties();
216 PointerType::PointerType(const Type *E) : DerivedType("", PointerTyID),
217 ValueType(PATypeHandle<Type>(E, this)) {
218 setDerivedTypeProperties();
221 OpaqueType::OpaqueType() : DerivedType("", OpaqueTyID) {
223 setDescription("opaque"+utostr(getUniqueID()));
224 #ifdef DEBUG_MERGE_TYPES
225 cerr << "Derived new type: " << getDescription() << endl;
232 //===----------------------------------------------------------------------===//
233 // Derived Type setDerivedTypeProperties Function
234 //===----------------------------------------------------------------------===//
236 // getTypeProps - This is a recursive function that walks a type hierarchy
237 // calculating the description for a type and whether or not it is abstract or
238 // recursive. Worst case it will have to do a lot of traversing if you have
239 // some whacko opaque types, but in most cases, it will do some simple stuff
240 // when it hits non-abstract types that aren't recursive.
242 static string getTypeProps(const Type *Ty, vector<const Type *> &TypeStack,
243 bool &isAbstract, bool &isRecursive) {
245 if (!Ty->isAbstract() && !Ty->isRecursive() && // Base case for the recursion
246 Ty->getDescription().size()) {
247 Result = Ty->getDescription(); // Primitive = leaf type
248 } else if (isa<OpaqueType>(Ty)) { // Base case for the recursion
249 Result = Ty->getDescription(); // Opaque = leaf type
250 isAbstract = true; // This whole type is abstract!
252 // Check to see if the Type is already on the stack...
253 unsigned Slot = 0, CurSize = TypeStack.size();
254 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
256 // This is another base case for the recursion. In this case, we know
257 // that we have looped back to a type that we have previously visited.
258 // Generate the appropriate upreference to handle this.
260 if (Slot < CurSize) {
261 Result = "\\" + utostr(CurSize-Slot); // Here's the upreference
262 isRecursive = true; // We know we are recursive
263 } else { // Recursive case: abstract derived type...
264 TypeStack.push_back(Ty); // Add us to the stack..
266 switch (Ty->getPrimitiveID()) {
267 case Type::MethodTyID: {
268 const MethodType *MTy = cast<const MethodType>(Ty);
269 Result = getTypeProps(MTy->getReturnType(), TypeStack,
270 isAbstract, isRecursive)+" (";
271 for (MethodType::ParamTypes::const_iterator
272 I = MTy->getParamTypes().begin(),
273 E = MTy->getParamTypes().end(); I != E; ++I) {
274 if (I != MTy->getParamTypes().begin())
276 Result += getTypeProps(*I, TypeStack, isAbstract, isRecursive);
278 if (MTy->isVarArg()) {
279 if (!MTy->getParamTypes().empty()) Result += ", ";
285 case Type::StructTyID: {
286 const StructType *STy = cast<const StructType>(Ty);
288 for (StructType::ElementTypes::const_iterator
289 I = STy->getElementTypes().begin(),
290 E = STy->getElementTypes().end(); I != E; ++I) {
291 if (I != STy->getElementTypes().begin())
293 Result += getTypeProps(*I, TypeStack, isAbstract, isRecursive);
298 case Type::PointerTyID: {
299 const PointerType *PTy = cast<const PointerType>(Ty);
300 Result = getTypeProps(PTy->getElementType(), TypeStack,
301 isAbstract, isRecursive) + " *";
304 case Type::ArrayTyID: {
305 const ArrayType *ATy = cast<const ArrayType>(Ty);
306 int NumElements = ATy->getNumElements();
308 if (NumElements != -1) Result += itostr(NumElements) + " x ";
309 Result += getTypeProps(ATy->getElementType(), TypeStack,
310 isAbstract, isRecursive) + "]";
314 assert(0 && "Unhandled case in getTypeProps!");
318 TypeStack.pop_back(); // Remove self from stack...
325 // setDerivedTypeProperties - This function is used to calculate the
326 // isAbstract, isRecursive, and the Description settings for a type. The
327 // getTypeProps function does all the dirty work.
329 void DerivedType::setDerivedTypeProperties() {
330 vector<const Type *> TypeStack;
331 bool isAbstract = false, isRecursive = false;
333 setDescription(getTypeProps(this, TypeStack, isAbstract, isRecursive));
334 setAbstract(isAbstract);
335 setRecursive(isRecursive);
339 //===----------------------------------------------------------------------===//
340 // Type Structural Equality Testing
341 //===----------------------------------------------------------------------===//
343 // TypesEqual - Two types are considered structurally equal if they have the
344 // same "shape": Every level and element of the types have identical primitive
345 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
346 // be pointer equals to be equivalent though. This uses an optimistic algorithm
347 // that assumes that two graphs are the same until proven otherwise.
349 static bool TypesEqual(const Type *Ty, const Type *Ty2,
350 map<const Type *, const Type *> &EqTypes) {
351 if (Ty == Ty2) return true;
352 if (Ty->getPrimitiveID() != Ty2->getPrimitiveID()) return false;
353 if (Ty->isPrimitiveType()) return true;
354 if (isa<OpaqueType>(Ty))
355 return false; // Two nonequal opaque types are never equal
357 map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
358 if (It != EqTypes.end())
359 return It->second == Ty2; // Looping back on a type, check for equality
361 // Otherwise, add the mapping to the table to make sure we don't get
362 // recursion on the types...
363 EqTypes.insert(make_pair(Ty, Ty2));
365 // Iterate over the types and make sure the the contents are equivalent...
366 Type::subtype_iterator I = Ty ->subtype_begin(), IE = Ty ->subtype_end();
367 Type::subtype_iterator I2 = Ty2->subtype_begin(), IE2 = Ty2->subtype_end();
368 for (; I != IE && I2 != IE2; ++I, ++I2)
369 if (!TypesEqual(*I, *I2, EqTypes)) return false;
371 // Two really annoying special cases that breaks an otherwise nice simple
372 // algorithm is the fact that arraytypes have sizes that differentiates types,
373 // and that method types can be varargs or not. Consider this now.
374 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
375 if (ATy->getNumElements() != cast<const ArrayType>(Ty2)->getNumElements())
377 } else if (const MethodType *MTy = dyn_cast<MethodType>(Ty)) {
378 if (MTy->isVarArg() != cast<const MethodType>(Ty2)->isVarArg())
382 return I == IE && I2 == IE2; // Types equal if both iterators are done
385 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
386 map<const Type *, const Type *> EqTypes;
387 return TypesEqual(Ty, Ty2, EqTypes);
392 //===----------------------------------------------------------------------===//
393 // Derived Type Factory Functions
394 //===----------------------------------------------------------------------===//
396 // TypeMap - Make sure that only one instance of a particular type may be
397 // created on any given run of the compiler... note that this involves updating
398 // our map if an abstract type gets refined somehow...
400 template<class ValType, class TypeClass>
401 class TypeMap : public AbstractTypeUser {
402 typedef map<ValType, PATypeHandle<TypeClass> > MapTy;
406 ~TypeMap() { print("ON EXIT"); }
408 inline TypeClass *get(const ValType &V) {
409 map<ValType, PATypeHandle<TypeClass> >::iterator I = Map.find(V);
410 // TODO: FIXME: When Types are not CONST.
411 return (I != Map.end()) ? (TypeClass*)I->second.get() : 0;
414 inline void add(const ValType &V, TypeClass *T) {
415 Map.insert(make_pair(V, PATypeHandle<TypeClass>(T, this)));
419 // containsEquivalent - Return true if the typemap contains a type that is
420 // structurally equivalent to the specified type.
422 inline const TypeClass *containsEquivalent(const TypeClass *Ty) {
423 for (MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
424 if (I->second.get() != Ty && TypesEqual(Ty, I->second.get()))
425 return (TypeClass*)I->second.get(); // FIXME TODO when types not const
429 // refineAbstractType - This is called when one of the contained abstract
430 // types gets refined... this simply removes the abstract type from our table.
431 // We expect that whoever refined the type will add it back to the table,
434 virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
435 if (OldTy == NewTy) {
436 if (!OldTy->isAbstract()) {
437 // Check to see if the type just became concrete.
438 // If so, remove self from user list.
439 for (MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
440 if (I->second == OldTy)
441 I->second.removeUserFromConcrete();
445 #ifdef DEBUG_MERGE_TYPES
446 cerr << "Removing Old type from Tab: " << (void*)OldTy << ", "
447 << OldTy->getDescription() << " replacement == " << (void*)NewTy
448 << ", " << NewTy->getDescription() << endl;
450 for (MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
451 if (I->second == OldTy) {
453 print("refineAbstractType after");
456 assert(0 && "Abstract type not found in table!");
459 void remove(const ValType &OldVal) {
460 MapTy::iterator I = Map.find(OldVal);
461 assert(I != Map.end() && "TypeMap::remove, element not found!");
465 void print(const char *Arg) {
466 #ifdef DEBUG_MERGE_TYPES
467 cerr << "TypeMap<>::" << Arg << " table contents:\n";
469 for (MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
470 cerr << " " << (++i) << ". " << I->second << " "
471 << I->second->getDescription() << endl;
477 // ValTypeBase - This is the base class that is used by the various
478 // instantiations of TypeMap. This class is an AbstractType user that notifies
479 // the underlying TypeMap when it gets modified.
481 template<class ValType, class TypeClass>
482 class ValTypeBase : public AbstractTypeUser {
483 TypeMap<ValType, TypeClass> &MyTable;
485 inline ValTypeBase(TypeMap<ValType, TypeClass> &tab) : MyTable(tab) {}
487 // Subclass should override this... to update self as usual
488 virtual void doRefinement(const DerivedType *OldTy, const Type *NewTy) = 0;
490 // typeBecameConcrete - This callback occurs when a contained type refines
491 // to itself, but becomes concrete in the process. Our subclass should remove
492 // itself from the ATU list of the specified type.
494 virtual void typeBecameConcrete(const DerivedType *Ty) = 0;
496 virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
497 if (OldTy == NewTy) {
498 if (!OldTy->isAbstract())
499 typeBecameConcrete(OldTy);
502 TypeMap<ValType, TypeClass> &Table = MyTable; // Copy MyTable reference
503 ValType Tmp(*(ValType*)this); // Copy this.
504 PATypeHandle<TypeClass> OldType(Table.get(*(ValType*)this), this);
505 Table.remove(*(ValType*)this); // Destroy's this!
507 // Refine temporary to new state...
508 Tmp.doRefinement(OldTy, NewTy);
510 Table.add((ValType&)Tmp, (TypeClass*)OldType.get());
517 //===----------------------------------------------------------------------===//
518 // Method Type Factory and Value Class...
521 // MethodValType - Define a class to hold the key that goes into the TypeMap
523 class MethodValType : public ValTypeBase<MethodValType, MethodType> {
524 PATypeHandle<Type> RetTy;
525 vector<PATypeHandle<Type> > ArgTypes;
528 MethodValType(const Type *ret, const vector<const Type*> &args,
529 bool IVA, TypeMap<MethodValType, MethodType> &Tab)
530 : ValTypeBase<MethodValType, MethodType>(Tab), RetTy(ret, this),
532 for (unsigned i = 0; i < args.size(); ++i)
533 ArgTypes.push_back(PATypeHandle<Type>(args[i], this));
536 // We *MUST* have an explicit copy ctor so that the TypeHandles think that
537 // this MethodValType owns them, not the old one!
539 MethodValType(const MethodValType &MVT)
540 : ValTypeBase<MethodValType, MethodType>(MVT), RetTy(MVT.RetTy, this),
541 isVarArg(MVT.isVarArg) {
542 ArgTypes.reserve(MVT.ArgTypes.size());
543 for (unsigned i = 0; i < MVT.ArgTypes.size(); ++i)
544 ArgTypes.push_back(PATypeHandle<Type>(MVT.ArgTypes[i], this));
547 // Subclass should override this... to update self as usual
548 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
549 if (RetTy == OldType) RetTy = NewType;
550 for (unsigned i = 0; i < ArgTypes.size(); ++i)
551 if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
554 virtual void typeBecameConcrete(const DerivedType *Ty) {
555 if (RetTy == Ty) RetTy.removeUserFromConcrete();
557 for (unsigned i = 0; i < ArgTypes.size(); ++i)
558 if (ArgTypes[i] == Ty) ArgTypes[i].removeUserFromConcrete();
561 inline bool operator<(const MethodValType &MTV) const {
562 if (RetTy.get() < MTV.RetTy.get()) return true;
563 if (RetTy.get() > MTV.RetTy.get()) return false;
565 if (ArgTypes < MTV.ArgTypes) return true;
566 return (ArgTypes == MTV.ArgTypes) && isVarArg < MTV.isVarArg;
570 // Define the actual map itself now...
571 static TypeMap<MethodValType, MethodType> MethodTypes;
573 // MethodType::get - The factory function for the MethodType class...
574 MethodType *MethodType::get(const Type *ReturnType,
575 const vector<const Type*> &Params,
577 MethodValType VT(ReturnType, Params, isVarArg, MethodTypes);
578 MethodType *MT = MethodTypes.get(VT);
581 MethodTypes.add(VT, MT = new MethodType(ReturnType, Params, isVarArg));
583 #ifdef DEBUG_MERGE_TYPES
584 cerr << "Derived new type: " << MT << endl;
589 //===----------------------------------------------------------------------===//
590 // Array Type Factory...
592 class ArrayValType : public ValTypeBase<ArrayValType, ArrayType> {
593 PATypeHandle<Type> ValTy;
596 ArrayValType(const Type *val, int sz, TypeMap<ArrayValType, ArrayType> &Tab)
597 : ValTypeBase<ArrayValType, ArrayType>(Tab), ValTy(val, this), Size(sz) {}
599 // We *MUST* have an explicit copy ctor so that the ValTy thinks that this
600 // ArrayValType owns it, not the old one!
602 ArrayValType(const ArrayValType &AVT)
603 : ValTypeBase<ArrayValType, ArrayType>(AVT), ValTy(AVT.ValTy, this),
606 // Subclass should override this... to update self as usual
607 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
608 if (ValTy == OldType) ValTy = NewType;
611 virtual void typeBecameConcrete(const DerivedType *Ty) {
612 assert(ValTy == Ty &&
613 "Contained type became concrete but we're not using it!");
614 ValTy.removeUserFromConcrete();
617 inline bool operator<(const ArrayValType &MTV) const {
618 if (Size < MTV.Size) return true;
619 return Size == MTV.Size && ValTy.get() < MTV.ValTy.get();
623 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
625 ArrayType *ArrayType::get(const Type *ElementType, int NumElements = -1) {
626 assert(ElementType && "Can't get array of null types!");
628 ArrayValType AVT(ElementType, NumElements, ArrayTypes);
629 ArrayType *AT = ArrayTypes.get(AVT);
630 if (AT) return AT; // Found a match, return it!
632 // Value not found. Derive a new type!
633 ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
635 #ifdef DEBUG_MERGE_TYPES
636 cerr << "Derived new type: " << AT->getDescription() << endl;
641 //===----------------------------------------------------------------------===//
642 // Struct Type Factory...
645 // StructValType - Define a class to hold the key that goes into the TypeMap
647 class StructValType : public ValTypeBase<StructValType, StructType> {
648 vector<PATypeHandle<Type> > ElTypes;
650 StructValType(const vector<const Type*> &args,
651 TypeMap<StructValType, StructType> &Tab)
652 : ValTypeBase<StructValType, StructType>(Tab) {
653 for (unsigned i = 0; i < args.size(); ++i)
654 ElTypes.push_back(PATypeHandle<Type>(args[i], this));
657 // We *MUST* have an explicit copy ctor so that the TypeHandles think that
658 // this StructValType owns them, not the old one!
660 StructValType(const StructValType &SVT)
661 : ValTypeBase<StructValType, StructType>(SVT){
662 ElTypes.reserve(SVT.ElTypes.size());
663 for (unsigned i = 0; i < SVT.ElTypes.size(); ++i)
664 ElTypes.push_back(PATypeHandle<Type>(SVT.ElTypes[i], this));
667 // Subclass should override this... to update self as usual
668 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
669 for (unsigned i = 0; i < ElTypes.size(); ++i)
670 if (ElTypes[i] == OldType) ElTypes[i] = NewType;
673 virtual void typeBecameConcrete(const DerivedType *Ty) {
674 for (unsigned i = 0; i < ElTypes.size(); ++i)
675 if (ElTypes[i] == Ty) ElTypes[i].removeUserFromConcrete();
678 inline bool operator<(const StructValType &STV) const {
679 return ElTypes < STV.ElTypes;
683 static TypeMap<StructValType, StructType> StructTypes;
685 StructType *StructType::get(const vector<const Type*> &ETypes) {
686 StructValType STV(ETypes, StructTypes);
687 StructType *ST = StructTypes.get(STV);
690 // Value not found. Derive a new type!
691 StructTypes.add(STV, ST = new StructType(ETypes));
693 #ifdef DEBUG_MERGE_TYPES
694 cerr << "Derived new type: " << ST->getDescription() << endl;
699 //===----------------------------------------------------------------------===//
700 // Pointer Type Factory...
703 // PointerValType - Define a class to hold the key that goes into the TypeMap
705 class PointerValType : public ValTypeBase<PointerValType, PointerType> {
706 PATypeHandle<Type> ValTy;
708 PointerValType(const Type *val, TypeMap<PointerValType, PointerType> &Tab)
709 : ValTypeBase<PointerValType, PointerType>(Tab), ValTy(val, this) {}
711 // We *MUST* have an explicit copy ctor so that the ValTy thinks that this
712 // PointerValType owns it, not the old one!
714 PointerValType(const PointerValType &PVT)
715 : ValTypeBase<PointerValType, PointerType>(PVT), ValTy(PVT.ValTy, this) {}
717 // Subclass should override this... to update self as usual
718 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
719 if (ValTy == OldType) ValTy = NewType;
722 virtual void typeBecameConcrete(const DerivedType *Ty) {
723 assert(ValTy == Ty &&
724 "Contained type became concrete but we're not using it!");
725 ValTy.removeUserFromConcrete();
728 inline bool operator<(const PointerValType &MTV) const {
729 return ValTy.get() < MTV.ValTy.get();
733 static TypeMap<PointerValType, PointerType> PointerTypes;
735 PointerType *PointerType::get(const Type *ValueType) {
736 assert(ValueType && "Can't get a pointer to <null> type!");
737 PointerValType PVT(ValueType, PointerTypes);
739 PointerType *PT = PointerTypes.get(PVT);
742 // Value not found. Derive a new type!
743 PointerTypes.add(PVT, PT = new PointerType(ValueType));
745 #ifdef DEBUG_MERGE_TYPES
746 cerr << "Derived new type: " << PT->getDescription() << endl;
753 //===----------------------------------------------------------------------===//
754 // Derived Type Refinement Functions
755 //===----------------------------------------------------------------------===//
757 // removeAbstractTypeUser - Notify an abstract type that a user of the class
758 // no longer has a handle to the type. This function is called primarily by
759 // the PATypeHandle class. When there are no users of the abstract type, it
760 // is anihilated, because there is no way to get a reference to it ever again.
762 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
763 // Search from back to front because we will notify users from back to
764 // front. Also, it is likely that there will be a stack like behavior to
765 // users that register and unregister users.
767 for (unsigned i = AbstractTypeUsers.size(); i > 0; --i) {
768 if (AbstractTypeUsers[i-1] == U) {
769 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i-1);
771 #ifdef DEBUG_MERGE_TYPES
772 cerr << " removeAbstractTypeUser<" << (void*)this << ", "
773 << getDescription() << ">[" << i << "] User = " << U << endl;
776 if (AbstractTypeUsers.empty() && isAbstract()) {
777 #ifdef DEBUG_MERGE_TYPES
778 cerr << "DELETEing unused abstract type: <" << getDescription()
779 << ">[" << (void*)this << "]" << endl;
781 delete this; // No users of this abstract type!
786 assert(0 && "AbstractTypeUser not in user list!");
790 // refineAbstractTypeTo - This function is used to when it is discovered that
791 // the 'this' abstract type is actually equivalent to the NewType specified.
792 // This causes all users of 'this' to switch to reference the more concrete
793 // type NewType and for 'this' to be deleted.
795 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
796 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
797 assert(this != NewType && "Can't refine to myself!");
799 #ifdef DEBUG_MERGE_TYPES
800 cerr << "REFINING abstract type [" << (void*)this << " " << getDescription()
801 << "] to [" << (void*)NewType << " " << NewType->getDescription()
806 // Make sure to put the type to be refined to into a holder so that if IT gets
807 // refined, that we will not continue using a dead reference...
809 PATypeHolder<Type> NewTy(NewType);
811 // Add a self use of the current type so that we don't delete ourself until
812 // after this while loop. We are careful to never invoke refine on ourself,
813 // so this extra reference shouldn't be a problem. Note that we must only
814 // remove a single reference at the end, but we must tolerate multiple self
815 // references because we could be refineAbstractTypeTo'ing recursively on the
818 addAbstractTypeUser(this);
820 // Count the number of self uses. Stop looping when sizeof(list) == NSU.
821 unsigned NumSelfUses = 0;
823 // Iterate over all of the uses of this type, invoking callback. Each user
824 // should remove itself from our use list automatically.
826 while (AbstractTypeUsers.size() > NumSelfUses) {
827 AbstractTypeUser *User = AbstractTypeUsers.back();
830 // Move self use to the start of the list. Increment NSU.
831 swap(AbstractTypeUsers.back(), AbstractTypeUsers[NumSelfUses++]);
833 unsigned OldSize = AbstractTypeUsers.size();
834 #ifdef DEBUG_MERGE_TYPES
835 cerr << " REFINING user " << OldSize-1 << " of abstract type ["
836 << (void*)this << " " << getDescription() << "] to ["
837 << (void*)NewTy.get() << " " << NewTy->getDescription() << "]!\n";
839 User->refineAbstractType(this, NewTy);
841 if (AbstractTypeUsers.size() == OldSize) {
842 User->refineAbstractType(this, NewTy);
844 assert(AbstractTypeUsers.size() != OldSize &&
845 "AbsTyUser did not remove self from user list!");
849 // Remove a single self use, even though there may be several here. This will
850 // probably 'delete this', so no instance variables may be used after this
852 assert(AbstractTypeUsers.back() == this && "Only self uses should be left!");
853 removeAbstractTypeUser(this);
857 // typeIsRefined - Notify AbstractTypeUsers of this type that the current type
858 // has been refined a bit. The pointer is still valid and still should be
859 // used, but the subtypes have changed.
861 void DerivedType::typeIsRefined() {
862 assert(isRefining >= 0 && isRefining <= 2 && "isRefining out of bounds!");
863 if (isRefining == 1) return; // Kill recursion here...
866 #ifdef DEBUG_MERGE_TYPES
867 cerr << "typeIsREFINED type: " << (void*)this <<" "<<getDescription() << endl;
869 for (unsigned i = 0; i < AbstractTypeUsers.size(); ) {
870 AbstractTypeUser *ATU = AbstractTypeUsers[i];
871 #ifdef DEBUG_MERGE_TYPES
872 cerr << " typeIsREFINED user " << i << " of abstract type ["
873 << (void*)this << " " << getDescription() << "]\n";
875 ATU->refineAbstractType(this, this);
877 // If the user didn't remove itself from the list, continue...
878 if (AbstractTypeUsers.size() > i && AbstractTypeUsers[i] == ATU) {
886 if (!(isAbstract() || AbstractTypeUsers.empty()))
887 for (unsigned i = 0; i < AbstractTypeUsers.size(); ++i) {
888 if (AbstractTypeUsers[i] != this) {
890 cerr << "FOUND FAILURE\n";
891 AbstractTypeUsers[i]->refineAbstractType(this, this);
892 assert(0 && "Type became concrete,"
893 " but it still has abstract type users hanging around!");
902 // refineAbstractType - Called when a contained type is found to be more
903 // concrete - this could potentially change us from an abstract type to a
906 void MethodType::refineAbstractType(const DerivedType *OldType,
907 const Type *NewType) {
908 #ifdef DEBUG_MERGE_TYPES
909 cerr << "MethodTy::refineAbstractTy(" << (void*)OldType << "["
910 << OldType->getDescription() << "], " << (void*)NewType << " ["
911 << NewType->getDescription() << "])\n";
914 if (!OldType->isAbstract()) {
915 if (ResultType == OldType) ResultType.removeUserFromConcrete();
916 for (unsigned i = 0; i < ParamTys.size(); ++i)
917 if (ParamTys[i] == OldType) ParamTys[i].removeUserFromConcrete();
920 if (OldType != NewType) {
921 if (ResultType == OldType) ResultType = NewType;
923 for (unsigned i = 0; i < ParamTys.size(); ++i)
924 if (ParamTys[i] == OldType) ParamTys[i] = NewType;
927 const MethodType *MT = MethodTypes.containsEquivalent(this);
928 if (MT && MT != this) {
929 refineAbstractTypeTo(MT); // Different type altogether...
931 setDerivedTypeProperties(); // Update the name and isAbstract
932 typeIsRefined(); // Same type, different contents...
937 // refineAbstractType - Called when a contained type is found to be more
938 // concrete - this could potentially change us from an abstract type to a
941 void ArrayType::refineAbstractType(const DerivedType *OldType,
942 const Type *NewType) {
943 #ifdef DEBUG_MERGE_TYPES
944 cerr << "ArrayTy::refineAbstractTy(" << (void*)OldType << "["
945 << OldType->getDescription() << "], " << (void*)NewType << " ["
946 << NewType->getDescription() << "])\n";
949 if (!OldType->isAbstract()) {
950 assert(ElementType == OldType);
951 ElementType.removeUserFromConcrete();
954 ElementType = NewType;
955 const ArrayType *AT = ArrayTypes.containsEquivalent(this);
956 if (AT && AT != this) {
957 refineAbstractTypeTo(AT); // Different type altogether...
959 setDerivedTypeProperties(); // Update the name and isAbstract
960 typeIsRefined(); // Same type, different contents...
965 // refineAbstractType - Called when a contained type is found to be more
966 // concrete - this could potentially change us from an abstract type to a
969 void StructType::refineAbstractType(const DerivedType *OldType,
970 const Type *NewType) {
971 #ifdef DEBUG_MERGE_TYPES
972 cerr << "StructTy::refineAbstractTy(" << (void*)OldType << "["
973 << OldType->getDescription() << "], " << (void*)NewType << " ["
974 << NewType->getDescription() << "])\n";
976 if (!OldType->isAbstract()) {
977 for (unsigned i = 0; i < ETypes.size(); ++i)
978 if (ETypes[i] == OldType)
979 ETypes[i].removeUserFromConcrete();
982 if (OldType != NewType) {
983 // Update old type to new type in the array...
984 for (unsigned i = 0; i < ETypes.size(); ++i)
985 if (ETypes[i] == OldType)
989 const StructType *ST = StructTypes.containsEquivalent(this);
990 if (ST && ST != this) {
991 refineAbstractTypeTo(ST); // Different type altogether...
993 setDerivedTypeProperties(); // Update the name and isAbstract
994 typeIsRefined(); // Same type, different contents...
998 // refineAbstractType - Called when a contained type is found to be more
999 // concrete - this could potentially change us from an abstract type to a
1002 void PointerType::refineAbstractType(const DerivedType *OldType,
1003 const Type *NewType) {
1004 #ifdef DEBUG_MERGE_TYPES
1005 cerr << "PointerTy::refineAbstractTy(" << (void*)OldType << "["
1006 << OldType->getDescription() << "], " << (void*)NewType << " ["
1007 << NewType->getDescription() << "])\n";
1010 if (!OldType->isAbstract()) {
1011 assert(ValueType == OldType);
1012 ValueType.removeUserFromConcrete();
1015 ValueType = NewType;
1016 const PointerType *PT = PointerTypes.containsEquivalent(this);
1018 if (PT && PT != this) {
1019 refineAbstractTypeTo(PT); // Different type altogether...
1021 setDerivedTypeProperties(); // Update the name and isAbstract
1022 typeIsRefined(); // Same type, different contents...