1 //===-- Type.cpp - Implement the Type class -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/Constants.h"
16 #include "llvm/ADT/DepthFirstIterator.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/SCCIterator.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/Support/MathExtras.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/ManagedStatic.h"
23 #include "llvm/Support/Debug.h"
28 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
29 // created and later destroyed, all in an effort to make sure that there is only
30 // a single canonical version of a type.
32 // #define DEBUG_MERGE_TYPES 1
34 AbstractTypeUser::~AbstractTypeUser() {}
37 //===----------------------------------------------------------------------===//
38 // Type Class Implementation
39 //===----------------------------------------------------------------------===//
41 // Concrete/Abstract TypeDescriptions - We lazily calculate type descriptions
42 // for types as they are needed. Because resolution of types must invalidate
43 // all of the abstract type descriptions, we keep them in a seperate map to make
45 static ManagedStatic<std::map<const Type*,
46 std::string> > ConcreteTypeDescriptions;
47 static ManagedStatic<std::map<const Type*,
48 std::string> > AbstractTypeDescriptions;
50 /// Because of the way Type subclasses are allocated, this function is necessary
51 /// to use the correct kind of "delete" operator to deallocate the Type object.
52 /// Some type objects (FunctionTy, StructTy) allocate additional space after
53 /// the space for their derived type to hold the contained types array of
54 /// PATypeHandles. Using this allocation scheme means all the PATypeHandles are
55 /// allocated with the type object, decreasing allocations and eliminating the
56 /// need for a std::vector to be used in the Type class itself.
57 /// @brief Type destruction function
58 void Type::destroy() const {
60 // Structures and Functions allocate their contained types past the end of
61 // the type object itself. These need to be destroyed differently than the
63 if (isa<FunctionType>(this) || isa<StructType>(this)) {
64 // First, make sure we destruct any PATypeHandles allocated by these
65 // subclasses. They must be manually destructed.
66 for (unsigned i = 0; i < NumContainedTys; ++i)
67 ContainedTys[i].PATypeHandle::~PATypeHandle();
69 // Now call the destructor for the subclass directly because we're going
70 // to delete this as an array of char.
71 if (isa<FunctionType>(this))
72 static_cast<const FunctionType*>(this)->FunctionType::~FunctionType();
74 static_cast<const StructType*>(this)->StructType::~StructType();
76 // Finally, remove the memory as an array deallocation of the chars it was
78 operator delete(const_cast<Type *>(this));
83 // For all the other type subclasses, there is either no contained types or
84 // just one (all Sequentials). For Sequentials, the PATypeHandle is not
85 // allocated past the type object, its included directly in the SequentialType
86 // class. This means we can safely just do "normal" delete of this object and
87 // all the destructors that need to run will be run.
91 const Type *Type::getPrimitiveType(TypeID IDNumber) {
93 case VoidTyID : return VoidTy;
94 case FloatTyID : return FloatTy;
95 case DoubleTyID : return DoubleTy;
96 case X86_FP80TyID : return X86_FP80Ty;
97 case FP128TyID : return FP128Ty;
98 case PPC_FP128TyID : return PPC_FP128Ty;
99 case LabelTyID : return LabelTy;
105 const Type *Type::getVAArgsPromotedType() const {
106 if (ID == IntegerTyID && getSubclassData() < 32)
107 return Type::Int32Ty;
108 else if (ID == FloatTyID)
109 return Type::DoubleTy;
114 /// isIntOrIntVector - Return true if this is an integer type or a vector of
117 bool Type::isIntOrIntVector() const {
120 if (ID != Type::VectorTyID) return false;
122 return cast<VectorType>(this)->getElementType()->isInteger();
125 /// isFPOrFPVector - Return true if this is a FP type or a vector of FP types.
127 bool Type::isFPOrFPVector() const {
128 if (ID == Type::FloatTyID || ID == Type::DoubleTyID ||
129 ID == Type::FP128TyID || ID == Type::X86_FP80TyID ||
130 ID == Type::PPC_FP128TyID)
132 if (ID != Type::VectorTyID) return false;
134 return cast<VectorType>(this)->getElementType()->isFloatingPoint();
137 // canLosslesllyBitCastTo - Return true if this type can be converted to
138 // 'Ty' without any reinterpretation of bits. For example, uint to int.
140 bool Type::canLosslesslyBitCastTo(const Type *Ty) const {
141 // Identity cast means no change so return true
145 // They are not convertible unless they are at least first class types
146 if (!this->isFirstClassType() || !Ty->isFirstClassType())
149 // Vector -> Vector conversions are always lossless if the two vector types
150 // have the same size, otherwise not.
151 if (const VectorType *thisPTy = dyn_cast<VectorType>(this))
152 if (const VectorType *thatPTy = dyn_cast<VectorType>(Ty))
153 return thisPTy->getBitWidth() == thatPTy->getBitWidth();
155 // At this point we have only various mismatches of the first class types
156 // remaining and ptr->ptr. Just select the lossless conversions. Everything
157 // else is not lossless.
158 if (isa<PointerType>(this))
159 return isa<PointerType>(Ty);
160 return false; // Other types have no identity values
163 unsigned Type::getPrimitiveSizeInBits() const {
164 switch (getTypeID()) {
165 case Type::FloatTyID: return 32;
166 case Type::DoubleTyID: return 64;
167 case Type::X86_FP80TyID: return 80;
168 case Type::FP128TyID: return 128;
169 case Type::PPC_FP128TyID: return 128;
170 case Type::IntegerTyID: return cast<IntegerType>(this)->getBitWidth();
171 case Type::VectorTyID: return cast<VectorType>(this)->getBitWidth();
176 /// isSizedDerivedType - Derived types like structures and arrays are sized
177 /// iff all of the members of the type are sized as well. Since asking for
178 /// their size is relatively uncommon, move this operation out of line.
179 bool Type::isSizedDerivedType() const {
180 if (isa<IntegerType>(this))
183 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
184 return ATy->getElementType()->isSized();
186 if (const VectorType *PTy = dyn_cast<VectorType>(this))
187 return PTy->getElementType()->isSized();
189 if (!isa<StructType>(this))
192 // Okay, our struct is sized if all of the elements are...
193 for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I)
194 if (!(*I)->isSized())
200 /// getForwardedTypeInternal - This method is used to implement the union-find
201 /// algorithm for when a type is being forwarded to another type.
202 const Type *Type::getForwardedTypeInternal() const {
203 assert(ForwardType && "This type is not being forwarded to another type!");
205 // Check to see if the forwarded type has been forwarded on. If so, collapse
206 // the forwarding links.
207 const Type *RealForwardedType = ForwardType->getForwardedType();
208 if (!RealForwardedType)
209 return ForwardType; // No it's not forwarded again
211 // Yes, it is forwarded again. First thing, add the reference to the new
213 if (RealForwardedType->isAbstract())
214 cast<DerivedType>(RealForwardedType)->addRef();
216 // Now drop the old reference. This could cause ForwardType to get deleted.
217 cast<DerivedType>(ForwardType)->dropRef();
219 // Return the updated type.
220 ForwardType = RealForwardedType;
224 void Type::refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
227 void Type::typeBecameConcrete(const DerivedType *AbsTy) {
232 // getTypeDescription - This is a recursive function that walks a type hierarchy
233 // calculating the description for a type.
235 static std::string getTypeDescription(const Type *Ty,
236 std::vector<const Type *> &TypeStack) {
237 if (isa<OpaqueType>(Ty)) { // Base case for the recursion
238 std::map<const Type*, std::string>::iterator I =
239 AbstractTypeDescriptions->find(Ty);
240 if (I != AbstractTypeDescriptions->end())
242 std::string Desc = "opaque";
243 AbstractTypeDescriptions->insert(std::make_pair(Ty, Desc));
247 if (!Ty->isAbstract()) { // Base case for the recursion
248 std::map<const Type*, std::string>::iterator I =
249 ConcreteTypeDescriptions->find(Ty);
250 if (I != ConcreteTypeDescriptions->end())
253 if (Ty->isPrimitiveType()) {
254 switch (Ty->getTypeID()) {
255 default: assert(0 && "Unknown prim type!");
256 case Type::VoidTyID: return (*ConcreteTypeDescriptions)[Ty] = "void";
257 case Type::FloatTyID: return (*ConcreteTypeDescriptions)[Ty] = "float";
258 case Type::DoubleTyID: return (*ConcreteTypeDescriptions)[Ty] = "double";
259 case Type::X86_FP80TyID:
260 return (*ConcreteTypeDescriptions)[Ty] = "x86_fp80";
261 case Type::FP128TyID: return (*ConcreteTypeDescriptions)[Ty] = "fp128";
262 case Type::PPC_FP128TyID:
263 return (*ConcreteTypeDescriptions)[Ty] = "ppc_fp128";
264 case Type::LabelTyID: return (*ConcreteTypeDescriptions)[Ty] = "label";
269 // Check to see if the Type is already on the stack...
270 unsigned Slot = 0, CurSize = TypeStack.size();
271 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
273 // This is another base case for the recursion. In this case, we know
274 // that we have looped back to a type that we have previously visited.
275 // Generate the appropriate upreference to handle this.
278 return "\\" + utostr(CurSize-Slot); // Here's the upreference
280 // Recursive case: derived types...
282 TypeStack.push_back(Ty); // Add us to the stack..
284 switch (Ty->getTypeID()) {
285 case Type::IntegerTyID: {
286 const IntegerType *ITy = cast<IntegerType>(Ty);
287 Result = "i" + utostr(ITy->getBitWidth());
290 case Type::FunctionTyID: {
291 const FunctionType *FTy = cast<FunctionType>(Ty);
294 Result += getTypeDescription(FTy->getReturnType(), TypeStack) + " (";
295 for (FunctionType::param_iterator I = FTy->param_begin(),
296 E = FTy->param_end(); I != E; ++I) {
297 if (I != FTy->param_begin())
299 Result += getTypeDescription(*I, TypeStack);
301 if (FTy->isVarArg()) {
302 if (FTy->getNumParams()) Result += ", ";
308 case Type::StructTyID: {
309 const StructType *STy = cast<StructType>(Ty);
314 for (StructType::element_iterator I = STy->element_begin(),
315 E = STy->element_end(); I != E; ++I) {
316 if (I != STy->element_begin())
318 Result += getTypeDescription(*I, TypeStack);
325 case Type::PointerTyID: {
326 const PointerType *PTy = cast<PointerType>(Ty);
327 Result = getTypeDescription(PTy->getElementType(), TypeStack);
328 if (unsigned AddressSpace = PTy->getAddressSpace())
329 Result += " addrspace(" + utostr(AddressSpace) + ")";
333 case Type::ArrayTyID: {
334 const ArrayType *ATy = cast<ArrayType>(Ty);
335 unsigned NumElements = ATy->getNumElements();
337 Result += utostr(NumElements) + " x ";
338 Result += getTypeDescription(ATy->getElementType(), TypeStack) + "]";
341 case Type::VectorTyID: {
342 const VectorType *PTy = cast<VectorType>(Ty);
343 unsigned NumElements = PTy->getNumElements();
345 Result += utostr(NumElements) + " x ";
346 Result += getTypeDescription(PTy->getElementType(), TypeStack) + ">";
351 assert(0 && "Unhandled type in getTypeDescription!");
354 TypeStack.pop_back(); // Remove self from stack...
361 static const std::string &getOrCreateDesc(std::map<const Type*,std::string>&Map,
363 std::map<const Type*, std::string>::iterator I = Map.find(Ty);
364 if (I != Map.end()) return I->second;
366 std::vector<const Type *> TypeStack;
367 std::string Result = getTypeDescription(Ty, TypeStack);
368 return Map[Ty] = Result;
372 const std::string &Type::getDescription() const {
374 return getOrCreateDesc(*AbstractTypeDescriptions, this);
376 return getOrCreateDesc(*ConcreteTypeDescriptions, this);
380 bool StructType::indexValid(const Value *V) const {
381 // Structure indexes require 32-bit integer constants.
382 if (V->getType() == Type::Int32Ty)
383 if (const ConstantInt *CU = dyn_cast<ConstantInt>(V))
384 return indexValid(CU->getZExtValue());
388 bool StructType::indexValid(unsigned V) const {
389 return V < NumContainedTys;
392 // getTypeAtIndex - Given an index value into the type, return the type of the
393 // element. For a structure type, this must be a constant value...
395 const Type *StructType::getTypeAtIndex(const Value *V) const {
396 unsigned Idx = (unsigned)cast<ConstantInt>(V)->getZExtValue();
397 return getTypeAtIndex(Idx);
400 const Type *StructType::getTypeAtIndex(unsigned Idx) const {
401 assert(indexValid(Idx) && "Invalid structure index!");
402 return ContainedTys[Idx];
405 //===----------------------------------------------------------------------===//
406 // Primitive 'Type' data
407 //===----------------------------------------------------------------------===//
409 const Type *Type::VoidTy = new Type(Type::VoidTyID);
410 const Type *Type::FloatTy = new Type(Type::FloatTyID);
411 const Type *Type::DoubleTy = new Type(Type::DoubleTyID);
412 const Type *Type::X86_FP80Ty = new Type(Type::X86_FP80TyID);
413 const Type *Type::FP128Ty = new Type(Type::FP128TyID);
414 const Type *Type::PPC_FP128Ty = new Type(Type::PPC_FP128TyID);
415 const Type *Type::LabelTy = new Type(Type::LabelTyID);
418 struct BuiltinIntegerType : public IntegerType {
419 explicit BuiltinIntegerType(unsigned W) : IntegerType(W) {}
422 const IntegerType *Type::Int1Ty = new BuiltinIntegerType(1);
423 const IntegerType *Type::Int8Ty = new BuiltinIntegerType(8);
424 const IntegerType *Type::Int16Ty = new BuiltinIntegerType(16);
425 const IntegerType *Type::Int32Ty = new BuiltinIntegerType(32);
426 const IntegerType *Type::Int64Ty = new BuiltinIntegerType(64);
429 //===----------------------------------------------------------------------===//
430 // Derived Type Constructors
431 //===----------------------------------------------------------------------===//
433 /// isValidReturnType - Return true if the specified type is valid as a return
435 bool FunctionType::isValidReturnType(const Type *RetTy) {
436 if (RetTy->isFirstClassType())
438 if (RetTy == Type::VoidTy || isa<OpaqueType>(RetTy))
441 // If this is a multiple return case, verify that each return is a first class
442 // value and that there is at least one value.
443 const StructType *SRetTy = dyn_cast<StructType>(RetTy);
444 if (SRetTy == 0 || SRetTy->getNumElements() == 0)
447 for (unsigned i = 0, e = SRetTy->getNumElements(); i != e; ++i)
448 if (!SRetTy->getElementType(i)->isFirstClassType())
453 FunctionType::FunctionType(const Type *Result,
454 const std::vector<const Type*> &Params,
456 : DerivedType(FunctionTyID), isVarArgs(IsVarArgs) {
457 ContainedTys = reinterpret_cast<PATypeHandle*>(this+1);
458 NumContainedTys = Params.size() + 1; // + 1 for result type
459 assert(isValidReturnType(Result) && "invalid return type for function");
462 bool isAbstract = Result->isAbstract();
463 new (&ContainedTys[0]) PATypeHandle(Result, this);
465 for (unsigned i = 0; i != Params.size(); ++i) {
466 assert((Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])) &&
467 "Function arguments must be value types!");
468 new (&ContainedTys[i+1]) PATypeHandle(Params[i],this);
469 isAbstract |= Params[i]->isAbstract();
472 // Calculate whether or not this type is abstract
473 setAbstract(isAbstract);
476 StructType::StructType(const std::vector<const Type*> &Types, bool isPacked)
477 : CompositeType(StructTyID) {
478 ContainedTys = reinterpret_cast<PATypeHandle*>(this + 1);
479 NumContainedTys = Types.size();
480 setSubclassData(isPacked);
481 bool isAbstract = false;
482 for (unsigned i = 0; i < Types.size(); ++i) {
483 assert(Types[i] != Type::VoidTy && "Void type for structure field!!");
484 new (&ContainedTys[i]) PATypeHandle(Types[i], this);
485 isAbstract |= Types[i]->isAbstract();
488 // Calculate whether or not this type is abstract
489 setAbstract(isAbstract);
492 ArrayType::ArrayType(const Type *ElType, uint64_t NumEl)
493 : SequentialType(ArrayTyID, ElType) {
496 // Calculate whether or not this type is abstract
497 setAbstract(ElType->isAbstract());
500 VectorType::VectorType(const Type *ElType, unsigned NumEl)
501 : SequentialType(VectorTyID, ElType) {
503 setAbstract(ElType->isAbstract());
504 assert(NumEl > 0 && "NumEl of a VectorType must be greater than 0");
505 assert((ElType->isInteger() || ElType->isFloatingPoint() ||
506 isa<OpaqueType>(ElType)) &&
507 "Elements of a VectorType must be a primitive type");
512 PointerType::PointerType(const Type *E, unsigned AddrSpace)
513 : SequentialType(PointerTyID, E) {
514 AddressSpace = AddrSpace;
515 // Calculate whether or not this type is abstract
516 setAbstract(E->isAbstract());
519 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
521 #ifdef DEBUG_MERGE_TYPES
522 DOUT << "Derived new type: " << *this << "\n";
526 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
527 // another (more concrete) type, we must eliminate all references to other
528 // types, to avoid some circular reference problems.
529 void DerivedType::dropAllTypeUses() {
530 if (NumContainedTys != 0) {
531 // The type must stay abstract. To do this, we insert a pointer to a type
532 // that will never get resolved, thus will always be abstract.
533 static Type *AlwaysOpaqueTy = OpaqueType::get();
534 static PATypeHolder Holder(AlwaysOpaqueTy);
535 ContainedTys[0] = AlwaysOpaqueTy;
537 // Change the rest of the types to be Int32Ty's. It doesn't matter what we
538 // pick so long as it doesn't point back to this type. We choose something
539 // concrete to avoid overhead for adding to AbstracTypeUser lists and stuff.
540 for (unsigned i = 1, e = NumContainedTys; i != e; ++i)
541 ContainedTys[i] = Type::Int32Ty;
548 /// TypePromotionGraph and graph traits - this is designed to allow us to do
549 /// efficient SCC processing of type graphs. This is the exact same as
550 /// GraphTraits<Type*>, except that we pretend that concrete types have no
551 /// children to avoid processing them.
552 struct TypePromotionGraph {
554 TypePromotionGraph(Type *T) : Ty(T) {}
560 template <> struct GraphTraits<TypePromotionGraph> {
561 typedef Type NodeType;
562 typedef Type::subtype_iterator ChildIteratorType;
564 static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
565 static inline ChildIteratorType child_begin(NodeType *N) {
567 return N->subtype_begin();
568 else // No need to process children of concrete types.
569 return N->subtype_end();
571 static inline ChildIteratorType child_end(NodeType *N) {
572 return N->subtype_end();
578 // PromoteAbstractToConcrete - This is a recursive function that walks a type
579 // graph calculating whether or not a type is abstract.
581 void Type::PromoteAbstractToConcrete() {
582 if (!isAbstract()) return;
584 scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
585 scc_iterator<TypePromotionGraph> SE = scc_end (TypePromotionGraph(this));
587 for (; SI != SE; ++SI) {
588 std::vector<Type*> &SCC = *SI;
590 // Concrete types are leaves in the tree. Since an SCC will either be all
591 // abstract or all concrete, we only need to check one type.
592 if (SCC[0]->isAbstract()) {
593 if (isa<OpaqueType>(SCC[0]))
594 return; // Not going to be concrete, sorry.
596 // If all of the children of all of the types in this SCC are concrete,
597 // then this SCC is now concrete as well. If not, neither this SCC, nor
598 // any parent SCCs will be concrete, so we might as well just exit.
599 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
600 for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
601 E = SCC[i]->subtype_end(); CI != E; ++CI)
602 if ((*CI)->isAbstract())
603 // If the child type is in our SCC, it doesn't make the entire SCC
604 // abstract unless there is a non-SCC abstract type.
605 if (std::find(SCC.begin(), SCC.end(), *CI) == SCC.end())
606 return; // Not going to be concrete, sorry.
608 // Okay, we just discovered this whole SCC is now concrete, mark it as
610 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
611 assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
613 SCC[i]->setAbstract(false);
616 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
617 assert(!SCC[i]->isAbstract() && "Concrete type became abstract?");
618 // The type just became concrete, notify all users!
619 cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
626 //===----------------------------------------------------------------------===//
627 // Type Structural Equality Testing
628 //===----------------------------------------------------------------------===//
630 // TypesEqual - Two types are considered structurally equal if they have the
631 // same "shape": Every level and element of the types have identical primitive
632 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
633 // be pointer equals to be equivalent though. This uses an optimistic algorithm
634 // that assumes that two graphs are the same until proven otherwise.
636 static bool TypesEqual(const Type *Ty, const Type *Ty2,
637 std::map<const Type *, const Type *> &EqTypes) {
638 if (Ty == Ty2) return true;
639 if (Ty->getTypeID() != Ty2->getTypeID()) return false;
640 if (isa<OpaqueType>(Ty))
641 return false; // Two unequal opaque types are never equal
643 std::map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
644 if (It != EqTypes.end())
645 return It->second == Ty2; // Looping back on a type, check for equality
647 // Otherwise, add the mapping to the table to make sure we don't get
648 // recursion on the types...
649 EqTypes.insert(It, std::make_pair(Ty, Ty2));
651 // Two really annoying special cases that breaks an otherwise nice simple
652 // algorithm is the fact that arraytypes have sizes that differentiates types,
653 // and that function types can be varargs or not. Consider this now.
655 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
656 const IntegerType *ITy2 = cast<IntegerType>(Ty2);
657 return ITy->getBitWidth() == ITy2->getBitWidth();
658 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
659 const PointerType *PTy2 = cast<PointerType>(Ty2);
660 return PTy->getAddressSpace() == PTy2->getAddressSpace() &&
661 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
662 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
663 const StructType *STy2 = cast<StructType>(Ty2);
664 if (STy->getNumElements() != STy2->getNumElements()) return false;
665 if (STy->isPacked() != STy2->isPacked()) return false;
666 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
667 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
670 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
671 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
672 return ATy->getNumElements() == ATy2->getNumElements() &&
673 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
674 } else if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
675 const VectorType *PTy2 = cast<VectorType>(Ty2);
676 return PTy->getNumElements() == PTy2->getNumElements() &&
677 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
678 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
679 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
680 if (FTy->isVarArg() != FTy2->isVarArg() ||
681 FTy->getNumParams() != FTy2->getNumParams() ||
682 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
684 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i) {
685 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
690 assert(0 && "Unknown derived type!");
695 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
696 std::map<const Type *, const Type *> EqTypes;
697 return TypesEqual(Ty, Ty2, EqTypes);
700 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
701 // TargetTy in the type graph. We know that Ty is an abstract type, so if we
702 // ever reach a non-abstract type, we know that we don't need to search the
704 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
705 SmallPtrSet<const Type*, 128> &VisitedTypes) {
706 if (TargetTy == CurTy) return true;
707 if (!CurTy->isAbstract()) return false;
709 if (!VisitedTypes.insert(CurTy))
710 return false; // Already been here.
712 for (Type::subtype_iterator I = CurTy->subtype_begin(),
713 E = CurTy->subtype_end(); I != E; ++I)
714 if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
719 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
720 SmallPtrSet<const Type*, 128> &VisitedTypes) {
721 if (TargetTy == CurTy) return true;
723 if (!VisitedTypes.insert(CurTy))
724 return false; // Already been here.
726 for (Type::subtype_iterator I = CurTy->subtype_begin(),
727 E = CurTy->subtype_end(); I != E; ++I)
728 if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
733 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
735 static bool TypeHasCycleThroughItself(const Type *Ty) {
736 SmallPtrSet<const Type*, 128> VisitedTypes;
738 if (Ty->isAbstract()) { // Optimized case for abstract types.
739 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
741 if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
744 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
746 if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
752 /// getSubElementHash - Generate a hash value for all of the SubType's of this
753 /// type. The hash value is guaranteed to be zero if any of the subtypes are
754 /// an opaque type. Otherwise we try to mix them in as well as possible, but do
755 /// not look at the subtype's subtype's.
756 static unsigned getSubElementHash(const Type *Ty) {
757 unsigned HashVal = 0;
758 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
761 const Type *SubTy = I->get();
762 HashVal += SubTy->getTypeID();
763 switch (SubTy->getTypeID()) {
765 case Type::OpaqueTyID: return 0; // Opaque -> hash = 0 no matter what.
766 case Type::IntegerTyID:
767 HashVal ^= (cast<IntegerType>(SubTy)->getBitWidth() << 3);
769 case Type::FunctionTyID:
770 HashVal ^= cast<FunctionType>(SubTy)->getNumParams()*2 +
771 cast<FunctionType>(SubTy)->isVarArg();
773 case Type::ArrayTyID:
774 HashVal ^= cast<ArrayType>(SubTy)->getNumElements();
776 case Type::VectorTyID:
777 HashVal ^= cast<VectorType>(SubTy)->getNumElements();
779 case Type::StructTyID:
780 HashVal ^= cast<StructType>(SubTy)->getNumElements();
782 case Type::PointerTyID:
783 HashVal ^= cast<PointerType>(SubTy)->getAddressSpace();
787 return HashVal ? HashVal : 1; // Do not return zero unless opaque subty.
790 //===----------------------------------------------------------------------===//
791 // Derived Type Factory Functions
792 //===----------------------------------------------------------------------===//
797 /// TypesByHash - Keep track of types by their structure hash value. Note
798 /// that we only keep track of types that have cycles through themselves in
801 std::multimap<unsigned, PATypeHolder> TypesByHash;
804 void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
805 std::multimap<unsigned, PATypeHolder>::iterator I =
806 TypesByHash.lower_bound(Hash);
807 for (; I != TypesByHash.end() && I->first == Hash; ++I) {
808 if (I->second == Ty) {
809 TypesByHash.erase(I);
814 // This must be do to an opaque type that was resolved. Switch down to hash
816 assert(Hash && "Didn't find type entry!");
817 RemoveFromTypesByHash(0, Ty);
820 /// TypeBecameConcrete - When Ty gets a notification that TheType just became
821 /// concrete, drop uses and make Ty non-abstract if we should.
822 void TypeBecameConcrete(DerivedType *Ty, const DerivedType *TheType) {
823 // If the element just became concrete, remove 'ty' from the abstract
824 // type user list for the type. Do this for as many times as Ty uses
826 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
828 if (I->get() == TheType)
829 TheType->removeAbstractTypeUser(Ty);
831 // If the type is currently thought to be abstract, rescan all of our
832 // subtypes to see if the type has just become concrete! Note that this
833 // may send out notifications to AbstractTypeUsers that types become
835 if (Ty->isAbstract())
836 Ty->PromoteAbstractToConcrete();
842 // TypeMap - Make sure that only one instance of a particular type may be
843 // created on any given run of the compiler... note that this involves updating
844 // our map if an abstract type gets refined somehow.
847 template<class ValType, class TypeClass>
848 class TypeMap : public TypeMapBase {
849 std::map<ValType, PATypeHolder> Map;
851 typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
852 ~TypeMap() { print("ON EXIT"); }
854 inline TypeClass *get(const ValType &V) {
855 iterator I = Map.find(V);
856 return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
859 inline void add(const ValType &V, TypeClass *Ty) {
860 Map.insert(std::make_pair(V, Ty));
862 // If this type has a cycle, remember it.
863 TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
867 /// RefineAbstractType - This method is called after we have merged a type
868 /// with another one. We must now either merge the type away with
869 /// some other type or reinstall it in the map with it's new configuration.
870 void RefineAbstractType(TypeClass *Ty, const DerivedType *OldType,
871 const Type *NewType) {
872 #ifdef DEBUG_MERGE_TYPES
873 DOUT << "RefineAbstractType(" << (void*)OldType << "[" << *OldType
874 << "], " << (void*)NewType << " [" << *NewType << "])\n";
877 // Otherwise, we are changing one subelement type into another. Clearly the
878 // OldType must have been abstract, making us abstract.
879 assert(Ty->isAbstract() && "Refining a non-abstract type!");
880 assert(OldType != NewType);
882 // Make a temporary type holder for the type so that it doesn't disappear on
883 // us when we erase the entry from the map.
884 PATypeHolder TyHolder = Ty;
886 // The old record is now out-of-date, because one of the children has been
887 // updated. Remove the obsolete entry from the map.
888 unsigned NumErased = Map.erase(ValType::get(Ty));
889 assert(NumErased && "Element not found!"); NumErased = NumErased;
891 // Remember the structural hash for the type before we start hacking on it,
892 // in case we need it later.
893 unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
895 // Find the type element we are refining... and change it now!
896 for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i)
897 if (Ty->ContainedTys[i] == OldType)
898 Ty->ContainedTys[i] = NewType;
899 unsigned NewTypeHash = ValType::hashTypeStructure(Ty);
901 // If there are no cycles going through this node, we can do a simple,
902 // efficient lookup in the map, instead of an inefficient nasty linear
904 if (!TypeHasCycleThroughItself(Ty)) {
905 typename std::map<ValType, PATypeHolder>::iterator I;
908 tie(I, Inserted) = Map.insert(std::make_pair(ValType::get(Ty), Ty));
910 // Refined to a different type altogether?
911 RemoveFromTypesByHash(OldTypeHash, Ty);
913 // We already have this type in the table. Get rid of the newly refined
915 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
916 Ty->refineAbstractTypeTo(NewTy);
920 // Now we check to see if there is an existing entry in the table which is
921 // structurally identical to the newly refined type. If so, this type
922 // gets refined to the pre-existing type.
924 std::multimap<unsigned, PATypeHolder>::iterator I, E, Entry;
925 tie(I, E) = TypesByHash.equal_range(NewTypeHash);
927 for (; I != E; ++I) {
928 if (I->second == Ty) {
929 // Remember the position of the old type if we see it in our scan.
932 if (TypesEqual(Ty, I->second)) {
933 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
935 // Remove the old entry form TypesByHash. If the hash values differ
936 // now, remove it from the old place. Otherwise, continue scanning
937 // withing this hashcode to reduce work.
938 if (NewTypeHash != OldTypeHash) {
939 RemoveFromTypesByHash(OldTypeHash, Ty);
942 // Find the location of Ty in the TypesByHash structure if we
943 // haven't seen it already.
944 while (I->second != Ty) {
946 assert(I != E && "Structure doesn't contain type??");
950 TypesByHash.erase(Entry);
952 Ty->refineAbstractTypeTo(NewTy);
958 // If there is no existing type of the same structure, we reinsert an
959 // updated record into the map.
960 Map.insert(std::make_pair(ValType::get(Ty), Ty));
963 // If the hash codes differ, update TypesByHash
964 if (NewTypeHash != OldTypeHash) {
965 RemoveFromTypesByHash(OldTypeHash, Ty);
966 TypesByHash.insert(std::make_pair(NewTypeHash, Ty));
969 // If the type is currently thought to be abstract, rescan all of our
970 // subtypes to see if the type has just become concrete! Note that this
971 // may send out notifications to AbstractTypeUsers that types become
973 if (Ty->isAbstract())
974 Ty->PromoteAbstractToConcrete();
977 void print(const char *Arg) const {
978 #ifdef DEBUG_MERGE_TYPES
979 DOUT << "TypeMap<>::" << Arg << " table contents:\n";
981 for (typename std::map<ValType, PATypeHolder>::const_iterator I
982 = Map.begin(), E = Map.end(); I != E; ++I)
983 DOUT << " " << (++i) << ". " << (void*)I->second.get() << " "
984 << *I->second.get() << "\n";
988 void dump() const { print("dump output"); }
993 //===----------------------------------------------------------------------===//
994 // Function Type Factory and Value Class...
997 //===----------------------------------------------------------------------===//
998 // Integer Type Factory...
1001 class IntegerValType {
1004 IntegerValType(uint16_t numbits) : bits(numbits) {}
1006 static IntegerValType get(const IntegerType *Ty) {
1007 return IntegerValType(Ty->getBitWidth());
1010 static unsigned hashTypeStructure(const IntegerType *Ty) {
1011 return (unsigned)Ty->getBitWidth();
1014 inline bool operator<(const IntegerValType &IVT) const {
1015 return bits < IVT.bits;
1020 static ManagedStatic<TypeMap<IntegerValType, IntegerType> > IntegerTypes;
1022 const IntegerType *IntegerType::get(unsigned NumBits) {
1023 assert(NumBits >= MIN_INT_BITS && "bitwidth too small");
1024 assert(NumBits <= MAX_INT_BITS && "bitwidth too large");
1026 // Check for the built-in integer types
1028 case 1: return cast<IntegerType>(Type::Int1Ty);
1029 case 8: return cast<IntegerType>(Type::Int8Ty);
1030 case 16: return cast<IntegerType>(Type::Int16Ty);
1031 case 32: return cast<IntegerType>(Type::Int32Ty);
1032 case 64: return cast<IntegerType>(Type::Int64Ty);
1037 IntegerValType IVT(NumBits);
1038 IntegerType *ITy = IntegerTypes->get(IVT);
1039 if (ITy) return ITy; // Found a match, return it!
1041 // Value not found. Derive a new type!
1042 ITy = new IntegerType(NumBits);
1043 IntegerTypes->add(IVT, ITy);
1045 #ifdef DEBUG_MERGE_TYPES
1046 DOUT << "Derived new type: " << *ITy << "\n";
1051 bool IntegerType::isPowerOf2ByteWidth() const {
1052 unsigned BitWidth = getBitWidth();
1053 return (BitWidth > 7) && isPowerOf2_32(BitWidth);
1056 APInt IntegerType::getMask() const {
1057 return APInt::getAllOnesValue(getBitWidth());
1060 // FunctionValType - Define a class to hold the key that goes into the TypeMap
1063 class FunctionValType {
1065 std::vector<const Type*> ArgTypes;
1068 FunctionValType(const Type *ret, const std::vector<const Type*> &args,
1069 bool isVA) : RetTy(ret), ArgTypes(args), isVarArg(isVA) {}
1071 static FunctionValType get(const FunctionType *FT);
1073 static unsigned hashTypeStructure(const FunctionType *FT) {
1074 unsigned Result = FT->getNumParams()*2 + FT->isVarArg();
1078 inline bool operator<(const FunctionValType &MTV) const {
1079 if (RetTy < MTV.RetTy) return true;
1080 if (RetTy > MTV.RetTy) return false;
1081 if (isVarArg < MTV.isVarArg) return true;
1082 if (isVarArg > MTV.isVarArg) return false;
1083 if (ArgTypes < MTV.ArgTypes) return true;
1084 if (ArgTypes > MTV.ArgTypes) return false;
1090 // Define the actual map itself now...
1091 static ManagedStatic<TypeMap<FunctionValType, FunctionType> > FunctionTypes;
1093 FunctionValType FunctionValType::get(const FunctionType *FT) {
1094 // Build up a FunctionValType
1095 std::vector<const Type *> ParamTypes;
1096 ParamTypes.reserve(FT->getNumParams());
1097 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
1098 ParamTypes.push_back(FT->getParamType(i));
1099 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
1103 // FunctionType::get - The factory function for the FunctionType class...
1104 FunctionType *FunctionType::get(const Type *ReturnType,
1105 const std::vector<const Type*> &Params,
1107 FunctionValType VT(ReturnType, Params, isVarArg);
1108 FunctionType *FT = FunctionTypes->get(VT);
1112 FT = (FunctionType*) operator new(sizeof(FunctionType) +
1113 sizeof(PATypeHandle)*(Params.size()+1));
1114 new (FT) FunctionType(ReturnType, Params, isVarArg);
1115 FunctionTypes->add(VT, FT);
1117 #ifdef DEBUG_MERGE_TYPES
1118 DOUT << "Derived new type: " << FT << "\n";
1123 //===----------------------------------------------------------------------===//
1124 // Array Type Factory...
1127 class ArrayValType {
1131 ArrayValType(const Type *val, uint64_t sz) : ValTy(val), Size(sz) {}
1133 static ArrayValType get(const ArrayType *AT) {
1134 return ArrayValType(AT->getElementType(), AT->getNumElements());
1137 static unsigned hashTypeStructure(const ArrayType *AT) {
1138 return (unsigned)AT->getNumElements();
1141 inline bool operator<(const ArrayValType &MTV) const {
1142 if (Size < MTV.Size) return true;
1143 return Size == MTV.Size && ValTy < MTV.ValTy;
1147 static ManagedStatic<TypeMap<ArrayValType, ArrayType> > ArrayTypes;
1150 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
1151 assert(ElementType && "Can't get array of null types!");
1153 ArrayValType AVT(ElementType, NumElements);
1154 ArrayType *AT = ArrayTypes->get(AVT);
1155 if (AT) return AT; // Found a match, return it!
1157 // Value not found. Derive a new type!
1158 ArrayTypes->add(AVT, AT = new ArrayType(ElementType, NumElements));
1160 #ifdef DEBUG_MERGE_TYPES
1161 DOUT << "Derived new type: " << *AT << "\n";
1167 //===----------------------------------------------------------------------===//
1168 // Vector Type Factory...
1171 class VectorValType {
1175 VectorValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
1177 static VectorValType get(const VectorType *PT) {
1178 return VectorValType(PT->getElementType(), PT->getNumElements());
1181 static unsigned hashTypeStructure(const VectorType *PT) {
1182 return PT->getNumElements();
1185 inline bool operator<(const VectorValType &MTV) const {
1186 if (Size < MTV.Size) return true;
1187 return Size == MTV.Size && ValTy < MTV.ValTy;
1191 static ManagedStatic<TypeMap<VectorValType, VectorType> > VectorTypes;
1194 VectorType *VectorType::get(const Type *ElementType, unsigned NumElements) {
1195 assert(ElementType && "Can't get vector of null types!");
1197 VectorValType PVT(ElementType, NumElements);
1198 VectorType *PT = VectorTypes->get(PVT);
1199 if (PT) return PT; // Found a match, return it!
1201 // Value not found. Derive a new type!
1202 VectorTypes->add(PVT, PT = new VectorType(ElementType, NumElements));
1204 #ifdef DEBUG_MERGE_TYPES
1205 DOUT << "Derived new type: " << *PT << "\n";
1210 //===----------------------------------------------------------------------===//
1211 // Struct Type Factory...
1215 // StructValType - Define a class to hold the key that goes into the TypeMap
1217 class StructValType {
1218 std::vector<const Type*> ElTypes;
1221 StructValType(const std::vector<const Type*> &args, bool isPacked)
1222 : ElTypes(args), packed(isPacked) {}
1224 static StructValType get(const StructType *ST) {
1225 std::vector<const Type *> ElTypes;
1226 ElTypes.reserve(ST->getNumElements());
1227 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
1228 ElTypes.push_back(ST->getElementType(i));
1230 return StructValType(ElTypes, ST->isPacked());
1233 static unsigned hashTypeStructure(const StructType *ST) {
1234 return ST->getNumElements();
1237 inline bool operator<(const StructValType &STV) const {
1238 if (ElTypes < STV.ElTypes) return true;
1239 else if (ElTypes > STV.ElTypes) return false;
1240 else return (int)packed < (int)STV.packed;
1245 static ManagedStatic<TypeMap<StructValType, StructType> > StructTypes;
1247 StructType *StructType::get(const std::vector<const Type*> &ETypes,
1249 StructValType STV(ETypes, isPacked);
1250 StructType *ST = StructTypes->get(STV);
1253 // Value not found. Derive a new type!
1254 ST = (StructType*) operator new(sizeof(StructType) +
1255 sizeof(PATypeHandle) * ETypes.size());
1256 new (ST) StructType(ETypes, isPacked);
1257 StructTypes->add(STV, ST);
1259 #ifdef DEBUG_MERGE_TYPES
1260 DOUT << "Derived new type: " << *ST << "\n";
1265 StructType *StructType::get(const Type *type, ...) {
1267 std::vector<const llvm::Type*> StructFields;
1270 StructFields.push_back(type);
1271 type = va_arg(ap, llvm::Type*);
1273 return llvm::StructType::get(StructFields);
1278 //===----------------------------------------------------------------------===//
1279 // Pointer Type Factory...
1282 // PointerValType - Define a class to hold the key that goes into the TypeMap
1285 class PointerValType {
1287 unsigned AddressSpace;
1289 PointerValType(const Type *val, unsigned as) : ValTy(val), AddressSpace(as) {}
1291 static PointerValType get(const PointerType *PT) {
1292 return PointerValType(PT->getElementType(), PT->getAddressSpace());
1295 static unsigned hashTypeStructure(const PointerType *PT) {
1296 return getSubElementHash(PT);
1299 bool operator<(const PointerValType &MTV) const {
1300 if (AddressSpace < MTV.AddressSpace) return true;
1301 return AddressSpace == MTV.AddressSpace && ValTy < MTV.ValTy;
1306 static ManagedStatic<TypeMap<PointerValType, PointerType> > PointerTypes;
1308 PointerType *PointerType::get(const Type *ValueType, unsigned AddressSpace) {
1309 assert(ValueType && "Can't get a pointer to <null> type!");
1310 assert(ValueType != Type::VoidTy &&
1311 "Pointer to void is not valid, use sbyte* instead!");
1312 assert(ValueType != Type::LabelTy && "Pointer to label is not valid!");
1313 PointerValType PVT(ValueType, AddressSpace);
1315 PointerType *PT = PointerTypes->get(PVT);
1318 // Value not found. Derive a new type!
1319 PointerTypes->add(PVT, PT = new PointerType(ValueType, AddressSpace));
1321 #ifdef DEBUG_MERGE_TYPES
1322 DOUT << "Derived new type: " << *PT << "\n";
1327 //===----------------------------------------------------------------------===//
1328 // Derived Type Refinement Functions
1329 //===----------------------------------------------------------------------===//
1331 // removeAbstractTypeUser - Notify an abstract type that a user of the class
1332 // no longer has a handle to the type. This function is called primarily by
1333 // the PATypeHandle class. When there are no users of the abstract type, it
1334 // is annihilated, because there is no way to get a reference to it ever again.
1336 void Type::removeAbstractTypeUser(AbstractTypeUser *U) const {
1337 // Search from back to front because we will notify users from back to
1338 // front. Also, it is likely that there will be a stack like behavior to
1339 // users that register and unregister users.
1342 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1343 assert(i != 0 && "AbstractTypeUser not in user list!");
1345 --i; // Convert to be in range 0 <= i < size()
1346 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
1348 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1350 #ifdef DEBUG_MERGE_TYPES
1351 DOUT << " remAbstractTypeUser[" << (void*)this << ", "
1352 << *this << "][" << i << "] User = " << U << "\n";
1355 if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1356 #ifdef DEBUG_MERGE_TYPES
1357 DOUT << "DELETEing unused abstract type: <" << *this
1358 << ">[" << (void*)this << "]" << "\n";
1364 // refineAbstractTypeTo - This function is used when it is discovered that
1365 // the 'this' abstract type is actually equivalent to the NewType specified.
1366 // This causes all users of 'this' to switch to reference the more concrete type
1367 // NewType and for 'this' to be deleted.
1369 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1370 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1371 assert(this != NewType && "Can't refine to myself!");
1372 assert(ForwardType == 0 && "This type has already been refined!");
1374 // The descriptions may be out of date. Conservatively clear them all!
1375 AbstractTypeDescriptions->clear();
1377 #ifdef DEBUG_MERGE_TYPES
1378 DOUT << "REFINING abstract type [" << (void*)this << " "
1379 << *this << "] to [" << (void*)NewType << " "
1380 << *NewType << "]!\n";
1383 // Make sure to put the type to be refined to into a holder so that if IT gets
1384 // refined, that we will not continue using a dead reference...
1386 PATypeHolder NewTy(NewType);
1388 // Any PATypeHolders referring to this type will now automatically forward to
1389 // the type we are resolved to.
1390 ForwardType = NewType;
1391 if (NewType->isAbstract())
1392 cast<DerivedType>(NewType)->addRef();
1394 // Add a self use of the current type so that we don't delete ourself until
1395 // after the function exits.
1397 PATypeHolder CurrentTy(this);
1399 // To make the situation simpler, we ask the subclass to remove this type from
1400 // the type map, and to replace any type uses with uses of non-abstract types.
1401 // This dramatically limits the amount of recursive type trouble we can find
1405 // Iterate over all of the uses of this type, invoking callback. Each user
1406 // should remove itself from our use list automatically. We have to check to
1407 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1408 // will not cause users to drop off of the use list. If we resolve to ourself
1411 while (!AbstractTypeUsers.empty() && NewTy != this) {
1412 AbstractTypeUser *User = AbstractTypeUsers.back();
1414 unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1415 #ifdef DEBUG_MERGE_TYPES
1416 DOUT << " REFINING user " << OldSize-1 << "[" << (void*)User
1417 << "] of abstract type [" << (void*)this << " "
1418 << *this << "] to [" << (void*)NewTy.get() << " "
1419 << *NewTy << "]!\n";
1421 User->refineAbstractType(this, NewTy);
1423 assert(AbstractTypeUsers.size() != OldSize &&
1424 "AbsTyUser did not remove self from user list!");
1427 // If we were successful removing all users from the type, 'this' will be
1428 // deleted when the last PATypeHolder is destroyed or updated from this type.
1429 // This may occur on exit of this function, as the CurrentTy object is
1433 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1434 // the current type has transitioned from being abstract to being concrete.
1436 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1437 #ifdef DEBUG_MERGE_TYPES
1438 DOUT << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1441 unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1442 while (!AbstractTypeUsers.empty()) {
1443 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1444 ATU->typeBecameConcrete(this);
1446 assert(AbstractTypeUsers.size() < OldSize-- &&
1447 "AbstractTypeUser did not remove itself from the use list!");
1451 // refineAbstractType - Called when a contained type is found to be more
1452 // concrete - this could potentially change us from an abstract type to a
1455 void FunctionType::refineAbstractType(const DerivedType *OldType,
1456 const Type *NewType) {
1457 FunctionTypes->RefineAbstractType(this, OldType, NewType);
1460 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1461 FunctionTypes->TypeBecameConcrete(this, AbsTy);
1465 // refineAbstractType - Called when a contained type is found to be more
1466 // concrete - this could potentially change us from an abstract type to a
1469 void ArrayType::refineAbstractType(const DerivedType *OldType,
1470 const Type *NewType) {
1471 ArrayTypes->RefineAbstractType(this, OldType, NewType);
1474 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1475 ArrayTypes->TypeBecameConcrete(this, AbsTy);
1478 // refineAbstractType - Called when a contained type is found to be more
1479 // concrete - this could potentially change us from an abstract type to a
1482 void VectorType::refineAbstractType(const DerivedType *OldType,
1483 const Type *NewType) {
1484 VectorTypes->RefineAbstractType(this, OldType, NewType);
1487 void VectorType::typeBecameConcrete(const DerivedType *AbsTy) {
1488 VectorTypes->TypeBecameConcrete(this, AbsTy);
1491 // refineAbstractType - Called when a contained type is found to be more
1492 // concrete - this could potentially change us from an abstract type to a
1495 void StructType::refineAbstractType(const DerivedType *OldType,
1496 const Type *NewType) {
1497 StructTypes->RefineAbstractType(this, OldType, NewType);
1500 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1501 StructTypes->TypeBecameConcrete(this, AbsTy);
1504 // refineAbstractType - Called when a contained type is found to be more
1505 // concrete - this could potentially change us from an abstract type to a
1508 void PointerType::refineAbstractType(const DerivedType *OldType,
1509 const Type *NewType) {
1510 PointerTypes->RefineAbstractType(this, OldType, NewType);
1513 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1514 PointerTypes->TypeBecameConcrete(this, AbsTy);
1517 bool SequentialType::indexValid(const Value *V) const {
1518 if (const IntegerType *IT = dyn_cast<IntegerType>(V->getType()))
1519 return IT->getBitWidth() == 32 || IT->getBitWidth() == 64;
1524 std::ostream &operator<<(std::ostream &OS, const Type *T) {
1526 OS << "<null> value!\n";
1532 std::ostream &operator<<(std::ostream &OS, const Type &T) {