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/Threading.h"
35 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
36 // created and later destroyed, all in an effort to make sure that there is only
37 // a single canonical version of a type.
39 // #define DEBUG_MERGE_TYPES 1
41 AbstractTypeUser::~AbstractTypeUser() {}
43 void AbstractTypeUser::setType(Value *V, const Type *NewTy) {
47 //===----------------------------------------------------------------------===//
48 // Type Class Implementation
49 //===----------------------------------------------------------------------===//
51 /// Because of the way Type subclasses are allocated, this function is necessary
52 /// to use the correct kind of "delete" operator to deallocate the Type object.
53 /// Some type objects (FunctionTy, StructTy, UnionTy) allocate additional space
54 /// after the space for their derived type to hold the contained types array of
55 /// PATypeHandles. Using this allocation scheme means all the PATypeHandles are
56 /// allocated with the type object, decreasing allocations and eliminating the
57 /// need for a std::vector to be used in the Type class itself.
58 /// @brief Type destruction function
59 void Type::destroy() const {
61 // Structures and Functions allocate their contained types past the end of
62 // the type object itself. These need to be destroyed differently than the
64 if (this->isFunctionTy() || this->isStructTy() ||
66 // First, make sure we destruct any PATypeHandles allocated by these
67 // subclasses. They must be manually destructed.
68 for (unsigned i = 0; i < NumContainedTys; ++i)
69 ContainedTys[i].PATypeHandle::~PATypeHandle();
71 // Now call the destructor for the subclass directly because we're going
72 // to delete this as an array of char.
73 if (this->isFunctionTy())
74 static_cast<const FunctionType*>(this)->FunctionType::~FunctionType();
75 else if (this->isStructTy())
76 static_cast<const StructType*>(this)->StructType::~StructType();
78 static_cast<const UnionType*>(this)->UnionType::~UnionType();
80 // Finally, remove the memory as an array deallocation of the chars it was
82 operator delete(const_cast<Type *>(this));
85 } else if (const OpaqueType *opaque_this = dyn_cast<OpaqueType>(this)) {
86 LLVMContextImpl *pImpl = this->getContext().pImpl;
87 pImpl->OpaqueTypes.erase(opaque_this);
90 // For all the other type subclasses, there is either no contained types or
91 // just one (all Sequentials). For Sequentials, the PATypeHandle is not
92 // allocated past the type object, its included directly in the SequentialType
93 // class. This means we can safely just do "normal" delete of this object and
94 // all the destructors that need to run will be run.
98 const Type *Type::getPrimitiveType(LLVMContext &C, TypeID IDNumber) {
100 case VoidTyID : return getVoidTy(C);
101 case FloatTyID : return getFloatTy(C);
102 case DoubleTyID : return getDoubleTy(C);
103 case X86_FP80TyID : return getX86_FP80Ty(C);
104 case FP128TyID : return getFP128Ty(C);
105 case PPC_FP128TyID : return getPPC_FP128Ty(C);
106 case LabelTyID : return getLabelTy(C);
107 case MetadataTyID : return getMetadataTy(C);
113 const Type *Type::getVAArgsPromotedType(LLVMContext &C) const {
114 if (ID == IntegerTyID && getSubclassData() < 32)
115 return Type::getInt32Ty(C);
116 else if (ID == FloatTyID)
117 return Type::getDoubleTy(C);
122 /// getScalarType - If this is a vector type, return the element type,
123 /// otherwise return this.
124 const Type *Type::getScalarType() const {
125 if (const VectorType *VTy = dyn_cast<VectorType>(this))
126 return VTy->getElementType();
130 /// isIntegerTy - Return true if this is an IntegerType of the specified width.
131 bool Type::isIntegerTy(unsigned Bitwidth) const {
132 return isIntegerTy() && cast<IntegerType>(this)->getBitWidth() == Bitwidth;
135 /// isIntOrIntVectorTy - Return true if this is an integer type or a vector of
138 bool Type::isIntOrIntVectorTy() const {
141 if (ID != Type::VectorTyID) return false;
143 return cast<VectorType>(this)->getElementType()->isIntegerTy();
146 /// isFPOrFPVectorTy - Return true if this is a FP type or a vector of FP types.
148 bool Type::isFPOrFPVectorTy() const {
149 if (ID == Type::FloatTyID || ID == Type::DoubleTyID ||
150 ID == Type::FP128TyID || ID == Type::X86_FP80TyID ||
151 ID == Type::PPC_FP128TyID)
153 if (ID != Type::VectorTyID) return false;
155 return cast<VectorType>(this)->getElementType()->isFloatingPointTy();
158 // canLosslesslyBitCastTo - Return true if this type can be converted to
159 // 'Ty' without any reinterpretation of bits. For example, i8* to i32*.
161 bool Type::canLosslesslyBitCastTo(const Type *Ty) const {
162 // Identity cast means no change so return true
166 // They are not convertible unless they are at least first class types
167 if (!this->isFirstClassType() || !Ty->isFirstClassType())
170 // Vector -> Vector conversions are always lossless if the two vector types
171 // have the same size, otherwise not.
172 if (const VectorType *thisPTy = dyn_cast<VectorType>(this))
173 if (const VectorType *thatPTy = dyn_cast<VectorType>(Ty))
174 return thisPTy->getBitWidth() == thatPTy->getBitWidth();
176 // At this point we have only various mismatches of the first class types
177 // remaining and ptr->ptr. Just select the lossless conversions. Everything
178 // else is not lossless.
179 if (this->isPointerTy())
180 return Ty->isPointerTy();
181 return false; // Other types have no identity values
184 unsigned Type::getPrimitiveSizeInBits() const {
185 switch (getTypeID()) {
186 case Type::FloatTyID: return 32;
187 case Type::DoubleTyID: return 64;
188 case Type::X86_FP80TyID: return 80;
189 case Type::FP128TyID: return 128;
190 case Type::PPC_FP128TyID: return 128;
191 case Type::IntegerTyID: return cast<IntegerType>(this)->getBitWidth();
192 case Type::VectorTyID: return cast<VectorType>(this)->getBitWidth();
197 /// getScalarSizeInBits - If this is a vector type, return the
198 /// getPrimitiveSizeInBits value for the element type. Otherwise return the
199 /// getPrimitiveSizeInBits value for this type.
200 unsigned Type::getScalarSizeInBits() const {
201 return getScalarType()->getPrimitiveSizeInBits();
204 /// getFPMantissaWidth - Return the width of the mantissa of this type. This
205 /// is only valid on floating point types. If the FP type does not
206 /// have a stable mantissa (e.g. ppc long double), this method returns -1.
207 int Type::getFPMantissaWidth() const {
208 if (const VectorType *VTy = dyn_cast<VectorType>(this))
209 return VTy->getElementType()->getFPMantissaWidth();
210 assert(isFloatingPointTy() && "Not a floating point type!");
211 if (ID == FloatTyID) return 24;
212 if (ID == DoubleTyID) return 53;
213 if (ID == X86_FP80TyID) return 64;
214 if (ID == FP128TyID) return 113;
215 assert(ID == PPC_FP128TyID && "unknown fp type");
219 /// isSizedDerivedType - Derived types like structures and arrays are sized
220 /// iff all of the members of the type are sized as well. Since asking for
221 /// their size is relatively uncommon, move this operation out of line.
222 bool Type::isSizedDerivedType() const {
223 if (this->isIntegerTy())
226 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
227 return ATy->getElementType()->isSized();
229 if (const VectorType *PTy = dyn_cast<VectorType>(this))
230 return PTy->getElementType()->isSized();
232 if (!this->isStructTy() && !this->isUnionTy())
235 // Okay, our struct is sized if all of the elements are...
236 for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I)
237 if (!(*I)->isSized())
243 /// getForwardedTypeInternal - This method is used to implement the union-find
244 /// algorithm for when a type is being forwarded to another type.
245 const Type *Type::getForwardedTypeInternal() const {
246 assert(ForwardType && "This type is not being forwarded to another type!");
248 // Check to see if the forwarded type has been forwarded on. If so, collapse
249 // the forwarding links.
250 const Type *RealForwardedType = ForwardType->getForwardedType();
251 if (!RealForwardedType)
252 return ForwardType; // No it's not forwarded again
254 // Yes, it is forwarded again. First thing, add the reference to the new
256 if (RealForwardedType->isAbstract())
257 cast<DerivedType>(RealForwardedType)->addRef();
259 // Now drop the old reference. This could cause ForwardType to get deleted.
260 cast<DerivedType>(ForwardType)->dropRef();
262 // Return the updated type.
263 ForwardType = RealForwardedType;
267 void Type::refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
268 llvm_unreachable("Attempting to refine a derived type!");
270 void Type::typeBecameConcrete(const DerivedType *AbsTy) {
271 llvm_unreachable("DerivedType is already a concrete type!");
275 std::string Type::getDescription() const {
276 LLVMContextImpl *pImpl = getContext().pImpl;
279 pImpl->AbstractTypeDescriptions :
280 pImpl->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()->isIntegerTy(32))
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];
315 bool UnionType::indexValid(const Value *V) const {
316 // Union indexes require 32-bit integer constants.
317 if (V->getType()->isIntegerTy(32))
318 if (const ConstantInt *CU = dyn_cast<ConstantInt>(V))
319 return indexValid(CU->getZExtValue());
323 bool UnionType::indexValid(unsigned V) const {
324 return V < NumContainedTys;
327 // getTypeAtIndex - Given an index value into the type, return the type of the
328 // element. For a structure type, this must be a constant value...
330 const Type *UnionType::getTypeAtIndex(const Value *V) const {
331 unsigned Idx = (unsigned)cast<ConstantInt>(V)->getZExtValue();
332 return getTypeAtIndex(Idx);
335 const Type *UnionType::getTypeAtIndex(unsigned Idx) const {
336 assert(indexValid(Idx) && "Invalid structure index!");
337 return ContainedTys[Idx];
340 //===----------------------------------------------------------------------===//
341 // Primitive 'Type' data
342 //===----------------------------------------------------------------------===//
344 const Type *Type::getVoidTy(LLVMContext &C) {
345 return &C.pImpl->VoidTy;
348 const Type *Type::getLabelTy(LLVMContext &C) {
349 return &C.pImpl->LabelTy;
352 const Type *Type::getFloatTy(LLVMContext &C) {
353 return &C.pImpl->FloatTy;
356 const Type *Type::getDoubleTy(LLVMContext &C) {
357 return &C.pImpl->DoubleTy;
360 const Type *Type::getMetadataTy(LLVMContext &C) {
361 return &C.pImpl->MetadataTy;
364 const Type *Type::getX86_FP80Ty(LLVMContext &C) {
365 return &C.pImpl->X86_FP80Ty;
368 const Type *Type::getFP128Ty(LLVMContext &C) {
369 return &C.pImpl->FP128Ty;
372 const Type *Type::getPPC_FP128Ty(LLVMContext &C) {
373 return &C.pImpl->PPC_FP128Ty;
376 const IntegerType *Type::getInt1Ty(LLVMContext &C) {
377 return &C.pImpl->Int1Ty;
380 const IntegerType *Type::getInt8Ty(LLVMContext &C) {
381 return &C.pImpl->Int8Ty;
384 const IntegerType *Type::getInt16Ty(LLVMContext &C) {
385 return &C.pImpl->Int16Ty;
388 const IntegerType *Type::getInt32Ty(LLVMContext &C) {
389 return &C.pImpl->Int32Ty;
392 const IntegerType *Type::getInt64Ty(LLVMContext &C) {
393 return &C.pImpl->Int64Ty;
396 const PointerType *Type::getFloatPtrTy(LLVMContext &C, unsigned AS) {
397 return getFloatTy(C)->getPointerTo(AS);
400 const PointerType *Type::getDoublePtrTy(LLVMContext &C, unsigned AS) {
401 return getDoubleTy(C)->getPointerTo(AS);
404 const PointerType *Type::getX86_FP80PtrTy(LLVMContext &C, unsigned AS) {
405 return getX86_FP80Ty(C)->getPointerTo(AS);
408 const PointerType *Type::getFP128PtrTy(LLVMContext &C, unsigned AS) {
409 return getFP128Ty(C)->getPointerTo(AS);
412 const PointerType *Type::getPPC_FP128PtrTy(LLVMContext &C, unsigned AS) {
413 return getPPC_FP128Ty(C)->getPointerTo(AS);
416 const PointerType *Type::getInt1PtrTy(LLVMContext &C, unsigned AS) {
417 return getInt1Ty(C)->getPointerTo(AS);
420 const PointerType *Type::getInt8PtrTy(LLVMContext &C, unsigned AS) {
421 return getInt8Ty(C)->getPointerTo(AS);
424 const PointerType *Type::getInt16PtrTy(LLVMContext &C, unsigned AS) {
425 return getInt16Ty(C)->getPointerTo(AS);
428 const PointerType *Type::getInt32PtrTy(LLVMContext &C, unsigned AS) {
429 return getInt32Ty(C)->getPointerTo(AS);
432 const PointerType *Type::getInt64PtrTy(LLVMContext &C, unsigned AS) {
433 return getInt64Ty(C)->getPointerTo(AS);
436 //===----------------------------------------------------------------------===//
437 // Derived Type Constructors
438 //===----------------------------------------------------------------------===//
440 /// isValidReturnType - Return true if the specified type is valid as a return
442 bool FunctionType::isValidReturnType(const Type *RetTy) {
443 return RetTy->getTypeID() != LabelTyID &&
444 RetTy->getTypeID() != MetadataTyID;
447 /// isValidArgumentType - Return true if the specified type is valid as an
449 bool FunctionType::isValidArgumentType(const Type *ArgTy) {
450 return ArgTy->isFirstClassType() || ArgTy->isOpaqueTy();
453 FunctionType::FunctionType(const Type *Result,
454 const std::vector<const Type*> &Params,
456 : DerivedType(Result->getContext(), FunctionTyID), isVarArgs(IsVarArgs) {
457 ContainedTys = reinterpret_cast<PATypeHandle*>(this+1);
458 NumContainedTys = Params.size() + 1; // + 1 for result type
459 assert(isValidReturnType(Result) && "invalid return type for function");
462 bool isAbstract = Result->isAbstract();
463 new (&ContainedTys[0]) PATypeHandle(Result, this);
465 for (unsigned i = 0; i != Params.size(); ++i) {
466 assert(isValidArgumentType(Params[i]) &&
467 "Not a valid type for function argument!");
468 new (&ContainedTys[i+1]) PATypeHandle(Params[i], this);
469 isAbstract |= Params[i]->isAbstract();
472 // Calculate whether or not this type is abstract
473 setAbstract(isAbstract);
476 StructType::StructType(LLVMContext &C,
477 const std::vector<const Type*> &Types, bool isPacked)
478 : CompositeType(C, StructTyID) {
479 ContainedTys = reinterpret_cast<PATypeHandle*>(this + 1);
480 NumContainedTys = Types.size();
481 setSubclassData(isPacked);
482 bool isAbstract = false;
483 for (unsigned i = 0; i < Types.size(); ++i) {
484 assert(Types[i] && "<null> type for structure field!");
485 assert(isValidElementType(Types[i]) &&
486 "Invalid type for structure element!");
487 new (&ContainedTys[i]) PATypeHandle(Types[i], this);
488 isAbstract |= Types[i]->isAbstract();
491 // Calculate whether or not this type is abstract
492 setAbstract(isAbstract);
495 UnionType::UnionType(LLVMContext &C,const Type* const* Types, unsigned NumTypes)
496 : CompositeType(C, UnionTyID) {
497 ContainedTys = reinterpret_cast<PATypeHandle*>(this + 1);
498 NumContainedTys = NumTypes;
499 bool isAbstract = false;
500 for (unsigned i = 0; i < NumTypes; ++i) {
501 assert(Types[i] && "<null> type for union field!");
502 assert(isValidElementType(Types[i]) &&
503 "Invalid type for union element!");
504 new (&ContainedTys[i]) PATypeHandle(Types[i], this);
505 isAbstract |= Types[i]->isAbstract();
508 // Calculate whether or not this type is abstract
509 setAbstract(isAbstract);
512 ArrayType::ArrayType(const Type *ElType, uint64_t NumEl)
513 : SequentialType(ArrayTyID, ElType) {
516 // Calculate whether or not this type is abstract
517 setAbstract(ElType->isAbstract());
520 VectorType::VectorType(const Type *ElType, unsigned NumEl)
521 : SequentialType(VectorTyID, ElType) {
523 setAbstract(ElType->isAbstract());
524 assert(NumEl > 0 && "NumEl of a VectorType must be greater than 0");
525 assert(isValidElementType(ElType) &&
526 "Elements of a VectorType must be a primitive type");
531 PointerType::PointerType(const Type *E, unsigned AddrSpace)
532 : SequentialType(PointerTyID, E) {
533 AddressSpace = AddrSpace;
534 // Calculate whether or not this type is abstract
535 setAbstract(E->isAbstract());
538 OpaqueType::OpaqueType(LLVMContext &C) : DerivedType(C, OpaqueTyID) {
540 #ifdef DEBUG_MERGE_TYPES
541 DEBUG(dbgs() << "Derived new type: " << *this << "\n");
545 void PATypeHolder::destroy() {
549 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
550 // another (more concrete) type, we must eliminate all references to other
551 // types, to avoid some circular reference problems.
552 void DerivedType::dropAllTypeUses() {
553 if (NumContainedTys != 0) {
554 // The type must stay abstract. To do this, we insert a pointer to a type
555 // that will never get resolved, thus will always be abstract.
556 ContainedTys[0] = getContext().pImpl->AlwaysOpaqueTy;
558 // Change the rest of the types to be Int32Ty's. It doesn't matter what we
559 // pick so long as it doesn't point back to this type. We choose something
560 // concrete to avoid overhead for adding to AbstractTypeUser lists and
562 const Type *ConcreteTy = Type::getInt32Ty(getContext());
563 for (unsigned i = 1, e = NumContainedTys; i != e; ++i)
564 ContainedTys[i] = ConcreteTy;
571 /// TypePromotionGraph and graph traits - this is designed to allow us to do
572 /// efficient SCC processing of type graphs. This is the exact same as
573 /// GraphTraits<Type*>, except that we pretend that concrete types have no
574 /// children to avoid processing them.
575 struct TypePromotionGraph {
577 TypePromotionGraph(Type *T) : Ty(T) {}
583 template <> struct GraphTraits<TypePromotionGraph> {
584 typedef Type NodeType;
585 typedef Type::subtype_iterator ChildIteratorType;
587 static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
588 static inline ChildIteratorType child_begin(NodeType *N) {
590 return N->subtype_begin();
591 else // No need to process children of concrete types.
592 return N->subtype_end();
594 static inline ChildIteratorType child_end(NodeType *N) {
595 return N->subtype_end();
601 // PromoteAbstractToConcrete - This is a recursive function that walks a type
602 // graph calculating whether or not a type is abstract.
604 void Type::PromoteAbstractToConcrete() {
605 if (!isAbstract()) return;
607 scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
608 scc_iterator<TypePromotionGraph> SE = scc_end (TypePromotionGraph(this));
610 for (; SI != SE; ++SI) {
611 std::vector<Type*> &SCC = *SI;
613 // Concrete types are leaves in the tree. Since an SCC will either be all
614 // abstract or all concrete, we only need to check one type.
615 if (SCC[0]->isAbstract()) {
616 if (SCC[0]->isOpaqueTy())
617 return; // Not going to be concrete, sorry.
619 // If all of the children of all of the types in this SCC are concrete,
620 // then this SCC is now concrete as well. If not, neither this SCC, nor
621 // any parent SCCs will be concrete, so we might as well just exit.
622 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
623 for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
624 E = SCC[i]->subtype_end(); CI != E; ++CI)
625 if ((*CI)->isAbstract())
626 // If the child type is in our SCC, it doesn't make the entire SCC
627 // abstract unless there is a non-SCC abstract type.
628 if (std::find(SCC.begin(), SCC.end(), *CI) == SCC.end())
629 return; // Not going to be concrete, sorry.
631 // Okay, we just discovered this whole SCC is now concrete, mark it as
633 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
634 assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
636 SCC[i]->setAbstract(false);
639 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
640 assert(!SCC[i]->isAbstract() && "Concrete type became abstract?");
641 // The type just became concrete, notify all users!
642 cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
649 //===----------------------------------------------------------------------===//
650 // Type Structural Equality Testing
651 //===----------------------------------------------------------------------===//
653 // TypesEqual - Two types are considered structurally equal if they have the
654 // same "shape": Every level and element of the types have identical primitive
655 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
656 // be pointer equals to be equivalent though. This uses an optimistic algorithm
657 // that assumes that two graphs are the same until proven otherwise.
659 static bool TypesEqual(const Type *Ty, const Type *Ty2,
660 std::map<const Type *, const Type *> &EqTypes) {
661 if (Ty == Ty2) return true;
662 if (Ty->getTypeID() != Ty2->getTypeID()) return false;
663 if (Ty->isOpaqueTy())
664 return false; // Two unequal opaque types are never equal
666 std::map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
667 if (It != EqTypes.end())
668 return It->second == Ty2; // Looping back on a type, check for equality
670 // Otherwise, add the mapping to the table to make sure we don't get
671 // recursion on the types...
672 EqTypes.insert(It, std::make_pair(Ty, Ty2));
674 // Two really annoying special cases that breaks an otherwise nice simple
675 // algorithm is the fact that arraytypes have sizes that differentiates types,
676 // and that function types can be varargs or not. Consider this now.
678 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
679 const IntegerType *ITy2 = cast<IntegerType>(Ty2);
680 return ITy->getBitWidth() == ITy2->getBitWidth();
681 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
682 const PointerType *PTy2 = cast<PointerType>(Ty2);
683 return PTy->getAddressSpace() == PTy2->getAddressSpace() &&
684 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
685 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
686 const StructType *STy2 = cast<StructType>(Ty2);
687 if (STy->getNumElements() != STy2->getNumElements()) return false;
688 if (STy->isPacked() != STy2->isPacked()) return false;
689 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
690 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
693 } else if (const UnionType *UTy = dyn_cast<UnionType>(Ty)) {
694 const UnionType *UTy2 = cast<UnionType>(Ty2);
695 if (UTy->getNumElements() != UTy2->getNumElements()) return false;
696 for (unsigned i = 0, e = UTy2->getNumElements(); i != e; ++i)
697 if (!TypesEqual(UTy->getElementType(i), UTy2->getElementType(i), EqTypes))
700 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
701 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
702 return ATy->getNumElements() == ATy2->getNumElements() &&
703 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
704 } else if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
705 const VectorType *PTy2 = cast<VectorType>(Ty2);
706 return PTy->getNumElements() == PTy2->getNumElements() &&
707 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
708 } else if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
709 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
710 if (FTy->isVarArg() != FTy2->isVarArg() ||
711 FTy->getNumParams() != FTy2->getNumParams() ||
712 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
714 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i) {
715 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
720 llvm_unreachable("Unknown derived type!");
725 namespace llvm { // in namespace llvm so findable by ADL
726 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
727 std::map<const Type *, const Type *> EqTypes;
728 return ::TypesEqual(Ty, Ty2, EqTypes);
732 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
733 // TargetTy in the type graph. We know that Ty is an abstract type, so if we
734 // ever reach a non-abstract type, we know that we don't need to search the
736 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
737 SmallPtrSet<const Type*, 128> &VisitedTypes) {
738 if (TargetTy == CurTy) return true;
739 if (!CurTy->isAbstract()) return false;
741 if (!VisitedTypes.insert(CurTy))
742 return false; // Already been here.
744 for (Type::subtype_iterator I = CurTy->subtype_begin(),
745 E = CurTy->subtype_end(); I != E; ++I)
746 if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
751 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
752 SmallPtrSet<const Type*, 128> &VisitedTypes) {
753 if (TargetTy == CurTy) return true;
755 if (!VisitedTypes.insert(CurTy))
756 return false; // Already been here.
758 for (Type::subtype_iterator I = CurTy->subtype_begin(),
759 E = CurTy->subtype_end(); I != E; ++I)
760 if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
765 /// TypeHasCycleThroughItself - Return true if the specified type has
766 /// a cycle back to itself.
768 namespace llvm { // in namespace llvm so it's findable by ADL
769 static bool TypeHasCycleThroughItself(const Type *Ty) {
770 SmallPtrSet<const Type*, 128> VisitedTypes;
772 if (Ty->isAbstract()) { // Optimized case for abstract types.
773 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
775 if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
778 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
780 if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
787 //===----------------------------------------------------------------------===//
788 // Function Type Factory and Value Class...
790 const IntegerType *IntegerType::get(LLVMContext &C, unsigned NumBits) {
791 assert(NumBits >= MIN_INT_BITS && "bitwidth too small");
792 assert(NumBits <= MAX_INT_BITS && "bitwidth too large");
794 // Check for the built-in integer types
796 case 1: return cast<IntegerType>(Type::getInt1Ty(C));
797 case 8: return cast<IntegerType>(Type::getInt8Ty(C));
798 case 16: return cast<IntegerType>(Type::getInt16Ty(C));
799 case 32: return cast<IntegerType>(Type::getInt32Ty(C));
800 case 64: return cast<IntegerType>(Type::getInt64Ty(C));
805 LLVMContextImpl *pImpl = C.pImpl;
807 IntegerValType IVT(NumBits);
808 IntegerType *ITy = 0;
810 // First, see if the type is already in the table, for which
811 // a reader lock suffices.
812 ITy = pImpl->IntegerTypes.get(IVT);
815 // Value not found. Derive a new type!
816 ITy = new IntegerType(C, NumBits);
817 pImpl->IntegerTypes.add(IVT, ITy);
819 #ifdef DEBUG_MERGE_TYPES
820 DEBUG(dbgs() << "Derived new type: " << *ITy << "\n");
825 bool IntegerType::isPowerOf2ByteWidth() const {
826 unsigned BitWidth = getBitWidth();
827 return (BitWidth > 7) && isPowerOf2_32(BitWidth);
830 APInt IntegerType::getMask() const {
831 return APInt::getAllOnesValue(getBitWidth());
834 FunctionValType FunctionValType::get(const FunctionType *FT) {
835 // Build up a FunctionValType
836 std::vector<const Type *> ParamTypes;
837 ParamTypes.reserve(FT->getNumParams());
838 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
839 ParamTypes.push_back(FT->getParamType(i));
840 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
844 // FunctionType::get - The factory function for the FunctionType class...
845 FunctionType *FunctionType::get(const Type *ReturnType,
846 const std::vector<const Type*> &Params,
848 FunctionValType VT(ReturnType, Params, isVarArg);
849 FunctionType *FT = 0;
851 LLVMContextImpl *pImpl = ReturnType->getContext().pImpl;
853 FT = pImpl->FunctionTypes.get(VT);
856 FT = (FunctionType*) operator new(sizeof(FunctionType) +
857 sizeof(PATypeHandle)*(Params.size()+1));
858 new (FT) FunctionType(ReturnType, Params, isVarArg);
859 pImpl->FunctionTypes.add(VT, FT);
862 #ifdef DEBUG_MERGE_TYPES
863 DEBUG(dbgs() << "Derived new type: " << FT << "\n");
868 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
869 assert(ElementType && "Can't get array of <null> types!");
870 assert(isValidElementType(ElementType) && "Invalid type for array element!");
872 ArrayValType AVT(ElementType, NumElements);
875 LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
877 AT = pImpl->ArrayTypes.get(AVT);
880 // Value not found. Derive a new type!
881 pImpl->ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
883 #ifdef DEBUG_MERGE_TYPES
884 DEBUG(dbgs() << "Derived new type: " << *AT << "\n");
889 bool ArrayType::isValidElementType(const Type *ElemTy) {
890 return ElemTy->getTypeID() != VoidTyID && ElemTy->getTypeID() != LabelTyID &&
891 ElemTy->getTypeID() != MetadataTyID && !ElemTy->isFunctionTy();
894 VectorType *VectorType::get(const Type *ElementType, unsigned NumElements) {
895 assert(ElementType && "Can't get vector of <null> types!");
897 VectorValType PVT(ElementType, NumElements);
900 LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
902 PT = pImpl->VectorTypes.get(PVT);
905 pImpl->VectorTypes.add(PVT, PT = new VectorType(ElementType, NumElements));
907 #ifdef DEBUG_MERGE_TYPES
908 DEBUG(dbgs() << "Derived new type: " << *PT << "\n");
913 bool VectorType::isValidElementType(const Type *ElemTy) {
914 return ElemTy->isIntegerTy() || ElemTy->isFloatingPointTy() ||
915 ElemTy->isOpaqueTy();
918 //===----------------------------------------------------------------------===//
919 // Struct Type Factory...
922 StructType *StructType::get(LLVMContext &Context,
923 const std::vector<const Type*> &ETypes,
925 StructValType STV(ETypes, isPacked);
928 LLVMContextImpl *pImpl = Context.pImpl;
930 ST = pImpl->StructTypes.get(STV);
933 // Value not found. Derive a new type!
934 ST = (StructType*) operator new(sizeof(StructType) +
935 sizeof(PATypeHandle) * ETypes.size());
936 new (ST) StructType(Context, ETypes, isPacked);
937 pImpl->StructTypes.add(STV, ST);
939 #ifdef DEBUG_MERGE_TYPES
940 DEBUG(dbgs() << "Derived new type: " << *ST << "\n");
945 StructType *StructType::get(LLVMContext &Context, const Type *type, ...) {
947 std::vector<const llvm::Type*> StructFields;
950 StructFields.push_back(type);
951 type = va_arg(ap, llvm::Type*);
953 return llvm::StructType::get(Context, StructFields);
956 bool StructType::isValidElementType(const Type *ElemTy) {
957 return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
958 !ElemTy->isMetadataTy() && !ElemTy->isFunctionTy();
962 //===----------------------------------------------------------------------===//
963 // Union Type Factory...
966 UnionType *UnionType::get(const Type* const* Types, unsigned NumTypes) {
967 assert(NumTypes > 0 && "union must have at least one member type!");
968 UnionValType UTV(Types, NumTypes);
971 LLVMContextImpl *pImpl = Types[0]->getContext().pImpl;
973 UT = pImpl->UnionTypes.get(UTV);
976 // Value not found. Derive a new type!
977 UT = (UnionType*) operator new(sizeof(UnionType) +
978 sizeof(PATypeHandle) * NumTypes);
979 new (UT) UnionType(Types[0]->getContext(), Types, NumTypes);
980 pImpl->UnionTypes.add(UTV, UT);
982 #ifdef DEBUG_MERGE_TYPES
983 DEBUG(dbgs() << "Derived new type: " << *UT << "\n");
988 UnionType *UnionType::get(const Type *type, ...) {
990 SmallVector<const llvm::Type*, 8> UnionFields;
993 UnionFields.push_back(type);
994 type = va_arg(ap, llvm::Type*);
996 unsigned NumTypes = UnionFields.size();
997 assert(NumTypes > 0 && "union must have at least one member type!");
998 return llvm::UnionType::get(&UnionFields[0], NumTypes);
1001 bool UnionType::isValidElementType(const Type *ElemTy) {
1002 return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
1003 !ElemTy->isMetadataTy() && !ElemTy->isFunctionTy();
1006 int UnionType::getElementTypeIndex(const Type *ElemTy) const {
1008 for (UnionType::element_iterator I = element_begin(), E = element_end();
1009 I != E; ++I, ++index) {
1010 if (ElemTy == *I) return index;
1016 //===----------------------------------------------------------------------===//
1017 // Pointer Type Factory...
1020 PointerType *PointerType::get(const Type *ValueType, unsigned AddressSpace) {
1021 assert(ValueType && "Can't get a pointer to <null> type!");
1022 assert(ValueType->getTypeID() != VoidTyID &&
1023 "Pointer to void is not valid, use i8* instead!");
1024 assert(isValidElementType(ValueType) && "Invalid type for pointer element!");
1025 PointerValType PVT(ValueType, AddressSpace);
1027 PointerType *PT = 0;
1029 LLVMContextImpl *pImpl = ValueType->getContext().pImpl;
1031 PT = pImpl->PointerTypes.get(PVT);
1034 // Value not found. Derive a new type!
1035 pImpl->PointerTypes.add(PVT, PT = new PointerType(ValueType, AddressSpace));
1037 #ifdef DEBUG_MERGE_TYPES
1038 DEBUG(dbgs() << "Derived new type: " << *PT << "\n");
1043 const PointerType *Type::getPointerTo(unsigned addrs) const {
1044 return PointerType::get(this, addrs);
1047 bool PointerType::isValidElementType(const Type *ElemTy) {
1048 return ElemTy->getTypeID() != VoidTyID &&
1049 ElemTy->getTypeID() != LabelTyID &&
1050 ElemTy->getTypeID() != MetadataTyID;
1054 //===----------------------------------------------------------------------===//
1055 // Opaque Type Factory...
1058 OpaqueType *OpaqueType::get(LLVMContext &C) {
1059 OpaqueType *OT = new OpaqueType(C); // All opaque types are distinct
1061 LLVMContextImpl *pImpl = C.pImpl;
1062 pImpl->OpaqueTypes.insert(OT);
1068 //===----------------------------------------------------------------------===//
1069 // Derived Type Refinement Functions
1070 //===----------------------------------------------------------------------===//
1072 // addAbstractTypeUser - Notify an abstract type that there is a new user of
1073 // it. This function is called primarily by the PATypeHandle class.
1074 void Type::addAbstractTypeUser(AbstractTypeUser *U) const {
1075 assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
1076 AbstractTypeUsers.push_back(U);
1080 // removeAbstractTypeUser - Notify an abstract type that a user of the class
1081 // no longer has a handle to the type. This function is called primarily by
1082 // the PATypeHandle class. When there are no users of the abstract type, it
1083 // is annihilated, because there is no way to get a reference to it ever again.
1085 void Type::removeAbstractTypeUser(AbstractTypeUser *U) const {
1087 // Search from back to front because we will notify users from back to
1088 // front. Also, it is likely that there will be a stack like behavior to
1089 // users that register and unregister users.
1092 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1093 assert(i != 0 && "AbstractTypeUser not in user list!");
1095 --i; // Convert to be in range 0 <= i < size()
1096 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
1098 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1100 #ifdef DEBUG_MERGE_TYPES
1101 DEBUG(dbgs() << " remAbstractTypeUser[" << (void*)this << ", "
1102 << *this << "][" << i << "] User = " << U << "\n");
1105 if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1106 #ifdef DEBUG_MERGE_TYPES
1107 DEBUG(dbgs() << "DELETEing unused abstract type: <" << *this
1108 << ">[" << (void*)this << "]" << "\n");
1116 // unlockedRefineAbstractTypeTo - This function is used when it is discovered
1117 // that the 'this' abstract type is actually equivalent to the NewType
1118 // specified. This causes all users of 'this' to switch to reference the more
1119 // concrete type NewType and for 'this' to be deleted. Only used for internal
1122 void DerivedType::unlockedRefineAbstractTypeTo(const Type *NewType) {
1123 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1124 assert(this != NewType && "Can't refine to myself!");
1125 assert(ForwardType == 0 && "This type has already been refined!");
1127 LLVMContextImpl *pImpl = getContext().pImpl;
1129 // The descriptions may be out of date. Conservatively clear them all!
1130 pImpl->AbstractTypeDescriptions.clear();
1132 #ifdef DEBUG_MERGE_TYPES
1133 DEBUG(dbgs() << "REFINING abstract type [" << (void*)this << " "
1134 << *this << "] to [" << (void*)NewType << " "
1135 << *NewType << "]!\n");
1138 // Make sure to put the type to be refined to into a holder so that if IT gets
1139 // refined, that we will not continue using a dead reference...
1141 PATypeHolder NewTy(NewType);
1142 // Any PATypeHolders referring to this type will now automatically forward to
1143 // the type we are resolved to.
1144 ForwardType = NewType;
1145 if (NewType->isAbstract())
1146 cast<DerivedType>(NewType)->addRef();
1148 // Add a self use of the current type so that we don't delete ourself until
1149 // after the function exits.
1151 PATypeHolder CurrentTy(this);
1153 // To make the situation simpler, we ask the subclass to remove this type from
1154 // the type map, and to replace any type uses with uses of non-abstract types.
1155 // This dramatically limits the amount of recursive type trouble we can find
1159 // Iterate over all of the uses of this type, invoking callback. Each user
1160 // should remove itself from our use list automatically. We have to check to
1161 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1162 // will not cause users to drop off of the use list. If we resolve to ourself
1165 while (!AbstractTypeUsers.empty() && NewTy != this) {
1166 AbstractTypeUser *User = AbstractTypeUsers.back();
1168 unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1169 #ifdef DEBUG_MERGE_TYPES
1170 DEBUG(dbgs() << " REFINING user " << OldSize-1 << "[" << (void*)User
1171 << "] of abstract type [" << (void*)this << " "
1172 << *this << "] to [" << (void*)NewTy.get() << " "
1173 << *NewTy << "]!\n");
1175 User->refineAbstractType(this, NewTy);
1177 assert(AbstractTypeUsers.size() != OldSize &&
1178 "AbsTyUser did not remove self from user list!");
1181 // If we were successful removing all users from the type, 'this' will be
1182 // deleted when the last PATypeHolder is destroyed or updated from this type.
1183 // This may occur on exit of this function, as the CurrentTy object is
1187 // refineAbstractTypeTo - This function is used by external callers to notify
1188 // us that this abstract type is equivalent to another type.
1190 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1191 // All recursive calls will go through unlockedRefineAbstractTypeTo,
1192 // to avoid deadlock problems.
1193 unlockedRefineAbstractTypeTo(NewType);
1196 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1197 // the current type has transitioned from being abstract to being concrete.
1199 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1200 #ifdef DEBUG_MERGE_TYPES
1201 DEBUG(dbgs() << "typeIsREFINED type: " << (void*)this << " " << *this <<"\n");
1204 unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1205 while (!AbstractTypeUsers.empty()) {
1206 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1207 ATU->typeBecameConcrete(this);
1209 assert(AbstractTypeUsers.size() < OldSize-- &&
1210 "AbstractTypeUser did not remove itself from the use list!");
1214 // refineAbstractType - Called when a contained type is found to be more
1215 // concrete - this could potentially change us from an abstract type to a
1218 void FunctionType::refineAbstractType(const DerivedType *OldType,
1219 const Type *NewType) {
1220 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1221 pImpl->FunctionTypes.RefineAbstractType(this, OldType, NewType);
1224 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1225 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1226 pImpl->FunctionTypes.TypeBecameConcrete(this, AbsTy);
1230 // refineAbstractType - Called when a contained type is found to be more
1231 // concrete - this could potentially change us from an abstract type to a
1234 void ArrayType::refineAbstractType(const DerivedType *OldType,
1235 const Type *NewType) {
1236 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1237 pImpl->ArrayTypes.RefineAbstractType(this, OldType, NewType);
1240 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1241 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1242 pImpl->ArrayTypes.TypeBecameConcrete(this, AbsTy);
1245 // refineAbstractType - Called when a contained type is found to be more
1246 // concrete - this could potentially change us from an abstract type to a
1249 void VectorType::refineAbstractType(const DerivedType *OldType,
1250 const Type *NewType) {
1251 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1252 pImpl->VectorTypes.RefineAbstractType(this, OldType, NewType);
1255 void VectorType::typeBecameConcrete(const DerivedType *AbsTy) {
1256 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1257 pImpl->VectorTypes.TypeBecameConcrete(this, AbsTy);
1260 // refineAbstractType - Called when a contained type is found to be more
1261 // concrete - this could potentially change us from an abstract type to a
1264 void StructType::refineAbstractType(const DerivedType *OldType,
1265 const Type *NewType) {
1266 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1267 pImpl->StructTypes.RefineAbstractType(this, OldType, NewType);
1270 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1271 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1272 pImpl->StructTypes.TypeBecameConcrete(this, AbsTy);
1275 // refineAbstractType - Called when a contained type is found to be more
1276 // concrete - this could potentially change us from an abstract type to a
1279 void UnionType::refineAbstractType(const DerivedType *OldType,
1280 const Type *NewType) {
1281 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1282 pImpl->UnionTypes.RefineAbstractType(this, OldType, NewType);
1285 void UnionType::typeBecameConcrete(const DerivedType *AbsTy) {
1286 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1287 pImpl->UnionTypes.TypeBecameConcrete(this, AbsTy);
1290 // refineAbstractType - Called when a contained type is found to be more
1291 // concrete - this could potentially change us from an abstract type to a
1294 void PointerType::refineAbstractType(const DerivedType *OldType,
1295 const Type *NewType) {
1296 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1297 pImpl->PointerTypes.RefineAbstractType(this, OldType, NewType);
1300 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1301 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1302 pImpl->PointerTypes.TypeBecameConcrete(this, AbsTy);
1305 bool SequentialType::indexValid(const Value *V) const {
1306 if (V->getType()->isIntegerTy())
1312 raw_ostream &operator<<(raw_ostream &OS, const Type &T) {