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"
14 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
15 // created and later destroyed, all in an effort to make sure that there is only
16 // a single cannonical version of a type.
18 //#define DEBUG_MERGE_TYPES 1
21 //===----------------------------------------------------------------------===//
22 // Type Class Implementation
23 //===----------------------------------------------------------------------===//
25 static unsigned CurUID = 0;
26 static std::vector<const Type *> UIDMappings;
28 // Concrete/Abstract TypeDescriptions - We lazily calculate type descriptions
29 // for types as they are needed. Because resolution of types must invalidate
30 // all of the abstract type descriptions, we keep them in a seperate map to make
32 static std::map<const Type*, std::string> ConcreteTypeDescriptions;
33 static std::map<const Type*, std::string> AbstractTypeDescriptions;
35 void PATypeHolder::dump() const {
36 std::cerr << "PATypeHolder(" << (void*)this << ")\n";
40 Type::Type(const std::string &name, PrimitiveID id)
41 : Value(Type::TypeTy, Value::TypeVal) {
43 ConcreteTypeDescriptions[this] = name;
46 UID = CurUID++; // Assign types UID's as they are created
47 UIDMappings.push_back(this);
50 void Type::setName(const std::string &Name, SymbolTable *ST) {
51 assert(ST && "Type::setName - Must provide symbol table argument!");
53 if (Name.size()) ST->insert(Name, this);
57 const Type *Type::getUniqueIDType(unsigned UID) {
58 assert(UID < UIDMappings.size() &&
59 "Type::getPrimitiveType: UID out of range!");
60 return UIDMappings[UID];
63 const Type *Type::getPrimitiveType(PrimitiveID IDNumber) {
65 case VoidTyID : return VoidTy;
66 case BoolTyID : return BoolTy;
67 case UByteTyID : return UByteTy;
68 case SByteTyID : return SByteTy;
69 case UShortTyID: return UShortTy;
70 case ShortTyID : return ShortTy;
71 case UIntTyID : return UIntTy;
72 case IntTyID : return IntTy;
73 case ULongTyID : return ULongTy;
74 case LongTyID : return LongTy;
75 case FloatTyID : return FloatTy;
76 case DoubleTyID: return DoubleTy;
77 case TypeTyID : return TypeTy;
78 case LabelTyID : return LabelTy;
84 // isLosslesslyConvertibleTo - Return true if this type can be converted to
85 // 'Ty' without any reinterpretation of bits. For example, uint to int.
87 bool Type::isLosslesslyConvertibleTo(const Type *Ty) const {
88 if (this == Ty) return true;
89 if ((!isPrimitiveType() && !isa<PointerType>(this)) ||
90 (!isa<PointerType>(Ty) && !Ty->isPrimitiveType())) return false;
92 if (getPrimitiveID() == Ty->getPrimitiveID())
93 return true; // Handles identity cast, and cast of differing pointer types
95 // Now we know that they are two differing primitive or pointer types
96 switch (getPrimitiveID()) {
97 case Type::UByteTyID: return Ty == Type::SByteTy;
98 case Type::SByteTyID: return Ty == Type::UByteTy;
99 case Type::UShortTyID: return Ty == Type::ShortTy;
100 case Type::ShortTyID: return Ty == Type::UShortTy;
101 case Type::UIntTyID: return Ty == Type::IntTy;
102 case Type::IntTyID: return Ty == Type::UIntTy;
103 case Type::ULongTyID:
105 case Type::PointerTyID:
106 return Ty == Type::ULongTy || Ty == Type::LongTy || isa<PointerType>(Ty);
108 return false; // Other types have no identity values
112 // getPrimitiveSize - Return the basic size of this type if it is a primative
113 // type. These are fixed by LLVM and are not target dependent. This will
114 // return zero if the type does not have a size or is not a primitive type.
116 unsigned Type::getPrimitiveSize() const {
117 switch (getPrimitiveID()) {
118 #define HANDLE_PRIM_TYPE(TY,SIZE) case TY##TyID: return SIZE;
119 #include "llvm/Type.def"
125 // getTypeDescription - This is a recursive function that walks a type hierarchy
126 // calculating the description for a type.
128 static std::string getTypeDescription(const Type *Ty,
129 std::vector<const Type *> &TypeStack) {
130 if (isa<OpaqueType>(Ty)) { // Base case for the recursion
131 std::map<const Type*, std::string>::iterator I =
132 AbstractTypeDescriptions.lower_bound(Ty);
133 if (I != AbstractTypeDescriptions.end() && I->first == Ty)
135 std::string Desc = "opaque"+utostr(Ty->getUniqueID());
136 AbstractTypeDescriptions.insert(std::make_pair(Ty, Desc));
140 if (!Ty->isAbstract()) { // Base case for the recursion
141 std::map<const Type*, std::string>::iterator I =
142 ConcreteTypeDescriptions.find(Ty);
143 if (I != ConcreteTypeDescriptions.end()) return I->second;
146 // Check to see if the Type is already on the stack...
147 unsigned Slot = 0, CurSize = TypeStack.size();
148 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
150 // This is another base case for the recursion. In this case, we know
151 // that we have looped back to a type that we have previously visited.
152 // Generate the appropriate upreference to handle this.
155 return "\\" + utostr(CurSize-Slot); // Here's the upreference
157 // Recursive case: derived types...
159 TypeStack.push_back(Ty); // Add us to the stack..
161 switch (Ty->getPrimitiveID()) {
162 case Type::FunctionTyID: {
163 const FunctionType *FTy = cast<FunctionType>(Ty);
164 Result = getTypeDescription(FTy->getReturnType(), TypeStack) + " (";
165 for (FunctionType::ParamTypes::const_iterator
166 I = FTy->getParamTypes().begin(),
167 E = FTy->getParamTypes().end(); I != E; ++I) {
168 if (I != FTy->getParamTypes().begin())
170 Result += getTypeDescription(*I, TypeStack);
172 if (FTy->isVarArg()) {
173 if (!FTy->getParamTypes().empty()) Result += ", ";
179 case Type::StructTyID: {
180 const StructType *STy = cast<StructType>(Ty);
182 for (StructType::ElementTypes::const_iterator
183 I = STy->getElementTypes().begin(),
184 E = STy->getElementTypes().end(); I != E; ++I) {
185 if (I != STy->getElementTypes().begin())
187 Result += getTypeDescription(*I, TypeStack);
192 case Type::PointerTyID: {
193 const PointerType *PTy = cast<PointerType>(Ty);
194 Result = getTypeDescription(PTy->getElementType(), TypeStack) + " *";
197 case Type::ArrayTyID: {
198 const ArrayType *ATy = cast<ArrayType>(Ty);
199 unsigned NumElements = ATy->getNumElements();
201 Result += utostr(NumElements) + " x ";
202 Result += getTypeDescription(ATy->getElementType(), TypeStack) + "]";
207 assert(0 && "Unhandled type in getTypeDescription!");
210 TypeStack.pop_back(); // Remove self from stack...
217 static const std::string &getOrCreateDesc(std::map<const Type*,std::string>&Map,
219 std::map<const Type*, std::string>::iterator I = Map.find(Ty);
220 if (I != Map.end()) return I->second;
222 std::vector<const Type *> TypeStack;
223 return Map[Ty] = getTypeDescription(Ty, TypeStack);
227 const std::string &Type::getDescription() const {
229 return getOrCreateDesc(AbstractTypeDescriptions, this);
231 return getOrCreateDesc(ConcreteTypeDescriptions, this);
235 bool StructType::indexValid(const Value *V) const {
236 if (!isa<Constant>(V)) return false;
237 if (V->getType() != Type::UByteTy) return false;
238 unsigned Idx = cast<ConstantUInt>(V)->getValue();
239 return Idx < ETypes.size();
242 // getTypeAtIndex - Given an index value into the type, return the type of the
243 // element. For a structure type, this must be a constant value...
245 const Type *StructType::getTypeAtIndex(const Value *V) const {
246 assert(isa<Constant>(V) && "Structure index must be a constant!!");
247 assert(V->getType() == Type::UByteTy && "Structure index must be ubyte!");
248 unsigned Idx = cast<ConstantUInt>(V)->getValue();
249 assert(Idx < ETypes.size() && "Structure index out of range!");
250 assert(indexValid(V) && "Invalid structure index!"); // Duplicate check
256 //===----------------------------------------------------------------------===//
257 // Auxilliary classes
258 //===----------------------------------------------------------------------===//
260 // These classes are used to implement specialized behavior for each different
263 struct SignedIntType : public Type {
264 SignedIntType(const std::string &Name, PrimitiveID id) : Type(Name, id) {}
266 // isSigned - Return whether a numeric type is signed.
267 virtual bool isSigned() const { return 1; }
269 // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
270 // virtual function invocation.
272 virtual bool isInteger() const { return 1; }
275 struct UnsignedIntType : public Type {
276 UnsignedIntType(const std::string &N, PrimitiveID id) : Type(N, id) {}
278 // isUnsigned - Return whether a numeric type is signed.
279 virtual bool isUnsigned() const { return 1; }
281 // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
282 // virtual function invocation.
284 virtual bool isInteger() const { return 1; }
287 struct OtherType : public Type {
288 OtherType(const std::string &N, PrimitiveID id) : Type(N, id) {}
291 static struct TypeType : public Type {
292 TypeType() : Type("type", TypeTyID) {}
293 } TheTypeTy; // Implement the type that is global.
296 //===----------------------------------------------------------------------===//
297 // Static 'Type' data
298 //===----------------------------------------------------------------------===//
300 static OtherType TheVoidTy ("void" , Type::VoidTyID);
301 static OtherType TheBoolTy ("bool" , Type::BoolTyID);
302 static SignedIntType TheSByteTy ("sbyte" , Type::SByteTyID);
303 static UnsignedIntType TheUByteTy ("ubyte" , Type::UByteTyID);
304 static SignedIntType TheShortTy ("short" , Type::ShortTyID);
305 static UnsignedIntType TheUShortTy("ushort", Type::UShortTyID);
306 static SignedIntType TheIntTy ("int" , Type::IntTyID);
307 static UnsignedIntType TheUIntTy ("uint" , Type::UIntTyID);
308 static SignedIntType TheLongTy ("long" , Type::LongTyID);
309 static UnsignedIntType TheULongTy ("ulong" , Type::ULongTyID);
310 static OtherType TheFloatTy ("float" , Type::FloatTyID);
311 static OtherType TheDoubleTy("double", Type::DoubleTyID);
312 static OtherType TheLabelTy ("label" , Type::LabelTyID);
314 Type *Type::VoidTy = &TheVoidTy;
315 Type *Type::BoolTy = &TheBoolTy;
316 Type *Type::SByteTy = &TheSByteTy;
317 Type *Type::UByteTy = &TheUByteTy;
318 Type *Type::ShortTy = &TheShortTy;
319 Type *Type::UShortTy = &TheUShortTy;
320 Type *Type::IntTy = &TheIntTy;
321 Type *Type::UIntTy = &TheUIntTy;
322 Type *Type::LongTy = &TheLongTy;
323 Type *Type::ULongTy = &TheULongTy;
324 Type *Type::FloatTy = &TheFloatTy;
325 Type *Type::DoubleTy = &TheDoubleTy;
326 Type *Type::TypeTy = &TheTypeTy;
327 Type *Type::LabelTy = &TheLabelTy;
330 //===----------------------------------------------------------------------===//
331 // Derived Type Constructors
332 //===----------------------------------------------------------------------===//
334 FunctionType::FunctionType(const Type *Result,
335 const std::vector<const Type*> &Params,
336 bool IsVarArgs) : DerivedType(FunctionTyID),
337 ResultType(PATypeHandle(Result, this)),
338 isVarArgs(IsVarArgs) {
339 bool isAbstract = Result->isAbstract();
340 ParamTys.reserve(Params.size());
341 for (unsigned i = 0; i < Params.size(); ++i) {
342 ParamTys.push_back(PATypeHandle(Params[i], this));
343 isAbstract |= Params[i]->isAbstract();
346 // Calculate whether or not this type is abstract
347 setAbstract(isAbstract);
350 StructType::StructType(const std::vector<const Type*> &Types)
351 : CompositeType(StructTyID) {
352 ETypes.reserve(Types.size());
353 bool isAbstract = false;
354 for (unsigned i = 0; i < Types.size(); ++i) {
355 assert(Types[i] != Type::VoidTy && "Void type in method prototype!!");
356 ETypes.push_back(PATypeHandle(Types[i], this));
357 isAbstract |= Types[i]->isAbstract();
360 // Calculate whether or not this type is abstract
361 setAbstract(isAbstract);
364 ArrayType::ArrayType(const Type *ElType, unsigned NumEl)
365 : SequentialType(ArrayTyID, ElType) {
368 // Calculate whether or not this type is abstract
369 setAbstract(ElType->isAbstract());
372 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
373 // Calculate whether or not this type is abstract
374 setAbstract(E->isAbstract());
377 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
379 #ifdef DEBUG_MERGE_TYPES
380 std::cerr << "Derived new type: " << *this << "\n";
385 // isTypeAbstract - This is a recursive function that walks a type hierarchy
386 // calculating whether or not a type is abstract. Worst case it will have to do
387 // a lot of traversing if you have some whacko opaque types, but in most cases,
388 // it will do some simple stuff when it hits non-abstract types that aren't
391 bool Type::isTypeAbstract() {
392 if (!isAbstract()) // Base case for the recursion
393 return false; // Primitive = leaf type
395 if (isa<OpaqueType>(this)) // Base case for the recursion
396 return true; // This whole type is abstract!
398 // We have to guard against recursion. To do this, we temporarily mark this
399 // type as concrete, so that if we get back to here recursively we will think
400 // it's not abstract, and thus not scan it again.
403 // Scan all of the sub-types. If any of them are abstract, than so is this
405 for (Type::subtype_iterator I = subtype_begin(), E = subtype_end();
407 if (const_cast<Type*>(*I)->isTypeAbstract()) {
408 setAbstract(true); // Restore the abstract bit.
409 return true; // This type is abstract if subtype is abstract!
412 // Restore the abstract bit.
415 // Nothing looks abstract here...
420 //===----------------------------------------------------------------------===//
421 // Type Structural Equality Testing
422 //===----------------------------------------------------------------------===//
424 // TypesEqual - Two types are considered structurally equal if they have the
425 // same "shape": Every level and element of the types have identical primitive
426 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
427 // be pointer equals to be equivalent though. This uses an optimistic algorithm
428 // that assumes that two graphs are the same until proven otherwise.
430 static bool TypesEqual(const Type *Ty, const Type *Ty2,
431 std::map<const Type *, const Type *> &EqTypes) {
432 if (Ty == Ty2) return true;
433 if (Ty->getPrimitiveID() != Ty2->getPrimitiveID()) return false;
434 if (Ty->isPrimitiveType()) return true;
435 if (isa<OpaqueType>(Ty))
436 return false; // Two nonequal opaque types are never equal
438 std::map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
439 if (It != EqTypes.end())
440 return It->second == Ty2; // Looping back on a type, check for equality
442 // Otherwise, add the mapping to the table to make sure we don't get
443 // recursion on the types...
444 EqTypes.insert(std::make_pair(Ty, Ty2));
446 // Iterate over the types and make sure the the contents are equivalent...
447 Type::subtype_iterator I = Ty ->subtype_begin(), IE = Ty ->subtype_end();
448 Type::subtype_iterator I2 = Ty2->subtype_begin(), IE2 = Ty2->subtype_end();
449 for (; I != IE && I2 != IE2; ++I, ++I2)
450 if (!TypesEqual(*I, *I2, EqTypes)) return false;
452 // Two really annoying special cases that breaks an otherwise nice simple
453 // algorithm is the fact that arraytypes have sizes that differentiates types,
454 // and that method types can be varargs or not. Consider this now.
455 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
456 if (ATy->getNumElements() != cast<ArrayType>(Ty2)->getNumElements())
458 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
459 if (FTy->isVarArg() != cast<FunctionType>(Ty2)->isVarArg())
463 return I == IE && I2 == IE2; // Types equal if both iterators are done
466 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
467 std::map<const Type *, const Type *> EqTypes;
468 return TypesEqual(Ty, Ty2, EqTypes);
473 //===----------------------------------------------------------------------===//
474 // Derived Type Factory Functions
475 //===----------------------------------------------------------------------===//
477 // TypeMap - Make sure that only one instance of a particular type may be
478 // created on any given run of the compiler... note that this involves updating
479 // our map if an abstract type gets refined somehow...
481 template<class ValType, class TypeClass>
482 class TypeMap : public AbstractTypeUser {
483 typedef std::map<ValType, PATypeHandle> MapTy;
486 ~TypeMap() { print("ON EXIT"); }
488 inline TypeClass *get(const ValType &V) {
489 typename std::map<ValType, PATypeHandle>::iterator I
491 // TODO: FIXME: When Types are not CONST.
492 return (I != Map.end()) ? (TypeClass*)I->second.get() : 0;
495 inline void add(const ValType &V, TypeClass *T) {
496 Map.insert(std::make_pair(V, PATypeHandle(T, this)));
500 // containsEquivalent - Return true if the typemap contains a type that is
501 // structurally equivalent to the specified type.
503 inline const TypeClass *containsEquivalent(const TypeClass *Ty) {
504 for (typename MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
505 if (I->second.get() != Ty && TypesEqual(Ty, I->second.get()))
506 return (TypeClass*)I->second.get(); // FIXME TODO when types not const
510 // refineAbstractType - This is called when one of the contained abstract
511 // types gets refined... this simply removes the abstract type from our table.
512 // We expect that whoever refined the type will add it back to the table,
515 virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
516 #ifdef DEBUG_MERGE_TYPES
517 std::cerr << "Removing Old type from Tab: " << (void*)OldTy << ", "
518 << *OldTy << " replacement == " << (void*)NewTy
519 << ", " << *NewTy << "\n";
521 for (typename MapTy::iterator I = Map.begin(), E = Map.end(); I != E; ++I)
522 if (I->second == OldTy) {
523 // Check to see if the type just became concrete. If so, remove self
525 I->second.removeUserFromConcrete();
526 I->second = cast<TypeClass>(NewTy);
530 void remove(const ValType &OldVal) {
531 typename MapTy::iterator I = Map.find(OldVal);
532 assert(I != Map.end() && "TypeMap::remove, element not found!");
536 void print(const char *Arg) const {
537 #ifdef DEBUG_MERGE_TYPES
538 std::cerr << "TypeMap<>::" << Arg << " table contents:\n";
540 for (MapTy::const_iterator I = Map.begin(), E = Map.end(); I != E; ++I)
541 std::cerr << " " << (++i) << ". " << I->second << " "
542 << *I->second << "\n";
546 void dump() const { print("dump output"); }
550 // ValTypeBase - This is the base class that is used by the various
551 // instantiations of TypeMap. This class is an AbstractType user that notifies
552 // the underlying TypeMap when it gets modified.
554 template<class ValType, class TypeClass>
555 class ValTypeBase : public AbstractTypeUser {
556 TypeMap<ValType, TypeClass> &MyTable;
558 inline ValTypeBase(TypeMap<ValType, TypeClass> &tab) : MyTable(tab) {}
560 // Subclass should override this... to update self as usual
561 virtual void doRefinement(const DerivedType *OldTy, const Type *NewTy) = 0;
563 // typeBecameConcrete - This callback occurs when a contained type refines
564 // to itself, but becomes concrete in the process. Our subclass should remove
565 // itself from the ATU list of the specified type.
567 virtual void typeBecameConcrete(const DerivedType *Ty) = 0;
569 virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
570 assert(OldTy == NewTy || OldTy->isAbstract());
572 if (!OldTy->isAbstract())
573 typeBecameConcrete(OldTy);
575 TypeMap<ValType, TypeClass> &Table = MyTable; // Copy MyTable reference
576 ValType Tmp(*(ValType*)this); // Copy this.
577 PATypeHandle OldType(Table.get(*(ValType*)this), this);
578 Table.remove(*(ValType*)this); // Destroy's this!
580 // Refine temporary to new state...
582 Tmp.doRefinement(OldTy, NewTy);
584 // FIXME: when types are not const!
585 Table.add((ValType&)Tmp, (TypeClass*)OldType.get());
589 std::cerr << "ValTypeBase instance!\n";
595 //===----------------------------------------------------------------------===//
596 // Function Type Factory and Value Class...
599 // FunctionValType - Define a class to hold the key that goes into the TypeMap
601 class FunctionValType : public ValTypeBase<FunctionValType, FunctionType> {
603 std::vector<PATypeHandle> ArgTypes;
606 FunctionValType(const Type *ret, const std::vector<const Type*> &args,
607 bool IVA, TypeMap<FunctionValType, FunctionType> &Tab)
608 : ValTypeBase<FunctionValType, FunctionType>(Tab), RetTy(ret, this),
610 for (unsigned i = 0; i < args.size(); ++i)
611 ArgTypes.push_back(PATypeHandle(args[i], this));
614 // We *MUST* have an explicit copy ctor so that the TypeHandles think that
615 // this FunctionValType owns them, not the old one!
617 FunctionValType(const FunctionValType &MVT)
618 : ValTypeBase<FunctionValType, FunctionType>(MVT), RetTy(MVT.RetTy, this),
619 isVarArg(MVT.isVarArg) {
620 ArgTypes.reserve(MVT.ArgTypes.size());
621 for (unsigned i = 0; i < MVT.ArgTypes.size(); ++i)
622 ArgTypes.push_back(PATypeHandle(MVT.ArgTypes[i], this));
625 // Subclass should override this... to update self as usual
626 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
627 if (RetTy == OldType) RetTy = NewType;
628 for (unsigned i = 0, e = ArgTypes.size(); i != e; ++i)
629 if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
632 virtual void typeBecameConcrete(const DerivedType *Ty) {
633 if (RetTy == Ty) RetTy.removeUserFromConcrete();
635 for (unsigned i = 0; i < ArgTypes.size(); ++i)
636 if (ArgTypes[i] == Ty) ArgTypes[i].removeUserFromConcrete();
639 inline bool operator<(const FunctionValType &MTV) const {
640 if (RetTy.get() < MTV.RetTy.get()) return true;
641 if (RetTy.get() > MTV.RetTy.get()) return false;
643 if (ArgTypes < MTV.ArgTypes) return true;
644 return (ArgTypes == MTV.ArgTypes) && isVarArg < MTV.isVarArg;
648 // Define the actual map itself now...
649 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
651 // FunctionType::get - The factory function for the FunctionType class...
652 FunctionType *FunctionType::get(const Type *ReturnType,
653 const std::vector<const Type*> &Params,
655 FunctionValType VT(ReturnType, Params, isVarArg, FunctionTypes);
656 FunctionType *MT = FunctionTypes.get(VT);
659 FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
661 #ifdef DEBUG_MERGE_TYPES
662 std::cerr << "Derived new type: " << MT << "\n";
667 //===----------------------------------------------------------------------===//
668 // Array Type Factory...
670 class ArrayValType : public ValTypeBase<ArrayValType, ArrayType> {
674 ArrayValType(const Type *val, int sz, TypeMap<ArrayValType, ArrayType> &Tab)
675 : ValTypeBase<ArrayValType, ArrayType>(Tab), ValTy(val, this), Size(sz) {}
677 // We *MUST* have an explicit copy ctor so that the ValTy thinks that this
678 // ArrayValType owns it, not the old one!
680 ArrayValType(const ArrayValType &AVT)
681 : ValTypeBase<ArrayValType, ArrayType>(AVT), ValTy(AVT.ValTy, this),
684 // Subclass should override this... to update self as usual
685 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
686 assert(ValTy == OldType);
690 virtual void typeBecameConcrete(const DerivedType *Ty) {
691 assert(ValTy == Ty &&
692 "Contained type became concrete but we're not using it!");
693 ValTy.removeUserFromConcrete();
696 inline bool operator<(const ArrayValType &MTV) const {
697 if (Size < MTV.Size) return true;
698 return Size == MTV.Size && ValTy.get() < MTV.ValTy.get();
702 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
704 ArrayType *ArrayType::get(const Type *ElementType, unsigned NumElements) {
705 assert(ElementType && "Can't get array of null types!");
707 ArrayValType AVT(ElementType, NumElements, ArrayTypes);
708 ArrayType *AT = ArrayTypes.get(AVT);
709 if (AT) return AT; // Found a match, return it!
711 // Value not found. Derive a new type!
712 ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
714 #ifdef DEBUG_MERGE_TYPES
715 std::cerr << "Derived new type: " << *AT << "\n";
720 //===----------------------------------------------------------------------===//
721 // Struct Type Factory...
724 // StructValType - Define a class to hold the key that goes into the TypeMap
726 class StructValType : public ValTypeBase<StructValType, StructType> {
727 std::vector<PATypeHandle> ElTypes;
729 StructValType(const std::vector<const Type*> &args,
730 TypeMap<StructValType, StructType> &Tab)
731 : ValTypeBase<StructValType, StructType>(Tab) {
732 ElTypes.reserve(args.size());
733 for (unsigned i = 0, e = args.size(); i != e; ++i)
734 ElTypes.push_back(PATypeHandle(args[i], this));
737 // We *MUST* have an explicit copy ctor so that the TypeHandles think that
738 // this StructValType owns them, not the old one!
740 StructValType(const StructValType &SVT)
741 : ValTypeBase<StructValType, StructType>(SVT){
742 ElTypes.reserve(SVT.ElTypes.size());
743 for (unsigned i = 0, e = SVT.ElTypes.size(); i != e; ++i)
744 ElTypes.push_back(PATypeHandle(SVT.ElTypes[i], this));
747 // Subclass should override this... to update self as usual
748 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
749 for (unsigned i = 0; i < ElTypes.size(); ++i)
750 if (ElTypes[i] == OldType) ElTypes[i] = NewType;
753 virtual void typeBecameConcrete(const DerivedType *Ty) {
754 for (unsigned i = 0, e = ElTypes.size(); i != e; ++i)
755 if (ElTypes[i] == Ty)
756 ElTypes[i].removeUserFromConcrete();
759 inline bool operator<(const StructValType &STV) const {
760 return ElTypes < STV.ElTypes;
764 static TypeMap<StructValType, StructType> StructTypes;
766 StructType *StructType::get(const std::vector<const Type*> &ETypes) {
767 StructValType STV(ETypes, StructTypes);
768 StructType *ST = StructTypes.get(STV);
771 // Value not found. Derive a new type!
772 StructTypes.add(STV, ST = new StructType(ETypes));
774 #ifdef DEBUG_MERGE_TYPES
775 std::cerr << "Derived new type: " << *ST << "\n";
780 //===----------------------------------------------------------------------===//
781 // Pointer Type Factory...
784 // PointerValType - Define a class to hold the key that goes into the TypeMap
786 class PointerValType : public ValTypeBase<PointerValType, PointerType> {
789 PointerValType(const Type *val, TypeMap<PointerValType, PointerType> &Tab)
790 : ValTypeBase<PointerValType, PointerType>(Tab), ValTy(val, this) {}
792 // We *MUST* have an explicit copy ctor so that the ValTy thinks that this
793 // PointerValType owns it, not the old one!
795 PointerValType(const PointerValType &PVT)
796 : ValTypeBase<PointerValType, PointerType>(PVT), ValTy(PVT.ValTy, this) {}
798 // Subclass should override this... to update self as usual
799 virtual void doRefinement(const DerivedType *OldType, const Type *NewType) {
800 assert(ValTy == OldType);
804 virtual void typeBecameConcrete(const DerivedType *Ty) {
805 assert(ValTy == Ty &&
806 "Contained type became concrete but we're not using it!");
807 ValTy.removeUserFromConcrete();
810 inline bool operator<(const PointerValType &MTV) const {
811 return ValTy.get() < MTV.ValTy.get();
815 static TypeMap<PointerValType, PointerType> PointerTypes;
817 PointerType *PointerType::get(const Type *ValueType) {
818 assert(ValueType && "Can't get a pointer to <null> type!");
819 PointerValType PVT(ValueType, PointerTypes);
821 PointerType *PT = PointerTypes.get(PVT);
824 // Value not found. Derive a new type!
825 PointerTypes.add(PVT, PT = new PointerType(ValueType));
827 #ifdef DEBUG_MERGE_TYPES
828 std::cerr << "Derived new type: " << *PT << "\n";
833 void debug_type_tables() {
834 FunctionTypes.dump();
841 //===----------------------------------------------------------------------===//
842 // Derived Type Refinement Functions
843 //===----------------------------------------------------------------------===//
845 // addAbstractTypeUser - Notify an abstract type that there is a new user of
846 // it. This function is called primarily by the PATypeHandle class.
848 void DerivedType::addAbstractTypeUser(AbstractTypeUser *U) const {
849 assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
851 #if DEBUG_MERGE_TYPES
852 std::cerr << " addAbstractTypeUser[" << (void*)this << ", "
853 << *this << "][" << AbstractTypeUsers.size()
854 << "] User = " << U << "\n";
856 AbstractTypeUsers.push_back(U);
860 // removeAbstractTypeUser - Notify an abstract type that a user of the class
861 // no longer has a handle to the type. This function is called primarily by
862 // the PATypeHandle class. When there are no users of the abstract type, it
863 // is anihilated, because there is no way to get a reference to it ever again.
865 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
866 // Search from back to front because we will notify users from back to
867 // front. Also, it is likely that there will be a stack like behavior to
868 // users that register and unregister users.
871 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
872 assert(i != 0 && "AbstractTypeUser not in user list!");
874 --i; // Convert to be in range 0 <= i < size()
875 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
877 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
879 #ifdef DEBUG_MERGE_TYPES
880 std::cerr << " remAbstractTypeUser[" << (void*)this << ", "
881 << *this << "][" << i << "] User = " << U << "\n";
884 if (AbstractTypeUsers.empty() && isAbstract()) {
885 #ifdef DEBUG_MERGE_TYPES
886 std::cerr << "DELETEing unused abstract type: <" << *this
887 << ">[" << (void*)this << "]" << "\n";
889 delete this; // No users of this abstract type!
894 // refineAbstractTypeTo - This function is used to when it is discovered that
895 // the 'this' abstract type is actually equivalent to the NewType specified.
896 // This causes all users of 'this' to switch to reference the more concrete
897 // type NewType and for 'this' to be deleted.
899 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
900 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
901 assert(this != NewType && "Can't refine to myself!");
903 // The descriptions may be out of date. Conservatively clear them all!
904 AbstractTypeDescriptions.clear();
906 #ifdef DEBUG_MERGE_TYPES
907 std::cerr << "REFINING abstract type [" << (void*)this << " "
908 << *this << "] to [" << (void*)NewType << " "
909 << *NewType << "]!\n";
913 // Make sure to put the type to be refined to into a holder so that if IT gets
914 // refined, that we will not continue using a dead reference...
916 PATypeHolder NewTy(NewType);
918 // Add a self use of the current type so that we don't delete ourself until
919 // after this while loop. We are careful to never invoke refine on ourself,
920 // so this extra reference shouldn't be a problem. Note that we must only
921 // remove a single reference at the end, but we must tolerate multiple self
922 // references because we could be refineAbstractTypeTo'ing recursively on the
925 addAbstractTypeUser(this);
927 // Count the number of self uses. Stop looping when sizeof(list) == NSU.
928 unsigned NumSelfUses = 0;
930 // Iterate over all of the uses of this type, invoking callback. Each user
931 // should remove itself from our use list automatically. We have to check to
932 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
933 // will not cause users to drop off of the use list. If we resolve to ourself
936 while (AbstractTypeUsers.size() > NumSelfUses && NewTy != this) {
937 AbstractTypeUser *User = AbstractTypeUsers.back();
940 // Move self use to the start of the list. Increment NSU.
941 std::swap(AbstractTypeUsers.back(), AbstractTypeUsers[NumSelfUses++]);
943 unsigned OldSize = AbstractTypeUsers.size();
944 #ifdef DEBUG_MERGE_TYPES
945 std::cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
946 << "] of abstract type [" << (void*)this << " "
947 << *this << "] to [" << (void*)NewTy.get() << " "
950 User->refineAbstractType(this, NewTy);
952 #ifdef DEBUG_MERGE_TYPES
953 if (AbstractTypeUsers.size() == OldSize) {
954 User->refineAbstractType(this, NewTy);
955 if (AbstractTypeUsers.back() != User)
956 std::cerr << "User changed!\n";
957 std::cerr << "Top of user list is:\n";
958 AbstractTypeUsers.back()->dump();
960 std::cerr <<"\nOld User=\n";
964 assert(AbstractTypeUsers.size() != OldSize &&
965 "AbsTyUser did not remove self from user list!");
969 // Remove a single self use, even though there may be several here. This will
970 // probably 'delete this', so no instance variables may be used after this
973 assert((NewTy == this || AbstractTypeUsers.back() == this) &&
974 "Only self uses should be left!");
975 removeAbstractTypeUser(this);
978 // typeIsRefined - Notify AbstractTypeUsers of this type that the current type
979 // has been refined a bit. The pointer is still valid and still should be
980 // used, but the subtypes have changed.
982 void DerivedType::typeIsRefined() {
983 assert(isRefining >= 0 && isRefining <= 2 && "isRefining out of bounds!");
984 if (isRefining == 1) return; // Kill recursion here...
987 #ifdef DEBUG_MERGE_TYPES
988 std::cerr << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
991 // In this loop we have to be very careful not to get into infinite loops and
992 // other problem cases. Specifically, we loop through all of the abstract
993 // type users in the user list, notifying them that the type has been refined.
994 // At their choice, they may or may not choose to remove themselves from the
995 // list of users. Regardless of whether they do or not, we have to be sure
996 // that we only notify each user exactly once. Because the refineAbstractType
997 // method can cause an arbitrary permutation to the user list, we cannot loop
998 // through it in any particular order and be guaranteed that we will be
999 // successful at this aim. Because of this, we keep track of all the users we
1000 // have visited and only visit users we have not seen. Because this user list
1001 // should be small, we use a vector instead of a full featured set to keep
1002 // track of what users we have notified so far.
1004 std::vector<AbstractTypeUser*> Refined;
1007 for (i = AbstractTypeUsers.size(); i != 0; --i)
1008 if (find(Refined.begin(), Refined.end(), AbstractTypeUsers[i-1]) ==
1010 break; // Found an unrefined user?
1012 if (i == 0) break; // Noone to refine left, break out of here!
1014 AbstractTypeUser *ATU = AbstractTypeUsers[--i];
1015 Refined.push_back(ATU); // Keep track of which users we have refined!
1017 #ifdef DEBUG_MERGE_TYPES
1018 std::cerr << " typeIsREFINED user " << i << "[" << ATU
1019 << "] of abstract type [" << (void*)this << " "
1022 ATU->refineAbstractType(this, this);
1028 if (!(isAbstract() || AbstractTypeUsers.empty()))
1029 for (unsigned i = 0; i < AbstractTypeUsers.size(); ++i) {
1030 if (AbstractTypeUsers[i] != this) {
1032 std::cerr << "FOUND FAILURE\nUser: ";
1033 AbstractTypeUsers[i]->dump();
1034 std::cerr << "\nCatch:\n";
1035 AbstractTypeUsers[i]->refineAbstractType(this, this);
1036 assert(0 && "Type became concrete,"
1037 " but it still has abstract type users hanging around!");
1046 // refineAbstractType - Called when a contained type is found to be more
1047 // concrete - this could potentially change us from an abstract type to a
1050 void FunctionType::refineAbstractType(const DerivedType *OldType,
1051 const Type *NewType) {
1052 #ifdef DEBUG_MERGE_TYPES
1053 std::cerr << "FunctionTy::refineAbstractTy(" << (void*)OldType << "["
1054 << *OldType << "], " << (void*)NewType << " ["
1055 << *NewType << "])\n";
1057 // Find the type element we are refining...
1058 if (ResultType == OldType) {
1059 ResultType.removeUserFromConcrete();
1060 ResultType = NewType;
1062 for (unsigned i = 0, e = ParamTys.size(); i != e; ++i)
1063 if (ParamTys[i] == OldType) {
1064 ParamTys[i].removeUserFromConcrete();
1065 ParamTys[i] = NewType;
1068 const FunctionType *MT = FunctionTypes.containsEquivalent(this);
1069 if (MT && MT != this) {
1070 refineAbstractTypeTo(MT); // Different type altogether...
1072 // If the type is currently thought to be abstract, rescan all of our
1073 // subtypes to see if the type has just become concrete!
1074 if (isAbstract()) setAbstract(isTypeAbstract());
1075 typeIsRefined(); // Same type, different contents...
1080 // refineAbstractType - Called when a contained type is found to be more
1081 // concrete - this could potentially change us from an abstract type to a
1084 void ArrayType::refineAbstractType(const DerivedType *OldType,
1085 const Type *NewType) {
1086 #ifdef DEBUG_MERGE_TYPES
1087 std::cerr << "ArrayTy::refineAbstractTy(" << (void*)OldType << "["
1088 << *OldType << "], " << (void*)NewType << " ["
1089 << *NewType << "])\n";
1092 assert(getElementType() == OldType);
1093 ElementType.removeUserFromConcrete();
1094 ElementType = NewType;
1096 const ArrayType *AT = ArrayTypes.containsEquivalent(this);
1097 if (AT && AT != this) {
1098 refineAbstractTypeTo(AT); // Different type altogether...
1100 // If the type is currently thought to be abstract, rescan all of our
1101 // subtypes to see if the type has just become concrete!
1102 if (isAbstract()) setAbstract(isTypeAbstract());
1103 typeIsRefined(); // Same type, different contents...
1108 // refineAbstractType - Called when a contained type is found to be more
1109 // concrete - this could potentially change us from an abstract type to a
1112 void StructType::refineAbstractType(const DerivedType *OldType,
1113 const Type *NewType) {
1114 #ifdef DEBUG_MERGE_TYPES
1115 std::cerr << "StructTy::refineAbstractTy(" << (void*)OldType << "["
1116 << *OldType << "], " << (void*)NewType << " ["
1117 << *NewType << "])\n";
1119 for (int i = ETypes.size()-1; i >= 0; --i)
1120 if (ETypes[i] == OldType) {
1121 ETypes[i].removeUserFromConcrete();
1123 // Update old type to new type in the array...
1124 ETypes[i] = NewType;
1127 const StructType *ST = StructTypes.containsEquivalent(this);
1128 if (ST && ST != this) {
1129 refineAbstractTypeTo(ST); // Different type altogether...
1131 // If the type is currently thought to be abstract, rescan all of our
1132 // subtypes to see if the type has just become concrete!
1133 if (isAbstract()) setAbstract(isTypeAbstract());
1134 typeIsRefined(); // Same type, different contents...
1138 // refineAbstractType - Called when a contained type is found to be more
1139 // concrete - this could potentially change us from an abstract type to a
1142 void PointerType::refineAbstractType(const DerivedType *OldType,
1143 const Type *NewType) {
1144 #ifdef DEBUG_MERGE_TYPES
1145 std::cerr << "PointerTy::refineAbstractTy(" << (void*)OldType << "["
1146 << *OldType << "], " << (void*)NewType << " ["
1147 << *NewType << "])\n";
1150 assert(ElementType == OldType);
1151 ElementType.removeUserFromConcrete();
1152 ElementType = NewType;
1154 const PointerType *PT = PointerTypes.containsEquivalent(this);
1155 if (PT && PT != this) {
1156 refineAbstractTypeTo(PT); // Different type altogether...
1158 // If the type is currently thought to be abstract, rescan all of our
1159 // subtypes to see if the type has just become concrete!
1160 if (isAbstract()) setAbstract(isTypeAbstract());
1161 typeIsRefined(); // Same type, different contents...