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 "llvm/Constants.h"
10 #include "Support/StringExtras.h"
11 #include "Support/STLExtras.h"
22 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
23 // created and later destroyed, all in an effort to make sure that there is only
24 // a single cannonical version of a type.
26 //#define DEBUG_MERGE_TYPES 1
30 //===----------------------------------------------------------------------===//
31 // Type Class Implementation
32 //===----------------------------------------------------------------------===//
34 static unsigned CurUID = 0;
35 static vector<const Type *> UIDMappings;
37 void PATypeHolder::dump() const {
38 cerr << "PATypeHolder(" << (void*)this << ")\n";
42 Type::Type(const string &name, PrimitiveID id)
43 : Value(Type::TypeTy, Value::TypeVal) {
46 Abstract = Recursive = false;
47 UID = CurUID++; // Assign types UID's as they are created
48 UIDMappings.push_back(this);
51 void Type::setName(const string &Name, SymbolTable *ST) {
52 assert(ST && "Type::setName - Must provide symbol table argument!");
54 if (Name.size()) ST->insert(Name, this);
58 const Type *Type::getUniqueIDType(unsigned UID) {
59 assert(UID < UIDMappings.size() &&
60 "Type::getPrimitiveType: UID out of range!");
61 return UIDMappings[UID];
64 const Type *Type::getPrimitiveType(PrimitiveID IDNumber) {
66 case VoidTyID : return VoidTy;
67 case BoolTyID : return BoolTy;
68 case UByteTyID : return UByteTy;
69 case SByteTyID : return SByteTy;
70 case UShortTyID: return UShortTy;
71 case ShortTyID : return ShortTy;
72 case UIntTyID : return UIntTy;
73 case IntTyID : return IntTy;
74 case ULongTyID : return ULongTy;
75 case LongTyID : return LongTy;
76 case FloatTyID : return FloatTy;
77 case DoubleTyID: return DoubleTy;
78 case TypeTyID : return TypeTy;
79 case LabelTyID : return LabelTy;
85 // isLosslesslyConvertableTo - Return true if this type can be converted to
86 // 'Ty' without any reinterpretation of bits. For example, uint to int.
88 bool Type::isLosslesslyConvertableTo(const Type *Ty) const {
89 if (this == Ty) return true;
90 if ((!isPrimitiveType() && !isa<PointerType>(this)) ||
91 (!isa<PointerType>(Ty) && !Ty->isPrimitiveType())) return false;
93 if (getPrimitiveID() == Ty->getPrimitiveID())
94 return true; // Handles identity cast, and cast of differing pointer types
96 // Now we know that they are two differing primitive or pointer types
97 switch (getPrimitiveID()) {
98 case Type::UByteTyID: return Ty == Type::SByteTy;
99 case Type::SByteTyID: return Ty == Type::UByteTy;
100 case Type::UShortTyID: return Ty == Type::ShortTy;
101 case Type::ShortTyID: return Ty == Type::UShortTy;
102 case Type::UIntTyID: return Ty == Type::IntTy;
103 case Type::IntTyID: return Ty == Type::UIntTy;
104 case Type::ULongTyID:
106 case Type::PointerTyID:
107 return Ty == Type::ULongTy || Ty == Type::LongTy || isa<PointerType>(Ty);
109 return false; // Other types have no identity values
113 // getPrimitiveSize - Return the basic size of this type if it is a primative
114 // type. These are fixed by LLVM and are not target dependant. This will
115 // return zero if the type does not have a size or is not a primitive type.
117 unsigned Type::getPrimitiveSize() const {
118 switch (getPrimitiveID()) {
119 #define HANDLE_PRIM_TYPE(TY,SIZE) case TY##TyID: return SIZE;
120 #include "llvm/Type.def"
126 bool StructType::indexValid(const Value *V) const {
127 if (!isa<Constant>(V)) return false;
128 if (V->getType() != Type::UByteTy) return false;
129 unsigned Idx = cast<ConstantUInt>(V)->getValue();
130 return Idx < ETypes.size();
133 // getTypeAtIndex - Given an index value into the type, return the type of the
134 // element. For a structure type, this must be a constant value...
136 const Type *StructType::getTypeAtIndex(const Value *V) const {
137 assert(isa<Constant>(V) && "Structure index must be a constant!!");
138 assert(V->getType() == Type::UByteTy && "Structure index must be ubyte!");
139 unsigned Idx = cast<ConstantUInt>(V)->getValue();
140 assert(Idx < ETypes.size() && "Structure index out of range!");
141 assert(indexValid(V) && "Invalid structure index!"); // Duplicate check
147 //===----------------------------------------------------------------------===//
148 // Auxilliary classes
149 //===----------------------------------------------------------------------===//
151 // These classes are used to implement specialized behavior for each different
154 struct SignedIntType : public Type {
155 SignedIntType(const string &Name, PrimitiveID id) : Type(Name, id) {}
157 // isSigned - Return whether a numeric type is signed.
158 virtual bool isSigned() const { return 1; }
160 // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
161 // virtual function invocation.
163 virtual bool isInteger() const { return 1; }
166 struct UnsignedIntType : public Type {
167 UnsignedIntType(const string &N, PrimitiveID id) : Type(N, id) {}
169 // isUnsigned - Return whether a numeric type is signed.
170 virtual bool isUnsigned() const { return 1; }
172 // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
173 // virtual function invocation.
175 virtual bool isInteger() const { return 1; }
178 static struct TypeType : public Type {
179 TypeType() : Type("type", TypeTyID) {}
180 } TheTypeType; // Implement the type that is global.
183 //===----------------------------------------------------------------------===//
184 // Static 'Type' data
185 //===----------------------------------------------------------------------===//
187 Type *Type::VoidTy = new Type("void" , VoidTyID),
188 *Type::BoolTy = new Type("bool" , BoolTyID),
189 *Type::SByteTy = new SignedIntType("sbyte" , SByteTyID),
190 *Type::UByteTy = new UnsignedIntType("ubyte" , UByteTyID),
191 *Type::ShortTy = new SignedIntType("short" , ShortTyID),
192 *Type::UShortTy = new UnsignedIntType("ushort", UShortTyID),
193 *Type::IntTy = new SignedIntType("int" , IntTyID),
194 *Type::UIntTy = new UnsignedIntType("uint" , UIntTyID),
195 *Type::LongTy = new SignedIntType("long" , LongTyID),
196 *Type::ULongTy = new UnsignedIntType("ulong" , ULongTyID),
197 *Type::FloatTy = new Type("float" , FloatTyID),
198 *Type::DoubleTy = new Type("double", DoubleTyID),
199 *Type::TypeTy = &TheTypeType,
200 *Type::LabelTy = new Type("label" , LabelTyID);
203 //===----------------------------------------------------------------------===//
204 // Derived Type Constructors
205 //===----------------------------------------------------------------------===//
207 FunctionType::FunctionType(const Type *Result,
208 const vector<const Type*> &Params,
209 bool IsVarArgs) : DerivedType(FunctionTyID),
210 ResultType(PATypeHandle<Type>(Result, this)),
211 isVarArgs(IsVarArgs) {
212 ParamTys.reserve(Params.size());
213 for (unsigned i = 0; i < Params.size(); ++i)
214 ParamTys.push_back(PATypeHandle<Type>(Params[i], this));
216 setDerivedTypeProperties();
219 StructType::StructType(const vector<const Type*> &Types)
220 : CompositeType(StructTyID) {
221 ETypes.reserve(Types.size());
222 for (unsigned i = 0; i < Types.size(); ++i) {
223 assert(Types[i] != Type::VoidTy && "Void type in method prototype!!");
224 ETypes.push_back(PATypeHandle<Type>(Types[i], this));
226 setDerivedTypeProperties();
229 ArrayType::ArrayType(const Type *ElType, unsigned NumEl)
230 : SequentialType(ArrayTyID, ElType) {
232 setDerivedTypeProperties();
235 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
236 setDerivedTypeProperties();
239 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
241 setDescription("opaque"+utostr(getUniqueID()));
242 #ifdef DEBUG_MERGE_TYPES
243 cerr << "Derived new type: " << getDescription() << endl;
250 //===----------------------------------------------------------------------===//
251 // Derived Type setDerivedTypeProperties Function
252 //===----------------------------------------------------------------------===//
254 // getTypeProps - This is a recursive function that walks a type hierarchy
255 // calculating the description for a type and whether or not it is abstract or
256 // recursive. Worst case it will have to do a lot of traversing if you have
257 // some whacko opaque types, but in most cases, it will do some simple stuff
258 // when it hits non-abstract types that aren't recursive.
260 static string getTypeProps(const Type *Ty, vector<const Type *> &TypeStack,
261 bool &isAbstract, bool &isRecursive) {
263 if (!Ty->isAbstract() && !Ty->isRecursive() && // Base case for the recursion
264 Ty->getDescription().size()) {
265 Result = Ty->getDescription(); // Primitive = leaf type
266 } else if (isa<OpaqueType>(Ty)) { // Base case for the recursion
267 Result = Ty->getDescription(); // Opaque = leaf type
268 isAbstract = true; // This whole type is abstract!
270 // Check to see if the Type is already on the stack...
271 unsigned Slot = 0, CurSize = TypeStack.size();
272 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
274 // This is another base case for the recursion. In this case, we know
275 // that we have looped back to a type that we have previously visited.
276 // Generate the appropriate upreference to handle this.
278 if (Slot < CurSize) {
279 Result = "\\" + utostr(CurSize-Slot); // Here's the upreference
280 isRecursive = true; // We know we are recursive
281 } else { // Recursive case: abstract derived type...
282 TypeStack.push_back(Ty); // Add us to the stack..
284 switch (Ty->getPrimitiveID()) {
285 case Type::FunctionTyID: {
286 const FunctionType *MTy = cast<const FunctionType>(Ty);
287 Result = getTypeProps(MTy->getReturnType(), TypeStack,
288 isAbstract, isRecursive)+" (";
289 for (FunctionType::ParamTypes::const_iterator
290 I = MTy->getParamTypes().begin(),
291 E = MTy->getParamTypes().end(); I != E; ++I) {
292 if (I != MTy->getParamTypes().begin())
294 Result += getTypeProps(*I, TypeStack, isAbstract, isRecursive);
296 if (MTy->isVarArg()) {
297 if (!MTy->getParamTypes().empty()) Result += ", ";
303 case Type::StructTyID: {
304 const StructType *STy = cast<const StructType>(Ty);
306 for (StructType::ElementTypes::const_iterator
307 I = STy->getElementTypes().begin(),
308 E = STy->getElementTypes().end(); I != E; ++I) {
309 if (I != STy->getElementTypes().begin())
311 Result += getTypeProps(*I, TypeStack, isAbstract, isRecursive);
316 case Type::PointerTyID: {
317 const PointerType *PTy = cast<const PointerType>(Ty);
318 Result = getTypeProps(PTy->getElementType(), TypeStack,
319 isAbstract, isRecursive) + " *";
322 case Type::ArrayTyID: {
323 const ArrayType *ATy = cast<const ArrayType>(Ty);
324 unsigned NumElements = ATy->getNumElements();
326 Result += utostr(NumElements) + " x ";
327 Result += getTypeProps(ATy->getElementType(), TypeStack,
328 isAbstract, isRecursive) + "]";
332 assert(0 && "Unhandled case in getTypeProps!");
336 TypeStack.pop_back(); // Remove self from stack...
343 // setDerivedTypeProperties - This function is used to calculate the
344 // isAbstract, isRecursive, and the Description settings for a type. The
345 // getTypeProps function does all the dirty work.
347 void DerivedType::setDerivedTypeProperties() {
348 vector<const Type *> TypeStack;
349 bool isAbstract = false, isRecursive = false;
351 setDescription(getTypeProps(this, TypeStack, isAbstract, isRecursive));
352 setAbstract(isAbstract);
353 setRecursive(isRecursive);
357 //===----------------------------------------------------------------------===//
358 // Type Structural Equality Testing
359 //===----------------------------------------------------------------------===//
361 // TypesEqual - Two types are considered structurally equal if they have the
362 // same "shape": Every level and element of the types have identical primitive
363 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
364 // be pointer equals to be equivalent though. This uses an optimistic algorithm
365 // that assumes that two graphs are the same until proven otherwise.
367 static bool TypesEqual(const Type *Ty, const Type *Ty2,
368 map<const Type *, const Type *> &EqTypes) {
369 if (Ty == Ty2) return true;
370 if (Ty->getPrimitiveID() != Ty2->getPrimitiveID()) return false;
371 if (Ty->isPrimitiveType()) return true;
372 if (isa<OpaqueType>(Ty))
373 return false; // Two nonequal opaque types are never equal
375 map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
376 if (It != EqTypes.end())
377 return It->second == Ty2; // Looping back on a type, check for equality
379 // Otherwise, add the mapping to the table to make sure we don't get
380 // recursion on the types...
381 EqTypes.insert(make_pair(Ty, Ty2));
383 // Iterate over the types and make sure the the contents are equivalent...
384 Type::subtype_iterator I = Ty ->subtype_begin(), IE = Ty ->subtype_end();
385 Type::subtype_iterator I2 = Ty2->subtype_begin(), IE2 = Ty2->subtype_end();
386 for (; I != IE && I2 != IE2; ++I, ++I2)
387 if (!TypesEqual(*I, *I2, EqTypes)) return false;
389 // Two really annoying special cases that breaks an otherwise nice simple
390 // algorithm is the fact that arraytypes have sizes that differentiates types,
391 // and that method types can be varargs or not. Consider this now.
392 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
393 if (ATy->getNumElements() != cast<const ArrayType>(Ty2)->getNumElements())
395 } else if (const FunctionType *MTy = dyn_cast<FunctionType>(Ty)) {
396 if (MTy->isVarArg() != cast<const FunctionType>(Ty2)->isVarArg())
400 return I == IE && I2 == IE2; // Types equal if both iterators are done
403 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
404 map<const Type *, const Type *> EqTypes;
405 return TypesEqual(Ty, Ty2, EqTypes);
410 //===----------------------------------------------------------------------===//
411 // Derived Type Factory Functions
412 //===----------------------------------------------------------------------===//
414 // TypeMap - Make sure that only one instance of a particular type may be
415 // created on any given run of the compiler... note that this involves updating
416 // our map if an abstract type gets refined somehow...
418 template<class ValType, class TypeClass>
419 class TypeMap : public AbstractTypeUser {
420 typedef map<ValType, PATypeHandle<TypeClass> > MapTy;
423 ~TypeMap() { print("ON EXIT"); }
425 inline TypeClass *get(const ValType &V) {
426 typename map<ValType, PATypeHandle<TypeClass> >::iterator I = Map.find(V);
427 // TODO: FIXME: When Types are not CONST.
428 return (I != Map.end()) ? (TypeClass*)I->second.get() : 0;
431 inline void add(const ValType &V, TypeClass *T) {
432 Map.insert(make_pair(V, PATypeHandle<TypeClass>(T, this)));
436 // containsEquivalent - Return true if the typemap contains a type that is
437 // structurally equivalent to the specified type.
439 inline const TypeClass *containsEquivalent(const TypeClass *Ty) {
440 for (typename MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
441 if (I->second.get() != Ty && TypesEqual(Ty, I->second.get()))
442 return (TypeClass*)I->second.get(); // FIXME TODO when types not const
446 // refineAbstractType - This is called when one of the contained abstract
447 // types gets refined... this simply removes the abstract type from our table.
448 // We expect that whoever refined the type will add it back to the table,
451 virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
452 #ifdef DEBUG_MERGE_TYPES
453 cerr << "Removing Old type from Tab: " << (void*)OldTy << ", "
454 << OldTy->getDescription() << " replacement == " << (void*)NewTy
455 << ", " << NewTy->getDescription() << endl;
457 for (typename MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
458 if (I->second == OldTy) {
459 // Check to see if the type just became concrete. If so, remove self
461 I->second.removeUserFromConcrete();
462 I->second = cast<TypeClass>(NewTy);
466 void remove(const ValType &OldVal) {
467 typename MapTy::iterator I = Map.find(OldVal);
468 assert(I != Map.end() && "TypeMap::remove, element not found!");
472 void print(const char *Arg) const {
473 #ifdef DEBUG_MERGE_TYPES
474 cerr << "TypeMap<>::" << Arg << " table contents:\n";
476 for (MapTy::const_iterator I = Map.begin(), E = Map.end(); I != E; ++I)
477 cerr << " " << (++i) << ". " << I->second << " "
478 << I->second->getDescription() << endl;
482 void dump() const { print("dump output"); }
486 // ValTypeBase - This is the base class that is used by the various
487 // instantiations of TypeMap. This class is an AbstractType user that notifies
488 // the underlying TypeMap when it gets modified.
490 template<class ValType, class TypeClass>
491 class ValTypeBase : public AbstractTypeUser {
492 TypeMap<ValType, TypeClass> &MyTable;
494 inline ValTypeBase(TypeMap<ValType, TypeClass> &tab) : MyTable(tab) {}
496 // Subclass should override this... to update self as usual
497 virtual void doRefinement(const DerivedType *OldTy, const Type *NewTy) = 0;
499 // typeBecameConcrete - This callback occurs when a contained type refines
500 // to itself, but becomes concrete in the process. Our subclass should remove
501 // itself from the ATU list of the specified type.
503 virtual void typeBecameConcrete(const DerivedType *Ty) = 0;
505 virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
506 assert(OldTy == NewTy || OldTy->isAbstract());
508 if (!OldTy->isAbstract())
509 typeBecameConcrete(OldTy);
511 TypeMap<ValType, TypeClass> &Table = MyTable; // Copy MyTable reference
512 ValType Tmp(*(ValType*)this); // Copy this.
513 PATypeHandle<TypeClass> OldType(Table.get(*(ValType*)this), this);
514 Table.remove(*(ValType*)this); // Destroy's this!
516 // Refine temporary to new state...
518 Tmp.doRefinement(OldTy, NewTy);
520 // FIXME: when types are not const!
521 Table.add((ValType&)Tmp, (TypeClass*)OldType.get());
525 cerr << "ValTypeBase instance!\n";
531 //===----------------------------------------------------------------------===//
532 // Function Type Factory and Value Class...
535 // FunctionValType - Define a class to hold the key that goes into the TypeMap
537 class FunctionValType : public ValTypeBase<FunctionValType, FunctionType> {
538 PATypeHandle<Type> RetTy;
539 vector<PATypeHandle<Type> > ArgTypes;
542 FunctionValType(const Type *ret, const vector<const Type*> &args,
543 bool IVA, TypeMap<FunctionValType, FunctionType> &Tab)
544 : ValTypeBase<FunctionValType, FunctionType>(Tab), RetTy(ret, this),
546 for (unsigned i = 0; i < args.size(); ++i)
547 ArgTypes.push_back(PATypeHandle<Type>(args[i], this));
550 // We *MUST* have an explicit copy ctor so that the TypeHandles think that
551 // this FunctionValType owns them, not the old one!
553 FunctionValType(const FunctionValType &MVT)
554 : ValTypeBase<FunctionValType, FunctionType>(MVT), RetTy(MVT.RetTy, this),
555 isVarArg(MVT.isVarArg) {
556 ArgTypes.reserve(MVT.ArgTypes.size());
557 for (unsigned i = 0; i < MVT.ArgTypes.size(); ++i)
558 ArgTypes.push_back(PATypeHandle<Type>(MVT.ArgTypes[i], this));
561 // Subclass should override this... to update self as usual
562 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
563 if (RetTy == OldType) RetTy = NewType;
564 for (unsigned i = 0, e = ArgTypes.size(); i != e; ++i)
565 if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
568 virtual void typeBecameConcrete(const DerivedType *Ty) {
569 if (RetTy == Ty) RetTy.removeUserFromConcrete();
571 for (unsigned i = 0; i < ArgTypes.size(); ++i)
572 if (ArgTypes[i] == Ty) ArgTypes[i].removeUserFromConcrete();
575 inline bool operator<(const FunctionValType &MTV) const {
576 if (RetTy.get() < MTV.RetTy.get()) return true;
577 if (RetTy.get() > MTV.RetTy.get()) return false;
579 if (ArgTypes < MTV.ArgTypes) return true;
580 return (ArgTypes == MTV.ArgTypes) && isVarArg < MTV.isVarArg;
584 // Define the actual map itself now...
585 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
587 // FunctionType::get - The factory function for the FunctionType class...
588 FunctionType *FunctionType::get(const Type *ReturnType,
589 const vector<const Type*> &Params,
591 FunctionValType VT(ReturnType, Params, isVarArg, FunctionTypes);
592 FunctionType *MT = FunctionTypes.get(VT);
595 FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
597 #ifdef DEBUG_MERGE_TYPES
598 cerr << "Derived new type: " << MT << endl;
603 //===----------------------------------------------------------------------===//
604 // Array Type Factory...
606 class ArrayValType : public ValTypeBase<ArrayValType, ArrayType> {
607 PATypeHandle<Type> ValTy;
610 ArrayValType(const Type *val, int sz, TypeMap<ArrayValType, ArrayType> &Tab)
611 : ValTypeBase<ArrayValType, ArrayType>(Tab), ValTy(val, this), Size(sz) {}
613 // We *MUST* have an explicit copy ctor so that the ValTy thinks that this
614 // ArrayValType owns it, not the old one!
616 ArrayValType(const ArrayValType &AVT)
617 : ValTypeBase<ArrayValType, ArrayType>(AVT), ValTy(AVT.ValTy, this),
620 // Subclass should override this... to update self as usual
621 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
622 assert(ValTy == OldType);
626 virtual void typeBecameConcrete(const DerivedType *Ty) {
627 assert(ValTy == Ty &&
628 "Contained type became concrete but we're not using it!");
629 ValTy.removeUserFromConcrete();
632 inline bool operator<(const ArrayValType &MTV) const {
633 if (Size < MTV.Size) return true;
634 return Size == MTV.Size && ValTy.get() < MTV.ValTy.get();
638 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
640 ArrayType *ArrayType::get(const Type *ElementType, unsigned NumElements) {
641 assert(ElementType && "Can't get array of null types!");
643 ArrayValType AVT(ElementType, NumElements, ArrayTypes);
644 ArrayType *AT = ArrayTypes.get(AVT);
645 if (AT) return AT; // Found a match, return it!
647 // Value not found. Derive a new type!
648 ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
650 #ifdef DEBUG_MERGE_TYPES
651 cerr << "Derived new type: " << AT->getDescription() << endl;
656 //===----------------------------------------------------------------------===//
657 // Struct Type Factory...
660 // StructValType - Define a class to hold the key that goes into the TypeMap
662 class StructValType : public ValTypeBase<StructValType, StructType> {
663 vector<PATypeHandle<Type> > ElTypes;
665 StructValType(const vector<const Type*> &args,
666 TypeMap<StructValType, StructType> &Tab)
667 : ValTypeBase<StructValType, StructType>(Tab) {
668 ElTypes.reserve(args.size());
669 for (unsigned i = 0, e = args.size(); i != e; ++i)
670 ElTypes.push_back(PATypeHandle<Type>(args[i], this));
673 // We *MUST* have an explicit copy ctor so that the TypeHandles think that
674 // this StructValType owns them, not the old one!
676 StructValType(const StructValType &SVT)
677 : ValTypeBase<StructValType, StructType>(SVT){
678 ElTypes.reserve(SVT.ElTypes.size());
679 for (unsigned i = 0, e = SVT.ElTypes.size(); i != e; ++i)
680 ElTypes.push_back(PATypeHandle<Type>(SVT.ElTypes[i], this));
683 // Subclass should override this... to update self as usual
684 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
685 for (unsigned i = 0; i < ElTypes.size(); ++i)
686 if (ElTypes[i] == OldType) ElTypes[i] = NewType;
689 virtual void typeBecameConcrete(const DerivedType *Ty) {
690 for (unsigned i = 0, e = ElTypes.size(); i != e; ++i)
691 if (ElTypes[i] == Ty)
692 ElTypes[i].removeUserFromConcrete();
695 inline bool operator<(const StructValType &STV) const {
696 return ElTypes < STV.ElTypes;
700 static TypeMap<StructValType, StructType> StructTypes;
702 StructType *StructType::get(const vector<const Type*> &ETypes) {
703 StructValType STV(ETypes, StructTypes);
704 StructType *ST = StructTypes.get(STV);
707 // Value not found. Derive a new type!
708 StructTypes.add(STV, ST = new StructType(ETypes));
710 #ifdef DEBUG_MERGE_TYPES
711 cerr << "Derived new type: " << ST->getDescription() << endl;
716 //===----------------------------------------------------------------------===//
717 // Pointer Type Factory...
720 // PointerValType - Define a class to hold the key that goes into the TypeMap
722 class PointerValType : public ValTypeBase<PointerValType, PointerType> {
723 PATypeHandle<Type> ValTy;
725 PointerValType(const Type *val, TypeMap<PointerValType, PointerType> &Tab)
726 : ValTypeBase<PointerValType, PointerType>(Tab), ValTy(val, this) {}
728 // We *MUST* have an explicit copy ctor so that the ValTy thinks that this
729 // PointerValType owns it, not the old one!
731 PointerValType(const PointerValType &PVT)
732 : ValTypeBase<PointerValType, PointerType>(PVT), ValTy(PVT.ValTy, this) {}
734 // Subclass should override this... to update self as usual
735 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
736 assert(ValTy == OldType);
740 virtual void typeBecameConcrete(const DerivedType *Ty) {
741 assert(ValTy == Ty &&
742 "Contained type became concrete but we're not using it!");
743 ValTy.removeUserFromConcrete();
746 inline bool operator<(const PointerValType &MTV) const {
747 return ValTy.get() < MTV.ValTy.get();
751 static TypeMap<PointerValType, PointerType> PointerTypes;
753 PointerType *PointerType::get(const Type *ValueType) {
754 assert(ValueType && "Can't get a pointer to <null> type!");
755 PointerValType PVT(ValueType, PointerTypes);
757 PointerType *PT = PointerTypes.get(PVT);
760 // Value not found. Derive a new type!
761 PointerTypes.add(PVT, PT = new PointerType(ValueType));
763 #ifdef DEBUG_MERGE_TYPES
764 cerr << "Derived new type: " << PT->getDescription() << endl;
769 void debug_type_tables() {
770 FunctionTypes.dump();
777 //===----------------------------------------------------------------------===//
778 // Derived Type Refinement Functions
779 //===----------------------------------------------------------------------===//
781 // addAbstractTypeUser - Notify an abstract type that there is a new user of
782 // it. This function is called primarily by the PATypeHandle class.
784 void DerivedType::addAbstractTypeUser(AbstractTypeUser *U) const {
785 assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
787 #if DEBUG_MERGE_TYPES
788 cerr << " addAbstractTypeUser[" << (void*)this << ", " << getDescription()
789 << "][" << AbstractTypeUsers.size() << "] User = " << U << endl;
791 AbstractTypeUsers.push_back(U);
795 // removeAbstractTypeUser - Notify an abstract type that a user of the class
796 // no longer has a handle to the type. This function is called primarily by
797 // the PATypeHandle class. When there are no users of the abstract type, it
798 // is anihilated, because there is no way to get a reference to it ever again.
800 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
801 // Search from back to front because we will notify users from back to
802 // front. Also, it is likely that there will be a stack like behavior to
803 // users that register and unregister users.
806 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
807 assert(i != 0 && "AbstractTypeUser not in user list!");
809 --i; // Convert to be in range 0 <= i < size()
810 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
812 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
814 #ifdef DEBUG_MERGE_TYPES
815 cerr << " remAbstractTypeUser[" << (void*)this << ", "
816 << getDescription() << "][" << i << "] User = " << U << endl;
819 if (AbstractTypeUsers.empty() && isAbstract()) {
820 #ifdef DEBUG_MERGE_TYPES
821 cerr << "DELETEing unused abstract type: <" << getDescription()
822 << ">[" << (void*)this << "]" << endl;
824 delete this; // No users of this abstract type!
829 // refineAbstractTypeTo - This function is used to when it is discovered that
830 // the 'this' abstract type is actually equivalent to the NewType specified.
831 // This causes all users of 'this' to switch to reference the more concrete
832 // type NewType and for 'this' to be deleted.
834 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
835 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
836 assert(this != NewType && "Can't refine to myself!");
838 #ifdef DEBUG_MERGE_TYPES
839 cerr << "REFINING abstract type [" << (void*)this << " " << getDescription()
840 << "] to [" << (void*)NewType << " " << NewType->getDescription()
845 // Make sure to put the type to be refined to into a holder so that if IT gets
846 // refined, that we will not continue using a dead reference...
848 PATypeHolder NewTy(NewType);
850 // Add a self use of the current type so that we don't delete ourself until
851 // after this while loop. We are careful to never invoke refine on ourself,
852 // so this extra reference shouldn't be a problem. Note that we must only
853 // remove a single reference at the end, but we must tolerate multiple self
854 // references because we could be refineAbstractTypeTo'ing recursively on the
857 addAbstractTypeUser(this);
859 // Count the number of self uses. Stop looping when sizeof(list) == NSU.
860 unsigned NumSelfUses = 0;
862 // Iterate over all of the uses of this type, invoking callback. Each user
863 // should remove itself from our use list automatically. We have to check to
864 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
865 // will not cause users to drop off of the use list. If we resolve to ourself
868 while (AbstractTypeUsers.size() > NumSelfUses && NewTy != this) {
869 AbstractTypeUser *User = AbstractTypeUsers.back();
872 // Move self use to the start of the list. Increment NSU.
873 swap(AbstractTypeUsers.back(), AbstractTypeUsers[NumSelfUses++]);
875 unsigned OldSize = AbstractTypeUsers.size();
876 #ifdef DEBUG_MERGE_TYPES
877 cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
878 << "] of abstract type ["
879 << (void*)this << " " << getDescription() << "] to ["
880 << (void*)NewTy.get() << " " << NewTy->getDescription() << "]!\n";
882 User->refineAbstractType(this, NewTy);
884 #ifdef DEBUG_MERGE_TYPES
885 if (AbstractTypeUsers.size() == OldSize) {
886 User->refineAbstractType(this, NewTy);
887 if (AbstractTypeUsers.back() != User)
888 cerr << "User changed!\n";
889 cerr << "Top of user list is:\n";
890 AbstractTypeUsers.back()->dump();
892 cerr <<"\nOld User=\n";
896 assert(AbstractTypeUsers.size() != OldSize &&
897 "AbsTyUser did not remove self from user list!");
901 // Remove a single self use, even though there may be several here. This will
902 // probably 'delete this', so no instance variables may be used after this
905 assert((NewTy == this || AbstractTypeUsers.back() == this) &&
906 "Only self uses should be left!");
907 removeAbstractTypeUser(this);
910 // typeIsRefined - Notify AbstractTypeUsers of this type that the current type
911 // has been refined a bit. The pointer is still valid and still should be
912 // used, but the subtypes have changed.
914 void DerivedType::typeIsRefined() {
915 assert(isRefining >= 0 && isRefining <= 2 && "isRefining out of bounds!");
916 if (isRefining == 1) return; // Kill recursion here...
919 #ifdef DEBUG_MERGE_TYPES
920 cerr << "typeIsREFINED type: " << (void*)this <<" "<<getDescription() << "\n";
923 // In this loop we have to be very careful not to get into infinite loops and
924 // other problem cases. Specifically, we loop through all of the abstract
925 // type users in the user list, notifying them that the type has been refined.
926 // At their choice, they may or may not choose to remove themselves from the
927 // list of users. Regardless of whether they do or not, we have to be sure
928 // that we only notify each user exactly once. Because the refineAbstractType
929 // method can cause an arbitrary permutation to the user list, we cannot loop
930 // through it in any particular order and be guaranteed that we will be
931 // successful at this aim. Because of this, we keep track of all the users we
932 // have visited and only visit users we have not seen. Because this user list
933 // should be small, we use a vector instead of a full featured set to keep
934 // track of what users we have notified so far.
936 vector<AbstractTypeUser*> Refined;
939 for (i = AbstractTypeUsers.size(); i != 0; --i)
940 if (find(Refined.begin(), Refined.end(), AbstractTypeUsers[i-1]) ==
942 break; // Found an unrefined user?
944 if (i == 0) break; // Noone to refine left, break out of here!
946 AbstractTypeUser *ATU = AbstractTypeUsers[--i];
947 Refined.push_back(ATU); // Keep track of which users we have refined!
949 #ifdef DEBUG_MERGE_TYPES
950 cerr << " typeIsREFINED user " << i << "[" << ATU << "] of abstract type ["
951 << (void*)this << " " << getDescription() << "]\n";
953 ATU->refineAbstractType(this, this);
959 if (!(isAbstract() || AbstractTypeUsers.empty()))
960 for (unsigned i = 0; i < AbstractTypeUsers.size(); ++i) {
961 if (AbstractTypeUsers[i] != this) {
963 cerr << "FOUND FAILURE\nUser: ";
964 AbstractTypeUsers[i]->dump();
965 cerr << "\nCatch:\n";
966 AbstractTypeUsers[i]->refineAbstractType(this, this);
967 assert(0 && "Type became concrete,"
968 " but it still has abstract type users hanging around!");
977 // refineAbstractType - Called when a contained type is found to be more
978 // concrete - this could potentially change us from an abstract type to a
981 void FunctionType::refineAbstractType(const DerivedType *OldType,
982 const Type *NewType) {
983 #ifdef DEBUG_MERGE_TYPES
984 cerr << "FunctionTy::refineAbstractTy(" << (void*)OldType << "["
985 << OldType->getDescription() << "], " << (void*)NewType << " ["
986 << NewType->getDescription() << "])\n";
988 // Find the type element we are refining...
989 if (ResultType == OldType) {
990 ResultType.removeUserFromConcrete();
991 ResultType = NewType;
993 for (unsigned i = 0, e = ParamTys.size(); i != e; ++i)
994 if (ParamTys[i] == OldType) {
995 ParamTys[i].removeUserFromConcrete();
996 ParamTys[i] = NewType;
999 const FunctionType *MT = FunctionTypes.containsEquivalent(this);
1000 if (MT && MT != this) {
1001 refineAbstractTypeTo(MT); // Different type altogether...
1003 setDerivedTypeProperties(); // Update the name and isAbstract
1004 typeIsRefined(); // Same type, different contents...
1009 // refineAbstractType - Called when a contained type is found to be more
1010 // concrete - this could potentially change us from an abstract type to a
1013 void ArrayType::refineAbstractType(const DerivedType *OldType,
1014 const Type *NewType) {
1015 #ifdef DEBUG_MERGE_TYPES
1016 cerr << "ArrayTy::refineAbstractTy(" << (void*)OldType << "["
1017 << OldType->getDescription() << "], " << (void*)NewType << " ["
1018 << NewType->getDescription() << "])\n";
1021 assert(getElementType() == OldType);
1022 ElementType.removeUserFromConcrete();
1023 ElementType = NewType;
1025 const ArrayType *AT = ArrayTypes.containsEquivalent(this);
1026 if (AT && AT != this) {
1027 refineAbstractTypeTo(AT); // Different type altogether...
1029 setDerivedTypeProperties(); // Update the name and isAbstract
1030 typeIsRefined(); // Same type, different contents...
1035 // refineAbstractType - Called when a contained type is found to be more
1036 // concrete - this could potentially change us from an abstract type to a
1039 void StructType::refineAbstractType(const DerivedType *OldType,
1040 const Type *NewType) {
1041 #ifdef DEBUG_MERGE_TYPES
1042 cerr << "StructTy::refineAbstractTy(" << (void*)OldType << "["
1043 << OldType->getDescription() << "], " << (void*)NewType << " ["
1044 << NewType->getDescription() << "])\n";
1046 for (unsigned i = 0, e = ETypes.size(); i != e; ++i)
1047 if (ETypes[i] == OldType) {
1048 ETypes[i].removeUserFromConcrete();
1050 // Update old type to new type in the array...
1051 ETypes[i] = NewType;
1054 const StructType *ST = StructTypes.containsEquivalent(this);
1055 if (ST && ST != this) {
1056 refineAbstractTypeTo(ST); // Different type altogether...
1058 setDerivedTypeProperties(); // Update the name and isAbstract
1059 typeIsRefined(); // Same type, different contents...
1063 // refineAbstractType - Called when a contained type is found to be more
1064 // concrete - this could potentially change us from an abstract type to a
1067 void PointerType::refineAbstractType(const DerivedType *OldType,
1068 const Type *NewType) {
1069 #ifdef DEBUG_MERGE_TYPES
1070 cerr << "PointerTy::refineAbstractTy(" << (void*)OldType << "["
1071 << OldType->getDescription() << "], " << (void*)NewType << " ["
1072 << NewType->getDescription() << "])\n";
1075 assert(ElementType == OldType);
1076 ElementType.removeUserFromConcrete();
1077 ElementType = NewType;
1079 const PointerType *PT = PointerTypes.containsEquivalent(this);
1080 if (PT && PT != this) {
1081 refineAbstractTypeTo(PT); // Different type altogether...
1083 setDerivedTypeProperties(); // Update the name and isAbstract
1084 typeIsRefined(); // Same type, different contents...