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/ArrayRef.h"
21 #include "llvm/ADT/DepthFirstIterator.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/SCCIterator.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Support/Threading.h"
36 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
37 // created and later destroyed, all in an effort to make sure that there is only
38 // a single canonical version of a type.
40 // #define DEBUG_MERGE_TYPES 1
42 AbstractTypeUser::~AbstractTypeUser() {}
44 void AbstractTypeUser::setType(Value *V, const Type *NewTy) {
48 //===----------------------------------------------------------------------===//
49 // Type Class Implementation
50 //===----------------------------------------------------------------------===//
52 /// Because of the way Type subclasses are allocated, this function is necessary
53 /// to use the correct kind of "delete" operator to deallocate the Type object.
54 /// Some type objects (FunctionTy, StructTy) allocate additional space
55 /// after the space for their derived type to hold the contained types array of
56 /// PATypeHandles. Using this allocation scheme means all the PATypeHandles are
57 /// allocated with the type object, decreasing allocations and eliminating the
58 /// need for a std::vector to be used in the Type class itself.
59 /// @brief Type destruction function
60 void Type::destroy() const {
61 // Nothing calls getForwardedType from here on.
62 if (ForwardType && ForwardType->isAbstract()) {
63 ForwardType->dropRef();
67 // Structures and Functions allocate their contained types past the end of
68 // the type object itself. These need to be destroyed differently than the
70 if (this->isFunctionTy() || this->isStructTy()) {
71 // First, make sure we destruct any PATypeHandles allocated by these
72 // subclasses. They must be manually destructed.
73 for (unsigned i = 0; i < NumContainedTys; ++i)
74 ContainedTys[i].PATypeHandle::~PATypeHandle();
76 // Now call the destructor for the subclass directly because we're going
77 // to delete this as an array of char.
78 if (this->isFunctionTy())
79 static_cast<const FunctionType*>(this)->FunctionType::~FunctionType();
82 static_cast<const StructType*>(this)->StructType::~StructType();
85 // Finally, remove the memory as an array deallocation of the chars it was
87 operator delete(const_cast<Type *>(this));
90 } else if (const OpaqueType *opaque_this = dyn_cast<OpaqueType>(this)) {
91 LLVMContextImpl *pImpl = this->getContext().pImpl;
92 pImpl->OpaqueTypes.erase(opaque_this);
95 // For all the other type subclasses, there is either no contained types or
96 // just one (all Sequentials). For Sequentials, the PATypeHandle is not
97 // allocated past the type object, its included directly in the SequentialType
98 // class. This means we can safely just do "normal" delete of this object and
99 // all the destructors that need to run will be run.
103 const Type *Type::getPrimitiveType(LLVMContext &C, TypeID IDNumber) {
105 case VoidTyID : return getVoidTy(C);
106 case FloatTyID : return getFloatTy(C);
107 case DoubleTyID : return getDoubleTy(C);
108 case X86_FP80TyID : return getX86_FP80Ty(C);
109 case FP128TyID : return getFP128Ty(C);
110 case PPC_FP128TyID : return getPPC_FP128Ty(C);
111 case LabelTyID : return getLabelTy(C);
112 case MetadataTyID : return getMetadataTy(C);
113 case X86_MMXTyID : return getX86_MMXTy(C);
119 /// getScalarType - If this is a vector type, return the element type,
120 /// otherwise return this.
121 const Type *Type::getScalarType() const {
122 if (const VectorType *VTy = dyn_cast<VectorType>(this))
123 return VTy->getElementType();
127 /// isIntegerTy - Return true if this is an IntegerType of the specified width.
128 bool Type::isIntegerTy(unsigned Bitwidth) const {
129 return isIntegerTy() && cast<IntegerType>(this)->getBitWidth() == Bitwidth;
132 /// isIntOrIntVectorTy - Return true if this is an integer type or a vector of
135 bool Type::isIntOrIntVectorTy() const {
138 if (ID != Type::VectorTyID) return false;
140 return cast<VectorType>(this)->getElementType()->isIntegerTy();
143 /// isFPOrFPVectorTy - Return true if this is a FP type or a vector of FP types.
145 bool Type::isFPOrFPVectorTy() const {
146 if (ID == Type::FloatTyID || ID == Type::DoubleTyID ||
147 ID == Type::FP128TyID || ID == Type::X86_FP80TyID ||
148 ID == Type::PPC_FP128TyID)
150 if (ID != Type::VectorTyID) return false;
152 return cast<VectorType>(this)->getElementType()->isFloatingPointTy();
155 // canLosslesslyBitCastTo - Return true if this type can be converted to
156 // 'Ty' without any reinterpretation of bits. For example, i8* to i32*.
158 bool Type::canLosslesslyBitCastTo(const Type *Ty) const {
159 // Identity cast means no change so return true
163 // They are not convertible unless they are at least first class types
164 if (!this->isFirstClassType() || !Ty->isFirstClassType())
167 // Vector -> Vector conversions are always lossless if the two vector types
168 // have the same size, otherwise not. Also, 64-bit vector types can be
169 // converted to x86mmx.
170 if (const VectorType *thisPTy = dyn_cast<VectorType>(this)) {
171 if (const VectorType *thatPTy = dyn_cast<VectorType>(Ty))
172 return thisPTy->getBitWidth() == thatPTy->getBitWidth();
173 if (Ty->getTypeID() == Type::X86_MMXTyID &&
174 thisPTy->getBitWidth() == 64)
178 if (this->getTypeID() == Type::X86_MMXTyID)
179 if (const VectorType *thatPTy = dyn_cast<VectorType>(Ty))
180 if (thatPTy->getBitWidth() == 64)
183 // At this point we have only various mismatches of the first class types
184 // remaining and ptr->ptr. Just select the lossless conversions. Everything
185 // else is not lossless.
186 if (this->isPointerTy())
187 return Ty->isPointerTy();
188 return false; // Other types have no identity values
191 bool Type::isEmptyTy() const {
192 const ArrayType *ATy = dyn_cast<ArrayType>(this);
194 unsigned NumElements = ATy->getNumElements();
195 return NumElements == 0 || ATy->getElementType()->isEmptyTy();
198 const StructType *STy = dyn_cast<StructType>(this);
200 unsigned NumElements = STy->getNumElements();
201 for (unsigned i = 0; i < NumElements; ++i)
202 if (!STy->getElementType(i)->isEmptyTy())
210 unsigned Type::getPrimitiveSizeInBits() const {
211 switch (getTypeID()) {
212 case Type::FloatTyID: return 32;
213 case Type::DoubleTyID: return 64;
214 case Type::X86_FP80TyID: return 80;
215 case Type::FP128TyID: return 128;
216 case Type::PPC_FP128TyID: return 128;
217 case Type::X86_MMXTyID: return 64;
218 case Type::IntegerTyID: return cast<IntegerType>(this)->getBitWidth();
219 case Type::VectorTyID: return cast<VectorType>(this)->getBitWidth();
224 /// getScalarSizeInBits - If this is a vector type, return the
225 /// getPrimitiveSizeInBits value for the element type. Otherwise return the
226 /// getPrimitiveSizeInBits value for this type.
227 unsigned Type::getScalarSizeInBits() const {
228 return getScalarType()->getPrimitiveSizeInBits();
231 /// getFPMantissaWidth - Return the width of the mantissa of this type. This
232 /// is only valid on floating point types. If the FP type does not
233 /// have a stable mantissa (e.g. ppc long double), this method returns -1.
234 int Type::getFPMantissaWidth() const {
235 if (const VectorType *VTy = dyn_cast<VectorType>(this))
236 return VTy->getElementType()->getFPMantissaWidth();
237 assert(isFloatingPointTy() && "Not a floating point type!");
238 if (ID == FloatTyID) return 24;
239 if (ID == DoubleTyID) return 53;
240 if (ID == X86_FP80TyID) return 64;
241 if (ID == FP128TyID) return 113;
242 assert(ID == PPC_FP128TyID && "unknown fp type");
246 /// isSizedDerivedType - Derived types like structures and arrays are sized
247 /// iff all of the members of the type are sized as well. Since asking for
248 /// their size is relatively uncommon, move this operation out of line.
249 bool Type::isSizedDerivedType() const {
250 if (this->isIntegerTy())
253 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
254 return ATy->getElementType()->isSized();
256 if (const VectorType *PTy = dyn_cast<VectorType>(this))
257 return PTy->getElementType()->isSized();
259 if (!this->isStructTy())
262 // Okay, our struct is sized if all of the elements are...
263 for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I)
264 if (!(*I)->isSized())
270 /// getForwardedTypeInternal - This method is used to implement the union-find
271 /// algorithm for when a type is being forwarded to another type.
272 const Type *Type::getForwardedTypeInternal() const {
273 assert(ForwardType && "This type is not being forwarded to another type!");
275 // Check to see if the forwarded type has been forwarded on. If so, collapse
276 // the forwarding links.
277 const Type *RealForwardedType = ForwardType->getForwardedType();
278 if (!RealForwardedType)
279 return ForwardType; // No it's not forwarded again
281 // Yes, it is forwarded again. First thing, add the reference to the new
283 if (RealForwardedType->isAbstract())
284 RealForwardedType->addRef();
286 // Now drop the old reference. This could cause ForwardType to get deleted.
287 // ForwardType must be abstract because only abstract types can have their own
289 ForwardType->dropRef();
291 // Return the updated type.
292 ForwardType = RealForwardedType;
296 void Type::refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
297 llvm_unreachable("Attempting to refine a derived type!");
299 void Type::typeBecameConcrete(const DerivedType *AbsTy) {
300 llvm_unreachable("DerivedType is already a concrete type!");
304 std::string Type::getDescription() const {
305 LLVMContextImpl *pImpl = getContext().pImpl;
308 pImpl->AbstractTypeDescriptions :
309 pImpl->ConcreteTypeDescriptions;
312 raw_string_ostream DescOS(DescStr);
313 Map.print(this, DescOS);
318 bool StructType::indexValid(const Value *V) const {
319 // Structure indexes require 32-bit integer constants.
320 if (V->getType()->isIntegerTy(32))
321 if (const ConstantInt *CU = dyn_cast<ConstantInt>(V))
322 return indexValid(CU->getZExtValue());
326 bool StructType::indexValid(unsigned V) const {
327 return V < NumContainedTys;
330 // getTypeAtIndex - Given an index value into the type, return the type of the
331 // element. For a structure type, this must be a constant value...
333 const Type *StructType::getTypeAtIndex(const Value *V) const {
334 unsigned Idx = (unsigned)cast<ConstantInt>(V)->getZExtValue();
335 return getTypeAtIndex(Idx);
338 const Type *StructType::getTypeAtIndex(unsigned Idx) const {
339 assert(indexValid(Idx) && "Invalid structure index!");
340 return ContainedTys[Idx];
344 //===----------------------------------------------------------------------===//
345 // Primitive 'Type' data
346 //===----------------------------------------------------------------------===//
348 const Type *Type::getVoidTy(LLVMContext &C) {
349 return &C.pImpl->VoidTy;
352 const Type *Type::getLabelTy(LLVMContext &C) {
353 return &C.pImpl->LabelTy;
356 const Type *Type::getFloatTy(LLVMContext &C) {
357 return &C.pImpl->FloatTy;
360 const Type *Type::getDoubleTy(LLVMContext &C) {
361 return &C.pImpl->DoubleTy;
364 const Type *Type::getMetadataTy(LLVMContext &C) {
365 return &C.pImpl->MetadataTy;
368 const Type *Type::getX86_FP80Ty(LLVMContext &C) {
369 return &C.pImpl->X86_FP80Ty;
372 const Type *Type::getFP128Ty(LLVMContext &C) {
373 return &C.pImpl->FP128Ty;
376 const Type *Type::getPPC_FP128Ty(LLVMContext &C) {
377 return &C.pImpl->PPC_FP128Ty;
380 const Type *Type::getX86_MMXTy(LLVMContext &C) {
381 return &C.pImpl->X86_MMXTy;
384 const IntegerType *Type::getIntNTy(LLVMContext &C, unsigned N) {
385 return IntegerType::get(C, N);
388 const IntegerType *Type::getInt1Ty(LLVMContext &C) {
389 return &C.pImpl->Int1Ty;
392 const IntegerType *Type::getInt8Ty(LLVMContext &C) {
393 return &C.pImpl->Int8Ty;
396 const IntegerType *Type::getInt16Ty(LLVMContext &C) {
397 return &C.pImpl->Int16Ty;
400 const IntegerType *Type::getInt32Ty(LLVMContext &C) {
401 return &C.pImpl->Int32Ty;
404 const IntegerType *Type::getInt64Ty(LLVMContext &C) {
405 return &C.pImpl->Int64Ty;
408 const PointerType *Type::getFloatPtrTy(LLVMContext &C, unsigned AS) {
409 return getFloatTy(C)->getPointerTo(AS);
412 const PointerType *Type::getDoublePtrTy(LLVMContext &C, unsigned AS) {
413 return getDoubleTy(C)->getPointerTo(AS);
416 const PointerType *Type::getX86_FP80PtrTy(LLVMContext &C, unsigned AS) {
417 return getX86_FP80Ty(C)->getPointerTo(AS);
420 const PointerType *Type::getFP128PtrTy(LLVMContext &C, unsigned AS) {
421 return getFP128Ty(C)->getPointerTo(AS);
424 const PointerType *Type::getPPC_FP128PtrTy(LLVMContext &C, unsigned AS) {
425 return getPPC_FP128Ty(C)->getPointerTo(AS);
428 const PointerType *Type::getX86_MMXPtrTy(LLVMContext &C, unsigned AS) {
429 return getX86_MMXTy(C)->getPointerTo(AS);
432 const PointerType *Type::getIntNPtrTy(LLVMContext &C, unsigned N, unsigned AS) {
433 return getIntNTy(C, N)->getPointerTo(AS);
436 const PointerType *Type::getInt1PtrTy(LLVMContext &C, unsigned AS) {
437 return getInt1Ty(C)->getPointerTo(AS);
440 const PointerType *Type::getInt8PtrTy(LLVMContext &C, unsigned AS) {
441 return getInt8Ty(C)->getPointerTo(AS);
444 const PointerType *Type::getInt16PtrTy(LLVMContext &C, unsigned AS) {
445 return getInt16Ty(C)->getPointerTo(AS);
448 const PointerType *Type::getInt32PtrTy(LLVMContext &C, unsigned AS) {
449 return getInt32Ty(C)->getPointerTo(AS);
452 const PointerType *Type::getInt64PtrTy(LLVMContext &C, unsigned AS) {
453 return getInt64Ty(C)->getPointerTo(AS);
456 //===----------------------------------------------------------------------===//
457 // Derived Type Constructors
458 //===----------------------------------------------------------------------===//
460 /// isValidReturnType - Return true if the specified type is valid as a return
462 bool FunctionType::isValidReturnType(const Type *RetTy) {
463 return !RetTy->isFunctionTy() && !RetTy->isLabelTy() &&
464 !RetTy->isMetadataTy();
467 /// isValidArgumentType - Return true if the specified type is valid as an
469 bool FunctionType::isValidArgumentType(const Type *ArgTy) {
470 return ArgTy->isFirstClassType() || ArgTy->isOpaqueTy();
473 FunctionType::FunctionType(const Type *Result,
474 ArrayRef<const Type*> Params,
476 : DerivedType(Result->getContext(), FunctionTyID) {
477 ContainedTys = reinterpret_cast<PATypeHandle*>(this+1);
478 NumContainedTys = Params.size() + 1; // + 1 for result type
479 assert(isValidReturnType(Result) && "invalid return type for function");
480 setSubclassData(IsVarArgs);
482 bool isAbstract = Result->isAbstract();
483 new (&ContainedTys[0]) PATypeHandle(Result, this);
485 for (unsigned i = 0; i != Params.size(); ++i) {
486 assert(isValidArgumentType(Params[i]) &&
487 "Not a valid type for function argument!");
488 new (&ContainedTys[i+1]) PATypeHandle(Params[i], this);
489 isAbstract |= Params[i]->isAbstract();
492 // Calculate whether or not this type is abstract
493 setAbstract(isAbstract);
496 StructType::StructType(LLVMContext &C,
497 ArrayRef<const Type*> Types, bool isPacked)
498 : CompositeType(C, StructTyID) {
499 ContainedTys = reinterpret_cast<PATypeHandle*>(this + 1);
500 NumContainedTys = Types.size();
501 setSubclassData(isPacked);
502 bool isAbstract = false;
503 for (unsigned i = 0; i < Types.size(); ++i) {
504 assert(Types[i] && "<null> type for structure field!");
505 assert(isValidElementType(Types[i]) &&
506 "Invalid type for structure element!");
507 new (&ContainedTys[i]) PATypeHandle(Types[i], this);
508 isAbstract |= Types[i]->isAbstract();
511 // Calculate whether or not this type is abstract
512 setAbstract(isAbstract);
515 ArrayType::ArrayType(const Type *ElType, uint64_t NumEl)
516 : SequentialType(ArrayTyID, ElType) {
519 // Calculate whether or not this type is abstract
520 setAbstract(ElType->isAbstract());
523 VectorType::VectorType(const Type *ElType, unsigned NumEl)
524 : SequentialType(VectorTyID, ElType) {
526 setAbstract(ElType->isAbstract());
527 assert(NumEl > 0 && "NumEl of a VectorType must be greater than 0");
528 assert(isValidElementType(ElType) &&
529 "Elements of a VectorType must be a primitive type");
534 PointerType::PointerType(const Type *E, unsigned AddrSpace)
535 : SequentialType(PointerTyID, E) {
536 AddressSpace = AddrSpace;
537 // Calculate whether or not this type is abstract
538 setAbstract(E->isAbstract());
541 OpaqueType::OpaqueType(LLVMContext &C) : DerivedType(C, OpaqueTyID) {
543 #ifdef DEBUG_MERGE_TYPES
544 DEBUG(dbgs() << "Derived new type: " << *this << "\n");
548 void PATypeHolder::destroy() {
552 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
553 // another (more concrete) type, we must eliminate all references to other
554 // types, to avoid some circular reference problems.
555 void DerivedType::dropAllTypeUses() {
556 if (NumContainedTys != 0) {
557 // The type must stay abstract. To do this, we insert a pointer to a type
558 // that will never get resolved, thus will always be abstract.
559 ContainedTys[0] = getContext().pImpl->AlwaysOpaqueTy;
561 // Change the rest of the types to be Int32Ty's. It doesn't matter what we
562 // pick so long as it doesn't point back to this type. We choose something
563 // concrete to avoid overhead for adding to AbstractTypeUser lists and
565 const Type *ConcreteTy = Type::getInt32Ty(getContext());
566 for (unsigned i = 1, e = NumContainedTys; i != e; ++i)
567 ContainedTys[i] = ConcreteTy;
574 /// TypePromotionGraph and graph traits - this is designed to allow us to do
575 /// efficient SCC processing of type graphs. This is the exact same as
576 /// GraphTraits<Type*>, except that we pretend that concrete types have no
577 /// children to avoid processing them.
578 struct TypePromotionGraph {
580 TypePromotionGraph(Type *T) : Ty(T) {}
586 template <> struct GraphTraits<TypePromotionGraph> {
587 typedef Type NodeType;
588 typedef Type::subtype_iterator ChildIteratorType;
590 static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
591 static inline ChildIteratorType child_begin(NodeType *N) {
593 return N->subtype_begin();
594 // No need to process children of concrete types.
595 return N->subtype_end();
597 static inline ChildIteratorType child_end(NodeType *N) {
598 return N->subtype_end();
604 // PromoteAbstractToConcrete - This is a recursive function that walks a type
605 // graph calculating whether or not a type is abstract.
607 void Type::PromoteAbstractToConcrete() {
608 if (!isAbstract()) return;
610 scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
611 scc_iterator<TypePromotionGraph> SE = scc_end (TypePromotionGraph(this));
613 for (; SI != SE; ++SI) {
614 std::vector<Type*> &SCC = *SI;
616 // Concrete types are leaves in the tree. Since an SCC will either be all
617 // abstract or all concrete, we only need to check one type.
618 if (!SCC[0]->isAbstract()) continue;
620 if (SCC[0]->isOpaqueTy())
621 return; // Not going to be concrete, sorry.
623 // If all of the children of all of the types in this SCC are concrete,
624 // then this SCC is now concrete as well. If not, neither this SCC, nor
625 // any parent SCCs will be concrete, so we might as well just exit.
626 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
627 for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
628 E = SCC[i]->subtype_end(); CI != E; ++CI)
629 if ((*CI)->isAbstract())
630 // If the child type is in our SCC, it doesn't make the entire SCC
631 // abstract unless there is a non-SCC abstract type.
632 if (std::find(SCC.begin(), SCC.end(), *CI) == SCC.end())
633 return; // Not going to be concrete, sorry.
635 // Okay, we just discovered this whole SCC is now concrete, mark it as
637 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
638 assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
640 SCC[i]->setAbstract(false);
643 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
644 assert(!SCC[i]->isAbstract() && "Concrete type became abstract?");
645 // The type just became concrete, notify all users!
646 cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
652 //===----------------------------------------------------------------------===//
653 // Type Structural Equality Testing
654 //===----------------------------------------------------------------------===//
656 // TypesEqual - Two types are considered structurally equal if they have the
657 // same "shape": Every level and element of the types have identical primitive
658 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
659 // be pointer equals to be equivalent though. This uses an optimistic algorithm
660 // that assumes that two graphs are the same until proven otherwise.
662 static bool TypesEqual(const Type *Ty, const Type *Ty2,
663 std::map<const Type *, const Type *> &EqTypes) {
664 if (Ty == Ty2) return true;
665 if (Ty->getTypeID() != Ty2->getTypeID()) return false;
666 if (Ty->isOpaqueTy())
667 return false; // Two unequal opaque types are never equal
669 std::map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
670 if (It != EqTypes.end())
671 return It->second == Ty2; // Looping back on a type, check for equality
673 // Otherwise, add the mapping to the table to make sure we don't get
674 // recursion on the types...
675 EqTypes.insert(It, std::make_pair(Ty, Ty2));
677 // Two really annoying special cases that breaks an otherwise nice simple
678 // algorithm is the fact that arraytypes have sizes that differentiates types,
679 // and that function types can be varargs or not. Consider this now.
681 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
682 const IntegerType *ITy2 = cast<IntegerType>(Ty2);
683 return ITy->getBitWidth() == ITy2->getBitWidth();
686 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
687 const PointerType *PTy2 = cast<PointerType>(Ty2);
688 return PTy->getAddressSpace() == PTy2->getAddressSpace() &&
689 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
692 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
693 const StructType *STy2 = cast<StructType>(Ty2);
694 if (STy->getNumElements() != STy2->getNumElements()) return false;
695 if (STy->isPacked() != STy2->isPacked()) return false;
696 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
697 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
702 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
703 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
704 return ATy->getNumElements() == ATy2->getNumElements() &&
705 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
708 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
709 const VectorType *PTy2 = cast<VectorType>(Ty2);
710 return PTy->getNumElements() == PTy2->getNumElements() &&
711 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
714 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
715 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
716 if (FTy->isVarArg() != FTy2->isVarArg() ||
717 FTy->getNumParams() != FTy2->getNumParams() ||
718 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
720 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i) {
721 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
727 llvm_unreachable("Unknown derived type!");
731 namespace llvm { // in namespace llvm so findable by ADL
732 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
733 std::map<const Type *, const Type *> EqTypes;
734 return ::TypesEqual(Ty, Ty2, EqTypes);
738 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
739 // TargetTy in the type graph. We know that Ty is an abstract type, so if we
740 // ever reach a non-abstract type, we know that we don't need to search the
742 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
743 SmallPtrSet<const Type*, 128> &VisitedTypes) {
744 if (TargetTy == CurTy) return true;
745 if (!CurTy->isAbstract()) return false;
747 if (!VisitedTypes.insert(CurTy))
748 return false; // Already been here.
750 for (Type::subtype_iterator I = CurTy->subtype_begin(),
751 E = CurTy->subtype_end(); I != E; ++I)
752 if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
757 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
758 SmallPtrSet<const Type*, 128> &VisitedTypes) {
759 if (TargetTy == CurTy) return true;
761 if (!VisitedTypes.insert(CurTy))
762 return false; // Already been here.
764 for (Type::subtype_iterator I = CurTy->subtype_begin(),
765 E = CurTy->subtype_end(); I != E; ++I)
766 if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
771 /// TypeHasCycleThroughItself - Return true if the specified type has
772 /// a cycle back to itself.
774 namespace llvm { // in namespace llvm so it's findable by ADL
775 static bool TypeHasCycleThroughItself(const Type *Ty) {
776 SmallPtrSet<const Type*, 128> VisitedTypes;
778 if (Ty->isAbstract()) { // Optimized case for abstract types.
779 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
781 if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
784 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
786 if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
793 //===----------------------------------------------------------------------===//
794 // Function Type Factory and Value Class...
796 const IntegerType *IntegerType::get(LLVMContext &C, unsigned NumBits) {
797 assert(NumBits >= MIN_INT_BITS && "bitwidth too small");
798 assert(NumBits <= MAX_INT_BITS && "bitwidth too large");
800 // Check for the built-in integer types
802 case 1: return cast<IntegerType>(Type::getInt1Ty(C));
803 case 8: return cast<IntegerType>(Type::getInt8Ty(C));
804 case 16: return cast<IntegerType>(Type::getInt16Ty(C));
805 case 32: return cast<IntegerType>(Type::getInt32Ty(C));
806 case 64: return cast<IntegerType>(Type::getInt64Ty(C));
811 LLVMContextImpl *pImpl = C.pImpl;
813 IntegerValType IVT(NumBits);
814 IntegerType *ITy = 0;
816 // First, see if the type is already in the table, for which
817 // a reader lock suffices.
818 ITy = pImpl->IntegerTypes.get(IVT);
821 // Value not found. Derive a new type!
822 ITy = new IntegerType(C, NumBits);
823 pImpl->IntegerTypes.add(IVT, ITy);
825 #ifdef DEBUG_MERGE_TYPES
826 DEBUG(dbgs() << "Derived new type: " << *ITy << "\n");
831 bool IntegerType::isPowerOf2ByteWidth() const {
832 unsigned BitWidth = getBitWidth();
833 return (BitWidth > 7) && isPowerOf2_32(BitWidth);
836 APInt IntegerType::getMask() const {
837 return APInt::getAllOnesValue(getBitWidth());
840 FunctionValType FunctionValType::get(const FunctionType *FT) {
841 // Build up a FunctionValType
842 std::vector<const Type *> ParamTypes;
843 ParamTypes.reserve(FT->getNumParams());
844 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
845 ParamTypes.push_back(FT->getParamType(i));
846 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
850 // FunctionType::get - The factory function for the FunctionType class...
851 FunctionType *FunctionType::get(const Type *ReturnType,
852 ArrayRef<const Type*> Params,
854 FunctionValType VT(ReturnType, Params, isVarArg);
855 FunctionType *FT = 0;
857 LLVMContextImpl *pImpl = ReturnType->getContext().pImpl;
859 FT = pImpl->FunctionTypes.get(VT);
862 FT = (FunctionType*) operator new(sizeof(FunctionType) +
863 sizeof(PATypeHandle)*(Params.size()+1));
864 new (FT) FunctionType(ReturnType, Params, isVarArg);
865 pImpl->FunctionTypes.add(VT, FT);
868 #ifdef DEBUG_MERGE_TYPES
869 DEBUG(dbgs() << "Derived new type: " << FT << "\n");
874 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
875 assert(ElementType && "Can't get array of <null> types!");
876 assert(isValidElementType(ElementType) && "Invalid type for array element!");
878 ArrayValType AVT(ElementType, NumElements);
881 LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
883 AT = pImpl->ArrayTypes.get(AVT);
886 // Value not found. Derive a new type!
887 pImpl->ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
889 #ifdef DEBUG_MERGE_TYPES
890 DEBUG(dbgs() << "Derived new type: " << *AT << "\n");
895 bool ArrayType::isValidElementType(const Type *ElemTy) {
896 return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
897 !ElemTy->isMetadataTy() && !ElemTy->isFunctionTy();
900 VectorType *VectorType::get(const Type *ElementType, unsigned NumElements) {
901 assert(ElementType && "Can't get vector of <null> types!");
903 VectorValType PVT(ElementType, NumElements);
906 LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
908 PT = pImpl->VectorTypes.get(PVT);
911 pImpl->VectorTypes.add(PVT, PT = new VectorType(ElementType, NumElements));
913 #ifdef DEBUG_MERGE_TYPES
914 DEBUG(dbgs() << "Derived new type: " << *PT << "\n");
919 bool VectorType::isValidElementType(const Type *ElemTy) {
920 return ElemTy->isIntegerTy() || ElemTy->isFloatingPointTy() ||
921 ElemTy->isOpaqueTy();
924 //===----------------------------------------------------------------------===//
925 // Struct Type Factory...
928 StructType *StructType::get(LLVMContext &Context,
929 ArrayRef<const Type*> ETypes,
931 StructValType STV(ETypes, isPacked);
934 LLVMContextImpl *pImpl = Context.pImpl;
936 ST = pImpl->StructTypes.get(STV);
939 // Value not found. Derive a new type!
940 ST = (StructType*) operator new(sizeof(StructType) +
941 sizeof(PATypeHandle) * ETypes.size());
942 new (ST) StructType(Context, ETypes, isPacked);
943 pImpl->StructTypes.add(STV, ST);
945 #ifdef DEBUG_MERGE_TYPES
946 DEBUG(dbgs() << "Derived new type: " << *ST << "\n");
951 StructType *StructType::get(LLVMContext &Context, const Type *type, ...) {
953 std::vector<const llvm::Type*> StructFields;
956 StructFields.push_back(type);
957 type = va_arg(ap, llvm::Type*);
959 return llvm::StructType::get(Context, StructFields);
962 bool StructType::isValidElementType(const Type *ElemTy) {
963 return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
964 !ElemTy->isMetadataTy() && !ElemTy->isFunctionTy();
968 //===----------------------------------------------------------------------===//
969 // Pointer Type Factory...
972 PointerType *PointerType::get(const Type *ValueType, unsigned AddressSpace) {
973 assert(ValueType && "Can't get a pointer to <null> type!");
974 assert(ValueType->getTypeID() != VoidTyID &&
975 "Pointer to void is not valid, use i8* instead!");
976 assert(isValidElementType(ValueType) && "Invalid type for pointer element!");
977 PointerValType PVT(ValueType, AddressSpace);
981 LLVMContextImpl *pImpl = ValueType->getContext().pImpl;
983 PT = pImpl->PointerTypes.get(PVT);
986 // Value not found. Derive a new type!
987 pImpl->PointerTypes.add(PVT, PT = new PointerType(ValueType, AddressSpace));
989 #ifdef DEBUG_MERGE_TYPES
990 DEBUG(dbgs() << "Derived new type: " << *PT << "\n");
995 const PointerType *Type::getPointerTo(unsigned addrs) const {
996 return PointerType::get(this, addrs);
999 bool PointerType::isValidElementType(const Type *ElemTy) {
1000 return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
1001 !ElemTy->isMetadataTy();
1005 //===----------------------------------------------------------------------===//
1006 // Opaque Type Factory...
1009 OpaqueType *OpaqueType::get(LLVMContext &C) {
1010 OpaqueType *OT = new OpaqueType(C); // All opaque types are distinct.
1011 LLVMContextImpl *pImpl = C.pImpl;
1012 pImpl->OpaqueTypes.insert(OT);
1018 //===----------------------------------------------------------------------===//
1019 // Derived Type Refinement Functions
1020 //===----------------------------------------------------------------------===//
1022 // addAbstractTypeUser - Notify an abstract type that there is a new user of
1023 // it. This function is called primarily by the PATypeHandle class.
1024 void Type::addAbstractTypeUser(AbstractTypeUser *U) const {
1025 assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
1026 AbstractTypeUsers.push_back(U);
1030 // removeAbstractTypeUser - Notify an abstract type that a user of the class
1031 // no longer has a handle to the type. This function is called primarily by
1032 // the PATypeHandle class. When there are no users of the abstract type, it
1033 // is annihilated, because there is no way to get a reference to it ever again.
1035 void Type::removeAbstractTypeUser(AbstractTypeUser *U) const {
1037 // Search from back to front because we will notify users from back to
1038 // front. Also, it is likely that there will be a stack like behavior to
1039 // users that register and unregister users.
1042 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1043 assert(i != 0 && "AbstractTypeUser not in user list!");
1045 --i; // Convert to be in range 0 <= i < size()
1046 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
1048 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1050 #ifdef DEBUG_MERGE_TYPES
1051 DEBUG(dbgs() << " remAbstractTypeUser[" << (void*)this << ", "
1052 << *this << "][" << i << "] User = " << U << "\n");
1055 if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1056 #ifdef DEBUG_MERGE_TYPES
1057 DEBUG(dbgs() << "DELETEing unused abstract type: <" << *this
1058 << ">[" << (void*)this << "]" << "\n");
1065 // refineAbstractTypeTo - This function is used when it is discovered
1066 // that the 'this' abstract type is actually equivalent to the NewType
1067 // specified. This causes all users of 'this' to switch to reference the more
1068 // concrete type NewType and for 'this' to be deleted. Only used for internal
1071 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1072 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1073 assert(this != NewType && "Can't refine to myself!");
1074 assert(ForwardType == 0 && "This type has already been refined!");
1076 LLVMContextImpl *pImpl = getContext().pImpl;
1078 // The descriptions may be out of date. Conservatively clear them all!
1079 pImpl->AbstractTypeDescriptions.clear();
1081 #ifdef DEBUG_MERGE_TYPES
1082 DEBUG(dbgs() << "REFINING abstract type [" << (void*)this << " "
1083 << *this << "] to [" << (void*)NewType << " "
1084 << *NewType << "]!\n");
1087 // Make sure to put the type to be refined to into a holder so that if IT gets
1088 // refined, that we will not continue using a dead reference...
1090 PATypeHolder NewTy(NewType);
1091 // Any PATypeHolders referring to this type will now automatically forward to
1092 // the type we are resolved to.
1093 ForwardType = NewType;
1094 if (ForwardType->isAbstract())
1095 ForwardType->addRef();
1097 // Add a self use of the current type so that we don't delete ourself until
1098 // after the function exits.
1100 PATypeHolder CurrentTy(this);
1102 // To make the situation simpler, we ask the subclass to remove this type from
1103 // the type map, and to replace any type uses with uses of non-abstract types.
1104 // This dramatically limits the amount of recursive type trouble we can find
1108 // Iterate over all of the uses of this type, invoking callback. Each user
1109 // should remove itself from our use list automatically. We have to check to
1110 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1111 // will not cause users to drop off of the use list. If we resolve to ourself
1114 while (!AbstractTypeUsers.empty() && NewTy != this) {
1115 AbstractTypeUser *User = AbstractTypeUsers.back();
1117 unsigned OldSize = AbstractTypeUsers.size(); (void)OldSize;
1118 #ifdef DEBUG_MERGE_TYPES
1119 DEBUG(dbgs() << " REFINING user " << OldSize-1 << "[" << (void*)User
1120 << "] of abstract type [" << (void*)this << " "
1121 << *this << "] to [" << (void*)NewTy.get() << " "
1122 << *NewTy << "]!\n");
1124 User->refineAbstractType(this, NewTy);
1126 assert(AbstractTypeUsers.size() != OldSize &&
1127 "AbsTyUser did not remove self from user list!");
1130 // If we were successful removing all users from the type, 'this' will be
1131 // deleted when the last PATypeHolder is destroyed or updated from this type.
1132 // This may occur on exit of this function, as the CurrentTy object is
1136 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1137 // the current type has transitioned from being abstract to being concrete.
1139 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1140 #ifdef DEBUG_MERGE_TYPES
1141 DEBUG(dbgs() << "typeIsREFINED type: " << (void*)this << " " << *this <<"\n");
1144 unsigned OldSize = AbstractTypeUsers.size(); (void)OldSize;
1145 while (!AbstractTypeUsers.empty()) {
1146 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1147 ATU->typeBecameConcrete(this);
1149 assert(AbstractTypeUsers.size() < OldSize-- &&
1150 "AbstractTypeUser did not remove itself from the use list!");
1154 // refineAbstractType - Called when a contained type is found to be more
1155 // concrete - this could potentially change us from an abstract type to a
1158 void FunctionType::refineAbstractType(const DerivedType *OldType,
1159 const Type *NewType) {
1160 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1161 pImpl->FunctionTypes.RefineAbstractType(this, OldType, NewType);
1164 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1165 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1166 pImpl->FunctionTypes.TypeBecameConcrete(this, AbsTy);
1170 // refineAbstractType - Called when a contained type is found to be more
1171 // concrete - this could potentially change us from an abstract type to a
1174 void ArrayType::refineAbstractType(const DerivedType *OldType,
1175 const Type *NewType) {
1176 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1177 pImpl->ArrayTypes.RefineAbstractType(this, OldType, NewType);
1180 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1181 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1182 pImpl->ArrayTypes.TypeBecameConcrete(this, AbsTy);
1185 // refineAbstractType - Called when a contained type is found to be more
1186 // concrete - this could potentially change us from an abstract type to a
1189 void VectorType::refineAbstractType(const DerivedType *OldType,
1190 const Type *NewType) {
1191 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1192 pImpl->VectorTypes.RefineAbstractType(this, OldType, NewType);
1195 void VectorType::typeBecameConcrete(const DerivedType *AbsTy) {
1196 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1197 pImpl->VectorTypes.TypeBecameConcrete(this, AbsTy);
1200 // refineAbstractType - Called when a contained type is found to be more
1201 // concrete - this could potentially change us from an abstract type to a
1204 void StructType::refineAbstractType(const DerivedType *OldType,
1205 const Type *NewType) {
1206 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1207 pImpl->StructTypes.RefineAbstractType(this, OldType, NewType);
1210 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1211 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1212 pImpl->StructTypes.TypeBecameConcrete(this, AbsTy);
1215 // refineAbstractType - Called when a contained type is found to be more
1216 // concrete - this could potentially change us from an abstract type to a
1219 void PointerType::refineAbstractType(const DerivedType *OldType,
1220 const Type *NewType) {
1221 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1222 pImpl->PointerTypes.RefineAbstractType(this, OldType, NewType);
1225 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1226 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1227 pImpl->PointerTypes.TypeBecameConcrete(this, AbsTy);
1230 bool SequentialType::indexValid(const Value *V) const {
1231 if (V->getType()->isIntegerTy())
1237 raw_ostream &operator<<(raw_ostream &OS, const Type &T) {