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 (V->getType() == Type::UIntTy)
299 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(V))
300 return CU->getValue() < ContainedTys.size();
304 // getTypeAtIndex - Given an index value into the type, return the type of the
305 // element. For a structure type, this must be a constant value...
307 const Type *StructType::getTypeAtIndex(const Value *V) const {
308 assert(indexValid(V) && "Invalid structure index!");
309 unsigned Idx = cast<ConstantUInt>(V)->getValue();
310 return ContainedTys[Idx];
314 //===----------------------------------------------------------------------===//
316 //===----------------------------------------------------------------------===//
318 // These classes are used to implement specialized behavior for each different
321 struct SignedIntType : public Type {
322 SignedIntType(const std::string &Name, PrimitiveID id) : Type(Name, id) {}
324 // isSigned - Return whether a numeric type is signed.
325 virtual bool isSigned() const { return 1; }
327 // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
328 // virtual function invocation.
330 virtual bool isInteger() const { return 1; }
333 struct UnsignedIntType : public Type {
334 UnsignedIntType(const std::string &N, PrimitiveID id) : Type(N, id) {}
336 // isUnsigned - Return whether a numeric type is signed.
337 virtual bool isUnsigned() const { return 1; }
339 // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
340 // virtual function invocation.
342 virtual bool isInteger() const { return 1; }
345 struct OtherType : public Type {
346 OtherType(const std::string &N, PrimitiveID id) : Type(N, id) {}
349 static struct TypeType : public Type {
350 TypeType() : Type("type", TypeTyID) {}
351 } TheTypeTy; // Implement the type that is global.
354 //===----------------------------------------------------------------------===//
355 // Static 'Type' data
356 //===----------------------------------------------------------------------===//
358 static OtherType TheVoidTy ("void" , Type::VoidTyID);
359 static OtherType TheBoolTy ("bool" , Type::BoolTyID);
360 static SignedIntType TheSByteTy ("sbyte" , Type::SByteTyID);
361 static UnsignedIntType TheUByteTy ("ubyte" , Type::UByteTyID);
362 static SignedIntType TheShortTy ("short" , Type::ShortTyID);
363 static UnsignedIntType TheUShortTy("ushort", Type::UShortTyID);
364 static SignedIntType TheIntTy ("int" , Type::IntTyID);
365 static UnsignedIntType TheUIntTy ("uint" , Type::UIntTyID);
366 static SignedIntType TheLongTy ("long" , Type::LongTyID);
367 static UnsignedIntType TheULongTy ("ulong" , Type::ULongTyID);
368 static OtherType TheFloatTy ("float" , Type::FloatTyID);
369 static OtherType TheDoubleTy("double", Type::DoubleTyID);
370 static OtherType TheLabelTy ("label" , Type::LabelTyID);
372 Type *Type::VoidTy = &TheVoidTy;
373 Type *Type::BoolTy = &TheBoolTy;
374 Type *Type::SByteTy = &TheSByteTy;
375 Type *Type::UByteTy = &TheUByteTy;
376 Type *Type::ShortTy = &TheShortTy;
377 Type *Type::UShortTy = &TheUShortTy;
378 Type *Type::IntTy = &TheIntTy;
379 Type *Type::UIntTy = &TheUIntTy;
380 Type *Type::LongTy = &TheLongTy;
381 Type *Type::ULongTy = &TheULongTy;
382 Type *Type::FloatTy = &TheFloatTy;
383 Type *Type::DoubleTy = &TheDoubleTy;
384 Type *Type::TypeTy = &TheTypeTy;
385 Type *Type::LabelTy = &TheLabelTy;
388 //===----------------------------------------------------------------------===//
389 // Derived Type Constructors
390 //===----------------------------------------------------------------------===//
392 FunctionType::FunctionType(const Type *Result,
393 const std::vector<const Type*> &Params,
394 bool IsVarArgs) : DerivedType(FunctionTyID),
395 isVarArgs(IsVarArgs) {
396 bool isAbstract = Result->isAbstract();
397 ContainedTys.reserve(Params.size()+1);
398 ContainedTys.push_back(PATypeHandle(Result, this));
400 for (unsigned i = 0; i != Params.size(); ++i) {
401 ContainedTys.push_back(PATypeHandle(Params[i], this));
402 isAbstract |= Params[i]->isAbstract();
405 // Calculate whether or not this type is abstract
406 setAbstract(isAbstract);
409 StructType::StructType(const std::vector<const Type*> &Types)
410 : CompositeType(StructTyID) {
411 ContainedTys.reserve(Types.size());
412 bool isAbstract = false;
413 for (unsigned i = 0; i < Types.size(); ++i) {
414 assert(Types[i] != Type::VoidTy && "Void type for structure field!!");
415 ContainedTys.push_back(PATypeHandle(Types[i], this));
416 isAbstract |= Types[i]->isAbstract();
419 // Calculate whether or not this type is abstract
420 setAbstract(isAbstract);
423 ArrayType::ArrayType(const Type *ElType, unsigned NumEl)
424 : SequentialType(ArrayTyID, ElType) {
427 // Calculate whether or not this type is abstract
428 setAbstract(ElType->isAbstract());
431 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
432 // Calculate whether or not this type is abstract
433 setAbstract(E->isAbstract());
436 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
438 #ifdef DEBUG_MERGE_TYPES
439 std::cerr << "Derived new type: " << *this << "\n";
443 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
444 // another (more concrete) type, we must eliminate all references to other
445 // types, to avoid some circular reference problems.
446 void DerivedType::dropAllTypeUses() {
447 if (!ContainedTys.empty()) {
448 while (ContainedTys.size() > 1)
449 ContainedTys.pop_back();
451 // The type must stay abstract. To do this, we insert a pointer to a type
452 // that will never get resolved, thus will always be abstract.
453 static Type *AlwaysOpaqueTy = OpaqueType::get();
454 static PATypeHolder Holder(AlwaysOpaqueTy);
455 ContainedTys[0] = AlwaysOpaqueTy;
459 // isTypeAbstract - This is a recursive function that walks a type hierarchy
460 // calculating whether or not a type is abstract. Worst case it will have to do
461 // a lot of traversing if you have some whacko opaque types, but in most cases,
462 // it will do some simple stuff when it hits non-abstract types that aren't
465 bool Type::isTypeAbstract() {
466 if (!isAbstract()) // Base case for the recursion
467 return false; // Primitive = leaf type
469 if (isa<OpaqueType>(this)) // Base case for the recursion
470 return true; // This whole type is abstract!
472 // We have to guard against recursion. To do this, we temporarily mark this
473 // type as concrete, so that if we get back to here recursively we will think
474 // it's not abstract, and thus not scan it again.
477 // Scan all of the sub-types. If any of them are abstract, than so is this
479 for (Type::subtype_iterator I = subtype_begin(), E = subtype_end();
481 if (const_cast<Type*>(I->get())->isTypeAbstract()) {
482 setAbstract(true); // Restore the abstract bit.
483 return true; // This type is abstract if subtype is abstract!
486 // Restore the abstract bit.
489 // Nothing looks abstract here...
494 //===----------------------------------------------------------------------===//
495 // Type Structural Equality Testing
496 //===----------------------------------------------------------------------===//
498 // TypesEqual - Two types are considered structurally equal if they have the
499 // same "shape": Every level and element of the types have identical primitive
500 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
501 // be pointer equals to be equivalent though. This uses an optimistic algorithm
502 // that assumes that two graphs are the same until proven otherwise.
504 static bool TypesEqual(const Type *Ty, const Type *Ty2,
505 std::map<const Type *, const Type *> &EqTypes) {
506 if (Ty == Ty2) return true;
507 if (Ty->getPrimitiveID() != Ty2->getPrimitiveID()) return false;
508 if (isa<OpaqueType>(Ty))
509 return false; // Two unequal opaque types are never equal
511 std::map<const Type*, const Type*>::iterator It = EqTypes.lower_bound(Ty);
512 if (It != EqTypes.end() && It->first == Ty)
513 return It->second == Ty2; // Looping back on a type, check for equality
515 // Otherwise, add the mapping to the table to make sure we don't get
516 // recursion on the types...
517 EqTypes.insert(It, std::make_pair(Ty, Ty2));
519 // Two really annoying special cases that breaks an otherwise nice simple
520 // algorithm is the fact that arraytypes have sizes that differentiates types,
521 // and that function types can be varargs or not. Consider this now.
523 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
524 return TypesEqual(PTy->getElementType(),
525 cast<PointerType>(Ty2)->getElementType(), EqTypes);
526 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
527 const StructType *STy2 = cast<StructType>(Ty2);
528 if (STy->getNumElements() != STy2->getNumElements()) return false;
529 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
530 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
533 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
534 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
535 return ATy->getNumElements() == ATy2->getNumElements() &&
536 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
537 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
538 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
539 if (FTy->isVarArg() != FTy2->isVarArg() ||
540 FTy->getNumParams() != FTy2->getNumParams() ||
541 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
543 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i)
544 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
548 assert(0 && "Unknown derived type!");
553 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
554 std::map<const Type *, const Type *> EqTypes;
555 return TypesEqual(Ty, Ty2, EqTypes);
558 // TypeHasCycleThrough - Return true there is a path from CurTy to TargetTy in
559 // the type graph. We know that Ty is an abstract type, so if we ever reach a
560 // non-abstract type, we know that we don't need to search the subgraph.
561 static bool TypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
562 std::set<const Type*> &VisitedTypes) {
563 if (TargetTy == CurTy) return true;
564 if (!CurTy->isAbstract()) return false;
566 std::set<const Type*>::iterator VTI = VisitedTypes.lower_bound(CurTy);
567 if (VTI != VisitedTypes.end() && *VTI == CurTy)
569 VisitedTypes.insert(VTI, CurTy);
571 for (Type::subtype_iterator I = CurTy->subtype_begin(),
572 E = CurTy->subtype_end(); I != E; ++I)
573 if (TypeHasCycleThrough(TargetTy, *I, VisitedTypes))
579 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
581 static bool TypeHasCycleThroughItself(const Type *Ty) {
582 assert(Ty->isAbstract() && "This code assumes that Ty was abstract!");
583 std::set<const Type*> VisitedTypes;
584 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
586 if (TypeHasCycleThrough(Ty, *I, VisitedTypes))
592 //===----------------------------------------------------------------------===//
593 // Derived Type Factory Functions
594 //===----------------------------------------------------------------------===//
596 // TypeMap - Make sure that only one instance of a particular type may be
597 // created on any given run of the compiler... note that this involves updating
598 // our map if an abstract type gets refined somehow.
601 template<class ValType, class TypeClass>
603 std::map<ValType, PATypeHolder> Map;
605 /// TypesByHash - Keep track of each type by its structure hash value.
607 std::multimap<unsigned, PATypeHolder> TypesByHash;
609 typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
610 ~TypeMap() { print("ON EXIT"); }
612 inline TypeClass *get(const ValType &V) {
613 iterator I = Map.find(V);
614 return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
617 inline void add(const ValType &V, TypeClass *Ty) {
618 Map.insert(std::make_pair(V, Ty));
620 // If this type has a cycle, remember it.
621 TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
625 void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
626 std::multimap<unsigned, PATypeHolder>::iterator I =
627 TypesByHash.lower_bound(Hash);
628 while (I->second != Ty) {
630 assert(I != TypesByHash.end() && I->first == Hash);
632 TypesByHash.erase(I);
635 /// finishRefinement - This method is called after we have updated an existing
636 /// type with its new components. We must now either merge the type away with
637 /// some other type or reinstall it in the map with it's new configuration.
638 /// The specified iterator tells us what the type USED to look like.
639 void finishRefinement(TypeClass *Ty, const DerivedType *OldType,
640 const Type *NewType) {
641 assert((Ty->isAbstract() || !OldType->isAbstract()) &&
642 "Refining a non-abstract type!");
643 #ifdef DEBUG_MERGE_TYPES
644 std::cerr << "refineAbstractTy(" << (void*)OldType << "[" << *OldType
645 << "], " << (void*)NewType << " [" << *NewType << "])\n";
648 // Make a temporary type holder for the type so that it doesn't disappear on
649 // us when we erase the entry from the map.
650 PATypeHolder TyHolder = Ty;
652 // The old record is now out-of-date, because one of the children has been
653 // updated. Remove the obsolete entry from the map.
654 Map.erase(ValType::get(Ty));
656 // Remember the structural hash for the type before we start hacking on it,
657 // in case we need it later. Also, check to see if the type HAD a cycle
658 // through it, if so, we know it will when we hack on it.
659 unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
661 // Find the type element we are refining... and change it now!
662 for (unsigned i = 0, e = Ty->ContainedTys.size(); i != e; ++i)
663 if (Ty->ContainedTys[i] == OldType) {
664 Ty->ContainedTys[i].removeUserFromConcrete();
665 Ty->ContainedTys[i] = NewType;
668 unsigned TypeHash = ValType::hashTypeStructure(Ty);
670 // If there are no cycles going through this node, we can do a simple,
671 // efficient lookup in the map, instead of an inefficient nasty linear
673 bool TypeHasCycle = Ty->isAbstract() && TypeHasCycleThroughItself(Ty);
675 iterator I = Map.find(ValType::get(Ty));
676 if (I != Map.end()) {
677 // We already have this type in the table. Get rid of the newly refined
679 assert(Ty->isAbstract() && "Replacing a non-abstract type?");
680 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
682 // Refined to a different type altogether?
683 RemoveFromTypesByHash(TypeHash, Ty);
684 Ty->refineAbstractTypeTo(NewTy);
689 // Now we check to see if there is an existing entry in the table which is
690 // structurally identical to the newly refined type. If so, this type
691 // gets refined to the pre-existing type.
693 std::multimap<unsigned, PATypeHolder>::iterator I,E, Entry;
694 tie(I, E) = TypesByHash.equal_range(TypeHash);
696 for (; I != E; ++I) {
697 if (I->second != Ty) {
698 if (TypesEqual(Ty, I->second)) {
699 assert(Ty->isAbstract() && "Replacing a non-abstract type?");
700 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
703 // Find the location of Ty in the TypesByHash structure.
704 while (I->second != Ty) {
706 assert(I != E && "Structure doesn't contain type??");
711 TypesByHash.erase(Entry);
712 Ty->refineAbstractTypeTo(NewTy);
716 // Remember the position of
722 // If we succeeded, we need to insert the type into the cycletypes table.
723 // There are several cases here, depending on whether the original type
724 // had the same hash code and was itself cyclic.
725 if (TypeHash != OldTypeHash) {
726 RemoveFromTypesByHash(OldTypeHash, Ty);
727 TypesByHash.insert(std::make_pair(TypeHash, Ty));
730 // If there is no existing type of the same structure, we reinsert an
731 // updated record into the map.
732 Map.insert(std::make_pair(ValType::get(Ty), Ty));
734 // If the type is currently thought to be abstract, rescan all of our
735 // subtypes to see if the type has just become concrete!
736 if (Ty->isAbstract()) {
737 Ty->setAbstract(Ty->isTypeAbstract());
739 // If the type just became concrete, notify all users!
740 if (!Ty->isAbstract())
741 Ty->notifyUsesThatTypeBecameConcrete();
745 void print(const char *Arg) const {
746 #ifdef DEBUG_MERGE_TYPES
747 std::cerr << "TypeMap<>::" << Arg << " table contents:\n";
749 for (typename std::map<ValType, PATypeHolder>::const_iterator I
750 = Map.begin(), E = Map.end(); I != E; ++I)
751 std::cerr << " " << (++i) << ". " << (void*)I->second.get() << " "
752 << *I->second.get() << "\n";
756 void dump() const { print("dump output"); }
761 //===----------------------------------------------------------------------===//
762 // Function Type Factory and Value Class...
765 // FunctionValType - Define a class to hold the key that goes into the TypeMap
768 class FunctionValType {
770 std::vector<const Type*> ArgTypes;
773 FunctionValType(const Type *ret, const std::vector<const Type*> &args,
774 bool IVA) : RetTy(ret), isVarArg(IVA) {
775 for (unsigned i = 0; i < args.size(); ++i)
776 ArgTypes.push_back(args[i]);
779 static FunctionValType get(const FunctionType *FT);
781 static unsigned hashTypeStructure(const FunctionType *FT) {
782 return FT->getNumParams()*2+FT->isVarArg();
785 // Subclass should override this... to update self as usual
786 void doRefinement(const DerivedType *OldType, const Type *NewType) {
787 if (RetTy == OldType) RetTy = NewType;
788 for (unsigned i = 0, e = ArgTypes.size(); i != e; ++i)
789 if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
792 inline bool operator<(const FunctionValType &MTV) const {
793 if (RetTy < MTV.RetTy) return true;
794 if (RetTy > MTV.RetTy) return false;
796 if (ArgTypes < MTV.ArgTypes) return true;
797 return ArgTypes == MTV.ArgTypes && isVarArg < MTV.isVarArg;
802 // Define the actual map itself now...
803 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
805 FunctionValType FunctionValType::get(const FunctionType *FT) {
806 // Build up a FunctionValType
807 std::vector<const Type *> ParamTypes;
808 ParamTypes.reserve(FT->getNumParams());
809 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
810 ParamTypes.push_back(FT->getParamType(i));
811 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
815 // FunctionType::get - The factory function for the FunctionType class...
816 FunctionType *FunctionType::get(const Type *ReturnType,
817 const std::vector<const Type*> &Params,
819 FunctionValType VT(ReturnType, Params, isVarArg);
820 FunctionType *MT = FunctionTypes.get(VT);
823 FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
825 #ifdef DEBUG_MERGE_TYPES
826 std::cerr << "Derived new type: " << MT << "\n";
831 //===----------------------------------------------------------------------===//
832 // Array Type Factory...
839 ArrayValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
841 static ArrayValType get(const ArrayType *AT) {
842 return ArrayValType(AT->getElementType(), AT->getNumElements());
845 static unsigned hashTypeStructure(const ArrayType *AT) {
846 return AT->getNumElements();
849 // Subclass should override this... to update self as usual
850 void doRefinement(const DerivedType *OldType, const Type *NewType) {
851 assert(ValTy == OldType);
855 inline bool operator<(const ArrayValType &MTV) const {
856 if (Size < MTV.Size) return true;
857 return Size == MTV.Size && ValTy < MTV.ValTy;
861 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
864 ArrayType *ArrayType::get(const Type *ElementType, unsigned NumElements) {
865 assert(ElementType && "Can't get array of null types!");
867 ArrayValType AVT(ElementType, NumElements);
868 ArrayType *AT = ArrayTypes.get(AVT);
869 if (AT) return AT; // Found a match, return it!
871 // Value not found. Derive a new type!
872 ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
874 #ifdef DEBUG_MERGE_TYPES
875 std::cerr << "Derived new type: " << *AT << "\n";
880 //===----------------------------------------------------------------------===//
881 // Struct Type Factory...
885 // StructValType - Define a class to hold the key that goes into the TypeMap
887 class StructValType {
888 std::vector<const Type*> ElTypes;
890 StructValType(const std::vector<const Type*> &args) : ElTypes(args) {}
892 static StructValType get(const StructType *ST) {
893 std::vector<const Type *> ElTypes;
894 ElTypes.reserve(ST->getNumElements());
895 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
896 ElTypes.push_back(ST->getElementType(i));
898 return StructValType(ElTypes);
901 static unsigned hashTypeStructure(const StructType *ST) {
902 return ST->getNumElements();
905 // Subclass should override this... to update self as usual
906 void doRefinement(const DerivedType *OldType, const Type *NewType) {
907 for (unsigned i = 0; i < ElTypes.size(); ++i)
908 if (ElTypes[i] == OldType) ElTypes[i] = NewType;
911 inline bool operator<(const StructValType &STV) const {
912 return ElTypes < STV.ElTypes;
917 static TypeMap<StructValType, StructType> StructTypes;
919 StructType *StructType::get(const std::vector<const Type*> &ETypes) {
920 StructValType STV(ETypes);
921 StructType *ST = StructTypes.get(STV);
924 // Value not found. Derive a new type!
925 StructTypes.add(STV, ST = new StructType(ETypes));
927 #ifdef DEBUG_MERGE_TYPES
928 std::cerr << "Derived new type: " << *ST << "\n";
935 //===----------------------------------------------------------------------===//
936 // Pointer Type Factory...
939 // PointerValType - Define a class to hold the key that goes into the TypeMap
942 class PointerValType {
945 PointerValType(const Type *val) : ValTy(val) {}
947 static PointerValType get(const PointerType *PT) {
948 return PointerValType(PT->getElementType());
951 static unsigned hashTypeStructure(const PointerType *PT) {
955 // Subclass should override this... to update self as usual
956 void doRefinement(const DerivedType *OldType, const Type *NewType) {
957 assert(ValTy == OldType);
961 bool operator<(const PointerValType &MTV) const {
962 return ValTy < MTV.ValTy;
967 static TypeMap<PointerValType, PointerType> PointerTypes;
969 PointerType *PointerType::get(const Type *ValueType) {
970 assert(ValueType && "Can't get a pointer to <null> type!");
971 PointerValType PVT(ValueType);
973 PointerType *PT = PointerTypes.get(PVT);
976 // Value not found. Derive a new type!
977 PointerTypes.add(PVT, PT = new PointerType(ValueType));
979 #ifdef DEBUG_MERGE_TYPES
980 std::cerr << "Derived new type: " << *PT << "\n";
986 //===----------------------------------------------------------------------===//
987 // Derived Type Refinement Functions
988 //===----------------------------------------------------------------------===//
990 // removeAbstractTypeUser - Notify an abstract type that a user of the class
991 // no longer has a handle to the type. This function is called primarily by
992 // the PATypeHandle class. When there are no users of the abstract type, it
993 // is annihilated, because there is no way to get a reference to it ever again.
995 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
996 // Search from back to front because we will notify users from back to
997 // front. Also, it is likely that there will be a stack like behavior to
998 // users that register and unregister users.
1001 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1002 assert(i != 0 && "AbstractTypeUser not in user list!");
1004 --i; // Convert to be in range 0 <= i < size()
1005 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
1007 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1009 #ifdef DEBUG_MERGE_TYPES
1010 std::cerr << " remAbstractTypeUser[" << (void*)this << ", "
1011 << *this << "][" << i << "] User = " << U << "\n";
1014 if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1015 #ifdef DEBUG_MERGE_TYPES
1016 std::cerr << "DELETEing unused abstract type: <" << *this
1017 << ">[" << (void*)this << "]" << "\n";
1019 delete this; // No users of this abstract type!
1024 // refineAbstractTypeTo - This function is used to when it is discovered that
1025 // the 'this' abstract type is actually equivalent to the NewType specified.
1026 // This causes all users of 'this' to switch to reference the more concrete type
1027 // NewType and for 'this' to be deleted.
1029 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1030 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1031 assert(this != NewType && "Can't refine to myself!");
1032 assert(ForwardType == 0 && "This type has already been refined!");
1034 // The descriptions may be out of date. Conservatively clear them all!
1035 AbstractTypeDescriptions.clear();
1037 #ifdef DEBUG_MERGE_TYPES
1038 std::cerr << "REFINING abstract type [" << (void*)this << " "
1039 << *this << "] to [" << (void*)NewType << " "
1040 << *NewType << "]!\n";
1043 // Make sure to put the type to be refined to into a holder so that if IT gets
1044 // refined, that we will not continue using a dead reference...
1046 PATypeHolder NewTy(NewType);
1048 // Any PATypeHolders referring to this type will now automatically forward to
1049 // the type we are resolved to.
1050 ForwardType = NewType;
1051 if (NewType->isAbstract())
1052 cast<DerivedType>(NewType)->addRef();
1054 // Add a self use of the current type so that we don't delete ourself until
1055 // after the function exits.
1057 PATypeHolder CurrentTy(this);
1059 // To make the situation simpler, we ask the subclass to remove this type from
1060 // the type map, and to replace any type uses with uses of non-abstract types.
1061 // This dramatically limits the amount of recursive type trouble we can find
1065 // Iterate over all of the uses of this type, invoking callback. Each user
1066 // should remove itself from our use list automatically. We have to check to
1067 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1068 // will not cause users to drop off of the use list. If we resolve to ourself
1071 while (!AbstractTypeUsers.empty() && NewTy != this) {
1072 AbstractTypeUser *User = AbstractTypeUsers.back();
1074 unsigned OldSize = AbstractTypeUsers.size();
1075 #ifdef DEBUG_MERGE_TYPES
1076 std::cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
1077 << "] of abstract type [" << (void*)this << " "
1078 << *this << "] to [" << (void*)NewTy.get() << " "
1079 << *NewTy << "]!\n";
1081 User->refineAbstractType(this, NewTy);
1083 assert(AbstractTypeUsers.size() != OldSize &&
1084 "AbsTyUser did not remove self from user list!");
1087 // If we were successful removing all users from the type, 'this' will be
1088 // deleted when the last PATypeHolder is destroyed or updated from this type.
1089 // This may occur on exit of this function, as the CurrentTy object is
1093 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1094 // the current type has transitioned from being abstract to being concrete.
1096 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1097 #ifdef DEBUG_MERGE_TYPES
1098 std::cerr << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1101 unsigned OldSize = AbstractTypeUsers.size();
1102 while (!AbstractTypeUsers.empty()) {
1103 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1104 ATU->typeBecameConcrete(this);
1106 assert(AbstractTypeUsers.size() < OldSize-- &&
1107 "AbstractTypeUser did not remove itself from the use list!");
1114 // refineAbstractType - Called when a contained type is found to be more
1115 // concrete - this could potentially change us from an abstract type to a
1118 void FunctionType::refineAbstractType(const DerivedType *OldType,
1119 const Type *NewType) {
1120 FunctionTypes.finishRefinement(this, OldType, NewType);
1123 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1124 refineAbstractType(AbsTy, AbsTy);
1128 // refineAbstractType - Called when a contained type is found to be more
1129 // concrete - this could potentially change us from an abstract type to a
1132 void ArrayType::refineAbstractType(const DerivedType *OldType,
1133 const Type *NewType) {
1134 ArrayTypes.finishRefinement(this, OldType, NewType);
1137 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1138 refineAbstractType(AbsTy, AbsTy);
1142 // refineAbstractType - Called when a contained type is found to be more
1143 // concrete - this could potentially change us from an abstract type to a
1146 void StructType::refineAbstractType(const DerivedType *OldType,
1147 const Type *NewType) {
1148 StructTypes.finishRefinement(this, OldType, NewType);
1151 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1152 refineAbstractType(AbsTy, AbsTy);
1155 // refineAbstractType - Called when a contained type is found to be more
1156 // concrete - this could potentially change us from an abstract type to a
1159 void PointerType::refineAbstractType(const DerivedType *OldType,
1160 const Type *NewType) {
1161 PointerTypes.finishRefinement(this, OldType, NewType);
1164 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1165 refineAbstractType(AbsTy, AbsTy);