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/AbstractTypeUser.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/SymbolTable.h"
17 #include "llvm/Constants.h"
18 #include "llvm/ADT/DepthFirstIterator.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/SCCIterator.h"
21 #include "llvm/ADT/STLExtras.h"
26 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
27 // created and later destroyed, all in an effort to make sure that there is only
28 // a single canonical version of a type.
30 //#define DEBUG_MERGE_TYPES 1
32 AbstractTypeUser::~AbstractTypeUser() {}
34 //===----------------------------------------------------------------------===//
35 // Type Class Implementation
36 //===----------------------------------------------------------------------===//
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, TypeID id )
46 : RefCount(0), ForwardType(0) {
48 ConcreteTypeDescriptions[this] = name;
53 const Type *Type::getPrimitiveType(TypeID IDNumber) {
55 case VoidTyID : return VoidTy;
56 case BoolTyID : return BoolTy;
57 case UByteTyID : return UByteTy;
58 case SByteTyID : return SByteTy;
59 case UShortTyID: return UShortTy;
60 case ShortTyID : return ShortTy;
61 case UIntTyID : return UIntTy;
62 case IntTyID : return IntTy;
63 case ULongTyID : return ULongTy;
64 case LongTyID : return LongTy;
65 case FloatTyID : return FloatTy;
66 case DoubleTyID: return DoubleTy;
67 case LabelTyID : return LabelTy;
73 // isLosslesslyConvertibleTo - Return true if this type can be converted to
74 // 'Ty' without any reinterpretation of bits. For example, uint to int.
76 bool Type::isLosslesslyConvertibleTo(const Type *Ty) const {
77 if (this == Ty) return true;
78 if ((!isPrimitiveType() && !isa<PointerType>(this)) ||
79 (!isa<PointerType>(Ty) && !Ty->isPrimitiveType())) return false;
81 if (getTypeID() == Ty->getTypeID())
82 return true; // Handles identity cast, and cast of differing pointer types
84 // Now we know that they are two differing primitive or pointer types
85 switch (getTypeID()) {
86 case Type::UByteTyID: return Ty == Type::SByteTy;
87 case Type::SByteTyID: return Ty == Type::UByteTy;
88 case Type::UShortTyID: return Ty == Type::ShortTy;
89 case Type::ShortTyID: return Ty == Type::UShortTy;
90 case Type::UIntTyID: return Ty == Type::IntTy;
91 case Type::IntTyID: return Ty == Type::UIntTy;
92 case Type::ULongTyID: return Ty == Type::LongTy;
93 case Type::LongTyID: return Ty == Type::ULongTy;
94 case Type::PointerTyID: return isa<PointerType>(Ty);
96 return false; // Other types have no identity values
100 /// getUnsignedVersion - If this is an integer type, return the unsigned
101 /// variant of this type. For example int -> uint.
102 const Type *Type::getUnsignedVersion() const {
103 switch (getTypeID()) {
105 assert(isInteger()&&"Type::getUnsignedVersion is only valid for integers!");
106 case Type::UByteTyID:
107 case Type::SByteTyID: return Type::UByteTy;
108 case Type::UShortTyID:
109 case Type::ShortTyID: return Type::UShortTy;
111 case Type::IntTyID: return Type::UIntTy;
112 case Type::ULongTyID:
113 case Type::LongTyID: return Type::ULongTy;
117 /// getSignedVersion - If this is an integer type, return the signed variant
118 /// of this type. For example uint -> int.
119 const Type *Type::getSignedVersion() const {
120 switch (getTypeID()) {
122 assert(isInteger() && "Type::getSignedVersion is only valid for integers!");
123 case Type::UByteTyID:
124 case Type::SByteTyID: return Type::SByteTy;
125 case Type::UShortTyID:
126 case Type::ShortTyID: return Type::ShortTy;
128 case Type::IntTyID: return Type::IntTy;
129 case Type::ULongTyID:
130 case Type::LongTyID: return Type::LongTy;
135 // getPrimitiveSize - Return the basic size of this type if it is a primitive
136 // type. These are fixed by LLVM and are not target dependent. This will
137 // return zero if the type does not have a size or is not a primitive type.
139 unsigned Type::getPrimitiveSize() const {
140 switch (getTypeID()) {
141 #define HANDLE_PRIM_TYPE(TY,SIZE) case TY##TyID: return SIZE;
142 #include "llvm/Type.def"
147 /// isSizedDerivedType - Derived types like structures and arrays are sized
148 /// iff all of the members of the type are sized as well. Since asking for
149 /// their size is relatively uncommon, move this operation out of line.
150 bool Type::isSizedDerivedType() const {
151 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
152 return ATy->getElementType()->isSized();
154 if (!isa<StructType>(this)) return false;
156 // Okay, our struct is sized if all of the elements are...
157 for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I)
158 if (!(*I)->isSized()) return false;
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";
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->getTypeID()) {
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) + "]";
265 case Type::PackedTyID: {
266 const PackedType *PTy = cast<PackedType>(Ty);
267 unsigned NumElements = PTy->getNumElements();
269 Result += utostr(NumElements) + " x ";
270 Result += getTypeDescription(PTy->getElementType(), TypeStack) + ">";
275 assert(0 && "Unhandled type in getTypeDescription!");
278 TypeStack.pop_back(); // Remove self from stack...
285 static const std::string &getOrCreateDesc(std::map<const Type*,std::string>&Map,
287 std::map<const Type*, std::string>::iterator I = Map.find(Ty);
288 if (I != Map.end()) return I->second;
290 std::vector<const Type *> TypeStack;
291 return Map[Ty] = getTypeDescription(Ty, TypeStack);
295 const std::string &Type::getDescription() const {
297 return getOrCreateDesc(AbstractTypeDescriptions, this);
299 return getOrCreateDesc(ConcreteTypeDescriptions, this);
303 bool StructType::indexValid(const Value *V) const {
304 // Structure indexes require unsigned integer constants.
305 if (V->getType() == Type::UIntTy)
306 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(V))
307 return CU->getValue() < ContainedTys.size();
311 // getTypeAtIndex - Given an index value into the type, return the type of the
312 // element. For a structure type, this must be a constant value...
314 const Type *StructType::getTypeAtIndex(const Value *V) const {
315 assert(indexValid(V) && "Invalid structure index!");
316 unsigned Idx = (unsigned)cast<ConstantUInt>(V)->getValue();
317 return ContainedTys[Idx];
321 //===----------------------------------------------------------------------===//
322 // Static 'Type' data
323 //===----------------------------------------------------------------------===//
326 struct PrimType : public Type {
327 PrimType(const char *S, TypeID ID) : Type(S, ID) {}
331 static PrimType TheVoidTy ("void" , Type::VoidTyID);
332 static PrimType TheBoolTy ("bool" , Type::BoolTyID);
333 static PrimType TheSByteTy ("sbyte" , Type::SByteTyID);
334 static PrimType TheUByteTy ("ubyte" , Type::UByteTyID);
335 static PrimType TheShortTy ("short" , Type::ShortTyID);
336 static PrimType TheUShortTy("ushort", Type::UShortTyID);
337 static PrimType TheIntTy ("int" , Type::IntTyID);
338 static PrimType TheUIntTy ("uint" , Type::UIntTyID);
339 static PrimType TheLongTy ("long" , Type::LongTyID);
340 static PrimType TheULongTy ("ulong" , Type::ULongTyID);
341 static PrimType TheFloatTy ("float" , Type::FloatTyID);
342 static PrimType TheDoubleTy("double", Type::DoubleTyID);
343 static PrimType TheLabelTy ("label" , Type::LabelTyID);
345 Type *Type::VoidTy = &TheVoidTy;
346 Type *Type::BoolTy = &TheBoolTy;
347 Type *Type::SByteTy = &TheSByteTy;
348 Type *Type::UByteTy = &TheUByteTy;
349 Type *Type::ShortTy = &TheShortTy;
350 Type *Type::UShortTy = &TheUShortTy;
351 Type *Type::IntTy = &TheIntTy;
352 Type *Type::UIntTy = &TheUIntTy;
353 Type *Type::LongTy = &TheLongTy;
354 Type *Type::ULongTy = &TheULongTy;
355 Type *Type::FloatTy = &TheFloatTy;
356 Type *Type::DoubleTy = &TheDoubleTy;
357 Type *Type::LabelTy = &TheLabelTy;
360 //===----------------------------------------------------------------------===//
361 // Derived Type Constructors
362 //===----------------------------------------------------------------------===//
364 FunctionType::FunctionType(const Type *Result,
365 const std::vector<const Type*> &Params,
366 bool IsVarArgs) : DerivedType(FunctionTyID),
367 isVarArgs(IsVarArgs) {
368 assert((Result->isFirstClassType() || Result == Type::VoidTy ||
369 isa<OpaqueType>(Result)) &&
370 "LLVM functions cannot return aggregates");
371 bool isAbstract = Result->isAbstract();
372 ContainedTys.reserve(Params.size()+1);
373 ContainedTys.push_back(PATypeHandle(Result, this));
375 for (unsigned i = 0; i != Params.size(); ++i) {
376 assert((Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])) &&
377 "Function arguments must be value types!");
379 ContainedTys.push_back(PATypeHandle(Params[i], this));
380 isAbstract |= Params[i]->isAbstract();
383 // Calculate whether or not this type is abstract
384 setAbstract(isAbstract);
387 StructType::StructType(const std::vector<const Type*> &Types)
388 : CompositeType(StructTyID) {
389 ContainedTys.reserve(Types.size());
390 bool isAbstract = false;
391 for (unsigned i = 0; i < Types.size(); ++i) {
392 assert(Types[i] != Type::VoidTy && "Void type for structure field!!");
393 ContainedTys.push_back(PATypeHandle(Types[i], this));
394 isAbstract |= Types[i]->isAbstract();
397 // Calculate whether or not this type is abstract
398 setAbstract(isAbstract);
401 ArrayType::ArrayType(const Type *ElType, unsigned NumEl)
402 : SequentialType(ArrayTyID, ElType) {
405 // Calculate whether or not this type is abstract
406 setAbstract(ElType->isAbstract());
409 PackedType::PackedType(const Type *ElType, unsigned NumEl)
410 : SequentialType(PackedTyID, ElType) {
413 assert(NumEl > 0 && "NumEl of a PackedType must be greater than 0");
414 assert((ElType->isIntegral() || ElType->isFloatingPoint()) &&
415 "Elements of a PackedType must be a primitive type");
419 PointerType::PointerType(const Type *E) : SequentialType(PointerTyID, E) {
420 // Calculate whether or not this type is abstract
421 setAbstract(E->isAbstract());
424 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
426 #ifdef DEBUG_MERGE_TYPES
427 std::cerr << "Derived new type: " << *this << "\n";
431 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
432 // another (more concrete) type, we must eliminate all references to other
433 // types, to avoid some circular reference problems.
434 void DerivedType::dropAllTypeUses() {
435 if (!ContainedTys.empty()) {
436 while (ContainedTys.size() > 1)
437 ContainedTys.pop_back();
439 // The type must stay abstract. To do this, we insert a pointer to a type
440 // that will never get resolved, thus will always be abstract.
441 static Type *AlwaysOpaqueTy = OpaqueType::get();
442 static PATypeHolder Holder(AlwaysOpaqueTy);
443 ContainedTys[0] = AlwaysOpaqueTy;
449 /// TypePromotionGraph and graph traits - this is designed to allow us to do
450 /// efficient SCC processing of type graphs. This is the exact same as
451 /// GraphTraits<Type*>, except that we pretend that concrete types have no
452 /// children to avoid processing them.
453 struct TypePromotionGraph {
455 TypePromotionGraph(Type *T) : Ty(T) {}
459 template <> struct GraphTraits<TypePromotionGraph> {
460 typedef Type NodeType;
461 typedef Type::subtype_iterator ChildIteratorType;
463 static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
464 static inline ChildIteratorType child_begin(NodeType *N) {
466 return N->subtype_begin();
467 else // No need to process children of concrete types.
468 return N->subtype_end();
470 static inline ChildIteratorType child_end(NodeType *N) {
471 return N->subtype_end();
477 // PromoteAbstractToConcrete - This is a recursive function that walks a type
478 // graph calculating whether or not a type is abstract.
480 // This method returns true if the type is found to still be abstract.
482 void Type::PromoteAbstractToConcrete() {
483 if (!isAbstract()) return;
485 scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
486 scc_iterator<TypePromotionGraph> SE = scc_end (TypePromotionGraph(this));
488 for (; SI != SE; ++SI) {
489 std::vector<Type*> &SCC = *SI;
491 // Concrete types are leaves in the tree. Since an SCC will either be all
492 // abstract or all concrete, we only need to check one type.
493 if (SCC[0]->isAbstract()) {
494 if (isa<OpaqueType>(SCC[0]))
495 return; // Not going to be concrete, sorry.
497 // If all of the children of all of the types in this SCC are concrete,
498 // then this SCC is now concrete as well. If not, neither this SCC, nor
499 // any parent SCCs will be concrete, so we might as well just exit.
500 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
501 for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
502 E = SCC[i]->subtype_end(); CI != E; ++CI)
503 if ((*CI)->isAbstract())
504 return; // Not going to be concrete, sorry.
506 // Okay, we just discovered this whole SCC is now concrete, mark it as
508 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
509 assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
511 SCC[i]->setAbstract(false);
512 // The type just became concrete, notify all users!
513 cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
520 //===----------------------------------------------------------------------===//
521 // Type Structural Equality Testing
522 //===----------------------------------------------------------------------===//
524 // TypesEqual - Two types are considered structurally equal if they have the
525 // same "shape": Every level and element of the types have identical primitive
526 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
527 // be pointer equals to be equivalent though. This uses an optimistic algorithm
528 // that assumes that two graphs are the same until proven otherwise.
530 static bool TypesEqual(const Type *Ty, const Type *Ty2,
531 std::map<const Type *, const Type *> &EqTypes) {
532 if (Ty == Ty2) return true;
533 if (Ty->getTypeID() != Ty2->getTypeID()) return false;
534 if (isa<OpaqueType>(Ty))
535 return false; // Two unequal opaque types are never equal
537 std::map<const Type*, const Type*>::iterator It = EqTypes.lower_bound(Ty);
538 if (It != EqTypes.end() && It->first == Ty)
539 return It->second == Ty2; // Looping back on a type, check for equality
541 // Otherwise, add the mapping to the table to make sure we don't get
542 // recursion on the types...
543 EqTypes.insert(It, std::make_pair(Ty, Ty2));
545 // Two really annoying special cases that breaks an otherwise nice simple
546 // algorithm is the fact that arraytypes have sizes that differentiates types,
547 // and that function types can be varargs or not. Consider this now.
549 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
550 return TypesEqual(PTy->getElementType(),
551 cast<PointerType>(Ty2)->getElementType(), EqTypes);
552 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
553 const StructType *STy2 = cast<StructType>(Ty2);
554 if (STy->getNumElements() != STy2->getNumElements()) return false;
555 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
556 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
559 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
560 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
561 return ATy->getNumElements() == ATy2->getNumElements() &&
562 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
563 } else if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
564 const PackedType *PTy2 = cast<PackedType>(Ty2);
565 return PTy->getNumElements() == PTy2->getNumElements() &&
566 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
567 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
568 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
569 if (FTy->isVarArg() != FTy2->isVarArg() ||
570 FTy->getNumParams() != FTy2->getNumParams() ||
571 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
573 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i)
574 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
578 assert(0 && "Unknown derived type!");
583 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
584 std::map<const Type *, const Type *> EqTypes;
585 return TypesEqual(Ty, Ty2, EqTypes);
588 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
589 // TargetTy in the type graph. We know that Ty is an abstract type, so if we
590 // ever reach a non-abstract type, we know that we don't need to search the
592 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
593 std::set<const Type*> &VisitedTypes) {
594 if (TargetTy == CurTy) return true;
595 if (!CurTy->isAbstract()) return false;
597 if (!VisitedTypes.insert(CurTy).second)
598 return false; // Already been here.
600 for (Type::subtype_iterator I = CurTy->subtype_begin(),
601 E = CurTy->subtype_end(); I != E; ++I)
602 if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
607 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
608 std::set<const Type*> &VisitedTypes) {
609 if (TargetTy == CurTy) return true;
611 if (!VisitedTypes.insert(CurTy).second)
612 return false; // Already been here.
614 for (Type::subtype_iterator I = CurTy->subtype_begin(),
615 E = CurTy->subtype_end(); I != E; ++I)
616 if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
621 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
623 static bool TypeHasCycleThroughItself(const Type *Ty) {
624 std::set<const Type*> VisitedTypes;
626 if (Ty->isAbstract()) { // Optimized case for abstract types.
627 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
629 if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
632 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
634 if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
643 //===----------------------------------------------------------------------===//
644 // Derived Type Factory Functions
645 //===----------------------------------------------------------------------===//
647 // TypeMap - Make sure that only one instance of a particular type may be
648 // created on any given run of the compiler... note that this involves updating
649 // our map if an abstract type gets refined somehow.
652 template<class ValType, class TypeClass>
654 std::map<ValType, PATypeHolder> Map;
656 /// TypesByHash - Keep track of each type by its structure hash value.
658 std::multimap<unsigned, PATypeHolder> TypesByHash;
660 typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
661 ~TypeMap() { print("ON EXIT"); }
663 inline TypeClass *get(const ValType &V) {
664 iterator I = Map.find(V);
665 return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
668 inline void add(const ValType &V, TypeClass *Ty) {
669 Map.insert(std::make_pair(V, Ty));
671 // If this type has a cycle, remember it.
672 TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
676 void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
677 std::multimap<unsigned, PATypeHolder>::iterator I =
678 TypesByHash.lower_bound(Hash);
679 while (I->second != Ty) {
681 assert(I != TypesByHash.end() && I->first == Hash);
683 TypesByHash.erase(I);
686 /// finishRefinement - This method is called after we have updated an existing
687 /// type with its new components. We must now either merge the type away with
688 /// some other type or reinstall it in the map with it's new configuration.
689 /// The specified iterator tells us what the type USED to look like.
690 void finishRefinement(TypeClass *Ty, const DerivedType *OldType,
691 const Type *NewType) {
692 assert((Ty->isAbstract() || !OldType->isAbstract()) &&
693 "Refining a non-abstract type!");
694 #ifdef DEBUG_MERGE_TYPES
695 std::cerr << "refineAbstractTy(" << (void*)OldType << "[" << *OldType
696 << "], " << (void*)NewType << " [" << *NewType << "])\n";
699 // Make a temporary type holder for the type so that it doesn't disappear on
700 // us when we erase the entry from the map.
701 PATypeHolder TyHolder = Ty;
703 // The old record is now out-of-date, because one of the children has been
704 // updated. Remove the obsolete entry from the map.
705 Map.erase(ValType::get(Ty));
707 // Remember the structural hash for the type before we start hacking on it,
708 // in case we need it later. Also, check to see if the type HAD a cycle
709 // through it, if so, we know it will when we hack on it.
710 unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
712 // Find the type element we are refining... and change it now!
713 for (unsigned i = 0, e = Ty->ContainedTys.size(); i != e; ++i)
714 if (Ty->ContainedTys[i] == OldType) {
715 Ty->ContainedTys[i].removeUserFromConcrete();
716 Ty->ContainedTys[i] = NewType;
719 unsigned TypeHash = ValType::hashTypeStructure(Ty);
721 // If there are no cycles going through this node, we can do a simple,
722 // efficient lookup in the map, instead of an inefficient nasty linear
724 bool TypeHasCycle = Ty->isAbstract() && TypeHasCycleThroughItself(Ty);
726 iterator I = Map.find(ValType::get(Ty));
727 if (I != Map.end()) {
728 // We already have this type in the table. Get rid of the newly refined
730 assert(Ty->isAbstract() && "Replacing a non-abstract type?");
731 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
733 // Refined to a different type altogether?
734 RemoveFromTypesByHash(TypeHash, Ty);
735 Ty->refineAbstractTypeTo(NewTy);
740 // Now we check to see if there is an existing entry in the table which is
741 // structurally identical to the newly refined type. If so, this type
742 // gets refined to the pre-existing type.
744 std::multimap<unsigned, PATypeHolder>::iterator I,E, Entry;
745 tie(I, E) = TypesByHash.equal_range(TypeHash);
747 for (; I != E; ++I) {
748 if (I->second != Ty) {
749 if (TypesEqual(Ty, I->second)) {
750 assert(Ty->isAbstract() && "Replacing a non-abstract type?");
751 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
754 // Find the location of Ty in the TypesByHash structure.
755 while (I->second != Ty) {
757 assert(I != E && "Structure doesn't contain type??");
762 TypesByHash.erase(Entry);
763 Ty->refineAbstractTypeTo(NewTy);
767 // Remember the position of
773 // If we succeeded, we need to insert the type into the cycletypes table.
774 // There are several cases here, depending on whether the original type
775 // had the same hash code and was itself cyclic.
776 if (TypeHash != OldTypeHash) {
777 RemoveFromTypesByHash(OldTypeHash, Ty);
778 TypesByHash.insert(std::make_pair(TypeHash, Ty));
781 // If there is no existing type of the same structure, we reinsert an
782 // updated record into the map.
783 Map.insert(std::make_pair(ValType::get(Ty), Ty));
785 // If the type is currently thought to be abstract, rescan all of our
786 // subtypes to see if the type has just become concrete!
787 if (Ty->isAbstract())
788 Ty->PromoteAbstractToConcrete();
791 void print(const char *Arg) const {
792 #ifdef DEBUG_MERGE_TYPES
793 std::cerr << "TypeMap<>::" << Arg << " table contents:\n";
795 for (typename std::map<ValType, PATypeHolder>::const_iterator I
796 = Map.begin(), E = Map.end(); I != E; ++I)
797 std::cerr << " " << (++i) << ". " << (void*)I->second.get() << " "
798 << *I->second.get() << "\n";
802 void dump() const { print("dump output"); }
807 //===----------------------------------------------------------------------===//
808 // Function Type Factory and Value Class...
811 // FunctionValType - Define a class to hold the key that goes into the TypeMap
814 class FunctionValType {
816 std::vector<const Type*> ArgTypes;
819 FunctionValType(const Type *ret, const std::vector<const Type*> &args,
820 bool IVA) : RetTy(ret), isVarArg(IVA) {
821 for (unsigned i = 0; i < args.size(); ++i)
822 ArgTypes.push_back(args[i]);
825 static FunctionValType get(const FunctionType *FT);
827 static unsigned hashTypeStructure(const FunctionType *FT) {
828 return FT->getNumParams()*2+FT->isVarArg();
831 // Subclass should override this... to update self as usual
832 void doRefinement(const DerivedType *OldType, const Type *NewType) {
833 if (RetTy == OldType) RetTy = NewType;
834 for (unsigned i = 0, e = ArgTypes.size(); i != e; ++i)
835 if (ArgTypes[i] == OldType) ArgTypes[i] = NewType;
838 inline bool operator<(const FunctionValType &MTV) const {
839 if (RetTy < MTV.RetTy) return true;
840 if (RetTy > MTV.RetTy) return false;
842 if (ArgTypes < MTV.ArgTypes) return true;
843 return ArgTypes == MTV.ArgTypes && isVarArg < MTV.isVarArg;
848 // Define the actual map itself now...
849 static TypeMap<FunctionValType, FunctionType> FunctionTypes;
851 FunctionValType FunctionValType::get(const FunctionType *FT) {
852 // Build up a FunctionValType
853 std::vector<const Type *> ParamTypes;
854 ParamTypes.reserve(FT->getNumParams());
855 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
856 ParamTypes.push_back(FT->getParamType(i));
857 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
861 // FunctionType::get - The factory function for the FunctionType class...
862 FunctionType *FunctionType::get(const Type *ReturnType,
863 const std::vector<const Type*> &Params,
865 FunctionValType VT(ReturnType, Params, isVarArg);
866 FunctionType *MT = FunctionTypes.get(VT);
869 FunctionTypes.add(VT, MT = new FunctionType(ReturnType, Params, isVarArg));
871 #ifdef DEBUG_MERGE_TYPES
872 std::cerr << "Derived new type: " << MT << "\n";
877 //===----------------------------------------------------------------------===//
878 // Array Type Factory...
885 ArrayValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
887 static ArrayValType get(const ArrayType *AT) {
888 return ArrayValType(AT->getElementType(), AT->getNumElements());
891 static unsigned hashTypeStructure(const ArrayType *AT) {
892 return AT->getNumElements();
895 // Subclass should override this... to update self as usual
896 void doRefinement(const DerivedType *OldType, const Type *NewType) {
897 assert(ValTy == OldType);
901 inline bool operator<(const ArrayValType &MTV) const {
902 if (Size < MTV.Size) return true;
903 return Size == MTV.Size && ValTy < MTV.ValTy;
907 static TypeMap<ArrayValType, ArrayType> ArrayTypes;
910 ArrayType *ArrayType::get(const Type *ElementType, unsigned NumElements) {
911 assert(ElementType && "Can't get array of null types!");
913 ArrayValType AVT(ElementType, NumElements);
914 ArrayType *AT = ArrayTypes.get(AVT);
915 if (AT) return AT; // Found a match, return it!
917 // Value not found. Derive a new type!
918 ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
920 #ifdef DEBUG_MERGE_TYPES
921 std::cerr << "Derived new type: " << *AT << "\n";
927 //===----------------------------------------------------------------------===//
928 // Packed Type Factory...
931 class PackedValType {
935 PackedValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
937 static PackedValType get(const PackedType *PT) {
938 return PackedValType(PT->getElementType(), PT->getNumElements());
941 static unsigned hashTypeStructure(const PackedType *PT) {
942 return PT->getNumElements();
945 // Subclass should override this... to update self as usual
946 void doRefinement(const DerivedType *OldType, const Type *NewType) {
947 assert(ValTy == OldType);
951 inline bool operator<(const PackedValType &MTV) const {
952 if (Size < MTV.Size) return true;
953 return Size == MTV.Size && ValTy < MTV.ValTy;
957 static TypeMap<PackedValType, PackedType> PackedTypes;
960 PackedType *PackedType::get(const Type *ElementType, unsigned NumElements) {
961 assert(ElementType && "Can't get packed of null types!");
963 PackedValType PVT(ElementType, NumElements);
964 PackedType *PT = PackedTypes.get(PVT);
965 if (PT) return PT; // Found a match, return it!
967 // Value not found. Derive a new type!
968 PackedTypes.add(PVT, PT = new PackedType(ElementType, NumElements));
970 #ifdef DEBUG_MERGE_TYPES
971 std::cerr << "Derived new type: " << *PT << "\n";
976 //===----------------------------------------------------------------------===//
977 // Struct Type Factory...
981 // StructValType - Define a class to hold the key that goes into the TypeMap
983 class StructValType {
984 std::vector<const Type*> ElTypes;
986 StructValType(const std::vector<const Type*> &args) : ElTypes(args) {}
988 static StructValType get(const StructType *ST) {
989 std::vector<const Type *> ElTypes;
990 ElTypes.reserve(ST->getNumElements());
991 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
992 ElTypes.push_back(ST->getElementType(i));
994 return StructValType(ElTypes);
997 static unsigned hashTypeStructure(const StructType *ST) {
998 return ST->getNumElements();
1001 // Subclass should override this... to update self as usual
1002 void doRefinement(const DerivedType *OldType, const Type *NewType) {
1003 for (unsigned i = 0; i < ElTypes.size(); ++i)
1004 if (ElTypes[i] == OldType) ElTypes[i] = NewType;
1007 inline bool operator<(const StructValType &STV) const {
1008 return ElTypes < STV.ElTypes;
1013 static TypeMap<StructValType, StructType> StructTypes;
1015 StructType *StructType::get(const std::vector<const Type*> &ETypes) {
1016 StructValType STV(ETypes);
1017 StructType *ST = StructTypes.get(STV);
1020 // Value not found. Derive a new type!
1021 StructTypes.add(STV, ST = new StructType(ETypes));
1023 #ifdef DEBUG_MERGE_TYPES
1024 std::cerr << "Derived new type: " << *ST << "\n";
1031 //===----------------------------------------------------------------------===//
1032 // Pointer Type Factory...
1035 // PointerValType - Define a class to hold the key that goes into the TypeMap
1038 class PointerValType {
1041 PointerValType(const Type *val) : ValTy(val) {}
1043 static PointerValType get(const PointerType *PT) {
1044 return PointerValType(PT->getElementType());
1047 static unsigned hashTypeStructure(const PointerType *PT) {
1051 // Subclass should override this... to update self as usual
1052 void doRefinement(const DerivedType *OldType, const Type *NewType) {
1053 assert(ValTy == OldType);
1057 bool operator<(const PointerValType &MTV) const {
1058 return ValTy < MTV.ValTy;
1063 static TypeMap<PointerValType, PointerType> PointerTypes;
1065 PointerType *PointerType::get(const Type *ValueType) {
1066 assert(ValueType && "Can't get a pointer to <null> type!");
1067 PointerValType PVT(ValueType);
1069 PointerType *PT = PointerTypes.get(PVT);
1072 // Value not found. Derive a new type!
1073 PointerTypes.add(PVT, PT = new PointerType(ValueType));
1075 #ifdef DEBUG_MERGE_TYPES
1076 std::cerr << "Derived new type: " << *PT << "\n";
1082 //===----------------------------------------------------------------------===//
1083 // Derived Type Refinement Functions
1084 //===----------------------------------------------------------------------===//
1086 // removeAbstractTypeUser - Notify an abstract type that a user of the class
1087 // no longer has a handle to the type. This function is called primarily by
1088 // the PATypeHandle class. When there are no users of the abstract type, it
1089 // is annihilated, because there is no way to get a reference to it ever again.
1091 void DerivedType::removeAbstractTypeUser(AbstractTypeUser *U) const {
1092 // Search from back to front because we will notify users from back to
1093 // front. Also, it is likely that there will be a stack like behavior to
1094 // users that register and unregister users.
1097 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1098 assert(i != 0 && "AbstractTypeUser not in user list!");
1100 --i; // Convert to be in range 0 <= i < size()
1101 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
1103 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1105 #ifdef DEBUG_MERGE_TYPES
1106 std::cerr << " remAbstractTypeUser[" << (void*)this << ", "
1107 << *this << "][" << i << "] User = " << U << "\n";
1110 if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1111 #ifdef DEBUG_MERGE_TYPES
1112 std::cerr << "DELETEing unused abstract type: <" << *this
1113 << ">[" << (void*)this << "]" << "\n";
1115 delete this; // No users of this abstract type!
1120 // refineAbstractTypeTo - This function is used to when it is discovered that
1121 // the 'this' abstract type is actually equivalent to the NewType specified.
1122 // This causes all users of 'this' to switch to reference the more concrete type
1123 // NewType and for 'this' to be deleted.
1125 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1126 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1127 assert(this != NewType && "Can't refine to myself!");
1128 assert(ForwardType == 0 && "This type has already been refined!");
1130 // The descriptions may be out of date. Conservatively clear them all!
1131 AbstractTypeDescriptions.clear();
1133 #ifdef DEBUG_MERGE_TYPES
1134 std::cerr << "REFINING abstract type [" << (void*)this << " "
1135 << *this << "] to [" << (void*)NewType << " "
1136 << *NewType << "]!\n";
1139 // Make sure to put the type to be refined to into a holder so that if IT gets
1140 // refined, that we will not continue using a dead reference...
1142 PATypeHolder NewTy(NewType);
1144 // Any PATypeHolders referring to this type will now automatically forward to
1145 // the type we are resolved to.
1146 ForwardType = NewType;
1147 if (NewType->isAbstract())
1148 cast<DerivedType>(NewType)->addRef();
1150 // Add a self use of the current type so that we don't delete ourself until
1151 // after the function exits.
1153 PATypeHolder CurrentTy(this);
1155 // To make the situation simpler, we ask the subclass to remove this type from
1156 // the type map, and to replace any type uses with uses of non-abstract types.
1157 // This dramatically limits the amount of recursive type trouble we can find
1161 // Iterate over all of the uses of this type, invoking callback. Each user
1162 // should remove itself from our use list automatically. We have to check to
1163 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1164 // will not cause users to drop off of the use list. If we resolve to ourself
1167 while (!AbstractTypeUsers.empty() && NewTy != this) {
1168 AbstractTypeUser *User = AbstractTypeUsers.back();
1170 unsigned OldSize = AbstractTypeUsers.size();
1171 #ifdef DEBUG_MERGE_TYPES
1172 std::cerr << " REFINING user " << OldSize-1 << "[" << (void*)User
1173 << "] of abstract type [" << (void*)this << " "
1174 << *this << "] to [" << (void*)NewTy.get() << " "
1175 << *NewTy << "]!\n";
1177 User->refineAbstractType(this, NewTy);
1179 assert(AbstractTypeUsers.size() != OldSize &&
1180 "AbsTyUser did not remove self from user list!");
1183 // If we were successful removing all users from the type, 'this' will be
1184 // deleted when the last PATypeHolder is destroyed or updated from this type.
1185 // This may occur on exit of this function, as the CurrentTy object is
1189 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1190 // the current type has transitioned from being abstract to being concrete.
1192 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1193 #ifdef DEBUG_MERGE_TYPES
1194 std::cerr << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1197 unsigned OldSize = AbstractTypeUsers.size();
1198 while (!AbstractTypeUsers.empty()) {
1199 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1200 ATU->typeBecameConcrete(this);
1202 assert(AbstractTypeUsers.size() < OldSize-- &&
1203 "AbstractTypeUser did not remove itself from the use list!");
1210 // refineAbstractType - Called when a contained type is found to be more
1211 // concrete - this could potentially change us from an abstract type to a
1214 void FunctionType::refineAbstractType(const DerivedType *OldType,
1215 const Type *NewType) {
1216 FunctionTypes.finishRefinement(this, OldType, NewType);
1219 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1220 refineAbstractType(AbsTy, AbsTy);
1224 // refineAbstractType - Called when a contained type is found to be more
1225 // concrete - this could potentially change us from an abstract type to a
1228 void ArrayType::refineAbstractType(const DerivedType *OldType,
1229 const Type *NewType) {
1230 ArrayTypes.finishRefinement(this, OldType, NewType);
1233 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1234 refineAbstractType(AbsTy, AbsTy);
1237 // refineAbstractType - Called when a contained type is found to be more
1238 // concrete - this could potentially change us from an abstract type to a
1241 void PackedType::refineAbstractType(const DerivedType *OldType,
1242 const Type *NewType) {
1243 PackedTypes.finishRefinement(this, OldType, NewType);
1246 void PackedType::typeBecameConcrete(const DerivedType *AbsTy) {
1247 refineAbstractType(AbsTy, AbsTy);
1250 // refineAbstractType - Called when a contained type is found to be more
1251 // concrete - this could potentially change us from an abstract type to a
1254 void StructType::refineAbstractType(const DerivedType *OldType,
1255 const Type *NewType) {
1256 StructTypes.finishRefinement(this, OldType, NewType);
1259 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1260 refineAbstractType(AbsTy, AbsTy);
1263 // refineAbstractType - Called when a contained type is found to be more
1264 // concrete - this could potentially change us from an abstract type to a
1267 void PointerType::refineAbstractType(const DerivedType *OldType,
1268 const Type *NewType) {
1269 PointerTypes.finishRefinement(this, OldType, NewType);
1272 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1273 refineAbstractType(AbsTy, AbsTy);
1276 bool SequentialType::indexValid(const Value *V) const {
1277 const Type *Ty = V->getType();
1278 switch (Ty->getTypeID()) {
1280 case Type::UIntTyID:
1281 case Type::LongTyID:
1282 case Type::ULongTyID:
1290 std::ostream &operator<<(std::ostream &OS, const Type *T) {
1292 OS << "<null> value!\n";
1298 std::ostream &operator<<(std::ostream &OS, const Type &T) {