1 //===-- Type.cpp - Implement the Type class -------------------------------===//
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 canonical 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 Type::Type(const std::string &name, PrimitiveID id)
36 : Value(Type::TypeTy, Value::TypeVal), ForwardType(0) {
38 ConcreteTypeDescriptions[this] = name;
41 UID = CurUID++; // Assign types UID's as they are created
42 UIDMappings.push_back(this);
45 void Type::setName(const std::string &Name, SymbolTable *ST) {
46 assert(ST && "Type::setName - Must provide symbol table argument!");
48 if (Name.size()) ST->insert(Name, this);
52 const Type *Type::getUniqueIDType(unsigned UID) {
53 assert(UID < UIDMappings.size() &&
54 "Type::getPrimitiveType: UID out of range!");
55 return UIDMappings[UID];
58 const Type *Type::getPrimitiveType(PrimitiveID IDNumber) {
60 case VoidTyID : return VoidTy;
61 case BoolTyID : return BoolTy;
62 case UByteTyID : return UByteTy;
63 case SByteTyID : return SByteTy;
64 case UShortTyID: return UShortTy;
65 case ShortTyID : return ShortTy;
66 case UIntTyID : return UIntTy;
67 case IntTyID : return IntTy;
68 case ULongTyID : return ULongTy;
69 case LongTyID : return LongTy;
70 case FloatTyID : return FloatTy;
71 case DoubleTyID: return DoubleTy;
72 case TypeTyID : return TypeTy;
73 case LabelTyID : return LabelTy;
79 // isLosslesslyConvertibleTo - Return true if this type can be converted to
80 // 'Ty' without any reinterpretation of bits. For example, uint to int.
82 bool Type::isLosslesslyConvertibleTo(const Type *Ty) const {
83 if (this == Ty) return true;
84 if ((!isPrimitiveType() && !isa<PointerType>(this)) ||
85 (!isa<PointerType>(Ty) && !Ty->isPrimitiveType())) return false;
87 if (getPrimitiveID() == Ty->getPrimitiveID())
88 return true; // Handles identity cast, and cast of differing pointer types
90 // Now we know that they are two differing primitive or pointer types
91 switch (getPrimitiveID()) {
92 case Type::UByteTyID: return Ty == Type::SByteTy;
93 case Type::SByteTyID: return Ty == Type::UByteTy;
94 case Type::UShortTyID: return Ty == Type::ShortTy;
95 case Type::ShortTyID: return Ty == Type::UShortTy;
96 case Type::UIntTyID: return Ty == Type::IntTy;
97 case Type::IntTyID: return Ty == Type::UIntTy;
100 case Type::PointerTyID:
101 return Ty == Type::ULongTy || Ty == Type::LongTy || isa<PointerType>(Ty);
103 return false; // Other types have no identity values
107 // getPrimitiveSize - Return the basic size of this type if it is a primitive
108 // type. These are fixed by LLVM and are not target dependent. This will
109 // return zero if the type does not have a size or is not a primitive type.
111 unsigned Type::getPrimitiveSize() const {
112 switch (getPrimitiveID()) {
113 #define HANDLE_PRIM_TYPE(TY,SIZE) case TY##TyID: return SIZE;
114 #include "llvm/Type.def"
120 /// getForwardedTypeInternal - This method is used to implement the union-find
121 /// algorithm for when a type is being forwarded to another type.
122 const Type *Type::getForwardedTypeInternal() const {
123 assert(ForwardType && "This type is not being forwarded to another type!");
125 // Check to see if the forwarded type has been forwarded on. If so, collapse
126 // the forwarding links.
127 const Type *RealForwardedType = ForwardType->getForwardedType();
128 if (!RealForwardedType)
129 return ForwardType; // No it's not forwarded again
131 // Yes, it is forwarded again. First thing, add the reference to the new
133 if (RealForwardedType->isAbstract())
134 cast<DerivedType>(RealForwardedType)->addRef();
136 // Now drop the old reference. This could cause ForwardType to get deleted.
137 cast<DerivedType>(ForwardType)->dropRef();
139 // Return the updated type.
140 ForwardType = RealForwardedType;
144 // getTypeDescription - This is a recursive function that walks a type hierarchy
145 // calculating the description for a type.
147 static std::string getTypeDescription(const Type *Ty,
148 std::vector<const Type *> &TypeStack) {
149 if (isa<OpaqueType>(Ty)) { // Base case for the recursion
150 std::map<const Type*, std::string>::iterator I =
151 AbstractTypeDescriptions.lower_bound(Ty);
152 if (I != AbstractTypeDescriptions.end() && I->first == Ty)
154 std::string Desc = "opaque"+utostr(Ty->getUniqueID());
155 AbstractTypeDescriptions.insert(std::make_pair(Ty, Desc));
159 if (!Ty->isAbstract()) { // Base case for the recursion
160 std::map<const Type*, std::string>::iterator I =
161 ConcreteTypeDescriptions.find(Ty);
162 if (I != ConcreteTypeDescriptions.end()) return I->second;
165 // Check to see if the Type is already on the stack...
166 unsigned Slot = 0, CurSize = TypeStack.size();
167 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
169 // This is another base case for the recursion. In this case, we know
170 // that we have looped back to a type that we have previously visited.
171 // Generate the appropriate upreference to handle this.
174 return "\\" + utostr(CurSize-Slot); // Here's the upreference
176 // Recursive case: derived types...
178 TypeStack.push_back(Ty); // Add us to the stack..
180 switch (Ty->getPrimitiveID()) {
181 case Type::FunctionTyID: {
182 const FunctionType *FTy = cast<FunctionType>(Ty);
183 Result = getTypeDescription(FTy->getReturnType(), TypeStack) + " (";
184 for (FunctionType::ParamTypes::const_iterator
185 I = FTy->getParamTypes().begin(),
186 E = FTy->getParamTypes().end(); I != E; ++I) {
187 if (I != FTy->getParamTypes().begin())
189 Result += getTypeDescription(*I, TypeStack);
191 if (FTy->isVarArg()) {
192 if (!FTy->getParamTypes().empty()) Result += ", ";
198 case Type::StructTyID: {
199 const StructType *STy = cast<StructType>(Ty);
201 for (StructType::ElementTypes::const_iterator
202 I = STy->getElementTypes().begin(),
203 E = STy->getElementTypes().end(); I != E; ++I) {
204 if (I != STy->getElementTypes().begin())
206 Result += getTypeDescription(*I, TypeStack);
211 case Type::PointerTyID: {
212 const PointerType *PTy = cast<PointerType>(Ty);
213 Result = getTypeDescription(PTy->getElementType(), TypeStack) + " *";
216 case Type::ArrayTyID: {
217 const ArrayType *ATy = cast<ArrayType>(Ty);
218 unsigned NumElements = ATy->getNumElements();
220 Result += utostr(NumElements) + " x ";
221 Result += getTypeDescription(ATy->getElementType(), TypeStack) + "]";
226 assert(0 && "Unhandled type in getTypeDescription!");
229 TypeStack.pop_back(); // Remove self from stack...
236 static const std::string &getOrCreateDesc(std::map<const Type*,std::string>&Map,
238 std::map<const Type*, std::string>::iterator I = Map.find(Ty);
239 if (I != Map.end()) return I->second;
241 std::vector<const Type *> TypeStack;
242 return Map[Ty] = getTypeDescription(Ty, TypeStack);
246 const std::string &Type::getDescription() const {
248 return getOrCreateDesc(AbstractTypeDescriptions, this);
250 return getOrCreateDesc(ConcreteTypeDescriptions, this);
254 bool StructType::indexValid(const Value *V) const {
255 if (!isa<Constant>(V)) return false;
256 if (V->getType() != Type::UByteTy) return false;
257 unsigned Idx = cast<ConstantUInt>(V)->getValue();
258 return Idx < ETypes.size();
261 // getTypeAtIndex - Given an index value into the type, return the type of the
262 // element. For a structure type, this must be a constant value...
264 const Type *StructType::getTypeAtIndex(const Value *V) const {
265 assert(isa<Constant>(V) && "Structure index must be a constant!!");
266 assert(V->getType() == Type::UByteTy && "Structure index must be ubyte!");
267 unsigned Idx = cast<ConstantUInt>(V)->getValue();
268 assert(Idx < ETypes.size() && "Structure index out of range!");
269 assert(indexValid(V) && "Invalid structure index!"); // Duplicate check
275 //===----------------------------------------------------------------------===//
277 //===----------------------------------------------------------------------===//
279 // These classes are used to implement specialized behavior for each different
282 struct SignedIntType : public Type {
283 SignedIntType(const std::string &Name, PrimitiveID id) : Type(Name, id) {}
285 // isSigned - Return whether a numeric type is signed.
286 virtual bool isSigned() const { return 1; }
288 // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
289 // virtual function invocation.
291 virtual bool isInteger() const { return 1; }
294 struct UnsignedIntType : public Type {
295 UnsignedIntType(const std::string &N, PrimitiveID id) : Type(N, id) {}
297 // isUnsigned - Return whether a numeric type is signed.
298 virtual bool isUnsigned() const { return 1; }
300 // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
301 // virtual function invocation.
303 virtual bool isInteger() const { return 1; }
306 struct OtherType : public Type {
307 OtherType(const std::string &N, PrimitiveID id) : Type(N, id) {}
310 static struct TypeType : public Type {
311 TypeType() : Type("type", TypeTyID) {}
312 } TheTypeTy; // Implement the type that is global.
315 //===----------------------------------------------------------------------===//
316 // Static 'Type' data
317 //===----------------------------------------------------------------------===//
319 static OtherType TheVoidTy ("void" , Type::VoidTyID);
320 static OtherType TheBoolTy ("bool" , Type::BoolTyID);
321 static SignedIntType TheSByteTy ("sbyte" , Type::SByteTyID);
322 static UnsignedIntType TheUByteTy ("ubyte" , Type::UByteTyID);
323 static SignedIntType TheShortTy ("short" , Type::ShortTyID);
324 static UnsignedIntType TheUShortTy("ushort", Type::UShortTyID);
325 static SignedIntType TheIntTy ("int" , Type::IntTyID);
326 static UnsignedIntType TheUIntTy ("uint" , Type::UIntTyID);
327 static SignedIntType TheLongTy ("long" , Type::LongTyID);
328 static UnsignedIntType TheULongTy ("ulong" , Type::ULongTyID);
329 static OtherType TheFloatTy ("float" , Type::FloatTyID);
330 static OtherType TheDoubleTy("double", Type::DoubleTyID);
331 static OtherType TheLabelTy ("label" , Type::LabelTyID);
333 Type *Type::VoidTy = &TheVoidTy;
334 Type *Type::BoolTy = &TheBoolTy;
335 Type *Type::SByteTy = &TheSByteTy;
336 Type *Type::UByteTy = &TheUByteTy;
337 Type *Type::ShortTy = &TheShortTy;
338 Type *Type::UShortTy = &TheUShortTy;
339 Type *Type::IntTy = &TheIntTy;
340 Type *Type::UIntTy = &TheUIntTy;
341 Type *Type::LongTy = &TheLongTy;
342 Type *Type::ULongTy = &TheULongTy;
343 Type *Type::FloatTy = &TheFloatTy;
344 Type *Type::DoubleTy = &TheDoubleTy;
345 Type *Type::TypeTy = &TheTypeTy;
346 Type *Type::LabelTy = &TheLabelTy;
349 //===----------------------------------------------------------------------===//
350 // Derived Type Constructors
351 //===----------------------------------------------------------------------===//
353 FunctionType::FunctionType(const Type *Result,
354 const std::vector<const Type*> &Params,
355 bool IsVarArgs) : DerivedType(FunctionTyID),
356 ResultType(PATypeHandle(Result, this)),
357 isVarArgs(IsVarArgs) {
358 bool isAbstract = Result->isAbstract();
359 ParamTys.reserve(Params.size());
360 for (unsigned i = 0; i < Params.size(); ++i) {
361 ParamTys.push_back(PATypeHandle(Params[i], this));
362 isAbstract |= Params[i]->isAbstract();
365 // Calculate whether or not this type is abstract
366 setAbstract(isAbstract);
369 StructType::StructType(const std::vector<const Type*> &Types)
370 : CompositeType(StructTyID) {
371 ETypes.reserve(Types.size());
372 bool isAbstract = false;
373 for (unsigned i = 0; i < Types.size(); ++i) {
374 assert(Types[i] != Type::VoidTy && "Void type in method prototype!!");
375 ETypes.push_back(PATypeHandle(Types[i], this));
376 isAbstract |= Types[i]->isAbstract();
379 // Calculate whether or not this type is abstract
380 setAbstract(isAbstract);
383 ArrayType::ArrayType(const Type *ElType, unsigned NumEl)
384 : SequentialType(ArrayTyID, ElType) {
387 // Calculate whether or not this type is abstract
388 setAbstract(ElType->isAbstract());
391 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
392 // Calculate whether or not this type is abstract
393 setAbstract(E->isAbstract());
396 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
398 #ifdef DEBUG_MERGE_TYPES
399 std::cerr << "Derived new type: " << *this << "\n";
404 // getAlwaysOpaqueTy - This function returns an opaque type. It doesn't matter
405 // _which_ opaque type it is, but the opaque type must never get resolved.
407 static Type *getAlwaysOpaqueTy() {
408 static Type *AlwaysOpaqueTy = OpaqueType::get();
409 static PATypeHolder Holder(AlwaysOpaqueTy);
410 return AlwaysOpaqueTy;
414 //===----------------------------------------------------------------------===//
415 // dropAllTypeUses methods - These methods eliminate any possibly recursive type
416 // references from a derived type. The type must remain abstract, so we make
417 // sure to use an always opaque type as an argument.
420 void FunctionType::dropAllTypeUses() {
421 ResultType = getAlwaysOpaqueTy();
425 void ArrayType::dropAllTypeUses() {
426 ElementType = getAlwaysOpaqueTy();
429 void StructType::dropAllTypeUses() {
431 ETypes.push_back(PATypeHandle(getAlwaysOpaqueTy(), this));
434 void PointerType::dropAllTypeUses() {
435 ElementType = getAlwaysOpaqueTy();
441 // isTypeAbstract - This is a recursive function that walks a type hierarchy
442 // calculating whether or not a type is abstract. Worst case it will have to do
443 // a lot of traversing if you have some whacko opaque types, but in most cases,
444 // it will do some simple stuff when it hits non-abstract types that aren't
447 bool Type::isTypeAbstract() {
448 if (!isAbstract()) // Base case for the recursion
449 return false; // Primitive = leaf type
451 if (isa<OpaqueType>(this)) // Base case for the recursion
452 return true; // This whole type is abstract!
454 // We have to guard against recursion. To do this, we temporarily mark this
455 // type as concrete, so that if we get back to here recursively we will think
456 // it's not abstract, and thus not scan it again.
459 // Scan all of the sub-types. If any of them are abstract, than so is this
461 for (Type::subtype_iterator I = subtype_begin(), E = subtype_end();
463 if (const_cast<Type*>(*I)->isTypeAbstract()) {
464 setAbstract(true); // Restore the abstract bit.
465 return true; // This type is abstract if subtype is abstract!
468 // Restore the abstract bit.
471 // Nothing looks abstract here...
476 //===----------------------------------------------------------------------===//
477 // Type Structural Equality Testing
478 //===----------------------------------------------------------------------===//
480 // TypesEqual - Two types are considered structurally equal if they have the
481 // same "shape": Every level and element of the types have identical primitive
482 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
483 // be pointer equals to be equivalent though. This uses an optimistic algorithm
484 // that assumes that two graphs are the same until proven otherwise.
486 static bool TypesEqual(const Type *Ty, const Type *Ty2,
487 std::map<const Type *, const Type *> &EqTypes) {
488 if (Ty == Ty2) return true;
489 if (Ty->getPrimitiveID() != Ty2->getPrimitiveID()) return false;
490 if (Ty->isPrimitiveType()) return true;
491 if (isa<OpaqueType>(Ty))
492 return false; // Two unequal opaque types are never equal
494 std::map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
495 if (It != EqTypes.end())
496 return It->second == Ty2; // Looping back on a type, check for equality
498 // Otherwise, add the mapping to the table to make sure we don't get
499 // recursion on the types...
500 EqTypes.insert(std::make_pair(Ty, Ty2));
502 // Iterate over the types and make sure the the contents are equivalent...
503 Type::subtype_iterator I = Ty ->subtype_begin(), IE = Ty ->subtype_end();
504 Type::subtype_iterator I2 = Ty2->subtype_begin(), IE2 = Ty2->subtype_end();
505 for (; I != IE && I2 != IE2; ++I, ++I2)
506 if (!TypesEqual(*I, *I2, EqTypes)) return false;
508 // Two really annoying special cases that breaks an otherwise nice simple
509 // algorithm is the fact that arraytypes have sizes that differentiates types,
510 // and that function types can be varargs or not. Consider this now.
511 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
512 if (ATy->getNumElements() != cast<ArrayType>(Ty2)->getNumElements())
514 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
515 if (FTy->isVarArg() != cast<FunctionType>(Ty2)->isVarArg())
519 return I == IE && I2 == IE2; // Types equal if both iterators are done
522 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
523 std::map<const Type *, const Type *> EqTypes;
524 return TypesEqual(Ty, Ty2, EqTypes);
529 //===----------------------------------------------------------------------===//
530 // Derived Type Factory Functions
531 //===----------------------------------------------------------------------===//
533 // TypeMap - Make sure that only one instance of a particular type may be
534 // created on any given run of the compiler... note that this involves updating
535 // our map if an abstract type gets refined somehow...
537 template<class ValType, class TypeClass>
539 typedef std::map<ValType, TypeClass *> MapTy;
542 typedef typename MapTy::iterator iterator;
543 ~TypeMap() { print("ON EXIT"); }
545 inline TypeClass *get(const ValType &V) {
546 iterator I = Map.find(V);
547 return I != Map.end() ? I->second : 0;
550 inline void add(const ValType &V, TypeClass *T) {
551 Map.insert(std::make_pair(V, T));
555 iterator getEntryForType(TypeClass *Ty) {
556 iterator I = Map.find(ValType::get(Ty));
557 if (I == Map.end()) print("ERROR!");
558 assert(I != Map.end() && "Didn't find type entry!");
559 assert(I->second == Ty && "Type entry wrong?");
564 void finishRefinement(iterator TyIt) {
565 TypeClass *Ty = TyIt->second;
567 // The old record is now out-of-date, because one of the children has been
568 // updated. Remove the obsolete entry from the map.
571 // Now we check to see if there is an existing entry in the table which is
572 // structurally identical to the newly refined type. If so, this type gets
573 // refined to the pre-existing type.
575 for (iterator I = Map.begin(), E = Map.end(); I != E; ++I)
576 if (TypesEqual(Ty, I->second)) {
577 assert(Ty->isAbstract() && "Replacing a non-abstract type?");
578 TypeClass *NewTy = I->second;
580 // Refined to a different type altogether?
581 Ty->refineAbstractTypeTo(NewTy);
585 // If there is no existing type of the same structure, we reinsert an
586 // updated record into the map.
587 Map.insert(std::make_pair(ValType::get(Ty), Ty));
589 // If the type is currently thought to be abstract, rescan all of our
590 // subtypes to see if the type has just become concrete!
591 if (Ty->isAbstract()) {
592 Ty->setAbstract(Ty->isTypeAbstract());
594 // If the type just became concrete, notify all users!
595 if (!Ty->isAbstract())
596 Ty->notifyUsesThatTypeBecameConcrete();
600 void remove(const ValType &OldVal) {
601 iterator I = Map.find(OldVal);
602 assert(I != Map.end() && "TypeMap::remove, element not found!");
606 void remove(iterator I) {
607 assert(I != Map.end() && "Cannot remove invalid iterator pointer!");
611 void print(const char *Arg) const {
612 #ifdef DEBUG_MERGE_TYPES
613 std::cerr << "TypeMap<>::" << Arg << " table contents:\n";
615 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
617 std::cerr << " " << (++i) << ". " << (void*)I->second << " "
618 << *I->second << "\n";
622 void dump() const { print("dump output"); }
627 //===----------------------------------------------------------------------===//
628 // Function Type Factory and Value Class...
631 // FunctionValType - Define a class to hold the key that goes into the TypeMap
633 class FunctionValType {
635 std::vector<const Type*> ArgTypes;
638 FunctionValType(const Type *ret, const std::vector<const Type*> &args,
639 bool IVA) : RetTy(ret), isVarArg(IVA) {
640 for (unsigned i = 0; i < args.size(); ++i)
641 ArgTypes.push_back(args[i]);
644 static FunctionValType get(const FunctionType *FT);
646 // Subclass should override this... to update self as usual
647 void doRefinement(const DerivedType *OldType, const Type *NewType) {
648 if (RetTy == OldType) RetTy = NewType;
649 for (unsigned i = 0, e = ArgTypes.size(); i != e; ++i)
650 if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
653 inline bool operator<(const FunctionValType &MTV) const {
654 if (RetTy < MTV.RetTy) return true;
655 if (RetTy > MTV.RetTy) return false;
657 if (ArgTypes < MTV.ArgTypes) return true;
658 return ArgTypes == MTV.ArgTypes && isVarArg < MTV.isVarArg;
662 // Define the actual map itself now...
663 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
665 FunctionValType FunctionValType::get(const FunctionType *FT) {
666 // Build up a FunctionValType
667 std::vector<const Type *> ParamTypes;
668 ParamTypes.reserve(FT->getParamTypes().size());
669 for (unsigned i = 0, e = FT->getParamTypes().size(); i != e; ++i)
670 ParamTypes.push_back(FT->getParamType(i));
671 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
675 // FunctionType::get - The factory function for the FunctionType class...
676 FunctionType *FunctionType::get(const Type *ReturnType,
677 const std::vector<const Type*> &Params,
679 FunctionValType VT(ReturnType, Params, isVarArg);
680 FunctionType *MT = FunctionTypes.get(VT);
683 FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
685 #ifdef DEBUG_MERGE_TYPES
686 std::cerr << "Derived new type: " << MT << "\n";
691 //===----------------------------------------------------------------------===//
692 // Array Type Factory...
698 ArrayValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
700 static ArrayValType get(const ArrayType *AT) {
701 return ArrayValType(AT->getElementType(), AT->getNumElements());
704 // Subclass should override this... to update self as usual
705 void doRefinement(const DerivedType *OldType, const Type *NewType) {
706 assert(ValTy == OldType);
710 inline bool operator<(const ArrayValType &MTV) const {
711 if (Size < MTV.Size) return true;
712 return Size == MTV.Size && ValTy < MTV.ValTy;
716 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
719 ArrayType *ArrayType::get(const Type *ElementType, unsigned NumElements) {
720 assert(ElementType && "Can't get array of null types!");
722 ArrayValType AVT(ElementType, NumElements);
723 ArrayType *AT = ArrayTypes.get(AVT);
724 if (AT) return AT; // Found a match, return it!
726 // Value not found. Derive a new type!
727 ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
729 #ifdef DEBUG_MERGE_TYPES
730 std::cerr << "Derived new type: " << *AT << "\n";
735 //===----------------------------------------------------------------------===//
736 // Struct Type Factory...
739 // StructValType - Define a class to hold the key that goes into the TypeMap
741 class StructValType {
742 std::vector<const Type*> ElTypes;
744 StructValType(const std::vector<const Type*> &args) : ElTypes(args) {}
746 static StructValType get(const StructType *ST) {
747 std::vector<const Type *> ElTypes;
748 ElTypes.reserve(ST->getElementTypes().size());
749 for (unsigned i = 0, e = ST->getElementTypes().size(); i != e; ++i)
750 ElTypes.push_back(ST->getElementTypes()[i]);
752 return StructValType(ElTypes);
755 // Subclass should override this... to update self as usual
756 void doRefinement(const DerivedType *OldType, const Type *NewType) {
757 for (unsigned i = 0; i < ElTypes.size(); ++i)
758 if (ElTypes[i] == OldType) ElTypes[i] = NewType;
761 inline bool operator<(const StructValType &STV) const {
762 return ElTypes < STV.ElTypes;
766 static TypeMap<StructValType, StructType> StructTypes;
768 StructType *StructType::get(const std::vector<const Type*> &ETypes) {
769 StructValType STV(ETypes);
770 StructType *ST = StructTypes.get(STV);
773 // Value not found. Derive a new type!
774 StructTypes.add(STV, ST = new StructType(ETypes));
776 #ifdef DEBUG_MERGE_TYPES
777 std::cerr << "Derived new type: " << *ST << "\n";
784 //===----------------------------------------------------------------------===//
785 // Pointer Type Factory...
788 // PointerValType - Define a class to hold the key that goes into the TypeMap
790 class PointerValType {
793 PointerValType(const Type *val) : ValTy(val) {}
795 static PointerValType get(const PointerType *PT) {
796 return PointerValType(PT->getElementType());
799 // Subclass should override this... to update self as usual
800 void doRefinement(const DerivedType *OldType, const Type *NewType) {
801 assert(ValTy == OldType);
805 bool operator<(const PointerValType &MTV) const {
806 return ValTy < MTV.ValTy;
810 static TypeMap<PointerValType, PointerType> PointerTypes;
812 PointerType *PointerType::get(const Type *ValueType) {
813 assert(ValueType && "Can't get a pointer to <null> type!");
814 PointerValType PVT(ValueType);
816 PointerType *PT = PointerTypes.get(PVT);
819 // Value not found. Derive a new type!
820 PointerTypes.add(PVT, PT = new PointerType(ValueType));
822 #ifdef DEBUG_MERGE_TYPES
823 std::cerr << "Derived new type: " << *PT << "\n";
828 void debug_type_tables() {
829 FunctionTypes.dump();
836 //===----------------------------------------------------------------------===//
837 // Derived Type Refinement Functions
838 //===----------------------------------------------------------------------===//
840 // removeAbstractTypeUser - Notify an abstract type that a user of the class
841 // no longer has a handle to the type. This function is called primarily by
842 // the PATypeHandle class. When there are no users of the abstract type, it
843 // is annihilated, because there is no way to get a reference to it ever again.
845 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
846 // Search from back to front because we will notify users from back to
847 // front. Also, it is likely that there will be a stack like behavior to
848 // users that register and unregister users.
851 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
852 assert(i != 0 && "AbstractTypeUser not in user list!");
854 --i; // Convert to be in range 0 <= i < size()
855 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
857 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
859 #ifdef DEBUG_MERGE_TYPES
860 std::cerr << " remAbstractTypeUser[" << (void*)this << ", "
861 << *this << "][" << i << "] User = " << U << "\n";
864 if (AbstractTypeUsers.empty() && RefCount == 0 && isAbstract()) {
865 #ifdef DEBUG_MERGE_TYPES
866 std::cerr << "DELETEing unused abstract type: <" << *this
867 << ">[" << (void*)this << "]" << "\n";
869 delete this; // No users of this abstract type!
874 // refineAbstractTypeTo - This function is used to when it is discovered that
875 // the 'this' abstract type is actually equivalent to the NewType specified.
876 // This causes all users of 'this' to switch to reference the more concrete type
877 // NewType and for 'this' to be deleted.
879 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
880 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
881 assert(this != NewType && "Can't refine to myself!");
882 assert(ForwardType == 0 && "This type has already been refined!");
884 // The descriptions may be out of date. Conservatively clear them all!
885 AbstractTypeDescriptions.clear();
887 #ifdef DEBUG_MERGE_TYPES
888 std::cerr << "REFINING abstract type [" << (void*)this << " "
889 << *this << "] to [" << (void*)NewType << " "
890 << *NewType << "]!\n";
893 // Make sure to put the type to be refined to into a holder so that if IT gets
894 // refined, that we will not continue using a dead reference...
896 PATypeHolder NewTy(NewType);
898 // Any PATypeHolders referring to this type will now automatically forward to
899 // the type we are resolved to.
900 ForwardType = NewType;
901 if (NewType->isAbstract())
902 cast<DerivedType>(NewType)->addRef();
904 // Add a self use of the current type so that we don't delete ourself until
905 // after the function exits.
907 PATypeHolder CurrentTy(this);
909 // To make the situation simpler, we ask the subclass to remove this type from
910 // the type map, and to replace any type uses with uses of non-abstract types.
911 // This dramatically limits the amount of recursive type trouble we can find
915 // Iterate over all of the uses of this type, invoking callback. Each user
916 // should remove itself from our use list automatically. We have to check to
917 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
918 // will not cause users to drop off of the use list. If we resolve to ourself
921 while (!AbstractTypeUsers.empty() && NewTy != this) {
922 AbstractTypeUser *User = AbstractTypeUsers.back();
924 unsigned OldSize = AbstractTypeUsers.size();
925 #ifdef DEBUG_MERGE_TYPES
926 std::cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
927 << "] of abstract type [" << (void*)this << " "
928 << *this << "] to [" << (void*)NewTy.get() << " "
931 User->refineAbstractType(this, NewTy);
933 assert(AbstractTypeUsers.size() != OldSize &&
934 "AbsTyUser did not remove self from user list!");
937 // If we were successful removing all users from the type, 'this' will be
938 // deleted when the last PATypeHolder is destroyed or updated from this type.
939 // This may occur on exit of this function, as the CurrentTy object is
943 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
944 // the current type has transitioned from being abstract to being concrete.
946 void DerivedType::notifyUsesThatTypeBecameConcrete() {
947 #ifdef DEBUG_MERGE_TYPES
948 std::cerr << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
951 unsigned OldSize = AbstractTypeUsers.size();
952 while (!AbstractTypeUsers.empty()) {
953 AbstractTypeUser *ATU = AbstractTypeUsers.back();
954 ATU->typeBecameConcrete(this);
956 assert(AbstractTypeUsers.size() < OldSize-- &&
957 "AbstractTypeUser did not remove itself from the use list!");
964 // refineAbstractType - Called when a contained type is found to be more
965 // concrete - this could potentially change us from an abstract type to a
968 void FunctionType::refineAbstractType(const DerivedType *OldType,
969 const Type *NewType) {
970 assert((isAbstract() || !OldType->isAbstract()) &&
971 "Refining a non-abstract type!");
972 #ifdef DEBUG_MERGE_TYPES
973 std::cerr << "FunctionTy::refineAbstractTy(" << (void*)OldType << "["
974 << *OldType << "], " << (void*)NewType << " ["
975 << *NewType << "])\n";
978 // Look up our current type map entry..
979 TypeMap<FunctionValType, FunctionType>::iterator TMI =
980 FunctionTypes.getEntryForType(this);
982 // Find the type element we are refining...
983 if (ResultType == OldType) {
984 ResultType.removeUserFromConcrete();
985 ResultType = NewType;
987 for (unsigned i = 0, e = ParamTys.size(); i != e; ++i)
988 if (ParamTys[i] == OldType) {
989 ParamTys[i].removeUserFromConcrete();
990 ParamTys[i] = NewType;
993 FunctionTypes.finishRefinement(TMI);
996 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
997 refineAbstractType(AbsTy, AbsTy);
1001 // refineAbstractType - Called when a contained type is found to be more
1002 // concrete - this could potentially change us from an abstract type to a
1005 void ArrayType::refineAbstractType(const DerivedType *OldType,
1006 const Type *NewType) {
1007 assert((isAbstract() || !OldType->isAbstract()) &&
1008 "Refining a non-abstract type!");
1009 #ifdef DEBUG_MERGE_TYPES
1010 std::cerr << "ArrayTy::refineAbstractTy(" << (void*)OldType << "["
1011 << *OldType << "], " << (void*)NewType << " ["
1012 << *NewType << "])\n";
1015 // Look up our current type map entry..
1016 TypeMap<ArrayValType, ArrayType>::iterator TMI =
1017 ArrayTypes.getEntryForType(this);
1019 assert(getElementType() == OldType);
1020 ElementType.removeUserFromConcrete();
1021 ElementType = NewType;
1023 ArrayTypes.finishRefinement(TMI);
1026 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1027 refineAbstractType(AbsTy, AbsTy);
1031 // refineAbstractType - Called when a contained type is found to be more
1032 // concrete - this could potentially change us from an abstract type to a
1035 void StructType::refineAbstractType(const DerivedType *OldType,
1036 const Type *NewType) {
1037 assert((isAbstract() || !OldType->isAbstract()) &&
1038 "Refining a non-abstract type!");
1039 #ifdef DEBUG_MERGE_TYPES
1040 std::cerr << "StructTy::refineAbstractTy(" << (void*)OldType << "["
1041 << *OldType << "], " << (void*)NewType << " ["
1042 << *NewType << "])\n";
1045 // Look up our current type map entry..
1046 TypeMap<StructValType, StructType>::iterator TMI =
1047 StructTypes.getEntryForType(this);
1049 for (int i = ETypes.size()-1; i >= 0; --i)
1050 if (ETypes[i] == OldType) {
1051 ETypes[i].removeUserFromConcrete();
1053 // Update old type to new type in the array...
1054 ETypes[i] = NewType;
1057 StructTypes.finishRefinement(TMI);
1060 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1061 refineAbstractType(AbsTy, AbsTy);
1064 // refineAbstractType - Called when a contained type is found to be more
1065 // concrete - this could potentially change us from an abstract type to a
1068 void PointerType::refineAbstractType(const DerivedType *OldType,
1069 const Type *NewType) {
1070 assert((isAbstract() || !OldType->isAbstract()) &&
1071 "Refining a non-abstract type!");
1072 #ifdef DEBUG_MERGE_TYPES
1073 std::cerr << "PointerTy::refineAbstractTy(" << (void*)OldType << "["
1074 << *OldType << "], " << (void*)NewType << " ["
1075 << *NewType << "])\n";
1078 // Look up our current type map entry..
1079 TypeMap<PointerValType, PointerType>::iterator TMI =
1080 PointerTypes.getEntryForType(this);
1082 assert(ElementType == OldType);
1083 ElementType.removeUserFromConcrete();
1084 ElementType = NewType;
1086 PointerTypes.finishRefinement(TMI);
1089 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1090 refineAbstractType(AbsTy, AbsTy);