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 PATypeHolder Implementation
39 //===----------------------------------------------------------------------===//
41 /// get - This implements the forwarding part of the union-find algorithm for
42 /// abstract types. Before every access to the Type*, we check to see if the
43 /// type we are pointing to is forwarding to a new type. If so, we drop our
44 /// reference to the type.
46 Type* PATypeHolder::get() const {
47 const Type *NewTy = Ty->getForwardedType();
48 if (!NewTy) return const_cast<Type*>(Ty);
49 return *const_cast<PATypeHolder*>(this) = NewTy;
52 //===----------------------------------------------------------------------===//
53 // Type Class Implementation
54 //===----------------------------------------------------------------------===//
56 // Concrete/Abstract TypeDescriptions - We lazily calculate type descriptions
57 // for types as they are needed. Because resolution of types must invalidate
58 // all of the abstract type descriptions, we keep them in a seperate map to make
60 static ManagedStatic<std::map<const Type*,
61 std::string> > ConcreteTypeDescriptions;
62 static ManagedStatic<std::map<const Type*,
63 std::string> > AbstractTypeDescriptions;
65 /// Because of the way Type subclasses are allocated, this function is necessary
66 /// to use the correct kind of "delete" operator to deallocate the Type object.
67 /// Some type objects (FunctionTy, StructTy) allocate additional space after
68 /// the space for their derived type to hold the contained types array of
69 /// PATypeHandles. Using this allocation scheme means all the PATypeHandles are
70 /// allocated with the type object, decreasing allocations and eliminating the
71 /// need for a std::vector to be used in the Type class itself.
72 /// @brief Type destruction function
73 void Type::destroy() const {
75 // Structures and Functions allocate their contained types past the end of
76 // the type object itself. These need to be destroyed differently than the
78 if (isa<FunctionType>(this) || isa<StructType>(this)) {
79 // First, make sure we destruct any PATypeHandles allocated by these
80 // subclasses. They must be manually destructed.
81 for (unsigned i = 0; i < NumContainedTys; ++i)
82 ContainedTys[i].PATypeHandle::~PATypeHandle();
84 // Now call the destructor for the subclass directly because we're going
85 // to delete this as an array of char.
86 if (isa<FunctionType>(this))
87 ((FunctionType*)this)->FunctionType::~FunctionType();
89 ((StructType*)this)->StructType::~StructType();
91 // Finally, remove the memory as an array deallocation of the chars it was
93 delete [] reinterpret_cast<const char*>(this);
98 // For all the other type subclasses, there is either no contained types or
99 // just one (all Sequentials). For Sequentials, the PATypeHandle is not
100 // allocated past the type object, its included directly in the SequentialType
101 // class. This means we can safely just do "normal" delete of this object and
102 // all the destructors that need to run will be run.
106 const Type *Type::getPrimitiveType(TypeID IDNumber) {
108 case VoidTyID : return VoidTy;
109 case FloatTyID : return FloatTy;
110 case DoubleTyID : return DoubleTy;
111 case X86_FP80TyID : return X86_FP80Ty;
112 case FP128TyID : return FP128Ty;
113 case PPC_FP128TyID : return PPC_FP128Ty;
114 case LabelTyID : return LabelTy;
120 const Type *Type::getVAArgsPromotedType() const {
121 if (ID == IntegerTyID && getSubclassData() < 32)
122 return Type::Int32Ty;
123 else if (ID == FloatTyID)
124 return Type::DoubleTy;
129 /// isIntOrIntVector - Return true if this is an integer type or a vector of
132 bool Type::isIntOrIntVector() const {
135 if (ID != Type::VectorTyID) return false;
137 return cast<VectorType>(this)->getElementType()->isInteger();
140 /// isFPOrFPVector - Return true if this is a FP type or a vector of FP types.
142 bool Type::isFPOrFPVector() const {
143 if (ID == Type::FloatTyID || ID == Type::DoubleTyID ||
144 ID == Type::FP128TyID || ID == Type::X86_FP80TyID ||
145 ID == Type::PPC_FP128TyID)
147 if (ID != Type::VectorTyID) return false;
149 return cast<VectorType>(this)->getElementType()->isFloatingPoint();
152 // canLosslesllyBitCastTo - Return true if this type can be converted to
153 // 'Ty' without any reinterpretation of bits. For example, uint to int.
155 bool Type::canLosslesslyBitCastTo(const Type *Ty) const {
156 // Identity cast means no change so return true
160 // They are not convertible unless they are at least first class types
161 if (!this->isFirstClassType() || !Ty->isFirstClassType())
164 // Vector -> Vector conversions are always lossless if the two vector types
165 // have the same size, otherwise not.
166 if (const VectorType *thisPTy = dyn_cast<VectorType>(this))
167 if (const VectorType *thatPTy = dyn_cast<VectorType>(Ty))
168 return thisPTy->getBitWidth() == thatPTy->getBitWidth();
170 // At this point we have only various mismatches of the first class types
171 // remaining and ptr->ptr. Just select the lossless conversions. Everything
172 // else is not lossless.
173 if (isa<PointerType>(this))
174 return isa<PointerType>(Ty);
175 return false; // Other types have no identity values
178 unsigned Type::getPrimitiveSizeInBits() const {
179 switch (getTypeID()) {
180 case Type::FloatTyID: return 32;
181 case Type::DoubleTyID: return 64;
182 case Type::X86_FP80TyID: return 80;
183 case Type::FP128TyID: return 128;
184 case Type::PPC_FP128TyID: return 128;
185 case Type::IntegerTyID: return cast<IntegerType>(this)->getBitWidth();
186 case Type::VectorTyID: return cast<VectorType>(this)->getBitWidth();
191 /// isSizedDerivedType - Derived types like structures and arrays are sized
192 /// iff all of the members of the type are sized as well. Since asking for
193 /// their size is relatively uncommon, move this operation out of line.
194 bool Type::isSizedDerivedType() const {
195 if (isa<IntegerType>(this))
198 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
199 return ATy->getElementType()->isSized();
201 if (const VectorType *PTy = dyn_cast<VectorType>(this))
202 return PTy->getElementType()->isSized();
204 if (!isa<StructType>(this))
207 // Okay, our struct is sized if all of the elements are...
208 for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I)
209 if (!(*I)->isSized())
215 /// getForwardedTypeInternal - This method is used to implement the union-find
216 /// algorithm for when a type is being forwarded to another type.
217 const Type *Type::getForwardedTypeInternal() const {
218 assert(ForwardType && "This type is not being forwarded to another type!");
220 // Check to see if the forwarded type has been forwarded on. If so, collapse
221 // the forwarding links.
222 const Type *RealForwardedType = ForwardType->getForwardedType();
223 if (!RealForwardedType)
224 return ForwardType; // No it's not forwarded again
226 // Yes, it is forwarded again. First thing, add the reference to the new
228 if (RealForwardedType->isAbstract())
229 cast<DerivedType>(RealForwardedType)->addRef();
231 // Now drop the old reference. This could cause ForwardType to get deleted.
232 cast<DerivedType>(ForwardType)->dropRef();
234 // Return the updated type.
235 ForwardType = RealForwardedType;
239 void Type::refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
242 void Type::typeBecameConcrete(const DerivedType *AbsTy) {
247 // getTypeDescription - This is a recursive function that walks a type hierarchy
248 // calculating the description for a type.
250 static std::string getTypeDescription(const Type *Ty,
251 std::vector<const Type *> &TypeStack) {
252 if (isa<OpaqueType>(Ty)) { // Base case for the recursion
253 std::map<const Type*, std::string>::iterator I =
254 AbstractTypeDescriptions->lower_bound(Ty);
255 if (I != AbstractTypeDescriptions->end() && I->first == Ty)
257 std::string Desc = "opaque";
258 AbstractTypeDescriptions->insert(std::make_pair(Ty, Desc));
262 if (!Ty->isAbstract()) { // Base case for the recursion
263 std::map<const Type*, std::string>::iterator I =
264 ConcreteTypeDescriptions->find(Ty);
265 if (I != ConcreteTypeDescriptions->end())
268 if (Ty->isPrimitiveType()) {
269 switch (Ty->getTypeID()) {
270 default: assert(0 && "Unknown prim type!");
271 case Type::VoidTyID: return (*ConcreteTypeDescriptions)[Ty] = "void";
272 case Type::FloatTyID: return (*ConcreteTypeDescriptions)[Ty] = "float";
273 case Type::DoubleTyID: return (*ConcreteTypeDescriptions)[Ty] = "double";
274 case Type::X86_FP80TyID:
275 return (*ConcreteTypeDescriptions)[Ty] = "x86_fp80";
276 case Type::FP128TyID: return (*ConcreteTypeDescriptions)[Ty] = "fp128";
277 case Type::PPC_FP128TyID:
278 return (*ConcreteTypeDescriptions)[Ty] = "ppc_fp128";
279 case Type::LabelTyID: return (*ConcreteTypeDescriptions)[Ty] = "label";
284 // Check to see if the Type is already on the stack...
285 unsigned Slot = 0, CurSize = TypeStack.size();
286 while (Slot < CurSize && TypeStack[Slot] != Ty) ++Slot; // Scan for type
288 // This is another base case for the recursion. In this case, we know
289 // that we have looped back to a type that we have previously visited.
290 // Generate the appropriate upreference to handle this.
293 return "\\" + utostr(CurSize-Slot); // Here's the upreference
295 // Recursive case: derived types...
297 TypeStack.push_back(Ty); // Add us to the stack..
299 switch (Ty->getTypeID()) {
300 case Type::IntegerTyID: {
301 const IntegerType *ITy = cast<IntegerType>(Ty);
302 Result = "i" + utostr(ITy->getBitWidth());
305 case Type::FunctionTyID: {
306 const FunctionType *FTy = cast<FunctionType>(Ty);
309 Result += getTypeDescription(FTy->getReturnType(), TypeStack) + " (";
310 for (FunctionType::param_iterator I = FTy->param_begin(),
311 E = FTy->param_end(); I != E; ++I) {
312 if (I != FTy->param_begin())
314 Result += getTypeDescription(*I, TypeStack);
316 if (FTy->isVarArg()) {
317 if (FTy->getNumParams()) Result += ", ";
323 case Type::StructTyID: {
324 const StructType *STy = cast<StructType>(Ty);
329 for (StructType::element_iterator I = STy->element_begin(),
330 E = STy->element_end(); I != E; ++I) {
331 if (I != STy->element_begin())
333 Result += getTypeDescription(*I, TypeStack);
340 case Type::PointerTyID: {
341 const PointerType *PTy = cast<PointerType>(Ty);
342 Result = getTypeDescription(PTy->getElementType(), TypeStack);
343 if (unsigned AddressSpace = PTy->getAddressSpace())
344 Result += " addrspace(" + utostr(AddressSpace) + ")";
348 case Type::ArrayTyID: {
349 const ArrayType *ATy = cast<ArrayType>(Ty);
350 unsigned NumElements = ATy->getNumElements();
352 Result += utostr(NumElements) + " x ";
353 Result += getTypeDescription(ATy->getElementType(), TypeStack) + "]";
356 case Type::VectorTyID: {
357 const VectorType *PTy = cast<VectorType>(Ty);
358 unsigned NumElements = PTy->getNumElements();
360 Result += utostr(NumElements) + " x ";
361 Result += getTypeDescription(PTy->getElementType(), TypeStack) + ">";
366 assert(0 && "Unhandled type in getTypeDescription!");
369 TypeStack.pop_back(); // Remove self from stack...
376 static const std::string &getOrCreateDesc(std::map<const Type*,std::string>&Map,
378 std::map<const Type*, std::string>::iterator I = Map.find(Ty);
379 if (I != Map.end()) return I->second;
381 std::vector<const Type *> TypeStack;
382 std::string Result = getTypeDescription(Ty, TypeStack);
383 return Map[Ty] = Result;
387 const std::string &Type::getDescription() const {
389 return getOrCreateDesc(*AbstractTypeDescriptions, this);
391 return getOrCreateDesc(*ConcreteTypeDescriptions, this);
395 bool StructType::indexValid(const Value *V) const {
396 // Structure indexes require 32-bit integer constants.
397 if (V->getType() == Type::Int32Ty)
398 if (const ConstantInt *CU = dyn_cast<ConstantInt>(V))
399 return CU->getZExtValue() < NumContainedTys;
403 // getTypeAtIndex - Given an index value into the type, return the type of the
404 // element. For a structure type, this must be a constant value...
406 const Type *StructType::getTypeAtIndex(const Value *V) const {
407 assert(indexValid(V) && "Invalid structure index!");
408 unsigned Idx = (unsigned)cast<ConstantInt>(V)->getZExtValue();
409 return ContainedTys[Idx];
412 //===----------------------------------------------------------------------===//
413 // Primitive 'Type' data
414 //===----------------------------------------------------------------------===//
416 const Type *Type::VoidTy = new Type(Type::VoidTyID);
417 const Type *Type::FloatTy = new Type(Type::FloatTyID);
418 const Type *Type::DoubleTy = new Type(Type::DoubleTyID);
419 const Type *Type::X86_FP80Ty = new Type(Type::X86_FP80TyID);
420 const Type *Type::FP128Ty = new Type(Type::FP128TyID);
421 const Type *Type::PPC_FP128Ty = new Type(Type::PPC_FP128TyID);
422 const Type *Type::LabelTy = new Type(Type::LabelTyID);
425 struct BuiltinIntegerType : public IntegerType {
426 BuiltinIntegerType(unsigned W) : IntegerType(W) {}
429 const IntegerType *Type::Int1Ty = new BuiltinIntegerType(1);
430 const IntegerType *Type::Int8Ty = new BuiltinIntegerType(8);
431 const IntegerType *Type::Int16Ty = new BuiltinIntegerType(16);
432 const IntegerType *Type::Int32Ty = new BuiltinIntegerType(32);
433 const IntegerType *Type::Int64Ty = new BuiltinIntegerType(64);
436 //===----------------------------------------------------------------------===//
437 // Derived Type Constructors
438 //===----------------------------------------------------------------------===//
440 /// isValidReturnType - Return true if the specified type is valid as a return
442 bool FunctionType::isValidReturnType(const Type *RetTy) {
443 if (RetTy->isFirstClassType())
445 if (RetTy == Type::VoidTy || isa<OpaqueType>(RetTy))
448 // If this is a multiple return case, verify that each return is a first class
449 // value and that there is at least one value.
450 const StructType *SRetTy = dyn_cast<StructType>(RetTy);
451 if (SRetTy == 0 || SRetTy->getNumElements() == 0)
454 for (unsigned i = 0, e = SRetTy->getNumElements(); i != e; ++i)
455 if (!SRetTy->getElementType(i)->isFirstClassType())
460 FunctionType::FunctionType(const Type *Result,
461 const std::vector<const Type*> &Params,
463 : DerivedType(FunctionTyID), isVarArgs(IsVarArgs) {
464 ContainedTys = reinterpret_cast<PATypeHandle*>(this+1);
465 NumContainedTys = Params.size() + 1; // + 1 for result type
466 assert(isValidReturnType(Result) && "invalid return type for function");
469 bool isAbstract = Result->isAbstract();
470 new (&ContainedTys[0]) PATypeHandle(Result, this);
472 for (unsigned i = 0; i != Params.size(); ++i) {
473 assert((Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])) &&
474 "Function arguments must be value types!");
475 new (&ContainedTys[i+1]) PATypeHandle(Params[i],this);
476 isAbstract |= Params[i]->isAbstract();
479 // Calculate whether or not this type is abstract
480 setAbstract(isAbstract);
483 StructType::StructType(const std::vector<const Type*> &Types, bool isPacked)
484 : CompositeType(StructTyID) {
485 ContainedTys = reinterpret_cast<PATypeHandle*>(this + 1);
486 NumContainedTys = Types.size();
487 setSubclassData(isPacked);
488 bool isAbstract = false;
489 for (unsigned i = 0; i < Types.size(); ++i) {
490 assert(Types[i] != Type::VoidTy && "Void type for structure field!!");
491 new (&ContainedTys[i]) PATypeHandle(Types[i], this);
492 isAbstract |= Types[i]->isAbstract();
495 // Calculate whether or not this type is abstract
496 setAbstract(isAbstract);
499 ArrayType::ArrayType(const Type *ElType, uint64_t NumEl)
500 : SequentialType(ArrayTyID, ElType) {
503 // Calculate whether or not this type is abstract
504 setAbstract(ElType->isAbstract());
507 VectorType::VectorType(const Type *ElType, unsigned NumEl)
508 : SequentialType(VectorTyID, ElType) {
510 setAbstract(ElType->isAbstract());
511 assert(NumEl > 0 && "NumEl of a VectorType must be greater than 0");
512 assert((ElType->isInteger() || ElType->isFloatingPoint() ||
513 isa<OpaqueType>(ElType)) &&
514 "Elements of a VectorType must be a primitive type");
519 PointerType::PointerType(const Type *E, unsigned AddrSpace)
520 : SequentialType(PointerTyID, E) {
521 AddressSpace = AddrSpace;
522 // Calculate whether or not this type is abstract
523 setAbstract(E->isAbstract());
526 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
528 #ifdef DEBUG_MERGE_TYPES
529 DOUT << "Derived new type: " << *this << "\n";
533 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
534 // another (more concrete) type, we must eliminate all references to other
535 // types, to avoid some circular reference problems.
536 void DerivedType::dropAllTypeUses() {
537 if (NumContainedTys != 0) {
538 // The type must stay abstract. To do this, we insert a pointer to a type
539 // that will never get resolved, thus will always be abstract.
540 static Type *AlwaysOpaqueTy = OpaqueType::get();
541 static PATypeHolder Holder(AlwaysOpaqueTy);
542 ContainedTys[0] = AlwaysOpaqueTy;
544 // Change the rest of the types to be Int32Ty's. It doesn't matter what we
545 // pick so long as it doesn't point back to this type. We choose something
546 // concrete to avoid overhead for adding to AbstracTypeUser lists and stuff.
547 for (unsigned i = 1, e = NumContainedTys; i != e; ++i)
548 ContainedTys[i] = Type::Int32Ty;
554 /// TypePromotionGraph and graph traits - this is designed to allow us to do
555 /// efficient SCC processing of type graphs. This is the exact same as
556 /// GraphTraits<Type*>, except that we pretend that concrete types have no
557 /// children to avoid processing them.
558 struct TypePromotionGraph {
560 TypePromotionGraph(Type *T) : Ty(T) {}
564 template <> struct GraphTraits<TypePromotionGraph> {
565 typedef Type NodeType;
566 typedef Type::subtype_iterator ChildIteratorType;
568 static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
569 static inline ChildIteratorType child_begin(NodeType *N) {
571 return N->subtype_begin();
572 else // No need to process children of concrete types.
573 return N->subtype_end();
575 static inline ChildIteratorType child_end(NodeType *N) {
576 return N->subtype_end();
582 // PromoteAbstractToConcrete - This is a recursive function that walks a type
583 // graph calculating whether or not a type is abstract.
585 void Type::PromoteAbstractToConcrete() {
586 if (!isAbstract()) return;
588 scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
589 scc_iterator<TypePromotionGraph> SE = scc_end (TypePromotionGraph(this));
591 for (; SI != SE; ++SI) {
592 std::vector<Type*> &SCC = *SI;
594 // Concrete types are leaves in the tree. Since an SCC will either be all
595 // abstract or all concrete, we only need to check one type.
596 if (SCC[0]->isAbstract()) {
597 if (isa<OpaqueType>(SCC[0]))
598 return; // Not going to be concrete, sorry.
600 // If all of the children of all of the types in this SCC are concrete,
601 // then this SCC is now concrete as well. If not, neither this SCC, nor
602 // any parent SCCs will be concrete, so we might as well just exit.
603 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
604 for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
605 E = SCC[i]->subtype_end(); CI != E; ++CI)
606 if ((*CI)->isAbstract())
607 // If the child type is in our SCC, it doesn't make the entire SCC
608 // abstract unless there is a non-SCC abstract type.
609 if (std::find(SCC.begin(), SCC.end(), *CI) == SCC.end())
610 return; // Not going to be concrete, sorry.
612 // Okay, we just discovered this whole SCC is now concrete, mark it as
614 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
615 assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
617 SCC[i]->setAbstract(false);
620 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
621 assert(!SCC[i]->isAbstract() && "Concrete type became abstract?");
622 // The type just became concrete, notify all users!
623 cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
630 //===----------------------------------------------------------------------===//
631 // Type Structural Equality Testing
632 //===----------------------------------------------------------------------===//
634 // TypesEqual - Two types are considered structurally equal if they have the
635 // same "shape": Every level and element of the types have identical primitive
636 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
637 // be pointer equals to be equivalent though. This uses an optimistic algorithm
638 // that assumes that two graphs are the same until proven otherwise.
640 static bool TypesEqual(const Type *Ty, const Type *Ty2,
641 std::map<const Type *, const Type *> &EqTypes) {
642 if (Ty == Ty2) return true;
643 if (Ty->getTypeID() != Ty2->getTypeID()) return false;
644 if (isa<OpaqueType>(Ty))
645 return false; // Two unequal opaque types are never equal
647 std::map<const Type*, const Type*>::iterator It = EqTypes.lower_bound(Ty);
648 if (It != EqTypes.end() && It->first == Ty)
649 return It->second == Ty2; // Looping back on a type, check for equality
651 // Otherwise, add the mapping to the table to make sure we don't get
652 // recursion on the types...
653 EqTypes.insert(It, std::make_pair(Ty, Ty2));
655 // Two really annoying special cases that breaks an otherwise nice simple
656 // algorithm is the fact that arraytypes have sizes that differentiates types,
657 // and that function types can be varargs or not. Consider this now.
659 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
660 const IntegerType *ITy2 = cast<IntegerType>(Ty2);
661 return ITy->getBitWidth() == ITy2->getBitWidth();
662 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
663 const PointerType *PTy2 = cast<PointerType>(Ty2);
664 return PTy->getAddressSpace() == PTy2->getAddressSpace() &&
665 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
666 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
667 const StructType *STy2 = cast<StructType>(Ty2);
668 if (STy->getNumElements() != STy2->getNumElements()) return false;
669 if (STy->isPacked() != STy2->isPacked()) return false;
670 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
671 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
674 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
675 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
676 return ATy->getNumElements() == ATy2->getNumElements() &&
677 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
678 } else if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
679 const VectorType *PTy2 = cast<VectorType>(Ty2);
680 return PTy->getNumElements() == PTy2->getNumElements() &&
681 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
682 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
683 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
684 if (FTy->isVarArg() != FTy2->isVarArg() ||
685 FTy->getNumParams() != FTy2->getNumParams() ||
686 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
688 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i) {
689 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
694 assert(0 && "Unknown derived type!");
699 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
700 std::map<const Type *, const Type *> EqTypes;
701 return TypesEqual(Ty, Ty2, EqTypes);
704 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
705 // TargetTy in the type graph. We know that Ty is an abstract type, so if we
706 // ever reach a non-abstract type, we know that we don't need to search the
708 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
709 std::set<const Type*> &VisitedTypes) {
710 if (TargetTy == CurTy) return true;
711 if (!CurTy->isAbstract()) return false;
713 if (!VisitedTypes.insert(CurTy).second)
714 return false; // Already been here.
716 for (Type::subtype_iterator I = CurTy->subtype_begin(),
717 E = CurTy->subtype_end(); I != E; ++I)
718 if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
723 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
724 std::set<const Type*> &VisitedTypes) {
725 if (TargetTy == CurTy) return true;
727 if (!VisitedTypes.insert(CurTy).second)
728 return false; // Already been here.
730 for (Type::subtype_iterator I = CurTy->subtype_begin(),
731 E = CurTy->subtype_end(); I != E; ++I)
732 if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
737 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
739 static bool TypeHasCycleThroughItself(const Type *Ty) {
740 std::set<const Type*> VisitedTypes;
742 if (Ty->isAbstract()) { // Optimized case for abstract types.
743 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
745 if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
748 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
750 if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
756 /// getSubElementHash - Generate a hash value for all of the SubType's of this
757 /// type. The hash value is guaranteed to be zero if any of the subtypes are
758 /// an opaque type. Otherwise we try to mix them in as well as possible, but do
759 /// not look at the subtype's subtype's.
760 static unsigned getSubElementHash(const Type *Ty) {
761 unsigned HashVal = 0;
762 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
765 const Type *SubTy = I->get();
766 HashVal += SubTy->getTypeID();
767 switch (SubTy->getTypeID()) {
769 case Type::OpaqueTyID: return 0; // Opaque -> hash = 0 no matter what.
770 case Type::IntegerTyID:
771 HashVal ^= (cast<IntegerType>(SubTy)->getBitWidth() << 3);
773 case Type::FunctionTyID:
774 HashVal ^= cast<FunctionType>(SubTy)->getNumParams()*2 +
775 cast<FunctionType>(SubTy)->isVarArg();
777 case Type::ArrayTyID:
778 HashVal ^= cast<ArrayType>(SubTy)->getNumElements();
780 case Type::VectorTyID:
781 HashVal ^= cast<VectorType>(SubTy)->getNumElements();
783 case Type::StructTyID:
784 HashVal ^= cast<StructType>(SubTy)->getNumElements();
786 case Type::PointerTyID:
787 HashVal ^= cast<PointerType>(SubTy)->getAddressSpace();
791 return HashVal ? HashVal : 1; // Do not return zero unless opaque subty.
794 //===----------------------------------------------------------------------===//
795 // Derived Type Factory Functions
796 //===----------------------------------------------------------------------===//
801 /// TypesByHash - Keep track of types by their structure hash value. Note
802 /// that we only keep track of types that have cycles through themselves in
805 std::multimap<unsigned, PATypeHolder> TypesByHash;
808 void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
809 std::multimap<unsigned, PATypeHolder>::iterator I =
810 TypesByHash.lower_bound(Hash);
811 for (; I != TypesByHash.end() && I->first == Hash; ++I) {
812 if (I->second == Ty) {
813 TypesByHash.erase(I);
818 // This must be do to an opaque type that was resolved. Switch down to hash
820 assert(Hash && "Didn't find type entry!");
821 RemoveFromTypesByHash(0, Ty);
824 /// TypeBecameConcrete - When Ty gets a notification that TheType just became
825 /// concrete, drop uses and make Ty non-abstract if we should.
826 void TypeBecameConcrete(DerivedType *Ty, const DerivedType *TheType) {
827 // If the element just became concrete, remove 'ty' from the abstract
828 // type user list for the type. Do this for as many times as Ty uses
830 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
832 if (I->get() == TheType)
833 TheType->removeAbstractTypeUser(Ty);
835 // If the type is currently thought to be abstract, rescan all of our
836 // subtypes to see if the type has just become concrete! Note that this
837 // may send out notifications to AbstractTypeUsers that types become
839 if (Ty->isAbstract())
840 Ty->PromoteAbstractToConcrete();
846 // TypeMap - Make sure that only one instance of a particular type may be
847 // created on any given run of the compiler... note that this involves updating
848 // our map if an abstract type gets refined somehow.
851 template<class ValType, class TypeClass>
852 class TypeMap : public TypeMapBase {
853 std::map<ValType, PATypeHolder> Map;
855 typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
856 ~TypeMap() { print("ON EXIT"); }
858 inline TypeClass *get(const ValType &V) {
859 iterator I = Map.find(V);
860 return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
863 inline void add(const ValType &V, TypeClass *Ty) {
864 Map.insert(std::make_pair(V, Ty));
866 // If this type has a cycle, remember it.
867 TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
871 /// RefineAbstractType - This method is called after we have merged a type
872 /// with another one. We must now either merge the type away with
873 /// some other type or reinstall it in the map with it's new configuration.
874 void RefineAbstractType(TypeClass *Ty, const DerivedType *OldType,
875 const Type *NewType) {
876 #ifdef DEBUG_MERGE_TYPES
877 DOUT << "RefineAbstractType(" << (void*)OldType << "[" << *OldType
878 << "], " << (void*)NewType << " [" << *NewType << "])\n";
881 // Otherwise, we are changing one subelement type into another. Clearly the
882 // OldType must have been abstract, making us abstract.
883 assert(Ty->isAbstract() && "Refining a non-abstract type!");
884 assert(OldType != NewType);
886 // Make a temporary type holder for the type so that it doesn't disappear on
887 // us when we erase the entry from the map.
888 PATypeHolder TyHolder = Ty;
890 // The old record is now out-of-date, because one of the children has been
891 // updated. Remove the obsolete entry from the map.
892 unsigned NumErased = Map.erase(ValType::get(Ty));
893 assert(NumErased && "Element not found!");
895 // Remember the structural hash for the type before we start hacking on it,
896 // in case we need it later.
897 unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
899 // Find the type element we are refining... and change it now!
900 for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i)
901 if (Ty->ContainedTys[i] == OldType)
902 Ty->ContainedTys[i] = NewType;
903 unsigned NewTypeHash = ValType::hashTypeStructure(Ty);
905 // If there are no cycles going through this node, we can do a simple,
906 // efficient lookup in the map, instead of an inefficient nasty linear
908 if (!TypeHasCycleThroughItself(Ty)) {
909 typename std::map<ValType, PATypeHolder>::iterator I;
912 tie(I, Inserted) = Map.insert(std::make_pair(ValType::get(Ty), Ty));
914 // Refined to a different type altogether?
915 RemoveFromTypesByHash(OldTypeHash, Ty);
917 // We already have this type in the table. Get rid of the newly refined
919 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
920 Ty->refineAbstractTypeTo(NewTy);
924 // Now we check to see if there is an existing entry in the table which is
925 // structurally identical to the newly refined type. If so, this type
926 // gets refined to the pre-existing type.
928 std::multimap<unsigned, PATypeHolder>::iterator I, E, Entry;
929 tie(I, E) = TypesByHash.equal_range(NewTypeHash);
931 for (; I != E; ++I) {
932 if (I->second == Ty) {
933 // Remember the position of the old type if we see it in our scan.
936 if (TypesEqual(Ty, I->second)) {
937 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
939 // Remove the old entry form TypesByHash. If the hash values differ
940 // now, remove it from the old place. Otherwise, continue scanning
941 // withing this hashcode to reduce work.
942 if (NewTypeHash != OldTypeHash) {
943 RemoveFromTypesByHash(OldTypeHash, Ty);
946 // Find the location of Ty in the TypesByHash structure if we
947 // haven't seen it already.
948 while (I->second != Ty) {
950 assert(I != E && "Structure doesn't contain type??");
954 TypesByHash.erase(Entry);
956 Ty->refineAbstractTypeTo(NewTy);
962 // If there is no existing type of the same structure, we reinsert an
963 // updated record into the map.
964 Map.insert(std::make_pair(ValType::get(Ty), Ty));
967 // If the hash codes differ, update TypesByHash
968 if (NewTypeHash != OldTypeHash) {
969 RemoveFromTypesByHash(OldTypeHash, Ty);
970 TypesByHash.insert(std::make_pair(NewTypeHash, Ty));
973 // If the type is currently thought to be abstract, rescan all of our
974 // subtypes to see if the type has just become concrete! Note that this
975 // may send out notifications to AbstractTypeUsers that types become
977 if (Ty->isAbstract())
978 Ty->PromoteAbstractToConcrete();
981 void print(const char *Arg) const {
982 #ifdef DEBUG_MERGE_TYPES
983 DOUT << "TypeMap<>::" << Arg << " table contents:\n";
985 for (typename std::map<ValType, PATypeHolder>::const_iterator I
986 = Map.begin(), E = Map.end(); I != E; ++I)
987 DOUT << " " << (++i) << ". " << (void*)I->second.get() << " "
988 << *I->second.get() << "\n";
992 void dump() const { print("dump output"); }
997 //===----------------------------------------------------------------------===//
998 // Function Type Factory and Value Class...
1001 //===----------------------------------------------------------------------===//
1002 // Integer Type Factory...
1005 class IntegerValType {
1008 IntegerValType(uint16_t numbits) : bits(numbits) {}
1010 static IntegerValType get(const IntegerType *Ty) {
1011 return IntegerValType(Ty->getBitWidth());
1014 static unsigned hashTypeStructure(const IntegerType *Ty) {
1015 return (unsigned)Ty->getBitWidth();
1018 inline bool operator<(const IntegerValType &IVT) const {
1019 return bits < IVT.bits;
1024 static ManagedStatic<TypeMap<IntegerValType, IntegerType> > IntegerTypes;
1026 const IntegerType *IntegerType::get(unsigned NumBits) {
1027 assert(NumBits >= MIN_INT_BITS && "bitwidth too small");
1028 assert(NumBits <= MAX_INT_BITS && "bitwidth too large");
1030 // Check for the built-in integer types
1032 case 1: return cast<IntegerType>(Type::Int1Ty);
1033 case 8: return cast<IntegerType>(Type::Int8Ty);
1034 case 16: return cast<IntegerType>(Type::Int16Ty);
1035 case 32: return cast<IntegerType>(Type::Int32Ty);
1036 case 64: return cast<IntegerType>(Type::Int64Ty);
1041 IntegerValType IVT(NumBits);
1042 IntegerType *ITy = IntegerTypes->get(IVT);
1043 if (ITy) return ITy; // Found a match, return it!
1045 // Value not found. Derive a new type!
1046 ITy = new IntegerType(NumBits);
1047 IntegerTypes->add(IVT, ITy);
1049 #ifdef DEBUG_MERGE_TYPES
1050 DOUT << "Derived new type: " << *ITy << "\n";
1055 bool IntegerType::isPowerOf2ByteWidth() const {
1056 unsigned BitWidth = getBitWidth();
1057 return (BitWidth > 7) && isPowerOf2_32(BitWidth);
1060 APInt IntegerType::getMask() const {
1061 return APInt::getAllOnesValue(getBitWidth());
1064 // FunctionValType - Define a class to hold the key that goes into the TypeMap
1067 class FunctionValType {
1069 std::vector<const Type*> ArgTypes;
1072 FunctionValType(const Type *ret, const std::vector<const Type*> &args,
1073 bool isVA) : RetTy(ret), ArgTypes(args), isVarArg(isVA) {}
1075 static FunctionValType get(const FunctionType *FT);
1077 static unsigned hashTypeStructure(const FunctionType *FT) {
1078 unsigned Result = FT->getNumParams()*2 + FT->isVarArg();
1082 inline bool operator<(const FunctionValType &MTV) const {
1083 if (RetTy < MTV.RetTy) return true;
1084 if (RetTy > MTV.RetTy) return false;
1085 if (isVarArg < MTV.isVarArg) return true;
1086 if (isVarArg > MTV.isVarArg) return false;
1087 if (ArgTypes < MTV.ArgTypes) return true;
1088 if (ArgTypes > MTV.ArgTypes) return false;
1094 // Define the actual map itself now...
1095 static ManagedStatic<TypeMap<FunctionValType, FunctionType> > FunctionTypes;
1097 FunctionValType FunctionValType::get(const FunctionType *FT) {
1098 // Build up a FunctionValType
1099 std::vector<const Type *> ParamTypes;
1100 ParamTypes.reserve(FT->getNumParams());
1101 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
1102 ParamTypes.push_back(FT->getParamType(i));
1103 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
1107 // FunctionType::get - The factory function for the FunctionType class...
1108 FunctionType *FunctionType::get(const Type *ReturnType,
1109 const std::vector<const Type*> &Params,
1111 FunctionValType VT(ReturnType, Params, isVarArg);
1112 FunctionType *FT = FunctionTypes->get(VT);
1116 FT = (FunctionType*) new char[sizeof(FunctionType) +
1117 sizeof(PATypeHandle)*(Params.size()+1)];
1118 new (FT) FunctionType(ReturnType, Params, isVarArg);
1119 FunctionTypes->add(VT, FT);
1121 #ifdef DEBUG_MERGE_TYPES
1122 DOUT << "Derived new type: " << FT << "\n";
1127 //===----------------------------------------------------------------------===//
1128 // Array Type Factory...
1131 class ArrayValType {
1135 ArrayValType(const Type *val, uint64_t sz) : ValTy(val), Size(sz) {}
1137 static ArrayValType get(const ArrayType *AT) {
1138 return ArrayValType(AT->getElementType(), AT->getNumElements());
1141 static unsigned hashTypeStructure(const ArrayType *AT) {
1142 return (unsigned)AT->getNumElements();
1145 inline bool operator<(const ArrayValType &MTV) const {
1146 if (Size < MTV.Size) return true;
1147 return Size == MTV.Size && ValTy < MTV.ValTy;
1151 static ManagedStatic<TypeMap<ArrayValType, ArrayType> > ArrayTypes;
1154 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
1155 assert(ElementType && "Can't get array of null types!");
1157 ArrayValType AVT(ElementType, NumElements);
1158 ArrayType *AT = ArrayTypes->get(AVT);
1159 if (AT) return AT; // Found a match, return it!
1161 // Value not found. Derive a new type!
1162 ArrayTypes->add(AVT, AT = new ArrayType(ElementType, NumElements));
1164 #ifdef DEBUG_MERGE_TYPES
1165 DOUT << "Derived new type: " << *AT << "\n";
1171 //===----------------------------------------------------------------------===//
1172 // Vector Type Factory...
1175 class VectorValType {
1179 VectorValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
1181 static VectorValType get(const VectorType *PT) {
1182 return VectorValType(PT->getElementType(), PT->getNumElements());
1185 static unsigned hashTypeStructure(const VectorType *PT) {
1186 return PT->getNumElements();
1189 inline bool operator<(const VectorValType &MTV) const {
1190 if (Size < MTV.Size) return true;
1191 return Size == MTV.Size && ValTy < MTV.ValTy;
1195 static ManagedStatic<TypeMap<VectorValType, VectorType> > VectorTypes;
1198 VectorType *VectorType::get(const Type *ElementType, unsigned NumElements) {
1199 assert(ElementType && "Can't get vector of null types!");
1201 VectorValType PVT(ElementType, NumElements);
1202 VectorType *PT = VectorTypes->get(PVT);
1203 if (PT) return PT; // Found a match, return it!
1205 // Value not found. Derive a new type!
1206 VectorTypes->add(PVT, PT = new VectorType(ElementType, NumElements));
1208 #ifdef DEBUG_MERGE_TYPES
1209 DOUT << "Derived new type: " << *PT << "\n";
1214 //===----------------------------------------------------------------------===//
1215 // Struct Type Factory...
1219 // StructValType - Define a class to hold the key that goes into the TypeMap
1221 class StructValType {
1222 std::vector<const Type*> ElTypes;
1225 StructValType(const std::vector<const Type*> &args, bool isPacked)
1226 : ElTypes(args), packed(isPacked) {}
1228 static StructValType get(const StructType *ST) {
1229 std::vector<const Type *> ElTypes;
1230 ElTypes.reserve(ST->getNumElements());
1231 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
1232 ElTypes.push_back(ST->getElementType(i));
1234 return StructValType(ElTypes, ST->isPacked());
1237 static unsigned hashTypeStructure(const StructType *ST) {
1238 return ST->getNumElements();
1241 inline bool operator<(const StructValType &STV) const {
1242 if (ElTypes < STV.ElTypes) return true;
1243 else if (ElTypes > STV.ElTypes) return false;
1244 else return (int)packed < (int)STV.packed;
1249 static ManagedStatic<TypeMap<StructValType, StructType> > StructTypes;
1251 StructType *StructType::get(const std::vector<const Type*> &ETypes,
1253 StructValType STV(ETypes, isPacked);
1254 StructType *ST = StructTypes->get(STV);
1257 // Value not found. Derive a new type!
1258 ST = (StructType*) new char[sizeof(StructType) +
1259 sizeof(PATypeHandle) * ETypes.size()];
1260 new (ST) StructType(ETypes, isPacked);
1261 StructTypes->add(STV, ST);
1263 #ifdef DEBUG_MERGE_TYPES
1264 DOUT << "Derived new type: " << *ST << "\n";
1269 StructType *StructType::get(const Type *type, ...) {
1271 std::vector<const llvm::Type*> StructFields;
1274 StructFields.push_back(type);
1275 type = va_arg(ap, llvm::Type*);
1277 return llvm::StructType::get(StructFields);
1282 //===----------------------------------------------------------------------===//
1283 // Pointer Type Factory...
1286 // PointerValType - Define a class to hold the key that goes into the TypeMap
1289 class PointerValType {
1291 unsigned AddressSpace;
1293 PointerValType(const Type *val, unsigned as) : ValTy(val), AddressSpace(as) {}
1295 static PointerValType get(const PointerType *PT) {
1296 return PointerValType(PT->getElementType(), PT->getAddressSpace());
1299 static unsigned hashTypeStructure(const PointerType *PT) {
1300 return getSubElementHash(PT);
1303 bool operator<(const PointerValType &MTV) const {
1304 if (AddressSpace < MTV.AddressSpace) return true;
1305 return AddressSpace == MTV.AddressSpace && ValTy < MTV.ValTy;
1310 static ManagedStatic<TypeMap<PointerValType, PointerType> > PointerTypes;
1312 PointerType *PointerType::get(const Type *ValueType, unsigned AddressSpace) {
1313 assert(ValueType && "Can't get a pointer to <null> type!");
1314 assert(ValueType != Type::VoidTy &&
1315 "Pointer to void is not valid, use sbyte* instead!");
1316 assert(ValueType != Type::LabelTy && "Pointer to label is not valid!");
1317 PointerValType PVT(ValueType, AddressSpace);
1319 PointerType *PT = PointerTypes->get(PVT);
1322 // Value not found. Derive a new type!
1323 PointerTypes->add(PVT, PT = new PointerType(ValueType, AddressSpace));
1325 #ifdef DEBUG_MERGE_TYPES
1326 DOUT << "Derived new type: " << *PT << "\n";
1331 //===----------------------------------------------------------------------===//
1332 // Derived Type Refinement Functions
1333 //===----------------------------------------------------------------------===//
1335 // removeAbstractTypeUser - Notify an abstract type that a user of the class
1336 // no longer has a handle to the type. This function is called primarily by
1337 // the PATypeHandle class. When there are no users of the abstract type, it
1338 // is annihilated, because there is no way to get a reference to it ever again.
1340 void Type::removeAbstractTypeUser(AbstractTypeUser *U) const {
1341 // Search from back to front because we will notify users from back to
1342 // front. Also, it is likely that there will be a stack like behavior to
1343 // users that register and unregister users.
1346 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1347 assert(i != 0 && "AbstractTypeUser not in user list!");
1349 --i; // Convert to be in range 0 <= i < size()
1350 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
1352 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1354 #ifdef DEBUG_MERGE_TYPES
1355 DOUT << " remAbstractTypeUser[" << (void*)this << ", "
1356 << *this << "][" << i << "] User = " << U << "\n";
1359 if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1360 #ifdef DEBUG_MERGE_TYPES
1361 DOUT << "DELETEing unused abstract type: <" << *this
1362 << ">[" << (void*)this << "]" << "\n";
1368 // refineAbstractTypeTo - This function is used when it is discovered that
1369 // the 'this' abstract type is actually equivalent to the NewType specified.
1370 // This causes all users of 'this' to switch to reference the more concrete type
1371 // NewType and for 'this' to be deleted.
1373 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1374 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1375 assert(this != NewType && "Can't refine to myself!");
1376 assert(ForwardType == 0 && "This type has already been refined!");
1378 // The descriptions may be out of date. Conservatively clear them all!
1379 AbstractTypeDescriptions->clear();
1381 #ifdef DEBUG_MERGE_TYPES
1382 DOUT << "REFINING abstract type [" << (void*)this << " "
1383 << *this << "] to [" << (void*)NewType << " "
1384 << *NewType << "]!\n";
1387 // Make sure to put the type to be refined to into a holder so that if IT gets
1388 // refined, that we will not continue using a dead reference...
1390 PATypeHolder NewTy(NewType);
1392 // Any PATypeHolders referring to this type will now automatically forward to
1393 // the type we are resolved to.
1394 ForwardType = NewType;
1395 if (NewType->isAbstract())
1396 cast<DerivedType>(NewType)->addRef();
1398 // Add a self use of the current type so that we don't delete ourself until
1399 // after the function exits.
1401 PATypeHolder CurrentTy(this);
1403 // To make the situation simpler, we ask the subclass to remove this type from
1404 // the type map, and to replace any type uses with uses of non-abstract types.
1405 // This dramatically limits the amount of recursive type trouble we can find
1409 // Iterate over all of the uses of this type, invoking callback. Each user
1410 // should remove itself from our use list automatically. We have to check to
1411 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1412 // will not cause users to drop off of the use list. If we resolve to ourself
1415 while (!AbstractTypeUsers.empty() && NewTy != this) {
1416 AbstractTypeUser *User = AbstractTypeUsers.back();
1418 unsigned OldSize = AbstractTypeUsers.size();
1419 #ifdef DEBUG_MERGE_TYPES
1420 DOUT << " REFINING user " << OldSize-1 << "[" << (void*)User
1421 << "] of abstract type [" << (void*)this << " "
1422 << *this << "] to [" << (void*)NewTy.get() << " "
1423 << *NewTy << "]!\n";
1425 User->refineAbstractType(this, NewTy);
1427 assert(AbstractTypeUsers.size() != OldSize &&
1428 "AbsTyUser did not remove self from user list!");
1431 // If we were successful removing all users from the type, 'this' will be
1432 // deleted when the last PATypeHolder is destroyed or updated from this type.
1433 // This may occur on exit of this function, as the CurrentTy object is
1437 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1438 // the current type has transitioned from being abstract to being concrete.
1440 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1441 #ifdef DEBUG_MERGE_TYPES
1442 DOUT << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1445 unsigned OldSize = AbstractTypeUsers.size();
1446 while (!AbstractTypeUsers.empty()) {
1447 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1448 ATU->typeBecameConcrete(this);
1450 assert(AbstractTypeUsers.size() < OldSize-- &&
1451 "AbstractTypeUser did not remove itself from the use list!");
1455 // refineAbstractType - Called when a contained type is found to be more
1456 // concrete - this could potentially change us from an abstract type to a
1459 void FunctionType::refineAbstractType(const DerivedType *OldType,
1460 const Type *NewType) {
1461 FunctionTypes->RefineAbstractType(this, OldType, NewType);
1464 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1465 FunctionTypes->TypeBecameConcrete(this, AbsTy);
1469 // refineAbstractType - Called when a contained type is found to be more
1470 // concrete - this could potentially change us from an abstract type to a
1473 void ArrayType::refineAbstractType(const DerivedType *OldType,
1474 const Type *NewType) {
1475 ArrayTypes->RefineAbstractType(this, OldType, NewType);
1478 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1479 ArrayTypes->TypeBecameConcrete(this, AbsTy);
1482 // refineAbstractType - Called when a contained type is found to be more
1483 // concrete - this could potentially change us from an abstract type to a
1486 void VectorType::refineAbstractType(const DerivedType *OldType,
1487 const Type *NewType) {
1488 VectorTypes->RefineAbstractType(this, OldType, NewType);
1491 void VectorType::typeBecameConcrete(const DerivedType *AbsTy) {
1492 VectorTypes->TypeBecameConcrete(this, AbsTy);
1495 // refineAbstractType - Called when a contained type is found to be more
1496 // concrete - this could potentially change us from an abstract type to a
1499 void StructType::refineAbstractType(const DerivedType *OldType,
1500 const Type *NewType) {
1501 StructTypes->RefineAbstractType(this, OldType, NewType);
1504 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1505 StructTypes->TypeBecameConcrete(this, AbsTy);
1508 // refineAbstractType - Called when a contained type is found to be more
1509 // concrete - this could potentially change us from an abstract type to a
1512 void PointerType::refineAbstractType(const DerivedType *OldType,
1513 const Type *NewType) {
1514 PointerTypes->RefineAbstractType(this, OldType, NewType);
1517 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1518 PointerTypes->TypeBecameConcrete(this, AbsTy);
1521 bool SequentialType::indexValid(const Value *V) const {
1522 if (const IntegerType *IT = dyn_cast<IntegerType>(V->getType()))
1523 return IT->getBitWidth() == 32 || IT->getBitWidth() == 64;
1528 std::ostream &operator<<(std::ostream &OS, const Type *T) {
1530 OS << "<null> value!\n";
1536 std::ostream &operator<<(std::ostream &OS, const Type &T) {