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
30 //===----------------------------------------------------------------------===//
31 // Type Class Implementation
32 //===----------------------------------------------------------------------===//
34 static unsigned CurUID = 0;
35 static std::vector<const Type *> UIDMappings;
37 // Concrete/Abstract TypeDescriptions - We lazily calculate type descriptions
38 // for types as they are needed. Because resolution of types must invalidate
39 // all of the abstract type descriptions, we keep them in a seperate map to make
41 static std::map<const Type*, std::string> ConcreteTypeDescriptions;
42 static std::map<const Type*, std::string> AbstractTypeDescriptions;
44 Type::Type(const std::string &name, PrimitiveID id)
45 : Value(Type::TypeTy, Value::TypeVal), ForwardType(0) {
47 ConcreteTypeDescriptions[this] = name;
50 UID = CurUID++; // Assign types UID's as they are created
51 UIDMappings.push_back(this);
54 void Type::setName(const std::string &Name, SymbolTable *ST) {
55 assert(ST && "Type::setName - Must provide symbol table argument!");
57 if (Name.size()) 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 // getPrimitiveSize - Return the basic size of this type if it is a primitive
116 // type. These are fixed by LLVM and are not target dependent. This will
117 // return zero if the type does not have a size or is not a primitive type.
119 unsigned Type::getPrimitiveSize() const {
120 switch (getPrimitiveID()) {
121 #define HANDLE_PRIM_TYPE(TY,SIZE) case TY##TyID: return SIZE;
122 #include "llvm/Type.def"
128 /// getForwardedTypeInternal - This method is used to implement the union-find
129 /// algorithm for when a type is being forwarded to another type.
130 const Type *Type::getForwardedTypeInternal() const {
131 assert(ForwardType && "This type is not being forwarded to another type!");
133 // Check to see if the forwarded type has been forwarded on. If so, collapse
134 // the forwarding links.
135 const Type *RealForwardedType = ForwardType->getForwardedType();
136 if (!RealForwardedType)
137 return ForwardType; // No it's not forwarded again
139 // Yes, it is forwarded again. First thing, add the reference to the new
141 if (RealForwardedType->isAbstract())
142 cast<DerivedType>(RealForwardedType)->addRef();
144 // Now drop the old reference. This could cause ForwardType to get deleted.
145 cast<DerivedType>(ForwardType)->dropRef();
147 // Return the updated type.
148 ForwardType = RealForwardedType;
152 // getTypeDescription - This is a recursive function that walks a type hierarchy
153 // calculating the description for a type.
155 static std::string getTypeDescription(const Type *Ty,
156 std::vector<const Type *> &TypeStack) {
157 if (isa<OpaqueType>(Ty)) { // Base case for the recursion
158 std::map<const Type*, std::string>::iterator I =
159 AbstractTypeDescriptions.lower_bound(Ty);
160 if (I != AbstractTypeDescriptions.end() && I->first == Ty)
162 std::string Desc = "opaque"+utostr(Ty->getUniqueID());
163 AbstractTypeDescriptions.insert(std::make_pair(Ty, Desc));
167 if (!Ty->isAbstract()) { // Base case for the recursion
168 std::map<const Type*, std::string>::iterator I =
169 ConcreteTypeDescriptions.find(Ty);
170 if (I != ConcreteTypeDescriptions.end()) return I->second;
173 // Check to see if the Type is already on the stack...
174 unsigned Slot = 0, CurSize = TypeStack.size();
175 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
177 // This is another base case for the recursion. In this case, we know
178 // that we have looped back to a type that we have previously visited.
179 // Generate the appropriate upreference to handle this.
182 return "\\" + utostr(CurSize-Slot); // Here's the upreference
184 // Recursive case: derived types...
186 TypeStack.push_back(Ty); // Add us to the stack..
188 switch (Ty->getPrimitiveID()) {
189 case Type::FunctionTyID: {
190 const FunctionType *FTy = cast<FunctionType>(Ty);
191 Result = getTypeDescription(FTy->getReturnType(), TypeStack) + " (";
192 for (FunctionType::param_iterator I = FTy->param_begin(),
193 E = FTy->param_end(); I != E; ++I) {
194 if (I != FTy->param_begin())
196 Result += getTypeDescription(*I, TypeStack);
198 if (FTy->isVarArg()) {
199 if (FTy->getNumParams()) Result += ", ";
205 case Type::StructTyID: {
206 const StructType *STy = cast<StructType>(Ty);
208 for (StructType::element_iterator I = STy->element_begin(),
209 E = STy->element_end(); I != E; ++I) {
210 if (I != STy->element_begin())
212 Result += getTypeDescription(*I, TypeStack);
217 case Type::PointerTyID: {
218 const PointerType *PTy = cast<PointerType>(Ty);
219 Result = getTypeDescription(PTy->getElementType(), TypeStack) + " *";
222 case Type::ArrayTyID: {
223 const ArrayType *ATy = cast<ArrayType>(Ty);
224 unsigned NumElements = ATy->getNumElements();
226 Result += utostr(NumElements) + " x ";
227 Result += getTypeDescription(ATy->getElementType(), TypeStack) + "]";
232 assert(0 && "Unhandled type in getTypeDescription!");
235 TypeStack.pop_back(); // Remove self from stack...
242 static const std::string &getOrCreateDesc(std::map<const Type*,std::string>&Map,
244 std::map<const Type*, std::string>::iterator I = Map.find(Ty);
245 if (I != Map.end()) return I->second;
247 std::vector<const Type *> TypeStack;
248 return Map[Ty] = getTypeDescription(Ty, TypeStack);
252 const std::string &Type::getDescription() const {
254 return getOrCreateDesc(AbstractTypeDescriptions, this);
256 return getOrCreateDesc(ConcreteTypeDescriptions, this);
260 bool StructType::indexValid(const Value *V) const {
261 // Structure indexes require unsigned integer constants.
262 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(V))
263 return CU->getValue() < ContainedTys.size();
267 // getTypeAtIndex - Given an index value into the type, return the type of the
268 // element. For a structure type, this must be a constant value...
270 const Type *StructType::getTypeAtIndex(const Value *V) const {
271 assert(isa<Constant>(V) && "Structure index must be a constant!!");
272 unsigned Idx = cast<ConstantUInt>(V)->getValue();
273 assert(Idx < ContainedTys.size() && "Structure index out of range!");
274 assert(indexValid(V) && "Invalid structure index!"); // Duplicate check
275 return ContainedTys[Idx];
279 //===----------------------------------------------------------------------===//
281 //===----------------------------------------------------------------------===//
283 // These classes are used to implement specialized behavior for each different
286 struct SignedIntType : public Type {
287 SignedIntType(const std::string &Name, PrimitiveID id) : Type(Name, id) {}
289 // isSigned - Return whether a numeric type is signed.
290 virtual bool isSigned() const { return 1; }
292 // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
293 // virtual function invocation.
295 virtual bool isInteger() const { return 1; }
298 struct UnsignedIntType : public Type {
299 UnsignedIntType(const std::string &N, PrimitiveID id) : Type(N, id) {}
301 // isUnsigned - Return whether a numeric type is signed.
302 virtual bool isUnsigned() const { return 1; }
304 // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
305 // virtual function invocation.
307 virtual bool isInteger() const { return 1; }
310 struct OtherType : public Type {
311 OtherType(const std::string &N, PrimitiveID id) : Type(N, id) {}
314 static struct TypeType : public Type {
315 TypeType() : Type("type", TypeTyID) {}
316 } TheTypeTy; // Implement the type that is global.
319 //===----------------------------------------------------------------------===//
320 // Static 'Type' data
321 //===----------------------------------------------------------------------===//
323 static OtherType TheVoidTy ("void" , Type::VoidTyID);
324 static OtherType TheBoolTy ("bool" , Type::BoolTyID);
325 static SignedIntType TheSByteTy ("sbyte" , Type::SByteTyID);
326 static UnsignedIntType TheUByteTy ("ubyte" , Type::UByteTyID);
327 static SignedIntType TheShortTy ("short" , Type::ShortTyID);
328 static UnsignedIntType TheUShortTy("ushort", Type::UShortTyID);
329 static SignedIntType TheIntTy ("int" , Type::IntTyID);
330 static UnsignedIntType TheUIntTy ("uint" , Type::UIntTyID);
331 static SignedIntType TheLongTy ("long" , Type::LongTyID);
332 static UnsignedIntType TheULongTy ("ulong" , Type::ULongTyID);
333 static OtherType TheFloatTy ("float" , Type::FloatTyID);
334 static OtherType TheDoubleTy("double", Type::DoubleTyID);
335 static OtherType TheLabelTy ("label" , Type::LabelTyID);
337 Type *Type::VoidTy = &TheVoidTy;
338 Type *Type::BoolTy = &TheBoolTy;
339 Type *Type::SByteTy = &TheSByteTy;
340 Type *Type::UByteTy = &TheUByteTy;
341 Type *Type::ShortTy = &TheShortTy;
342 Type *Type::UShortTy = &TheUShortTy;
343 Type *Type::IntTy = &TheIntTy;
344 Type *Type::UIntTy = &TheUIntTy;
345 Type *Type::LongTy = &TheLongTy;
346 Type *Type::ULongTy = &TheULongTy;
347 Type *Type::FloatTy = &TheFloatTy;
348 Type *Type::DoubleTy = &TheDoubleTy;
349 Type *Type::TypeTy = &TheTypeTy;
350 Type *Type::LabelTy = &TheLabelTy;
353 //===----------------------------------------------------------------------===//
354 // Derived Type Constructors
355 //===----------------------------------------------------------------------===//
357 FunctionType::FunctionType(const Type *Result,
358 const std::vector<const Type*> &Params,
359 bool IsVarArgs) : DerivedType(FunctionTyID),
360 isVarArgs(IsVarArgs) {
361 bool isAbstract = Result->isAbstract();
362 ContainedTys.reserve(Params.size()+1);
363 ContainedTys.push_back(PATypeHandle(Result, this));
365 for (unsigned i = 0; i != Params.size(); ++i) {
366 ContainedTys.push_back(PATypeHandle(Params[i], this));
367 isAbstract |= Params[i]->isAbstract();
370 // Calculate whether or not this type is abstract
371 setAbstract(isAbstract);
374 StructType::StructType(const std::vector<const Type*> &Types)
375 : CompositeType(StructTyID) {
376 ContainedTys.reserve(Types.size());
377 bool isAbstract = false;
378 for (unsigned i = 0; i < Types.size(); ++i) {
379 assert(Types[i] != Type::VoidTy && "Void type in method prototype!!");
380 ContainedTys.push_back(PATypeHandle(Types[i], this));
381 isAbstract |= Types[i]->isAbstract();
384 // Calculate whether or not this type is abstract
385 setAbstract(isAbstract);
388 ArrayType::ArrayType(const Type *ElType, unsigned NumEl)
389 : SequentialType(ArrayTyID, ElType) {
392 // Calculate whether or not this type is abstract
393 setAbstract(ElType->isAbstract());
396 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
397 // Calculate whether or not this type is abstract
398 setAbstract(E->isAbstract());
401 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
403 #ifdef DEBUG_MERGE_TYPES
404 std::cerr << "Derived new type: " << *this << "\n";
408 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
409 // another (more concrete) type, we must eliminate all references to other
410 // types, to avoid some circular reference problems.
411 void DerivedType::dropAllTypeUses() {
412 if (!ContainedTys.empty()) {
413 while (ContainedTys.size() > 1)
414 ContainedTys.pop_back();
416 // The type must stay abstract. To do this, we insert a pointer to a type
417 // that will never get resolved, thus will always be abstract.
418 static Type *AlwaysOpaqueTy = OpaqueType::get();
419 static PATypeHolder Holder(AlwaysOpaqueTy);
420 ContainedTys[0] = AlwaysOpaqueTy;
424 // isTypeAbstract - This is a recursive function that walks a type hierarchy
425 // calculating whether or not a type is abstract. Worst case it will have to do
426 // a lot of traversing if you have some whacko opaque types, but in most cases,
427 // it will do some simple stuff when it hits non-abstract types that aren't
430 bool Type::isTypeAbstract() {
431 if (!isAbstract()) // Base case for the recursion
432 return false; // Primitive = leaf type
434 if (isa<OpaqueType>(this)) // Base case for the recursion
435 return true; // This whole type is abstract!
437 // We have to guard against recursion. To do this, we temporarily mark this
438 // type as concrete, so that if we get back to here recursively we will think
439 // it's not abstract, and thus not scan it again.
442 // Scan all of the sub-types. If any of them are abstract, than so is this
444 for (Type::subtype_iterator I = subtype_begin(), E = subtype_end();
446 if (const_cast<Type*>(I->get())->isTypeAbstract()) {
447 setAbstract(true); // Restore the abstract bit.
448 return true; // This type is abstract if subtype is abstract!
451 // Restore the abstract bit.
454 // Nothing looks abstract here...
459 //===----------------------------------------------------------------------===//
460 // Type Structural Equality Testing
461 //===----------------------------------------------------------------------===//
463 // TypesEqual - Two types are considered structurally equal if they have the
464 // same "shape": Every level and element of the types have identical primitive
465 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
466 // be pointer equals to be equivalent though. This uses an optimistic algorithm
467 // that assumes that two graphs are the same until proven otherwise.
469 static bool TypesEqual(const Type *Ty, const Type *Ty2,
470 std::map<const Type *, const Type *> &EqTypes) {
471 if (Ty == Ty2) return true;
472 if (Ty->getPrimitiveID() != Ty2->getPrimitiveID()) return false;
473 if (isa<OpaqueType>(Ty))
474 return false; // Two unequal opaque types are never equal
476 std::map<const Type*, const Type*>::iterator It = EqTypes.lower_bound(Ty);
477 if (It != EqTypes.end() && It->first == Ty)
478 return It->second == Ty2; // Looping back on a type, check for equality
480 // Otherwise, add the mapping to the table to make sure we don't get
481 // recursion on the types...
482 EqTypes.insert(It, std::make_pair(Ty, Ty2));
484 // Two really annoying special cases that breaks an otherwise nice simple
485 // algorithm is the fact that arraytypes have sizes that differentiates types,
486 // and that function types can be varargs or not. Consider this now.
488 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
489 return TypesEqual(PTy->getElementType(),
490 cast<PointerType>(Ty2)->getElementType(), EqTypes);
491 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
492 const StructType *STy2 = cast<StructType>(Ty2);
493 if (STy->getNumElements() != STy2->getNumElements()) return false;
494 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
495 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
498 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
499 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
500 return ATy->getNumElements() == ATy2->getNumElements() &&
501 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
502 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
503 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
504 if (FTy->isVarArg() != FTy2->isVarArg() ||
505 FTy->getNumParams() != FTy2->getNumParams() ||
506 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
508 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i)
509 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
513 assert(0 && "Unknown derived type!");
518 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
519 std::map<const Type *, const Type *> EqTypes;
520 return TypesEqual(Ty, Ty2, EqTypes);
523 // TypeHasCycleThrough - Return true there is a path from CurTy to TargetTy in
524 // the type graph. We know that Ty is an abstract type, so if we ever reach a
525 // non-abstract type, we know that we don't need to search the subgraph.
526 static bool TypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
527 std::set<const Type*> &VisitedTypes) {
528 if (TargetTy == CurTy) return true;
529 if (!CurTy->isAbstract()) return false;
531 std::set<const Type*>::iterator VTI = VisitedTypes.lower_bound(CurTy);
532 if (VTI != VisitedTypes.end() && *VTI == CurTy)
534 VisitedTypes.insert(VTI, CurTy);
536 for (Type::subtype_iterator I = CurTy->subtype_begin(),
537 E = CurTy->subtype_end(); I != E; ++I)
538 if (TypeHasCycleThrough(TargetTy, *I, VisitedTypes))
544 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
546 static bool TypeHasCycleThroughItself(const Type *Ty) {
547 assert(Ty->isAbstract() && "This code assumes that Ty was abstract!");
548 std::set<const Type*> VisitedTypes;
549 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
551 if (TypeHasCycleThrough(Ty, *I, VisitedTypes))
557 //===----------------------------------------------------------------------===//
558 // Derived Type Factory Functions
559 //===----------------------------------------------------------------------===//
561 // TypeMap - Make sure that only one instance of a particular type may be
562 // created on any given run of the compiler... note that this involves updating
563 // our map if an abstract type gets refined somehow.
566 template<class ValType, class TypeClass>
568 std::map<ValType, PATypeHolder> Map;
570 /// TypesByHash - Keep track of each type by its structure hash value.
572 std::multimap<unsigned, PATypeHolder> TypesByHash;
574 typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
575 ~TypeMap() { print("ON EXIT"); }
577 inline TypeClass *get(const ValType &V) {
578 iterator I = Map.find(V);
579 return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
582 inline void add(const ValType &V, TypeClass *Ty) {
583 Map.insert(std::make_pair(V, Ty));
585 // If this type has a cycle, remember it.
586 TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
590 void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
591 std::multimap<unsigned, PATypeHolder>::iterator I =
592 TypesByHash.lower_bound(Hash);
593 while (I->second != Ty) {
595 assert(I != TypesByHash.end() && I->first == Hash);
597 TypesByHash.erase(I);
600 /// finishRefinement - This method is called after we have updated an existing
601 /// type with its new components. We must now either merge the type away with
602 /// some other type or reinstall it in the map with it's new configuration.
603 /// The specified iterator tells us what the type USED to look like.
604 void finishRefinement(TypeClass *Ty, const DerivedType *OldType,
605 const Type *NewType) {
606 assert((Ty->isAbstract() || !OldType->isAbstract()) &&
607 "Refining a non-abstract type!");
608 #ifdef DEBUG_MERGE_TYPES
609 std::cerr << "refineAbstractTy(" << (void*)OldType << "[" << *OldType
610 << "], " << (void*)NewType << " [" << *NewType << "])\n";
613 // Make a temporary type holder for the type so that it doesn't disappear on
614 // us when we erase the entry from the map.
615 PATypeHolder TyHolder = Ty;
617 // The old record is now out-of-date, because one of the children has been
618 // updated. Remove the obsolete entry from the map.
619 Map.erase(ValType::get(Ty));
621 // Remember the structural hash for the type before we start hacking on it,
622 // in case we need it later. Also, check to see if the type HAD a cycle
623 // through it, if so, we know it will when we hack on it.
624 unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
626 // Find the type element we are refining... and change it now!
627 for (unsigned i = 0, e = Ty->ContainedTys.size(); i != e; ++i)
628 if (Ty->ContainedTys[i] == OldType) {
629 Ty->ContainedTys[i].removeUserFromConcrete();
630 Ty->ContainedTys[i] = NewType;
633 unsigned TypeHash = ValType::hashTypeStructure(Ty);
635 // If there are no cycles going through this node, we can do a simple,
636 // efficient lookup in the map, instead of an inefficient nasty linear
638 bool TypeHasCycle = Ty->isAbstract() && TypeHasCycleThroughItself(Ty);
640 iterator I = Map.find(ValType::get(Ty));
641 if (I != Map.end()) {
642 // We already have this type in the table. Get rid of the newly refined
644 assert(Ty->isAbstract() && "Replacing a non-abstract type?");
645 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
647 // Refined to a different type altogether?
648 RemoveFromTypesByHash(TypeHash, Ty);
649 Ty->refineAbstractTypeTo(NewTy);
654 // Now we check to see if there is an existing entry in the table which is
655 // structurally identical to the newly refined type. If so, this type
656 // gets refined to the pre-existing type.
658 std::multimap<unsigned, PATypeHolder>::iterator I,E, Entry;
659 tie(I, E) = TypesByHash.equal_range(TypeHash);
661 for (; I != E; ++I) {
662 if (I->second != Ty) {
663 if (TypesEqual(Ty, I->second)) {
664 assert(Ty->isAbstract() && "Replacing a non-abstract type?");
665 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
668 // Find the location of Ty in the TypesByHash structure.
669 while (I->second != Ty) {
671 assert(I != E && "Structure doesn't contain type??");
676 TypesByHash.erase(Entry);
677 Ty->refineAbstractTypeTo(NewTy);
681 // Remember the position of
687 // If we succeeded, we need to insert the type into the cycletypes table.
688 // There are several cases here, depending on whether the original type
689 // had the same hash code and was itself cyclic.
690 if (TypeHash != OldTypeHash) {
691 RemoveFromTypesByHash(OldTypeHash, Ty);
692 TypesByHash.insert(std::make_pair(TypeHash, Ty));
695 // If there is no existing type of the same structure, we reinsert an
696 // updated record into the map.
697 Map.insert(std::make_pair(ValType::get(Ty), Ty));
699 // If the type is currently thought to be abstract, rescan all of our
700 // subtypes to see if the type has just become concrete!
701 if (Ty->isAbstract()) {
702 Ty->setAbstract(Ty->isTypeAbstract());
704 // If the type just became concrete, notify all users!
705 if (!Ty->isAbstract())
706 Ty->notifyUsesThatTypeBecameConcrete();
710 void print(const char *Arg) const {
711 #ifdef DEBUG_MERGE_TYPES
712 std::cerr << "TypeMap<>::" << Arg << " table contents:\n";
714 for (typename std::map<ValType, PATypeHolder>::const_iterator I
715 = Map.begin(), E = Map.end(); I != E; ++I)
716 std::cerr << " " << (++i) << ". " << (void*)I->second.get() << " "
717 << *I->second.get() << "\n";
721 void dump() const { print("dump output"); }
726 //===----------------------------------------------------------------------===//
727 // Function Type Factory and Value Class...
730 // FunctionValType - Define a class to hold the key that goes into the TypeMap
733 class FunctionValType {
735 std::vector<const Type*> ArgTypes;
738 FunctionValType(const Type *ret, const std::vector<const Type*> &args,
739 bool IVA) : RetTy(ret), isVarArg(IVA) {
740 for (unsigned i = 0; i < args.size(); ++i)
741 ArgTypes.push_back(args[i]);
744 static FunctionValType get(const FunctionType *FT);
746 static unsigned hashTypeStructure(const FunctionType *FT) {
747 return FT->getNumParams()*2+FT->isVarArg();
750 // Subclass should override this... to update self as usual
751 void doRefinement(const DerivedType *OldType, const Type *NewType) {
752 if (RetTy == OldType) RetTy = NewType;
753 for (unsigned i = 0, e = ArgTypes.size(); i != e; ++i)
754 if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
757 inline bool operator<(const FunctionValType &MTV) const {
758 if (RetTy < MTV.RetTy) return true;
759 if (RetTy > MTV.RetTy) return false;
761 if (ArgTypes < MTV.ArgTypes) return true;
762 return ArgTypes == MTV.ArgTypes && isVarArg < MTV.isVarArg;
767 // Define the actual map itself now...
768 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
770 FunctionValType FunctionValType::get(const FunctionType *FT) {
771 // Build up a FunctionValType
772 std::vector<const Type *> ParamTypes;
773 ParamTypes.reserve(FT->getNumParams());
774 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
775 ParamTypes.push_back(FT->getParamType(i));
776 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
780 // FunctionType::get - The factory function for the FunctionType class...
781 FunctionType *FunctionType::get(const Type *ReturnType,
782 const std::vector<const Type*> &Params,
784 FunctionValType VT(ReturnType, Params, isVarArg);
785 FunctionType *MT = FunctionTypes.get(VT);
788 FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
790 #ifdef DEBUG_MERGE_TYPES
791 std::cerr << "Derived new type: " << MT << "\n";
796 //===----------------------------------------------------------------------===//
797 // Array Type Factory...
804 ArrayValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
806 static ArrayValType get(const ArrayType *AT) {
807 return ArrayValType(AT->getElementType(), AT->getNumElements());
810 static unsigned hashTypeStructure(const ArrayType *AT) {
811 return AT->getNumElements();
814 // Subclass should override this... to update self as usual
815 void doRefinement(const DerivedType *OldType, const Type *NewType) {
816 assert(ValTy == OldType);
820 inline bool operator<(const ArrayValType &MTV) const {
821 if (Size < MTV.Size) return true;
822 return Size == MTV.Size && ValTy < MTV.ValTy;
826 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
829 ArrayType *ArrayType::get(const Type *ElementType, unsigned NumElements) {
830 assert(ElementType && "Can't get array of null types!");
832 ArrayValType AVT(ElementType, NumElements);
833 ArrayType *AT = ArrayTypes.get(AVT);
834 if (AT) return AT; // Found a match, return it!
836 // Value not found. Derive a new type!
837 ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
839 #ifdef DEBUG_MERGE_TYPES
840 std::cerr << "Derived new type: " << *AT << "\n";
845 //===----------------------------------------------------------------------===//
846 // Struct Type Factory...
850 // StructValType - Define a class to hold the key that goes into the TypeMap
852 class StructValType {
853 std::vector<const Type*> ElTypes;
855 StructValType(const std::vector<const Type*> &args) : ElTypes(args) {}
857 static StructValType get(const StructType *ST) {
858 std::vector<const Type *> ElTypes;
859 ElTypes.reserve(ST->getNumElements());
860 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
861 ElTypes.push_back(ST->getElementType(i));
863 return StructValType(ElTypes);
866 static unsigned hashTypeStructure(const StructType *ST) {
867 return ST->getNumElements();
870 // Subclass should override this... to update self as usual
871 void doRefinement(const DerivedType *OldType, const Type *NewType) {
872 for (unsigned i = 0; i < ElTypes.size(); ++i)
873 if (ElTypes[i] == OldType) ElTypes[i] = NewType;
876 inline bool operator<(const StructValType &STV) const {
877 return ElTypes < STV.ElTypes;
882 static TypeMap<StructValType, StructType> StructTypes;
884 StructType *StructType::get(const std::vector<const Type*> &ETypes) {
885 StructValType STV(ETypes);
886 StructType *ST = StructTypes.get(STV);
889 // Value not found. Derive a new type!
890 StructTypes.add(STV, ST = new StructType(ETypes));
892 #ifdef DEBUG_MERGE_TYPES
893 std::cerr << "Derived new type: " << *ST << "\n";
900 //===----------------------------------------------------------------------===//
901 // Pointer Type Factory...
904 // PointerValType - Define a class to hold the key that goes into the TypeMap
907 class PointerValType {
910 PointerValType(const Type *val) : ValTy(val) {}
912 static PointerValType get(const PointerType *PT) {
913 return PointerValType(PT->getElementType());
916 static unsigned hashTypeStructure(const PointerType *PT) {
920 // Subclass should override this... to update self as usual
921 void doRefinement(const DerivedType *OldType, const Type *NewType) {
922 assert(ValTy == OldType);
926 bool operator<(const PointerValType &MTV) const {
927 return ValTy < MTV.ValTy;
932 static TypeMap<PointerValType, PointerType> PointerTypes;
934 PointerType *PointerType::get(const Type *ValueType) {
935 assert(ValueType && "Can't get a pointer to <null> type!");
936 PointerValType PVT(ValueType);
938 PointerType *PT = PointerTypes.get(PVT);
941 // Value not found. Derive a new type!
942 PointerTypes.add(PVT, PT = new PointerType(ValueType));
944 #ifdef DEBUG_MERGE_TYPES
945 std::cerr << "Derived new type: " << *PT << "\n";
951 //===----------------------------------------------------------------------===//
952 // Derived Type Refinement Functions
953 //===----------------------------------------------------------------------===//
955 // removeAbstractTypeUser - Notify an abstract type that a user of the class
956 // no longer has a handle to the type. This function is called primarily by
957 // the PATypeHandle class. When there are no users of the abstract type, it
958 // is annihilated, because there is no way to get a reference to it ever again.
960 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
961 // Search from back to front because we will notify users from back to
962 // front. Also, it is likely that there will be a stack like behavior to
963 // users that register and unregister users.
966 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
967 assert(i != 0 && "AbstractTypeUser not in user list!");
969 --i; // Convert to be in range 0 <= i < size()
970 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
972 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
974 #ifdef DEBUG_MERGE_TYPES
975 std::cerr << " remAbstractTypeUser[" << (void*)this << ", "
976 << *this << "][" << i << "] User = " << U << "\n";
979 if (AbstractTypeUsers.empty() && RefCount == 0 && isAbstract()) {
980 #ifdef DEBUG_MERGE_TYPES
981 std::cerr << "DELETEing unused abstract type: <" << *this
982 << ">[" << (void*)this << "]" << "\n";
984 delete this; // No users of this abstract type!
989 // refineAbstractTypeTo - This function is used to when it is discovered that
990 // the 'this' abstract type is actually equivalent to the NewType specified.
991 // This causes all users of 'this' to switch to reference the more concrete type
992 // NewType and for 'this' to be deleted.
994 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
995 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
996 assert(this != NewType && "Can't refine to myself!");
997 assert(ForwardType == 0 && "This type has already been refined!");
999 // The descriptions may be out of date. Conservatively clear them all!
1000 AbstractTypeDescriptions.clear();
1002 #ifdef DEBUG_MERGE_TYPES
1003 std::cerr << "REFINING abstract type [" << (void*)this << " "
1004 << *this << "] to [" << (void*)NewType << " "
1005 << *NewType << "]!\n";
1008 // Make sure to put the type to be refined to into a holder so that if IT gets
1009 // refined, that we will not continue using a dead reference...
1011 PATypeHolder NewTy(NewType);
1013 // Any PATypeHolders referring to this type will now automatically forward to
1014 // the type we are resolved to.
1015 ForwardType = NewType;
1016 if (NewType->isAbstract())
1017 cast<DerivedType>(NewType)->addRef();
1019 // Add a self use of the current type so that we don't delete ourself until
1020 // after the function exits.
1022 PATypeHolder CurrentTy(this);
1024 // To make the situation simpler, we ask the subclass to remove this type from
1025 // the type map, and to replace any type uses with uses of non-abstract types.
1026 // This dramatically limits the amount of recursive type trouble we can find
1030 // Iterate over all of the uses of this type, invoking callback. Each user
1031 // should remove itself from our use list automatically. We have to check to
1032 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1033 // will not cause users to drop off of the use list. If we resolve to ourself
1036 while (!AbstractTypeUsers.empty() && NewTy != this) {
1037 AbstractTypeUser *User = AbstractTypeUsers.back();
1039 unsigned OldSize = AbstractTypeUsers.size();
1040 #ifdef DEBUG_MERGE_TYPES
1041 std::cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
1042 << "] of abstract type [" << (void*)this << " "
1043 << *this << "] to [" << (void*)NewTy.get() << " "
1044 << *NewTy << "]!\n";
1046 User->refineAbstractType(this, NewTy);
1048 assert(AbstractTypeUsers.size() != OldSize &&
1049 "AbsTyUser did not remove self from user list!");
1052 // If we were successful removing all users from the type, 'this' will be
1053 // deleted when the last PATypeHolder is destroyed or updated from this type.
1054 // This may occur on exit of this function, as the CurrentTy object is
1058 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1059 // the current type has transitioned from being abstract to being concrete.
1061 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1062 #ifdef DEBUG_MERGE_TYPES
1063 std::cerr << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1066 unsigned OldSize = AbstractTypeUsers.size();
1067 while (!AbstractTypeUsers.empty()) {
1068 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1069 ATU->typeBecameConcrete(this);
1071 assert(AbstractTypeUsers.size() < OldSize-- &&
1072 "AbstractTypeUser did not remove itself from the use list!");
1079 // refineAbstractType - Called when a contained type is found to be more
1080 // concrete - this could potentially change us from an abstract type to a
1083 void FunctionType::refineAbstractType(const DerivedType *OldType,
1084 const Type *NewType) {
1085 FunctionTypes.finishRefinement(this, OldType, NewType);
1088 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1089 refineAbstractType(AbsTy, AbsTy);
1093 // refineAbstractType - Called when a contained type is found to be more
1094 // concrete - this could potentially change us from an abstract type to a
1097 void ArrayType::refineAbstractType(const DerivedType *OldType,
1098 const Type *NewType) {
1099 ArrayTypes.finishRefinement(this, OldType, NewType);
1102 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1103 refineAbstractType(AbsTy, AbsTy);
1107 // refineAbstractType - Called when a contained type is found to be more
1108 // concrete - this could potentially change us from an abstract type to a
1111 void StructType::refineAbstractType(const DerivedType *OldType,
1112 const Type *NewType) {
1113 StructTypes.finishRefinement(this, OldType, NewType);
1116 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1117 refineAbstractType(AbsTy, AbsTy);
1120 // refineAbstractType - Called when a contained type is found to be more
1121 // concrete - this could potentially change us from an abstract type to a
1124 void PointerType::refineAbstractType(const DerivedType *OldType,
1125 const Type *NewType) {
1126 PointerTypes.finishRefinement(this, OldType, NewType);
1129 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1130 refineAbstractType(AbsTy, AbsTy);