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 "LLVMContextImpl.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Constants.h"
17 #include "llvm/Assembly/Writer.h"
18 #include "llvm/LLVMContext.h"
19 #include "llvm/Metadata.h"
20 #include "llvm/ADT/DepthFirstIterator.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/SCCIterator.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/System/Mutex.h"
31 #include "llvm/System/RWMutex.h"
32 #include "llvm/System/Threading.h"
37 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
38 // created and later destroyed, all in an effort to make sure that there is only
39 // a single canonical version of a type.
41 // #define DEBUG_MERGE_TYPES 1
43 AbstractTypeUser::~AbstractTypeUser() {}
46 //===----------------------------------------------------------------------===//
47 // Type Class Implementation
48 //===----------------------------------------------------------------------===//
50 // Lock used for guarding access to the type maps.
51 static ManagedStatic<sys::SmartMutex<true> > TypeMapLock;
53 // Recursive lock used for guarding access to AbstractTypeUsers.
54 // NOTE: The true template parameter means this will no-op when we're not in
55 // multithreaded mode.
56 static ManagedStatic<sys::SmartMutex<true> > AbstractTypeUsersLock;
58 // Concrete/Abstract TypeDescriptions - We lazily calculate type descriptions
59 // for types as they are needed. Because resolution of types must invalidate
60 // all of the abstract type descriptions, we keep them in a seperate map to make
62 static ManagedStatic<TypePrinting> ConcreteTypeDescriptions;
63 static ManagedStatic<TypePrinting> 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 static_cast<const FunctionType*>(this)->FunctionType::~FunctionType();
89 static_cast<const StructType*>(this)->StructType::~StructType();
91 // Finally, remove the memory as an array deallocation of the chars it was
93 operator delete(const_cast<Type *>(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(LLVMContext &C, TypeID IDNumber) {
108 case VoidTyID : return getVoidTy(C);
109 case FloatTyID : return getFloatTy(C);
110 case DoubleTyID : return getDoubleTy(C);
111 case X86_FP80TyID : return getX86_FP80Ty(C);
112 case FP128TyID : return getFP128Ty(C);
113 case PPC_FP128TyID : return getPPC_FP128Ty(C);
114 case LabelTyID : return getLabelTy(C);
115 case MetadataTyID : return getMetadataTy(C);
121 const Type *Type::getVAArgsPromotedType(LLVMContext &C) const {
122 if (ID == IntegerTyID && getSubclassData() < 32)
123 return Type::getInt32Ty(C);
124 else if (ID == FloatTyID)
125 return Type::getDoubleTy(C);
130 /// getScalarType - If this is a vector type, return the element type,
131 /// otherwise return this.
132 const Type *Type::getScalarType() const {
133 if (const VectorType *VTy = dyn_cast<VectorType>(this))
134 return VTy->getElementType();
138 /// isIntOrIntVector - Return true if this is an integer type or a vector of
141 bool Type::isIntOrIntVector() const {
144 if (ID != Type::VectorTyID) return false;
146 return cast<VectorType>(this)->getElementType()->isInteger();
149 /// isFPOrFPVector - Return true if this is a FP type or a vector of FP types.
151 bool Type::isFPOrFPVector() const {
152 if (ID == Type::FloatTyID || ID == Type::DoubleTyID ||
153 ID == Type::FP128TyID || ID == Type::X86_FP80TyID ||
154 ID == Type::PPC_FP128TyID)
156 if (ID != Type::VectorTyID) return false;
158 return cast<VectorType>(this)->getElementType()->isFloatingPoint();
161 // canLosslesslyBitCastTo - Return true if this type can be converted to
162 // 'Ty' without any reinterpretation of bits. For example, i8* to i32*.
164 bool Type::canLosslesslyBitCastTo(const Type *Ty) const {
165 // Identity cast means no change so return true
169 // They are not convertible unless they are at least first class types
170 if (!this->isFirstClassType() || !Ty->isFirstClassType())
173 // Vector -> Vector conversions are always lossless if the two vector types
174 // have the same size, otherwise not.
175 if (const VectorType *thisPTy = dyn_cast<VectorType>(this))
176 if (const VectorType *thatPTy = dyn_cast<VectorType>(Ty))
177 return thisPTy->getBitWidth() == thatPTy->getBitWidth();
179 // At this point we have only various mismatches of the first class types
180 // remaining and ptr->ptr. Just select the lossless conversions. Everything
181 // else is not lossless.
182 if (isa<PointerType>(this))
183 return isa<PointerType>(Ty);
184 return false; // Other types have no identity values
187 unsigned Type::getPrimitiveSizeInBits() const {
188 switch (getTypeID()) {
189 case Type::FloatTyID: return 32;
190 case Type::DoubleTyID: return 64;
191 case Type::X86_FP80TyID: return 80;
192 case Type::FP128TyID: return 128;
193 case Type::PPC_FP128TyID: return 128;
194 case Type::IntegerTyID: return cast<IntegerType>(this)->getBitWidth();
195 case Type::VectorTyID: return cast<VectorType>(this)->getBitWidth();
200 /// getScalarSizeInBits - If this is a vector type, return the
201 /// getPrimitiveSizeInBits value for the element type. Otherwise return the
202 /// getPrimitiveSizeInBits value for this type.
203 unsigned Type::getScalarSizeInBits() const {
204 return getScalarType()->getPrimitiveSizeInBits();
207 /// getFPMantissaWidth - Return the width of the mantissa of this type. This
208 /// is only valid on floating point types. If the FP type does not
209 /// have a stable mantissa (e.g. ppc long double), this method returns -1.
210 int Type::getFPMantissaWidth() const {
211 if (const VectorType *VTy = dyn_cast<VectorType>(this))
212 return VTy->getElementType()->getFPMantissaWidth();
213 assert(isFloatingPoint() && "Not a floating point type!");
214 if (ID == FloatTyID) return 24;
215 if (ID == DoubleTyID) return 53;
216 if (ID == X86_FP80TyID) return 64;
217 if (ID == FP128TyID) return 113;
218 assert(ID == PPC_FP128TyID && "unknown fp type");
222 /// isSizedDerivedType - Derived types like structures and arrays are sized
223 /// iff all of the members of the type are sized as well. Since asking for
224 /// their size is relatively uncommon, move this operation out of line.
225 bool Type::isSizedDerivedType() const {
226 if (isa<IntegerType>(this))
229 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
230 return ATy->getElementType()->isSized();
232 if (const VectorType *PTy = dyn_cast<VectorType>(this))
233 return PTy->getElementType()->isSized();
235 if (!isa<StructType>(this))
238 // Okay, our struct is sized if all of the elements are...
239 for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I)
240 if (!(*I)->isSized())
246 /// getForwardedTypeInternal - This method is used to implement the union-find
247 /// algorithm for when a type is being forwarded to another type.
248 const Type *Type::getForwardedTypeInternal() const {
249 assert(ForwardType && "This type is not being forwarded to another type!");
251 // Check to see if the forwarded type has been forwarded on. If so, collapse
252 // the forwarding links.
253 const Type *RealForwardedType = ForwardType->getForwardedType();
254 if (!RealForwardedType)
255 return ForwardType; // No it's not forwarded again
257 // Yes, it is forwarded again. First thing, add the reference to the new
259 if (RealForwardedType->isAbstract())
260 cast<DerivedType>(RealForwardedType)->addRef();
262 // Now drop the old reference. This could cause ForwardType to get deleted.
263 cast<DerivedType>(ForwardType)->dropRef();
265 // Return the updated type.
266 ForwardType = RealForwardedType;
270 void Type::refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
271 llvm_unreachable("Attempting to refine a derived type!");
273 void Type::typeBecameConcrete(const DerivedType *AbsTy) {
274 llvm_unreachable("DerivedType is already a concrete type!");
278 std::string Type::getDescription() const {
280 isAbstract() ? *AbstractTypeDescriptions : *ConcreteTypeDescriptions;
283 raw_string_ostream DescOS(DescStr);
284 Map.print(this, DescOS);
289 bool StructType::indexValid(const Value *V) const {
290 // Structure indexes require 32-bit integer constants.
291 if (V->getType() == Type::getInt32Ty(V->getContext()))
292 if (const ConstantInt *CU = dyn_cast<ConstantInt>(V))
293 return indexValid(CU->getZExtValue());
297 bool StructType::indexValid(unsigned V) const {
298 return V < NumContainedTys;
301 // getTypeAtIndex - Given an index value into the type, return the type of the
302 // element. For a structure type, this must be a constant value...
304 const Type *StructType::getTypeAtIndex(const Value *V) const {
305 unsigned Idx = (unsigned)cast<ConstantInt>(V)->getZExtValue();
306 return getTypeAtIndex(Idx);
309 const Type *StructType::getTypeAtIndex(unsigned Idx) const {
310 assert(indexValid(Idx) && "Invalid structure index!");
311 return ContainedTys[Idx];
314 //===----------------------------------------------------------------------===//
315 // Primitive 'Type' data
316 //===----------------------------------------------------------------------===//
318 const Type *Type::getVoidTy(LLVMContext &C) {
319 return C.pImpl->VoidTy;
322 const Type *Type::getLabelTy(LLVMContext &C) {
323 return C.pImpl->LabelTy;
326 const Type *Type::getFloatTy(LLVMContext &C) {
327 return C.pImpl->FloatTy;
330 const Type *Type::getDoubleTy(LLVMContext &C) {
331 return C.pImpl->DoubleTy;
334 const Type *Type::getMetadataTy(LLVMContext &C) {
335 return C.pImpl->MetadataTy;
338 const Type *Type::getX86_FP80Ty(LLVMContext &C) {
339 return C.pImpl->X86_FP80Ty;
342 const Type *Type::getFP128Ty(LLVMContext &C) {
343 return C.pImpl->FP128Ty;
346 const Type *Type::getPPC_FP128Ty(LLVMContext &C) {
347 return C.pImpl->PPC_FP128Ty;
350 const IntegerType *Type::getInt1Ty(LLVMContext &C) {
351 return C.pImpl->Int1Ty;
354 const IntegerType *Type::getInt8Ty(LLVMContext &C) {
355 return C.pImpl->Int8Ty;
358 const IntegerType *Type::getInt16Ty(LLVMContext &C) {
359 return C.pImpl->Int16Ty;
362 const IntegerType *Type::getInt32Ty(LLVMContext &C) {
363 return C.pImpl->Int32Ty;
366 const IntegerType *Type::getInt64Ty(LLVMContext &C) {
367 return C.pImpl->Int64Ty;
370 //===----------------------------------------------------------------------===//
371 // Derived Type Constructors
372 //===----------------------------------------------------------------------===//
374 /// isValidReturnType - Return true if the specified type is valid as a return
376 bool FunctionType::isValidReturnType(const Type *RetTy) {
377 if (RetTy->isFirstClassType()) {
378 if (const PointerType *PTy = dyn_cast<PointerType>(RetTy))
379 return PTy->getElementType() != Type::getMetadataTy(RetTy->getContext());
382 if (RetTy == Type::getVoidTy(RetTy->getContext()) ||
383 RetTy == Type::getMetadataTy(RetTy->getContext()) ||
384 isa<OpaqueType>(RetTy))
387 // If this is a multiple return case, verify that each return is a first class
388 // value and that there is at least one value.
389 const StructType *SRetTy = dyn_cast<StructType>(RetTy);
390 if (SRetTy == 0 || SRetTy->getNumElements() == 0)
393 for (unsigned i = 0, e = SRetTy->getNumElements(); i != e; ++i)
394 if (!SRetTy->getElementType(i)->isFirstClassType())
399 /// isValidArgumentType - Return true if the specified type is valid as an
401 bool FunctionType::isValidArgumentType(const Type *ArgTy) {
402 if ((!ArgTy->isFirstClassType() && !isa<OpaqueType>(ArgTy)) ||
403 (isa<PointerType>(ArgTy) &&
404 cast<PointerType>(ArgTy)->getElementType() ==
405 Type::getMetadataTy(ArgTy->getContext())))
411 FunctionType::FunctionType(const Type *Result,
412 const std::vector<const Type*> &Params,
414 : DerivedType(Result->getContext(), FunctionTyID), isVarArgs(IsVarArgs) {
415 ContainedTys = reinterpret_cast<PATypeHandle*>(this+1);
416 NumContainedTys = Params.size() + 1; // + 1 for result type
417 assert(isValidReturnType(Result) && "invalid return type for function");
420 bool isAbstract = Result->isAbstract();
421 new (&ContainedTys[0]) PATypeHandle(Result, this);
423 for (unsigned i = 0; i != Params.size(); ++i) {
424 assert(isValidArgumentType(Params[i]) &&
425 "Not a valid type for function argument!");
426 new (&ContainedTys[i+1]) PATypeHandle(Params[i], this);
427 isAbstract |= Params[i]->isAbstract();
430 // Calculate whether or not this type is abstract
431 setAbstract(isAbstract);
434 StructType::StructType(LLVMContext &C,
435 const std::vector<const Type*> &Types, bool isPacked)
436 : CompositeType(C, StructTyID) {
437 ContainedTys = reinterpret_cast<PATypeHandle*>(this + 1);
438 NumContainedTys = Types.size();
439 setSubclassData(isPacked);
440 bool isAbstract = false;
441 for (unsigned i = 0; i < Types.size(); ++i) {
442 assert(Types[i] && "<null> type for structure field!");
443 assert(isValidElementType(Types[i]) &&
444 "Invalid type for structure element!");
445 new (&ContainedTys[i]) PATypeHandle(Types[i], this);
446 isAbstract |= Types[i]->isAbstract();
449 // Calculate whether or not this type is abstract
450 setAbstract(isAbstract);
453 ArrayType::ArrayType(const Type *ElType, uint64_t NumEl)
454 : SequentialType(ArrayTyID, ElType) {
457 // Calculate whether or not this type is abstract
458 setAbstract(ElType->isAbstract());
461 VectorType::VectorType(const Type *ElType, unsigned NumEl)
462 : SequentialType(VectorTyID, ElType) {
464 setAbstract(ElType->isAbstract());
465 assert(NumEl > 0 && "NumEl of a VectorType must be greater than 0");
466 assert(isValidElementType(ElType) &&
467 "Elements of a VectorType must be a primitive type");
472 PointerType::PointerType(const Type *E, unsigned AddrSpace)
473 : SequentialType(PointerTyID, E) {
474 AddressSpace = AddrSpace;
475 // Calculate whether or not this type is abstract
476 setAbstract(E->isAbstract());
479 OpaqueType::OpaqueType(LLVMContext &C) : DerivedType(C, OpaqueTyID) {
481 #ifdef DEBUG_MERGE_TYPES
482 DOUT << "Derived new type: " << *this << "\n";
486 void PATypeHolder::destroy() {
490 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
491 // another (more concrete) type, we must eliminate all references to other
492 // types, to avoid some circular reference problems.
493 void DerivedType::dropAllTypeUses() {
494 if (NumContainedTys != 0) {
495 // The type must stay abstract. To do this, we insert a pointer to a type
496 // that will never get resolved, thus will always be abstract.
497 static Type *AlwaysOpaqueTy = 0;
498 static PATypeHolder* Holder = 0;
499 Type *tmp = AlwaysOpaqueTy;
500 if (llvm_is_multithreaded()) {
503 llvm_acquire_global_lock();
504 tmp = AlwaysOpaqueTy;
506 tmp = OpaqueType::get(getContext());
507 PATypeHolder* tmp2 = new PATypeHolder(AlwaysOpaqueTy);
509 AlwaysOpaqueTy = tmp;
513 llvm_release_global_lock();
516 AlwaysOpaqueTy = OpaqueType::get(getContext());
517 Holder = new PATypeHolder(AlwaysOpaqueTy);
520 ContainedTys[0] = AlwaysOpaqueTy;
522 // Change the rest of the types to be Int32Ty's. It doesn't matter what we
523 // pick so long as it doesn't point back to this type. We choose something
524 // concrete to avoid overhead for adding to AbstracTypeUser lists and stuff.
525 for (unsigned i = 1, e = NumContainedTys; i != e; ++i)
526 ContainedTys[i] = Type::getInt32Ty(getContext());
533 /// TypePromotionGraph and graph traits - this is designed to allow us to do
534 /// efficient SCC processing of type graphs. This is the exact same as
535 /// GraphTraits<Type*>, except that we pretend that concrete types have no
536 /// children to avoid processing them.
537 struct TypePromotionGraph {
539 TypePromotionGraph(Type *T) : Ty(T) {}
545 template <> struct GraphTraits<TypePromotionGraph> {
546 typedef Type NodeType;
547 typedef Type::subtype_iterator ChildIteratorType;
549 static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
550 static inline ChildIteratorType child_begin(NodeType *N) {
552 return N->subtype_begin();
553 else // No need to process children of concrete types.
554 return N->subtype_end();
556 static inline ChildIteratorType child_end(NodeType *N) {
557 return N->subtype_end();
563 // PromoteAbstractToConcrete - This is a recursive function that walks a type
564 // graph calculating whether or not a type is abstract.
566 void Type::PromoteAbstractToConcrete() {
567 if (!isAbstract()) return;
569 scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
570 scc_iterator<TypePromotionGraph> SE = scc_end (TypePromotionGraph(this));
572 for (; SI != SE; ++SI) {
573 std::vector<Type*> &SCC = *SI;
575 // Concrete types are leaves in the tree. Since an SCC will either be all
576 // abstract or all concrete, we only need to check one type.
577 if (SCC[0]->isAbstract()) {
578 if (isa<OpaqueType>(SCC[0]))
579 return; // Not going to be concrete, sorry.
581 // If all of the children of all of the types in this SCC are concrete,
582 // then this SCC is now concrete as well. If not, neither this SCC, nor
583 // any parent SCCs will be concrete, so we might as well just exit.
584 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
585 for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
586 E = SCC[i]->subtype_end(); CI != E; ++CI)
587 if ((*CI)->isAbstract())
588 // If the child type is in our SCC, it doesn't make the entire SCC
589 // abstract unless there is a non-SCC abstract type.
590 if (std::find(SCC.begin(), SCC.end(), *CI) == SCC.end())
591 return; // Not going to be concrete, sorry.
593 // Okay, we just discovered this whole SCC is now concrete, mark it as
595 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
596 assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
598 SCC[i]->setAbstract(false);
601 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
602 assert(!SCC[i]->isAbstract() && "Concrete type became abstract?");
603 // The type just became concrete, notify all users!
604 cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
611 //===----------------------------------------------------------------------===//
612 // Type Structural Equality Testing
613 //===----------------------------------------------------------------------===//
615 // TypesEqual - Two types are considered structurally equal if they have the
616 // same "shape": Every level and element of the types have identical primitive
617 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
618 // be pointer equals to be equivalent though. This uses an optimistic algorithm
619 // that assumes that two graphs are the same until proven otherwise.
621 static bool TypesEqual(const Type *Ty, const Type *Ty2,
622 std::map<const Type *, const Type *> &EqTypes) {
623 if (Ty == Ty2) return true;
624 if (Ty->getTypeID() != Ty2->getTypeID()) return false;
625 if (isa<OpaqueType>(Ty))
626 return false; // Two unequal opaque types are never equal
628 std::map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
629 if (It != EqTypes.end())
630 return It->second == Ty2; // Looping back on a type, check for equality
632 // Otherwise, add the mapping to the table to make sure we don't get
633 // recursion on the types...
634 EqTypes.insert(It, std::make_pair(Ty, Ty2));
636 // Two really annoying special cases that breaks an otherwise nice simple
637 // algorithm is the fact that arraytypes have sizes that differentiates types,
638 // and that function types can be varargs or not. Consider this now.
640 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
641 const IntegerType *ITy2 = cast<IntegerType>(Ty2);
642 return ITy->getBitWidth() == ITy2->getBitWidth();
643 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
644 const PointerType *PTy2 = cast<PointerType>(Ty2);
645 return PTy->getAddressSpace() == PTy2->getAddressSpace() &&
646 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
647 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
648 const StructType *STy2 = cast<StructType>(Ty2);
649 if (STy->getNumElements() != STy2->getNumElements()) return false;
650 if (STy->isPacked() != STy2->isPacked()) return false;
651 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
652 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
655 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
656 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
657 return ATy->getNumElements() == ATy2->getNumElements() &&
658 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
659 } else if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
660 const VectorType *PTy2 = cast<VectorType>(Ty2);
661 return PTy->getNumElements() == PTy2->getNumElements() &&
662 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
663 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
664 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
665 if (FTy->isVarArg() != FTy2->isVarArg() ||
666 FTy->getNumParams() != FTy2->getNumParams() ||
667 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
669 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i) {
670 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
675 llvm_unreachable("Unknown derived type!");
680 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
681 std::map<const Type *, const Type *> EqTypes;
682 return TypesEqual(Ty, Ty2, EqTypes);
685 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
686 // TargetTy in the type graph. We know that Ty is an abstract type, so if we
687 // ever reach a non-abstract type, we know that we don't need to search the
689 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
690 SmallPtrSet<const Type*, 128> &VisitedTypes) {
691 if (TargetTy == CurTy) return true;
692 if (!CurTy->isAbstract()) return false;
694 if (!VisitedTypes.insert(CurTy))
695 return false; // Already been here.
697 for (Type::subtype_iterator I = CurTy->subtype_begin(),
698 E = CurTy->subtype_end(); I != E; ++I)
699 if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
704 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
705 SmallPtrSet<const Type*, 128> &VisitedTypes) {
706 if (TargetTy == CurTy) return true;
708 if (!VisitedTypes.insert(CurTy))
709 return false; // Already been here.
711 for (Type::subtype_iterator I = CurTy->subtype_begin(),
712 E = CurTy->subtype_end(); I != E; ++I)
713 if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
718 /// TypeHasCycleThroughItself - Return true if the specified type has a cycle
720 static bool TypeHasCycleThroughItself(const Type *Ty) {
721 SmallPtrSet<const Type*, 128> VisitedTypes;
723 if (Ty->isAbstract()) { // Optimized case for abstract types.
724 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
726 if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
729 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
731 if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
737 //===----------------------------------------------------------------------===//
738 // Function Type Factory and Value Class...
740 const IntegerType *IntegerType::get(LLVMContext &C, unsigned NumBits) {
741 assert(NumBits >= MIN_INT_BITS && "bitwidth too small");
742 assert(NumBits <= MAX_INT_BITS && "bitwidth too large");
744 // Check for the built-in integer types
746 case 1: return cast<IntegerType>(Type::getInt1Ty(C));
747 case 8: return cast<IntegerType>(Type::getInt8Ty(C));
748 case 16: return cast<IntegerType>(Type::getInt16Ty(C));
749 case 32: return cast<IntegerType>(Type::getInt32Ty(C));
750 case 64: return cast<IntegerType>(Type::getInt64Ty(C));
755 LLVMContextImpl *pImpl = C.pImpl;
757 IntegerValType IVT(NumBits);
758 IntegerType *ITy = 0;
760 // First, see if the type is already in the table, for which
761 // a reader lock suffices.
762 sys::SmartScopedLock<true> L(*TypeMapLock);
763 ITy = pImpl->IntegerTypes.get(IVT);
766 // Value not found. Derive a new type!
767 ITy = new IntegerType(C, NumBits);
768 pImpl->IntegerTypes.add(IVT, ITy);
770 #ifdef DEBUG_MERGE_TYPES
771 DOUT << "Derived new type: " << *ITy << "\n";
776 bool IntegerType::isPowerOf2ByteWidth() const {
777 unsigned BitWidth = getBitWidth();
778 return (BitWidth > 7) && isPowerOf2_32(BitWidth);
781 APInt IntegerType::getMask() const {
782 return APInt::getAllOnesValue(getBitWidth());
785 FunctionValType FunctionValType::get(const FunctionType *FT) {
786 // Build up a FunctionValType
787 std::vector<const Type *> ParamTypes;
788 ParamTypes.reserve(FT->getNumParams());
789 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
790 ParamTypes.push_back(FT->getParamType(i));
791 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
795 // FunctionType::get - The factory function for the FunctionType class...
796 FunctionType *FunctionType::get(const Type *ReturnType,
797 const std::vector<const Type*> &Params,
799 FunctionValType VT(ReturnType, Params, isVarArg);
800 FunctionType *FT = 0;
802 LLVMContextImpl *pImpl = ReturnType->getContext().pImpl;
804 sys::SmartScopedLock<true> L(*TypeMapLock);
805 FT = pImpl->FunctionTypes.get(VT);
808 FT = (FunctionType*) operator new(sizeof(FunctionType) +
809 sizeof(PATypeHandle)*(Params.size()+1));
810 new (FT) FunctionType(ReturnType, Params, isVarArg);
811 pImpl->FunctionTypes.add(VT, FT);
814 #ifdef DEBUG_MERGE_TYPES
815 DOUT << "Derived new type: " << FT << "\n";
820 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
821 assert(ElementType && "Can't get array of <null> types!");
822 assert(isValidElementType(ElementType) && "Invalid type for array element!");
824 ArrayValType AVT(ElementType, NumElements);
827 LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
829 sys::SmartScopedLock<true> L(*TypeMapLock);
830 AT = pImpl->ArrayTypes.get(AVT);
833 // Value not found. Derive a new type!
834 pImpl->ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
836 #ifdef DEBUG_MERGE_TYPES
837 DOUT << "Derived new type: " << *AT << "\n";
842 bool ArrayType::isValidElementType(const Type *ElemTy) {
843 if (ElemTy == Type::getVoidTy(ElemTy->getContext()) ||
844 ElemTy == Type::getLabelTy(ElemTy->getContext()) ||
845 ElemTy == Type::getMetadataTy(ElemTy->getContext()))
848 if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
849 if (PTy->getElementType() == Type::getMetadataTy(ElemTy->getContext()))
855 VectorType *VectorType::get(const Type *ElementType, unsigned NumElements) {
856 assert(ElementType && "Can't get vector of <null> types!");
858 VectorValType PVT(ElementType, NumElements);
861 LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
863 sys::SmartScopedLock<true> L(*TypeMapLock);
864 PT = pImpl->VectorTypes.get(PVT);
867 pImpl->VectorTypes.add(PVT, PT = new VectorType(ElementType, NumElements));
869 #ifdef DEBUG_MERGE_TYPES
870 DOUT << "Derived new type: " << *PT << "\n";
875 bool VectorType::isValidElementType(const Type *ElemTy) {
876 if (ElemTy->isInteger() || ElemTy->isFloatingPoint() ||
877 isa<OpaqueType>(ElemTy))
883 //===----------------------------------------------------------------------===//
884 // Struct Type Factory...
887 StructType *StructType::get(LLVMContext &Context,
888 const std::vector<const Type*> &ETypes,
890 StructValType STV(ETypes, isPacked);
893 LLVMContextImpl *pImpl = Context.pImpl;
895 sys::SmartScopedLock<true> L(*TypeMapLock);
896 ST = pImpl->StructTypes.get(STV);
899 // Value not found. Derive a new type!
900 ST = (StructType*) operator new(sizeof(StructType) +
901 sizeof(PATypeHandle) * ETypes.size());
902 new (ST) StructType(Context, ETypes, isPacked);
903 pImpl->StructTypes.add(STV, ST);
905 #ifdef DEBUG_MERGE_TYPES
906 DOUT << "Derived new type: " << *ST << "\n";
911 StructType *StructType::get(LLVMContext &Context, const Type *type, ...) {
913 std::vector<const llvm::Type*> StructFields;
916 StructFields.push_back(type);
917 type = va_arg(ap, llvm::Type*);
919 return llvm::StructType::get(Context, StructFields);
922 bool StructType::isValidElementType(const Type *ElemTy) {
923 if (ElemTy == Type::getVoidTy(ElemTy->getContext()) ||
924 ElemTy == Type::getLabelTy(ElemTy->getContext()) ||
925 ElemTy == Type::getMetadataTy(ElemTy->getContext()))
928 if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
929 if (PTy->getElementType() == Type::getMetadataTy(ElemTy->getContext()))
936 //===----------------------------------------------------------------------===//
937 // Pointer Type Factory...
940 PointerType *PointerType::get(const Type *ValueType, unsigned AddressSpace) {
941 assert(ValueType && "Can't get a pointer to <null> type!");
942 assert(ValueType != Type::getVoidTy(ValueType->getContext()) &&
943 "Pointer to void is not valid, use i8* instead!");
944 assert(isValidElementType(ValueType) && "Invalid type for pointer element!");
945 PointerValType PVT(ValueType, AddressSpace);
949 LLVMContextImpl *pImpl = ValueType->getContext().pImpl;
951 sys::SmartScopedLock<true> L(*TypeMapLock);
952 PT = pImpl->PointerTypes.get(PVT);
955 // Value not found. Derive a new type!
956 pImpl->PointerTypes.add(PVT, PT = new PointerType(ValueType, AddressSpace));
958 #ifdef DEBUG_MERGE_TYPES
959 DOUT << "Derived new type: " << *PT << "\n";
964 PointerType *Type::getPointerTo(unsigned addrs) const {
965 return PointerType::get(this, addrs);
968 bool PointerType::isValidElementType(const Type *ElemTy) {
969 if (ElemTy == Type::getVoidTy(ElemTy->getContext()) ||
970 ElemTy == Type::getLabelTy(ElemTy->getContext()))
973 if (const PointerType *PTy = dyn_cast<PointerType>(ElemTy))
974 if (PTy->getElementType() == Type::getMetadataTy(ElemTy->getContext()))
981 //===----------------------------------------------------------------------===//
982 // Derived Type Refinement Functions
983 //===----------------------------------------------------------------------===//
985 // addAbstractTypeUser - Notify an abstract type that there is a new user of
986 // it. This function is called primarily by the PATypeHandle class.
987 void Type::addAbstractTypeUser(AbstractTypeUser *U) const {
988 assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
989 AbstractTypeUsersLock->acquire();
990 AbstractTypeUsers.push_back(U);
991 AbstractTypeUsersLock->release();
995 // removeAbstractTypeUser - Notify an abstract type that a user of the class
996 // no longer has a handle to the type. This function is called primarily by
997 // the PATypeHandle class. When there are no users of the abstract type, it
998 // is annihilated, because there is no way to get a reference to it ever again.
1000 void Type::removeAbstractTypeUser(AbstractTypeUser *U) const {
1001 AbstractTypeUsersLock->acquire();
1003 // Search from back to front because we will notify users from back to
1004 // front. Also, it is likely that there will be a stack like behavior to
1005 // users that register and unregister users.
1008 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1009 assert(i != 0 && "AbstractTypeUser not in user list!");
1011 --i; // Convert to be in range 0 <= i < size()
1012 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
1014 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1016 #ifdef DEBUG_MERGE_TYPES
1017 DOUT << " remAbstractTypeUser[" << (void*)this << ", "
1018 << *this << "][" << i << "] User = " << U << "\n";
1021 if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1022 #ifdef DEBUG_MERGE_TYPES
1023 DOUT << "DELETEing unused abstract type: <" << *this
1024 << ">[" << (void*)this << "]" << "\n";
1030 AbstractTypeUsersLock->release();
1033 // unlockedRefineAbstractTypeTo - This function is used when it is discovered
1034 // that the 'this' abstract type is actually equivalent to the NewType
1035 // specified. This causes all users of 'this' to switch to reference the more
1036 // concrete type NewType and for 'this' to be deleted. Only used for internal
1039 void DerivedType::unlockedRefineAbstractTypeTo(const Type *NewType) {
1040 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1041 assert(this != NewType && "Can't refine to myself!");
1042 assert(ForwardType == 0 && "This type has already been refined!");
1044 // The descriptions may be out of date. Conservatively clear them all!
1045 if (AbstractTypeDescriptions.isConstructed())
1046 AbstractTypeDescriptions->clear();
1048 #ifdef DEBUG_MERGE_TYPES
1049 DOUT << "REFINING abstract type [" << (void*)this << " "
1050 << *this << "] to [" << (void*)NewType << " "
1051 << *NewType << "]!\n";
1054 // Make sure to put the type to be refined to into a holder so that if IT gets
1055 // refined, that we will not continue using a dead reference...
1057 PATypeHolder NewTy(NewType);
1058 // Any PATypeHolders referring to this type will now automatically forward o
1059 // the type we are resolved to.
1060 ForwardType = NewType;
1061 if (NewType->isAbstract())
1062 cast<DerivedType>(NewType)->addRef();
1064 // Add a self use of the current type so that we don't delete ourself until
1065 // after the function exits.
1067 PATypeHolder CurrentTy(this);
1069 // To make the situation simpler, we ask the subclass to remove this type from
1070 // the type map, and to replace any type uses with uses of non-abstract types.
1071 // This dramatically limits the amount of recursive type trouble we can find
1075 // Iterate over all of the uses of this type, invoking callback. Each user
1076 // should remove itself from our use list automatically. We have to check to
1077 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1078 // will not cause users to drop off of the use list. If we resolve to ourself
1081 AbstractTypeUsersLock->acquire();
1082 while (!AbstractTypeUsers.empty() && NewTy != this) {
1083 AbstractTypeUser *User = AbstractTypeUsers.back();
1085 unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1086 #ifdef DEBUG_MERGE_TYPES
1087 DOUT << " REFINING user " << OldSize-1 << "[" << (void*)User
1088 << "] of abstract type [" << (void*)this << " "
1089 << *this << "] to [" << (void*)NewTy.get() << " "
1090 << *NewTy << "]!\n";
1092 User->refineAbstractType(this, NewTy);
1094 assert(AbstractTypeUsers.size() != OldSize &&
1095 "AbsTyUser did not remove self from user list!");
1097 AbstractTypeUsersLock->release();
1099 // If we were successful removing all users from the type, 'this' will be
1100 // deleted when the last PATypeHolder is destroyed or updated from this type.
1101 // This may occur on exit of this function, as the CurrentTy object is
1105 // refineAbstractTypeTo - This function is used by external callers to notify
1106 // us that this abstract type is equivalent to another type.
1108 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1109 // All recursive calls will go through unlockedRefineAbstractTypeTo,
1110 // to avoid deadlock problems.
1111 sys::SmartScopedLock<true> L(*TypeMapLock);
1112 unlockedRefineAbstractTypeTo(NewType);
1115 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1116 // the current type has transitioned from being abstract to being concrete.
1118 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1119 #ifdef DEBUG_MERGE_TYPES
1120 DOUT << "typeIsREFINED type: " << (void*)this << " " << *this << "\n";
1123 AbstractTypeUsersLock->acquire();
1124 unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1125 while (!AbstractTypeUsers.empty()) {
1126 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1127 ATU->typeBecameConcrete(this);
1129 assert(AbstractTypeUsers.size() < OldSize-- &&
1130 "AbstractTypeUser did not remove itself from the use list!");
1132 AbstractTypeUsersLock->release();
1135 // refineAbstractType - Called when a contained type is found to be more
1136 // concrete - this could potentially change us from an abstract type to a
1139 void FunctionType::refineAbstractType(const DerivedType *OldType,
1140 const Type *NewType) {
1141 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1142 pImpl->FunctionTypes.RefineAbstractType(this, OldType, NewType);
1145 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1146 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1147 pImpl->FunctionTypes.TypeBecameConcrete(this, AbsTy);
1151 // refineAbstractType - Called when a contained type is found to be more
1152 // concrete - this could potentially change us from an abstract type to a
1155 void ArrayType::refineAbstractType(const DerivedType *OldType,
1156 const Type *NewType) {
1157 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1158 pImpl->ArrayTypes.RefineAbstractType(this, OldType, NewType);
1161 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1162 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1163 pImpl->ArrayTypes.TypeBecameConcrete(this, AbsTy);
1166 // refineAbstractType - Called when a contained type is found to be more
1167 // concrete - this could potentially change us from an abstract type to a
1170 void VectorType::refineAbstractType(const DerivedType *OldType,
1171 const Type *NewType) {
1172 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1173 pImpl->VectorTypes.RefineAbstractType(this, OldType, NewType);
1176 void VectorType::typeBecameConcrete(const DerivedType *AbsTy) {
1177 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1178 pImpl->VectorTypes.TypeBecameConcrete(this, AbsTy);
1181 // refineAbstractType - Called when a contained type is found to be more
1182 // concrete - this could potentially change us from an abstract type to a
1185 void StructType::refineAbstractType(const DerivedType *OldType,
1186 const Type *NewType) {
1187 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1188 pImpl->StructTypes.RefineAbstractType(this, OldType, NewType);
1191 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1192 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1193 pImpl->StructTypes.TypeBecameConcrete(this, AbsTy);
1196 // refineAbstractType - Called when a contained type is found to be more
1197 // concrete - this could potentially change us from an abstract type to a
1200 void PointerType::refineAbstractType(const DerivedType *OldType,
1201 const Type *NewType) {
1202 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1203 pImpl->PointerTypes.RefineAbstractType(this, OldType, NewType);
1206 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1207 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1208 pImpl->PointerTypes.TypeBecameConcrete(this, AbsTy);
1211 bool SequentialType::indexValid(const Value *V) const {
1212 if (isa<IntegerType>(V->getType()))
1218 std::ostream &operator<<(std::ostream &OS, const Type *T) {
1220 OS << "<null> value!\n";
1226 std::ostream &operator<<(std::ostream &OS, const Type &T) {
1231 raw_ostream &operator<<(raw_ostream &OS, const Type &T) {