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/ADT/SCCIterator.h"
20 // DEBUG_MERGE_TYPES - Enable this #define to see how and when derived types are
21 // created and later destroyed, all in an effort to make sure that there is only
22 // a single canonical version of a type.
24 // #define DEBUG_MERGE_TYPES 1
26 AbstractTypeUser::~AbstractTypeUser() {}
28 void AbstractTypeUser::setType(Value *V, const Type *NewTy) {
32 //===----------------------------------------------------------------------===//
33 // Type Class Implementation
34 //===----------------------------------------------------------------------===//
36 /// Because of the way Type subclasses are allocated, this function is necessary
37 /// to use the correct kind of "delete" operator to deallocate the Type object.
38 /// Some type objects (FunctionTy, StructTy) allocate additional space
39 /// after the space for their derived type to hold the contained types array of
40 /// PATypeHandles. Using this allocation scheme means all the PATypeHandles are
41 /// allocated with the type object, decreasing allocations and eliminating the
42 /// need for a std::vector to be used in the Type class itself.
43 /// @brief Type destruction function
44 void Type::destroy() const {
45 // Nothing calls getForwardedType from here on.
46 if (ForwardType && ForwardType->isAbstract()) {
47 ForwardType->dropRef();
51 // Structures and Functions allocate their contained types past the end of
52 // the type object itself. These need to be destroyed differently than the
54 if (this->isFunctionTy() || this->isStructTy()) {
55 // First, make sure we destruct any PATypeHandles allocated by these
56 // subclasses. They must be manually destructed.
57 for (unsigned i = 0; i < NumContainedTys; ++i)
58 ContainedTys[i].PATypeHandle::~PATypeHandle();
60 // Now call the destructor for the subclass directly because we're going
61 // to delete this as an array of char.
62 if (this->isFunctionTy())
63 static_cast<const FunctionType*>(this)->FunctionType::~FunctionType();
66 static_cast<const StructType*>(this)->StructType::~StructType();
69 // Finally, remove the memory as an array deallocation of the chars it was
71 operator delete(const_cast<Type *>(this));
76 if (const OpaqueType *opaque_this = dyn_cast<OpaqueType>(this)) {
77 LLVMContextImpl *pImpl = this->getContext().pImpl;
78 pImpl->OpaqueTypes.erase(opaque_this);
81 // For all the other type subclasses, there is either no contained types or
82 // just one (all Sequentials). For Sequentials, the PATypeHandle is not
83 // allocated past the type object, its included directly in the SequentialType
84 // class. This means we can safely just do "normal" delete of this object and
85 // all the destructors that need to run will be run.
89 const Type *Type::getPrimitiveType(LLVMContext &C, TypeID IDNumber) {
91 case VoidTyID : return getVoidTy(C);
92 case FloatTyID : return getFloatTy(C);
93 case DoubleTyID : return getDoubleTy(C);
94 case X86_FP80TyID : return getX86_FP80Ty(C);
95 case FP128TyID : return getFP128Ty(C);
96 case PPC_FP128TyID : return getPPC_FP128Ty(C);
97 case LabelTyID : return getLabelTy(C);
98 case MetadataTyID : return getMetadataTy(C);
99 case X86_MMXTyID : return getX86_MMXTy(C);
105 /// getScalarType - If this is a vector type, return the element type,
106 /// otherwise return this.
107 const Type *Type::getScalarType() const {
108 if (const VectorType *VTy = dyn_cast<VectorType>(this))
109 return VTy->getElementType();
113 /// isIntegerTy - Return true if this is an IntegerType of the specified width.
114 bool Type::isIntegerTy(unsigned Bitwidth) const {
115 return isIntegerTy() && cast<IntegerType>(this)->getBitWidth() == Bitwidth;
118 /// isIntOrIntVectorTy - Return true if this is an integer type or a vector of
121 bool Type::isIntOrIntVectorTy() const {
124 if (ID != Type::VectorTyID) return false;
126 return cast<VectorType>(this)->getElementType()->isIntegerTy();
129 /// isFPOrFPVectorTy - Return true if this is a FP type or a vector of FP types.
131 bool Type::isFPOrFPVectorTy() const {
132 if (ID == Type::FloatTyID || ID == Type::DoubleTyID ||
133 ID == Type::FP128TyID || ID == Type::X86_FP80TyID ||
134 ID == Type::PPC_FP128TyID)
136 if (ID != Type::VectorTyID) return false;
138 return cast<VectorType>(this)->getElementType()->isFloatingPointTy();
141 // canLosslesslyBitCastTo - Return true if this type can be converted to
142 // 'Ty' without any reinterpretation of bits. For example, i8* to i32*.
144 bool Type::canLosslesslyBitCastTo(const Type *Ty) const {
145 // Identity cast means no change so return true
149 // They are not convertible unless they are at least first class types
150 if (!this->isFirstClassType() || !Ty->isFirstClassType())
153 // Vector -> Vector conversions are always lossless if the two vector types
154 // have the same size, otherwise not. Also, 64-bit vector types can be
155 // converted to x86mmx.
156 if (const VectorType *thisPTy = dyn_cast<VectorType>(this)) {
157 if (const VectorType *thatPTy = dyn_cast<VectorType>(Ty))
158 return thisPTy->getBitWidth() == thatPTy->getBitWidth();
159 if (Ty->getTypeID() == Type::X86_MMXTyID &&
160 thisPTy->getBitWidth() == 64)
164 if (this->getTypeID() == Type::X86_MMXTyID)
165 if (const VectorType *thatPTy = dyn_cast<VectorType>(Ty))
166 if (thatPTy->getBitWidth() == 64)
169 // At this point we have only various mismatches of the first class types
170 // remaining and ptr->ptr. Just select the lossless conversions. Everything
171 // else is not lossless.
172 if (this->isPointerTy())
173 return Ty->isPointerTy();
174 return false; // Other types have no identity values
177 bool Type::isEmptyTy() const {
178 const ArrayType *ATy = dyn_cast<ArrayType>(this);
180 unsigned NumElements = ATy->getNumElements();
181 return NumElements == 0 || ATy->getElementType()->isEmptyTy();
184 const StructType *STy = dyn_cast<StructType>(this);
186 unsigned NumElements = STy->getNumElements();
187 for (unsigned i = 0; i < NumElements; ++i)
188 if (!STy->getElementType(i)->isEmptyTy())
196 unsigned Type::getPrimitiveSizeInBits() const {
197 switch (getTypeID()) {
198 case Type::FloatTyID: return 32;
199 case Type::DoubleTyID: return 64;
200 case Type::X86_FP80TyID: return 80;
201 case Type::FP128TyID: return 128;
202 case Type::PPC_FP128TyID: return 128;
203 case Type::X86_MMXTyID: return 64;
204 case Type::IntegerTyID: return cast<IntegerType>(this)->getBitWidth();
205 case Type::VectorTyID: return cast<VectorType>(this)->getBitWidth();
210 /// getScalarSizeInBits - If this is a vector type, return the
211 /// getPrimitiveSizeInBits value for the element type. Otherwise return the
212 /// getPrimitiveSizeInBits value for this type.
213 unsigned Type::getScalarSizeInBits() const {
214 return getScalarType()->getPrimitiveSizeInBits();
217 /// getFPMantissaWidth - Return the width of the mantissa of this type. This
218 /// is only valid on floating point types. If the FP type does not
219 /// have a stable mantissa (e.g. ppc long double), this method returns -1.
220 int Type::getFPMantissaWidth() const {
221 if (const VectorType *VTy = dyn_cast<VectorType>(this))
222 return VTy->getElementType()->getFPMantissaWidth();
223 assert(isFloatingPointTy() && "Not a floating point type!");
224 if (ID == FloatTyID) return 24;
225 if (ID == DoubleTyID) return 53;
226 if (ID == X86_FP80TyID) return 64;
227 if (ID == FP128TyID) return 113;
228 assert(ID == PPC_FP128TyID && "unknown fp type");
232 /// isSizedDerivedType - Derived types like structures and arrays are sized
233 /// iff all of the members of the type are sized as well. Since asking for
234 /// their size is relatively uncommon, move this operation out of line.
235 bool Type::isSizedDerivedType() const {
236 if (this->isIntegerTy())
239 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
240 return ATy->getElementType()->isSized();
242 if (const VectorType *VTy = dyn_cast<VectorType>(this))
243 return VTy->getElementType()->isSized();
245 if (!this->isStructTy())
248 // Okay, our struct is sized if all of the elements are...
249 for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I)
250 if (!(*I)->isSized())
256 /// getForwardedTypeInternal - This method is used to implement the union-find
257 /// algorithm for when a type is being forwarded to another type.
258 const Type *Type::getForwardedTypeInternal() const {
259 assert(ForwardType && "This type is not being forwarded to another type!");
261 // Check to see if the forwarded type has been forwarded on. If so, collapse
262 // the forwarding links.
263 const Type *RealForwardedType = ForwardType->getForwardedType();
264 if (!RealForwardedType)
265 return ForwardType; // No it's not forwarded again
267 // Yes, it is forwarded again. First thing, add the reference to the new
269 if (RealForwardedType->isAbstract())
270 RealForwardedType->addRef();
272 // Now drop the old reference. This could cause ForwardType to get deleted.
273 // ForwardType must be abstract because only abstract types can have their own
275 ForwardType->dropRef();
277 // Return the updated type.
278 ForwardType = RealForwardedType;
282 void Type::refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
283 llvm_unreachable("Attempting to refine a derived type!");
285 void Type::typeBecameConcrete(const DerivedType *AbsTy) {
286 llvm_unreachable("DerivedType is already a concrete type!");
290 std::string Type::getDescription() const {
291 LLVMContextImpl *pImpl = getContext().pImpl;
294 pImpl->AbstractTypeDescriptions :
295 pImpl->ConcreteTypeDescriptions;
298 raw_string_ostream DescOS(DescStr);
299 Map.print(this, DescOS);
304 bool StructType::indexValid(const Value *V) const {
305 // Structure indexes require 32-bit integer constants.
306 if (V->getType()->isIntegerTy(32))
307 if (const ConstantInt *CU = dyn_cast<ConstantInt>(V))
308 return indexValid(CU->getZExtValue());
312 bool StructType::indexValid(unsigned V) const {
313 return V < NumContainedTys;
316 // getTypeAtIndex - Given an index value into the type, return the type of the
317 // element. For a structure type, this must be a constant value...
319 const Type *StructType::getTypeAtIndex(const Value *V) const {
320 unsigned Idx = (unsigned)cast<ConstantInt>(V)->getZExtValue();
321 return getTypeAtIndex(Idx);
324 const Type *StructType::getTypeAtIndex(unsigned Idx) const {
325 assert(indexValid(Idx) && "Invalid structure index!");
326 return ContainedTys[Idx];
330 //===----------------------------------------------------------------------===//
331 // Primitive 'Type' data
332 //===----------------------------------------------------------------------===//
334 const Type *Type::getVoidTy(LLVMContext &C) {
335 return &C.pImpl->VoidTy;
338 const Type *Type::getLabelTy(LLVMContext &C) {
339 return &C.pImpl->LabelTy;
342 const Type *Type::getFloatTy(LLVMContext &C) {
343 return &C.pImpl->FloatTy;
346 const Type *Type::getDoubleTy(LLVMContext &C) {
347 return &C.pImpl->DoubleTy;
350 const Type *Type::getMetadataTy(LLVMContext &C) {
351 return &C.pImpl->MetadataTy;
354 const Type *Type::getX86_FP80Ty(LLVMContext &C) {
355 return &C.pImpl->X86_FP80Ty;
358 const Type *Type::getFP128Ty(LLVMContext &C) {
359 return &C.pImpl->FP128Ty;
362 const Type *Type::getPPC_FP128Ty(LLVMContext &C) {
363 return &C.pImpl->PPC_FP128Ty;
366 const Type *Type::getX86_MMXTy(LLVMContext &C) {
367 return &C.pImpl->X86_MMXTy;
370 const IntegerType *Type::getIntNTy(LLVMContext &C, unsigned N) {
371 return IntegerType::get(C, N);
374 const IntegerType *Type::getInt1Ty(LLVMContext &C) {
375 return &C.pImpl->Int1Ty;
378 const IntegerType *Type::getInt8Ty(LLVMContext &C) {
379 return &C.pImpl->Int8Ty;
382 const IntegerType *Type::getInt16Ty(LLVMContext &C) {
383 return &C.pImpl->Int16Ty;
386 const IntegerType *Type::getInt32Ty(LLVMContext &C) {
387 return &C.pImpl->Int32Ty;
390 const IntegerType *Type::getInt64Ty(LLVMContext &C) {
391 return &C.pImpl->Int64Ty;
394 const PointerType *Type::getFloatPtrTy(LLVMContext &C, unsigned AS) {
395 return getFloatTy(C)->getPointerTo(AS);
398 const PointerType *Type::getDoublePtrTy(LLVMContext &C, unsigned AS) {
399 return getDoubleTy(C)->getPointerTo(AS);
402 const PointerType *Type::getX86_FP80PtrTy(LLVMContext &C, unsigned AS) {
403 return getX86_FP80Ty(C)->getPointerTo(AS);
406 const PointerType *Type::getFP128PtrTy(LLVMContext &C, unsigned AS) {
407 return getFP128Ty(C)->getPointerTo(AS);
410 const PointerType *Type::getPPC_FP128PtrTy(LLVMContext &C, unsigned AS) {
411 return getPPC_FP128Ty(C)->getPointerTo(AS);
414 const PointerType *Type::getX86_MMXPtrTy(LLVMContext &C, unsigned AS) {
415 return getX86_MMXTy(C)->getPointerTo(AS);
418 const PointerType *Type::getIntNPtrTy(LLVMContext &C, unsigned N, unsigned AS) {
419 return getIntNTy(C, N)->getPointerTo(AS);
422 const PointerType *Type::getInt1PtrTy(LLVMContext &C, unsigned AS) {
423 return getInt1Ty(C)->getPointerTo(AS);
426 const PointerType *Type::getInt8PtrTy(LLVMContext &C, unsigned AS) {
427 return getInt8Ty(C)->getPointerTo(AS);
430 const PointerType *Type::getInt16PtrTy(LLVMContext &C, unsigned AS) {
431 return getInt16Ty(C)->getPointerTo(AS);
434 const PointerType *Type::getInt32PtrTy(LLVMContext &C, unsigned AS) {
435 return getInt32Ty(C)->getPointerTo(AS);
438 const PointerType *Type::getInt64PtrTy(LLVMContext &C, unsigned AS) {
439 return getInt64Ty(C)->getPointerTo(AS);
442 //===----------------------------------------------------------------------===//
443 // Derived Type Constructors
444 //===----------------------------------------------------------------------===//
446 /// isValidReturnType - Return true if the specified type is valid as a return
448 bool FunctionType::isValidReturnType(const Type *RetTy) {
449 return !RetTy->isFunctionTy() && !RetTy->isLabelTy() &&
450 !RetTy->isMetadataTy();
453 /// isValidArgumentType - Return true if the specified type is valid as an
455 bool FunctionType::isValidArgumentType(const Type *ArgTy) {
456 return ArgTy->isFirstClassType() || ArgTy->isOpaqueTy();
459 FunctionType::FunctionType(const Type *Result,
460 ArrayRef<const Type*> Params,
462 : DerivedType(Result->getContext(), FunctionTyID) {
463 ContainedTys = reinterpret_cast<PATypeHandle*>(this+1);
464 NumContainedTys = Params.size() + 1; // + 1 for result type
465 assert(isValidReturnType(Result) && "invalid return type for function");
466 setSubclassData(IsVarArgs);
468 bool isAbstract = Result->isAbstract();
469 new (&ContainedTys[0]) PATypeHandle(Result, this);
471 for (unsigned i = 0; i != Params.size(); ++i) {
472 assert(isValidArgumentType(Params[i]) &&
473 "Not a valid type for function argument!");
474 new (&ContainedTys[i+1]) PATypeHandle(Params[i], this);
475 isAbstract |= Params[i]->isAbstract();
478 // Calculate whether or not this type is abstract
479 setAbstract(isAbstract);
482 StructType::StructType(LLVMContext &C,
483 ArrayRef<const Type*> Types, bool isPacked)
484 : CompositeType(C, StructTyID) {
485 ContainedTys = reinterpret_cast<PATypeHandle*>(this + 1);
486 NumContainedTys = Types.size();
487 setSubclassData(isPacked);
488 bool isAbstract = false;
489 for (unsigned i = 0; i < Types.size(); ++i) {
490 assert(Types[i] && "<null> type for structure field!");
491 assert(isValidElementType(Types[i]) &&
492 "Invalid type for structure element!");
493 new (&ContainedTys[i]) PATypeHandle(Types[i], this);
494 isAbstract |= Types[i]->isAbstract();
497 // Calculate whether or not this type is abstract
498 setAbstract(isAbstract);
501 ArrayType::ArrayType(const Type *ElType, uint64_t NumEl)
502 : SequentialType(ArrayTyID, ElType) {
505 // Calculate whether or not this type is abstract
506 setAbstract(ElType->isAbstract());
509 VectorType::VectorType(const Type *ElType, unsigned NumEl)
510 : SequentialType(VectorTyID, ElType) {
512 setAbstract(ElType->isAbstract());
513 assert(NumEl > 0 && "NumEl of a VectorType must be greater than 0");
514 assert(isValidElementType(ElType) &&
515 "Elements of a VectorType must be a primitive type");
520 PointerType::PointerType(const Type *E, unsigned AddrSpace)
521 : SequentialType(PointerTyID, E) {
522 setSubclassData(AddrSpace);
523 // Calculate whether or not this type is abstract
524 setAbstract(E->isAbstract());
527 OpaqueType::OpaqueType(LLVMContext &C) : DerivedType(C, OpaqueTyID) {
529 #ifdef DEBUG_MERGE_TYPES
530 DEBUG(dbgs() << "Derived new type: " << *this << "\n");
534 void PATypeHolder::destroy() {
538 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
539 // another (more concrete) type, we must eliminate all references to other
540 // types, to avoid some circular reference problems.
541 void DerivedType::dropAllTypeUses() {
542 if (NumContainedTys != 0) {
543 // The type must stay abstract. To do this, we insert a pointer to a type
544 // that will never get resolved, thus will always be abstract.
545 ContainedTys[0] = getContext().pImpl->AlwaysOpaqueTy;
547 // Change the rest of the types to be Int32Ty's. It doesn't matter what we
548 // pick so long as it doesn't point back to this type. We choose something
549 // concrete to avoid overhead for adding to AbstractTypeUser lists and
551 const Type *ConcreteTy = Type::getInt32Ty(getContext());
552 for (unsigned i = 1, e = NumContainedTys; i != e; ++i)
553 ContainedTys[i] = ConcreteTy;
560 /// TypePromotionGraph and graph traits - this is designed to allow us to do
561 /// efficient SCC processing of type graphs. This is the exact same as
562 /// GraphTraits<Type*>, except that we pretend that concrete types have no
563 /// children to avoid processing them.
564 struct TypePromotionGraph {
566 TypePromotionGraph(Type *T) : Ty(T) {}
572 template <> struct GraphTraits<TypePromotionGraph> {
573 typedef Type NodeType;
574 typedef Type::subtype_iterator ChildIteratorType;
576 static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
577 static inline ChildIteratorType child_begin(NodeType *N) {
579 return N->subtype_begin();
580 // No need to process children of concrete types.
581 return N->subtype_end();
583 static inline ChildIteratorType child_end(NodeType *N) {
584 return N->subtype_end();
590 // PromoteAbstractToConcrete - This is a recursive function that walks a type
591 // graph calculating whether or not a type is abstract.
593 void Type::PromoteAbstractToConcrete() {
594 if (!isAbstract()) return;
596 scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
597 scc_iterator<TypePromotionGraph> SE = scc_end (TypePromotionGraph(this));
599 for (; SI != SE; ++SI) {
600 std::vector<Type*> &SCC = *SI;
602 // Concrete types are leaves in the tree. Since an SCC will either be all
603 // abstract or all concrete, we only need to check one type.
604 if (!SCC[0]->isAbstract()) continue;
606 if (SCC[0]->isOpaqueTy())
607 return; // Not going to be concrete, sorry.
609 // If all of the children of all of the types in this SCC are concrete,
610 // then this SCC is now concrete as well. If not, neither this SCC, nor
611 // any parent SCCs will be concrete, so we might as well just exit.
612 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
613 for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
614 E = SCC[i]->subtype_end(); CI != E; ++CI)
615 if ((*CI)->isAbstract())
616 // If the child type is in our SCC, it doesn't make the entire SCC
617 // abstract unless there is a non-SCC abstract type.
618 if (std::find(SCC.begin(), SCC.end(), *CI) == SCC.end())
619 return; // Not going to be concrete, sorry.
621 // Okay, we just discovered this whole SCC is now concrete, mark it as
623 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
624 assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
626 SCC[i]->setAbstract(false);
629 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
630 assert(!SCC[i]->isAbstract() && "Concrete type became abstract?");
631 // The type just became concrete, notify all users!
632 cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
638 //===----------------------------------------------------------------------===//
639 // Type Structural Equality Testing
640 //===----------------------------------------------------------------------===//
642 // TypesEqual - Two types are considered structurally equal if they have the
643 // same "shape": Every level and element of the types have identical primitive
644 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
645 // be pointer equals to be equivalent though. This uses an optimistic algorithm
646 // that assumes that two graphs are the same until proven otherwise.
648 static bool TypesEqual(const Type *Ty, const Type *Ty2,
649 std::map<const Type *, const Type *> &EqTypes) {
650 if (Ty == Ty2) return true;
651 if (Ty->getTypeID() != Ty2->getTypeID()) return false;
652 if (Ty->isOpaqueTy())
653 return false; // Two unequal opaque types are never equal
655 std::map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
656 if (It != EqTypes.end())
657 return It->second == Ty2; // Looping back on a type, check for equality
659 // Otherwise, add the mapping to the table to make sure we don't get
660 // recursion on the types...
661 EqTypes.insert(It, std::make_pair(Ty, Ty2));
663 // Two really annoying special cases that breaks an otherwise nice simple
664 // algorithm is the fact that arraytypes have sizes that differentiates types,
665 // and that function types can be varargs or not. Consider this now.
667 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
668 const IntegerType *ITy2 = cast<IntegerType>(Ty2);
669 return ITy->getBitWidth() == ITy2->getBitWidth();
672 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
673 const PointerType *PTy2 = cast<PointerType>(Ty2);
674 return PTy->getAddressSpace() == PTy2->getAddressSpace() &&
675 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
678 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
679 const StructType *STy2 = cast<StructType>(Ty2);
680 if (STy->getNumElements() != STy2->getNumElements()) return false;
681 if (STy->isPacked() != STy2->isPacked()) return false;
682 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
683 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
688 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
689 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
690 return ATy->getNumElements() == ATy2->getNumElements() &&
691 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
694 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
695 const VectorType *PTy2 = cast<VectorType>(Ty2);
696 return PTy->getNumElements() == PTy2->getNumElements() &&
697 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
700 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
701 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
702 if (FTy->isVarArg() != FTy2->isVarArg() ||
703 FTy->getNumParams() != FTy2->getNumParams() ||
704 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
706 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i) {
707 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
713 llvm_unreachable("Unknown derived type!");
717 namespace llvm { // in namespace llvm so findable by ADL
718 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
719 std::map<const Type *, const Type *> EqTypes;
720 return ::TypesEqual(Ty, Ty2, EqTypes);
724 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
725 // TargetTy in the type graph. We know that Ty is an abstract type, so if we
726 // ever reach a non-abstract type, we know that we don't need to search the
728 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
729 SmallPtrSet<const Type*, 128> &VisitedTypes) {
730 if (TargetTy == CurTy) return true;
731 if (!CurTy->isAbstract()) return false;
733 if (!VisitedTypes.insert(CurTy))
734 return false; // Already been here.
736 for (Type::subtype_iterator I = CurTy->subtype_begin(),
737 E = CurTy->subtype_end(); I != E; ++I)
738 if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
743 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
744 SmallPtrSet<const Type*, 128> &VisitedTypes) {
745 if (TargetTy == CurTy) return true;
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 (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
757 /// TypeHasCycleThroughItself - Return true if the specified type has
758 /// a cycle back to itself.
760 namespace llvm { // in namespace llvm so it's findable by ADL
761 static bool TypeHasCycleThroughItself(const Type *Ty) {
762 SmallPtrSet<const Type*, 128> VisitedTypes;
764 if (Ty->isAbstract()) { // Optimized case for abstract types.
765 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
767 if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
770 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
772 if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
779 //===----------------------------------------------------------------------===//
780 // Function Type Factory and Value Class...
782 const IntegerType *IntegerType::get(LLVMContext &C, unsigned NumBits) {
783 assert(NumBits >= MIN_INT_BITS && "bitwidth too small");
784 assert(NumBits <= MAX_INT_BITS && "bitwidth too large");
786 // Check for the built-in integer types
788 case 1: return cast<IntegerType>(Type::getInt1Ty(C));
789 case 8: return cast<IntegerType>(Type::getInt8Ty(C));
790 case 16: return cast<IntegerType>(Type::getInt16Ty(C));
791 case 32: return cast<IntegerType>(Type::getInt32Ty(C));
792 case 64: return cast<IntegerType>(Type::getInt64Ty(C));
797 LLVMContextImpl *pImpl = C.pImpl;
799 IntegerValType IVT(NumBits);
800 IntegerType *ITy = 0;
802 // First, see if the type is already in the table, for which
803 // a reader lock suffices.
804 ITy = pImpl->IntegerTypes.get(IVT);
807 // Value not found. Derive a new type!
808 ITy = new IntegerType(C, NumBits);
809 pImpl->IntegerTypes.add(IVT, ITy);
811 #ifdef DEBUG_MERGE_TYPES
812 DEBUG(dbgs() << "Derived new type: " << *ITy << "\n");
817 bool IntegerType::isPowerOf2ByteWidth() const {
818 unsigned BitWidth = getBitWidth();
819 return (BitWidth > 7) && isPowerOf2_32(BitWidth);
822 APInt IntegerType::getMask() const {
823 return APInt::getAllOnesValue(getBitWidth());
826 FunctionValType FunctionValType::get(const FunctionType *FT) {
827 // Build up a FunctionValType
828 std::vector<const Type *> ParamTypes;
829 ParamTypes.reserve(FT->getNumParams());
830 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
831 ParamTypes.push_back(FT->getParamType(i));
832 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
836 // FunctionType::get - The factory function for the FunctionType class...
837 FunctionType *FunctionType::get(const Type *ReturnType,
838 ArrayRef<const Type*> Params,
840 FunctionValType VT(ReturnType, Params, isVarArg);
841 FunctionType *FT = 0;
843 LLVMContextImpl *pImpl = ReturnType->getContext().pImpl;
845 FT = pImpl->FunctionTypes.get(VT);
848 FT = (FunctionType*) operator new(sizeof(FunctionType) +
849 sizeof(PATypeHandle)*(Params.size()+1));
850 new (FT) FunctionType(ReturnType, Params, isVarArg);
851 pImpl->FunctionTypes.add(VT, FT);
854 #ifdef DEBUG_MERGE_TYPES
855 DEBUG(dbgs() << "Derived new type: " << FT << "\n");
860 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
861 assert(ElementType && "Can't get array of <null> types!");
862 assert(isValidElementType(ElementType) && "Invalid type for array element!");
864 ArrayValType AVT(ElementType, NumElements);
867 LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
869 AT = pImpl->ArrayTypes.get(AVT);
872 // Value not found. Derive a new type!
873 pImpl->ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
875 #ifdef DEBUG_MERGE_TYPES
876 DEBUG(dbgs() << "Derived new type: " << *AT << "\n");
881 bool ArrayType::isValidElementType(const Type *ElemTy) {
882 return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
883 !ElemTy->isMetadataTy() && !ElemTy->isFunctionTy();
886 VectorType *VectorType::get(const Type *ElementType, unsigned NumElements) {
887 assert(ElementType && "Can't get vector of <null> types!");
889 VectorValType PVT(ElementType, NumElements);
892 LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
894 PT = pImpl->VectorTypes.get(PVT);
897 pImpl->VectorTypes.add(PVT, PT = new VectorType(ElementType, NumElements));
899 #ifdef DEBUG_MERGE_TYPES
900 DEBUG(dbgs() << "Derived new type: " << *PT << "\n");
905 bool VectorType::isValidElementType(const Type *ElemTy) {
906 return ElemTy->isIntegerTy() || ElemTy->isFloatingPointTy() ||
907 ElemTy->isOpaqueTy();
910 //===----------------------------------------------------------------------===//
911 // Struct Type Factory...
914 StructType *StructType::get(LLVMContext &Context,
915 ArrayRef<const Type*> ETypes,
917 StructValType STV(ETypes, isPacked);
920 LLVMContextImpl *pImpl = Context.pImpl;
922 ST = pImpl->StructTypes.get(STV);
925 // Value not found. Derive a new type!
926 ST = (StructType*) operator new(sizeof(StructType) +
927 sizeof(PATypeHandle) * ETypes.size());
928 new (ST) StructType(Context, ETypes, isPacked);
929 pImpl->StructTypes.add(STV, ST);
931 #ifdef DEBUG_MERGE_TYPES
932 DEBUG(dbgs() << "Derived new type: " << *ST << "\n");
937 StructType *StructType::get(LLVMContext &Context, const Type *type, ...) {
939 std::vector<const llvm::Type*> StructFields;
942 StructFields.push_back(type);
943 type = va_arg(ap, llvm::Type*);
945 return llvm::StructType::get(Context, StructFields);
948 bool StructType::isValidElementType(const Type *ElemTy) {
949 return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
950 !ElemTy->isMetadataTy() && !ElemTy->isFunctionTy();
954 //===----------------------------------------------------------------------===//
955 // Pointer Type Factory...
958 PointerType *PointerType::get(const Type *ValueType, unsigned AddressSpace) {
959 assert(ValueType && "Can't get a pointer to <null> type!");
960 assert(ValueType->getTypeID() != VoidTyID &&
961 "Pointer to void is not valid, use i8* instead!");
962 assert(isValidElementType(ValueType) && "Invalid type for pointer element!");
963 PointerValType PVT(ValueType, AddressSpace);
967 LLVMContextImpl *pImpl = ValueType->getContext().pImpl;
969 PT = pImpl->PointerTypes.get(PVT);
972 // Value not found. Derive a new type!
973 pImpl->PointerTypes.add(PVT, PT = new PointerType(ValueType, AddressSpace));
975 #ifdef DEBUG_MERGE_TYPES
976 DEBUG(dbgs() << "Derived new type: " << *PT << "\n");
981 const PointerType *Type::getPointerTo(unsigned addrs) const {
982 return PointerType::get(this, addrs);
985 bool PointerType::isValidElementType(const Type *ElemTy) {
986 return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
987 !ElemTy->isMetadataTy();
991 //===----------------------------------------------------------------------===//
992 // Opaque Type Factory...
995 OpaqueType *OpaqueType::get(LLVMContext &C) {
996 OpaqueType *OT = new OpaqueType(C); // All opaque types are distinct.
997 LLVMContextImpl *pImpl = C.pImpl;
998 pImpl->OpaqueTypes.insert(OT);
1004 //===----------------------------------------------------------------------===//
1005 // Derived Type Refinement Functions
1006 //===----------------------------------------------------------------------===//
1008 // addAbstractTypeUser - Notify an abstract type that there is a new user of
1009 // it. This function is called primarily by the PATypeHandle class.
1010 void Type::addAbstractTypeUser(AbstractTypeUser *U) const {
1011 assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
1012 AbstractTypeUsers.push_back(U);
1016 // removeAbstractTypeUser - Notify an abstract type that a user of the class
1017 // no longer has a handle to the type. This function is called primarily by
1018 // the PATypeHandle class. When there are no users of the abstract type, it
1019 // is annihilated, because there is no way to get a reference to it ever again.
1021 void Type::removeAbstractTypeUser(AbstractTypeUser *U) const {
1023 // Search from back to front because we will notify users from back to
1024 // front. Also, it is likely that there will be a stack like behavior to
1025 // users that register and unregister users.
1028 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1029 assert(i != 0 && "AbstractTypeUser not in user list!");
1031 --i; // Convert to be in range 0 <= i < size()
1032 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
1034 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1036 #ifdef DEBUG_MERGE_TYPES
1037 DEBUG(dbgs() << " remAbstractTypeUser[" << (void*)this << ", "
1038 << *this << "][" << i << "] User = " << U << "\n");
1041 if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1042 #ifdef DEBUG_MERGE_TYPES
1043 DEBUG(dbgs() << "DELETEing unused abstract type: <" << *this
1044 << ">[" << (void*)this << "]" << "\n");
1051 // refineAbstractTypeTo - This function is used when it is discovered
1052 // that the 'this' abstract type is actually equivalent to the NewType
1053 // specified. This causes all users of 'this' to switch to reference the more
1054 // concrete type NewType and for 'this' to be deleted. Only used for internal
1057 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1058 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1059 assert(this != NewType && "Can't refine to myself!");
1060 assert(ForwardType == 0 && "This type has already been refined!");
1062 LLVMContextImpl *pImpl = getContext().pImpl;
1064 // The descriptions may be out of date. Conservatively clear them all!
1065 pImpl->AbstractTypeDescriptions.clear();
1067 #ifdef DEBUG_MERGE_TYPES
1068 DEBUG(dbgs() << "REFINING abstract type [" << (void*)this << " "
1069 << *this << "] to [" << (void*)NewType << " "
1070 << *NewType << "]!\n");
1073 // Make sure to put the type to be refined to into a holder so that if IT gets
1074 // refined, that we will not continue using a dead reference...
1076 PATypeHolder NewTy(NewType);
1077 // Any PATypeHolders referring to this type will now automatically forward to
1078 // the type we are resolved to.
1079 ForwardType = NewType;
1080 if (ForwardType->isAbstract())
1081 ForwardType->addRef();
1083 // Add a self use of the current type so that we don't delete ourself until
1084 // after the function exits.
1086 PATypeHolder CurrentTy(this);
1088 // To make the situation simpler, we ask the subclass to remove this type from
1089 // the type map, and to replace any type uses with uses of non-abstract types.
1090 // This dramatically limits the amount of recursive type trouble we can find
1094 // Iterate over all of the uses of this type, invoking callback. Each user
1095 // should remove itself from our use list automatically. We have to check to
1096 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1097 // will not cause users to drop off of the use list. If we resolve to ourself
1100 while (!AbstractTypeUsers.empty() && NewTy != this) {
1101 AbstractTypeUser *User = AbstractTypeUsers.back();
1103 unsigned OldSize = AbstractTypeUsers.size(); (void)OldSize;
1104 #ifdef DEBUG_MERGE_TYPES
1105 DEBUG(dbgs() << " REFINING user " << OldSize-1 << "[" << (void*)User
1106 << "] of abstract type [" << (void*)this << " "
1107 << *this << "] to [" << (void*)NewTy.get() << " "
1108 << *NewTy << "]!\n");
1110 User->refineAbstractType(this, NewTy);
1112 assert(AbstractTypeUsers.size() != OldSize &&
1113 "AbsTyUser did not remove self from user list!");
1116 // If we were successful removing all users from the type, 'this' will be
1117 // deleted when the last PATypeHolder is destroyed or updated from this type.
1118 // This may occur on exit of this function, as the CurrentTy object is
1122 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1123 // the current type has transitioned from being abstract to being concrete.
1125 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1126 #ifdef DEBUG_MERGE_TYPES
1127 DEBUG(dbgs() << "typeIsREFINED type: " << (void*)this << " " << *this <<"\n");
1130 unsigned OldSize = AbstractTypeUsers.size(); (void)OldSize;
1131 while (!AbstractTypeUsers.empty()) {
1132 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1133 ATU->typeBecameConcrete(this);
1135 assert(AbstractTypeUsers.size() < OldSize-- &&
1136 "AbstractTypeUser did not remove itself from the use list!");
1140 // refineAbstractType - Called when a contained type is found to be more
1141 // concrete - this could potentially change us from an abstract type to a
1144 void FunctionType::refineAbstractType(const DerivedType *OldType,
1145 const Type *NewType) {
1146 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1147 pImpl->FunctionTypes.RefineAbstractType(this, OldType, NewType);
1150 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1151 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1152 pImpl->FunctionTypes.TypeBecameConcrete(this, AbsTy);
1156 // refineAbstractType - Called when a contained type is found to be more
1157 // concrete - this could potentially change us from an abstract type to a
1160 void ArrayType::refineAbstractType(const DerivedType *OldType,
1161 const Type *NewType) {
1162 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1163 pImpl->ArrayTypes.RefineAbstractType(this, OldType, NewType);
1166 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1167 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1168 pImpl->ArrayTypes.TypeBecameConcrete(this, AbsTy);
1171 // refineAbstractType - Called when a contained type is found to be more
1172 // concrete - this could potentially change us from an abstract type to a
1175 void VectorType::refineAbstractType(const DerivedType *OldType,
1176 const Type *NewType) {
1177 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1178 pImpl->VectorTypes.RefineAbstractType(this, OldType, NewType);
1181 void VectorType::typeBecameConcrete(const DerivedType *AbsTy) {
1182 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1183 pImpl->VectorTypes.TypeBecameConcrete(this, AbsTy);
1186 // refineAbstractType - Called when a contained type is found to be more
1187 // concrete - this could potentially change us from an abstract type to a
1190 void StructType::refineAbstractType(const DerivedType *OldType,
1191 const Type *NewType) {
1192 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1193 pImpl->StructTypes.RefineAbstractType(this, OldType, NewType);
1196 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1197 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1198 pImpl->StructTypes.TypeBecameConcrete(this, AbsTy);
1201 // refineAbstractType - Called when a contained type is found to be more
1202 // concrete - this could potentially change us from an abstract type to a
1205 void PointerType::refineAbstractType(const DerivedType *OldType,
1206 const Type *NewType) {
1207 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1208 pImpl->PointerTypes.RefineAbstractType(this, OldType, NewType);
1211 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1212 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1213 pImpl->PointerTypes.TypeBecameConcrete(this, AbsTy);
1216 bool SequentialType::indexValid(const Value *V) const {
1217 if (V->getType()->isIntegerTy())
1223 raw_ostream &operator<<(raw_ostream &OS, const Type &T) {