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"
20 #include "Support/Statistic.h"
25 static Statistic<> NumSlowTypes("type", "num slow types");
26 static Statistic<> NumTypeEqualsCalls("type", "num typeequals calls");
27 static Statistic<> NumTypeEquals("type", "num types actually equal");
29 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
30 // created and later destroyed, all in an effort to make sure that there is only
31 // a single canonical version of a type.
33 //#define DEBUG_MERGE_TYPES 1
36 //===----------------------------------------------------------------------===//
37 // Type Class Implementation
38 //===----------------------------------------------------------------------===//
40 static unsigned CurUID = 0;
41 static std::vector<const Type *> UIDMappings;
43 // Concrete/Abstract TypeDescriptions - We lazily calculate type descriptions
44 // for types as they are needed. Because resolution of types must invalidate
45 // all of the abstract type descriptions, we keep them in a seperate map to make
47 static std::map<const Type*, std::string> ConcreteTypeDescriptions;
48 static std::map<const Type*, std::string> AbstractTypeDescriptions;
50 Type::Type(const std::string &name, PrimitiveID id)
51 : Value(Type::TypeTy, Value::TypeVal), ForwardType(0) {
53 ConcreteTypeDescriptions[this] = name;
56 UID = CurUID++; // Assign types UID's as they are created
57 UIDMappings.push_back(this);
60 void Type::setName(const std::string &Name, SymbolTable *ST) {
61 assert(ST && "Type::setName - Must provide symbol table argument!");
63 if (Name.size()) ST->insert(Name, this);
67 const Type *Type::getUniqueIDType(unsigned UID) {
68 assert(UID < UIDMappings.size() &&
69 "Type::getPrimitiveType: UID out of range!");
70 return UIDMappings[UID];
73 const Type *Type::getPrimitiveType(PrimitiveID IDNumber) {
75 case VoidTyID : return VoidTy;
76 case BoolTyID : return BoolTy;
77 case UByteTyID : return UByteTy;
78 case SByteTyID : return SByteTy;
79 case UShortTyID: return UShortTy;
80 case ShortTyID : return ShortTy;
81 case UIntTyID : return UIntTy;
82 case IntTyID : return IntTy;
83 case ULongTyID : return ULongTy;
84 case LongTyID : return LongTy;
85 case FloatTyID : return FloatTy;
86 case DoubleTyID: return DoubleTy;
87 case TypeTyID : return TypeTy;
88 case LabelTyID : return LabelTy;
94 // isLosslesslyConvertibleTo - Return true if this type can be converted to
95 // 'Ty' without any reinterpretation of bits. For example, uint to int.
97 bool Type::isLosslesslyConvertibleTo(const Type *Ty) const {
98 if (this == Ty) return true;
99 if ((!isPrimitiveType() && !isa<PointerType>(this)) ||
100 (!isa<PointerType>(Ty) && !Ty->isPrimitiveType())) return false;
102 if (getPrimitiveID() == Ty->getPrimitiveID())
103 return true; // Handles identity cast, and cast of differing pointer types
105 // Now we know that they are two differing primitive or pointer types
106 switch (getPrimitiveID()) {
107 case Type::UByteTyID: return Ty == Type::SByteTy;
108 case Type::SByteTyID: return Ty == Type::UByteTy;
109 case Type::UShortTyID: return Ty == Type::ShortTy;
110 case Type::ShortTyID: return Ty == Type::UShortTy;
111 case Type::UIntTyID: return Ty == Type::IntTy;
112 case Type::IntTyID: return Ty == Type::UIntTy;
113 case Type::ULongTyID: return Ty == Type::LongTy;
114 case Type::LongTyID: return Ty == Type::ULongTy;
115 case Type::PointerTyID: return isa<PointerType>(Ty);
117 return false; // Other types have no identity values
121 // getPrimitiveSize - Return the basic size of this type if it is a primitive
122 // type. These are fixed by LLVM and are not target dependent. This will
123 // return zero if the type does not have a size or is not a primitive type.
125 unsigned Type::getPrimitiveSize() const {
126 switch (getPrimitiveID()) {
127 #define HANDLE_PRIM_TYPE(TY,SIZE) case TY##TyID: return SIZE;
128 #include "llvm/Type.def"
134 /// getForwardedTypeInternal - This method is used to implement the union-find
135 /// algorithm for when a type is being forwarded to another type.
136 const Type *Type::getForwardedTypeInternal() const {
137 assert(ForwardType && "This type is not being forwarded to another type!");
139 // Check to see if the forwarded type has been forwarded on. If so, collapse
140 // the forwarding links.
141 const Type *RealForwardedType = ForwardType->getForwardedType();
142 if (!RealForwardedType)
143 return ForwardType; // No it's not forwarded again
145 // Yes, it is forwarded again. First thing, add the reference to the new
147 if (RealForwardedType->isAbstract())
148 cast<DerivedType>(RealForwardedType)->addRef();
150 // Now drop the old reference. This could cause ForwardType to get deleted.
151 cast<DerivedType>(ForwardType)->dropRef();
153 // Return the updated type.
154 ForwardType = RealForwardedType;
158 // getTypeDescription - This is a recursive function that walks a type hierarchy
159 // calculating the description for a type.
161 static std::string getTypeDescription(const Type *Ty,
162 std::vector<const Type *> &TypeStack) {
163 if (isa<OpaqueType>(Ty)) { // Base case for the recursion
164 std::map<const Type*, std::string>::iterator I =
165 AbstractTypeDescriptions.lower_bound(Ty);
166 if (I != AbstractTypeDescriptions.end() && I->first == Ty)
168 std::string Desc = "opaque"+utostr(Ty->getUniqueID());
169 AbstractTypeDescriptions.insert(std::make_pair(Ty, Desc));
173 if (!Ty->isAbstract()) { // Base case for the recursion
174 std::map<const Type*, std::string>::iterator I =
175 ConcreteTypeDescriptions.find(Ty);
176 if (I != ConcreteTypeDescriptions.end()) return I->second;
179 // Check to see if the Type is already on the stack...
180 unsigned Slot = 0, CurSize = TypeStack.size();
181 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
183 // This is another base case for the recursion. In this case, we know
184 // that we have looped back to a type that we have previously visited.
185 // Generate the appropriate upreference to handle this.
188 return "\\" + utostr(CurSize-Slot); // Here's the upreference
190 // Recursive case: derived types...
192 TypeStack.push_back(Ty); // Add us to the stack..
194 switch (Ty->getPrimitiveID()) {
195 case Type::FunctionTyID: {
196 const FunctionType *FTy = cast<FunctionType>(Ty);
197 Result = getTypeDescription(FTy->getReturnType(), TypeStack) + " (";
198 for (FunctionType::param_iterator I = FTy->param_begin(),
199 E = FTy->param_end(); I != E; ++I) {
200 if (I != FTy->param_begin())
202 Result += getTypeDescription(*I, TypeStack);
204 if (FTy->isVarArg()) {
205 if (FTy->getNumParams()) Result += ", ";
211 case Type::StructTyID: {
212 const StructType *STy = cast<StructType>(Ty);
214 for (StructType::element_iterator I = STy->element_begin(),
215 E = STy->element_end(); I != E; ++I) {
216 if (I != STy->element_begin())
218 Result += getTypeDescription(*I, TypeStack);
223 case Type::PointerTyID: {
224 const PointerType *PTy = cast<PointerType>(Ty);
225 Result = getTypeDescription(PTy->getElementType(), TypeStack) + " *";
228 case Type::ArrayTyID: {
229 const ArrayType *ATy = cast<ArrayType>(Ty);
230 unsigned NumElements = ATy->getNumElements();
232 Result += utostr(NumElements) + " x ";
233 Result += getTypeDescription(ATy->getElementType(), TypeStack) + "]";
238 assert(0 && "Unhandled type in getTypeDescription!");
241 TypeStack.pop_back(); // Remove self from stack...
248 static const std::string &getOrCreateDesc(std::map<const Type*,std::string>&Map,
250 std::map<const Type*, std::string>::iterator I = Map.find(Ty);
251 if (I != Map.end()) return I->second;
253 std::vector<const Type *> TypeStack;
254 return Map[Ty] = getTypeDescription(Ty, TypeStack);
258 const std::string &Type::getDescription() const {
260 return getOrCreateDesc(AbstractTypeDescriptions, this);
262 return getOrCreateDesc(ConcreteTypeDescriptions, this);
266 bool StructType::indexValid(const Value *V) const {
267 // Structure indexes require unsigned integer constants.
268 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(V))
269 return CU->getValue() < ContainedTys.size();
273 // getTypeAtIndex - Given an index value into the type, return the type of the
274 // element. For a structure type, this must be a constant value...
276 const Type *StructType::getTypeAtIndex(const Value *V) const {
277 assert(isa<Constant>(V) && "Structure index must be a constant!!");
278 unsigned Idx = cast<ConstantUInt>(V)->getValue();
279 assert(Idx < ContainedTys.size() && "Structure index out of range!");
280 assert(indexValid(V) && "Invalid structure index!"); // Duplicate check
281 return ContainedTys[Idx];
285 //===----------------------------------------------------------------------===//
287 //===----------------------------------------------------------------------===//
289 // These classes are used to implement specialized behavior for each different
292 struct SignedIntType : public Type {
293 SignedIntType(const std::string &Name, PrimitiveID id) : Type(Name, id) {}
295 // isSigned - Return whether a numeric type is signed.
296 virtual bool isSigned() const { return 1; }
298 // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
299 // virtual function invocation.
301 virtual bool isInteger() const { return 1; }
304 struct UnsignedIntType : public Type {
305 UnsignedIntType(const std::string &N, PrimitiveID id) : Type(N, id) {}
307 // isUnsigned - Return whether a numeric type is signed.
308 virtual bool isUnsigned() const { return 1; }
310 // isInteger - Equivalent to isSigned() || isUnsigned, but with only a single
311 // virtual function invocation.
313 virtual bool isInteger() const { return 1; }
316 struct OtherType : public Type {
317 OtherType(const std::string &N, PrimitiveID id) : Type(N, id) {}
320 static struct TypeType : public Type {
321 TypeType() : Type("type", TypeTyID) {}
322 } TheTypeTy; // Implement the type that is global.
325 //===----------------------------------------------------------------------===//
326 // Static 'Type' data
327 //===----------------------------------------------------------------------===//
329 static OtherType TheVoidTy ("void" , Type::VoidTyID);
330 static OtherType TheBoolTy ("bool" , Type::BoolTyID);
331 static SignedIntType TheSByteTy ("sbyte" , Type::SByteTyID);
332 static UnsignedIntType TheUByteTy ("ubyte" , Type::UByteTyID);
333 static SignedIntType TheShortTy ("short" , Type::ShortTyID);
334 static UnsignedIntType TheUShortTy("ushort", Type::UShortTyID);
335 static SignedIntType TheIntTy ("int" , Type::IntTyID);
336 static UnsignedIntType TheUIntTy ("uint" , Type::UIntTyID);
337 static SignedIntType TheLongTy ("long" , Type::LongTyID);
338 static UnsignedIntType TheULongTy ("ulong" , Type::ULongTyID);
339 static OtherType TheFloatTy ("float" , Type::FloatTyID);
340 static OtherType TheDoubleTy("double", Type::DoubleTyID);
341 static OtherType TheLabelTy ("label" , Type::LabelTyID);
343 Type *Type::VoidTy = &TheVoidTy;
344 Type *Type::BoolTy = &TheBoolTy;
345 Type *Type::SByteTy = &TheSByteTy;
346 Type *Type::UByteTy = &TheUByteTy;
347 Type *Type::ShortTy = &TheShortTy;
348 Type *Type::UShortTy = &TheUShortTy;
349 Type *Type::IntTy = &TheIntTy;
350 Type *Type::UIntTy = &TheUIntTy;
351 Type *Type::LongTy = &TheLongTy;
352 Type *Type::ULongTy = &TheULongTy;
353 Type *Type::FloatTy = &TheFloatTy;
354 Type *Type::DoubleTy = &TheDoubleTy;
355 Type *Type::TypeTy = &TheTypeTy;
356 Type *Type::LabelTy = &TheLabelTy;
359 //===----------------------------------------------------------------------===//
360 // Derived Type Constructors
361 //===----------------------------------------------------------------------===//
363 FunctionType::FunctionType(const Type *Result,
364 const std::vector<const Type*> &Params,
365 bool IsVarArgs) : DerivedType(FunctionTyID),
366 isVarArgs(IsVarArgs) {
367 bool isAbstract = Result->isAbstract();
368 ContainedTys.reserve(Params.size()+1);
369 ContainedTys.push_back(PATypeHandle(Result, this));
371 for (unsigned i = 0; i != Params.size(); ++i) {
372 ContainedTys.push_back(PATypeHandle(Params[i], this));
373 isAbstract |= Params[i]->isAbstract();
376 // Calculate whether or not this type is abstract
377 setAbstract(isAbstract);
380 StructType::StructType(const std::vector<const Type*> &Types)
381 : CompositeType(StructTyID) {
382 ContainedTys.reserve(Types.size());
383 bool isAbstract = false;
384 for (unsigned i = 0; i < Types.size(); ++i) {
385 assert(Types[i] != Type::VoidTy && "Void type in method prototype!!");
386 ContainedTys.push_back(PATypeHandle(Types[i], this));
387 isAbstract |= Types[i]->isAbstract();
390 // Calculate whether or not this type is abstract
391 setAbstract(isAbstract);
394 ArrayType::ArrayType(const Type *ElType, unsigned NumEl)
395 : SequentialType(ArrayTyID, ElType) {
398 // Calculate whether or not this type is abstract
399 setAbstract(ElType->isAbstract());
402 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
403 // Calculate whether or not this type is abstract
404 setAbstract(E->isAbstract());
407 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
409 #ifdef DEBUG_MERGE_TYPES
410 std::cerr << "Derived new type: " << *this << "\n";
414 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
415 // another (more concrete) type, we must eliminate all references to other
416 // types, to avoid some circular reference problems.
417 void DerivedType::dropAllTypeUses() {
418 if (!ContainedTys.empty()) {
419 while (ContainedTys.size() > 1)
420 ContainedTys.pop_back();
422 // The type must stay abstract. To do this, we insert a pointer to a type
423 // that will never get resolved, thus will always be abstract.
424 static Type *AlwaysOpaqueTy = OpaqueType::get();
425 static PATypeHolder Holder(AlwaysOpaqueTy);
426 ContainedTys[0] = AlwaysOpaqueTy;
430 // isTypeAbstract - This is a recursive function that walks a type hierarchy
431 // calculating whether or not a type is abstract. Worst case it will have to do
432 // a lot of traversing if you have some whacko opaque types, but in most cases,
433 // it will do some simple stuff when it hits non-abstract types that aren't
436 bool Type::isTypeAbstract() {
437 if (!isAbstract()) // Base case for the recursion
438 return false; // Primitive = leaf type
440 if (isa<OpaqueType>(this)) // Base case for the recursion
441 return true; // This whole type is abstract!
443 // We have to guard against recursion. To do this, we temporarily mark this
444 // type as concrete, so that if we get back to here recursively we will think
445 // it's not abstract, and thus not scan it again.
448 // Scan all of the sub-types. If any of them are abstract, than so is this
450 for (Type::subtype_iterator I = subtype_begin(), E = subtype_end();
452 if (const_cast<Type*>(I->get())->isTypeAbstract()) {
453 setAbstract(true); // Restore the abstract bit.
454 return true; // This type is abstract if subtype is abstract!
457 // Restore the abstract bit.
460 // Nothing looks abstract here...
465 //===----------------------------------------------------------------------===//
466 // Type Structural Equality Testing
467 //===----------------------------------------------------------------------===//
469 // TypesEqual - Two types are considered structurally equal if they have the
470 // same "shape": Every level and element of the types have identical primitive
471 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
472 // be pointer equals to be equivalent though. This uses an optimistic algorithm
473 // that assumes that two graphs are the same until proven otherwise.
475 static bool TypesEqual(const Type *Ty, const Type *Ty2,
476 std::map<const Type *, const Type *> &EqTypes) {
477 if (Ty == Ty2) return true;
478 if (Ty->getPrimitiveID() != Ty2->getPrimitiveID()) return false;
479 if (isa<OpaqueType>(Ty))
480 return false; // Two unequal opaque types are never equal
482 std::map<const Type*, const Type*>::iterator It = EqTypes.lower_bound(Ty);
483 if (It != EqTypes.end() && It->first == Ty)
484 return It->second == Ty2; // Looping back on a type, check for equality
486 // Otherwise, add the mapping to the table to make sure we don't get
487 // recursion on the types...
488 EqTypes.insert(It, std::make_pair(Ty, Ty2));
490 // Two really annoying special cases that breaks an otherwise nice simple
491 // algorithm is the fact that arraytypes have sizes that differentiates types,
492 // and that function types can be varargs or not. Consider this now.
494 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
495 return TypesEqual(PTy->getElementType(),
496 cast<PointerType>(Ty2)->getElementType(), EqTypes);
497 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
498 const StructType *STy2 = cast<StructType>(Ty2);
499 if (STy->getNumElements() != STy2->getNumElements()) return false;
500 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
501 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
504 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
505 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
506 return ATy->getNumElements() == ATy2->getNumElements() &&
507 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
508 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
509 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
510 if (FTy->isVarArg() != FTy2->isVarArg() ||
511 FTy->getNumParams() != FTy2->getNumParams() ||
512 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
514 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i)
515 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
519 assert(0 && "Unknown derived type!");
524 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
525 std::map<const Type *, const Type *> EqTypes;
526 return TypesEqual(Ty, Ty2, EqTypes);
529 // TypeHasCycleThrough - Return true there is a path from CurTy to TargetTy in
530 // the type graph. We know that Ty is an abstract type, so if we ever reach a
531 // non-abstract type, we know that we don't need to search the subgraph.
532 static bool TypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
533 std::set<const Type*> &VisitedTypes) {
534 if (TargetTy == CurTy) return true;
535 if (!CurTy->isAbstract()) return false;
537 std::set<const Type*>::iterator VTI = VisitedTypes.lower_bound(CurTy);
538 if (VTI != VisitedTypes.end() && *VTI == CurTy)
540 VisitedTypes.insert(VTI, CurTy);
542 for (Type::subtype_iterator I = CurTy->subtype_begin(),
543 E = CurTy->subtype_end(); I != E; ++I)
544 if (TypeHasCycleThrough(TargetTy, *I, VisitedTypes))
550 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
552 static bool TypeHasCycleThroughItself(const Type *Ty) {
553 assert(Ty->isAbstract() && "This code assumes that Ty was abstract!");
554 std::set<const Type*> VisitedTypes;
555 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
557 if (TypeHasCycleThrough(Ty, *I, VisitedTypes))
563 //===----------------------------------------------------------------------===//
564 // Derived Type Factory Functions
565 //===----------------------------------------------------------------------===//
567 // TypeMap - Make sure that only one instance of a particular type may be
568 // created on any given run of the compiler... note that this involves updating
569 // our map if an abstract type gets refined somehow.
572 template<class ValType, class TypeClass>
574 std::map<ValType, PATypeHolder> Map;
576 /// TypesByHash - Keep track of each type by its structure hash value.
578 std::multimap<unsigned, PATypeHolder> TypesByHash;
580 typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
581 ~TypeMap() { print("ON EXIT"); }
583 inline TypeClass *get(const ValType &V) {
584 iterator I = Map.find(V);
585 return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
588 inline void add(const ValType &V, TypeClass *Ty) {
589 Map.insert(std::make_pair(V, Ty));
591 // If this type has a cycle, remember it.
592 TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
596 void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
597 std::multimap<unsigned, PATypeHolder>::iterator I =
598 TypesByHash.lower_bound(Hash);
599 while (I->second != Ty) {
601 assert(I != TypesByHash.end() && I->first == Hash);
603 TypesByHash.erase(I);
606 /// finishRefinement - This method is called after we have updated an existing
607 /// type with its new components. We must now either merge the type away with
608 /// some other type or reinstall it in the map with it's new configuration.
609 /// The specified iterator tells us what the type USED to look like.
610 void finishRefinement(TypeClass *Ty, const DerivedType *OldType,
611 const Type *NewType) {
612 assert((Ty->isAbstract() || !OldType->isAbstract()) &&
613 "Refining a non-abstract type!");
614 #ifdef DEBUG_MERGE_TYPES
615 std::cerr << "refineAbstractTy(" << (void*)OldType << "[" << *OldType
616 << "], " << (void*)NewType << " [" << *NewType << "])\n";
619 // Make a temporary type holder for the type so that it doesn't disappear on
620 // us when we erase the entry from the map.
621 PATypeHolder TyHolder = Ty;
623 // The old record is now out-of-date, because one of the children has been
624 // updated. Remove the obsolete entry from the map.
625 Map.erase(ValType::get(Ty));
627 // Remember the structural hash for the type before we start hacking on it,
628 // in case we need it later. Also, check to see if the type HAD a cycle
629 // through it, if so, we know it will when we hack on it.
630 unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
632 // Find the type element we are refining... and change it now!
633 for (unsigned i = 0, e = Ty->ContainedTys.size(); i != e; ++i)
634 if (Ty->ContainedTys[i] == OldType) {
635 Ty->ContainedTys[i].removeUserFromConcrete();
636 Ty->ContainedTys[i] = NewType;
639 unsigned TypeHash = ValType::hashTypeStructure(Ty);
641 // If there are no cycles going through this node, we can do a simple,
642 // efficient lookup in the map, instead of an inefficient nasty linear
644 bool TypeHasCycle = Ty->isAbstract() && TypeHasCycleThroughItself(Ty);
646 iterator I = Map.find(ValType::get(Ty));
647 if (I != Map.end()) {
648 // We already have this type in the table. Get rid of the newly refined
650 assert(Ty->isAbstract() && "Replacing a non-abstract type?");
651 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
653 // Refined to a different type altogether?
654 RemoveFromTypesByHash(TypeHash, Ty);
655 Ty->refineAbstractTypeTo(NewTy);
662 // Now we check to see if there is an existing entry in the table which is
663 // structurally identical to the newly refined type. If so, this type
664 // gets refined to the pre-existing type.
666 std::multimap<unsigned, PATypeHolder>::iterator I,E, Entry;
667 tie(I, E) = TypesByHash.equal_range(TypeHash);
669 for (; I != E; ++I) {
670 ++NumTypeEqualsCalls;
671 if (I->second != Ty) {
672 if (TypesEqual(Ty, I->second)) {
675 assert(Ty->isAbstract() && "Replacing a non-abstract type?");
676 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
679 // Find the location of Ty in the TypesByHash structure.
680 while (I->second != Ty) {
682 assert(I != E && "Structure doesn't contain type??");
687 TypesByHash.erase(Entry);
688 Ty->refineAbstractTypeTo(NewTy);
692 // Remember the position of
698 // If we succeeded, we need to insert the type into the cycletypes table.
699 // There are several cases here, depending on whether the original type
700 // had the same hash code and was itself cyclic.
701 if (TypeHash != OldTypeHash) {
702 RemoveFromTypesByHash(OldTypeHash, Ty);
703 TypesByHash.insert(std::make_pair(TypeHash, Ty));
706 // If there is no existing type of the same structure, we reinsert an
707 // updated record into the map.
708 Map.insert(std::make_pair(ValType::get(Ty), Ty));
710 // If the type is currently thought to be abstract, rescan all of our
711 // subtypes to see if the type has just become concrete!
712 if (Ty->isAbstract()) {
713 Ty->setAbstract(Ty->isTypeAbstract());
715 // If the type just became concrete, notify all users!
716 if (!Ty->isAbstract())
717 Ty->notifyUsesThatTypeBecameConcrete();
721 void print(const char *Arg) const {
722 #ifdef DEBUG_MERGE_TYPES
723 std::cerr << "TypeMap<>::" << Arg << " table contents:\n";
725 for (typename std::map<ValType, PATypeHolder>::const_iterator I
726 = Map.begin(), E = Map.end(); I != E; ++I)
727 std::cerr << " " << (++i) << ". " << (void*)I->second.get() << " "
728 << *I->second.get() << "\n";
732 void dump() const { print("dump output"); }
737 //===----------------------------------------------------------------------===//
738 // Function Type Factory and Value Class...
741 // FunctionValType - Define a class to hold the key that goes into the TypeMap
744 class FunctionValType {
746 std::vector<const Type*> ArgTypes;
749 FunctionValType(const Type *ret, const std::vector<const Type*> &args,
750 bool IVA) : RetTy(ret), isVarArg(IVA) {
751 for (unsigned i = 0; i < args.size(); ++i)
752 ArgTypes.push_back(args[i]);
755 static FunctionValType get(const FunctionType *FT);
757 static unsigned hashTypeStructure(const FunctionType *FT) {
758 return FT->getNumParams()*2+FT->isVarArg();
761 // Subclass should override this... to update self as usual
762 void doRefinement(const DerivedType *OldType, const Type *NewType) {
763 if (RetTy == OldType) RetTy = NewType;
764 for (unsigned i = 0, e = ArgTypes.size(); i != e; ++i)
765 if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
768 inline bool operator<(const FunctionValType &MTV) const {
769 if (RetTy < MTV.RetTy) return true;
770 if (RetTy > MTV.RetTy) return false;
772 if (ArgTypes < MTV.ArgTypes) return true;
773 return ArgTypes == MTV.ArgTypes && isVarArg < MTV.isVarArg;
778 // Define the actual map itself now...
779 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
781 FunctionValType FunctionValType::get(const FunctionType *FT) {
782 // Build up a FunctionValType
783 std::vector<const Type *> ParamTypes;
784 ParamTypes.reserve(FT->getNumParams());
785 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
786 ParamTypes.push_back(FT->getParamType(i));
787 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
791 // FunctionType::get - The factory function for the FunctionType class...
792 FunctionType *FunctionType::get(const Type *ReturnType,
793 const std::vector<const Type*> &Params,
795 FunctionValType VT(ReturnType, Params, isVarArg);
796 FunctionType *MT = FunctionTypes.get(VT);
799 FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
801 #ifdef DEBUG_MERGE_TYPES
802 std::cerr << "Derived new type: " << MT << "\n";
807 //===----------------------------------------------------------------------===//
808 // Array Type Factory...
815 ArrayValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
817 static ArrayValType get(const ArrayType *AT) {
818 return ArrayValType(AT->getElementType(), AT->getNumElements());
821 static unsigned hashTypeStructure(const ArrayType *AT) {
822 return AT->getNumElements();
825 // Subclass should override this... to update self as usual
826 void doRefinement(const DerivedType *OldType, const Type *NewType) {
827 assert(ValTy == OldType);
831 inline bool operator<(const ArrayValType &MTV) const {
832 if (Size < MTV.Size) return true;
833 return Size == MTV.Size && ValTy < MTV.ValTy;
837 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
840 ArrayType *ArrayType::get(const Type *ElementType, unsigned NumElements) {
841 assert(ElementType && "Can't get array of null types!");
843 ArrayValType AVT(ElementType, NumElements);
844 ArrayType *AT = ArrayTypes.get(AVT);
845 if (AT) return AT; // Found a match, return it!
847 // Value not found. Derive a new type!
848 ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
850 #ifdef DEBUG_MERGE_TYPES
851 std::cerr << "Derived new type: " << *AT << "\n";
856 //===----------------------------------------------------------------------===//
857 // Struct Type Factory...
861 // StructValType - Define a class to hold the key that goes into the TypeMap
863 class StructValType {
864 std::vector<const Type*> ElTypes;
866 StructValType(const std::vector<const Type*> &args) : ElTypes(args) {}
868 static StructValType get(const StructType *ST) {
869 std::vector<const Type *> ElTypes;
870 ElTypes.reserve(ST->getNumElements());
871 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
872 ElTypes.push_back(ST->getElementType(i));
874 return StructValType(ElTypes);
877 static unsigned hashTypeStructure(const StructType *ST) {
878 return ST->getNumElements();
881 // Subclass should override this... to update self as usual
882 void doRefinement(const DerivedType *OldType, const Type *NewType) {
883 for (unsigned i = 0; i < ElTypes.size(); ++i)
884 if (ElTypes[i] == OldType) ElTypes[i] = NewType;
887 inline bool operator<(const StructValType &STV) const {
888 return ElTypes < STV.ElTypes;
893 static TypeMap<StructValType, StructType> StructTypes;
895 StructType *StructType::get(const std::vector<const Type*> &ETypes) {
896 StructValType STV(ETypes);
897 StructType *ST = StructTypes.get(STV);
900 // Value not found. Derive a new type!
901 StructTypes.add(STV, ST = new StructType(ETypes));
903 #ifdef DEBUG_MERGE_TYPES
904 std::cerr << "Derived new type: " << *ST << "\n";
911 //===----------------------------------------------------------------------===//
912 // Pointer Type Factory...
915 // PointerValType - Define a class to hold the key that goes into the TypeMap
918 class PointerValType {
921 PointerValType(const Type *val) : ValTy(val) {}
923 static PointerValType get(const PointerType *PT) {
924 return PointerValType(PT->getElementType());
927 static unsigned hashTypeStructure(const PointerType *PT) {
931 // Subclass should override this... to update self as usual
932 void doRefinement(const DerivedType *OldType, const Type *NewType) {
933 assert(ValTy == OldType);
937 bool operator<(const PointerValType &MTV) const {
938 return ValTy < MTV.ValTy;
943 static TypeMap<PointerValType, PointerType> PointerTypes;
945 PointerType *PointerType::get(const Type *ValueType) {
946 assert(ValueType && "Can't get a pointer to <null> type!");
947 PointerValType PVT(ValueType);
949 PointerType *PT = PointerTypes.get(PVT);
952 // Value not found. Derive a new type!
953 PointerTypes.add(PVT, PT = new PointerType(ValueType));
955 #ifdef DEBUG_MERGE_TYPES
956 std::cerr << "Derived new type: " << *PT << "\n";
962 //===----------------------------------------------------------------------===//
963 // Derived Type Refinement Functions
964 //===----------------------------------------------------------------------===//
966 // removeAbstractTypeUser - Notify an abstract type that a user of the class
967 // no longer has a handle to the type. This function is called primarily by
968 // the PATypeHandle class. When there are no users of the abstract type, it
969 // is annihilated, because there is no way to get a reference to it ever again.
971 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
972 // Search from back to front because we will notify users from back to
973 // front. Also, it is likely that there will be a stack like behavior to
974 // users that register and unregister users.
977 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
978 assert(i != 0 && "AbstractTypeUser not in user list!");
980 --i; // Convert to be in range 0 <= i < size()
981 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
983 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
985 #ifdef DEBUG_MERGE_TYPES
986 std::cerr << " remAbstractTypeUser[" << (void*)this << ", "
987 << *this << "][" << i << "] User = " << U << "\n";
990 if (AbstractTypeUsers.empty() && RefCount == 0 && isAbstract()) {
991 #ifdef DEBUG_MERGE_TYPES
992 std::cerr << "DELETEing unused abstract type: <" << *this
993 << ">[" << (void*)this << "]" << "\n";
995 delete this; // No users of this abstract type!
1000 // refineAbstractTypeTo - This function is used to when it is discovered that
1001 // the 'this' abstract type is actually equivalent to the NewType specified.
1002 // This causes all users of 'this' to switch to reference the more concrete type
1003 // NewType and for 'this' to be deleted.
1005 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1006 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1007 assert(this != NewType && "Can't refine to myself!");
1008 assert(ForwardType == 0 && "This type has already been refined!");
1010 // The descriptions may be out of date. Conservatively clear them all!
1011 AbstractTypeDescriptions.clear();
1013 #ifdef DEBUG_MERGE_TYPES
1014 std::cerr << "REFINING abstract type [" << (void*)this << " "
1015 << *this << "] to [" << (void*)NewType << " "
1016 << *NewType << "]!\n";
1019 // Make sure to put the type to be refined to into a holder so that if IT gets
1020 // refined, that we will not continue using a dead reference...
1022 PATypeHolder NewTy(NewType);
1024 // Any PATypeHolders referring to this type will now automatically forward to
1025 // the type we are resolved to.
1026 ForwardType = NewType;
1027 if (NewType->isAbstract())
1028 cast<DerivedType>(NewType)->addRef();
1030 // Add a self use of the current type so that we don't delete ourself until
1031 // after the function exits.
1033 PATypeHolder CurrentTy(this);
1035 // To make the situation simpler, we ask the subclass to remove this type from
1036 // the type map, and to replace any type uses with uses of non-abstract types.
1037 // This dramatically limits the amount of recursive type trouble we can find
1041 // Iterate over all of the uses of this type, invoking callback. Each user
1042 // should remove itself from our use list automatically. We have to check to
1043 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1044 // will not cause users to drop off of the use list. If we resolve to ourself
1047 while (!AbstractTypeUsers.empty() && NewTy != this) {
1048 AbstractTypeUser *User = AbstractTypeUsers.back();
1050 unsigned OldSize = AbstractTypeUsers.size();
1051 #ifdef DEBUG_MERGE_TYPES
1052 std::cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
1053 << "] of abstract type [" << (void*)this << " "
1054 << *this << "] to [" << (void*)NewTy.get() << " "
1055 << *NewTy << "]!\n";
1057 User->refineAbstractType(this, NewTy);
1059 assert(AbstractTypeUsers.size() != OldSize &&
1060 "AbsTyUser did not remove self from user list!");
1063 // If we were successful removing all users from the type, 'this' will be
1064 // deleted when the last PATypeHolder is destroyed or updated from this type.
1065 // This may occur on exit of this function, as the CurrentTy object is
1069 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1070 // the current type has transitioned from being abstract to being concrete.
1072 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1073 #ifdef DEBUG_MERGE_TYPES
1074 std::cerr << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1077 unsigned OldSize = AbstractTypeUsers.size();
1078 while (!AbstractTypeUsers.empty()) {
1079 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1080 ATU->typeBecameConcrete(this);
1082 assert(AbstractTypeUsers.size() < OldSize-- &&
1083 "AbstractTypeUser did not remove itself from the use list!");
1090 // refineAbstractType - Called when a contained type is found to be more
1091 // concrete - this could potentially change us from an abstract type to a
1094 void FunctionType::refineAbstractType(const DerivedType *OldType,
1095 const Type *NewType) {
1096 FunctionTypes.finishRefinement(this, OldType, NewType);
1099 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1100 refineAbstractType(AbsTy, AbsTy);
1104 // refineAbstractType - Called when a contained type is found to be more
1105 // concrete - this could potentially change us from an abstract type to a
1108 void ArrayType::refineAbstractType(const DerivedType *OldType,
1109 const Type *NewType) {
1110 ArrayTypes.finishRefinement(this, OldType, NewType);
1113 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1114 refineAbstractType(AbsTy, AbsTy);
1118 // refineAbstractType - Called when a contained type is found to be more
1119 // concrete - this could potentially change us from an abstract type to a
1122 void StructType::refineAbstractType(const DerivedType *OldType,
1123 const Type *NewType) {
1124 StructTypes.finishRefinement(this, OldType, NewType);
1127 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1128 refineAbstractType(AbsTy, AbsTy);
1131 // refineAbstractType - Called when a contained type is found to be more
1132 // concrete - this could potentially change us from an abstract type to a
1135 void PointerType::refineAbstractType(const DerivedType *OldType,
1136 const Type *NewType) {
1137 PointerTypes.finishRefinement(this, OldType, NewType);
1140 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1141 refineAbstractType(AbsTy, AbsTy);