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) 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 {
60 // Nothing calls getForwardedType from here on.
61 if (ForwardType && ForwardType->isAbstract()) {
62 ForwardType->dropRef();
66 // Structures and Functions allocate their contained types past the end of
67 // the type object itself. These need to be destroyed differently than the
69 if (this->isFunctionTy() || this->isStructTy()) {
70 // First, make sure we destruct any PATypeHandles allocated by these
71 // subclasses. They must be manually destructed.
72 for (unsigned i = 0; i < NumContainedTys; ++i)
73 ContainedTys[i].PATypeHandle::~PATypeHandle();
75 // Now call the destructor for the subclass directly because we're going
76 // to delete this as an array of char.
77 if (this->isFunctionTy())
78 static_cast<const FunctionType*>(this)->FunctionType::~FunctionType();
81 static_cast<const StructType*>(this)->StructType::~StructType();
84 // Finally, remove the memory as an array deallocation of the chars it was
86 operator delete(const_cast<Type *>(this));
89 } else if (const OpaqueType *opaque_this = dyn_cast<OpaqueType>(this)) {
90 LLVMContextImpl *pImpl = this->getContext().pImpl;
91 pImpl->OpaqueTypes.erase(opaque_this);
94 // For all the other type subclasses, there is either no contained types or
95 // just one (all Sequentials). For Sequentials, the PATypeHandle is not
96 // allocated past the type object, its included directly in the SequentialType
97 // class. This means we can safely just do "normal" delete of this object and
98 // all the destructors that need to run will be run.
102 const Type *Type::getPrimitiveType(LLVMContext &C, TypeID IDNumber) {
104 case VoidTyID : return getVoidTy(C);
105 case FloatTyID : return getFloatTy(C);
106 case DoubleTyID : return getDoubleTy(C);
107 case X86_FP80TyID : return getX86_FP80Ty(C);
108 case FP128TyID : return getFP128Ty(C);
109 case PPC_FP128TyID : return getPPC_FP128Ty(C);
110 case LabelTyID : return getLabelTy(C);
111 case MetadataTyID : return getMetadataTy(C);
117 const Type *Type::getVAArgsPromotedType(LLVMContext &C) const {
118 if (ID == IntegerTyID && getSubclassData() < 32)
119 return Type::getInt32Ty(C);
120 else if (ID == FloatTyID)
121 return Type::getDoubleTy(C);
126 /// getScalarType - If this is a vector type, return the element type,
127 /// otherwise return this.
128 const Type *Type::getScalarType() const {
129 if (const VectorType *VTy = dyn_cast<VectorType>(this))
130 return VTy->getElementType();
134 /// isIntegerTy - Return true if this is an IntegerType of the specified width.
135 bool Type::isIntegerTy(unsigned Bitwidth) const {
136 return isIntegerTy() && cast<IntegerType>(this)->getBitWidth() == Bitwidth;
139 /// isIntOrIntVectorTy - Return true if this is an integer type or a vector of
142 bool Type::isIntOrIntVectorTy() const {
145 if (ID != Type::VectorTyID) return false;
147 return cast<VectorType>(this)->getElementType()->isIntegerTy();
150 /// isFPOrFPVectorTy - Return true if this is a FP type or a vector of FP types.
152 bool Type::isFPOrFPVectorTy() const {
153 if (ID == Type::FloatTyID || ID == Type::DoubleTyID ||
154 ID == Type::FP128TyID || ID == Type::X86_FP80TyID ||
155 ID == Type::PPC_FP128TyID)
157 if (ID != Type::VectorTyID) return false;
159 return cast<VectorType>(this)->getElementType()->isFloatingPointTy();
162 // canLosslesslyBitCastTo - Return true if this type can be converted to
163 // 'Ty' without any reinterpretation of bits. For example, i8* to i32*.
165 bool Type::canLosslesslyBitCastTo(const Type *Ty) const {
166 // Identity cast means no change so return true
170 // They are not convertible unless they are at least first class types
171 if (!this->isFirstClassType() || !Ty->isFirstClassType())
174 // Vector -> Vector conversions are always lossless if the two vector types
175 // have the same size, otherwise not.
176 if (const VectorType *thisPTy = dyn_cast<VectorType>(this))
177 if (const VectorType *thatPTy = dyn_cast<VectorType>(Ty))
178 return thisPTy->getBitWidth() == thatPTy->getBitWidth();
180 // At this point we have only various mismatches of the first class types
181 // remaining and ptr->ptr. Just select the lossless conversions. Everything
182 // else is not lossless.
183 if (this->isPointerTy())
184 return Ty->isPointerTy();
185 return false; // Other types have no identity values
188 unsigned Type::getPrimitiveSizeInBits() const {
189 switch (getTypeID()) {
190 case Type::FloatTyID: return 32;
191 case Type::DoubleTyID: return 64;
192 case Type::X86_FP80TyID: return 80;
193 case Type::FP128TyID: return 128;
194 case Type::PPC_FP128TyID: return 128;
195 case Type::IntegerTyID: return cast<IntegerType>(this)->getBitWidth();
196 case Type::VectorTyID: return cast<VectorType>(this)->getBitWidth();
201 /// getScalarSizeInBits - If this is a vector type, return the
202 /// getPrimitiveSizeInBits value for the element type. Otherwise return the
203 /// getPrimitiveSizeInBits value for this type.
204 unsigned Type::getScalarSizeInBits() const {
205 return getScalarType()->getPrimitiveSizeInBits();
208 /// getFPMantissaWidth - Return the width of the mantissa of this type. This
209 /// is only valid on floating point types. If the FP type does not
210 /// have a stable mantissa (e.g. ppc long double), this method returns -1.
211 int Type::getFPMantissaWidth() const {
212 if (const VectorType *VTy = dyn_cast<VectorType>(this))
213 return VTy->getElementType()->getFPMantissaWidth();
214 assert(isFloatingPointTy() && "Not a floating point type!");
215 if (ID == FloatTyID) return 24;
216 if (ID == DoubleTyID) return 53;
217 if (ID == X86_FP80TyID) return 64;
218 if (ID == FP128TyID) return 113;
219 assert(ID == PPC_FP128TyID && "unknown fp type");
223 /// isSizedDerivedType - Derived types like structures and arrays are sized
224 /// iff all of the members of the type are sized as well. Since asking for
225 /// their size is relatively uncommon, move this operation out of line.
226 bool Type::isSizedDerivedType() const {
227 if (this->isIntegerTy())
230 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
231 return ATy->getElementType()->isSized();
233 if (const VectorType *PTy = dyn_cast<VectorType>(this))
234 return PTy->getElementType()->isSized();
236 if (!this->isStructTy())
239 // Okay, our struct is sized if all of the elements are...
240 for (subtype_iterator I = subtype_begin(), E = subtype_end(); I != E; ++I)
241 if (!(*I)->isSized())
247 /// getForwardedTypeInternal - This method is used to implement the union-find
248 /// algorithm for when a type is being forwarded to another type.
249 const Type *Type::getForwardedTypeInternal() const {
250 assert(ForwardType && "This type is not being forwarded to another type!");
252 // Check to see if the forwarded type has been forwarded on. If so, collapse
253 // the forwarding links.
254 const Type *RealForwardedType = ForwardType->getForwardedType();
255 if (!RealForwardedType)
256 return ForwardType; // No it's not forwarded again
258 // Yes, it is forwarded again. First thing, add the reference to the new
260 if (RealForwardedType->isAbstract())
261 RealForwardedType->addRef();
263 // Now drop the old reference. This could cause ForwardType to get deleted.
264 // ForwardType must be abstract because only abstract types can have their own
266 ForwardType->dropRef();
268 // Return the updated type.
269 ForwardType = RealForwardedType;
273 void Type::refineAbstractType(const DerivedType *OldTy, const Type *NewTy) {
274 llvm_unreachable("Attempting to refine a derived type!");
276 void Type::typeBecameConcrete(const DerivedType *AbsTy) {
277 llvm_unreachable("DerivedType is already a concrete type!");
281 std::string Type::getDescription() const {
282 LLVMContextImpl *pImpl = getContext().pImpl;
285 pImpl->AbstractTypeDescriptions :
286 pImpl->ConcreteTypeDescriptions;
289 raw_string_ostream DescOS(DescStr);
290 Map.print(this, DescOS);
295 bool StructType::indexValid(const Value *V) const {
296 // Structure indexes require 32-bit integer constants.
297 if (V->getType()->isIntegerTy(32))
298 if (const ConstantInt *CU = dyn_cast<ConstantInt>(V))
299 return indexValid(CU->getZExtValue());
303 bool StructType::indexValid(unsigned V) const {
304 return V < NumContainedTys;
307 // getTypeAtIndex - Given an index value into the type, return the type of the
308 // element. For a structure type, this must be a constant value...
310 const Type *StructType::getTypeAtIndex(const Value *V) const {
311 unsigned Idx = (unsigned)cast<ConstantInt>(V)->getZExtValue();
312 return getTypeAtIndex(Idx);
315 const Type *StructType::getTypeAtIndex(unsigned Idx) const {
316 assert(indexValid(Idx) && "Invalid structure index!");
317 return ContainedTys[Idx];
321 //===----------------------------------------------------------------------===//
322 // Primitive 'Type' data
323 //===----------------------------------------------------------------------===//
325 const Type *Type::getVoidTy(LLVMContext &C) {
326 return &C.pImpl->VoidTy;
329 const Type *Type::getLabelTy(LLVMContext &C) {
330 return &C.pImpl->LabelTy;
333 const Type *Type::getFloatTy(LLVMContext &C) {
334 return &C.pImpl->FloatTy;
337 const Type *Type::getDoubleTy(LLVMContext &C) {
338 return &C.pImpl->DoubleTy;
341 const Type *Type::getMetadataTy(LLVMContext &C) {
342 return &C.pImpl->MetadataTy;
345 const Type *Type::getX86_FP80Ty(LLVMContext &C) {
346 return &C.pImpl->X86_FP80Ty;
349 const Type *Type::getFP128Ty(LLVMContext &C) {
350 return &C.pImpl->FP128Ty;
353 const Type *Type::getPPC_FP128Ty(LLVMContext &C) {
354 return &C.pImpl->PPC_FP128Ty;
357 const IntegerType *Type::getIntNTy(LLVMContext &C, unsigned N) {
358 return IntegerType::get(C, N);
361 const IntegerType *Type::getInt1Ty(LLVMContext &C) {
362 return &C.pImpl->Int1Ty;
365 const IntegerType *Type::getInt8Ty(LLVMContext &C) {
366 return &C.pImpl->Int8Ty;
369 const IntegerType *Type::getInt16Ty(LLVMContext &C) {
370 return &C.pImpl->Int16Ty;
373 const IntegerType *Type::getInt32Ty(LLVMContext &C) {
374 return &C.pImpl->Int32Ty;
377 const IntegerType *Type::getInt64Ty(LLVMContext &C) {
378 return &C.pImpl->Int64Ty;
381 const PointerType *Type::getFloatPtrTy(LLVMContext &C, unsigned AS) {
382 return getFloatTy(C)->getPointerTo(AS);
385 const PointerType *Type::getDoublePtrTy(LLVMContext &C, unsigned AS) {
386 return getDoubleTy(C)->getPointerTo(AS);
389 const PointerType *Type::getX86_FP80PtrTy(LLVMContext &C, unsigned AS) {
390 return getX86_FP80Ty(C)->getPointerTo(AS);
393 const PointerType *Type::getFP128PtrTy(LLVMContext &C, unsigned AS) {
394 return getFP128Ty(C)->getPointerTo(AS);
397 const PointerType *Type::getPPC_FP128PtrTy(LLVMContext &C, unsigned AS) {
398 return getPPC_FP128Ty(C)->getPointerTo(AS);
401 const PointerType *Type::getIntNPtrTy(LLVMContext &C, unsigned N, unsigned AS) {
402 return getIntNTy(C, N)->getPointerTo(AS);
405 const PointerType *Type::getInt1PtrTy(LLVMContext &C, unsigned AS) {
406 return getInt1Ty(C)->getPointerTo(AS);
409 const PointerType *Type::getInt8PtrTy(LLVMContext &C, unsigned AS) {
410 return getInt8Ty(C)->getPointerTo(AS);
413 const PointerType *Type::getInt16PtrTy(LLVMContext &C, unsigned AS) {
414 return getInt16Ty(C)->getPointerTo(AS);
417 const PointerType *Type::getInt32PtrTy(LLVMContext &C, unsigned AS) {
418 return getInt32Ty(C)->getPointerTo(AS);
421 const PointerType *Type::getInt64PtrTy(LLVMContext &C, unsigned AS) {
422 return getInt64Ty(C)->getPointerTo(AS);
425 //===----------------------------------------------------------------------===//
426 // Derived Type Constructors
427 //===----------------------------------------------------------------------===//
429 /// isValidReturnType - Return true if the specified type is valid as a return
431 bool FunctionType::isValidReturnType(const Type *RetTy) {
432 return !RetTy->isFunctionTy() && !RetTy->isLabelTy() &&
433 !RetTy->isMetadataTy();
436 /// isValidArgumentType - Return true if the specified type is valid as an
438 bool FunctionType::isValidArgumentType(const Type *ArgTy) {
439 return ArgTy->isFirstClassType() || ArgTy->isOpaqueTy();
442 FunctionType::FunctionType(const Type *Result,
443 const std::vector<const Type*> &Params,
445 : DerivedType(Result->getContext(), FunctionTyID), isVarArgs(IsVarArgs) {
446 ContainedTys = reinterpret_cast<PATypeHandle*>(this+1);
447 NumContainedTys = Params.size() + 1; // + 1 for result type
448 assert(isValidReturnType(Result) && "invalid return type for function");
451 bool isAbstract = Result->isAbstract();
452 new (&ContainedTys[0]) PATypeHandle(Result, this);
454 for (unsigned i = 0; i != Params.size(); ++i) {
455 assert(isValidArgumentType(Params[i]) &&
456 "Not a valid type for function argument!");
457 new (&ContainedTys[i+1]) PATypeHandle(Params[i], this);
458 isAbstract |= Params[i]->isAbstract();
461 // Calculate whether or not this type is abstract
462 setAbstract(isAbstract);
465 StructType::StructType(LLVMContext &C,
466 const std::vector<const Type*> &Types, bool isPacked)
467 : CompositeType(C, StructTyID) {
468 ContainedTys = reinterpret_cast<PATypeHandle*>(this + 1);
469 NumContainedTys = Types.size();
470 setSubclassData(isPacked);
471 bool isAbstract = false;
472 for (unsigned i = 0; i < Types.size(); ++i) {
473 assert(Types[i] && "<null> type for structure field!");
474 assert(isValidElementType(Types[i]) &&
475 "Invalid type for structure element!");
476 new (&ContainedTys[i]) PATypeHandle(Types[i], this);
477 isAbstract |= Types[i]->isAbstract();
480 // Calculate whether or not this type is abstract
481 setAbstract(isAbstract);
484 ArrayType::ArrayType(const Type *ElType, uint64_t NumEl)
485 : SequentialType(ArrayTyID, ElType) {
488 // Calculate whether or not this type is abstract
489 setAbstract(ElType->isAbstract());
492 VectorType::VectorType(const Type *ElType, unsigned NumEl)
493 : SequentialType(VectorTyID, ElType) {
495 setAbstract(ElType->isAbstract());
496 assert(NumEl > 0 && "NumEl of a VectorType must be greater than 0");
497 assert(isValidElementType(ElType) &&
498 "Elements of a VectorType must be a primitive type");
503 PointerType::PointerType(const Type *E, unsigned AddrSpace)
504 : SequentialType(PointerTyID, E) {
505 AddressSpace = AddrSpace;
506 // Calculate whether or not this type is abstract
507 setAbstract(E->isAbstract());
510 OpaqueType::OpaqueType(LLVMContext &C) : DerivedType(C, OpaqueTyID) {
512 #ifdef DEBUG_MERGE_TYPES
513 DEBUG(dbgs() << "Derived new type: " << *this << "\n");
517 void PATypeHolder::destroy() {
521 // dropAllTypeUses - When this (abstract) type is resolved to be equal to
522 // another (more concrete) type, we must eliminate all references to other
523 // types, to avoid some circular reference problems.
524 void DerivedType::dropAllTypeUses() {
525 if (NumContainedTys != 0) {
526 // The type must stay abstract. To do this, we insert a pointer to a type
527 // that will never get resolved, thus will always be abstract.
528 ContainedTys[0] = getContext().pImpl->AlwaysOpaqueTy;
530 // Change the rest of the types to be Int32Ty's. It doesn't matter what we
531 // pick so long as it doesn't point back to this type. We choose something
532 // concrete to avoid overhead for adding to AbstractTypeUser lists and
534 const Type *ConcreteTy = Type::getInt32Ty(getContext());
535 for (unsigned i = 1, e = NumContainedTys; i != e; ++i)
536 ContainedTys[i] = ConcreteTy;
543 /// TypePromotionGraph and graph traits - this is designed to allow us to do
544 /// efficient SCC processing of type graphs. This is the exact same as
545 /// GraphTraits<Type*>, except that we pretend that concrete types have no
546 /// children to avoid processing them.
547 struct TypePromotionGraph {
549 TypePromotionGraph(Type *T) : Ty(T) {}
555 template <> struct GraphTraits<TypePromotionGraph> {
556 typedef Type NodeType;
557 typedef Type::subtype_iterator ChildIteratorType;
559 static inline NodeType *getEntryNode(TypePromotionGraph G) { return G.Ty; }
560 static inline ChildIteratorType child_begin(NodeType *N) {
562 return N->subtype_begin();
563 // No need to process children of concrete types.
564 return N->subtype_end();
566 static inline ChildIteratorType child_end(NodeType *N) {
567 return N->subtype_end();
573 // PromoteAbstractToConcrete - This is a recursive function that walks a type
574 // graph calculating whether or not a type is abstract.
576 void Type::PromoteAbstractToConcrete() {
577 if (!isAbstract()) return;
579 scc_iterator<TypePromotionGraph> SI = scc_begin(TypePromotionGraph(this));
580 scc_iterator<TypePromotionGraph> SE = scc_end (TypePromotionGraph(this));
582 for (; SI != SE; ++SI) {
583 std::vector<Type*> &SCC = *SI;
585 // Concrete types are leaves in the tree. Since an SCC will either be all
586 // abstract or all concrete, we only need to check one type.
587 if (!SCC[0]->isAbstract()) continue;
589 if (SCC[0]->isOpaqueTy())
590 return; // Not going to be concrete, sorry.
592 // If all of the children of all of the types in this SCC are concrete,
593 // then this SCC is now concrete as well. If not, neither this SCC, nor
594 // any parent SCCs will be concrete, so we might as well just exit.
595 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
596 for (Type::subtype_iterator CI = SCC[i]->subtype_begin(),
597 E = SCC[i]->subtype_end(); CI != E; ++CI)
598 if ((*CI)->isAbstract())
599 // If the child type is in our SCC, it doesn't make the entire SCC
600 // abstract unless there is a non-SCC abstract type.
601 if (std::find(SCC.begin(), SCC.end(), *CI) == SCC.end())
602 return; // Not going to be concrete, sorry.
604 // Okay, we just discovered this whole SCC is now concrete, mark it as
606 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
607 assert(SCC[i]->isAbstract() && "Why are we processing concrete types?");
609 SCC[i]->setAbstract(false);
612 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
613 assert(!SCC[i]->isAbstract() && "Concrete type became abstract?");
614 // The type just became concrete, notify all users!
615 cast<DerivedType>(SCC[i])->notifyUsesThatTypeBecameConcrete();
621 //===----------------------------------------------------------------------===//
622 // Type Structural Equality Testing
623 //===----------------------------------------------------------------------===//
625 // TypesEqual - Two types are considered structurally equal if they have the
626 // same "shape": Every level and element of the types have identical primitive
627 // ID's, and the graphs have the same edges/nodes in them. Nodes do not have to
628 // be pointer equals to be equivalent though. This uses an optimistic algorithm
629 // that assumes that two graphs are the same until proven otherwise.
631 static bool TypesEqual(const Type *Ty, const Type *Ty2,
632 std::map<const Type *, const Type *> &EqTypes) {
633 if (Ty == Ty2) return true;
634 if (Ty->getTypeID() != Ty2->getTypeID()) return false;
635 if (Ty->isOpaqueTy())
636 return false; // Two unequal opaque types are never equal
638 std::map<const Type*, const Type*>::iterator It = EqTypes.find(Ty);
639 if (It != EqTypes.end())
640 return It->second == Ty2; // Looping back on a type, check for equality
642 // Otherwise, add the mapping to the table to make sure we don't get
643 // recursion on the types...
644 EqTypes.insert(It, std::make_pair(Ty, Ty2));
646 // Two really annoying special cases that breaks an otherwise nice simple
647 // algorithm is the fact that arraytypes have sizes that differentiates types,
648 // and that function types can be varargs or not. Consider this now.
650 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
651 const IntegerType *ITy2 = cast<IntegerType>(Ty2);
652 return ITy->getBitWidth() == ITy2->getBitWidth();
655 if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
656 const PointerType *PTy2 = cast<PointerType>(Ty2);
657 return PTy->getAddressSpace() == PTy2->getAddressSpace() &&
658 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
661 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
662 const StructType *STy2 = cast<StructType>(Ty2);
663 if (STy->getNumElements() != STy2->getNumElements()) return false;
664 if (STy->isPacked() != STy2->isPacked()) return false;
665 for (unsigned i = 0, e = STy2->getNumElements(); i != e; ++i)
666 if (!TypesEqual(STy->getElementType(i), STy2->getElementType(i), EqTypes))
671 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
672 const ArrayType *ATy2 = cast<ArrayType>(Ty2);
673 return ATy->getNumElements() == ATy2->getNumElements() &&
674 TypesEqual(ATy->getElementType(), ATy2->getElementType(), EqTypes);
677 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
678 const VectorType *PTy2 = cast<VectorType>(Ty2);
679 return PTy->getNumElements() == PTy2->getNumElements() &&
680 TypesEqual(PTy->getElementType(), PTy2->getElementType(), EqTypes);
683 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
684 const FunctionType *FTy2 = cast<FunctionType>(Ty2);
685 if (FTy->isVarArg() != FTy2->isVarArg() ||
686 FTy->getNumParams() != FTy2->getNumParams() ||
687 !TypesEqual(FTy->getReturnType(), FTy2->getReturnType(), EqTypes))
689 for (unsigned i = 0, e = FTy2->getNumParams(); i != e; ++i) {
690 if (!TypesEqual(FTy->getParamType(i), FTy2->getParamType(i), EqTypes))
696 llvm_unreachable("Unknown derived type!");
700 namespace llvm { // in namespace llvm so findable by ADL
701 static bool TypesEqual(const Type *Ty, const Type *Ty2) {
702 std::map<const Type *, const Type *> EqTypes;
703 return ::TypesEqual(Ty, Ty2, EqTypes);
707 // AbstractTypeHasCycleThrough - Return true there is a path from CurTy to
708 // TargetTy in the type graph. We know that Ty is an abstract type, so if we
709 // ever reach a non-abstract type, we know that we don't need to search the
711 static bool AbstractTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
712 SmallPtrSet<const Type*, 128> &VisitedTypes) {
713 if (TargetTy == CurTy) return true;
714 if (!CurTy->isAbstract()) return false;
716 if (!VisitedTypes.insert(CurTy))
717 return false; // Already been here.
719 for (Type::subtype_iterator I = CurTy->subtype_begin(),
720 E = CurTy->subtype_end(); I != E; ++I)
721 if (AbstractTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
726 static bool ConcreteTypeHasCycleThrough(const Type *TargetTy, const Type *CurTy,
727 SmallPtrSet<const Type*, 128> &VisitedTypes) {
728 if (TargetTy == CurTy) return true;
730 if (!VisitedTypes.insert(CurTy))
731 return false; // Already been here.
733 for (Type::subtype_iterator I = CurTy->subtype_begin(),
734 E = CurTy->subtype_end(); I != E; ++I)
735 if (ConcreteTypeHasCycleThrough(TargetTy, *I, VisitedTypes))
740 /// TypeHasCycleThroughItself - Return true if the specified type has
741 /// a cycle back to itself.
743 namespace llvm { // in namespace llvm so it's findable by ADL
744 static bool TypeHasCycleThroughItself(const Type *Ty) {
745 SmallPtrSet<const Type*, 128> VisitedTypes;
747 if (Ty->isAbstract()) { // Optimized case for abstract types.
748 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
750 if (AbstractTypeHasCycleThrough(Ty, *I, VisitedTypes))
753 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
755 if (ConcreteTypeHasCycleThrough(Ty, *I, VisitedTypes))
762 //===----------------------------------------------------------------------===//
763 // Function Type Factory and Value Class...
765 const IntegerType *IntegerType::get(LLVMContext &C, unsigned NumBits) {
766 assert(NumBits >= MIN_INT_BITS && "bitwidth too small");
767 assert(NumBits <= MAX_INT_BITS && "bitwidth too large");
769 // Check for the built-in integer types
771 case 1: return cast<IntegerType>(Type::getInt1Ty(C));
772 case 8: return cast<IntegerType>(Type::getInt8Ty(C));
773 case 16: return cast<IntegerType>(Type::getInt16Ty(C));
774 case 32: return cast<IntegerType>(Type::getInt32Ty(C));
775 case 64: return cast<IntegerType>(Type::getInt64Ty(C));
780 LLVMContextImpl *pImpl = C.pImpl;
782 IntegerValType IVT(NumBits);
783 IntegerType *ITy = 0;
785 // First, see if the type is already in the table, for which
786 // a reader lock suffices.
787 ITy = pImpl->IntegerTypes.get(IVT);
790 // Value not found. Derive a new type!
791 ITy = new IntegerType(C, NumBits);
792 pImpl->IntegerTypes.add(IVT, ITy);
794 #ifdef DEBUG_MERGE_TYPES
795 DEBUG(dbgs() << "Derived new type: " << *ITy << "\n");
800 bool IntegerType::isPowerOf2ByteWidth() const {
801 unsigned BitWidth = getBitWidth();
802 return (BitWidth > 7) && isPowerOf2_32(BitWidth);
805 APInt IntegerType::getMask() const {
806 return APInt::getAllOnesValue(getBitWidth());
809 FunctionValType FunctionValType::get(const FunctionType *FT) {
810 // Build up a FunctionValType
811 std::vector<const Type *> ParamTypes;
812 ParamTypes.reserve(FT->getNumParams());
813 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
814 ParamTypes.push_back(FT->getParamType(i));
815 return FunctionValType(FT->getReturnType(), ParamTypes, FT->isVarArg());
819 // FunctionType::get - The factory function for the FunctionType class...
820 FunctionType *FunctionType::get(const Type *ReturnType,
821 const std::vector<const Type*> &Params,
823 FunctionValType VT(ReturnType, Params, isVarArg);
824 FunctionType *FT = 0;
826 LLVMContextImpl *pImpl = ReturnType->getContext().pImpl;
828 FT = pImpl->FunctionTypes.get(VT);
831 FT = (FunctionType*) operator new(sizeof(FunctionType) +
832 sizeof(PATypeHandle)*(Params.size()+1));
833 new (FT) FunctionType(ReturnType, Params, isVarArg);
834 pImpl->FunctionTypes.add(VT, FT);
837 #ifdef DEBUG_MERGE_TYPES
838 DEBUG(dbgs() << "Derived new type: " << FT << "\n");
843 ArrayType *ArrayType::get(const Type *ElementType, uint64_t NumElements) {
844 assert(ElementType && "Can't get array of <null> types!");
845 assert(isValidElementType(ElementType) && "Invalid type for array element!");
847 ArrayValType AVT(ElementType, NumElements);
850 LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
852 AT = pImpl->ArrayTypes.get(AVT);
855 // Value not found. Derive a new type!
856 pImpl->ArrayTypes.add(AVT, AT = new ArrayType(ElementType, NumElements));
858 #ifdef DEBUG_MERGE_TYPES
859 DEBUG(dbgs() << "Derived new type: " << *AT << "\n");
864 bool ArrayType::isValidElementType(const Type *ElemTy) {
865 return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
866 !ElemTy->isMetadataTy() && !ElemTy->isFunctionTy();
869 VectorType *VectorType::get(const Type *ElementType, unsigned NumElements) {
870 assert(ElementType && "Can't get vector of <null> types!");
872 VectorValType PVT(ElementType, NumElements);
875 LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
877 PT = pImpl->VectorTypes.get(PVT);
880 pImpl->VectorTypes.add(PVT, PT = new VectorType(ElementType, NumElements));
882 #ifdef DEBUG_MERGE_TYPES
883 DEBUG(dbgs() << "Derived new type: " << *PT << "\n");
888 bool VectorType::isValidElementType(const Type *ElemTy) {
889 return ElemTy->isIntegerTy() || ElemTy->isFloatingPointTy() ||
890 ElemTy->isOpaqueTy();
893 //===----------------------------------------------------------------------===//
894 // Struct Type Factory...
897 StructType *StructType::get(LLVMContext &Context,
898 const std::vector<const Type*> &ETypes,
900 StructValType STV(ETypes, isPacked);
903 LLVMContextImpl *pImpl = Context.pImpl;
905 ST = pImpl->StructTypes.get(STV);
908 // Value not found. Derive a new type!
909 ST = (StructType*) operator new(sizeof(StructType) +
910 sizeof(PATypeHandle) * ETypes.size());
911 new (ST) StructType(Context, ETypes, isPacked);
912 pImpl->StructTypes.add(STV, ST);
914 #ifdef DEBUG_MERGE_TYPES
915 DEBUG(dbgs() << "Derived new type: " << *ST << "\n");
920 StructType *StructType::get(LLVMContext &Context, const Type *type, ...) {
922 std::vector<const llvm::Type*> StructFields;
925 StructFields.push_back(type);
926 type = va_arg(ap, llvm::Type*);
928 return llvm::StructType::get(Context, StructFields);
931 bool StructType::isValidElementType(const Type *ElemTy) {
932 return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
933 !ElemTy->isMetadataTy() && !ElemTy->isFunctionTy();
937 //===----------------------------------------------------------------------===//
938 // Pointer Type Factory...
941 PointerType *PointerType::get(const Type *ValueType, unsigned AddressSpace) {
942 assert(ValueType && "Can't get a pointer to <null> type!");
943 assert(ValueType->getTypeID() != VoidTyID &&
944 "Pointer to void is not valid, use i8* instead!");
945 assert(isValidElementType(ValueType) && "Invalid type for pointer element!");
946 PointerValType PVT(ValueType, AddressSpace);
950 LLVMContextImpl *pImpl = ValueType->getContext().pImpl;
952 PT = pImpl->PointerTypes.get(PVT);
955 // Value not found. Derive a new type!
956 pImpl->PointerTypes.add(PVT, PT = new PointerType(ValueType, AddressSpace));
958 #ifdef DEBUG_MERGE_TYPES
959 DEBUG(dbgs() << "Derived new type: " << *PT << "\n");
964 const PointerType *Type::getPointerTo(unsigned addrs) const {
965 return PointerType::get(this, addrs);
968 bool PointerType::isValidElementType(const Type *ElemTy) {
969 return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
970 !ElemTy->isMetadataTy();
974 //===----------------------------------------------------------------------===//
975 // Opaque Type Factory...
978 OpaqueType *OpaqueType::get(LLVMContext &C) {
979 OpaqueType *OT = new OpaqueType(C); // All opaque types are distinct.
980 LLVMContextImpl *pImpl = C.pImpl;
981 pImpl->OpaqueTypes.insert(OT);
987 //===----------------------------------------------------------------------===//
988 // Derived Type Refinement Functions
989 //===----------------------------------------------------------------------===//
991 // addAbstractTypeUser - Notify an abstract type that there is a new user of
992 // it. This function is called primarily by the PATypeHandle class.
993 void Type::addAbstractTypeUser(AbstractTypeUser *U) const {
994 assert(isAbstract() && "addAbstractTypeUser: Current type not abstract!");
995 AbstractTypeUsers.push_back(U);
999 // removeAbstractTypeUser - Notify an abstract type that a user of the class
1000 // no longer has a handle to the type. This function is called primarily by
1001 // the PATypeHandle class. When there are no users of the abstract type, it
1002 // is annihilated, because there is no way to get a reference to it ever again.
1004 void Type::removeAbstractTypeUser(AbstractTypeUser *U) const {
1006 // Search from back to front because we will notify users from back to
1007 // front. Also, it is likely that there will be a stack like behavior to
1008 // users that register and unregister users.
1011 for (i = AbstractTypeUsers.size(); AbstractTypeUsers[i-1] != U; --i)
1012 assert(i != 0 && "AbstractTypeUser not in user list!");
1014 --i; // Convert to be in range 0 <= i < size()
1015 assert(i < AbstractTypeUsers.size() && "Index out of range!"); // Wraparound?
1017 AbstractTypeUsers.erase(AbstractTypeUsers.begin()+i);
1019 #ifdef DEBUG_MERGE_TYPES
1020 DEBUG(dbgs() << " remAbstractTypeUser[" << (void*)this << ", "
1021 << *this << "][" << i << "] User = " << U << "\n");
1024 if (AbstractTypeUsers.empty() && getRefCount() == 0 && isAbstract()) {
1025 #ifdef DEBUG_MERGE_TYPES
1026 DEBUG(dbgs() << "DELETEing unused abstract type: <" << *this
1027 << ">[" << (void*)this << "]" << "\n");
1034 // refineAbstractTypeTo - This function is used when it is discovered
1035 // that the 'this' abstract type is actually equivalent to the NewType
1036 // specified. This causes all users of 'this' to switch to reference the more
1037 // concrete type NewType and for 'this' to be deleted. Only used for internal
1040 void DerivedType::refineAbstractTypeTo(const Type *NewType) {
1041 assert(isAbstract() && "refineAbstractTypeTo: Current type is not abstract!");
1042 assert(this != NewType && "Can't refine to myself!");
1043 assert(ForwardType == 0 && "This type has already been refined!");
1045 LLVMContextImpl *pImpl = getContext().pImpl;
1047 // The descriptions may be out of date. Conservatively clear them all!
1048 pImpl->AbstractTypeDescriptions.clear();
1050 #ifdef DEBUG_MERGE_TYPES
1051 DEBUG(dbgs() << "REFINING abstract type [" << (void*)this << " "
1052 << *this << "] to [" << (void*)NewType << " "
1053 << *NewType << "]!\n");
1056 // Make sure to put the type to be refined to into a holder so that if IT gets
1057 // refined, that we will not continue using a dead reference...
1059 PATypeHolder NewTy(NewType);
1060 // Any PATypeHolders referring to this type will now automatically forward to
1061 // the type we are resolved to.
1062 ForwardType = NewType;
1063 if (ForwardType->isAbstract())
1064 ForwardType->addRef();
1066 // Add a self use of the current type so that we don't delete ourself until
1067 // after the function exits.
1069 PATypeHolder CurrentTy(this);
1071 // To make the situation simpler, we ask the subclass to remove this type from
1072 // the type map, and to replace any type uses with uses of non-abstract types.
1073 // This dramatically limits the amount of recursive type trouble we can find
1077 // Iterate over all of the uses of this type, invoking callback. Each user
1078 // should remove itself from our use list automatically. We have to check to
1079 // make sure that NewTy doesn't _become_ 'this'. If it does, resolving types
1080 // will not cause users to drop off of the use list. If we resolve to ourself
1083 while (!AbstractTypeUsers.empty() && NewTy != this) {
1084 AbstractTypeUser *User = AbstractTypeUsers.back();
1086 unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1087 #ifdef DEBUG_MERGE_TYPES
1088 DEBUG(dbgs() << " REFINING user " << OldSize-1 << "[" << (void*)User
1089 << "] of abstract type [" << (void*)this << " "
1090 << *this << "] to [" << (void*)NewTy.get() << " "
1091 << *NewTy << "]!\n");
1093 User->refineAbstractType(this, NewTy);
1095 assert(AbstractTypeUsers.size() != OldSize &&
1096 "AbsTyUser did not remove self from user list!");
1099 // If we were successful removing all users from the type, 'this' will be
1100 // deleted when the last PATypeHolder is destroyed or updated from this type.
1101 // This may occur on exit of this function, as the CurrentTy object is
1105 // notifyUsesThatTypeBecameConcrete - Notify AbstractTypeUsers of this type that
1106 // the current type has transitioned from being abstract to being concrete.
1108 void DerivedType::notifyUsesThatTypeBecameConcrete() {
1109 #ifdef DEBUG_MERGE_TYPES
1110 DEBUG(dbgs() << "typeIsREFINED type: " << (void*)this << " " << *this <<"\n");
1113 unsigned OldSize = AbstractTypeUsers.size(); OldSize=OldSize;
1114 while (!AbstractTypeUsers.empty()) {
1115 AbstractTypeUser *ATU = AbstractTypeUsers.back();
1116 ATU->typeBecameConcrete(this);
1118 assert(AbstractTypeUsers.size() < OldSize-- &&
1119 "AbstractTypeUser did not remove itself from the use list!");
1123 // refineAbstractType - Called when a contained type is found to be more
1124 // concrete - this could potentially change us from an abstract type to a
1127 void FunctionType::refineAbstractType(const DerivedType *OldType,
1128 const Type *NewType) {
1129 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1130 pImpl->FunctionTypes.RefineAbstractType(this, OldType, NewType);
1133 void FunctionType::typeBecameConcrete(const DerivedType *AbsTy) {
1134 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1135 pImpl->FunctionTypes.TypeBecameConcrete(this, AbsTy);
1139 // refineAbstractType - Called when a contained type is found to be more
1140 // concrete - this could potentially change us from an abstract type to a
1143 void ArrayType::refineAbstractType(const DerivedType *OldType,
1144 const Type *NewType) {
1145 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1146 pImpl->ArrayTypes.RefineAbstractType(this, OldType, NewType);
1149 void ArrayType::typeBecameConcrete(const DerivedType *AbsTy) {
1150 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1151 pImpl->ArrayTypes.TypeBecameConcrete(this, AbsTy);
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 VectorType::refineAbstractType(const DerivedType *OldType,
1159 const Type *NewType) {
1160 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1161 pImpl->VectorTypes.RefineAbstractType(this, OldType, NewType);
1164 void VectorType::typeBecameConcrete(const DerivedType *AbsTy) {
1165 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1166 pImpl->VectorTypes.TypeBecameConcrete(this, AbsTy);
1169 // refineAbstractType - Called when a contained type is found to be more
1170 // concrete - this could potentially change us from an abstract type to a
1173 void StructType::refineAbstractType(const DerivedType *OldType,
1174 const Type *NewType) {
1175 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1176 pImpl->StructTypes.RefineAbstractType(this, OldType, NewType);
1179 void StructType::typeBecameConcrete(const DerivedType *AbsTy) {
1180 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1181 pImpl->StructTypes.TypeBecameConcrete(this, AbsTy);
1184 // refineAbstractType - Called when a contained type is found to be more
1185 // concrete - this could potentially change us from an abstract type to a
1188 void PointerType::refineAbstractType(const DerivedType *OldType,
1189 const Type *NewType) {
1190 LLVMContextImpl *pImpl = OldType->getContext().pImpl;
1191 pImpl->PointerTypes.RefineAbstractType(this, OldType, NewType);
1194 void PointerType::typeBecameConcrete(const DerivedType *AbsTy) {
1195 LLVMContextImpl *pImpl = AbsTy->getContext().pImpl;
1196 pImpl->PointerTypes.TypeBecameConcrete(this, AbsTy);
1199 bool SequentialType::indexValid(const Value *V) const {
1200 if (V->getType()->isIntegerTy())
1206 raw_ostream &operator<<(raw_ostream &OS, const Type &T) {