1 //===-- Type.cpp - Implement the Type class -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Type class for the VMCore library.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/DerivedTypes.h"
15 #include "llvm/SymbolTable.h"
16 #include "llvm/Constants.h"
17 #include "Support/DepthFirstIterator.h"
18 #include "Support/StringExtras.h"
19 #include "Support/STLExtras.h"
23 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
24 // created and later destroyed, all in an effort to make sure that there is only
25 // a single canonical version of a type.
27 //#define DEBUG_MERGE_TYPES 1
29 AbstractTypeUser::~AbstractTypeUser() {}
31 //===----------------------------------------------------------------------===//
32 // Type Class Implementation
33 //===----------------------------------------------------------------------===//
35 static unsigned CurUID = 0;
36 static std::vector<const Type *> UIDMappings;
38 // Concrete/Abstract TypeDescriptions - We lazily calculate type descriptions
39 // for types as they are needed. Because resolution of types must invalidate
40 // all of the abstract type descriptions, we keep them in a seperate map to make
42 static std::map<const Type*, std::string> ConcreteTypeDescriptions;
43 static std::map<const Type*, std::string> AbstractTypeDescriptions;
45 Type::Type(const std::string &name, PrimitiveID id)
46 : Value(Type::TypeTy, Value::TypeVal), RefCount(0), ForwardType(0) {
48 ConcreteTypeDescriptions[this] = name;
51 UID = CurUID++; // Assign types UID's as they are created
52 UIDMappings.push_back(this);
55 void Type::setName(const std::string &Name, SymbolTable *ST) {
56 assert(ST && "Type::setName - Must provide symbol table argument!");
58 if (Name.size()) ST->insert(Name, this);
62 const Type *Type::getUniqueIDType(unsigned UID) {
63 assert(UID < UIDMappings.size() &&
64 "Type::getPrimitiveType: UID out of range!");
65 return UIDMappings[UID];
68 const Type *Type::getPrimitiveType(PrimitiveID IDNumber) {
70 case VoidTyID : return VoidTy;
71 case BoolTyID : return BoolTy;
72 case UByteTyID : return UByteTy;
73 case SByteTyID : return SByteTy;
74 case UShortTyID: return UShortTy;
75 case ShortTyID : return ShortTy;
76 case UIntTyID : return UIntTy;
77 case IntTyID : return IntTy;
78 case ULongTyID : return ULongTy;
79 case LongTyID : return LongTy;
80 case FloatTyID : return FloatTy;
81 case DoubleTyID: return DoubleTy;
82 case TypeTyID : return TypeTy;
83 case LabelTyID : return LabelTy;
89 // isLosslesslyConvertibleTo - Return true if this type can be converted to
90 // 'Ty' without any reinterpretation of bits. For example, uint to int.
92 bool Type::isLosslesslyConvertibleTo(const Type *Ty) const {
93 if (this == Ty) return true;
94 if ((!isPrimitiveType() && !isa<PointerType>(this)) ||
95 (!isa<PointerType>(Ty) && !Ty->isPrimitiveType())) return false;
97 if (getPrimitiveID() == Ty->getPrimitiveID())
98 return true; // Handles identity cast, and cast of differing pointer types
100 // Now we know that they are two differing primitive or pointer types
101 switch (getPrimitiveID()) {
102 case Type::UByteTyID: return Ty == Type::SByteTy;
103 case Type::SByteTyID: return Ty == Type::UByteTy;
104 case Type::UShortTyID: return Ty == Type::ShortTy;
105 case Type::ShortTyID: return Ty == Type::UShortTy;
106 case Type::UIntTyID: return Ty == Type::IntTy;
107 case Type::IntTyID: return Ty == Type::UIntTy;
108 case Type::ULongTyID: return Ty == Type::LongTy;
109 case Type::LongTyID: return Ty == Type::ULongTy;
110 case Type::PointerTyID: return isa<PointerType>(Ty);
112 return false; // Other types have no identity values
116 /// getUnsignedVersion - If this is an integer type, return the unsigned
117 /// variant of this type. For example int -> uint.
118 const Type *Type::getUnsignedVersion() const {
119 switch (getPrimitiveID()) {
121 assert(isInteger()&&"Type::getUnsignedVersion is only valid for integers!");
122 case Type::UByteTyID:
123 case Type::SByteTyID: return Type::UByteTy;
124 case Type::UShortTyID:
125 case Type::ShortTyID: return Type::UShortTy;
127 case Type::IntTyID: return Type::UIntTy;
128 case Type::ULongTyID:
129 case Type::LongTyID: return Type::ULongTy;
133 /// getSignedVersion - If this is an integer type, return the signed variant
134 /// of this type. For example uint -> int.
135 const Type *Type::getSignedVersion() const {
136 switch (getPrimitiveID()) {
138 assert(isInteger() && "Type::getSignedVersion is only valid for integers!");
139 case Type::UByteTyID:
140 case Type::SByteTyID: return Type::SByteTy;
141 case Type::UShortTyID:
142 case Type::ShortTyID: return Type::ShortTy;
144 case Type::IntTyID: return Type::IntTy;
145 case Type::ULongTyID:
146 case Type::LongTyID: return Type::LongTy;
151 // getPrimitiveSize - Return the basic size of this type if it is a primitive
152 // type. These are fixed by LLVM and are not target dependent. This will
153 // return zero if the type does not have a size or is not a primitive type.
155 unsigned Type::getPrimitiveSize() const {
156 switch (getPrimitiveID()) {
157 #define HANDLE_PRIM_TYPE(TY,SIZE) case TY##TyID: return SIZE;
158 #include "llvm/Type.def"
164 /// getForwardedTypeInternal - This method is used to implement the union-find
165 /// algorithm for when a type is being forwarded to another type.
166 const Type *Type::getForwardedTypeInternal() const {
167 assert(ForwardType && "This type is not being forwarded to another type!");
169 // Check to see if the forwarded type has been forwarded on. If so, collapse
170 // the forwarding links.
171 const Type *RealForwardedType = ForwardType->getForwardedType();
172 if (!RealForwardedType)
173 return ForwardType; // No it's not forwarded again
175 // Yes, it is forwarded again. First thing, add the reference to the new
177 if (RealForwardedType->isAbstract())
178 cast<DerivedType>(RealForwardedType)->addRef();
180 // Now drop the old reference. This could cause ForwardType to get deleted.
181 cast<DerivedType>(ForwardType)->dropRef();
183 // Return the updated type.
184 ForwardType = RealForwardedType;
188 // getTypeDescription - This is a recursive function that walks a type hierarchy
189 // calculating the description for a type.
191 static std::string getTypeDescription(const Type *Ty,
192 std::vector<const Type *> &TypeStack) {
193 if (isa<OpaqueType>(Ty)) { // Base case for the recursion
194 std::map<const Type*, std::string>::iterator I =
195 AbstractTypeDescriptions.lower_bound(Ty);
196 if (I != AbstractTypeDescriptions.end() && I->first == Ty)
198 std::string Desc = "opaque"+utostr(Ty->getUniqueID());
199 AbstractTypeDescriptions.insert(std::make_pair(Ty, Desc));
203 if (!Ty->isAbstract()) { // Base case for the recursion
204 std::map<const Type*, std::string>::iterator I =
205 ConcreteTypeDescriptions.find(Ty);
206 if (I != ConcreteTypeDescriptions.end()) return I->second;
209 // Check to see if the Type is already on the stack...
210 unsigned Slot = 0, CurSize = TypeStack.size();
211 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
213 // This is another base case for the recursion. In this case, we know
214 // that we have looped back to a type that we have previously visited.
215 // Generate the appropriate upreference to handle this.
218 return "\\" + utostr(CurSize-Slot); // Here's the upreference
220 // Recursive case: derived types...
222 TypeStack.push_back(Ty); // Add us to the stack..
224 switch (Ty->getPrimitiveID()) {
225 case Type::FunctionTyID: {
226 const FunctionType *FTy = cast<FunctionType>(Ty);
227 Result = getTypeDescription(FTy->getReturnType(), TypeStack) + " (";
228 for (FunctionType::param_iterator I = FTy->param_begin(),
229 E = FTy->param_end(); I != E; ++I) {
230 if (I != FTy->param_begin())
232 Result += getTypeDescription(*I, TypeStack);
234 if (FTy->isVarArg()) {
235 if (FTy->getNumParams()) Result += ", ";
241 case Type::StructTyID: {
242 const StructType *STy = cast<StructType>(Ty);
244 for (StructType::element_iterator I = STy->element_begin(),
245 E = STy->element_end(); I != E; ++I) {
246 if (I != STy->element_begin())
248 Result += getTypeDescription(*I, TypeStack);
253 case Type::PointerTyID: {
254 const PointerType *PTy = cast<PointerType>(Ty);
255 Result = getTypeDescription(PTy->getElementType(), TypeStack) + " *";
258 case Type::ArrayTyID: {
259 const ArrayType *ATy = cast<ArrayType>(Ty);
260 unsigned NumElements = ATy->getNumElements();
262 Result += utostr(NumElements) + " x ";
263 Result += getTypeDescription(ATy->getElementType(), TypeStack) + "]";
268 assert(0 && "Unhandled type in getTypeDescription!");
271 TypeStack.pop_back(); // Remove self from stack...
278 static const std::string &getOrCreateDesc(std::map<const Type*,std::string>&Map,
280 std::map<const Type*, std::string>::iterator I = Map.find(Ty);
281 if (I != Map.end()) return I->second;
283 std::vector<const Type *> TypeStack;
284 return Map[Ty] = getTypeDescription(Ty, TypeStack);
288 const std::string &Type::getDescription() const {
290 return getOrCreateDesc(AbstractTypeDescriptions, this);
292 return getOrCreateDesc(ConcreteTypeDescriptions, this);
296 bool StructType::indexValid(const Value *V) const {
297 // Structure indexes require unsigned integer constants.
298 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(V))
299 return CU->getValue() < ContainedTys.size();
303 // getTypeAtIndex - Given an index value into the type, return the type of the
304 // element. For a structure type, this must be a constant value...
306 const Type *StructType::getTypeAtIndex(const Value *V) const {
307 assert(isa<Constant>(V) && "Structure index must be a constant!!");
308 unsigned Idx = cast<ConstantUInt>(V)->getValue();
309 assert(Idx < ContainedTys.size() && "Structure index out of range!");
310 assert(indexValid(V) && "Invalid structure index!"); // Duplicate check
311 return ContainedTys[Idx];
315 //===----------------------------------------------------------------------===//
317 //===----------------------------------------------------------------------===//
319 // These classes are used to implement specialized behavior for each different
322 struct SignedIntType : public Type {
323 SignedIntType(const std::string &Name, PrimitiveID id) : Type(Name, id) {}
325 // isSigned - Return whether a numeric type is signed.
326 virtual bool isSigned() const { return 1; }
328 // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
329 // virtual function invocation.
331 virtual bool isInteger() const { return 1; }
334 struct UnsignedIntType : public Type {
335 UnsignedIntType(const std::string &N, PrimitiveID id) : Type(N, id) {}
337 // isUnsigned - Return whether a numeric type is signed.
338 virtual bool isUnsigned() const { return 1; }
340 // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
341 // virtual function invocation.
343 virtual bool isInteger() const { return 1; }
346 struct OtherType : public Type {
347 OtherType(const std::string &N, PrimitiveID id) : Type(N, id) {}
350 static struct TypeType : public Type {
351 TypeType() : Type("type", TypeTyID) {}
352 } TheTypeTy; // Implement the type that is global.
355 //===----------------------------------------------------------------------===//
356 // Static 'Type' data
357 //===----------------------------------------------------------------------===//
359 static OtherType TheVoidTy ("void" , Type::VoidTyID);
360 static OtherType TheBoolTy ("bool" , Type::BoolTyID);
361 static SignedIntType TheSByteTy ("sbyte" , Type::SByteTyID);
362 static UnsignedIntType TheUByteTy ("ubyte" , Type::UByteTyID);
363 static SignedIntType TheShortTy ("short" , Type::ShortTyID);
364 static UnsignedIntType TheUShortTy("ushort", Type::UShortTyID);
365 static SignedIntType TheIntTy ("int" , Type::IntTyID);
366 static UnsignedIntType TheUIntTy ("uint" , Type::UIntTyID);
367 static SignedIntType TheLongTy ("long" , Type::LongTyID);
368 static UnsignedIntType TheULongTy ("ulong" , Type::ULongTyID);
369 static OtherType TheFloatTy ("float" , Type::FloatTyID);
370 static OtherType TheDoubleTy("double", Type::DoubleTyID);
371 static OtherType TheLabelTy ("label" , Type::LabelTyID);
373 Type *Type::VoidTy = &TheVoidTy;
374 Type *Type::BoolTy = &TheBoolTy;
375 Type *Type::SByteTy = &TheSByteTy;
376 Type *Type::UByteTy = &TheUByteTy;
377 Type *Type::ShortTy = &TheShortTy;
378 Type *Type::UShortTy = &TheUShortTy;
379 Type *Type::IntTy = &TheIntTy;
380 Type *Type::UIntTy = &TheUIntTy;
381 Type *Type::LongTy = &TheLongTy;
382 Type *Type::ULongTy = &TheULongTy;
383 Type *Type::FloatTy = &TheFloatTy;
384 Type *Type::DoubleTy = &TheDoubleTy;
385 Type *Type::TypeTy = &TheTypeTy;
386 Type *Type::LabelTy = &TheLabelTy;
389 //===----------------------------------------------------------------------===//
390 // Derived Type Constructors
391 //===----------------------------------------------------------------------===//
393 FunctionType::FunctionType(const Type *Result,
394 const std::vector<const Type*> &Params,
395 bool IsVarArgs) : DerivedType(FunctionTyID),
396 isVarArgs(IsVarArgs) {
397 bool isAbstract = Result->isAbstract();
398 ContainedTys.reserve(Params.size()+1);
399 ContainedTys.push_back(PATypeHandle(Result, this));
401 for (unsigned i = 0; i != Params.size(); ++i) {
402 ContainedTys.push_back(PATypeHandle(Params[i], this));
403 isAbstract |= Params[i]->isAbstract();
406 // Calculate whether or not this type is abstract
407 setAbstract(isAbstract);
410 StructType::StructType(const std::vector<const Type*> &Types)
411 : CompositeType(StructTyID) {
412 ContainedTys.reserve(Types.size());
413 bool isAbstract = false;
414 for (unsigned i = 0; i < Types.size(); ++i) {
415 assert(Types[i] != Type::VoidTy && "Void type for structure field!!");
416 ContainedTys.push_back(PATypeHandle(Types[i], this));
417 isAbstract |= Types[i]->isAbstract();
420 // Calculate whether or not this type is abstract
421 setAbstract(isAbstract);
424 ArrayType::ArrayType(const Type *ElType, unsigned NumEl)
425 : SequentialType(ArrayTyID, ElType) {
428 // Calculate whether or not this type is abstract
429 setAbstract(ElType->isAbstract());
432 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
433 // Calculate whether or not this type is abstract
434 setAbstract(E->isAbstract());
437 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
439 #ifdef DEBUG_MERGE_TYPES
440 std::cerr << "Derived new type: " << *this << "\n";
444 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
445 // another (more concrete) type, we must eliminate all references to other
446 // types, to avoid some circular reference problems.
447 void DerivedType::dropAllTypeUses() {
448 if (!ContainedTys.empty()) {
449 while (ContainedTys.size() > 1)
450 ContainedTys.pop_back();
452 // The type must stay abstract. To do this, we insert a pointer to a type
453 // that will never get resolved, thus will always be abstract.
454 static Type *AlwaysOpaqueTy = OpaqueType::get();
455 static PATypeHolder Holder(AlwaysOpaqueTy);
456 ContainedTys[0] = AlwaysOpaqueTy;
460 // isTypeAbstract - This is a recursive function that walks a type hierarchy
461 // calculating whether or not a type is abstract. Worst case it will have to do
462 // a lot of traversing if you have some whacko opaque types, but in most cases,
463 // it will do some simple stuff when it hits non-abstract types that aren't
466 bool Type::isTypeAbstract() {
467 if (!isAbstract()) // Base case for the recursion
468 return false; // Primitive = leaf type
470 if (isa<OpaqueType>(this)) // Base case for the recursion
471 return true; // This whole type is abstract!
473 // We have to guard against recursion. To do this, we temporarily mark this
474 // type as concrete, so that if we get back to here recursively we will think
475 // it's not abstract, and thus not scan it again.
478 // Scan all of the sub-types. If any of them are abstract, than so is this
480 for (Type::subtype_iterator I = subtype_begin(), E = subtype_end();
482 if (const_cast<Type*>(I->get())->isTypeAbstract()) {
483 setAbstract(true); // Restore the abstract bit.
484 return true; // This type is abstract if subtype is abstract!
487 // Restore the abstract bit.
490 // Nothing looks abstract here...
495 //===----------------------------------------------------------------------===//
496 // Type Structural Equality Testing
497 //===----------------------------------------------------------------------===//
499 // TypesEqual - Two types are considered structurally equal if they have the
500 // same "shape": Every level and element of the types have identical primitive
501 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
502 // be pointer equals to be equivalent though. This uses an optimistic algorithm
503 // that assumes that two graphs are the same until proven otherwise.
505 static bool TypesEqual(const Type *Ty, const Type *Ty2,
506 std::map<const Type *, const Type *> &EqTypes) {
507 if (Ty == Ty2) return true;
508 if (Ty->getPrimitiveID() != Ty2->getPrimitiveID()) return false;
509 if (isa<OpaqueType>(Ty))
510 return false; // Two unequal opaque types are never equal
512 std::map<const Type*, const Type*>::iterator It = EqTypes.lower_bound(Ty);
513 if (It != EqTypes.end() && It->first == Ty)
514 return It->second == Ty2; // Looping back on a type, check for equality
516 // Otherwise, add the mapping to the table to make sure we don't get
517 // recursion on the types...
518 EqTypes.insert(It, std::make_pair(Ty, Ty2));
520 // Two really annoying special cases that breaks an otherwise nice simple
521 // algorithm is the fact that arraytypes have sizes that differentiates types,
522 // and that function types can be varargs or not. Consider this now.
524 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
525 return TypesEqual(PTy->getElementType(),
526 cast<PointerType>(Ty2)->getElementType(), EqTypes);
527 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
528 const StructType *STy2 = cast<StructType>(Ty2);
529 if (STy->getNumElements() != STy2->getNumElements()) return false;
530 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
531 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
534 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
535 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
536 return ATy->getNumElements() == ATy2->getNumElements() &&
537 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
538 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
539 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
540 if (FTy->isVarArg() != FTy2->isVarArg() ||
541 FTy->getNumParams() != FTy2->getNumParams() ||
542 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
544 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i)
545 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
549 assert(0 && "Unknown derived type!");
554 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
555 std::map<const Type *, const Type *> EqTypes;
556 return TypesEqual(Ty, Ty2, EqTypes);
559 // TypeHasCycleThrough - Return true there is a path from CurTy to TargetTy in
560 // the type graph. We know that Ty is an abstract type, so if we ever reach a
561 // non-abstract type, we know that we don't need to search the subgraph.
562 static bool TypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
563 std::set<const Type*> &VisitedTypes) {
564 if (TargetTy == CurTy) return true;
565 if (!CurTy->isAbstract()) return false;
567 std::set<const Type*>::iterator VTI = VisitedTypes.lower_bound(CurTy);
568 if (VTI != VisitedTypes.end() && *VTI == CurTy)
570 VisitedTypes.insert(VTI, CurTy);
572 for (Type::subtype_iterator I = CurTy->subtype_begin(),
573 E = CurTy->subtype_end(); I != E; ++I)
574 if (TypeHasCycleThrough(TargetTy, *I, VisitedTypes))
580 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
582 static bool TypeHasCycleThroughItself(const Type *Ty) {
583 assert(Ty->isAbstract() && "This code assumes that Ty was abstract!");
584 std::set<const Type*> VisitedTypes;
585 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
587 if (TypeHasCycleThrough(Ty, *I, VisitedTypes))
593 //===----------------------------------------------------------------------===//
594 // Derived Type Factory Functions
595 //===----------------------------------------------------------------------===//
597 // TypeMap - Make sure that only one instance of a particular type may be
598 // created on any given run of the compiler... note that this involves updating
599 // our map if an abstract type gets refined somehow.
602 template<class ValType, class TypeClass>
604 std::map<ValType, PATypeHolder> Map;
606 /// TypesByHash - Keep track of each type by its structure hash value.
608 std::multimap<unsigned, PATypeHolder> TypesByHash;
610 typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
611 ~TypeMap() { print("ON EXIT"); }
613 inline TypeClass *get(const ValType &V) {
614 iterator I = Map.find(V);
615 return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
618 inline void add(const ValType &V, TypeClass *Ty) {
619 Map.insert(std::make_pair(V, Ty));
621 // If this type has a cycle, remember it.
622 TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
626 void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
627 std::multimap<unsigned, PATypeHolder>::iterator I =
628 TypesByHash.lower_bound(Hash);
629 while (I->second != Ty) {
631 assert(I != TypesByHash.end() && I->first == Hash);
633 TypesByHash.erase(I);
636 /// finishRefinement - This method is called after we have updated an existing
637 /// type with its new components. We must now either merge the type away with
638 /// some other type or reinstall it in the map with it's new configuration.
639 /// The specified iterator tells us what the type USED to look like.
640 void finishRefinement(TypeClass *Ty, const DerivedType *OldType,
641 const Type *NewType) {
642 assert((Ty->isAbstract() || !OldType->isAbstract()) &&
643 "Refining a non-abstract type!");
644 #ifdef DEBUG_MERGE_TYPES
645 std::cerr << "refineAbstractTy(" << (void*)OldType << "[" << *OldType
646 << "], " << (void*)NewType << " [" << *NewType << "])\n";
649 // Make a temporary type holder for the type so that it doesn't disappear on
650 // us when we erase the entry from the map.
651 PATypeHolder TyHolder = Ty;
653 // The old record is now out-of-date, because one of the children has been
654 // updated. Remove the obsolete entry from the map.
655 Map.erase(ValType::get(Ty));
657 // Remember the structural hash for the type before we start hacking on it,
658 // in case we need it later. Also, check to see if the type HAD a cycle
659 // through it, if so, we know it will when we hack on it.
660 unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
662 // Find the type element we are refining... and change it now!
663 for (unsigned i = 0, e = Ty->ContainedTys.size(); i != e; ++i)
664 if (Ty->ContainedTys[i] == OldType) {
665 Ty->ContainedTys[i].removeUserFromConcrete();
666 Ty->ContainedTys[i] = NewType;
669 unsigned TypeHash = ValType::hashTypeStructure(Ty);
671 // If there are no cycles going through this node, we can do a simple,
672 // efficient lookup in the map, instead of an inefficient nasty linear
674 bool TypeHasCycle = Ty->isAbstract() && TypeHasCycleThroughItself(Ty);
676 iterator I = Map.find(ValType::get(Ty));
677 if (I != Map.end()) {
678 // We already have this type in the table. Get rid of the newly refined
680 assert(Ty->isAbstract() && "Replacing a non-abstract type?");
681 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
683 // Refined to a different type altogether?
684 RemoveFromTypesByHash(TypeHash, Ty);
685 Ty->refineAbstractTypeTo(NewTy);
690 // Now we check to see if there is an existing entry in the table which is
691 // structurally identical to the newly refined type. If so, this type
692 // gets refined to the pre-existing type.
694 std::multimap<unsigned, PATypeHolder>::iterator I,E, Entry;
695 tie(I, E) = TypesByHash.equal_range(TypeHash);
697 for (; I != E; ++I) {
698 if (I->second != Ty) {
699 if (TypesEqual(Ty, I->second)) {
700 assert(Ty->isAbstract() && "Replacing a non-abstract type?");
701 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
704 // Find the location of Ty in the TypesByHash structure.
705 while (I->second != Ty) {
707 assert(I != E && "Structure doesn't contain type??");
712 TypesByHash.erase(Entry);
713 Ty->refineAbstractTypeTo(NewTy);
717 // Remember the position of
723 // If we succeeded, we need to insert the type into the cycletypes table.
724 // There are several cases here, depending on whether the original type
725 // had the same hash code and was itself cyclic.
726 if (TypeHash != OldTypeHash) {
727 RemoveFromTypesByHash(OldTypeHash, Ty);
728 TypesByHash.insert(std::make_pair(TypeHash, Ty));
731 // If there is no existing type of the same structure, we reinsert an
732 // updated record into the map.
733 Map.insert(std::make_pair(ValType::get(Ty), Ty));
735 // If the type is currently thought to be abstract, rescan all of our
736 // subtypes to see if the type has just become concrete!
737 if (Ty->isAbstract()) {
738 Ty->setAbstract(Ty->isTypeAbstract());
740 // If the type just became concrete, notify all users!
741 if (!Ty->isAbstract())
742 Ty->notifyUsesThatTypeBecameConcrete();
746 void print(const char *Arg) const {
747 #ifdef DEBUG_MERGE_TYPES
748 std::cerr << "TypeMap<>::" << Arg << " table contents:\n";
750 for (typename std::map<ValType, PATypeHolder>::const_iterator I
751 = Map.begin(), E = Map.end(); I != E; ++I)
752 std::cerr << " " << (++i) << ". " << (void*)I->second.get() << " "
753 << *I->second.get() << "\n";
757 void dump() const { print("dump output"); }
762 //===----------------------------------------------------------------------===//
763 // Function Type Factory and Value Class...
766 // FunctionValType - Define a class to hold the key that goes into the TypeMap
769 class FunctionValType {
771 std::vector<const Type*> ArgTypes;
774 FunctionValType(const Type *ret, const std::vector<const Type*> &args,
775 bool IVA) : RetTy(ret), isVarArg(IVA) {
776 for (unsigned i = 0; i < args.size(); ++i)
777 ArgTypes.push_back(args[i]);
780 static FunctionValType get(const FunctionType *FT);
782 static unsigned hashTypeStructure(const FunctionType *FT) {
783 return FT->getNumParams()*2+FT->isVarArg();
786 // Subclass should override this... to update self as usual
787 void doRefinement(const DerivedType *OldType, const Type *NewType) {
788 if (RetTy == OldType) RetTy = NewType;
789 for (unsigned i = 0, e = ArgTypes.size(); i != e; ++i)
790 if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
793 inline bool operator<(const FunctionValType &MTV) const {
794 if (RetTy < MTV.RetTy) return true;
795 if (RetTy > MTV.RetTy) return false;
797 if (ArgTypes < MTV.ArgTypes) return true;
798 return ArgTypes == MTV.ArgTypes && isVarArg < MTV.isVarArg;
803 // Define the actual map itself now...
804 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
806 FunctionValType FunctionValType::get(const FunctionType *FT) {
807 // Build up a FunctionValType
808 std::vector<const Type *> ParamTypes;
809 ParamTypes.reserve(FT->getNumParams());
810 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
811 ParamTypes.push_back(FT->getParamType(i));
812 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
816 // FunctionType::get - The factory function for the FunctionType class...
817 FunctionType *FunctionType::get(const Type *ReturnType,
818 const std::vector<const Type*> &Params,
820 FunctionValType VT(ReturnType, Params, isVarArg);
821 FunctionType *MT = FunctionTypes.get(VT);
824 FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
826 #ifdef DEBUG_MERGE_TYPES
827 std::cerr << "Derived new type: " << MT << "\n";
832 //===----------------------------------------------------------------------===//
833 // Array Type Factory...
840 ArrayValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
842 static ArrayValType get(const ArrayType *AT) {
843 return ArrayValType(AT->getElementType(), AT->getNumElements());
846 static unsigned hashTypeStructure(const ArrayType *AT) {
847 return AT->getNumElements();
850 // Subclass should override this... to update self as usual
851 void doRefinement(const DerivedType *OldType, const Type *NewType) {
852 assert(ValTy == OldType);
856 inline bool operator<(const ArrayValType &MTV) const {
857 if (Size < MTV.Size) return true;
858 return Size == MTV.Size && ValTy < MTV.ValTy;
862 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
865 ArrayType *ArrayType::get(const Type *ElementType, unsigned NumElements) {
866 assert(ElementType && "Can't get array of null types!");
868 ArrayValType AVT(ElementType, NumElements);
869 ArrayType *AT = ArrayTypes.get(AVT);
870 if (AT) return AT; // Found a match, return it!
872 // Value not found. Derive a new type!
873 ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
875 #ifdef DEBUG_MERGE_TYPES
876 std::cerr << "Derived new type: " << *AT << "\n";
881 //===----------------------------------------------------------------------===//
882 // Struct Type Factory...
886 // StructValType - Define a class to hold the key that goes into the TypeMap
888 class StructValType {
889 std::vector<const Type*> ElTypes;
891 StructValType(const std::vector<const Type*> &args) : ElTypes(args) {}
893 static StructValType get(const StructType *ST) {
894 std::vector<const Type *> ElTypes;
895 ElTypes.reserve(ST->getNumElements());
896 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
897 ElTypes.push_back(ST->getElementType(i));
899 return StructValType(ElTypes);
902 static unsigned hashTypeStructure(const StructType *ST) {
903 return ST->getNumElements();
906 // Subclass should override this... to update self as usual
907 void doRefinement(const DerivedType *OldType, const Type *NewType) {
908 for (unsigned i = 0; i < ElTypes.size(); ++i)
909 if (ElTypes[i] == OldType) ElTypes[i] = NewType;
912 inline bool operator<(const StructValType &STV) const {
913 return ElTypes < STV.ElTypes;
918 static TypeMap<StructValType, StructType> StructTypes;
920 StructType *StructType::get(const std::vector<const Type*> &ETypes) {
921 StructValType STV(ETypes);
922 StructType *ST = StructTypes.get(STV);
925 // Value not found. Derive a new type!
926 StructTypes.add(STV, ST = new StructType(ETypes));
928 #ifdef DEBUG_MERGE_TYPES
929 std::cerr << "Derived new type: " << *ST << "\n";
936 //===----------------------------------------------------------------------===//
937 // Pointer Type Factory...
940 // PointerValType - Define a class to hold the key that goes into the TypeMap
943 class PointerValType {
946 PointerValType(const Type *val) : ValTy(val) {}
948 static PointerValType get(const PointerType *PT) {
949 return PointerValType(PT->getElementType());
952 static unsigned hashTypeStructure(const PointerType *PT) {
956 // Subclass should override this... to update self as usual
957 void doRefinement(const DerivedType *OldType, const Type *NewType) {
958 assert(ValTy == OldType);
962 bool operator<(const PointerValType &MTV) const {
963 return ValTy < MTV.ValTy;
968 static TypeMap<PointerValType, PointerType> PointerTypes;
970 PointerType *PointerType::get(const Type *ValueType) {
971 assert(ValueType && "Can't get a pointer to <null> type!");
972 PointerValType PVT(ValueType);
974 PointerType *PT = PointerTypes.get(PVT);
977 // Value not found. Derive a new type!
978 PointerTypes.add(PVT, PT = new PointerType(ValueType));
980 #ifdef DEBUG_MERGE_TYPES
981 std::cerr << "Derived new type: " << *PT << "\n";
987 //===----------------------------------------------------------------------===//
988 // Derived Type Refinement Functions
989 //===----------------------------------------------------------------------===//
991 // removeAbstractTypeUser - Notify an abstract type that a user of the class
992 // no longer has a handle to the type. This function is called primarily by
993 // the PATypeHandle class. When there are no users of the abstract type, it
994 // is annihilated, because there is no way to get a reference to it ever again.
996 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
997 // Search from back to front because we will notify users from back to
998 // front. Also, it is likely that there will be a stack like behavior to
999 // users that register and unregister users.
1002 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1003 assert(i != 0 && "AbstractTypeUser not in user list!");
1005 --i; // Convert to be in range 0 <= i < size()
1006 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
1008 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1010 #ifdef DEBUG_MERGE_TYPES
1011 std::cerr << " remAbstractTypeUser[" << (void*)this << ", "
1012 << *this << "][" << i << "] User = " << U << "\n";
1015 if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1016 #ifdef DEBUG_MERGE_TYPES
1017 std::cerr << "DELETEing unused abstract type: <" << *this
1018 << ">[" << (void*)this << "]" << "\n";
1020 delete this; // No users of this abstract type!
1025 // refineAbstractTypeTo - This function is used to when it is discovered that
1026 // the 'this' abstract type is actually equivalent to the NewType specified.
1027 // This causes all users of 'this' to switch to reference the more concrete type
1028 // NewType and for 'this' to be deleted.
1030 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1031 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1032 assert(this != NewType && "Can't refine to myself!");
1033 assert(ForwardType == 0 && "This type has already been refined!");
1035 // The descriptions may be out of date. Conservatively clear them all!
1036 AbstractTypeDescriptions.clear();
1038 #ifdef DEBUG_MERGE_TYPES
1039 std::cerr << "REFINING abstract type [" << (void*)this << " "
1040 << *this << "] to [" << (void*)NewType << " "
1041 << *NewType << "]!\n";
1044 // Make sure to put the type to be refined to into a holder so that if IT gets
1045 // refined, that we will not continue using a dead reference...
1047 PATypeHolder NewTy(NewType);
1049 // Any PATypeHolders referring to this type will now automatically forward to
1050 // the type we are resolved to.
1051 ForwardType = NewType;
1052 if (NewType->isAbstract())
1053 cast<DerivedType>(NewType)->addRef();
1055 // Add a self use of the current type so that we don't delete ourself until
1056 // after the function exits.
1058 PATypeHolder CurrentTy(this);
1060 // To make the situation simpler, we ask the subclass to remove this type from
1061 // the type map, and to replace any type uses with uses of non-abstract types.
1062 // This dramatically limits the amount of recursive type trouble we can find
1066 // Iterate over all of the uses of this type, invoking callback. Each user
1067 // should remove itself from our use list automatically. We have to check to
1068 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1069 // will not cause users to drop off of the use list. If we resolve to ourself
1072 while (!AbstractTypeUsers.empty() && NewTy != this) {
1073 AbstractTypeUser *User = AbstractTypeUsers.back();
1075 unsigned OldSize = AbstractTypeUsers.size();
1076 #ifdef DEBUG_MERGE_TYPES
1077 std::cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
1078 << "] of abstract type [" << (void*)this << " "
1079 << *this << "] to [" << (void*)NewTy.get() << " "
1080 << *NewTy << "]!\n";
1082 User->refineAbstractType(this, NewTy);
1084 assert(AbstractTypeUsers.size() != OldSize &&
1085 "AbsTyUser did not remove self from user list!");
1088 // If we were successful removing all users from the type, 'this' will be
1089 // deleted when the last PATypeHolder is destroyed or updated from this type.
1090 // This may occur on exit of this function, as the CurrentTy object is
1094 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1095 // the current type has transitioned from being abstract to being concrete.
1097 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1098 #ifdef DEBUG_MERGE_TYPES
1099 std::cerr << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1102 unsigned OldSize = AbstractTypeUsers.size();
1103 while (!AbstractTypeUsers.empty()) {
1104 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1105 ATU->typeBecameConcrete(this);
1107 assert(AbstractTypeUsers.size() < OldSize-- &&
1108 "AbstractTypeUser did not remove itself from the use list!");
1115 // refineAbstractType - Called when a contained type is found to be more
1116 // concrete - this could potentially change us from an abstract type to a
1119 void FunctionType::refineAbstractType(const DerivedType *OldType,
1120 const Type *NewType) {
1121 FunctionTypes.finishRefinement(this, OldType, NewType);
1124 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1125 refineAbstractType(AbsTy, AbsTy);
1129 // refineAbstractType - Called when a contained type is found to be more
1130 // concrete - this could potentially change us from an abstract type to a
1133 void ArrayType::refineAbstractType(const DerivedType *OldType,
1134 const Type *NewType) {
1135 ArrayTypes.finishRefinement(this, OldType, NewType);
1138 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1139 refineAbstractType(AbsTy, AbsTy);
1143 // refineAbstractType - Called when a contained type is found to be more
1144 // concrete - this could potentially change us from an abstract type to a
1147 void StructType::refineAbstractType(const DerivedType *OldType,
1148 const Type *NewType) {
1149 StructTypes.finishRefinement(this, OldType, NewType);
1152 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1153 refineAbstractType(AbsTy, AbsTy);
1156 // refineAbstractType - Called when a contained type is found to be more
1157 // concrete - this could potentially change us from an abstract type to a
1160 void PointerType::refineAbstractType(const DerivedType *OldType,
1161 const Type *NewType) {
1162 PointerTypes.finishRefinement(this, OldType, NewType);
1165 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1166 refineAbstractType(AbsTy, AbsTy);