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/Assembly/Writer.h"
17 #include "llvm/ADT/DepthFirstIterator.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/SCCIterator.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/System/Mutex.h"
27 #include "llvm/System/RWMutex.h"
28 #include "llvm/System/Threading.h"
33 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
34 // created and later destroyed, all in an effort to make sure that there is only
35 // a single canonical version of a type.
37 // #define DEBUG_MERGE_TYPES 1
39 AbstractTypeUser::~AbstractTypeUser() {}
42 //===----------------------------------------------------------------------===//
43 // Type Class Implementation
44 //===----------------------------------------------------------------------===//
46 // Lock used for guarding access to the type maps.
47 static ManagedStatic<sys::SmartMutex<true> > TypeMapLock;
49 // Recursive lock used for guarding access to AbstractTypeUsers.
50 // NOTE: The true template parameter means this will no-op when we're not in
51 // multithreaded mode.
52 static ManagedStatic<sys::SmartMutex<true> > AbstractTypeUsersLock;
54 // Concrete/Abstract TypeDescriptions - We lazily calculate type descriptions
55 // for types as they are needed. Because resolution of types must invalidate
56 // all of the abstract type descriptions, we keep them in a seperate map to make
58 static ManagedStatic<TypePrinting> ConcreteTypeDescriptions;
59 static ManagedStatic<TypePrinting> AbstractTypeDescriptions;
61 /// Because of the way Type subclasses are allocated, this function is necessary
62 /// to use the correct kind of "delete" operator to deallocate the Type object.
63 /// Some type objects (FunctionTy, StructTy) allocate additional space after
64 /// the space for their derived type to hold the contained types array of
65 /// PATypeHandles. Using this allocation scheme means all the PATypeHandles are
66 /// allocated with the type object, decreasing allocations and eliminating the
67 /// need for a std::vector to be used in the Type class itself.
68 /// @brief Type destruction function
69 void Type::destroy() const {
71 // Structures and Functions allocate their contained types past the end of
72 // the type object itself. These need to be destroyed differently than the
74 if (isa<FunctionType>(this) || isa<StructType>(this)) {
75 // First, make sure we destruct any PATypeHandles allocated by these
76 // subclasses. They must be manually destructed.
77 for (unsigned i = 0; i < NumContainedTys; ++i)
78 ContainedTys[i].PATypeHandle::~PATypeHandle();
80 // Now call the destructor for the subclass directly because we're going
81 // to delete this as an array of char.
82 if (isa<FunctionType>(this))
83 static_cast<const FunctionType*>(this)->FunctionType::~FunctionType();
85 static_cast<const StructType*>(this)->StructType::~StructType();
87 // Finally, remove the memory as an array deallocation of the chars it was
89 operator delete(const_cast<Type *>(this));
94 // For all the other type subclasses, there is either no contained types or
95 // just one (all Sequentials). For Sequentials, the PATypeHandle is not
96 // allocated past the type object, its included directly in the SequentialType
97 // class. This means we can safely just do "normal" delete of this object and
98 // all the destructors that need to run will be run.
102 const Type *Type::getPrimitiveType(TypeID IDNumber) {
104 case VoidTyID : return VoidTy;
105 case FloatTyID : return FloatTy;
106 case DoubleTyID : return DoubleTy;
107 case X86_FP80TyID : return X86_FP80Ty;
108 case FP128TyID : return FP128Ty;
109 case PPC_FP128TyID : return PPC_FP128Ty;
110 case LabelTyID : return LabelTy;
111 case MetadataTyID : return MetadataTy;
117 const Type *Type::getVAArgsPromotedType() const {
118 if (ID == IntegerTyID && getSubclassData() < 32)
119 return Type::Int32Ty;
120 else if (ID == FloatTyID)
121 return Type::DoubleTy;
126 /// getScalarType - If this is a vector type, return the element type,
127 /// otherwise return this.
128 const Type *Type::getScalarType() const {
129 if (const VectorType *VTy = dyn_cast<VectorType>(this))
130 return VTy->getElementType();
134 /// isIntOrIntVector - Return true if this is an integer type or a vector of
137 bool Type::isIntOrIntVector() const {
140 if (ID != Type::VectorTyID) return false;
142 return cast<VectorType>(this)->getElementType()->isInteger();
145 /// isFPOrFPVector - Return true if this is a FP type or a vector of FP types.
147 bool Type::isFPOrFPVector() const {
148 if (ID == Type::FloatTyID || ID == Type::DoubleTyID ||
149 ID == Type::FP128TyID || ID == Type::X86_FP80TyID ||
150 ID == Type::PPC_FP128TyID)
152 if (ID != Type::VectorTyID) return false;
154 return cast<VectorType>(this)->getElementType()->isFloatingPoint();
157 // canLosslesslyBitCastTo - Return true if this type can be converted to
158 // 'Ty' without any reinterpretation of bits. For example, i8* to i32*.
160 bool Type::canLosslesslyBitCastTo(const Type *Ty) const {
161 // Identity cast means no change so return true
165 // They are not convertible unless they are at least first class types
166 if (!this->isFirstClassType() || !Ty->isFirstClassType())
169 // Vector -> Vector conversions are always lossless if the two vector types
170 // have the same size, otherwise not.
171 if (const VectorType *thisPTy = dyn_cast<VectorType>(this))
172 if (const VectorType *thatPTy = dyn_cast<VectorType>(Ty))
173 return thisPTy->getBitWidth() == thatPTy->getBitWidth();
175 // At this point we have only various mismatches of the first class types
176 // remaining and ptr->ptr. Just select the lossless conversions. Everything
177 // else is not lossless.
178 if (isa<PointerType>(this))
179 return isa<PointerType>(Ty);
180 return false; // Other types have no identity values
183 unsigned Type::getPrimitiveSizeInBits() const {
184 switch (getTypeID()) {
185 case Type::FloatTyID: return 32;
186 case Type::DoubleTyID: return 64;
187 case Type::X86_FP80TyID: return 80;
188 case Type::FP128TyID: return 128;
189 case Type::PPC_FP128TyID: return 128;
190 case Type::IntegerTyID: return cast<IntegerType>(this)->getBitWidth();
191 case Type::VectorTyID: return cast<VectorType>(this)->getBitWidth();
196 /// getScalarSizeInBits - If this is a vector type, return the
197 /// getPrimitiveSizeInBits value for the element type. Otherwise return the
198 /// getPrimitiveSizeInBits value for this type.
199 unsigned Type::getScalarSizeInBits() const {
200 return getScalarType()->getPrimitiveSizeInBits();
203 /// getFPMantissaWidth - Return the width of the mantissa of this type. This
204 /// is only valid on floating point types. If the FP type does not
205 /// have a stable mantissa (e.g. ppc long double), this method returns -1.
206 int Type::getFPMantissaWidth() const {
207 if (const VectorType *VTy = dyn_cast<VectorType>(this))
208 return VTy->getElementType()->getFPMantissaWidth();
209 assert(isFloatingPoint() && "Not a floating point type!");
210 if (ID == FloatTyID) return 24;
211 if (ID == DoubleTyID) return 53;
212 if (ID == X86_FP80TyID) return 64;
213 if (ID == FP128TyID) return 113;
214 assert(ID == PPC_FP128TyID && "unknown fp type");
218 /// isSizedDerivedType - Derived types like structures and arrays are sized
219 /// iff all of the members of the type are sized as well. Since asking for
220 /// their size is relatively uncommon, move this operation out of line.
221 bool Type::isSizedDerivedType() const {
222 if (isa<IntegerType>(this))
225 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
226 return ATy->getElementType()->isSized();
228 if (const VectorType *PTy = dyn_cast<VectorType>(this))
229 return PTy->getElementType()->isSized();
231 if (!isa<StructType>(this))
234 // Okay, our struct is sized if all of the elements are...
235 for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I)
236 if (!(*I)->isSized())
242 /// getForwardedTypeInternal - This method is used to implement the union-find
243 /// algorithm for when a type is being forwarded to another type.
244 const Type *Type::getForwardedTypeInternal() const {
245 assert(ForwardType && "This type is not being forwarded to another type!");
247 // Check to see if the forwarded type has been forwarded on. If so, collapse
248 // the forwarding links.
249 const Type *RealForwardedType = ForwardType->getForwardedType();
250 if (!RealForwardedType)
251 return ForwardType; // No it's not forwarded again
253 // Yes, it is forwarded again. First thing, add the reference to the new
255 if (RealForwardedType->isAbstract())
256 cast<DerivedType>(RealForwardedType)->addRef();
258 // Now drop the old reference. This could cause ForwardType to get deleted.
259 cast<DerivedType>(ForwardType)->dropRef();
261 // Return the updated type.
262 ForwardType = RealForwardedType;
266 void Type::refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
269 void Type::typeBecameConcrete(const DerivedType *AbsTy) {
274 std::string Type::getDescription() const {
276 isAbstract() ? *AbstractTypeDescriptions : *ConcreteTypeDescriptions;
279 raw_string_ostream DescOS(DescStr);
280 Map.print(this, DescOS);
285 bool StructType::indexValid(const Value *V) const {
286 // Structure indexes require 32-bit integer constants.
287 if (V->getType() == Type::Int32Ty)
288 if (const ConstantInt *CU = dyn_cast<ConstantInt>(V))
289 return indexValid(CU->getZExtValue());
293 bool StructType::indexValid(unsigned V) const {
294 return V < NumContainedTys;
297 // getTypeAtIndex - Given an index value into the type, return the type of the
298 // element. For a structure type, this must be a constant value...
300 const Type *StructType::getTypeAtIndex(const Value *V) const {
301 unsigned Idx = (unsigned)cast<ConstantInt>(V)->getZExtValue();
302 return getTypeAtIndex(Idx);
305 const Type *StructType::getTypeAtIndex(unsigned Idx) const {
306 assert(indexValid(Idx) && "Invalid structure index!");
307 return ContainedTys[Idx];
310 //===----------------------------------------------------------------------===//
311 // Primitive 'Type' data
312 //===----------------------------------------------------------------------===//
314 const Type *Type::VoidTy = new Type(Type::VoidTyID);
315 const Type *Type::FloatTy = new Type(Type::FloatTyID);
316 const Type *Type::DoubleTy = new Type(Type::DoubleTyID);
317 const Type *Type::X86_FP80Ty = new Type(Type::X86_FP80TyID);
318 const Type *Type::FP128Ty = new Type(Type::FP128TyID);
319 const Type *Type::PPC_FP128Ty = new Type(Type::PPC_FP128TyID);
320 const Type *Type::LabelTy = new Type(Type::LabelTyID);
321 const Type *Type::MetadataTy = new Type(Type::MetadataTyID);
324 struct BuiltinIntegerType : public IntegerType {
325 explicit BuiltinIntegerType(unsigned W) : IntegerType(W) {}
328 const IntegerType *Type::Int1Ty = new BuiltinIntegerType(1);
329 const IntegerType *Type::Int8Ty = new BuiltinIntegerType(8);
330 const IntegerType *Type::Int16Ty = new BuiltinIntegerType(16);
331 const IntegerType *Type::Int32Ty = new BuiltinIntegerType(32);
332 const IntegerType *Type::Int64Ty = new BuiltinIntegerType(64);
334 //===----------------------------------------------------------------------===//
335 // Derived Type Constructors
336 //===----------------------------------------------------------------------===//
338 /// isValidReturnType - Return true if the specified type is valid as a return
340 bool FunctionType::isValidReturnType(const Type *RetTy) {
341 if (RetTy->isFirstClassType()) {
342 if (const PointerType *PTy = dyn_cast<PointerType>(RetTy))
343 return PTy->getElementType() != Type::MetadataTy;
346 if (RetTy == Type::VoidTy || RetTy == Type::MetadataTy ||
347 isa<OpaqueType>(RetTy))
350 // If this is a multiple return case, verify that each return is a first class
351 // value and that there is at least one value.
352 const StructType *SRetTy = dyn_cast<StructType>(RetTy);
353 if (SRetTy == 0 || SRetTy->getNumElements() == 0)
356 for (unsigned i = 0, e = SRetTy->getNumElements(); i != e; ++i)
357 if (!SRetTy->getElementType(i)->isFirstClassType())
362 /// isValidArgumentType - Return true if the specified type is valid as an
364 bool FunctionType::isValidArgumentType(const Type *ArgTy) {
365 if ((!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy)) ||
366 (isa<PointerType>(ArgTy) &&
367 cast<PointerType>(ArgTy)->getElementType() == Type::MetadataTy))
373 FunctionType::FunctionType(const Type *Result,
374 const std::vector<const Type*> &Params,
376 : DerivedType(FunctionTyID), isVarArgs(IsVarArgs) {
377 ContainedTys = reinterpret_cast<PATypeHandle*>(this+1);
378 NumContainedTys = Params.size() + 1; // + 1 for result type
379 assert(isValidReturnType(Result) && "invalid return type for function");
382 bool isAbstract = Result->isAbstract();
383 new (&ContainedTys[0]) PATypeHandle(Result, this);
385 for (unsigned i = 0; i != Params.size(); ++i) {
386 assert(isValidArgumentType(Params[i]) &&
387 "Not a valid type for function argument!");
388 new (&ContainedTys[i+1]) PATypeHandle(Params[i], this);
389 isAbstract |= Params[i]->isAbstract();
392 // Calculate whether or not this type is abstract
393 setAbstract(isAbstract);
396 StructType::StructType(const std::vector<const Type*> &Types, bool isPacked)
397 : CompositeType(StructTyID) {
398 ContainedTys = reinterpret_cast<PATypeHandle*>(this + 1);
399 NumContainedTys = Types.size();
400 setSubclassData(isPacked);
401 bool isAbstract = false;
402 for (unsigned i = 0; i < Types.size(); ++i) {
403 assert(Types[i] && "<null> type for structure field!");
404 assert(isValidElementType(Types[i]) &&
405 "Invalid type for structure element!");
406 new (&ContainedTys[i]) PATypeHandle(Types[i], this);
407 isAbstract |= Types[i]->isAbstract();
410 // Calculate whether or not this type is abstract
411 setAbstract(isAbstract);
414 ArrayType::ArrayType(const Type *ElType, uint64_t NumEl)
415 : SequentialType(ArrayTyID, ElType) {
418 // Calculate whether or not this type is abstract
419 setAbstract(ElType->isAbstract());
422 VectorType::VectorType(const Type *ElType, unsigned NumEl)
423 : SequentialType(VectorTyID, ElType) {
425 setAbstract(ElType->isAbstract());
426 assert(NumEl > 0 && "NumEl of a VectorType must be greater than 0");
427 assert(isValidElementType(ElType) &&
428 "Elements of a VectorType must be a primitive type");
433 PointerType::PointerType(const Type *E, unsigned AddrSpace)
434 : SequentialType(PointerTyID, E) {
435 AddressSpace = AddrSpace;
436 // Calculate whether or not this type is abstract
437 setAbstract(E->isAbstract());
440 OpaqueType::OpaqueType() : DerivedType(OpaqueTyID) {
442 #ifdef DEBUG_MERGE_TYPES
443 DOUT << "Derived new type: " << *this << "\n";
447 void PATypeHolder::destroy() {
451 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
452 // another (more concrete) type, we must eliminate all references to other
453 // types, to avoid some circular reference problems.
454 void DerivedType::dropAllTypeUses() {
455 if (NumContainedTys != 0) {
456 // The type must stay abstract. To do this, we insert a pointer to a type
457 // that will never get resolved, thus will always be abstract.
458 static Type *AlwaysOpaqueTy = 0;
459 static PATypeHolder* Holder = 0;
460 Type *tmp = AlwaysOpaqueTy;
461 if (llvm_is_multithreaded()) {
464 llvm_acquire_global_lock();
465 tmp = AlwaysOpaqueTy;
467 tmp = OpaqueType::get();
468 PATypeHolder* tmp2 = new PATypeHolder(AlwaysOpaqueTy);
470 AlwaysOpaqueTy = tmp;
474 llvm_release_global_lock();
477 AlwaysOpaqueTy = OpaqueType::get();
478 Holder = new PATypeHolder(AlwaysOpaqueTy);
481 ContainedTys[0] = AlwaysOpaqueTy;
483 // Change the rest of the types to be Int32Ty's. It doesn't matter what we
484 // pick so long as it doesn't point back to this type. We choose something
485 // concrete to avoid overhead for adding to AbstracTypeUser lists and stuff.
486 for (unsigned i = 1, e = NumContainedTys; i != e; ++i)
487 ContainedTys[i] = Type::Int32Ty;
494 /// TypePromotionGraph and graph traits - this is designed to allow us to do
495 /// efficient SCC processing of type graphs. This is the exact same as
496 /// GraphTraits<Type*>, except that we pretend that concrete types have no
497 /// children to avoid processing them.
498 struct TypePromotionGraph {
500 TypePromotionGraph(Type *T) : Ty(T) {}
506 template <> struct GraphTraits<TypePromotionGraph> {
507 typedef Type NodeType;
508 typedef Type::subtype_iterator ChildIteratorType;
510 static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
511 static inline ChildIteratorType child_begin(NodeType *N) {
513 return N->subtype_begin();
514 else // No need to process children of concrete types.
515 return N->subtype_end();
517 static inline ChildIteratorType child_end(NodeType *N) {
518 return N->subtype_end();
524 // PromoteAbstractToConcrete - This is a recursive function that walks a type
525 // graph calculating whether or not a type is abstract.
527 void Type::PromoteAbstractToConcrete() {
528 if (!isAbstract()) return;
530 scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
531 scc_iterator<TypePromotionGraph> SE = scc_end (TypePromotionGraph(this));
533 for (; SI != SE; ++SI) {
534 std::vector<Type*> &SCC = *SI;
536 // Concrete types are leaves in the tree. Since an SCC will either be all
537 // abstract or all concrete, we only need to check one type.
538 if (SCC[0]->isAbstract()) {
539 if (isa<OpaqueType>(SCC[0]))
540 return; // Not going to be concrete, sorry.
542 // If all of the children of all of the types in this SCC are concrete,
543 // then this SCC is now concrete as well. If not, neither this SCC, nor
544 // any parent SCCs will be concrete, so we might as well just exit.
545 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
546 for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
547 E = SCC[i]->subtype_end(); CI != E; ++CI)
548 if ((*CI)->isAbstract())
549 // If the child type is in our SCC, it doesn't make the entire SCC
550 // abstract unless there is a non-SCC abstract type.
551 if (std::find(SCC.begin(), SCC.end(), *CI) == SCC.end())
552 return; // Not going to be concrete, sorry.
554 // Okay, we just discovered this whole SCC is now concrete, mark it as
556 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
557 assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
559 SCC[i]->setAbstract(false);
562 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
563 assert(!SCC[i]->isAbstract() && "Concrete type became abstract?");
564 // The type just became concrete, notify all users!
565 cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
572 //===----------------------------------------------------------------------===//
573 // Type Structural Equality Testing
574 //===----------------------------------------------------------------------===//
576 // TypesEqual - Two types are considered structurally equal if they have the
577 // same "shape": Every level and element of the types have identical primitive
578 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
579 // be pointer equals to be equivalent though. This uses an optimistic algorithm
580 // that assumes that two graphs are the same until proven otherwise.
582 static bool TypesEqual(const Type *Ty, const Type *Ty2,
583 std::map<const Type *, const Type *> &EqTypes) {
584 if (Ty == Ty2) return true;
585 if (Ty->getTypeID() != Ty2->getTypeID()) return false;
586 if (isa<OpaqueType>(Ty))
587 return false; // Two unequal opaque types are never equal
589 std::map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
590 if (It != EqTypes.end())
591 return It->second == Ty2; // Looping back on a type, check for equality
593 // Otherwise, add the mapping to the table to make sure we don't get
594 // recursion on the types...
595 EqTypes.insert(It, std::make_pair(Ty, Ty2));
597 // Two really annoying special cases that breaks an otherwise nice simple
598 // algorithm is the fact that arraytypes have sizes that differentiates types,
599 // and that function types can be varargs or not. Consider this now.
601 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
602 const IntegerType *ITy2 = cast<IntegerType>(Ty2);
603 return ITy->getBitWidth() == ITy2->getBitWidth();
604 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
605 const PointerType *PTy2 = cast<PointerType>(Ty2);
606 return PTy->getAddressSpace() == PTy2->getAddressSpace() &&
607 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
608 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
609 const StructType *STy2 = cast<StructType>(Ty2);
610 if (STy->getNumElements() != STy2->getNumElements()) return false;
611 if (STy->isPacked() != STy2->isPacked()) return false;
612 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
613 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
616 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
617 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
618 return ATy->getNumElements() == ATy2->getNumElements() &&
619 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
620 } else if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
621 const VectorType *PTy2 = cast<VectorType>(Ty2);
622 return PTy->getNumElements() == PTy2->getNumElements() &&
623 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
624 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
625 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
626 if (FTy->isVarArg() != FTy2->isVarArg() ||
627 FTy->getNumParams() != FTy2->getNumParams() ||
628 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
630 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i) {
631 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
636 assert(0 && "Unknown derived type!");
641 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
642 std::map<const Type *, const Type *> EqTypes;
643 return TypesEqual(Ty, Ty2, EqTypes);
646 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
647 // TargetTy in the type graph. We know that Ty is an abstract type, so if we
648 // ever reach a non-abstract type, we know that we don't need to search the
650 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
651 SmallPtrSet<const Type*, 128> &VisitedTypes) {
652 if (TargetTy == CurTy) return true;
653 if (!CurTy->isAbstract()) return false;
655 if (!VisitedTypes.insert(CurTy))
656 return false; // Already been here.
658 for (Type::subtype_iterator I = CurTy->subtype_begin(),
659 E = CurTy->subtype_end(); I != E; ++I)
660 if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
665 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
666 SmallPtrSet<const Type*, 128> &VisitedTypes) {
667 if (TargetTy == CurTy) return true;
669 if (!VisitedTypes.insert(CurTy))
670 return false; // Already been here.
672 for (Type::subtype_iterator I = CurTy->subtype_begin(),
673 E = CurTy->subtype_end(); I != E; ++I)
674 if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
679 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
681 static bool TypeHasCycleThroughItself(const Type *Ty) {
682 SmallPtrSet<const Type*, 128> VisitedTypes;
684 if (Ty->isAbstract()) { // Optimized case for abstract types.
685 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
687 if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
690 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
692 if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
698 /// getSubElementHash - Generate a hash value for all of the SubType's of this
699 /// type. The hash value is guaranteed to be zero if any of the subtypes are
700 /// an opaque type. Otherwise we try to mix them in as well as possible, but do
701 /// not look at the subtype's subtype's.
702 static unsigned getSubElementHash(const Type *Ty) {
703 unsigned HashVal = 0;
704 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
707 const Type *SubTy = I->get();
708 HashVal += SubTy->getTypeID();
709 switch (SubTy->getTypeID()) {
711 case Type::OpaqueTyID: return 0; // Opaque -> hash = 0 no matter what.
712 case Type::IntegerTyID:
713 HashVal ^= (cast<IntegerType>(SubTy)->getBitWidth() << 3);
715 case Type::FunctionTyID:
716 HashVal ^= cast<FunctionType>(SubTy)->getNumParams()*2 +
717 cast<FunctionType>(SubTy)->isVarArg();
719 case Type::ArrayTyID:
720 HashVal ^= cast<ArrayType>(SubTy)->getNumElements();
722 case Type::VectorTyID:
723 HashVal ^= cast<VectorType>(SubTy)->getNumElements();
725 case Type::StructTyID:
726 HashVal ^= cast<StructType>(SubTy)->getNumElements();
728 case Type::PointerTyID:
729 HashVal ^= cast<PointerType>(SubTy)->getAddressSpace();
733 return HashVal ? HashVal : 1; // Do not return zero unless opaque subty.
736 //===----------------------------------------------------------------------===//
737 // Derived Type Factory Functions
738 //===----------------------------------------------------------------------===//
743 /// TypesByHash - Keep track of types by their structure hash value. Note
744 /// that we only keep track of types that have cycles through themselves in
747 std::multimap<unsigned, PATypeHolder> TypesByHash;
751 // PATypeHolder won't destroy non-abstract types.
752 // We can't destroy them by simply iterating, because
753 // they may contain references to each-other.
755 for (std::multimap<unsigned, PATypeHolder>::iterator I
756 = TypesByHash.begin(), E = TypesByHash.end(); I != E; ++I) {
757 Type *Ty = const_cast<Type*>(I->second.Ty);
759 // We can't invoke destroy or delete, because the type may
760 // contain references to already freed types.
761 // So we have to destruct the object the ugly way.
763 Ty->AbstractTypeUsers.clear();
764 static_cast<const Type*>(Ty)->Type::~Type();
771 void RemoveFromTypesByHash(unsigned Hash, const Type *Ty) {
772 std::multimap<unsigned, PATypeHolder>::iterator I =
773 TypesByHash.lower_bound(Hash);
774 for (; I != TypesByHash.end() && I->first == Hash; ++I) {
775 if (I->second == Ty) {
776 TypesByHash.erase(I);
781 // This must be do to an opaque type that was resolved. Switch down to hash
783 assert(Hash && "Didn't find type entry!");
784 RemoveFromTypesByHash(0, Ty);
787 /// TypeBecameConcrete - When Ty gets a notification that TheType just became
788 /// concrete, drop uses and make Ty non-abstract if we should.
789 void TypeBecameConcrete(DerivedType *Ty, const DerivedType *TheType) {
790 // If the element just became concrete, remove 'ty' from the abstract
791 // type user list for the type. Do this for as many times as Ty uses
793 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
795 if (I->get() == TheType)
796 TheType->removeAbstractTypeUser(Ty);
798 // If the type is currently thought to be abstract, rescan all of our
799 // subtypes to see if the type has just become concrete! Note that this
800 // may send out notifications to AbstractTypeUsers that types become
802 if (Ty->isAbstract())
803 Ty->PromoteAbstractToConcrete();
809 // TypeMap - Make sure that only one instance of a particular type may be
810 // created on any given run of the compiler... note that this involves updating
811 // our map if an abstract type gets refined somehow.
814 template<class ValType, class TypeClass>
815 class TypeMap : public TypeMapBase {
816 std::map<ValType, PATypeHolder> Map;
818 typedef typename std::map<ValType, PATypeHolder>::iterator iterator;
819 ~TypeMap() { print("ON EXIT"); }
821 inline TypeClass *get(const ValType &V) {
822 iterator I = Map.find(V);
823 return I != Map.end() ? cast<TypeClass>((Type*)I->second.get()) : 0;
826 inline void add(const ValType &V, TypeClass *Ty) {
827 Map.insert(std::make_pair(V, Ty));
829 // If this type has a cycle, remember it.
830 TypesByHash.insert(std::make_pair(ValType::hashTypeStructure(Ty), Ty));
834 /// RefineAbstractType - This method is called after we have merged a type
835 /// with another one. We must now either merge the type away with
836 /// some other type or reinstall it in the map with it's new configuration.
837 void RefineAbstractType(TypeClass *Ty, const DerivedType *OldType,
838 const Type *NewType) {
839 #ifdef DEBUG_MERGE_TYPES
840 DOUT << "RefineAbstractType(" << (void*)OldType << "[" << *OldType
841 << "], " << (void*)NewType << " [" << *NewType << "])\n";
844 // Otherwise, we are changing one subelement type into another. Clearly the
845 // OldType must have been abstract, making us abstract.
846 assert(Ty->isAbstract() && "Refining a non-abstract type!");
847 assert(OldType != NewType);
849 // Make a temporary type holder for the type so that it doesn't disappear on
850 // us when we erase the entry from the map.
851 PATypeHolder TyHolder = Ty;
853 // The old record is now out-of-date, because one of the children has been
854 // updated. Remove the obsolete entry from the map.
855 unsigned NumErased = Map.erase(ValType::get(Ty));
856 assert(NumErased && "Element not found!"); NumErased = NumErased;
858 // Remember the structural hash for the type before we start hacking on it,
859 // in case we need it later.
860 unsigned OldTypeHash = ValType::hashTypeStructure(Ty);
862 // Find the type element we are refining... and change it now!
863 for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i)
864 if (Ty->ContainedTys[i] == OldType)
865 Ty->ContainedTys[i] = NewType;
866 unsigned NewTypeHash = ValType::hashTypeStructure(Ty);
868 // If there are no cycles going through this node, we can do a simple,
869 // efficient lookup in the map, instead of an inefficient nasty linear
871 if (!TypeHasCycleThroughItself(Ty)) {
872 typename std::map<ValType, PATypeHolder>::iterator I;
875 tie(I, Inserted) = Map.insert(std::make_pair(ValType::get(Ty), Ty));
877 // Refined to a different type altogether?
878 RemoveFromTypesByHash(OldTypeHash, Ty);
880 // We already have this type in the table. Get rid of the newly refined
882 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
883 Ty->unlockedRefineAbstractTypeTo(NewTy);
887 // Now we check to see if there is an existing entry in the table which is
888 // structurally identical to the newly refined type. If so, this type
889 // gets refined to the pre-existing type.
891 std::multimap<unsigned, PATypeHolder>::iterator I, E, Entry;
892 tie(I, E) = TypesByHash.equal_range(NewTypeHash);
894 for (; I != E; ++I) {
895 if (I->second == Ty) {
896 // Remember the position of the old type if we see it in our scan.
899 if (TypesEqual(Ty, I->second)) {
900 TypeClass *NewTy = cast<TypeClass>((Type*)I->second.get());
902 // Remove the old entry form TypesByHash. If the hash values differ
903 // now, remove it from the old place. Otherwise, continue scanning
904 // withing this hashcode to reduce work.
905 if (NewTypeHash != OldTypeHash) {
906 RemoveFromTypesByHash(OldTypeHash, Ty);
909 // Find the location of Ty in the TypesByHash structure if we
910 // haven't seen it already.
911 while (I->second != Ty) {
913 assert(I != E && "Structure doesn't contain type??");
917 TypesByHash.erase(Entry);
919 Ty->unlockedRefineAbstractTypeTo(NewTy);
925 // If there is no existing type of the same structure, we reinsert an
926 // updated record into the map.
927 Map.insert(std::make_pair(ValType::get(Ty), Ty));
930 // If the hash codes differ, update TypesByHash
931 if (NewTypeHash != OldTypeHash) {
932 RemoveFromTypesByHash(OldTypeHash, Ty);
933 TypesByHash.insert(std::make_pair(NewTypeHash, Ty));
936 // If the type is currently thought to be abstract, rescan all of our
937 // subtypes to see if the type has just become concrete! Note that this
938 // may send out notifications to AbstractTypeUsers that types become
940 if (Ty->isAbstract())
941 Ty->PromoteAbstractToConcrete();
944 void print(const char *Arg) const {
945 #ifdef DEBUG_MERGE_TYPES
946 DOUT << "TypeMap<>::" << Arg << " table contents:\n";
948 for (typename std::map<ValType, PATypeHolder>::const_iterator I
949 = Map.begin(), E = Map.end(); I != E; ++I)
950 DOUT << " " << (++i) << ". " << (void*)I->second.get() << " "
951 << *I->second.get() << "\n";
955 void dump() const { print("dump output"); }
960 //===----------------------------------------------------------------------===//
961 // Function Type Factory and Value Class...
964 //===----------------------------------------------------------------------===//
965 // Integer Type Factory...
968 class IntegerValType {
971 IntegerValType(uint16_t numbits) : bits(numbits) {}
973 static IntegerValType get(const IntegerType *Ty) {
974 return IntegerValType(Ty->getBitWidth());
977 static unsigned hashTypeStructure(const IntegerType *Ty) {
978 return (unsigned)Ty->getBitWidth();
981 inline bool operator<(const IntegerValType &IVT) const {
982 return bits < IVT.bits;
987 static ManagedStatic<TypeMap<IntegerValType, IntegerType> > IntegerTypes;
989 const IntegerType *IntegerType::get(unsigned NumBits) {
990 assert(NumBits >= MIN_INT_BITS && "bitwidth too small");
991 assert(NumBits <= MAX_INT_BITS && "bitwidth too large");
993 // Check for the built-in integer types
995 case 1: return cast<IntegerType>(Type::Int1Ty);
996 case 8: return cast<IntegerType>(Type::Int8Ty);
997 case 16: return cast<IntegerType>(Type::Int16Ty);
998 case 32: return cast<IntegerType>(Type::Int32Ty);
999 case 64: return cast<IntegerType>(Type::Int64Ty);
1004 IntegerValType IVT(NumBits);
1005 IntegerType *ITy = 0;
1007 // First, see if the type is already in the table, for which
1008 // a reader lock suffices.
1009 sys::SmartScopedLock<true> L(&*TypeMapLock);
1010 ITy = IntegerTypes->get(IVT);
1013 // Value not found. Derive a new type!
1014 ITy = new IntegerType(NumBits);
1015 IntegerTypes->add(IVT, ITy);
1017 #ifdef DEBUG_MERGE_TYPES
1018 DOUT << "Derived new type: " << *ITy << "\n";
1023 bool IntegerType::isPowerOf2ByteWidth() const {
1024 unsigned BitWidth = getBitWidth();
1025 return (BitWidth > 7) && isPowerOf2_32(BitWidth);
1028 APInt IntegerType::getMask() const {
1029 return APInt::getAllOnesValue(getBitWidth());
1032 // FunctionValType - Define a class to hold the key that goes into the TypeMap
1035 class FunctionValType {
1037 std::vector<const Type*> ArgTypes;
1040 FunctionValType(const Type *ret, const std::vector<const Type*> &args,
1041 bool isVA) : RetTy(ret), ArgTypes(args), isVarArg(isVA) {}
1043 static FunctionValType get(const FunctionType *FT);
1045 static unsigned hashTypeStructure(const FunctionType *FT) {
1046 unsigned Result = FT->getNumParams()*2 + FT->isVarArg();
1050 inline bool operator<(const FunctionValType &MTV) const {
1051 if (RetTy < MTV.RetTy) return true;
1052 if (RetTy > MTV.RetTy) return false;
1053 if (isVarArg < MTV.isVarArg) return true;
1054 if (isVarArg > MTV.isVarArg) return false;
1055 if (ArgTypes < MTV.ArgTypes) return true;
1056 if (ArgTypes > MTV.ArgTypes) return false;
1062 // Define the actual map itself now...
1063 static ManagedStatic<TypeMap<FunctionValType, FunctionType> > FunctionTypes;
1065 FunctionValType FunctionValType::get(const FunctionType *FT) {
1066 // Build up a FunctionValType
1067 std::vector<const Type *> ParamTypes;
1068 ParamTypes.reserve(FT->getNumParams());
1069 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
1070 ParamTypes.push_back(FT->getParamType(i));
1071 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
1075 // FunctionType::get - The factory function for the FunctionType class...
1076 FunctionType *FunctionType::get(const Type *ReturnType,
1077 const std::vector<const Type*> &Params,
1079 FunctionValType VT(ReturnType, Params, isVarArg);
1080 FunctionType *FT = 0;
1082 sys::SmartScopedLock<true> L(&*TypeMapLock);
1083 FT = FunctionTypes->get(VT);
1086 FT = (FunctionType*) operator new(sizeof(FunctionType) +
1087 sizeof(PATypeHandle)*(Params.size()+1));
1088 new (FT) FunctionType(ReturnType, Params, isVarArg);
1089 FunctionTypes->add(VT, FT);
1092 #ifdef DEBUG_MERGE_TYPES
1093 DOUT << "Derived new type: " << FT << "\n";
1098 //===----------------------------------------------------------------------===//
1099 // Array Type Factory...
1102 class ArrayValType {
1106 ArrayValType(const Type *val, uint64_t sz) : ValTy(val), Size(sz) {}
1108 static ArrayValType get(const ArrayType *AT) {
1109 return ArrayValType(AT->getElementType(), AT->getNumElements());
1112 static unsigned hashTypeStructure(const ArrayType *AT) {
1113 return (unsigned)AT->getNumElements();
1116 inline bool operator<(const ArrayValType &MTV) const {
1117 if (Size < MTV.Size) return true;
1118 return Size == MTV.Size && ValTy < MTV.ValTy;
1123 static ManagedStatic<TypeMap<ArrayValType, ArrayType> > ArrayTypes;
1125 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
1126 assert(ElementType && "Can't get array of <null> types!");
1127 assert(isValidElementType(ElementType) && "Invalid type for array element!");
1129 ArrayValType AVT(ElementType, NumElements);
1132 sys::SmartScopedLock<true> L(&*TypeMapLock);
1133 AT = ArrayTypes->get(AVT);
1136 // Value not found. Derive a new type!
1137 ArrayTypes->add(AVT, AT = new ArrayType(ElementType, NumElements));
1139 #ifdef DEBUG_MERGE_TYPES
1140 DOUT << "Derived new type: " << *AT << "\n";
1145 bool ArrayType::isValidElementType(const Type *ElemTy) {
1146 if (ElemTy == Type::VoidTy || ElemTy == Type::LabelTy ||
1147 ElemTy == Type::MetadataTy)
1150 if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
1151 if (PTy->getElementType() == Type::MetadataTy)
1158 //===----------------------------------------------------------------------===//
1159 // Vector Type Factory...
1162 class VectorValType {
1166 VectorValType(const Type *val, int sz) : ValTy(val), Size(sz) {}
1168 static VectorValType get(const VectorType *PT) {
1169 return VectorValType(PT->getElementType(), PT->getNumElements());
1172 static unsigned hashTypeStructure(const VectorType *PT) {
1173 return PT->getNumElements();
1176 inline bool operator<(const VectorValType &MTV) const {
1177 if (Size < MTV.Size) return true;
1178 return Size == MTV.Size && ValTy < MTV.ValTy;
1183 static ManagedStatic<TypeMap<VectorValType, VectorType> > VectorTypes;
1185 VectorType *VectorType::get(const Type *ElementType, unsigned NumElements) {
1186 assert(ElementType && "Can't get vector of <null> types!");
1188 VectorValType PVT(ElementType, NumElements);
1191 sys::SmartScopedLock<true> L(&*TypeMapLock);
1192 PT = VectorTypes->get(PVT);
1195 VectorTypes->add(PVT, PT = new VectorType(ElementType, NumElements));
1197 #ifdef DEBUG_MERGE_TYPES
1198 DOUT << "Derived new type: " << *PT << "\n";
1203 bool VectorType::isValidElementType(const Type *ElemTy) {
1204 if (ElemTy->isInteger() || ElemTy->isFloatingPoint() ||
1205 isa<OpaqueType>(ElemTy))
1211 //===----------------------------------------------------------------------===//
1212 // Struct Type Factory...
1216 // StructValType - Define a class to hold the key that goes into the TypeMap
1218 class StructValType {
1219 std::vector<const Type*> ElTypes;
1222 StructValType(const std::vector<const Type*> &args, bool isPacked)
1223 : ElTypes(args), packed(isPacked) {}
1225 static StructValType get(const StructType *ST) {
1226 std::vector<const Type *> ElTypes;
1227 ElTypes.reserve(ST->getNumElements());
1228 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
1229 ElTypes.push_back(ST->getElementType(i));
1231 return StructValType(ElTypes, ST->isPacked());
1234 static unsigned hashTypeStructure(const StructType *ST) {
1235 return ST->getNumElements();
1238 inline bool operator<(const StructValType &STV) const {
1239 if (ElTypes < STV.ElTypes) return true;
1240 else if (ElTypes > STV.ElTypes) return false;
1241 else return (int)packed < (int)STV.packed;
1246 static ManagedStatic<TypeMap<StructValType, StructType> > StructTypes;
1248 StructType *StructType::get(const std::vector<const Type*> &ETypes,
1250 StructValType STV(ETypes, isPacked);
1253 sys::SmartScopedLock<true> L(&*TypeMapLock);
1254 ST = StructTypes->get(STV);
1257 // Value not found. Derive a new type!
1258 ST = (StructType*) operator new(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);
1280 bool StructType::isValidElementType(const Type *ElemTy) {
1281 if (ElemTy == Type::VoidTy || ElemTy == Type::LabelTy ||
1282 ElemTy == Type::MetadataTy)
1285 if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
1286 if (PTy->getElementType() == Type::MetadataTy)
1293 //===----------------------------------------------------------------------===//
1294 // Pointer Type Factory...
1297 // PointerValType - Define a class to hold the key that goes into the TypeMap
1300 class PointerValType {
1302 unsigned AddressSpace;
1304 PointerValType(const Type *val, unsigned as) : ValTy(val), AddressSpace(as) {}
1306 static PointerValType get(const PointerType *PT) {
1307 return PointerValType(PT->getElementType(), PT->getAddressSpace());
1310 static unsigned hashTypeStructure(const PointerType *PT) {
1311 return getSubElementHash(PT);
1314 bool operator<(const PointerValType &MTV) const {
1315 if (AddressSpace < MTV.AddressSpace) return true;
1316 return AddressSpace == MTV.AddressSpace && ValTy < MTV.ValTy;
1321 static ManagedStatic<TypeMap<PointerValType, PointerType> > PointerTypes;
1323 PointerType *PointerType::get(const Type *ValueType, unsigned AddressSpace) {
1324 assert(ValueType && "Can't get a pointer to <null> type!");
1325 assert(ValueType != Type::VoidTy &&
1326 "Pointer to void is not valid, use i8* instead!");
1327 assert(isValidElementType(ValueType) && "Invalid type for pointer element!");
1328 PointerValType PVT(ValueType, AddressSpace);
1330 PointerType *PT = 0;
1332 sys::SmartScopedLock<true> L(&*TypeMapLock);
1333 PT = PointerTypes->get(PVT);
1336 // Value not found. Derive a new type!
1337 PointerTypes->add(PVT, PT = new PointerType(ValueType, AddressSpace));
1339 #ifdef DEBUG_MERGE_TYPES
1340 DOUT << "Derived new type: " << *PT << "\n";
1345 PointerType *Type::getPointerTo(unsigned addrs) const {
1346 return PointerType::get(this, addrs);
1349 bool PointerType::isValidElementType(const Type *ElemTy) {
1350 if (ElemTy == Type::VoidTy || ElemTy == Type::LabelTy)
1353 if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
1354 if (PTy->getElementType() == Type::MetadataTy)
1361 //===----------------------------------------------------------------------===//
1362 // Derived Type Refinement Functions
1363 //===----------------------------------------------------------------------===//
1365 // addAbstractTypeUser - Notify an abstract type that there is a new user of
1366 // it. This function is called primarily by the PATypeHandle class.
1367 void Type::addAbstractTypeUser(AbstractTypeUser *U) const {
1368 assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
1369 AbstractTypeUsersLock->acquire();
1370 AbstractTypeUsers.push_back(U);
1371 AbstractTypeUsersLock->release();
1375 // removeAbstractTypeUser - Notify an abstract type that a user of the class
1376 // no longer has a handle to the type. This function is called primarily by
1377 // the PATypeHandle class. When there are no users of the abstract type, it
1378 // is annihilated, because there is no way to get a reference to it ever again.
1380 void Type::removeAbstractTypeUser(AbstractTypeUser *U) const {
1381 AbstractTypeUsersLock->acquire();
1383 // Search from back to front because we will notify users from back to
1384 // front. Also, it is likely that there will be a stack like behavior to
1385 // users that register and unregister users.
1388 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1389 assert(i != 0 && "AbstractTypeUser not in user list!");
1391 --i; // Convert to be in range 0 <= i < size()
1392 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
1394 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1396 #ifdef DEBUG_MERGE_TYPES
1397 DOUT << " remAbstractTypeUser[" << (void*)this << ", "
1398 << *this << "][" << i << "] User = " << U << "\n";
1401 if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1402 #ifdef DEBUG_MERGE_TYPES
1403 DOUT << "DELETEing unused abstract type: <" << *this
1404 << ">[" << (void*)this << "]" << "\n";
1410 AbstractTypeUsersLock->release();
1413 // unlockedRefineAbstractTypeTo - This function is used when it is discovered
1414 // that the 'this' abstract type is actually equivalent to the NewType
1415 // specified. This causes all users of 'this' to switch to reference the more
1416 // concrete type NewType and for 'this' to be deleted. Only used for internal
1419 void DerivedType::unlockedRefineAbstractTypeTo(const Type *NewType) {
1420 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1421 assert(this != NewType && "Can't refine to myself!");
1422 assert(ForwardType == 0 && "This type has already been refined!");
1424 // The descriptions may be out of date. Conservatively clear them all!
1425 if (AbstractTypeDescriptions.isConstructed())
1426 AbstractTypeDescriptions->clear();
1428 #ifdef DEBUG_MERGE_TYPES
1429 DOUT << "REFINING abstract type [" << (void*)this << " "
1430 << *this << "] to [" << (void*)NewType << " "
1431 << *NewType << "]!\n";
1434 // Make sure to put the type to be refined to into a holder so that if IT gets
1435 // refined, that we will not continue using a dead reference...
1437 PATypeHolder NewTy(NewType);
1438 // Any PATypeHolders referring to this type will now automatically forward o
1439 // the type we are resolved to.
1440 ForwardType = NewType;
1441 if (NewType->isAbstract())
1442 cast<DerivedType>(NewType)->addRef();
1444 // Add a self use of the current type so that we don't delete ourself until
1445 // after the function exits.
1447 PATypeHolder CurrentTy(this);
1449 // To make the situation simpler, we ask the subclass to remove this type from
1450 // the type map, and to replace any type uses with uses of non-abstract types.
1451 // This dramatically limits the amount of recursive type trouble we can find
1455 // Iterate over all of the uses of this type, invoking callback. Each user
1456 // should remove itself from our use list automatically. We have to check to
1457 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1458 // will not cause users to drop off of the use list. If we resolve to ourself
1461 AbstractTypeUsersLock->acquire();
1462 while (!AbstractTypeUsers.empty() && NewTy != this) {
1463 AbstractTypeUser *User = AbstractTypeUsers.back();
1465 unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1466 #ifdef DEBUG_MERGE_TYPES
1467 DOUT << " REFINING user " << OldSize-1 << "[" << (void*)User
1468 << "] of abstract type [" << (void*)this << " "
1469 << *this << "] to [" << (void*)NewTy.get() << " "
1470 << *NewTy << "]!\n";
1472 User->refineAbstractType(this, NewTy);
1474 assert(AbstractTypeUsers.size() != OldSize &&
1475 "AbsTyUser did not remove self from user list!");
1477 AbstractTypeUsersLock->release();
1479 // If we were successful removing all users from the type, 'this' will be
1480 // deleted when the last PATypeHolder is destroyed or updated from this type.
1481 // This may occur on exit of this function, as the CurrentTy object is
1485 // refineAbstractTypeTo - This function is used by external callers to notify
1486 // us that this abstract type is equivalent to another type.
1488 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1489 // All recursive calls will go through unlockedRefineAbstractTypeTo,
1490 // to avoid deadlock problems.
1491 sys::SmartScopedLock<true> L(&*TypeMapLock);
1492 unlockedRefineAbstractTypeTo(NewType);
1495 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1496 // the current type has transitioned from being abstract to being concrete.
1498 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1499 #ifdef DEBUG_MERGE_TYPES
1500 DOUT << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1503 AbstractTypeUsersLock->acquire();
1504 unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1505 while (!AbstractTypeUsers.empty()) {
1506 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1507 ATU->typeBecameConcrete(this);
1509 assert(AbstractTypeUsers.size() < OldSize-- &&
1510 "AbstractTypeUser did not remove itself from the use list!");
1512 AbstractTypeUsersLock->release();
1515 // refineAbstractType - Called when a contained type is found to be more
1516 // concrete - this could potentially change us from an abstract type to a
1519 void FunctionType::refineAbstractType(const DerivedType *OldType,
1520 const Type *NewType) {
1521 FunctionTypes->RefineAbstractType(this, OldType, NewType);
1524 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1525 FunctionTypes->TypeBecameConcrete(this, AbsTy);
1529 // refineAbstractType - Called when a contained type is found to be more
1530 // concrete - this could potentially change us from an abstract type to a
1533 void ArrayType::refineAbstractType(const DerivedType *OldType,
1534 const Type *NewType) {
1535 ArrayTypes->RefineAbstractType(this, OldType, NewType);
1538 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1539 ArrayTypes->TypeBecameConcrete(this, AbsTy);
1542 // refineAbstractType - Called when a contained type is found to be more
1543 // concrete - this could potentially change us from an abstract type to a
1546 void VectorType::refineAbstractType(const DerivedType *OldType,
1547 const Type *NewType) {
1548 VectorTypes->RefineAbstractType(this, OldType, NewType);
1551 void VectorType::typeBecameConcrete(const DerivedType *AbsTy) {
1552 VectorTypes->TypeBecameConcrete(this, AbsTy);
1555 // refineAbstractType - Called when a contained type is found to be more
1556 // concrete - this could potentially change us from an abstract type to a
1559 void StructType::refineAbstractType(const DerivedType *OldType,
1560 const Type *NewType) {
1561 StructTypes->RefineAbstractType(this, OldType, NewType);
1564 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1565 StructTypes->TypeBecameConcrete(this, AbsTy);
1568 // refineAbstractType - Called when a contained type is found to be more
1569 // concrete - this could potentially change us from an abstract type to a
1572 void PointerType::refineAbstractType(const DerivedType *OldType,
1573 const Type *NewType) {
1574 PointerTypes->RefineAbstractType(this, OldType, NewType);
1577 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1578 PointerTypes->TypeBecameConcrete(this, AbsTy);
1581 bool SequentialType::indexValid(const Value *V) const {
1582 if (isa<IntegerType>(V->getType()))
1588 std::ostream &operator<<(std::ostream &OS, const Type *T) {
1590 OS << "<null> value!\n";
1596 std::ostream &operator<<(std::ostream &OS, const Type &T) {
1601 raw_ostream &operator<<(raw_ostream &OS, const Type &T) {