1 //===--- Type.cpp - Type representation and manipulation ------------------===//
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 type-related functionality.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/Attr.h"
16 #include "clang/AST/CharUnits.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/PrettyPrinter.h"
22 #include "clang/AST/Type.h"
23 #include "clang/AST/TypeVisitor.h"
24 #include "clang/Basic/Specifiers.h"
25 #include "llvm/ADT/APSInt.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Support/raw_ostream.h"
29 using namespace clang;
31 bool Qualifiers::isStrictSupersetOf(Qualifiers Other) const {
32 return (*this != Other) &&
33 // CVR qualifiers superset
34 (((Mask & CVRMask) | (Other.Mask & CVRMask)) == (Mask & CVRMask)) &&
35 // ObjC GC qualifiers superset
36 ((getObjCGCAttr() == Other.getObjCGCAttr()) ||
37 (hasObjCGCAttr() && !Other.hasObjCGCAttr())) &&
38 // Address space superset.
39 ((getAddressSpace() == Other.getAddressSpace()) ||
40 (hasAddressSpace()&& !Other.hasAddressSpace())) &&
41 // Lifetime qualifier superset.
42 ((getObjCLifetime() == Other.getObjCLifetime()) ||
43 (hasObjCLifetime() && !Other.hasObjCLifetime()));
46 const IdentifierInfo* QualType::getBaseTypeIdentifier() const {
47 const Type* ty = getTypePtr();
48 NamedDecl *ND = nullptr;
49 if (ty->isPointerType() || ty->isReferenceType())
50 return ty->getPointeeType().getBaseTypeIdentifier();
51 else if (ty->isRecordType())
52 ND = ty->getAs<RecordType>()->getDecl();
53 else if (ty->isEnumeralType())
54 ND = ty->getAs<EnumType>()->getDecl();
55 else if (ty->getTypeClass() == Type::Typedef)
56 ND = ty->getAs<TypedefType>()->getDecl();
57 else if (ty->isArrayType())
58 return ty->castAsArrayTypeUnsafe()->
59 getElementType().getBaseTypeIdentifier();
62 return ND->getIdentifier();
66 bool QualType::isConstant(QualType T, ASTContext &Ctx) {
67 if (T.isConstQualified())
70 if (const ArrayType *AT = Ctx.getAsArrayType(T))
71 return AT->getElementType().isConstant(Ctx);
73 return T.getAddressSpace() == LangAS::opencl_constant;
76 unsigned ConstantArrayType::getNumAddressingBits(ASTContext &Context,
78 const llvm::APInt &NumElements) {
79 uint64_t ElementSize = Context.getTypeSizeInChars(ElementType).getQuantity();
81 // Fast path the common cases so we can avoid the conservative computation
82 // below, which in common cases allocates "large" APSInt values, which are
85 // If the element size is a power of 2, we can directly compute the additional
86 // number of addressing bits beyond those required for the element count.
87 if (llvm::isPowerOf2_64(ElementSize)) {
88 return NumElements.getActiveBits() + llvm::Log2_64(ElementSize);
91 // If both the element count and element size fit in 32-bits, we can do the
92 // computation directly in 64-bits.
93 if ((ElementSize >> 32) == 0 && NumElements.getBitWidth() <= 64 &&
94 (NumElements.getZExtValue() >> 32) == 0) {
95 uint64_t TotalSize = NumElements.getZExtValue() * ElementSize;
96 return 64 - llvm::countLeadingZeros(TotalSize);
99 // Otherwise, use APSInt to handle arbitrary sized values.
100 llvm::APSInt SizeExtended(NumElements, true);
101 unsigned SizeTypeBits = Context.getTypeSize(Context.getSizeType());
102 SizeExtended = SizeExtended.extend(std::max(SizeTypeBits,
103 SizeExtended.getBitWidth()) * 2);
105 llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize));
106 TotalSize *= SizeExtended;
108 return TotalSize.getActiveBits();
111 unsigned ConstantArrayType::getMaxSizeBits(ASTContext &Context) {
112 unsigned Bits = Context.getTypeSize(Context.getSizeType());
114 // Limit the number of bits in size_t so that maximal bit size fits 64 bit
115 // integer (see PR8256). We can do this as currently there is no hardware
116 // that supports full 64-bit virtual space.
123 DependentSizedArrayType::DependentSizedArrayType(const ASTContext &Context,
124 QualType et, QualType can,
125 Expr *e, ArraySizeModifier sm,
127 SourceRange brackets)
128 : ArrayType(DependentSizedArray, et, can, sm, tq,
129 (et->containsUnexpandedParameterPack() ||
130 (e && e->containsUnexpandedParameterPack()))),
131 Context(Context), SizeExpr((Stmt*) e), Brackets(brackets)
135 void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID,
136 const ASTContext &Context,
138 ArraySizeModifier SizeMod,
141 ID.AddPointer(ET.getAsOpaquePtr());
142 ID.AddInteger(SizeMod);
143 ID.AddInteger(TypeQuals);
144 E->Profile(ID, Context, true);
147 DependentSizedExtVectorType::DependentSizedExtVectorType(const
149 QualType ElementType,
153 : Type(DependentSizedExtVector, can, /*Dependent=*/true,
154 /*InstantiationDependent=*/true,
155 ElementType->isVariablyModifiedType(),
156 (ElementType->containsUnexpandedParameterPack() ||
157 (SizeExpr && SizeExpr->containsUnexpandedParameterPack()))),
158 Context(Context), SizeExpr(SizeExpr), ElementType(ElementType),
164 DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID,
165 const ASTContext &Context,
166 QualType ElementType, Expr *SizeExpr) {
167 ID.AddPointer(ElementType.getAsOpaquePtr());
168 SizeExpr->Profile(ID, Context, true);
171 VectorType::VectorType(QualType vecType, unsigned nElements, QualType canonType,
173 : Type(Vector, canonType, vecType->isDependentType(),
174 vecType->isInstantiationDependentType(),
175 vecType->isVariablyModifiedType(),
176 vecType->containsUnexpandedParameterPack()),
179 VectorTypeBits.VecKind = vecKind;
180 VectorTypeBits.NumElements = nElements;
183 VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements,
184 QualType canonType, VectorKind vecKind)
185 : Type(tc, canonType, vecType->isDependentType(),
186 vecType->isInstantiationDependentType(),
187 vecType->isVariablyModifiedType(),
188 vecType->containsUnexpandedParameterPack()),
191 VectorTypeBits.VecKind = vecKind;
192 VectorTypeBits.NumElements = nElements;
195 /// getArrayElementTypeNoTypeQual - If this is an array type, return the
196 /// element type of the array, potentially with type qualifiers missing.
197 /// This method should never be used when type qualifiers are meaningful.
198 const Type *Type::getArrayElementTypeNoTypeQual() const {
199 // If this is directly an array type, return it.
200 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
201 return ATy->getElementType().getTypePtr();
203 // If the canonical form of this type isn't the right kind, reject it.
204 if (!isa<ArrayType>(CanonicalType))
207 // If this is a typedef for an array type, strip the typedef off without
208 // losing all typedef information.
209 return cast<ArrayType>(getUnqualifiedDesugaredType())
210 ->getElementType().getTypePtr();
213 /// getDesugaredType - Return the specified type with any "sugar" removed from
214 /// the type. This takes off typedefs, typeof's etc. If the outer level of
215 /// the type is already concrete, it returns it unmodified. This is similar
216 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
217 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
219 QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) {
220 SplitQualType split = getSplitDesugaredType(T);
221 return Context.getQualifiedType(split.Ty, split.Quals);
224 QualType QualType::getSingleStepDesugaredTypeImpl(QualType type,
225 const ASTContext &Context) {
226 SplitQualType split = type.split();
227 QualType desugar = split.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
228 return Context.getQualifiedType(desugar, split.Quals);
231 QualType Type::getLocallyUnqualifiedSingleStepDesugaredType() const {
232 switch (getTypeClass()) {
233 #define ABSTRACT_TYPE(Class, Parent)
234 #define TYPE(Class, Parent) \
235 case Type::Class: { \
236 const Class##Type *ty = cast<Class##Type>(this); \
237 if (!ty->isSugared()) return QualType(ty, 0); \
238 return ty->desugar(); \
240 #include "clang/AST/TypeNodes.def"
242 llvm_unreachable("bad type kind!");
245 SplitQualType QualType::getSplitDesugaredType(QualType T) {
246 QualifierCollector Qs;
250 const Type *CurTy = Qs.strip(Cur);
251 switch (CurTy->getTypeClass()) {
252 #define ABSTRACT_TYPE(Class, Parent)
253 #define TYPE(Class, Parent) \
254 case Type::Class: { \
255 const Class##Type *Ty = cast<Class##Type>(CurTy); \
256 if (!Ty->isSugared()) \
257 return SplitQualType(Ty, Qs); \
258 Cur = Ty->desugar(); \
261 #include "clang/AST/TypeNodes.def"
266 SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) {
267 SplitQualType split = type.split();
269 // All the qualifiers we've seen so far.
270 Qualifiers quals = split.Quals;
272 // The last type node we saw with any nodes inside it.
273 const Type *lastTypeWithQuals = split.Ty;
278 // Do a single-step desugar, aborting the loop if the type isn't
280 switch (split.Ty->getTypeClass()) {
281 #define ABSTRACT_TYPE(Class, Parent)
282 #define TYPE(Class, Parent) \
283 case Type::Class: { \
284 const Class##Type *ty = cast<Class##Type>(split.Ty); \
285 if (!ty->isSugared()) goto done; \
286 next = ty->desugar(); \
289 #include "clang/AST/TypeNodes.def"
292 // Otherwise, split the underlying type. If that yields qualifiers,
293 // update the information.
294 split = next.split();
295 if (!split.Quals.empty()) {
296 lastTypeWithQuals = split.Ty;
297 quals.addConsistentQualifiers(split.Quals);
302 return SplitQualType(lastTypeWithQuals, quals);
305 QualType QualType::IgnoreParens(QualType T) {
306 // FIXME: this seems inherently un-qualifiers-safe.
307 while (const ParenType *PT = T->getAs<ParenType>())
308 T = PT->getInnerType();
312 /// \brief This will check for a T (which should be a Type which can act as
313 /// sugar, such as a TypedefType) by removing any existing sugar until it
314 /// reaches a T or a non-sugared type.
315 template<typename T> static const T *getAsSugar(const Type *Cur) {
317 if (const T *Sugar = dyn_cast<T>(Cur))
319 switch (Cur->getTypeClass()) {
320 #define ABSTRACT_TYPE(Class, Parent)
321 #define TYPE(Class, Parent) \
322 case Type::Class: { \
323 const Class##Type *Ty = cast<Class##Type>(Cur); \
324 if (!Ty->isSugared()) return 0; \
325 Cur = Ty->desugar().getTypePtr(); \
328 #include "clang/AST/TypeNodes.def"
333 template <> const TypedefType *Type::getAs() const {
334 return getAsSugar<TypedefType>(this);
337 template <> const TemplateSpecializationType *Type::getAs() const {
338 return getAsSugar<TemplateSpecializationType>(this);
341 template <> const AttributedType *Type::getAs() const {
342 return getAsSugar<AttributedType>(this);
345 /// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
346 /// sugar off the given type. This should produce an object of the
347 /// same dynamic type as the canonical type.
348 const Type *Type::getUnqualifiedDesugaredType() const {
349 const Type *Cur = this;
352 switch (Cur->getTypeClass()) {
353 #define ABSTRACT_TYPE(Class, Parent)
354 #define TYPE(Class, Parent) \
356 const Class##Type *Ty = cast<Class##Type>(Cur); \
357 if (!Ty->isSugared()) return Cur; \
358 Cur = Ty->desugar().getTypePtr(); \
361 #include "clang/AST/TypeNodes.def"
365 bool Type::isClassType() const {
366 if (const RecordType *RT = getAs<RecordType>())
367 return RT->getDecl()->isClass();
370 bool Type::isStructureType() const {
371 if (const RecordType *RT = getAs<RecordType>())
372 return RT->getDecl()->isStruct();
375 bool Type::isInterfaceType() const {
376 if (const RecordType *RT = getAs<RecordType>())
377 return RT->getDecl()->isInterface();
380 bool Type::isStructureOrClassType() const {
381 if (const RecordType *RT = getAs<RecordType>()) {
382 RecordDecl *RD = RT->getDecl();
383 return RD->isStruct() || RD->isClass() || RD->isInterface();
387 bool Type::isVoidPointerType() const {
388 if (const PointerType *PT = getAs<PointerType>())
389 return PT->getPointeeType()->isVoidType();
393 bool Type::isUnionType() const {
394 if (const RecordType *RT = getAs<RecordType>())
395 return RT->getDecl()->isUnion();
399 bool Type::isComplexType() const {
400 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
401 return CT->getElementType()->isFloatingType();
405 bool Type::isComplexIntegerType() const {
406 // Check for GCC complex integer extension.
407 return getAsComplexIntegerType();
410 const ComplexType *Type::getAsComplexIntegerType() const {
411 if (const ComplexType *Complex = getAs<ComplexType>())
412 if (Complex->getElementType()->isIntegerType())
417 QualType Type::getPointeeType() const {
418 if (const PointerType *PT = getAs<PointerType>())
419 return PT->getPointeeType();
420 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
421 return OPT->getPointeeType();
422 if (const BlockPointerType *BPT = getAs<BlockPointerType>())
423 return BPT->getPointeeType();
424 if (const ReferenceType *RT = getAs<ReferenceType>())
425 return RT->getPointeeType();
426 if (const MemberPointerType *MPT = getAs<MemberPointerType>())
427 return MPT->getPointeeType();
428 if (const DecayedType *DT = getAs<DecayedType>())
429 return DT->getPointeeType();
433 const RecordType *Type::getAsStructureType() const {
434 // If this is directly a structure type, return it.
435 if (const RecordType *RT = dyn_cast<RecordType>(this)) {
436 if (RT->getDecl()->isStruct())
440 // If the canonical form of this type isn't the right kind, reject it.
441 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
442 if (!RT->getDecl()->isStruct())
445 // If this is a typedef for a structure type, strip the typedef off without
446 // losing all typedef information.
447 return cast<RecordType>(getUnqualifiedDesugaredType());
452 const RecordType *Type::getAsUnionType() const {
453 // If this is directly a union type, return it.
454 if (const RecordType *RT = dyn_cast<RecordType>(this)) {
455 if (RT->getDecl()->isUnion())
459 // If the canonical form of this type isn't the right kind, reject it.
460 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
461 if (!RT->getDecl()->isUnion())
464 // If this is a typedef for a union type, strip the typedef off without
465 // losing all typedef information.
466 return cast<RecordType>(getUnqualifiedDesugaredType());
472 ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base,
473 ObjCProtocolDecl * const *Protocols,
474 unsigned NumProtocols)
475 : Type(ObjCObject, Canonical, false, false, false, false),
478 ObjCObjectTypeBits.NumProtocols = NumProtocols;
479 assert(getNumProtocols() == NumProtocols &&
480 "bitfield overflow in protocol count");
482 memcpy(getProtocolStorage(), Protocols,
483 NumProtocols * sizeof(ObjCProtocolDecl*));
486 const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const {
487 // There is no sugar for ObjCObjectType's, just return the canonical
488 // type pointer if it is the right class. There is no typedef information to
489 // return and these cannot be Address-space qualified.
490 if (const ObjCObjectType *T = getAs<ObjCObjectType>())
491 if (T->getNumProtocols() && T->getInterface())
496 bool Type::isObjCQualifiedInterfaceType() const {
497 return getAsObjCQualifiedInterfaceType() != nullptr;
500 const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
501 // There is no sugar for ObjCQualifiedIdType's, just return the canonical
502 // type pointer if it is the right class.
503 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
504 if (OPT->isObjCQualifiedIdType())
510 const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const {
511 // There is no sugar for ObjCQualifiedClassType's, just return the canonical
512 // type pointer if it is the right class.
513 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
514 if (OPT->isObjCQualifiedClassType())
520 const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
521 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
522 if (OPT->getInterfaceType())
528 const CXXRecordDecl *Type::getPointeeCXXRecordDecl() const {
529 QualType PointeeType;
530 if (const PointerType *PT = getAs<PointerType>())
531 PointeeType = PT->getPointeeType();
532 else if (const ReferenceType *RT = getAs<ReferenceType>())
533 PointeeType = RT->getPointeeType();
537 if (const RecordType *RT = PointeeType->getAs<RecordType>())
538 return dyn_cast<CXXRecordDecl>(RT->getDecl());
543 CXXRecordDecl *Type::getAsCXXRecordDecl() const {
544 return dyn_cast_or_null<CXXRecordDecl>(getAsTagDecl());
547 TagDecl *Type::getAsTagDecl() const {
548 if (const auto *TT = getAs<TagType>())
549 return cast<TagDecl>(TT->getDecl());
550 if (const auto *Injected = getAs<InjectedClassNameType>())
551 return Injected->getDecl();
557 class GetContainedAutoVisitor :
558 public TypeVisitor<GetContainedAutoVisitor, AutoType*> {
560 using TypeVisitor<GetContainedAutoVisitor, AutoType*>::Visit;
561 AutoType *Visit(QualType T) {
564 return Visit(T.getTypePtr());
567 // The 'auto' type itself.
568 AutoType *VisitAutoType(const AutoType *AT) {
569 return const_cast<AutoType*>(AT);
572 // Only these types can contain the desired 'auto' type.
573 AutoType *VisitPointerType(const PointerType *T) {
574 return Visit(T->getPointeeType());
576 AutoType *VisitBlockPointerType(const BlockPointerType *T) {
577 return Visit(T->getPointeeType());
579 AutoType *VisitReferenceType(const ReferenceType *T) {
580 return Visit(T->getPointeeTypeAsWritten());
582 AutoType *VisitMemberPointerType(const MemberPointerType *T) {
583 return Visit(T->getPointeeType());
585 AutoType *VisitArrayType(const ArrayType *T) {
586 return Visit(T->getElementType());
588 AutoType *VisitDependentSizedExtVectorType(
589 const DependentSizedExtVectorType *T) {
590 return Visit(T->getElementType());
592 AutoType *VisitVectorType(const VectorType *T) {
593 return Visit(T->getElementType());
595 AutoType *VisitFunctionType(const FunctionType *T) {
596 return Visit(T->getReturnType());
598 AutoType *VisitParenType(const ParenType *T) {
599 return Visit(T->getInnerType());
601 AutoType *VisitAttributedType(const AttributedType *T) {
602 return Visit(T->getModifiedType());
604 AutoType *VisitAdjustedType(const AdjustedType *T) {
605 return Visit(T->getOriginalType());
610 AutoType *Type::getContainedAutoType() const {
611 return GetContainedAutoVisitor().Visit(this);
614 bool Type::hasIntegerRepresentation() const {
615 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
616 return VT->getElementType()->isIntegerType();
618 return isIntegerType();
621 /// \brief Determine whether this type is an integral type.
623 /// This routine determines whether the given type is an integral type per
624 /// C++ [basic.fundamental]p7. Although the C standard does not define the
625 /// term "integral type", it has a similar term "integer type", and in C++
626 /// the two terms are equivalent. However, C's "integer type" includes
627 /// enumeration types, while C++'s "integer type" does not. The \c ASTContext
628 /// parameter is used to determine whether we should be following the C or
629 /// C++ rules when determining whether this type is an integral/integer type.
631 /// For cases where C permits "an integer type" and C++ permits "an integral
632 /// type", use this routine.
634 /// For cases where C permits "an integer type" and C++ permits "an integral
635 /// or enumeration type", use \c isIntegralOrEnumerationType() instead.
637 /// \param Ctx The context in which this type occurs.
639 /// \returns true if the type is considered an integral type, false otherwise.
640 bool Type::isIntegralType(ASTContext &Ctx) const {
641 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
642 return BT->getKind() >= BuiltinType::Bool &&
643 BT->getKind() <= BuiltinType::Int128;
645 if (!Ctx.getLangOpts().CPlusPlus)
646 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
647 return ET->getDecl()->isComplete(); // Complete enum types are integral in C.
653 bool Type::isIntegralOrUnscopedEnumerationType() const {
654 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
655 return BT->getKind() >= BuiltinType::Bool &&
656 BT->getKind() <= BuiltinType::Int128;
658 // Check for a complete enum type; incomplete enum types are not properly an
659 // enumeration type in the sense required here.
660 // C++0x: However, if the underlying type of the enum is fixed, it is
661 // considered complete.
662 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
663 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
670 bool Type::isCharType() const {
671 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
672 return BT->getKind() == BuiltinType::Char_U ||
673 BT->getKind() == BuiltinType::UChar ||
674 BT->getKind() == BuiltinType::Char_S ||
675 BT->getKind() == BuiltinType::SChar;
679 bool Type::isWideCharType() const {
680 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
681 return BT->getKind() == BuiltinType::WChar_S ||
682 BT->getKind() == BuiltinType::WChar_U;
686 bool Type::isChar16Type() const {
687 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
688 return BT->getKind() == BuiltinType::Char16;
692 bool Type::isChar32Type() const {
693 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
694 return BT->getKind() == BuiltinType::Char32;
698 /// \brief Determine whether this type is any of the built-in character
700 bool Type::isAnyCharacterType() const {
701 const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType);
702 if (!BT) return false;
703 switch (BT->getKind()) {
704 default: return false;
705 case BuiltinType::Char_U:
706 case BuiltinType::UChar:
707 case BuiltinType::WChar_U:
708 case BuiltinType::Char16:
709 case BuiltinType::Char32:
710 case BuiltinType::Char_S:
711 case BuiltinType::SChar:
712 case BuiltinType::WChar_S:
717 /// isSignedIntegerType - Return true if this is an integer type that is
718 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
719 /// an enum decl which has a signed representation
720 bool Type::isSignedIntegerType() const {
721 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
722 return BT->getKind() >= BuiltinType::Char_S &&
723 BT->getKind() <= BuiltinType::Int128;
726 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
727 // Incomplete enum types are not treated as integer types.
728 // FIXME: In C++, enum types are never integer types.
729 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
730 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
736 bool Type::isSignedIntegerOrEnumerationType() const {
737 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
738 return BT->getKind() >= BuiltinType::Char_S &&
739 BT->getKind() <= BuiltinType::Int128;
742 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
743 if (ET->getDecl()->isComplete())
744 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
750 bool Type::hasSignedIntegerRepresentation() const {
751 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
752 return VT->getElementType()->isSignedIntegerOrEnumerationType();
754 return isSignedIntegerOrEnumerationType();
757 /// isUnsignedIntegerType - Return true if this is an integer type that is
758 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
759 /// decl which has an unsigned representation
760 bool Type::isUnsignedIntegerType() const {
761 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
762 return BT->getKind() >= BuiltinType::Bool &&
763 BT->getKind() <= BuiltinType::UInt128;
766 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
767 // Incomplete enum types are not treated as integer types.
768 // FIXME: In C++, enum types are never integer types.
769 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
770 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
776 bool Type::isUnsignedIntegerOrEnumerationType() const {
777 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
778 return BT->getKind() >= BuiltinType::Bool &&
779 BT->getKind() <= BuiltinType::UInt128;
782 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
783 if (ET->getDecl()->isComplete())
784 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
790 bool Type::hasUnsignedIntegerRepresentation() const {
791 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
792 return VT->getElementType()->isUnsignedIntegerOrEnumerationType();
794 return isUnsignedIntegerOrEnumerationType();
797 bool Type::isFloatingType() const {
798 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
799 return BT->getKind() >= BuiltinType::Half &&
800 BT->getKind() <= BuiltinType::LongDouble;
801 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
802 return CT->getElementType()->isFloatingType();
806 bool Type::hasFloatingRepresentation() const {
807 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
808 return VT->getElementType()->isFloatingType();
810 return isFloatingType();
813 bool Type::isRealFloatingType() const {
814 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
815 return BT->isFloatingPoint();
819 bool Type::isRealType() const {
820 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
821 return BT->getKind() >= BuiltinType::Bool &&
822 BT->getKind() <= BuiltinType::LongDouble;
823 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
824 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
828 bool Type::isArithmeticType() const {
829 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
830 return BT->getKind() >= BuiltinType::Bool &&
831 BT->getKind() <= BuiltinType::LongDouble;
832 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
833 // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
834 // If a body isn't seen by the time we get here, return false.
836 // C++0x: Enumerations are not arithmetic types. For now, just return
837 // false for scoped enumerations since that will disable any
838 // unwanted implicit conversions.
839 return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete();
840 return isa<ComplexType>(CanonicalType);
843 Type::ScalarTypeKind Type::getScalarTypeKind() const {
844 assert(isScalarType());
846 const Type *T = CanonicalType.getTypePtr();
847 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) {
848 if (BT->getKind() == BuiltinType::Bool) return STK_Bool;
849 if (BT->getKind() == BuiltinType::NullPtr) return STK_CPointer;
850 if (BT->isInteger()) return STK_Integral;
851 if (BT->isFloatingPoint()) return STK_Floating;
852 llvm_unreachable("unknown scalar builtin type");
853 } else if (isa<PointerType>(T)) {
855 } else if (isa<BlockPointerType>(T)) {
856 return STK_BlockPointer;
857 } else if (isa<ObjCObjectPointerType>(T)) {
858 return STK_ObjCObjectPointer;
859 } else if (isa<MemberPointerType>(T)) {
860 return STK_MemberPointer;
861 } else if (isa<EnumType>(T)) {
862 assert(cast<EnumType>(T)->getDecl()->isComplete());
864 } else if (const ComplexType *CT = dyn_cast<ComplexType>(T)) {
865 if (CT->getElementType()->isRealFloatingType())
866 return STK_FloatingComplex;
867 return STK_IntegralComplex;
870 llvm_unreachable("unknown scalar type");
873 /// \brief Determines whether the type is a C++ aggregate type or C
874 /// aggregate or union type.
876 /// An aggregate type is an array or a class type (struct, union, or
877 /// class) that has no user-declared constructors, no private or
878 /// protected non-static data members, no base classes, and no virtual
879 /// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
880 /// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
881 /// includes union types.
882 bool Type::isAggregateType() const {
883 if (const RecordType *Record = dyn_cast<RecordType>(CanonicalType)) {
884 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
885 return ClassDecl->isAggregate();
890 return isa<ArrayType>(CanonicalType);
893 /// isConstantSizeType - Return true if this is not a variable sized type,
894 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
895 /// incomplete types or dependent types.
896 bool Type::isConstantSizeType() const {
897 assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
898 assert(!isDependentType() && "This doesn't make sense for dependent types");
899 // The VAT must have a size, as it is known to be complete.
900 return !isa<VariableArrayType>(CanonicalType);
903 /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
904 /// - a type that can describe objects, but which lacks information needed to
905 /// determine its size.
906 bool Type::isIncompleteType(NamedDecl **Def) const {
910 switch (CanonicalType->getTypeClass()) {
911 default: return false;
913 // Void is the only incomplete builtin type. Per C99 6.2.5p19, it can never
917 EnumDecl *EnumD = cast<EnumType>(CanonicalType)->getDecl();
921 // An enumeration with fixed underlying type is complete (C++0x 7.2p3).
922 if (EnumD->isFixed())
925 return !EnumD->isCompleteDefinition();
928 // A tagged type (struct/union/enum/class) is incomplete if the decl is a
929 // forward declaration, but not a full definition (C99 6.2.5p22).
930 RecordDecl *Rec = cast<RecordType>(CanonicalType)->getDecl();
933 return !Rec->isCompleteDefinition();
936 // An array is incomplete if its element type is incomplete
937 // (C++ [dcl.array]p1).
938 // We don't handle variable arrays (they're not allowed in C++) or
939 // dependent-sized arrays (dependent types are never treated as incomplete).
940 return cast<ArrayType>(CanonicalType)->getElementType()
941 ->isIncompleteType(Def);
942 case IncompleteArray:
943 // An array of unknown size is an incomplete type (C99 6.2.5p22).
946 return cast<ObjCObjectType>(CanonicalType)->getBaseType()
947 ->isIncompleteType(Def);
948 case ObjCInterface: {
949 // ObjC interfaces are incomplete if they are @class, not @interface.
950 ObjCInterfaceDecl *Interface
951 = cast<ObjCInterfaceType>(CanonicalType)->getDecl();
954 return !Interface->hasDefinition();
959 bool QualType::isPODType(ASTContext &Context) const {
960 // C++11 has a more relaxed definition of POD.
961 if (Context.getLangOpts().CPlusPlus11)
962 return isCXX11PODType(Context);
964 return isCXX98PODType(Context);
967 bool QualType::isCXX98PODType(ASTContext &Context) const {
968 // The compiler shouldn't query this for incomplete types, but the user might.
969 // We return false for that case. Except for incomplete arrays of PODs, which
970 // are PODs according to the standard.
974 if ((*this)->isIncompleteArrayType())
975 return Context.getBaseElementType(*this).isCXX98PODType(Context);
977 if ((*this)->isIncompleteType())
980 if (Context.getLangOpts().ObjCAutoRefCount) {
981 switch (getObjCLifetime()) {
982 case Qualifiers::OCL_ExplicitNone:
985 case Qualifiers::OCL_Strong:
986 case Qualifiers::OCL_Weak:
987 case Qualifiers::OCL_Autoreleasing:
990 case Qualifiers::OCL_None:
995 QualType CanonicalType = getTypePtr()->CanonicalType;
996 switch (CanonicalType->getTypeClass()) {
997 // Everything not explicitly mentioned is not POD.
998 default: return false;
999 case Type::VariableArray:
1000 case Type::ConstantArray:
1001 // IncompleteArray is handled above.
1002 return Context.getBaseElementType(*this).isCXX98PODType(Context);
1004 case Type::ObjCObjectPointer:
1005 case Type::BlockPointer:
1009 case Type::MemberPointer:
1011 case Type::ExtVector:
1018 if (CXXRecordDecl *ClassDecl
1019 = dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
1020 return ClassDecl->isPOD();
1022 // C struct/union is POD.
1027 bool QualType::isTrivialType(ASTContext &Context) const {
1028 // The compiler shouldn't query this for incomplete types, but the user might.
1029 // We return false for that case. Except for incomplete arrays of PODs, which
1030 // are PODs according to the standard.
1034 if ((*this)->isArrayType())
1035 return Context.getBaseElementType(*this).isTrivialType(Context);
1037 // Return false for incomplete types after skipping any incomplete array
1038 // types which are expressly allowed by the standard and thus our API.
1039 if ((*this)->isIncompleteType())
1042 if (Context.getLangOpts().ObjCAutoRefCount) {
1043 switch (getObjCLifetime()) {
1044 case Qualifiers::OCL_ExplicitNone:
1047 case Qualifiers::OCL_Strong:
1048 case Qualifiers::OCL_Weak:
1049 case Qualifiers::OCL_Autoreleasing:
1052 case Qualifiers::OCL_None:
1053 if ((*this)->isObjCLifetimeType())
1059 QualType CanonicalType = getTypePtr()->CanonicalType;
1060 if (CanonicalType->isDependentType())
1063 // C++0x [basic.types]p9:
1064 // Scalar types, trivial class types, arrays of such types, and
1065 // cv-qualified versions of these types are collectively called trivial
1068 // As an extension, Clang treats vector types as Scalar types.
1069 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
1071 if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
1072 if (const CXXRecordDecl *ClassDecl =
1073 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1075 // A trivial class is a class that has a default constructor,
1076 // has no non-trivial default constructors, and is trivially
1078 return ClassDecl->hasDefaultConstructor() &&
1079 !ClassDecl->hasNonTrivialDefaultConstructor() &&
1080 ClassDecl->isTriviallyCopyable();
1086 // No other types can match.
1090 bool QualType::isTriviallyCopyableType(ASTContext &Context) const {
1091 if ((*this)->isArrayType())
1092 return Context.getBaseElementType(*this).isTrivialType(Context);
1094 if (Context.getLangOpts().ObjCAutoRefCount) {
1095 switch (getObjCLifetime()) {
1096 case Qualifiers::OCL_ExplicitNone:
1099 case Qualifiers::OCL_Strong:
1100 case Qualifiers::OCL_Weak:
1101 case Qualifiers::OCL_Autoreleasing:
1104 case Qualifiers::OCL_None:
1105 if ((*this)->isObjCLifetimeType())
1111 // C++11 [basic.types]p9
1112 // Scalar types, trivially copyable class types, arrays of such types, and
1113 // non-volatile const-qualified versions of these types are collectively
1114 // called trivially copyable types.
1116 QualType CanonicalType = getCanonicalType();
1117 if (CanonicalType->isDependentType())
1120 if (CanonicalType.isVolatileQualified())
1123 // Return false for incomplete types after skipping any incomplete array types
1124 // which are expressly allowed by the standard and thus our API.
1125 if (CanonicalType->isIncompleteType())
1128 // As an extension, Clang treats vector types as Scalar types.
1129 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
1132 if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
1133 if (const CXXRecordDecl *ClassDecl =
1134 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1135 if (!ClassDecl->isTriviallyCopyable()) return false;
1141 // No other types can match.
1147 bool Type::isLiteralType(const ASTContext &Ctx) const {
1148 if (isDependentType())
1151 // C++1y [basic.types]p10:
1152 // A type is a literal type if it is:
1154 if (Ctx.getLangOpts().CPlusPlus14 && isVoidType())
1157 // C++11 [basic.types]p10:
1158 // A type is a literal type if it is:
1160 // -- an array of literal type other than an array of runtime bound; or
1161 if (isVariableArrayType())
1163 const Type *BaseTy = getBaseElementTypeUnsafe();
1164 assert(BaseTy && "NULL element type");
1166 // Return false for incomplete types after skipping any incomplete array
1167 // types; those are expressly allowed by the standard and thus our API.
1168 if (BaseTy->isIncompleteType())
1171 // C++11 [basic.types]p10:
1172 // A type is a literal type if it is:
1173 // -- a scalar type; or
1174 // As an extension, Clang treats vector types and complex types as
1176 if (BaseTy->isScalarType() || BaseTy->isVectorType() ||
1177 BaseTy->isAnyComplexType())
1179 // -- a reference type; or
1180 if (BaseTy->isReferenceType())
1182 // -- a class type that has all of the following properties:
1183 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1184 // -- a trivial destructor,
1185 // -- every constructor call and full-expression in the
1186 // brace-or-equal-initializers for non-static data members (if any)
1187 // is a constant expression,
1188 // -- it is an aggregate type or has at least one constexpr
1189 // constructor or constructor template that is not a copy or move
1191 // -- all non-static data members and base classes of literal types
1193 // We resolve DR1361 by ignoring the second bullet.
1194 if (const CXXRecordDecl *ClassDecl =
1195 dyn_cast<CXXRecordDecl>(RT->getDecl()))
1196 return ClassDecl->isLiteral();
1201 // We treat _Atomic T as a literal type if T is a literal type.
1202 if (const AtomicType *AT = BaseTy->getAs<AtomicType>())
1203 return AT->getValueType()->isLiteralType(Ctx);
1205 // If this type hasn't been deduced yet, then conservatively assume that
1206 // it'll work out to be a literal type.
1207 if (isa<AutoType>(BaseTy->getCanonicalTypeInternal()))
1213 bool Type::isStandardLayoutType() const {
1214 if (isDependentType())
1217 // C++0x [basic.types]p9:
1218 // Scalar types, standard-layout class types, arrays of such types, and
1219 // cv-qualified versions of these types are collectively called
1220 // standard-layout types.
1221 const Type *BaseTy = getBaseElementTypeUnsafe();
1222 assert(BaseTy && "NULL element type");
1224 // Return false for incomplete types after skipping any incomplete array
1225 // types which are expressly allowed by the standard and thus our API.
1226 if (BaseTy->isIncompleteType())
1229 // As an extension, Clang treats vector types as Scalar types.
1230 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
1231 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1232 if (const CXXRecordDecl *ClassDecl =
1233 dyn_cast<CXXRecordDecl>(RT->getDecl()))
1234 if (!ClassDecl->isStandardLayout())
1237 // Default to 'true' for non-C++ class types.
1238 // FIXME: This is a bit dubious, but plain C structs should trivially meet
1239 // all the requirements of standard layout classes.
1243 // No other types can match.
1247 // This is effectively the intersection of isTrivialType and
1248 // isStandardLayoutType. We implement it directly to avoid redundant
1249 // conversions from a type to a CXXRecordDecl.
1250 bool QualType::isCXX11PODType(ASTContext &Context) const {
1251 const Type *ty = getTypePtr();
1252 if (ty->isDependentType())
1255 if (Context.getLangOpts().ObjCAutoRefCount) {
1256 switch (getObjCLifetime()) {
1257 case Qualifiers::OCL_ExplicitNone:
1260 case Qualifiers::OCL_Strong:
1261 case Qualifiers::OCL_Weak:
1262 case Qualifiers::OCL_Autoreleasing:
1265 case Qualifiers::OCL_None:
1270 // C++11 [basic.types]p9:
1271 // Scalar types, POD classes, arrays of such types, and cv-qualified
1272 // versions of these types are collectively called trivial types.
1273 const Type *BaseTy = ty->getBaseElementTypeUnsafe();
1274 assert(BaseTy && "NULL element type");
1276 // Return false for incomplete types after skipping any incomplete array
1277 // types which are expressly allowed by the standard and thus our API.
1278 if (BaseTy->isIncompleteType())
1281 // As an extension, Clang treats vector types as Scalar types.
1282 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
1283 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1284 if (const CXXRecordDecl *ClassDecl =
1285 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1286 // C++11 [class]p10:
1287 // A POD struct is a non-union class that is both a trivial class [...]
1288 if (!ClassDecl->isTrivial()) return false;
1290 // C++11 [class]p10:
1291 // A POD struct is a non-union class that is both a trivial class and
1292 // a standard-layout class [...]
1293 if (!ClassDecl->isStandardLayout()) return false;
1295 // C++11 [class]p10:
1296 // A POD struct is a non-union class that is both a trivial class and
1297 // a standard-layout class, and has no non-static data members of type
1298 // non-POD struct, non-POD union (or array of such types). [...]
1300 // We don't directly query the recursive aspect as the requiremets for
1301 // both standard-layout classes and trivial classes apply recursively
1308 // No other types can match.
1312 bool Type::isPromotableIntegerType() const {
1313 if (const BuiltinType *BT = getAs<BuiltinType>())
1314 switch (BT->getKind()) {
1315 case BuiltinType::Bool:
1316 case BuiltinType::Char_S:
1317 case BuiltinType::Char_U:
1318 case BuiltinType::SChar:
1319 case BuiltinType::UChar:
1320 case BuiltinType::Short:
1321 case BuiltinType::UShort:
1322 case BuiltinType::WChar_S:
1323 case BuiltinType::WChar_U:
1324 case BuiltinType::Char16:
1325 case BuiltinType::Char32:
1331 // Enumerated types are promotable to their compatible integer types
1332 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1333 if (const EnumType *ET = getAs<EnumType>()){
1334 if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull()
1335 || ET->getDecl()->isScoped())
1344 bool Type::isSpecifierType() const {
1345 // Note that this intentionally does not use the canonical type.
1346 switch (getTypeClass()) {
1354 case TemplateTypeParm:
1355 case SubstTemplateTypeParm:
1356 case TemplateSpecialization:
1359 case DependentTemplateSpecialization:
1362 case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers
1369 ElaboratedTypeKeyword
1370 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) {
1372 default: return ETK_None;
1373 case TST_typename: return ETK_Typename;
1374 case TST_class: return ETK_Class;
1375 case TST_struct: return ETK_Struct;
1376 case TST_interface: return ETK_Interface;
1377 case TST_union: return ETK_Union;
1378 case TST_enum: return ETK_Enum;
1383 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
1385 case TST_class: return TTK_Class;
1386 case TST_struct: return TTK_Struct;
1387 case TST_interface: return TTK_Interface;
1388 case TST_union: return TTK_Union;
1389 case TST_enum: return TTK_Enum;
1392 llvm_unreachable("Type specifier is not a tag type kind.");
1395 ElaboratedTypeKeyword
1396 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) {
1398 case TTK_Class: return ETK_Class;
1399 case TTK_Struct: return ETK_Struct;
1400 case TTK_Interface: return ETK_Interface;
1401 case TTK_Union: return ETK_Union;
1402 case TTK_Enum: return ETK_Enum;
1404 llvm_unreachable("Unknown tag type kind.");
1408 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
1410 case ETK_Class: return TTK_Class;
1411 case ETK_Struct: return TTK_Struct;
1412 case ETK_Interface: return TTK_Interface;
1413 case ETK_Union: return TTK_Union;
1414 case ETK_Enum: return TTK_Enum;
1415 case ETK_None: // Fall through.
1417 llvm_unreachable("Elaborated type keyword is not a tag type kind.");
1419 llvm_unreachable("Unknown elaborated type keyword.");
1423 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
1435 llvm_unreachable("Unknown elaborated type keyword.");
1438 StringRef TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) {
1440 case ETK_None: return "";
1441 case ETK_Typename: return "typename";
1442 case ETK_Class: return "class";
1443 case ETK_Struct: return "struct";
1444 case ETK_Interface: return "__interface";
1445 case ETK_Union: return "union";
1446 case ETK_Enum: return "enum";
1449 llvm_unreachable("Unknown elaborated type keyword.");
1452 DependentTemplateSpecializationType::DependentTemplateSpecializationType(
1453 ElaboratedTypeKeyword Keyword,
1454 NestedNameSpecifier *NNS, const IdentifierInfo *Name,
1455 unsigned NumArgs, const TemplateArgument *Args,
1457 : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true, true,
1458 /*VariablyModified=*/false,
1459 NNS && NNS->containsUnexpandedParameterPack()),
1460 NNS(NNS), Name(Name), NumArgs(NumArgs) {
1461 assert((!NNS || NNS->isDependent()) &&
1462 "DependentTemplateSpecializatonType requires dependent qualifier");
1463 for (unsigned I = 0; I != NumArgs; ++I) {
1464 if (Args[I].containsUnexpandedParameterPack())
1465 setContainsUnexpandedParameterPack();
1467 new (&getArgBuffer()[I]) TemplateArgument(Args[I]);
1472 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1473 const ASTContext &Context,
1474 ElaboratedTypeKeyword Keyword,
1475 NestedNameSpecifier *Qualifier,
1476 const IdentifierInfo *Name,
1478 const TemplateArgument *Args) {
1479 ID.AddInteger(Keyword);
1480 ID.AddPointer(Qualifier);
1481 ID.AddPointer(Name);
1482 for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1483 Args[Idx].Profile(ID, Context);
1486 bool Type::isElaboratedTypeSpecifier() const {
1487 ElaboratedTypeKeyword Keyword;
1488 if (const ElaboratedType *Elab = dyn_cast<ElaboratedType>(this))
1489 Keyword = Elab->getKeyword();
1490 else if (const DependentNameType *DepName = dyn_cast<DependentNameType>(this))
1491 Keyword = DepName->getKeyword();
1492 else if (const DependentTemplateSpecializationType *DepTST =
1493 dyn_cast<DependentTemplateSpecializationType>(this))
1494 Keyword = DepTST->getKeyword();
1498 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
1501 const char *Type::getTypeClassName() const {
1502 switch (TypeBits.TC) {
1503 #define ABSTRACT_TYPE(Derived, Base)
1504 #define TYPE(Derived, Base) case Derived: return #Derived;
1505 #include "clang/AST/TypeNodes.def"
1508 llvm_unreachable("Invalid type class.");
1511 StringRef BuiltinType::getName(const PrintingPolicy &Policy) const {
1512 switch (getKind()) {
1513 case Void: return "void";
1514 case Bool: return Policy.Bool ? "bool" : "_Bool";
1515 case Char_S: return "char";
1516 case Char_U: return "char";
1517 case SChar: return "signed char";
1518 case Short: return "short";
1519 case Int: return "int";
1520 case Long: return "long";
1521 case LongLong: return "long long";
1522 case Int128: return "__int128";
1523 case UChar: return "unsigned char";
1524 case UShort: return "unsigned short";
1525 case UInt: return "unsigned int";
1526 case ULong: return "unsigned long";
1527 case ULongLong: return "unsigned long long";
1528 case UInt128: return "unsigned __int128";
1529 case Half: return Policy.Half ? "half" : "__fp16";
1530 case Float: return "float";
1531 case Double: return "double";
1532 case LongDouble: return "long double";
1534 case WChar_U: return Policy.MSWChar ? "__wchar_t" : "wchar_t";
1535 case Char16: return "char16_t";
1536 case Char32: return "char32_t";
1537 case NullPtr: return "nullptr_t";
1538 case Overload: return "<overloaded function type>";
1539 case BoundMember: return "<bound member function type>";
1540 case PseudoObject: return "<pseudo-object type>";
1541 case Dependent: return "<dependent type>";
1542 case UnknownAny: return "<unknown type>";
1543 case ARCUnbridgedCast: return "<ARC unbridged cast type>";
1544 case BuiltinFn: return "<builtin fn type>";
1545 case ObjCId: return "id";
1546 case ObjCClass: return "Class";
1547 case ObjCSel: return "SEL";
1548 case OCLImage1d: return "image1d_t";
1549 case OCLImage1dArray: return "image1d_array_t";
1550 case OCLImage1dBuffer: return "image1d_buffer_t";
1551 case OCLImage2d: return "image2d_t";
1552 case OCLImage2dArray: return "image2d_array_t";
1553 case OCLImage3d: return "image3d_t";
1554 case OCLSampler: return "sampler_t";
1555 case OCLEvent: return "event_t";
1558 llvm_unreachable("Invalid builtin type.");
1561 QualType QualType::getNonLValueExprType(const ASTContext &Context) const {
1562 if (const ReferenceType *RefType = getTypePtr()->getAs<ReferenceType>())
1563 return RefType->getPointeeType();
1565 // C++0x [basic.lval]:
1566 // Class prvalues can have cv-qualified types; non-class prvalues always
1567 // have cv-unqualified types.
1569 // See also C99 6.3.2.1p2.
1570 if (!Context.getLangOpts().CPlusPlus ||
1571 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
1572 return getUnqualifiedType();
1577 StringRef FunctionType::getNameForCallConv(CallingConv CC) {
1579 case CC_C: return "cdecl";
1580 case CC_X86StdCall: return "stdcall";
1581 case CC_X86FastCall: return "fastcall";
1582 case CC_X86ThisCall: return "thiscall";
1583 case CC_X86Pascal: return "pascal";
1584 case CC_X86VectorCall: return "vectorcall";
1585 case CC_X86_64Win64: return "ms_abi";
1586 case CC_X86_64SysV: return "sysv_abi";
1587 case CC_AAPCS: return "aapcs";
1588 case CC_AAPCS_VFP: return "aapcs-vfp";
1589 case CC_PnaclCall: return "pnaclcall";
1590 case CC_IntelOclBicc: return "intel_ocl_bicc";
1593 llvm_unreachable("Invalid calling convention.");
1596 FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> params,
1598 const ExtProtoInfo &epi)
1599 : FunctionType(FunctionProto, result, canonical,
1600 result->isDependentType(),
1601 result->isInstantiationDependentType(),
1602 result->isVariablyModifiedType(),
1603 result->containsUnexpandedParameterPack(), epi.ExtInfo),
1604 NumParams(params.size()),
1605 NumExceptions(epi.ExceptionSpec.Exceptions.size()),
1606 ExceptionSpecType(epi.ExceptionSpec.Type),
1607 HasAnyConsumedParams(epi.ConsumedParameters != nullptr),
1608 Variadic(epi.Variadic), HasTrailingReturn(epi.HasTrailingReturn) {
1609 assert(NumParams == params.size() && "function has too many parameters");
1611 FunctionTypeBits.TypeQuals = epi.TypeQuals;
1612 FunctionTypeBits.RefQualifier = epi.RefQualifier;
1614 // Fill in the trailing argument array.
1615 QualType *argSlot = reinterpret_cast<QualType*>(this+1);
1616 for (unsigned i = 0; i != NumParams; ++i) {
1617 if (params[i]->isDependentType())
1619 else if (params[i]->isInstantiationDependentType())
1620 setInstantiationDependent();
1622 if (params[i]->containsUnexpandedParameterPack())
1623 setContainsUnexpandedParameterPack();
1625 argSlot[i] = params[i];
1628 if (getExceptionSpecType() == EST_Dynamic) {
1629 // Fill in the exception array.
1630 QualType *exnSlot = argSlot + NumParams;
1632 for (QualType ExceptionType : epi.ExceptionSpec.Exceptions) {
1633 // Note that a dependent exception specification does *not* make
1634 // a type dependent; it's not even part of the C++ type system.
1635 if (ExceptionType->isInstantiationDependentType())
1636 setInstantiationDependent();
1638 if (ExceptionType->containsUnexpandedParameterPack())
1639 setContainsUnexpandedParameterPack();
1641 exnSlot[I++] = ExceptionType;
1643 } else if (getExceptionSpecType() == EST_ComputedNoexcept) {
1644 // Store the noexcept expression and context.
1645 Expr **noexSlot = reinterpret_cast<Expr **>(argSlot + NumParams);
1646 *noexSlot = epi.ExceptionSpec.NoexceptExpr;
1648 if (epi.ExceptionSpec.NoexceptExpr) {
1649 if (epi.ExceptionSpec.NoexceptExpr->isValueDependent() ||
1650 epi.ExceptionSpec.NoexceptExpr->isInstantiationDependent())
1651 setInstantiationDependent();
1653 if (epi.ExceptionSpec.NoexceptExpr->containsUnexpandedParameterPack())
1654 setContainsUnexpandedParameterPack();
1656 } else if (getExceptionSpecType() == EST_Uninstantiated) {
1657 // Store the function decl from which we will resolve our
1658 // exception specification.
1659 FunctionDecl **slot =
1660 reinterpret_cast<FunctionDecl **>(argSlot + NumParams);
1661 slot[0] = epi.ExceptionSpec.SourceDecl;
1662 slot[1] = epi.ExceptionSpec.SourceTemplate;
1663 // This exception specification doesn't make the type dependent, because
1664 // it's not instantiated as part of instantiating the type.
1665 } else if (getExceptionSpecType() == EST_Unevaluated) {
1666 // Store the function decl from which we will resolve our
1667 // exception specification.
1668 FunctionDecl **slot =
1669 reinterpret_cast<FunctionDecl **>(argSlot + NumParams);
1670 slot[0] = epi.ExceptionSpec.SourceDecl;
1673 if (epi.ConsumedParameters) {
1674 bool *consumedParams = const_cast<bool *>(getConsumedParamsBuffer());
1675 for (unsigned i = 0; i != NumParams; ++i)
1676 consumedParams[i] = epi.ConsumedParameters[i];
1680 bool FunctionProtoType::hasDependentExceptionSpec() const {
1681 if (Expr *NE = getNoexceptExpr())
1682 return NE->isValueDependent();
1683 for (QualType ET : exceptions())
1684 // A pack expansion with a non-dependent pattern is still dependent,
1685 // because we don't know whether the pattern is in the exception spec
1686 // or not (that depends on whether the pack has 0 expansions).
1687 if (ET->isDependentType() || ET->getAs<PackExpansionType>())
1692 FunctionProtoType::NoexceptResult
1693 FunctionProtoType::getNoexceptSpec(const ASTContext &ctx) const {
1694 ExceptionSpecificationType est = getExceptionSpecType();
1695 if (est == EST_BasicNoexcept)
1698 if (est != EST_ComputedNoexcept)
1699 return NR_NoNoexcept;
1701 Expr *noexceptExpr = getNoexceptExpr();
1703 return NR_BadNoexcept;
1704 if (noexceptExpr->isValueDependent())
1705 return NR_Dependent;
1708 bool isICE = noexceptExpr->isIntegerConstantExpr(value, ctx, nullptr,
1709 /*evaluated*/false);
1711 assert(isICE && "AST should not contain bad noexcept expressions.");
1713 return value.getBoolValue() ? NR_Nothrow : NR_Throw;
1716 bool FunctionProtoType::isNothrow(const ASTContext &Ctx,
1717 bool ResultIfDependent) const {
1718 ExceptionSpecificationType EST = getExceptionSpecType();
1719 assert(EST != EST_Unevaluated && EST != EST_Uninstantiated);
1720 if (EST == EST_DynamicNone || EST == EST_BasicNoexcept)
1723 if (EST == EST_Dynamic && ResultIfDependent == true) {
1724 // A dynamic exception specification is throwing unless every exception
1725 // type is an (unexpanded) pack expansion type.
1726 for (unsigned I = 0, N = NumExceptions; I != N; ++I)
1727 if (!getExceptionType(I)->getAs<PackExpansionType>())
1729 return ResultIfDependent;
1732 if (EST != EST_ComputedNoexcept)
1735 NoexceptResult NR = getNoexceptSpec(Ctx);
1736 if (NR == NR_Dependent)
1737 return ResultIfDependent;
1738 return NR == NR_Nothrow;
1741 bool FunctionProtoType::isTemplateVariadic() const {
1742 for (unsigned ArgIdx = getNumParams(); ArgIdx; --ArgIdx)
1743 if (isa<PackExpansionType>(getParamType(ArgIdx - 1)))
1749 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
1750 const QualType *ArgTys, unsigned NumParams,
1751 const ExtProtoInfo &epi,
1752 const ASTContext &Context) {
1754 // We have to be careful not to get ambiguous profile encodings.
1755 // Note that valid type pointers are never ambiguous with anything else.
1757 // The encoding grammar begins:
1758 // type type* bool int bool
1759 // If that final bool is true, then there is a section for the EH spec:
1761 // This is followed by an optional "consumed argument" section of the
1762 // same length as the first type sequence:
1764 // Finally, we have the ext info and trailing return type flag:
1767 // There is no ambiguity between the consumed arguments and an empty EH
1768 // spec because of the leading 'bool' which unambiguously indicates
1769 // whether the following bool is the EH spec or part of the arguments.
1771 ID.AddPointer(Result.getAsOpaquePtr());
1772 for (unsigned i = 0; i != NumParams; ++i)
1773 ID.AddPointer(ArgTys[i].getAsOpaquePtr());
1774 // This method is relatively performance sensitive, so as a performance
1775 // shortcut, use one AddInteger call instead of four for the next four
1777 assert(!(unsigned(epi.Variadic) & ~1) &&
1778 !(unsigned(epi.TypeQuals) & ~255) &&
1779 !(unsigned(epi.RefQualifier) & ~3) &&
1780 !(unsigned(epi.ExceptionSpec.Type) & ~15) &&
1781 "Values larger than expected.");
1782 ID.AddInteger(unsigned(epi.Variadic) +
1783 (epi.TypeQuals << 1) +
1784 (epi.RefQualifier << 9) +
1785 (epi.ExceptionSpec.Type << 11));
1786 if (epi.ExceptionSpec.Type == EST_Dynamic) {
1787 for (QualType Ex : epi.ExceptionSpec.Exceptions)
1788 ID.AddPointer(Ex.getAsOpaquePtr());
1789 } else if (epi.ExceptionSpec.Type == EST_ComputedNoexcept &&
1790 epi.ExceptionSpec.NoexceptExpr) {
1791 epi.ExceptionSpec.NoexceptExpr->Profile(ID, Context, false);
1792 } else if (epi.ExceptionSpec.Type == EST_Uninstantiated ||
1793 epi.ExceptionSpec.Type == EST_Unevaluated) {
1794 ID.AddPointer(epi.ExceptionSpec.SourceDecl->getCanonicalDecl());
1796 if (epi.ConsumedParameters) {
1797 for (unsigned i = 0; i != NumParams; ++i)
1798 ID.AddBoolean(epi.ConsumedParameters[i]);
1800 epi.ExtInfo.Profile(ID);
1801 ID.AddBoolean(epi.HasTrailingReturn);
1804 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
1805 const ASTContext &Ctx) {
1806 Profile(ID, getReturnType(), param_type_begin(), NumParams, getExtProtoInfo(),
1810 QualType TypedefType::desugar() const {
1811 return getDecl()->getUnderlyingType();
1814 TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
1815 : Type(TypeOfExpr, can, E->isTypeDependent(),
1816 E->isInstantiationDependent(),
1817 E->getType()->isVariablyModifiedType(),
1818 E->containsUnexpandedParameterPack()),
1822 bool TypeOfExprType::isSugared() const {
1823 return !TOExpr->isTypeDependent();
1826 QualType TypeOfExprType::desugar() const {
1828 return getUnderlyingExpr()->getType();
1830 return QualType(this, 0);
1833 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
1834 const ASTContext &Context, Expr *E) {
1835 E->Profile(ID, Context, true);
1838 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
1839 // C++11 [temp.type]p2: "If an expression e involves a template parameter,
1840 // decltype(e) denotes a unique dependent type." Hence a decltype type is
1841 // type-dependent even if its expression is only instantiation-dependent.
1842 : Type(Decltype, can, E->isInstantiationDependent(),
1843 E->isInstantiationDependent(),
1844 E->getType()->isVariablyModifiedType(),
1845 E->containsUnexpandedParameterPack()),
1847 UnderlyingType(underlyingType) {
1850 bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); }
1852 QualType DecltypeType::desugar() const {
1854 return getUnderlyingType();
1856 return QualType(this, 0);
1859 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E)
1860 : DecltypeType(E, Context.DependentTy), Context(Context) { }
1862 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
1863 const ASTContext &Context, Expr *E) {
1864 E->Profile(ID, Context, true);
1867 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
1868 : Type(TC, can, D->isDependentType(),
1869 /*InstantiationDependent=*/D->isDependentType(),
1870 /*VariablyModified=*/false,
1871 /*ContainsUnexpandedParameterPack=*/false),
1872 decl(const_cast<TagDecl*>(D)) {}
1874 static TagDecl *getInterestingTagDecl(TagDecl *decl) {
1875 for (auto I : decl->redecls()) {
1876 if (I->isCompleteDefinition() || I->isBeingDefined())
1879 // If there's no definition (not even in progress), return what we have.
1883 UnaryTransformType::UnaryTransformType(QualType BaseType,
1884 QualType UnderlyingType,
1886 QualType CanonicalType)
1887 : Type(UnaryTransform, CanonicalType, UnderlyingType->isDependentType(),
1888 UnderlyingType->isInstantiationDependentType(),
1889 UnderlyingType->isVariablyModifiedType(),
1890 BaseType->containsUnexpandedParameterPack())
1891 , BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind)
1894 TagDecl *TagType::getDecl() const {
1895 return getInterestingTagDecl(decl);
1898 bool TagType::isBeingDefined() const {
1899 return getDecl()->isBeingDefined();
1902 bool AttributedType::isMSTypeSpec() const {
1903 switch (getAttrKind()) {
1904 default: return false;
1911 llvm_unreachable("invalid attr kind");
1914 bool AttributedType::isCallingConv() const {
1915 switch (getAttrKind()) {
1920 case attr_address_space:
1922 case attr_vector_size:
1923 case attr_neon_vector_type:
1924 case attr_neon_polyvector_type:
1926 case attr_objc_ownership:
1935 case attr_vectorcall:
1939 case attr_pnaclcall:
1940 case attr_inteloclbicc:
1943 llvm_unreachable("invalid attr kind");
1946 CXXRecordDecl *InjectedClassNameType::getDecl() const {
1947 return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
1950 IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
1951 return isCanonicalUnqualified() ? nullptr : getDecl()->getIdentifier();
1954 SubstTemplateTypeParmPackType::
1955 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
1957 const TemplateArgument &ArgPack)
1958 : Type(SubstTemplateTypeParmPack, Canon, true, true, false, true),
1960 Arguments(ArgPack.pack_begin()), NumArguments(ArgPack.pack_size())
1964 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const {
1965 return TemplateArgument(Arguments, NumArguments);
1968 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
1969 Profile(ID, getReplacedParameter(), getArgumentPack());
1972 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
1973 const TemplateTypeParmType *Replaced,
1974 const TemplateArgument &ArgPack) {
1975 ID.AddPointer(Replaced);
1976 ID.AddInteger(ArgPack.pack_size());
1977 for (const auto &P : ArgPack.pack_elements())
1978 ID.AddPointer(P.getAsType().getAsOpaquePtr());
1981 bool TemplateSpecializationType::
1982 anyDependentTemplateArguments(const TemplateArgumentListInfo &Args,
1983 bool &InstantiationDependent) {
1984 return anyDependentTemplateArguments(Args.getArgumentArray(), Args.size(),
1985 InstantiationDependent);
1988 bool TemplateSpecializationType::
1989 anyDependentTemplateArguments(const TemplateArgumentLoc *Args, unsigned N,
1990 bool &InstantiationDependent) {
1991 for (unsigned i = 0; i != N; ++i) {
1992 if (Args[i].getArgument().isDependent()) {
1993 InstantiationDependent = true;
1997 if (Args[i].getArgument().isInstantiationDependent())
1998 InstantiationDependent = true;
2003 TemplateSpecializationType::
2004 TemplateSpecializationType(TemplateName T,
2005 const TemplateArgument *Args, unsigned NumArgs,
2006 QualType Canon, QualType AliasedType)
2007 : Type(TemplateSpecialization,
2008 Canon.isNull()? QualType(this, 0) : Canon,
2009 Canon.isNull()? true : Canon->isDependentType(),
2010 Canon.isNull()? true : Canon->isInstantiationDependentType(),
2012 T.containsUnexpandedParameterPack()),
2013 Template(T), NumArgs(NumArgs), TypeAlias(!AliasedType.isNull()) {
2014 assert(!T.getAsDependentTemplateName() &&
2015 "Use DependentTemplateSpecializationType for dependent template-name");
2016 assert((T.getKind() == TemplateName::Template ||
2017 T.getKind() == TemplateName::SubstTemplateTemplateParm ||
2018 T.getKind() == TemplateName::SubstTemplateTemplateParmPack) &&
2019 "Unexpected template name for TemplateSpecializationType");
2021 TemplateArgument *TemplateArgs
2022 = reinterpret_cast<TemplateArgument *>(this + 1);
2023 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
2024 // Update instantiation-dependent and variably-modified bits.
2025 // If the canonical type exists and is non-dependent, the template
2026 // specialization type can be non-dependent even if one of the type
2027 // arguments is. Given:
2028 // template<typename T> using U = int;
2029 // U<T> is always non-dependent, irrespective of the type T.
2030 // However, U<Ts> contains an unexpanded parameter pack, even though
2031 // its expansion (and thus its desugared type) doesn't.
2032 if (Args[Arg].isInstantiationDependent())
2033 setInstantiationDependent();
2034 if (Args[Arg].getKind() == TemplateArgument::Type &&
2035 Args[Arg].getAsType()->isVariablyModifiedType())
2036 setVariablyModified();
2037 if (Args[Arg].containsUnexpandedParameterPack())
2038 setContainsUnexpandedParameterPack();
2039 new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]);
2042 // Store the aliased type if this is a type alias template specialization.
2044 TemplateArgument *Begin = reinterpret_cast<TemplateArgument *>(this + 1);
2045 *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType;
2050 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
2052 const TemplateArgument *Args,
2054 const ASTContext &Context) {
2056 for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
2057 Args[Idx].Profile(ID, Context);
2061 QualifierCollector::apply(const ASTContext &Context, QualType QT) const {
2062 if (!hasNonFastQualifiers())
2063 return QT.withFastQualifiers(getFastQualifiers());
2065 return Context.getQualifiedType(QT, *this);
2069 QualifierCollector::apply(const ASTContext &Context, const Type *T) const {
2070 if (!hasNonFastQualifiers())
2071 return QualType(T, getFastQualifiers());
2073 return Context.getQualifiedType(T, *this);
2076 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
2078 ObjCProtocolDecl * const *Protocols,
2079 unsigned NumProtocols) {
2080 ID.AddPointer(BaseType.getAsOpaquePtr());
2081 for (unsigned i = 0; i != NumProtocols; i++)
2082 ID.AddPointer(Protocols[i]);
2085 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
2086 Profile(ID, getBaseType(), qual_begin(), getNumProtocols());
2091 /// \brief The cached properties of a type.
2092 class CachedProperties {
2097 CachedProperties(Linkage L, bool local) : L(L), local(local) {}
2099 Linkage getLinkage() const { return L; }
2100 bool hasLocalOrUnnamedType() const { return local; }
2102 friend CachedProperties merge(CachedProperties L, CachedProperties R) {
2103 Linkage MergedLinkage = minLinkage(L.L, R.L);
2104 return CachedProperties(MergedLinkage,
2105 L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType());
2110 static CachedProperties computeCachedProperties(const Type *T);
2113 /// The type-property cache. This is templated so as to be
2114 /// instantiated at an internal type to prevent unnecessary symbol
2116 template <class Private> class TypePropertyCache {
2118 static CachedProperties get(QualType T) {
2119 return get(T.getTypePtr());
2122 static CachedProperties get(const Type *T) {
2124 return CachedProperties(T->TypeBits.getLinkage(),
2125 T->TypeBits.hasLocalOrUnnamedType());
2128 static void ensure(const Type *T) {
2129 // If the cache is valid, we're okay.
2130 if (T->TypeBits.isCacheValid()) return;
2132 // If this type is non-canonical, ask its canonical type for the
2133 // relevant information.
2134 if (!T->isCanonicalUnqualified()) {
2135 const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
2137 T->TypeBits.CacheValid = true;
2138 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
2139 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
2143 // Compute the cached properties and then set the cache.
2144 CachedProperties Result = computeCachedProperties(T);
2145 T->TypeBits.CacheValid = true;
2146 T->TypeBits.CachedLinkage = Result.getLinkage();
2147 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
2152 // Instantiate the friend template at a private class. In a
2153 // reasonable implementation, these symbols will be internal.
2154 // It is terrible that this is the best way to accomplish this.
2155 namespace { class Private {}; }
2156 typedef TypePropertyCache<Private> Cache;
2158 static CachedProperties computeCachedProperties(const Type *T) {
2159 switch (T->getTypeClass()) {
2160 #define TYPE(Class,Base)
2161 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
2162 #include "clang/AST/TypeNodes.def"
2163 llvm_unreachable("didn't expect a non-canonical type here");
2165 #define TYPE(Class,Base)
2166 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
2167 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
2168 #include "clang/AST/TypeNodes.def"
2169 // Treat instantiation-dependent types as external.
2170 assert(T->isInstantiationDependentType());
2171 return CachedProperties(ExternalLinkage, false);
2174 // Give non-deduced 'auto' types external linkage. We should only see them
2175 // here in error recovery.
2176 return CachedProperties(ExternalLinkage, false);
2179 // C++ [basic.link]p8:
2180 // A type is said to have linkage if and only if:
2181 // - it is a fundamental type (3.9.1); or
2182 return CachedProperties(ExternalLinkage, false);
2186 const TagDecl *Tag = cast<TagType>(T)->getDecl();
2188 // C++ [basic.link]p8:
2189 // - it is a class or enumeration type that is named (or has a name
2190 // for linkage purposes (7.1.3)) and the name has linkage; or
2191 // - it is a specialization of a class template (14); or
2192 Linkage L = Tag->getLinkageInternal();
2193 bool IsLocalOrUnnamed =
2194 Tag->getDeclContext()->isFunctionOrMethod() ||
2195 !Tag->hasNameForLinkage();
2196 return CachedProperties(L, IsLocalOrUnnamed);
2199 // C++ [basic.link]p8:
2200 // - it is a compound type (3.9.2) other than a class or enumeration,
2201 // compounded exclusively from types that have linkage; or
2203 return Cache::get(cast<ComplexType>(T)->getElementType());
2205 return Cache::get(cast<PointerType>(T)->getPointeeType());
2206 case Type::BlockPointer:
2207 return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
2208 case Type::LValueReference:
2209 case Type::RValueReference:
2210 return Cache::get(cast<ReferenceType>(T)->getPointeeType());
2211 case Type::MemberPointer: {
2212 const MemberPointerType *MPT = cast<MemberPointerType>(T);
2213 return merge(Cache::get(MPT->getClass()),
2214 Cache::get(MPT->getPointeeType()));
2216 case Type::ConstantArray:
2217 case Type::IncompleteArray:
2218 case Type::VariableArray:
2219 return Cache::get(cast<ArrayType>(T)->getElementType());
2221 case Type::ExtVector:
2222 return Cache::get(cast<VectorType>(T)->getElementType());
2223 case Type::FunctionNoProto:
2224 return Cache::get(cast<FunctionType>(T)->getReturnType());
2225 case Type::FunctionProto: {
2226 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2227 CachedProperties result = Cache::get(FPT->getReturnType());
2228 for (const auto &ai : FPT->param_types())
2229 result = merge(result, Cache::get(ai));
2232 case Type::ObjCInterface: {
2233 Linkage L = cast<ObjCInterfaceType>(T)->getDecl()->getLinkageInternal();
2234 return CachedProperties(L, false);
2236 case Type::ObjCObject:
2237 return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
2238 case Type::ObjCObjectPointer:
2239 return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
2241 return Cache::get(cast<AtomicType>(T)->getValueType());
2244 llvm_unreachable("unhandled type class");
2247 /// \brief Determine the linkage of this type.
2248 Linkage Type::getLinkage() const {
2249 Cache::ensure(this);
2250 return TypeBits.getLinkage();
2253 bool Type::hasUnnamedOrLocalType() const {
2254 Cache::ensure(this);
2255 return TypeBits.hasLocalOrUnnamedType();
2258 static LinkageInfo computeLinkageInfo(QualType T);
2260 static LinkageInfo computeLinkageInfo(const Type *T) {
2261 switch (T->getTypeClass()) {
2262 #define TYPE(Class,Base)
2263 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
2264 #include "clang/AST/TypeNodes.def"
2265 llvm_unreachable("didn't expect a non-canonical type here");
2267 #define TYPE(Class,Base)
2268 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
2269 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
2270 #include "clang/AST/TypeNodes.def"
2271 // Treat instantiation-dependent types as external.
2272 assert(T->isInstantiationDependentType());
2273 return LinkageInfo::external();
2276 return LinkageInfo::external();
2279 return LinkageInfo::external();
2283 return cast<TagType>(T)->getDecl()->getLinkageAndVisibility();
2286 return computeLinkageInfo(cast<ComplexType>(T)->getElementType());
2288 return computeLinkageInfo(cast<PointerType>(T)->getPointeeType());
2289 case Type::BlockPointer:
2290 return computeLinkageInfo(cast<BlockPointerType>(T)->getPointeeType());
2291 case Type::LValueReference:
2292 case Type::RValueReference:
2293 return computeLinkageInfo(cast<ReferenceType>(T)->getPointeeType());
2294 case Type::MemberPointer: {
2295 const MemberPointerType *MPT = cast<MemberPointerType>(T);
2296 LinkageInfo LV = computeLinkageInfo(MPT->getClass());
2297 LV.merge(computeLinkageInfo(MPT->getPointeeType()));
2300 case Type::ConstantArray:
2301 case Type::IncompleteArray:
2302 case Type::VariableArray:
2303 return computeLinkageInfo(cast<ArrayType>(T)->getElementType());
2305 case Type::ExtVector:
2306 return computeLinkageInfo(cast<VectorType>(T)->getElementType());
2307 case Type::FunctionNoProto:
2308 return computeLinkageInfo(cast<FunctionType>(T)->getReturnType());
2309 case Type::FunctionProto: {
2310 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2311 LinkageInfo LV = computeLinkageInfo(FPT->getReturnType());
2312 for (const auto &ai : FPT->param_types())
2313 LV.merge(computeLinkageInfo(ai));
2316 case Type::ObjCInterface:
2317 return cast<ObjCInterfaceType>(T)->getDecl()->getLinkageAndVisibility();
2318 case Type::ObjCObject:
2319 return computeLinkageInfo(cast<ObjCObjectType>(T)->getBaseType());
2320 case Type::ObjCObjectPointer:
2321 return computeLinkageInfo(cast<ObjCObjectPointerType>(T)->getPointeeType());
2323 return computeLinkageInfo(cast<AtomicType>(T)->getValueType());
2326 llvm_unreachable("unhandled type class");
2329 static LinkageInfo computeLinkageInfo(QualType T) {
2330 return computeLinkageInfo(T.getTypePtr());
2333 bool Type::isLinkageValid() const {
2334 if (!TypeBits.isCacheValid())
2337 return computeLinkageInfo(getCanonicalTypeInternal()).getLinkage() ==
2338 TypeBits.getLinkage();
2341 LinkageInfo Type::getLinkageAndVisibility() const {
2342 if (!isCanonicalUnqualified())
2343 return computeLinkageInfo(getCanonicalTypeInternal());
2345 LinkageInfo LV = computeLinkageInfo(this);
2346 assert(LV.getLinkage() == getLinkage());
2350 Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const {
2351 if (isObjCARCImplicitlyUnretainedType())
2352 return Qualifiers::OCL_ExplicitNone;
2353 return Qualifiers::OCL_Strong;
2356 bool Type::isObjCARCImplicitlyUnretainedType() const {
2357 assert(isObjCLifetimeType() &&
2358 "cannot query implicit lifetime for non-inferrable type");
2360 const Type *canon = getCanonicalTypeInternal().getTypePtr();
2362 // Walk down to the base type. We don't care about qualifiers for this.
2363 while (const ArrayType *array = dyn_cast<ArrayType>(canon))
2364 canon = array->getElementType().getTypePtr();
2366 if (const ObjCObjectPointerType *opt
2367 = dyn_cast<ObjCObjectPointerType>(canon)) {
2368 // Class and Class<Protocol> don't require retension.
2369 if (opt->getObjectType()->isObjCClass())
2376 bool Type::isObjCNSObjectType() const {
2377 if (const TypedefType *typedefType = dyn_cast<TypedefType>(this))
2378 return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>();
2381 bool Type::isObjCRetainableType() const {
2382 return isObjCObjectPointerType() ||
2383 isBlockPointerType() ||
2384 isObjCNSObjectType();
2386 bool Type::isObjCIndirectLifetimeType() const {
2387 if (isObjCLifetimeType())
2389 if (const PointerType *OPT = getAs<PointerType>())
2390 return OPT->getPointeeType()->isObjCIndirectLifetimeType();
2391 if (const ReferenceType *Ref = getAs<ReferenceType>())
2392 return Ref->getPointeeType()->isObjCIndirectLifetimeType();
2393 if (const MemberPointerType *MemPtr = getAs<MemberPointerType>())
2394 return MemPtr->getPointeeType()->isObjCIndirectLifetimeType();
2398 /// Returns true if objects of this type have lifetime semantics under
2400 bool Type::isObjCLifetimeType() const {
2401 const Type *type = this;
2402 while (const ArrayType *array = type->getAsArrayTypeUnsafe())
2403 type = array->getElementType().getTypePtr();
2404 return type->isObjCRetainableType();
2407 /// \brief Determine whether the given type T is a "bridgable" Objective-C type,
2408 /// which is either an Objective-C object pointer type or an
2409 bool Type::isObjCARCBridgableType() const {
2410 return isObjCObjectPointerType() || isBlockPointerType();
2413 /// \brief Determine whether the given type T is a "bridgeable" C type.
2414 bool Type::isCARCBridgableType() const {
2415 const PointerType *Pointer = getAs<PointerType>();
2419 QualType Pointee = Pointer->getPointeeType();
2420 return Pointee->isVoidType() || Pointee->isRecordType();
2423 bool Type::hasSizedVLAType() const {
2424 if (!isVariablyModifiedType()) return false;
2426 if (const PointerType *ptr = getAs<PointerType>())
2427 return ptr->getPointeeType()->hasSizedVLAType();
2428 if (const ReferenceType *ref = getAs<ReferenceType>())
2429 return ref->getPointeeType()->hasSizedVLAType();
2430 if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
2431 if (isa<VariableArrayType>(arr) &&
2432 cast<VariableArrayType>(arr)->getSizeExpr())
2435 return arr->getElementType()->hasSizedVLAType();
2441 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
2442 switch (type.getObjCLifetime()) {
2443 case Qualifiers::OCL_None:
2444 case Qualifiers::OCL_ExplicitNone:
2445 case Qualifiers::OCL_Autoreleasing:
2448 case Qualifiers::OCL_Strong:
2449 return DK_objc_strong_lifetime;
2450 case Qualifiers::OCL_Weak:
2451 return DK_objc_weak_lifetime;
2454 /// Currently, the only destruction kind we recognize is C++ objects
2455 /// with non-trivial destructors.
2456 const CXXRecordDecl *record =
2457 type->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2458 if (record && record->hasDefinition() && !record->hasTrivialDestructor())
2459 return DK_cxx_destructor;
2464 CXXRecordDecl *MemberPointerType::getMostRecentCXXRecordDecl() const {
2465 return getClass()->getAsCXXRecordDecl()->getMostRecentDecl();