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!");
57 if (!Name.empty()) ST->insert(Name, this);
61 const Type *Type::getUniqueIDType(unsigned UID) {
62 assert(UID < UIDMappings.size() &&
63 "Type::getPrimitiveType: UID out of range!");
64 return UIDMappings[UID];
67 const Type *Type::getPrimitiveType(PrimitiveID IDNumber) {
69 case VoidTyID : return VoidTy;
70 case BoolTyID : return BoolTy;
71 case UByteTyID : return UByteTy;
72 case SByteTyID : return SByteTy;
73 case UShortTyID: return UShortTy;
74 case ShortTyID : return ShortTy;
75 case UIntTyID : return UIntTy;
76 case IntTyID : return IntTy;
77 case ULongTyID : return ULongTy;
78 case LongTyID : return LongTy;
79 case FloatTyID : return FloatTy;
80 case DoubleTyID: return DoubleTy;
81 case TypeTyID : return TypeTy;
82 case LabelTyID : return LabelTy;
88 // isLosslesslyConvertibleTo - Return true if this type can be converted to
89 // 'Ty' without any reinterpretation of bits. For example, uint to int.
91 bool Type::isLosslesslyConvertibleTo(const Type *Ty) const {
92 if (this == Ty) return true;
93 if ((!isPrimitiveType() && !isa<PointerType>(this)) ||
94 (!isa<PointerType>(Ty) && !Ty->isPrimitiveType())) return false;
96 if (getPrimitiveID() == Ty->getPrimitiveID())
97 return true; // Handles identity cast, and cast of differing pointer types
99 // Now we know that they are two differing primitive or pointer types
100 switch (getPrimitiveID()) {
101 case Type::UByteTyID: return Ty == Type::SByteTy;
102 case Type::SByteTyID: return Ty == Type::UByteTy;
103 case Type::UShortTyID: return Ty == Type::ShortTy;
104 case Type::ShortTyID: return Ty == Type::UShortTy;
105 case Type::UIntTyID: return Ty == Type::IntTy;
106 case Type::IntTyID: return Ty == Type::UIntTy;
107 case Type::ULongTyID: return Ty == Type::LongTy;
108 case Type::LongTyID: return Ty == Type::ULongTy;
109 case Type::PointerTyID: return isa<PointerType>(Ty);
111 return false; // Other types have no identity values
115 /// getUnsignedVersion - If this is an integer type, return the unsigned
116 /// variant of this type. For example int -> uint.
117 const Type *Type::getUnsignedVersion() const {
118 switch (getPrimitiveID()) {
120 assert(isInteger()&&"Type::getUnsignedVersion is only valid for integers!");
121 case Type::UByteTyID:
122 case Type::SByteTyID: return Type::UByteTy;
123 case Type::UShortTyID:
124 case Type::ShortTyID: return Type::UShortTy;
126 case Type::IntTyID: return Type::UIntTy;
127 case Type::ULongTyID:
128 case Type::LongTyID: return Type::ULongTy;
132 /// getSignedVersion - If this is an integer type, return the signed variant
133 /// of this type. For example uint -> int.
134 const Type *Type::getSignedVersion() const {
135 switch (getPrimitiveID()) {
137 assert(isInteger() && "Type::getSignedVersion is only valid for integers!");
138 case Type::UByteTyID:
139 case Type::SByteTyID: return Type::SByteTy;
140 case Type::UShortTyID:
141 case Type::ShortTyID: return Type::ShortTy;
143 case Type::IntTyID: return Type::IntTy;
144 case Type::ULongTyID:
145 case Type::LongTyID: return Type::LongTy;
150 // getPrimitiveSize - Return the basic size of this type if it is a primitive
151 // type. These are fixed by LLVM and are not target dependent. This will
152 // return zero if the type does not have a size or is not a primitive type.
154 unsigned Type::getPrimitiveSize() const {
155 switch (getPrimitiveID()) {
156 #define HANDLE_PRIM_TYPE(TY,SIZE) case TY##TyID: return SIZE;
157 #include "llvm/Type.def"
163 /// getForwardedTypeInternal - This method is used to implement the union-find
164 /// algorithm for when a type is being forwarded to another type.
165 const Type *Type::getForwardedTypeInternal() const {
166 assert(ForwardType && "This type is not being forwarded to another type!");
168 // Check to see if the forwarded type has been forwarded on. If so, collapse
169 // the forwarding links.
170 const Type *RealForwardedType = ForwardType->getForwardedType();
171 if (!RealForwardedType)
172 return ForwardType; // No it's not forwarded again
174 // Yes, it is forwarded again. First thing, add the reference to the new
176 if (RealForwardedType->isAbstract())
177 cast<DerivedType>(RealForwardedType)->addRef();
179 // Now drop the old reference. This could cause ForwardType to get deleted.
180 cast<DerivedType>(ForwardType)->dropRef();
182 // Return the updated type.
183 ForwardType = RealForwardedType;
187 // getTypeDescription - This is a recursive function that walks a type hierarchy
188 // calculating the description for a type.
190 static std::string getTypeDescription(const Type *Ty,
191 std::vector<const Type *> &TypeStack) {
192 if (isa<OpaqueType>(Ty)) { // Base case for the recursion
193 std::map<const Type*, std::string>::iterator I =
194 AbstractTypeDescriptions.lower_bound(Ty);
195 if (I != AbstractTypeDescriptions.end() && I->first == Ty)
197 std::string Desc = "opaque"+utostr(Ty->getUniqueID());
198 AbstractTypeDescriptions.insert(std::make_pair(Ty, Desc));
202 if (!Ty->isAbstract()) { // Base case for the recursion
203 std::map<const Type*, std::string>::iterator I =
204 ConcreteTypeDescriptions.find(Ty);
205 if (I != ConcreteTypeDescriptions.end()) return I->second;
208 // Check to see if the Type is already on the stack...
209 unsigned Slot = 0, CurSize = TypeStack.size();
210 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
212 // This is another base case for the recursion. In this case, we know
213 // that we have looped back to a type that we have previously visited.
214 // Generate the appropriate upreference to handle this.
217 return "\\" + utostr(CurSize-Slot); // Here's the upreference
219 // Recursive case: derived types...
221 TypeStack.push_back(Ty); // Add us to the stack..
223 switch (Ty->getPrimitiveID()) {
224 case Type::FunctionTyID: {
225 const FunctionType *FTy = cast<FunctionType>(Ty);
226 Result = getTypeDescription(FTy->getReturnType(), TypeStack) + " (";
227 for (FunctionType::param_iterator I = FTy->param_begin(),
228 E = FTy->param_end(); I != E; ++I) {
229 if (I != FTy->param_begin())
231 Result += getTypeDescription(*I, TypeStack);
233 if (FTy->isVarArg()) {
234 if (FTy->getNumParams()) Result += ", ";
240 case Type::StructTyID: {
241 const StructType *STy = cast<StructType>(Ty);
243 for (StructType::element_iterator I = STy->element_begin(),
244 E = STy->element_end(); I != E; ++I) {
245 if (I != STy->element_begin())
247 Result += getTypeDescription(*I, TypeStack);
252 case Type::PointerTyID: {
253 const PointerType *PTy = cast<PointerType>(Ty);
254 Result = getTypeDescription(PTy->getElementType(), TypeStack) + " *";
257 case Type::ArrayTyID: {
258 const ArrayType *ATy = cast<ArrayType>(Ty);
259 unsigned NumElements = ATy->getNumElements();
261 Result += utostr(NumElements) + " x ";
262 Result += getTypeDescription(ATy->getElementType(), TypeStack) + "]";
267 assert(0 && "Unhandled type in getTypeDescription!");
270 TypeStack.pop_back(); // Remove self from stack...
277 static const std::string &getOrCreateDesc(std::map<const Type*,std::string>&Map,
279 std::map<const Type*, std::string>::iterator I = Map.find(Ty);
280 if (I != Map.end()) return I->second;
282 std::vector<const Type *> TypeStack;
283 return Map[Ty] = getTypeDescription(Ty, TypeStack);
287 const std::string &Type::getDescription() const {
289 return getOrCreateDesc(AbstractTypeDescriptions, this);
291 return getOrCreateDesc(ConcreteTypeDescriptions, this);
295 bool StructType::indexValid(const Value *V) const {
296 // Structure indexes require unsigned integer constants.
297 if (V->getType() == Type::UIntTy)
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(indexValid(V) && "Invalid structure index!");
308 unsigned Idx = (unsigned)cast<ConstantUInt>(V)->getValue();
309 return ContainedTys[Idx];
313 //===----------------------------------------------------------------------===//
315 //===----------------------------------------------------------------------===//
317 // These classes are used to implement specialized behavior for each different
320 struct SignedIntType : public Type {
321 SignedIntType(const std::string &Name, PrimitiveID id) : Type(Name, id) {}
323 // isSigned - Return whether a numeric type is signed.
324 virtual bool isSigned() const { return 1; }
326 // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
327 // virtual function invocation.
329 virtual bool isInteger() const { return 1; }
332 struct UnsignedIntType : public Type {
333 UnsignedIntType(const std::string &N, PrimitiveID id) : Type(N, id) {}
335 // isUnsigned - Return whether a numeric type is signed.
336 virtual bool isUnsigned() const { return 1; }
338 // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
339 // virtual function invocation.
341 virtual bool isInteger() const { return 1; }
344 struct OtherType : public Type {
345 OtherType(const std::string &N, PrimitiveID id) : Type(N, id) {}
348 static struct TypeType : public Type {
349 TypeType() : Type("type", TypeTyID) {}
350 } TheTypeTy; // Implement the type that is global.
353 //===----------------------------------------------------------------------===//
354 // Static 'Type' data
355 //===----------------------------------------------------------------------===//
357 static OtherType TheVoidTy ("void" , Type::VoidTyID);
358 static OtherType TheBoolTy ("bool" , Type::BoolTyID);
359 static SignedIntType TheSByteTy ("sbyte" , Type::SByteTyID);
360 static UnsignedIntType TheUByteTy ("ubyte" , Type::UByteTyID);
361 static SignedIntType TheShortTy ("short" , Type::ShortTyID);
362 static UnsignedIntType TheUShortTy("ushort", Type::UShortTyID);
363 static SignedIntType TheIntTy ("int" , Type::IntTyID);
364 static UnsignedIntType TheUIntTy ("uint" , Type::UIntTyID);
365 static SignedIntType TheLongTy ("long" , Type::LongTyID);
366 static UnsignedIntType TheULongTy ("ulong" , Type::ULongTyID);
367 static OtherType TheFloatTy ("float" , Type::FloatTyID);
368 static OtherType TheDoubleTy("double", Type::DoubleTyID);
369 static OtherType TheLabelTy ("label" , Type::LabelTyID);
371 Type *Type::VoidTy = &TheVoidTy;
372 Type *Type::BoolTy = &TheBoolTy;
373 Type *Type::SByteTy = &TheSByteTy;
374 Type *Type::UByteTy = &TheUByteTy;
375 Type *Type::ShortTy = &TheShortTy;
376 Type *Type::UShortTy = &TheUShortTy;
377 Type *Type::IntTy = &TheIntTy;
378 Type *Type::UIntTy = &TheUIntTy;
379 Type *Type::LongTy = &TheLongTy;
380 Type *Type::ULongTy = &TheULongTy;
381 Type *Type::FloatTy = &TheFloatTy;
382 Type *Type::DoubleTy = &TheDoubleTy;
383 Type *Type::TypeTy = &TheTypeTy;
384 Type *Type::LabelTy = &TheLabelTy;
387 //===----------------------------------------------------------------------===//
388 // Derived Type Constructors
389 //===----------------------------------------------------------------------===//
391 FunctionType::FunctionType(const Type *Result,
392 const std::vector<const Type*> &Params,
393 bool IsVarArgs) : DerivedType(FunctionTyID),
394 isVarArgs(IsVarArgs) {
395 bool isAbstract = Result->isAbstract();
396 ContainedTys.reserve(Params.size()+1);
397 ContainedTys.push_back(PATypeHandle(Result, this));
399 for (unsigned i = 0; i != Params.size(); ++i) {
400 ContainedTys.push_back(PATypeHandle(Params[i], this));
401 isAbstract |= Params[i]->isAbstract();
404 // Calculate whether or not this type is abstract
405 setAbstract(isAbstract);
408 StructType::StructType(const std::vector<const Type*> &Types)
409 : CompositeType(StructTyID) {
410 ContainedTys.reserve(Types.size());
411 bool isAbstract = false;
412 for (unsigned i = 0; i < Types.size(); ++i) {
413 assert(Types[i] != Type::VoidTy && "Void type for structure field!!");
414 ContainedTys.push_back(PATypeHandle(Types[i], this));
415 isAbstract |= Types[i]->isAbstract();
418 // Calculate whether or not this type is abstract
419 setAbstract(isAbstract);
422 ArrayType::ArrayType(const Type *ElType, unsigned NumEl)
423 : SequentialType(ArrayTyID, ElType) {
426 // Calculate whether or not this type is abstract
427 setAbstract(ElType->isAbstract());
430 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
431 // Calculate whether or not this type is abstract
432 setAbstract(E->isAbstract());
435 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
437 #ifdef DEBUG_MERGE_TYPES
438 std::cerr << "Derived new type: " << *this << "\n";
442 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
443 // another (more concrete) type, we must eliminate all references to other
444 // types, to avoid some circular reference problems.
445 void DerivedType::dropAllTypeUses() {
446 if (!ContainedTys.empty()) {
447 while (ContainedTys.size() > 1)
448 ContainedTys.pop_back();
450 // The type must stay abstract. To do this, we insert a pointer to a type
451 // that will never get resolved, thus will always be abstract.
452 static Type *AlwaysOpaqueTy = OpaqueType::get();
453 static PATypeHolder Holder(AlwaysOpaqueTy);
454 ContainedTys[0] = AlwaysOpaqueTy;
458 // isTypeAbstract - This is a recursive function that walks a type hierarchy
459 // calculating whether or not a type is abstract. Worst case it will have to do
460 // a lot of traversing if you have some whacko opaque types, but in most cases,
461 // it will do some simple stuff when it hits non-abstract types that aren't
464 bool Type::isTypeAbstract() {
465 if (!isAbstract()) // Base case for the recursion
466 return false; // Primitive = leaf type
468 if (isa<OpaqueType>(this)) // Base case for the recursion
469 return true; // This whole type is abstract!
471 // We have to guard against recursion. To do this, we temporarily mark this
472 // type as concrete, so that if we get back to here recursively we will think
473 // it's not abstract, and thus not scan it again.
476 // Scan all of the sub-types. If any of them are abstract, than so is this
478 for (Type::subtype_iterator I = subtype_begin(), E = subtype_end();
480 if (const_cast<Type*>(I->get())->isTypeAbstract()) {
481 setAbstract(true); // Restore the abstract bit.
482 return true; // This type is abstract if subtype is abstract!
485 // Restore the abstract bit.
488 // Nothing looks abstract here...
493 //===----------------------------------------------------------------------===//
494 // Type Structural Equality Testing
495 //===----------------------------------------------------------------------===//
497 // TypesEqual - Two types are considered structurally equal if they have the
498 // same "shape": Every level and element of the types have identical primitive
499 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
500 // be pointer equals to be equivalent though. This uses an optimistic algorithm
501 // that assumes that two graphs are the same until proven otherwise.
503 static bool TypesEqual(const Type *Ty, const Type *Ty2,
504 std::map<const Type *, const Type *> &EqTypes) {
505 if (Ty == Ty2) return true;
506 if (Ty->getPrimitiveID() != Ty2->getPrimitiveID()) return false;
507 if (isa<OpaqueType>(Ty))
508 return false; // Two unequal opaque types are never equal
510 std::map<const Type*, const Type*>::iterator It = EqTypes.lower_bound(Ty);
511 if (It != EqTypes.end() && It->first == Ty)
512 return It->second == Ty2; // Looping back on a type, check for equality
514 // Otherwise, add the mapping to the table to make sure we don't get
515 // recursion on the types...
516 EqTypes.insert(It, std::make_pair(Ty, Ty2));
518 // Two really annoying special cases that breaks an otherwise nice simple
519 // algorithm is the fact that arraytypes have sizes that differentiates types,
520 // and that function types can be varargs or not. Consider this now.
522 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
523 return TypesEqual(PTy->getElementType(),
524 cast<PointerType>(Ty2)->getElementType(), EqTypes);
525 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
526 const StructType *STy2 = cast<StructType>(Ty2);
527 if (STy->getNumElements() != STy2->getNumElements()) return false;
528 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
529 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
532 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
533 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
534 return ATy->getNumElements() == ATy2->getNumElements() &&
535 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
536 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
537 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
538 if (FTy->isVarArg() != FTy2->isVarArg() ||
539 FTy->getNumParams() != FTy2->getNumParams() ||
540 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
542 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i)
543 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
547 assert(0 && "Unknown derived type!");
552 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
553 std::map<const Type *, const Type *> EqTypes;
554 return TypesEqual(Ty, Ty2, EqTypes);
557 // TypeHasCycleThrough - Return true there is a path from CurTy to TargetTy in
558 // the type graph. We know that Ty is an abstract type, so if we ever reach a
559 // non-abstract type, we know that we don't need to search the subgraph.
560 static bool TypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
561 std::set<const Type*> &VisitedTypes) {
562 if (TargetTy == CurTy) return true;
563 if (!CurTy->isAbstract()) return false;
565 std::set<const Type*>::iterator VTI = VisitedTypes.lower_bound(CurTy);
566 if (VTI != VisitedTypes.end() && *VTI == CurTy)
568 VisitedTypes.insert(VTI, CurTy);
570 for (Type::subtype_iterator I = CurTy->subtype_begin(),
571 E = CurTy->subtype_end(); I != E; ++I)
572 if (TypeHasCycleThrough(TargetTy, *I, VisitedTypes))
578 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
580 static bool TypeHasCycleThroughItself(const Type *Ty) {
581 assert(Ty->isAbstract() && "This code assumes that Ty was abstract!");
582 std::set<const Type*> VisitedTypes;
583 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
585 if (TypeHasCycleThrough(Ty, *I, VisitedTypes))
591 //===----------------------------------------------------------------------===//
592 // Derived Type Factory Functions
593 //===----------------------------------------------------------------------===//
595 // TypeMap - Make sure that only one instance of a particular type may be
596 // created on any given run of the compiler... note that this involves updating
597 // our map if an abstract type gets refined somehow.
600 template<class ValType, class TypeClass>
602 std::map<ValType, PATypeHolder> Map;
604 /// TypesByHash - Keep track of each type by its structure hash value.
606 std::multimap<unsigned, PATypeHolder> TypesByHash;
608 typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
609 ~TypeMap() { print("ON EXIT"); }
611 inline TypeClass *get(const ValType &V) {
612 iterator I = Map.find(V);
613 return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
616 inline void add(const ValType &V, TypeClass *Ty) {
617 Map.insert(std::make_pair(V, Ty));
619 // If this type has a cycle, remember it.
620 TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
624 void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
625 std::multimap<unsigned, PATypeHolder>::iterator I =
626 TypesByHash.lower_bound(Hash);
627 while (I->second != Ty) {
629 assert(I != TypesByHash.end() && I->first == Hash);
631 TypesByHash.erase(I);
634 /// finishRefinement - This method is called after we have updated an existing
635 /// type with its new components. We must now either merge the type away with
636 /// some other type or reinstall it in the map with it's new configuration.
637 /// The specified iterator tells us what the type USED to look like.
638 void finishRefinement(TypeClass *Ty, const DerivedType *OldType,
639 const Type *NewType) {
640 assert((Ty->isAbstract() || !OldType->isAbstract()) &&
641 "Refining a non-abstract type!");
642 #ifdef DEBUG_MERGE_TYPES
643 std::cerr << "refineAbstractTy(" << (void*)OldType << "[" << *OldType
644 << "], " << (void*)NewType << " [" << *NewType << "])\n";
647 // Make a temporary type holder for the type so that it doesn't disappear on
648 // us when we erase the entry from the map.
649 PATypeHolder TyHolder = Ty;
651 // The old record is now out-of-date, because one of the children has been
652 // updated. Remove the obsolete entry from the map.
653 Map.erase(ValType::get(Ty));
655 // Remember the structural hash for the type before we start hacking on it,
656 // in case we need it later. Also, check to see if the type HAD a cycle
657 // through it, if so, we know it will when we hack on it.
658 unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
660 // Find the type element we are refining... and change it now!
661 for (unsigned i = 0, e = Ty->ContainedTys.size(); i != e; ++i)
662 if (Ty->ContainedTys[i] == OldType) {
663 Ty->ContainedTys[i].removeUserFromConcrete();
664 Ty->ContainedTys[i] = NewType;
667 unsigned TypeHash = ValType::hashTypeStructure(Ty);
669 // If there are no cycles going through this node, we can do a simple,
670 // efficient lookup in the map, instead of an inefficient nasty linear
672 bool TypeHasCycle = Ty->isAbstract() && TypeHasCycleThroughItself(Ty);
674 iterator I = Map.find(ValType::get(Ty));
675 if (I != Map.end()) {
676 // We already have this type in the table. Get rid of the newly refined
678 assert(Ty->isAbstract() && "Replacing a non-abstract type?");
679 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
681 // Refined to a different type altogether?
682 RemoveFromTypesByHash(TypeHash, Ty);
683 Ty->refineAbstractTypeTo(NewTy);
688 // Now we check to see if there is an existing entry in the table which is
689 // structurally identical to the newly refined type. If so, this type
690 // gets refined to the pre-existing type.
692 std::multimap<unsigned, PATypeHolder>::iterator I,E, Entry;
693 tie(I, E) = TypesByHash.equal_range(TypeHash);
695 for (; I != E; ++I) {
696 if (I->second != Ty) {
697 if (TypesEqual(Ty, I->second)) {
698 assert(Ty->isAbstract() && "Replacing a non-abstract type?");
699 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
702 // Find the location of Ty in the TypesByHash structure.
703 while (I->second != Ty) {
705 assert(I != E && "Structure doesn't contain type??");
710 TypesByHash.erase(Entry);
711 Ty->refineAbstractTypeTo(NewTy);
715 // Remember the position of
721 // If we succeeded, we need to insert the type into the cycletypes table.
722 // There are several cases here, depending on whether the original type
723 // had the same hash code and was itself cyclic.
724 if (TypeHash != OldTypeHash) {
725 RemoveFromTypesByHash(OldTypeHash, Ty);
726 TypesByHash.insert(std::make_pair(TypeHash, Ty));
729 // If there is no existing type of the same structure, we reinsert an
730 // updated record into the map.
731 Map.insert(std::make_pair(ValType::get(Ty), Ty));
733 // If the type is currently thought to be abstract, rescan all of our
734 // subtypes to see if the type has just become concrete!
735 if (Ty->isAbstract()) {
736 Ty->setAbstract(Ty->isTypeAbstract());
738 // If the type just became concrete, notify all users!
739 if (!Ty->isAbstract())
740 Ty->notifyUsesThatTypeBecameConcrete();
744 void print(const char *Arg) const {
745 #ifdef DEBUG_MERGE_TYPES
746 std::cerr << "TypeMap<>::" << Arg << " table contents:\n";
748 for (typename std::map<ValType, PATypeHolder>::const_iterator I
749 = Map.begin(), E = Map.end(); I != E; ++I)
750 std::cerr << " " << (++i) << ". " << (void*)I->second.get() << " "
751 << *I->second.get() << "\n";
755 void dump() const { print("dump output"); }
760 //===----------------------------------------------------------------------===//
761 // Function Type Factory and Value Class...
764 // FunctionValType - Define a class to hold the key that goes into the TypeMap
767 class FunctionValType {
769 std::vector<const Type*> ArgTypes;
772 FunctionValType(const Type *ret, const std::vector<const Type*> &args,
773 bool IVA) : RetTy(ret), isVarArg(IVA) {
774 for (unsigned i = 0; i < args.size(); ++i)
775 ArgTypes.push_back(args[i]);
778 static FunctionValType get(const FunctionType *FT);
780 static unsigned hashTypeStructure(const FunctionType *FT) {
781 return FT->getNumParams()*2+FT->isVarArg();
784 // Subclass should override this... to update self as usual
785 void doRefinement(const DerivedType *OldType, const Type *NewType) {
786 if (RetTy == OldType) RetTy = NewType;
787 for (unsigned i = 0, e = ArgTypes.size(); i != e; ++i)
788 if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
791 inline bool operator<(const FunctionValType &MTV) const {
792 if (RetTy < MTV.RetTy) return true;
793 if (RetTy > MTV.RetTy) return false;
795 if (ArgTypes < MTV.ArgTypes) return true;
796 return ArgTypes == MTV.ArgTypes && isVarArg < MTV.isVarArg;
801 // Define the actual map itself now...
802 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
804 FunctionValType FunctionValType::get(const FunctionType *FT) {
805 // Build up a FunctionValType
806 std::vector<const Type *> ParamTypes;
807 ParamTypes.reserve(FT->getNumParams());
808 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
809 ParamTypes.push_back(FT->getParamType(i));
810 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
814 // FunctionType::get - The factory function for the FunctionType class...
815 FunctionType *FunctionType::get(const Type *ReturnType,
816 const std::vector<const Type*> &Params,
818 FunctionValType VT(ReturnType, Params, isVarArg);
819 FunctionType *MT = FunctionTypes.get(VT);
822 FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
824 #ifdef DEBUG_MERGE_TYPES
825 std::cerr << "Derived new type: " << MT << "\n";
830 //===----------------------------------------------------------------------===//
831 // Array Type Factory...
838 ArrayValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
840 static ArrayValType get(const ArrayType *AT) {
841 return ArrayValType(AT->getElementType(), AT->getNumElements());
844 static unsigned hashTypeStructure(const ArrayType *AT) {
845 return AT->getNumElements();
848 // Subclass should override this... to update self as usual
849 void doRefinement(const DerivedType *OldType, const Type *NewType) {
850 assert(ValTy == OldType);
854 inline bool operator<(const ArrayValType &MTV) const {
855 if (Size < MTV.Size) return true;
856 return Size == MTV.Size && ValTy < MTV.ValTy;
860 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
863 ArrayType *ArrayType::get(const Type *ElementType, unsigned NumElements) {
864 assert(ElementType && "Can't get array of null types!");
866 ArrayValType AVT(ElementType, NumElements);
867 ArrayType *AT = ArrayTypes.get(AVT);
868 if (AT) return AT; // Found a match, return it!
870 // Value not found. Derive a new type!
871 ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
873 #ifdef DEBUG_MERGE_TYPES
874 std::cerr << "Derived new type: " << *AT << "\n";
879 //===----------------------------------------------------------------------===//
880 // Struct Type Factory...
884 // StructValType - Define a class to hold the key that goes into the TypeMap
886 class StructValType {
887 std::vector<const Type*> ElTypes;
889 StructValType(const std::vector<const Type*> &args) : ElTypes(args) {}
891 static StructValType get(const StructType *ST) {
892 std::vector<const Type *> ElTypes;
893 ElTypes.reserve(ST->getNumElements());
894 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
895 ElTypes.push_back(ST->getElementType(i));
897 return StructValType(ElTypes);
900 static unsigned hashTypeStructure(const StructType *ST) {
901 return ST->getNumElements();
904 // Subclass should override this... to update self as usual
905 void doRefinement(const DerivedType *OldType, const Type *NewType) {
906 for (unsigned i = 0; i < ElTypes.size(); ++i)
907 if (ElTypes[i] == OldType) ElTypes[i] = NewType;
910 inline bool operator<(const StructValType &STV) const {
911 return ElTypes < STV.ElTypes;
916 static TypeMap<StructValType, StructType> StructTypes;
918 StructType *StructType::get(const std::vector<const Type*> &ETypes) {
919 StructValType STV(ETypes);
920 StructType *ST = StructTypes.get(STV);
923 // Value not found. Derive a new type!
924 StructTypes.add(STV, ST = new StructType(ETypes));
926 #ifdef DEBUG_MERGE_TYPES
927 std::cerr << "Derived new type: " << *ST << "\n";
934 //===----------------------------------------------------------------------===//
935 // Pointer Type Factory...
938 // PointerValType - Define a class to hold the key that goes into the TypeMap
941 class PointerValType {
944 PointerValType(const Type *val) : ValTy(val) {}
946 static PointerValType get(const PointerType *PT) {
947 return PointerValType(PT->getElementType());
950 static unsigned hashTypeStructure(const PointerType *PT) {
954 // Subclass should override this... to update self as usual
955 void doRefinement(const DerivedType *OldType, const Type *NewType) {
956 assert(ValTy == OldType);
960 bool operator<(const PointerValType &MTV) const {
961 return ValTy < MTV.ValTy;
966 static TypeMap<PointerValType, PointerType> PointerTypes;
968 PointerType *PointerType::get(const Type *ValueType) {
969 assert(ValueType && "Can't get a pointer to <null> type!");
970 PointerValType PVT(ValueType);
972 PointerType *PT = PointerTypes.get(PVT);
975 // Value not found. Derive a new type!
976 PointerTypes.add(PVT, PT = new PointerType(ValueType));
978 #ifdef DEBUG_MERGE_TYPES
979 std::cerr << "Derived new type: " << *PT << "\n";
985 //===----------------------------------------------------------------------===//
986 // Derived Type Refinement Functions
987 //===----------------------------------------------------------------------===//
989 // removeAbstractTypeUser - Notify an abstract type that a user of the class
990 // no longer has a handle to the type. This function is called primarily by
991 // the PATypeHandle class. When there are no users of the abstract type, it
992 // is annihilated, because there is no way to get a reference to it ever again.
994 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
995 // Search from back to front because we will notify users from back to
996 // front. Also, it is likely that there will be a stack like behavior to
997 // users that register and unregister users.
1000 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1001 assert(i != 0 && "AbstractTypeUser not in user list!");
1003 --i; // Convert to be in range 0 <= i < size()
1004 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
1006 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1008 #ifdef DEBUG_MERGE_TYPES
1009 std::cerr << " remAbstractTypeUser[" << (void*)this << ", "
1010 << *this << "][" << i << "] User = " << U << "\n";
1013 if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1014 #ifdef DEBUG_MERGE_TYPES
1015 std::cerr << "DELETEing unused abstract type: <" << *this
1016 << ">[" << (void*)this << "]" << "\n";
1018 delete this; // No users of this abstract type!
1023 // refineAbstractTypeTo - This function is used to when it is discovered that
1024 // the 'this' abstract type is actually equivalent to the NewType specified.
1025 // This causes all users of 'this' to switch to reference the more concrete type
1026 // NewType and for 'this' to be deleted.
1028 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1029 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1030 assert(this != NewType && "Can't refine to myself!");
1031 assert(ForwardType == 0 && "This type has already been refined!");
1033 // The descriptions may be out of date. Conservatively clear them all!
1034 AbstractTypeDescriptions.clear();
1036 #ifdef DEBUG_MERGE_TYPES
1037 std::cerr << "REFINING abstract type [" << (void*)this << " "
1038 << *this << "] to [" << (void*)NewType << " "
1039 << *NewType << "]!\n";
1042 // Make sure to put the type to be refined to into a holder so that if IT gets
1043 // refined, that we will not continue using a dead reference...
1045 PATypeHolder NewTy(NewType);
1047 // Any PATypeHolders referring to this type will now automatically forward to
1048 // the type we are resolved to.
1049 ForwardType = NewType;
1050 if (NewType->isAbstract())
1051 cast<DerivedType>(NewType)->addRef();
1053 // Add a self use of the current type so that we don't delete ourself until
1054 // after the function exits.
1056 PATypeHolder CurrentTy(this);
1058 // To make the situation simpler, we ask the subclass to remove this type from
1059 // the type map, and to replace any type uses with uses of non-abstract types.
1060 // This dramatically limits the amount of recursive type trouble we can find
1064 // Iterate over all of the uses of this type, invoking callback. Each user
1065 // should remove itself from our use list automatically. We have to check to
1066 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1067 // will not cause users to drop off of the use list. If we resolve to ourself
1070 while (!AbstractTypeUsers.empty() && NewTy != this) {
1071 AbstractTypeUser *User = AbstractTypeUsers.back();
1073 unsigned OldSize = AbstractTypeUsers.size();
1074 #ifdef DEBUG_MERGE_TYPES
1075 std::cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
1076 << "] of abstract type [" << (void*)this << " "
1077 << *this << "] to [" << (void*)NewTy.get() << " "
1078 << *NewTy << "]!\n";
1080 User->refineAbstractType(this, NewTy);
1082 assert(AbstractTypeUsers.size() != OldSize &&
1083 "AbsTyUser did not remove self from user list!");
1086 // If we were successful removing all users from the type, 'this' will be
1087 // deleted when the last PATypeHolder is destroyed or updated from this type.
1088 // This may occur on exit of this function, as the CurrentTy object is
1092 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1093 // the current type has transitioned from being abstract to being concrete.
1095 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1096 #ifdef DEBUG_MERGE_TYPES
1097 std::cerr << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1100 unsigned OldSize = AbstractTypeUsers.size();
1101 while (!AbstractTypeUsers.empty()) {
1102 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1103 ATU->typeBecameConcrete(this);
1105 assert(AbstractTypeUsers.size() < OldSize-- &&
1106 "AbstractTypeUser did not remove itself from the use list!");
1113 // refineAbstractType - Called when a contained type is found to be more
1114 // concrete - this could potentially change us from an abstract type to a
1117 void FunctionType::refineAbstractType(const DerivedType *OldType,
1118 const Type *NewType) {
1119 FunctionTypes.finishRefinement(this, OldType, NewType);
1122 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1123 refineAbstractType(AbsTy, AbsTy);
1127 // refineAbstractType - Called when a contained type is found to be more
1128 // concrete - this could potentially change us from an abstract type to a
1131 void ArrayType::refineAbstractType(const DerivedType *OldType,
1132 const Type *NewType) {
1133 ArrayTypes.finishRefinement(this, OldType, NewType);
1136 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1137 refineAbstractType(AbsTy, AbsTy);
1141 // refineAbstractType - Called when a contained type is found to be more
1142 // concrete - this could potentially change us from an abstract type to a
1145 void StructType::refineAbstractType(const DerivedType *OldType,
1146 const Type *NewType) {
1147 StructTypes.finishRefinement(this, OldType, NewType);
1150 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1151 refineAbstractType(AbsTy, AbsTy);
1154 // refineAbstractType - Called when a contained type is found to be more
1155 // concrete - this could potentially change us from an abstract type to a
1158 void PointerType::refineAbstractType(const DerivedType *OldType,
1159 const Type *NewType) {
1160 PointerTypes.finishRefinement(this, OldType, NewType);
1163 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1164 refineAbstractType(AbsTy, AbsTy);