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 : VectorType(Vector, vecType, nElements, canonType, vecKind) {}
175 VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements,
176 QualType canonType, VectorKind vecKind)
177 : Type(tc, canonType, vecType->isDependentType(),
178 vecType->isInstantiationDependentType(),
179 vecType->isVariablyModifiedType(),
180 vecType->containsUnexpandedParameterPack()),
183 VectorTypeBits.VecKind = vecKind;
184 VectorTypeBits.NumElements = nElements;
187 /// getArrayElementTypeNoTypeQual - If this is an array type, return the
188 /// element type of the array, potentially with type qualifiers missing.
189 /// This method should never be used when type qualifiers are meaningful.
190 const Type *Type::getArrayElementTypeNoTypeQual() const {
191 // If this is directly an array type, return it.
192 if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
193 return ATy->getElementType().getTypePtr();
195 // If the canonical form of this type isn't the right kind, reject it.
196 if (!isa<ArrayType>(CanonicalType))
199 // If this is a typedef for an array type, strip the typedef off without
200 // losing all typedef information.
201 return cast<ArrayType>(getUnqualifiedDesugaredType())
202 ->getElementType().getTypePtr();
205 /// getDesugaredType - Return the specified type with any "sugar" removed from
206 /// the type. This takes off typedefs, typeof's etc. If the outer level of
207 /// the type is already concrete, it returns it unmodified. This is similar
208 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
209 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
211 QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) {
212 SplitQualType split = getSplitDesugaredType(T);
213 return Context.getQualifiedType(split.Ty, split.Quals);
216 QualType QualType::getSingleStepDesugaredTypeImpl(QualType type,
217 const ASTContext &Context) {
218 SplitQualType split = type.split();
219 QualType desugar = split.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
220 return Context.getQualifiedType(desugar, split.Quals);
223 QualType Type::getLocallyUnqualifiedSingleStepDesugaredType() const {
224 switch (getTypeClass()) {
225 #define ABSTRACT_TYPE(Class, Parent)
226 #define TYPE(Class, Parent) \
227 case Type::Class: { \
228 const Class##Type *ty = cast<Class##Type>(this); \
229 if (!ty->isSugared()) return QualType(ty, 0); \
230 return ty->desugar(); \
232 #include "clang/AST/TypeNodes.def"
234 llvm_unreachable("bad type kind!");
237 SplitQualType QualType::getSplitDesugaredType(QualType T) {
238 QualifierCollector Qs;
242 const Type *CurTy = Qs.strip(Cur);
243 switch (CurTy->getTypeClass()) {
244 #define ABSTRACT_TYPE(Class, Parent)
245 #define TYPE(Class, Parent) \
246 case Type::Class: { \
247 const Class##Type *Ty = cast<Class##Type>(CurTy); \
248 if (!Ty->isSugared()) \
249 return SplitQualType(Ty, Qs); \
250 Cur = Ty->desugar(); \
253 #include "clang/AST/TypeNodes.def"
258 SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) {
259 SplitQualType split = type.split();
261 // All the qualifiers we've seen so far.
262 Qualifiers quals = split.Quals;
264 // The last type node we saw with any nodes inside it.
265 const Type *lastTypeWithQuals = split.Ty;
270 // Do a single-step desugar, aborting the loop if the type isn't
272 switch (split.Ty->getTypeClass()) {
273 #define ABSTRACT_TYPE(Class, Parent)
274 #define TYPE(Class, Parent) \
275 case Type::Class: { \
276 const Class##Type *ty = cast<Class##Type>(split.Ty); \
277 if (!ty->isSugared()) goto done; \
278 next = ty->desugar(); \
281 #include "clang/AST/TypeNodes.def"
284 // Otherwise, split the underlying type. If that yields qualifiers,
285 // update the information.
286 split = next.split();
287 if (!split.Quals.empty()) {
288 lastTypeWithQuals = split.Ty;
289 quals.addConsistentQualifiers(split.Quals);
294 return SplitQualType(lastTypeWithQuals, quals);
297 QualType QualType::IgnoreParens(QualType T) {
298 // FIXME: this seems inherently un-qualifiers-safe.
299 while (const ParenType *PT = T->getAs<ParenType>())
300 T = PT->getInnerType();
304 /// \brief This will check for a T (which should be a Type which can act as
305 /// sugar, such as a TypedefType) by removing any existing sugar until it
306 /// reaches a T or a non-sugared type.
307 template<typename T> static const T *getAsSugar(const Type *Cur) {
309 if (const T *Sugar = dyn_cast<T>(Cur))
311 switch (Cur->getTypeClass()) {
312 #define ABSTRACT_TYPE(Class, Parent)
313 #define TYPE(Class, Parent) \
314 case Type::Class: { \
315 const Class##Type *Ty = cast<Class##Type>(Cur); \
316 if (!Ty->isSugared()) return 0; \
317 Cur = Ty->desugar().getTypePtr(); \
320 #include "clang/AST/TypeNodes.def"
325 template <> const TypedefType *Type::getAs() const {
326 return getAsSugar<TypedefType>(this);
329 template <> const TemplateSpecializationType *Type::getAs() const {
330 return getAsSugar<TemplateSpecializationType>(this);
333 template <> const AttributedType *Type::getAs() const {
334 return getAsSugar<AttributedType>(this);
337 /// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
338 /// sugar off the given type. This should produce an object of the
339 /// same dynamic type as the canonical type.
340 const Type *Type::getUnqualifiedDesugaredType() const {
341 const Type *Cur = this;
344 switch (Cur->getTypeClass()) {
345 #define ABSTRACT_TYPE(Class, Parent)
346 #define TYPE(Class, Parent) \
348 const Class##Type *Ty = cast<Class##Type>(Cur); \
349 if (!Ty->isSugared()) return Cur; \
350 Cur = Ty->desugar().getTypePtr(); \
353 #include "clang/AST/TypeNodes.def"
357 bool Type::isClassType() const {
358 if (const RecordType *RT = getAs<RecordType>())
359 return RT->getDecl()->isClass();
362 bool Type::isStructureType() const {
363 if (const RecordType *RT = getAs<RecordType>())
364 return RT->getDecl()->isStruct();
367 bool Type::isObjCBoxableRecordType() const {
368 if (const RecordType *RT = getAs<RecordType>())
369 return RT->getDecl()->hasAttr<ObjCBoxableAttr>();
372 bool Type::isInterfaceType() const {
373 if (const RecordType *RT = getAs<RecordType>())
374 return RT->getDecl()->isInterface();
377 bool Type::isStructureOrClassType() const {
378 if (const RecordType *RT = getAs<RecordType>()) {
379 RecordDecl *RD = RT->getDecl();
380 return RD->isStruct() || RD->isClass() || RD->isInterface();
384 bool Type::isVoidPointerType() const {
385 if (const PointerType *PT = getAs<PointerType>())
386 return PT->getPointeeType()->isVoidType();
390 bool Type::isUnionType() const {
391 if (const RecordType *RT = getAs<RecordType>())
392 return RT->getDecl()->isUnion();
396 bool Type::isComplexType() const {
397 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
398 return CT->getElementType()->isFloatingType();
402 bool Type::isComplexIntegerType() const {
403 // Check for GCC complex integer extension.
404 return getAsComplexIntegerType();
407 const ComplexType *Type::getAsComplexIntegerType() const {
408 if (const ComplexType *Complex = getAs<ComplexType>())
409 if (Complex->getElementType()->isIntegerType())
414 QualType Type::getPointeeType() const {
415 if (const PointerType *PT = getAs<PointerType>())
416 return PT->getPointeeType();
417 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
418 return OPT->getPointeeType();
419 if (const BlockPointerType *BPT = getAs<BlockPointerType>())
420 return BPT->getPointeeType();
421 if (const ReferenceType *RT = getAs<ReferenceType>())
422 return RT->getPointeeType();
423 if (const MemberPointerType *MPT = getAs<MemberPointerType>())
424 return MPT->getPointeeType();
425 if (const DecayedType *DT = getAs<DecayedType>())
426 return DT->getPointeeType();
430 const RecordType *Type::getAsStructureType() const {
431 // If this is directly a structure type, return it.
432 if (const RecordType *RT = dyn_cast<RecordType>(this)) {
433 if (RT->getDecl()->isStruct())
437 // If the canonical form of this type isn't the right kind, reject it.
438 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
439 if (!RT->getDecl()->isStruct())
442 // If this is a typedef for a structure type, strip the typedef off without
443 // losing all typedef information.
444 return cast<RecordType>(getUnqualifiedDesugaredType());
449 const RecordType *Type::getAsUnionType() const {
450 // If this is directly a union type, return it.
451 if (const RecordType *RT = dyn_cast<RecordType>(this)) {
452 if (RT->getDecl()->isUnion())
456 // If the canonical form of this type isn't the right kind, reject it.
457 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
458 if (!RT->getDecl()->isUnion())
461 // If this is a typedef for a union type, strip the typedef off without
462 // losing all typedef information.
463 return cast<RecordType>(getUnqualifiedDesugaredType());
469 ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base,
470 ObjCProtocolDecl * const *Protocols,
471 unsigned NumProtocols)
472 : Type(ObjCObject, Canonical, false, false, false, false),
475 ObjCObjectTypeBits.NumProtocols = NumProtocols;
476 assert(getNumProtocols() == NumProtocols &&
477 "bitfield overflow in protocol count");
479 memcpy(getProtocolStorage(), Protocols,
480 NumProtocols * sizeof(ObjCProtocolDecl*));
483 const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const {
484 // There is no sugar for ObjCObjectType's, just return the canonical
485 // type pointer if it is the right class. There is no typedef information to
486 // return and these cannot be Address-space qualified.
487 if (const ObjCObjectType *T = getAs<ObjCObjectType>())
488 if (T->getNumProtocols() && T->getInterface())
493 bool Type::isObjCQualifiedInterfaceType() const {
494 return getAsObjCQualifiedInterfaceType() != nullptr;
497 const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
498 // There is no sugar for ObjCQualifiedIdType's, just return the canonical
499 // type pointer if it is the right class.
500 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
501 if (OPT->isObjCQualifiedIdType())
507 const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const {
508 // There is no sugar for ObjCQualifiedClassType's, just return the canonical
509 // type pointer if it is the right class.
510 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
511 if (OPT->isObjCQualifiedClassType())
517 const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
518 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
519 if (OPT->getInterfaceType())
525 const CXXRecordDecl *Type::getPointeeCXXRecordDecl() const {
526 QualType PointeeType;
527 if (const PointerType *PT = getAs<PointerType>())
528 PointeeType = PT->getPointeeType();
529 else if (const ReferenceType *RT = getAs<ReferenceType>())
530 PointeeType = RT->getPointeeType();
534 if (const RecordType *RT = PointeeType->getAs<RecordType>())
535 return dyn_cast<CXXRecordDecl>(RT->getDecl());
540 CXXRecordDecl *Type::getAsCXXRecordDecl() const {
541 return dyn_cast_or_null<CXXRecordDecl>(getAsTagDecl());
544 TagDecl *Type::getAsTagDecl() const {
545 if (const auto *TT = getAs<TagType>())
546 return cast<TagDecl>(TT->getDecl());
547 if (const auto *Injected = getAs<InjectedClassNameType>())
548 return Injected->getDecl();
554 class GetContainedAutoVisitor :
555 public TypeVisitor<GetContainedAutoVisitor, AutoType*> {
557 using TypeVisitor<GetContainedAutoVisitor, AutoType*>::Visit;
558 AutoType *Visit(QualType T) {
561 return Visit(T.getTypePtr());
564 // The 'auto' type itself.
565 AutoType *VisitAutoType(const AutoType *AT) {
566 return const_cast<AutoType*>(AT);
569 // Only these types can contain the desired 'auto' type.
570 AutoType *VisitPointerType(const PointerType *T) {
571 return Visit(T->getPointeeType());
573 AutoType *VisitBlockPointerType(const BlockPointerType *T) {
574 return Visit(T->getPointeeType());
576 AutoType *VisitReferenceType(const ReferenceType *T) {
577 return Visit(T->getPointeeTypeAsWritten());
579 AutoType *VisitMemberPointerType(const MemberPointerType *T) {
580 return Visit(T->getPointeeType());
582 AutoType *VisitArrayType(const ArrayType *T) {
583 return Visit(T->getElementType());
585 AutoType *VisitDependentSizedExtVectorType(
586 const DependentSizedExtVectorType *T) {
587 return Visit(T->getElementType());
589 AutoType *VisitVectorType(const VectorType *T) {
590 return Visit(T->getElementType());
592 AutoType *VisitFunctionType(const FunctionType *T) {
593 return Visit(T->getReturnType());
595 AutoType *VisitParenType(const ParenType *T) {
596 return Visit(T->getInnerType());
598 AutoType *VisitAttributedType(const AttributedType *T) {
599 return Visit(T->getModifiedType());
601 AutoType *VisitAdjustedType(const AdjustedType *T) {
602 return Visit(T->getOriginalType());
607 AutoType *Type::getContainedAutoType() const {
608 return GetContainedAutoVisitor().Visit(this);
611 bool Type::hasIntegerRepresentation() const {
612 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
613 return VT->getElementType()->isIntegerType();
615 return isIntegerType();
618 /// \brief Determine whether this type is an integral type.
620 /// This routine determines whether the given type is an integral type per
621 /// C++ [basic.fundamental]p7. Although the C standard does not define the
622 /// term "integral type", it has a similar term "integer type", and in C++
623 /// the two terms are equivalent. However, C's "integer type" includes
624 /// enumeration types, while C++'s "integer type" does not. The \c ASTContext
625 /// parameter is used to determine whether we should be following the C or
626 /// C++ rules when determining whether this type is an integral/integer type.
628 /// For cases where C permits "an integer type" and C++ permits "an integral
629 /// type", use this routine.
631 /// For cases where C permits "an integer type" and C++ permits "an integral
632 /// or enumeration type", use \c isIntegralOrEnumerationType() instead.
634 /// \param Ctx The context in which this type occurs.
636 /// \returns true if the type is considered an integral type, false otherwise.
637 bool Type::isIntegralType(ASTContext &Ctx) const {
638 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
639 return BT->getKind() >= BuiltinType::Bool &&
640 BT->getKind() <= BuiltinType::Int128;
642 // Complete enum types are integral in C.
643 if (!Ctx.getLangOpts().CPlusPlus)
644 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
645 return ET->getDecl()->isComplete();
651 bool Type::isIntegralOrUnscopedEnumerationType() const {
652 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
653 return BT->getKind() >= BuiltinType::Bool &&
654 BT->getKind() <= BuiltinType::Int128;
656 // Check for a complete enum type; incomplete enum types are not properly an
657 // enumeration type in the sense required here.
658 // C++0x: However, if the underlying type of the enum is fixed, it is
659 // considered complete.
660 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
661 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
668 bool Type::isCharType() const {
669 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
670 return BT->getKind() == BuiltinType::Char_U ||
671 BT->getKind() == BuiltinType::UChar ||
672 BT->getKind() == BuiltinType::Char_S ||
673 BT->getKind() == BuiltinType::SChar;
677 bool Type::isWideCharType() const {
678 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
679 return BT->getKind() == BuiltinType::WChar_S ||
680 BT->getKind() == BuiltinType::WChar_U;
684 bool Type::isChar16Type() const {
685 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
686 return BT->getKind() == BuiltinType::Char16;
690 bool Type::isChar32Type() const {
691 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
692 return BT->getKind() == BuiltinType::Char32;
696 /// \brief Determine whether this type is any of the built-in character
698 bool Type::isAnyCharacterType() const {
699 const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType);
700 if (!BT) return false;
701 switch (BT->getKind()) {
702 default: return false;
703 case BuiltinType::Char_U:
704 case BuiltinType::UChar:
705 case BuiltinType::WChar_U:
706 case BuiltinType::Char16:
707 case BuiltinType::Char32:
708 case BuiltinType::Char_S:
709 case BuiltinType::SChar:
710 case BuiltinType::WChar_S:
715 /// isSignedIntegerType - Return true if this is an integer type that is
716 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
717 /// an enum decl which has a signed representation
718 bool Type::isSignedIntegerType() const {
719 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
720 return BT->getKind() >= BuiltinType::Char_S &&
721 BT->getKind() <= BuiltinType::Int128;
724 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
725 // Incomplete enum types are not treated as integer types.
726 // FIXME: In C++, enum types are never integer types.
727 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
728 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
734 bool Type::isSignedIntegerOrEnumerationType() const {
735 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
736 return BT->getKind() >= BuiltinType::Char_S &&
737 BT->getKind() <= BuiltinType::Int128;
740 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
741 if (ET->getDecl()->isComplete())
742 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
748 bool Type::hasSignedIntegerRepresentation() const {
749 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
750 return VT->getElementType()->isSignedIntegerOrEnumerationType();
752 return isSignedIntegerOrEnumerationType();
755 /// isUnsignedIntegerType - Return true if this is an integer type that is
756 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
757 /// decl which has an unsigned representation
758 bool Type::isUnsignedIntegerType() const {
759 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
760 return BT->getKind() >= BuiltinType::Bool &&
761 BT->getKind() <= BuiltinType::UInt128;
764 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
765 // Incomplete enum types are not treated as integer types.
766 // FIXME: In C++, enum types are never integer types.
767 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
768 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
774 bool Type::isUnsignedIntegerOrEnumerationType() const {
775 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
776 return BT->getKind() >= BuiltinType::Bool &&
777 BT->getKind() <= BuiltinType::UInt128;
780 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
781 if (ET->getDecl()->isComplete())
782 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
788 bool Type::hasUnsignedIntegerRepresentation() const {
789 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
790 return VT->getElementType()->isUnsignedIntegerOrEnumerationType();
792 return isUnsignedIntegerOrEnumerationType();
795 bool Type::isFloatingType() const {
796 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
797 return BT->getKind() >= BuiltinType::Half &&
798 BT->getKind() <= BuiltinType::LongDouble;
799 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
800 return CT->getElementType()->isFloatingType();
804 bool Type::hasFloatingRepresentation() const {
805 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
806 return VT->getElementType()->isFloatingType();
808 return isFloatingType();
811 bool Type::isRealFloatingType() const {
812 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
813 return BT->isFloatingPoint();
817 bool Type::isRealType() const {
818 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
819 return BT->getKind() >= BuiltinType::Bool &&
820 BT->getKind() <= BuiltinType::LongDouble;
821 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
822 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
826 bool Type::isArithmeticType() const {
827 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
828 return BT->getKind() >= BuiltinType::Bool &&
829 BT->getKind() <= BuiltinType::LongDouble;
830 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
831 // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
832 // If a body isn't seen by the time we get here, return false.
834 // C++0x: Enumerations are not arithmetic types. For now, just return
835 // false for scoped enumerations since that will disable any
836 // unwanted implicit conversions.
837 return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete();
838 return isa<ComplexType>(CanonicalType);
841 Type::ScalarTypeKind Type::getScalarTypeKind() const {
842 assert(isScalarType());
844 const Type *T = CanonicalType.getTypePtr();
845 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) {
846 if (BT->getKind() == BuiltinType::Bool) return STK_Bool;
847 if (BT->getKind() == BuiltinType::NullPtr) return STK_CPointer;
848 if (BT->isInteger()) return STK_Integral;
849 if (BT->isFloatingPoint()) return STK_Floating;
850 llvm_unreachable("unknown scalar builtin type");
851 } else if (isa<PointerType>(T)) {
853 } else if (isa<BlockPointerType>(T)) {
854 return STK_BlockPointer;
855 } else if (isa<ObjCObjectPointerType>(T)) {
856 return STK_ObjCObjectPointer;
857 } else if (isa<MemberPointerType>(T)) {
858 return STK_MemberPointer;
859 } else if (isa<EnumType>(T)) {
860 assert(cast<EnumType>(T)->getDecl()->isComplete());
862 } else if (const ComplexType *CT = dyn_cast<ComplexType>(T)) {
863 if (CT->getElementType()->isRealFloatingType())
864 return STK_FloatingComplex;
865 return STK_IntegralComplex;
868 llvm_unreachable("unknown scalar type");
871 /// \brief Determines whether the type is a C++ aggregate type or C
872 /// aggregate or union type.
874 /// An aggregate type is an array or a class type (struct, union, or
875 /// class) that has no user-declared constructors, no private or
876 /// protected non-static data members, no base classes, and no virtual
877 /// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
878 /// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
879 /// includes union types.
880 bool Type::isAggregateType() const {
881 if (const RecordType *Record = dyn_cast<RecordType>(CanonicalType)) {
882 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
883 return ClassDecl->isAggregate();
888 return isa<ArrayType>(CanonicalType);
891 /// isConstantSizeType - Return true if this is not a variable sized type,
892 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
893 /// incomplete types or dependent types.
894 bool Type::isConstantSizeType() const {
895 assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
896 assert(!isDependentType() && "This doesn't make sense for dependent types");
897 // The VAT must have a size, as it is known to be complete.
898 return !isa<VariableArrayType>(CanonicalType);
901 /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
902 /// - a type that can describe objects, but which lacks information needed to
903 /// determine its size.
904 bool Type::isIncompleteType(NamedDecl **Def) const {
908 switch (CanonicalType->getTypeClass()) {
909 default: return false;
911 // Void is the only incomplete builtin type. Per C99 6.2.5p19, it can never
915 EnumDecl *EnumD = cast<EnumType>(CanonicalType)->getDecl();
919 // An enumeration with fixed underlying type is complete (C++0x 7.2p3).
920 if (EnumD->isFixed())
923 return !EnumD->isCompleteDefinition();
926 // A tagged type (struct/union/enum/class) is incomplete if the decl is a
927 // forward declaration, but not a full definition (C99 6.2.5p22).
928 RecordDecl *Rec = cast<RecordType>(CanonicalType)->getDecl();
931 return !Rec->isCompleteDefinition();
934 // An array is incomplete if its element type is incomplete
935 // (C++ [dcl.array]p1).
936 // We don't handle variable arrays (they're not allowed in C++) or
937 // dependent-sized arrays (dependent types are never treated as incomplete).
938 return cast<ArrayType>(CanonicalType)->getElementType()
939 ->isIncompleteType(Def);
940 case IncompleteArray:
941 // An array of unknown size is an incomplete type (C99 6.2.5p22).
944 return cast<ObjCObjectType>(CanonicalType)->getBaseType()
945 ->isIncompleteType(Def);
946 case ObjCInterface: {
947 // ObjC interfaces are incomplete if they are @class, not @interface.
948 ObjCInterfaceDecl *Interface
949 = cast<ObjCInterfaceType>(CanonicalType)->getDecl();
952 return !Interface->hasDefinition();
957 bool QualType::isPODType(ASTContext &Context) const {
958 // C++11 has a more relaxed definition of POD.
959 if (Context.getLangOpts().CPlusPlus11)
960 return isCXX11PODType(Context);
962 return isCXX98PODType(Context);
965 bool QualType::isCXX98PODType(ASTContext &Context) const {
966 // The compiler shouldn't query this for incomplete types, but the user might.
967 // We return false for that case. Except for incomplete arrays of PODs, which
968 // are PODs according to the standard.
972 if ((*this)->isIncompleteArrayType())
973 return Context.getBaseElementType(*this).isCXX98PODType(Context);
975 if ((*this)->isIncompleteType())
978 if (Context.getLangOpts().ObjCAutoRefCount) {
979 switch (getObjCLifetime()) {
980 case Qualifiers::OCL_ExplicitNone:
983 case Qualifiers::OCL_Strong:
984 case Qualifiers::OCL_Weak:
985 case Qualifiers::OCL_Autoreleasing:
988 case Qualifiers::OCL_None:
993 QualType CanonicalType = getTypePtr()->CanonicalType;
994 switch (CanonicalType->getTypeClass()) {
995 // Everything not explicitly mentioned is not POD.
996 default: return false;
997 case Type::VariableArray:
998 case Type::ConstantArray:
999 // IncompleteArray is handled above.
1000 return Context.getBaseElementType(*this).isCXX98PODType(Context);
1002 case Type::ObjCObjectPointer:
1003 case Type::BlockPointer:
1007 case Type::MemberPointer:
1009 case Type::ExtVector:
1016 if (CXXRecordDecl *ClassDecl
1017 = dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
1018 return ClassDecl->isPOD();
1020 // C struct/union is POD.
1025 bool QualType::isTrivialType(ASTContext &Context) const {
1026 // The compiler shouldn't query this for incomplete types, but the user might.
1027 // We return false for that case. Except for incomplete arrays of PODs, which
1028 // are PODs according to the standard.
1032 if ((*this)->isArrayType())
1033 return Context.getBaseElementType(*this).isTrivialType(Context);
1035 // Return false for incomplete types after skipping any incomplete array
1036 // types which are expressly allowed by the standard and thus our API.
1037 if ((*this)->isIncompleteType())
1040 if (Context.getLangOpts().ObjCAutoRefCount) {
1041 switch (getObjCLifetime()) {
1042 case Qualifiers::OCL_ExplicitNone:
1045 case Qualifiers::OCL_Strong:
1046 case Qualifiers::OCL_Weak:
1047 case Qualifiers::OCL_Autoreleasing:
1050 case Qualifiers::OCL_None:
1051 if ((*this)->isObjCLifetimeType())
1057 QualType CanonicalType = getTypePtr()->CanonicalType;
1058 if (CanonicalType->isDependentType())
1061 // C++0x [basic.types]p9:
1062 // Scalar types, trivial class types, arrays of such types, and
1063 // cv-qualified versions of these types are collectively called trivial
1066 // As an extension, Clang treats vector types as Scalar types.
1067 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
1069 if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
1070 if (const CXXRecordDecl *ClassDecl =
1071 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1073 // A trivial class is a class that has a default constructor,
1074 // has no non-trivial default constructors, and is trivially
1076 return ClassDecl->hasDefaultConstructor() &&
1077 !ClassDecl->hasNonTrivialDefaultConstructor() &&
1078 ClassDecl->isTriviallyCopyable();
1084 // No other types can match.
1088 bool QualType::isTriviallyCopyableType(ASTContext &Context) const {
1089 if ((*this)->isArrayType())
1090 return Context.getBaseElementType(*this).isTriviallyCopyableType(Context);
1092 if (Context.getLangOpts().ObjCAutoRefCount) {
1093 switch (getObjCLifetime()) {
1094 case Qualifiers::OCL_ExplicitNone:
1097 case Qualifiers::OCL_Strong:
1098 case Qualifiers::OCL_Weak:
1099 case Qualifiers::OCL_Autoreleasing:
1102 case Qualifiers::OCL_None:
1103 if ((*this)->isObjCLifetimeType())
1109 // C++11 [basic.types]p9
1110 // Scalar types, trivially copyable class types, arrays of such types, and
1111 // non-volatile const-qualified versions of these types are collectively
1112 // called trivially copyable types.
1114 QualType CanonicalType = getCanonicalType();
1115 if (CanonicalType->isDependentType())
1118 if (CanonicalType.isVolatileQualified())
1121 // Return false for incomplete types after skipping any incomplete array types
1122 // which are expressly allowed by the standard and thus our API.
1123 if (CanonicalType->isIncompleteType())
1126 // As an extension, Clang treats vector types as Scalar types.
1127 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
1130 if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
1131 if (const CXXRecordDecl *ClassDecl =
1132 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1133 if (!ClassDecl->isTriviallyCopyable()) return false;
1139 // No other types can match.
1145 bool Type::isLiteralType(const ASTContext &Ctx) const {
1146 if (isDependentType())
1149 // C++1y [basic.types]p10:
1150 // A type is a literal type if it is:
1152 if (Ctx.getLangOpts().CPlusPlus14 && isVoidType())
1155 // C++11 [basic.types]p10:
1156 // A type is a literal type if it is:
1158 // -- an array of literal type other than an array of runtime bound; or
1159 if (isVariableArrayType())
1161 const Type *BaseTy = getBaseElementTypeUnsafe();
1162 assert(BaseTy && "NULL element type");
1164 // Return false for incomplete types after skipping any incomplete array
1165 // types; those are expressly allowed by the standard and thus our API.
1166 if (BaseTy->isIncompleteType())
1169 // C++11 [basic.types]p10:
1170 // A type is a literal type if it is:
1171 // -- a scalar type; or
1172 // As an extension, Clang treats vector types and complex types as
1174 if (BaseTy->isScalarType() || BaseTy->isVectorType() ||
1175 BaseTy->isAnyComplexType())
1177 // -- a reference type; or
1178 if (BaseTy->isReferenceType())
1180 // -- a class type that has all of the following properties:
1181 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1182 // -- a trivial destructor,
1183 // -- every constructor call and full-expression in the
1184 // brace-or-equal-initializers for non-static data members (if any)
1185 // is a constant expression,
1186 // -- it is an aggregate type or has at least one constexpr
1187 // constructor or constructor template that is not a copy or move
1189 // -- all non-static data members and base classes of literal types
1191 // We resolve DR1361 by ignoring the second bullet.
1192 if (const CXXRecordDecl *ClassDecl =
1193 dyn_cast<CXXRecordDecl>(RT->getDecl()))
1194 return ClassDecl->isLiteral();
1199 // We treat _Atomic T as a literal type if T is a literal type.
1200 if (const AtomicType *AT = BaseTy->getAs<AtomicType>())
1201 return AT->getValueType()->isLiteralType(Ctx);
1203 // If this type hasn't been deduced yet, then conservatively assume that
1204 // it'll work out to be a literal type.
1205 if (isa<AutoType>(BaseTy->getCanonicalTypeInternal()))
1211 bool Type::isStandardLayoutType() const {
1212 if (isDependentType())
1215 // C++0x [basic.types]p9:
1216 // Scalar types, standard-layout class types, arrays of such types, and
1217 // cv-qualified versions of these types are collectively called
1218 // standard-layout types.
1219 const Type *BaseTy = getBaseElementTypeUnsafe();
1220 assert(BaseTy && "NULL element type");
1222 // Return false for incomplete types after skipping any incomplete array
1223 // types which are expressly allowed by the standard and thus our API.
1224 if (BaseTy->isIncompleteType())
1227 // As an extension, Clang treats vector types as Scalar types.
1228 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
1229 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1230 if (const CXXRecordDecl *ClassDecl =
1231 dyn_cast<CXXRecordDecl>(RT->getDecl()))
1232 if (!ClassDecl->isStandardLayout())
1235 // Default to 'true' for non-C++ class types.
1236 // FIXME: This is a bit dubious, but plain C structs should trivially meet
1237 // all the requirements of standard layout classes.
1241 // No other types can match.
1245 // This is effectively the intersection of isTrivialType and
1246 // isStandardLayoutType. We implement it directly to avoid redundant
1247 // conversions from a type to a CXXRecordDecl.
1248 bool QualType::isCXX11PODType(ASTContext &Context) const {
1249 const Type *ty = getTypePtr();
1250 if (ty->isDependentType())
1253 if (Context.getLangOpts().ObjCAutoRefCount) {
1254 switch (getObjCLifetime()) {
1255 case Qualifiers::OCL_ExplicitNone:
1258 case Qualifiers::OCL_Strong:
1259 case Qualifiers::OCL_Weak:
1260 case Qualifiers::OCL_Autoreleasing:
1263 case Qualifiers::OCL_None:
1268 // C++11 [basic.types]p9:
1269 // Scalar types, POD classes, arrays of such types, and cv-qualified
1270 // versions of these types are collectively called trivial types.
1271 const Type *BaseTy = ty->getBaseElementTypeUnsafe();
1272 assert(BaseTy && "NULL element type");
1274 // Return false for incomplete types after skipping any incomplete array
1275 // types which are expressly allowed by the standard and thus our API.
1276 if (BaseTy->isIncompleteType())
1279 // As an extension, Clang treats vector types as Scalar types.
1280 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
1281 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1282 if (const CXXRecordDecl *ClassDecl =
1283 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1284 // C++11 [class]p10:
1285 // A POD struct is a non-union class that is both a trivial class [...]
1286 if (!ClassDecl->isTrivial()) return false;
1288 // C++11 [class]p10:
1289 // A POD struct is a non-union class that is both a trivial class and
1290 // a standard-layout class [...]
1291 if (!ClassDecl->isStandardLayout()) return false;
1293 // C++11 [class]p10:
1294 // A POD struct is a non-union class that is both a trivial class and
1295 // a standard-layout class, and has no non-static data members of type
1296 // non-POD struct, non-POD union (or array of such types). [...]
1298 // We don't directly query the recursive aspect as the requiremets for
1299 // both standard-layout classes and trivial classes apply recursively
1306 // No other types can match.
1310 bool Type::isPromotableIntegerType() const {
1311 if (const BuiltinType *BT = getAs<BuiltinType>())
1312 switch (BT->getKind()) {
1313 case BuiltinType::Bool:
1314 case BuiltinType::Char_S:
1315 case BuiltinType::Char_U:
1316 case BuiltinType::SChar:
1317 case BuiltinType::UChar:
1318 case BuiltinType::Short:
1319 case BuiltinType::UShort:
1320 case BuiltinType::WChar_S:
1321 case BuiltinType::WChar_U:
1322 case BuiltinType::Char16:
1323 case BuiltinType::Char32:
1329 // Enumerated types are promotable to their compatible integer types
1330 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1331 if (const EnumType *ET = getAs<EnumType>()){
1332 if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull()
1333 || ET->getDecl()->isScoped())
1342 bool Type::isSpecifierType() const {
1343 // Note that this intentionally does not use the canonical type.
1344 switch (getTypeClass()) {
1352 case TemplateTypeParm:
1353 case SubstTemplateTypeParm:
1354 case TemplateSpecialization:
1357 case DependentTemplateSpecialization:
1360 case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers
1367 ElaboratedTypeKeyword
1368 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) {
1370 default: return ETK_None;
1371 case TST_typename: return ETK_Typename;
1372 case TST_class: return ETK_Class;
1373 case TST_struct: return ETK_Struct;
1374 case TST_interface: return ETK_Interface;
1375 case TST_union: return ETK_Union;
1376 case TST_enum: return ETK_Enum;
1381 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
1383 case TST_class: return TTK_Class;
1384 case TST_struct: return TTK_Struct;
1385 case TST_interface: return TTK_Interface;
1386 case TST_union: return TTK_Union;
1387 case TST_enum: return TTK_Enum;
1390 llvm_unreachable("Type specifier is not a tag type kind.");
1393 ElaboratedTypeKeyword
1394 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) {
1396 case TTK_Class: return ETK_Class;
1397 case TTK_Struct: return ETK_Struct;
1398 case TTK_Interface: return ETK_Interface;
1399 case TTK_Union: return ETK_Union;
1400 case TTK_Enum: return ETK_Enum;
1402 llvm_unreachable("Unknown tag type kind.");
1406 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
1408 case ETK_Class: return TTK_Class;
1409 case ETK_Struct: return TTK_Struct;
1410 case ETK_Interface: return TTK_Interface;
1411 case ETK_Union: return TTK_Union;
1412 case ETK_Enum: return TTK_Enum;
1413 case ETK_None: // Fall through.
1415 llvm_unreachable("Elaborated type keyword is not a tag type kind.");
1417 llvm_unreachable("Unknown elaborated type keyword.");
1421 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
1433 llvm_unreachable("Unknown elaborated type keyword.");
1436 StringRef TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) {
1438 case ETK_None: return "";
1439 case ETK_Typename: return "typename";
1440 case ETK_Class: return "class";
1441 case ETK_Struct: return "struct";
1442 case ETK_Interface: return "__interface";
1443 case ETK_Union: return "union";
1444 case ETK_Enum: return "enum";
1447 llvm_unreachable("Unknown elaborated type keyword.");
1450 DependentTemplateSpecializationType::DependentTemplateSpecializationType(
1451 ElaboratedTypeKeyword Keyword,
1452 NestedNameSpecifier *NNS, const IdentifierInfo *Name,
1453 unsigned NumArgs, const TemplateArgument *Args,
1455 : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true, true,
1456 /*VariablyModified=*/false,
1457 NNS && NNS->containsUnexpandedParameterPack()),
1458 NNS(NNS), Name(Name), NumArgs(NumArgs) {
1459 assert((!NNS || NNS->isDependent()) &&
1460 "DependentTemplateSpecializatonType requires dependent qualifier");
1461 for (unsigned I = 0; I != NumArgs; ++I) {
1462 if (Args[I].containsUnexpandedParameterPack())
1463 setContainsUnexpandedParameterPack();
1465 new (&getArgBuffer()[I]) TemplateArgument(Args[I]);
1470 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1471 const ASTContext &Context,
1472 ElaboratedTypeKeyword Keyword,
1473 NestedNameSpecifier *Qualifier,
1474 const IdentifierInfo *Name,
1476 const TemplateArgument *Args) {
1477 ID.AddInteger(Keyword);
1478 ID.AddPointer(Qualifier);
1479 ID.AddPointer(Name);
1480 for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1481 Args[Idx].Profile(ID, Context);
1484 bool Type::isElaboratedTypeSpecifier() const {
1485 ElaboratedTypeKeyword Keyword;
1486 if (const ElaboratedType *Elab = dyn_cast<ElaboratedType>(this))
1487 Keyword = Elab->getKeyword();
1488 else if (const DependentNameType *DepName = dyn_cast<DependentNameType>(this))
1489 Keyword = DepName->getKeyword();
1490 else if (const DependentTemplateSpecializationType *DepTST =
1491 dyn_cast<DependentTemplateSpecializationType>(this))
1492 Keyword = DepTST->getKeyword();
1496 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
1499 const char *Type::getTypeClassName() const {
1500 switch (TypeBits.TC) {
1501 #define ABSTRACT_TYPE(Derived, Base)
1502 #define TYPE(Derived, Base) case Derived: return #Derived;
1503 #include "clang/AST/TypeNodes.def"
1506 llvm_unreachable("Invalid type class.");
1509 StringRef BuiltinType::getName(const PrintingPolicy &Policy) const {
1510 switch (getKind()) {
1511 case Void: return "void";
1512 case Bool: return Policy.Bool ? "bool" : "_Bool";
1513 case Char_S: return "char";
1514 case Char_U: return "char";
1515 case SChar: return "signed char";
1516 case Short: return "short";
1517 case Int: return "int";
1518 case Long: return "long";
1519 case LongLong: return "long long";
1520 case Int128: return "__int128";
1521 case UChar: return "unsigned char";
1522 case UShort: return "unsigned short";
1523 case UInt: return "unsigned int";
1524 case ULong: return "unsigned long";
1525 case ULongLong: return "unsigned long long";
1526 case UInt128: return "unsigned __int128";
1527 case Half: return Policy.Half ? "half" : "__fp16";
1528 case Float: return "float";
1529 case Double: return "double";
1530 case LongDouble: return "long double";
1532 case WChar_U: return Policy.MSWChar ? "__wchar_t" : "wchar_t";
1533 case Char16: return "char16_t";
1534 case Char32: return "char32_t";
1535 case NullPtr: return "nullptr_t";
1536 case Overload: return "<overloaded function type>";
1537 case BoundMember: return "<bound member function type>";
1538 case PseudoObject: return "<pseudo-object type>";
1539 case Dependent: return "<dependent type>";
1540 case UnknownAny: return "<unknown type>";
1541 case ARCUnbridgedCast: return "<ARC unbridged cast type>";
1542 case BuiltinFn: return "<builtin fn type>";
1543 case ObjCId: return "id";
1544 case ObjCClass: return "Class";
1545 case ObjCSel: return "SEL";
1546 case OCLImage1d: return "image1d_t";
1547 case OCLImage1dArray: return "image1d_array_t";
1548 case OCLImage1dBuffer: return "image1d_buffer_t";
1549 case OCLImage2d: return "image2d_t";
1550 case OCLImage2dArray: return "image2d_array_t";
1551 case OCLImage3d: return "image3d_t";
1552 case OCLSampler: return "sampler_t";
1553 case OCLEvent: return "event_t";
1556 llvm_unreachable("Invalid builtin type.");
1559 QualType QualType::getNonLValueExprType(const ASTContext &Context) const {
1560 if (const ReferenceType *RefType = getTypePtr()->getAs<ReferenceType>())
1561 return RefType->getPointeeType();
1563 // C++0x [basic.lval]:
1564 // Class prvalues can have cv-qualified types; non-class prvalues always
1565 // have cv-unqualified types.
1567 // See also C99 6.3.2.1p2.
1568 if (!Context.getLangOpts().CPlusPlus ||
1569 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
1570 return getUnqualifiedType();
1575 StringRef FunctionType::getNameForCallConv(CallingConv CC) {
1577 case CC_C: return "cdecl";
1578 case CC_X86StdCall: return "stdcall";
1579 case CC_X86FastCall: return "fastcall";
1580 case CC_X86ThisCall: return "thiscall";
1581 case CC_X86Pascal: return "pascal";
1582 case CC_X86VectorCall: return "vectorcall";
1583 case CC_X86_64Win64: return "ms_abi";
1584 case CC_X86_64SysV: return "sysv_abi";
1585 case CC_AAPCS: return "aapcs";
1586 case CC_AAPCS_VFP: return "aapcs-vfp";
1587 case CC_IntelOclBicc: return "intel_ocl_bicc";
1588 case CC_SpirFunction: return "spir_function";
1589 case CC_SpirKernel: return "spir_kernel";
1592 llvm_unreachable("Invalid calling convention.");
1595 FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> params,
1597 const ExtProtoInfo &epi)
1598 : FunctionType(FunctionProto, result, canonical,
1599 result->isDependentType(),
1600 result->isInstantiationDependentType(),
1601 result->isVariablyModifiedType(),
1602 result->containsUnexpandedParameterPack(), epi.ExtInfo),
1603 NumParams(params.size()),
1604 NumExceptions(epi.ExceptionSpec.Exceptions.size()),
1605 ExceptionSpecType(epi.ExceptionSpec.Type),
1606 HasAnyConsumedParams(epi.ConsumedParameters != nullptr),
1607 Variadic(epi.Variadic), HasTrailingReturn(epi.HasTrailingReturn) {
1608 assert(NumParams == params.size() && "function has too many parameters");
1610 FunctionTypeBits.TypeQuals = epi.TypeQuals;
1611 FunctionTypeBits.RefQualifier = epi.RefQualifier;
1613 // Fill in the trailing argument array.
1614 QualType *argSlot = reinterpret_cast<QualType*>(this+1);
1615 for (unsigned i = 0; i != NumParams; ++i) {
1616 if (params[i]->isDependentType())
1618 else if (params[i]->isInstantiationDependentType())
1619 setInstantiationDependent();
1621 if (params[i]->containsUnexpandedParameterPack())
1622 setContainsUnexpandedParameterPack();
1624 argSlot[i] = params[i];
1627 if (getExceptionSpecType() == EST_Dynamic) {
1628 // Fill in the exception array.
1629 QualType *exnSlot = argSlot + NumParams;
1631 for (QualType ExceptionType : epi.ExceptionSpec.Exceptions) {
1632 // Note that a dependent exception specification does *not* make
1633 // a type dependent; it's not even part of the C++ type system.
1634 if (ExceptionType->isInstantiationDependentType())
1635 setInstantiationDependent();
1637 if (ExceptionType->containsUnexpandedParameterPack())
1638 setContainsUnexpandedParameterPack();
1640 exnSlot[I++] = ExceptionType;
1642 } else if (getExceptionSpecType() == EST_ComputedNoexcept) {
1643 // Store the noexcept expression and context.
1644 Expr **noexSlot = reinterpret_cast<Expr **>(argSlot + NumParams);
1645 *noexSlot = epi.ExceptionSpec.NoexceptExpr;
1647 if (epi.ExceptionSpec.NoexceptExpr) {
1648 if (epi.ExceptionSpec.NoexceptExpr->isValueDependent() ||
1649 epi.ExceptionSpec.NoexceptExpr->isInstantiationDependent())
1650 setInstantiationDependent();
1652 if (epi.ExceptionSpec.NoexceptExpr->containsUnexpandedParameterPack())
1653 setContainsUnexpandedParameterPack();
1655 } else if (getExceptionSpecType() == EST_Uninstantiated) {
1656 // Store the function decl from which we will resolve our
1657 // exception specification.
1658 FunctionDecl **slot =
1659 reinterpret_cast<FunctionDecl **>(argSlot + NumParams);
1660 slot[0] = epi.ExceptionSpec.SourceDecl;
1661 slot[1] = epi.ExceptionSpec.SourceTemplate;
1662 // This exception specification doesn't make the type dependent, because
1663 // it's not instantiated as part of instantiating the type.
1664 } else if (getExceptionSpecType() == EST_Unevaluated) {
1665 // Store the function decl from which we will resolve our
1666 // exception specification.
1667 FunctionDecl **slot =
1668 reinterpret_cast<FunctionDecl **>(argSlot + NumParams);
1669 slot[0] = epi.ExceptionSpec.SourceDecl;
1672 if (epi.ConsumedParameters) {
1673 bool *consumedParams = const_cast<bool *>(getConsumedParamsBuffer());
1674 for (unsigned i = 0; i != NumParams; ++i)
1675 consumedParams[i] = epi.ConsumedParameters[i];
1679 bool FunctionProtoType::hasDependentExceptionSpec() const {
1680 if (Expr *NE = getNoexceptExpr())
1681 return NE->isValueDependent();
1682 for (QualType ET : exceptions())
1683 // A pack expansion with a non-dependent pattern is still dependent,
1684 // because we don't know whether the pattern is in the exception spec
1685 // or not (that depends on whether the pack has 0 expansions).
1686 if (ET->isDependentType() || ET->getAs<PackExpansionType>())
1691 FunctionProtoType::NoexceptResult
1692 FunctionProtoType::getNoexceptSpec(const ASTContext &ctx) const {
1693 ExceptionSpecificationType est = getExceptionSpecType();
1694 if (est == EST_BasicNoexcept)
1697 if (est != EST_ComputedNoexcept)
1698 return NR_NoNoexcept;
1700 Expr *noexceptExpr = getNoexceptExpr();
1702 return NR_BadNoexcept;
1703 if (noexceptExpr->isValueDependent())
1704 return NR_Dependent;
1707 bool isICE = noexceptExpr->isIntegerConstantExpr(value, ctx, nullptr,
1708 /*evaluated*/false);
1710 assert(isICE && "AST should not contain bad noexcept expressions.");
1712 return value.getBoolValue() ? NR_Nothrow : NR_Throw;
1715 bool FunctionProtoType::isNothrow(const ASTContext &Ctx,
1716 bool ResultIfDependent) const {
1717 ExceptionSpecificationType EST = getExceptionSpecType();
1718 assert(EST != EST_Unevaluated && EST != EST_Uninstantiated);
1719 if (EST == EST_DynamicNone || EST == EST_BasicNoexcept)
1722 if (EST == EST_Dynamic && ResultIfDependent) {
1723 // A dynamic exception specification is throwing unless every exception
1724 // type is an (unexpanded) pack expansion type.
1725 for (unsigned I = 0, N = NumExceptions; I != N; ++I)
1726 if (!getExceptionType(I)->getAs<PackExpansionType>())
1728 return ResultIfDependent;
1731 if (EST != EST_ComputedNoexcept)
1734 NoexceptResult NR = getNoexceptSpec(Ctx);
1735 if (NR == NR_Dependent)
1736 return ResultIfDependent;
1737 return NR == NR_Nothrow;
1740 bool FunctionProtoType::isTemplateVariadic() const {
1741 for (unsigned ArgIdx = getNumParams(); ArgIdx; --ArgIdx)
1742 if (isa<PackExpansionType>(getParamType(ArgIdx - 1)))
1748 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
1749 const QualType *ArgTys, unsigned NumParams,
1750 const ExtProtoInfo &epi,
1751 const ASTContext &Context) {
1753 // We have to be careful not to get ambiguous profile encodings.
1754 // Note that valid type pointers are never ambiguous with anything else.
1756 // The encoding grammar begins:
1757 // type type* bool int bool
1758 // If that final bool is true, then there is a section for the EH spec:
1760 // This is followed by an optional "consumed argument" section of the
1761 // same length as the first type sequence:
1763 // Finally, we have the ext info and trailing return type flag:
1766 // There is no ambiguity between the consumed arguments and an empty EH
1767 // spec because of the leading 'bool' which unambiguously indicates
1768 // whether the following bool is the EH spec or part of the arguments.
1770 ID.AddPointer(Result.getAsOpaquePtr());
1771 for (unsigned i = 0; i != NumParams; ++i)
1772 ID.AddPointer(ArgTys[i].getAsOpaquePtr());
1773 // This method is relatively performance sensitive, so as a performance
1774 // shortcut, use one AddInteger call instead of four for the next four
1776 assert(!(unsigned(epi.Variadic) & ~1) &&
1777 !(unsigned(epi.TypeQuals) & ~255) &&
1778 !(unsigned(epi.RefQualifier) & ~3) &&
1779 !(unsigned(epi.ExceptionSpec.Type) & ~15) &&
1780 "Values larger than expected.");
1781 ID.AddInteger(unsigned(epi.Variadic) +
1782 (epi.TypeQuals << 1) +
1783 (epi.RefQualifier << 9) +
1784 (epi.ExceptionSpec.Type << 11));
1785 if (epi.ExceptionSpec.Type == EST_Dynamic) {
1786 for (QualType Ex : epi.ExceptionSpec.Exceptions)
1787 ID.AddPointer(Ex.getAsOpaquePtr());
1788 } else if (epi.ExceptionSpec.Type == EST_ComputedNoexcept &&
1789 epi.ExceptionSpec.NoexceptExpr) {
1790 epi.ExceptionSpec.NoexceptExpr->Profile(ID, Context, false);
1791 } else if (epi.ExceptionSpec.Type == EST_Uninstantiated ||
1792 epi.ExceptionSpec.Type == EST_Unevaluated) {
1793 ID.AddPointer(epi.ExceptionSpec.SourceDecl->getCanonicalDecl());
1795 if (epi.ConsumedParameters) {
1796 for (unsigned i = 0; i != NumParams; ++i)
1797 ID.AddBoolean(epi.ConsumedParameters[i]);
1799 epi.ExtInfo.Profile(ID);
1800 ID.AddBoolean(epi.HasTrailingReturn);
1803 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
1804 const ASTContext &Ctx) {
1805 Profile(ID, getReturnType(), param_type_begin(), NumParams, getExtProtoInfo(),
1809 QualType TypedefType::desugar() const {
1810 return getDecl()->getUnderlyingType();
1813 TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
1814 : Type(TypeOfExpr, can, E->isTypeDependent(),
1815 E->isInstantiationDependent(),
1816 E->getType()->isVariablyModifiedType(),
1817 E->containsUnexpandedParameterPack()),
1821 bool TypeOfExprType::isSugared() const {
1822 return !TOExpr->isTypeDependent();
1825 QualType TypeOfExprType::desugar() const {
1827 return getUnderlyingExpr()->getType();
1829 return QualType(this, 0);
1832 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
1833 const ASTContext &Context, Expr *E) {
1834 E->Profile(ID, Context, true);
1837 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
1838 // C++11 [temp.type]p2: "If an expression e involves a template parameter,
1839 // decltype(e) denotes a unique dependent type." Hence a decltype type is
1840 // type-dependent even if its expression is only instantiation-dependent.
1841 : Type(Decltype, can, E->isInstantiationDependent(),
1842 E->isInstantiationDependent(),
1843 E->getType()->isVariablyModifiedType(),
1844 E->containsUnexpandedParameterPack()),
1846 UnderlyingType(underlyingType) {
1849 bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); }
1851 QualType DecltypeType::desugar() const {
1853 return getUnderlyingType();
1855 return QualType(this, 0);
1858 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E)
1859 : DecltypeType(E, Context.DependentTy), Context(Context) { }
1861 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
1862 const ASTContext &Context, Expr *E) {
1863 E->Profile(ID, Context, true);
1866 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
1867 : Type(TC, can, D->isDependentType(),
1868 /*InstantiationDependent=*/D->isDependentType(),
1869 /*VariablyModified=*/false,
1870 /*ContainsUnexpandedParameterPack=*/false),
1871 decl(const_cast<TagDecl*>(D)) {}
1873 static TagDecl *getInterestingTagDecl(TagDecl *decl) {
1874 for (auto I : decl->redecls()) {
1875 if (I->isCompleteDefinition() || I->isBeingDefined())
1878 // If there's no definition (not even in progress), return what we have.
1882 UnaryTransformType::UnaryTransformType(QualType BaseType,
1883 QualType UnderlyingType,
1885 QualType CanonicalType)
1886 : Type(UnaryTransform, CanonicalType, UnderlyingType->isDependentType(),
1887 UnderlyingType->isInstantiationDependentType(),
1888 UnderlyingType->isVariablyModifiedType(),
1889 BaseType->containsUnexpandedParameterPack())
1890 , BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind)
1893 TagDecl *TagType::getDecl() const {
1894 return getInterestingTagDecl(decl);
1897 bool TagType::isBeingDefined() const {
1898 return getDecl()->isBeingDefined();
1901 bool AttributedType::isMSTypeSpec() const {
1902 switch (getAttrKind()) {
1903 default: return false;
1910 llvm_unreachable("invalid attr kind");
1913 bool AttributedType::isCallingConv() const {
1914 switch (getAttrKind()) {
1919 case attr_address_space:
1921 case attr_vector_size:
1922 case attr_neon_vector_type:
1923 case attr_neon_polyvector_type:
1925 case attr_objc_ownership:
1929 case attr_null_unspecified:
1937 case attr_vectorcall:
1941 case attr_inteloclbicc:
1944 llvm_unreachable("invalid attr kind");
1947 CXXRecordDecl *InjectedClassNameType::getDecl() const {
1948 return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
1951 IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
1952 return isCanonicalUnqualified() ? nullptr : getDecl()->getIdentifier();
1955 SubstTemplateTypeParmPackType::
1956 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
1958 const TemplateArgument &ArgPack)
1959 : Type(SubstTemplateTypeParmPack, Canon, true, true, false, true),
1961 Arguments(ArgPack.pack_begin()), NumArguments(ArgPack.pack_size())
1965 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const {
1966 return TemplateArgument(Arguments, NumArguments);
1969 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
1970 Profile(ID, getReplacedParameter(), getArgumentPack());
1973 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
1974 const TemplateTypeParmType *Replaced,
1975 const TemplateArgument &ArgPack) {
1976 ID.AddPointer(Replaced);
1977 ID.AddInteger(ArgPack.pack_size());
1978 for (const auto &P : ArgPack.pack_elements())
1979 ID.AddPointer(P.getAsType().getAsOpaquePtr());
1982 bool TemplateSpecializationType::
1983 anyDependentTemplateArguments(const TemplateArgumentListInfo &Args,
1984 bool &InstantiationDependent) {
1985 return anyDependentTemplateArguments(Args.getArgumentArray(), Args.size(),
1986 InstantiationDependent);
1989 bool TemplateSpecializationType::
1990 anyDependentTemplateArguments(const TemplateArgumentLoc *Args, unsigned N,
1991 bool &InstantiationDependent) {
1992 for (unsigned i = 0; i != N; ++i) {
1993 if (Args[i].getArgument().isDependent()) {
1994 InstantiationDependent = true;
1998 if (Args[i].getArgument().isInstantiationDependent())
1999 InstantiationDependent = true;
2004 TemplateSpecializationType::
2005 TemplateSpecializationType(TemplateName T,
2006 const TemplateArgument *Args, unsigned NumArgs,
2007 QualType Canon, QualType AliasedType)
2008 : Type(TemplateSpecialization,
2009 Canon.isNull()? QualType(this, 0) : Canon,
2010 Canon.isNull()? true : Canon->isDependentType(),
2011 Canon.isNull()? true : Canon->isInstantiationDependentType(),
2013 T.containsUnexpandedParameterPack()),
2014 Template(T), NumArgs(NumArgs), TypeAlias(!AliasedType.isNull()) {
2015 assert(!T.getAsDependentTemplateName() &&
2016 "Use DependentTemplateSpecializationType for dependent template-name");
2017 assert((T.getKind() == TemplateName::Template ||
2018 T.getKind() == TemplateName::SubstTemplateTemplateParm ||
2019 T.getKind() == TemplateName::SubstTemplateTemplateParmPack) &&
2020 "Unexpected template name for TemplateSpecializationType");
2022 TemplateArgument *TemplateArgs
2023 = reinterpret_cast<TemplateArgument *>(this + 1);
2024 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
2025 // Update instantiation-dependent and variably-modified bits.
2026 // If the canonical type exists and is non-dependent, the template
2027 // specialization type can be non-dependent even if one of the type
2028 // arguments is. Given:
2029 // template<typename T> using U = int;
2030 // U<T> is always non-dependent, irrespective of the type T.
2031 // However, U<Ts> contains an unexpanded parameter pack, even though
2032 // its expansion (and thus its desugared type) doesn't.
2033 if (Args[Arg].isInstantiationDependent())
2034 setInstantiationDependent();
2035 if (Args[Arg].getKind() == TemplateArgument::Type &&
2036 Args[Arg].getAsType()->isVariablyModifiedType())
2037 setVariablyModified();
2038 if (Args[Arg].containsUnexpandedParameterPack())
2039 setContainsUnexpandedParameterPack();
2040 new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]);
2043 // Store the aliased type if this is a type alias template specialization.
2045 TemplateArgument *Begin = reinterpret_cast<TemplateArgument *>(this + 1);
2046 *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType;
2051 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
2053 const TemplateArgument *Args,
2055 const ASTContext &Context) {
2057 for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
2058 Args[Idx].Profile(ID, Context);
2062 QualifierCollector::apply(const ASTContext &Context, QualType QT) const {
2063 if (!hasNonFastQualifiers())
2064 return QT.withFastQualifiers(getFastQualifiers());
2066 return Context.getQualifiedType(QT, *this);
2070 QualifierCollector::apply(const ASTContext &Context, const Type *T) const {
2071 if (!hasNonFastQualifiers())
2072 return QualType(T, getFastQualifiers());
2074 return Context.getQualifiedType(T, *this);
2077 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
2079 ObjCProtocolDecl * const *Protocols,
2080 unsigned NumProtocols) {
2081 ID.AddPointer(BaseType.getAsOpaquePtr());
2082 for (unsigned i = 0; i != NumProtocols; i++)
2083 ID.AddPointer(Protocols[i]);
2086 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
2087 Profile(ID, getBaseType(), qual_begin(), getNumProtocols());
2092 /// \brief The cached properties of a type.
2093 class CachedProperties {
2098 CachedProperties(Linkage L, bool local) : L(L), local(local) {}
2100 Linkage getLinkage() const { return L; }
2101 bool hasLocalOrUnnamedType() const { return local; }
2103 friend CachedProperties merge(CachedProperties L, CachedProperties R) {
2104 Linkage MergedLinkage = minLinkage(L.L, R.L);
2105 return CachedProperties(MergedLinkage,
2106 L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType());
2111 static CachedProperties computeCachedProperties(const Type *T);
2114 /// The type-property cache. This is templated so as to be
2115 /// instantiated at an internal type to prevent unnecessary symbol
2117 template <class Private> class TypePropertyCache {
2119 static CachedProperties get(QualType T) {
2120 return get(T.getTypePtr());
2123 static CachedProperties get(const Type *T) {
2125 return CachedProperties(T->TypeBits.getLinkage(),
2126 T->TypeBits.hasLocalOrUnnamedType());
2129 static void ensure(const Type *T) {
2130 // If the cache is valid, we're okay.
2131 if (T->TypeBits.isCacheValid()) return;
2133 // If this type is non-canonical, ask its canonical type for the
2134 // relevant information.
2135 if (!T->isCanonicalUnqualified()) {
2136 const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
2138 T->TypeBits.CacheValid = true;
2139 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
2140 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
2144 // Compute the cached properties and then set the cache.
2145 CachedProperties Result = computeCachedProperties(T);
2146 T->TypeBits.CacheValid = true;
2147 T->TypeBits.CachedLinkage = Result.getLinkage();
2148 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
2153 // Instantiate the friend template at a private class. In a
2154 // reasonable implementation, these symbols will be internal.
2155 // It is terrible that this is the best way to accomplish this.
2156 namespace { class Private {}; }
2157 typedef TypePropertyCache<Private> Cache;
2159 static CachedProperties computeCachedProperties(const Type *T) {
2160 switch (T->getTypeClass()) {
2161 #define TYPE(Class,Base)
2162 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
2163 #include "clang/AST/TypeNodes.def"
2164 llvm_unreachable("didn't expect a non-canonical type here");
2166 #define TYPE(Class,Base)
2167 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
2168 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
2169 #include "clang/AST/TypeNodes.def"
2170 // Treat instantiation-dependent types as external.
2171 assert(T->isInstantiationDependentType());
2172 return CachedProperties(ExternalLinkage, false);
2175 // Give non-deduced 'auto' types external linkage. We should only see them
2176 // here in error recovery.
2177 return CachedProperties(ExternalLinkage, false);
2180 // C++ [basic.link]p8:
2181 // A type is said to have linkage if and only if:
2182 // - it is a fundamental type (3.9.1); or
2183 return CachedProperties(ExternalLinkage, false);
2187 const TagDecl *Tag = cast<TagType>(T)->getDecl();
2189 // C++ [basic.link]p8:
2190 // - it is a class or enumeration type that is named (or has a name
2191 // for linkage purposes (7.1.3)) and the name has linkage; or
2192 // - it is a specialization of a class template (14); or
2193 Linkage L = Tag->getLinkageInternal();
2194 bool IsLocalOrUnnamed =
2195 Tag->getDeclContext()->isFunctionOrMethod() ||
2196 !Tag->hasNameForLinkage();
2197 return CachedProperties(L, IsLocalOrUnnamed);
2200 // C++ [basic.link]p8:
2201 // - it is a compound type (3.9.2) other than a class or enumeration,
2202 // compounded exclusively from types that have linkage; or
2204 return Cache::get(cast<ComplexType>(T)->getElementType());
2206 return Cache::get(cast<PointerType>(T)->getPointeeType());
2207 case Type::BlockPointer:
2208 return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
2209 case Type::LValueReference:
2210 case Type::RValueReference:
2211 return Cache::get(cast<ReferenceType>(T)->getPointeeType());
2212 case Type::MemberPointer: {
2213 const MemberPointerType *MPT = cast<MemberPointerType>(T);
2214 return merge(Cache::get(MPT->getClass()),
2215 Cache::get(MPT->getPointeeType()));
2217 case Type::ConstantArray:
2218 case Type::IncompleteArray:
2219 case Type::VariableArray:
2220 return Cache::get(cast<ArrayType>(T)->getElementType());
2222 case Type::ExtVector:
2223 return Cache::get(cast<VectorType>(T)->getElementType());
2224 case Type::FunctionNoProto:
2225 return Cache::get(cast<FunctionType>(T)->getReturnType());
2226 case Type::FunctionProto: {
2227 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2228 CachedProperties result = Cache::get(FPT->getReturnType());
2229 for (const auto &ai : FPT->param_types())
2230 result = merge(result, Cache::get(ai));
2233 case Type::ObjCInterface: {
2234 Linkage L = cast<ObjCInterfaceType>(T)->getDecl()->getLinkageInternal();
2235 return CachedProperties(L, false);
2237 case Type::ObjCObject:
2238 return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
2239 case Type::ObjCObjectPointer:
2240 return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
2242 return Cache::get(cast<AtomicType>(T)->getValueType());
2245 llvm_unreachable("unhandled type class");
2248 /// \brief Determine the linkage of this type.
2249 Linkage Type::getLinkage() const {
2250 Cache::ensure(this);
2251 return TypeBits.getLinkage();
2254 bool Type::hasUnnamedOrLocalType() const {
2255 Cache::ensure(this);
2256 return TypeBits.hasLocalOrUnnamedType();
2259 static LinkageInfo computeLinkageInfo(QualType T);
2261 static LinkageInfo computeLinkageInfo(const Type *T) {
2262 switch (T->getTypeClass()) {
2263 #define TYPE(Class,Base)
2264 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
2265 #include "clang/AST/TypeNodes.def"
2266 llvm_unreachable("didn't expect a non-canonical type here");
2268 #define TYPE(Class,Base)
2269 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
2270 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
2271 #include "clang/AST/TypeNodes.def"
2272 // Treat instantiation-dependent types as external.
2273 assert(T->isInstantiationDependentType());
2274 return LinkageInfo::external();
2277 return LinkageInfo::external();
2280 return LinkageInfo::external();
2284 return cast<TagType>(T)->getDecl()->getLinkageAndVisibility();
2287 return computeLinkageInfo(cast<ComplexType>(T)->getElementType());
2289 return computeLinkageInfo(cast<PointerType>(T)->getPointeeType());
2290 case Type::BlockPointer:
2291 return computeLinkageInfo(cast<BlockPointerType>(T)->getPointeeType());
2292 case Type::LValueReference:
2293 case Type::RValueReference:
2294 return computeLinkageInfo(cast<ReferenceType>(T)->getPointeeType());
2295 case Type::MemberPointer: {
2296 const MemberPointerType *MPT = cast<MemberPointerType>(T);
2297 LinkageInfo LV = computeLinkageInfo(MPT->getClass());
2298 LV.merge(computeLinkageInfo(MPT->getPointeeType()));
2301 case Type::ConstantArray:
2302 case Type::IncompleteArray:
2303 case Type::VariableArray:
2304 return computeLinkageInfo(cast<ArrayType>(T)->getElementType());
2306 case Type::ExtVector:
2307 return computeLinkageInfo(cast<VectorType>(T)->getElementType());
2308 case Type::FunctionNoProto:
2309 return computeLinkageInfo(cast<FunctionType>(T)->getReturnType());
2310 case Type::FunctionProto: {
2311 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2312 LinkageInfo LV = computeLinkageInfo(FPT->getReturnType());
2313 for (const auto &ai : FPT->param_types())
2314 LV.merge(computeLinkageInfo(ai));
2317 case Type::ObjCInterface:
2318 return cast<ObjCInterfaceType>(T)->getDecl()->getLinkageAndVisibility();
2319 case Type::ObjCObject:
2320 return computeLinkageInfo(cast<ObjCObjectType>(T)->getBaseType());
2321 case Type::ObjCObjectPointer:
2322 return computeLinkageInfo(cast<ObjCObjectPointerType>(T)->getPointeeType());
2324 return computeLinkageInfo(cast<AtomicType>(T)->getValueType());
2327 llvm_unreachable("unhandled type class");
2330 static LinkageInfo computeLinkageInfo(QualType T) {
2331 return computeLinkageInfo(T.getTypePtr());
2334 bool Type::isLinkageValid() const {
2335 if (!TypeBits.isCacheValid())
2338 return computeLinkageInfo(getCanonicalTypeInternal()).getLinkage() ==
2339 TypeBits.getLinkage();
2342 LinkageInfo Type::getLinkageAndVisibility() const {
2343 if (!isCanonicalUnqualified())
2344 return computeLinkageInfo(getCanonicalTypeInternal());
2346 LinkageInfo LV = computeLinkageInfo(this);
2347 assert(LV.getLinkage() == getLinkage());
2351 Optional<NullabilityKind> Type::getNullability(const ASTContext &context) const {
2352 QualType type(this, 0);
2354 // Check whether this is an attributed type with nullability
2356 if (auto attributed = dyn_cast<AttributedType>(type.getTypePtr())) {
2357 if (auto nullability = attributed->getImmediateNullability())
2361 // Desugar the type. If desugaring does nothing, we're done.
2362 QualType desugared = type.getSingleStepDesugaredType(context);
2363 if (desugared.getTypePtr() == type.getTypePtr())
2370 bool Type::canHaveNullability() const {
2371 QualType type = getCanonicalTypeInternal();
2373 switch (type->getTypeClass()) {
2374 // We'll only see canonical types here.
2375 #define NON_CANONICAL_TYPE(Class, Parent) \
2377 llvm_unreachable("non-canonical type");
2378 #define TYPE(Class, Parent)
2379 #include "clang/AST/TypeNodes.def"
2383 case Type::BlockPointer:
2384 case Type::MemberPointer:
2385 case Type::ObjCObjectPointer:
2388 // Dependent types that could instantiate to pointer types.
2389 case Type::UnresolvedUsing:
2390 case Type::TypeOfExpr:
2392 case Type::Decltype:
2393 case Type::UnaryTransform:
2394 case Type::TemplateTypeParm:
2395 case Type::SubstTemplateTypeParmPack:
2396 case Type::DependentName:
2397 case Type::DependentTemplateSpecialization:
2400 // Dependent template specializations can instantiate to pointer
2401 // types unless they're known to be specializations of a class
2403 case Type::TemplateSpecialization:
2404 if (TemplateDecl *templateDecl
2405 = cast<TemplateSpecializationType>(type.getTypePtr())
2406 ->getTemplateName().getAsTemplateDecl()) {
2407 if (isa<ClassTemplateDecl>(templateDecl))
2412 // auto is considered dependent when it isn't deduced.
2414 return !cast<AutoType>(type.getTypePtr())->isDeduced();
2417 switch (cast<BuiltinType>(type.getTypePtr())->getKind()) {
2418 // Signed, unsigned, and floating-point types cannot have nullability.
2419 #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
2420 #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
2421 #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
2422 #define BUILTIN_TYPE(Id, SingletonId)
2423 #include "clang/AST/BuiltinTypes.def"
2426 // Dependent types that could instantiate to a pointer type.
2427 case BuiltinType::Dependent:
2428 case BuiltinType::Overload:
2429 case BuiltinType::BoundMember:
2430 case BuiltinType::PseudoObject:
2431 case BuiltinType::UnknownAny:
2432 case BuiltinType::ARCUnbridgedCast:
2435 case BuiltinType::Void:
2436 case BuiltinType::ObjCId:
2437 case BuiltinType::ObjCClass:
2438 case BuiltinType::ObjCSel:
2439 case BuiltinType::OCLImage1d:
2440 case BuiltinType::OCLImage1dArray:
2441 case BuiltinType::OCLImage1dBuffer:
2442 case BuiltinType::OCLImage2d:
2443 case BuiltinType::OCLImage2dArray:
2444 case BuiltinType::OCLImage3d:
2445 case BuiltinType::OCLSampler:
2446 case BuiltinType::OCLEvent:
2447 case BuiltinType::BuiltinFn:
2448 case BuiltinType::NullPtr:
2452 // Non-pointer types.
2454 case Type::LValueReference:
2455 case Type::RValueReference:
2456 case Type::ConstantArray:
2457 case Type::IncompleteArray:
2458 case Type::VariableArray:
2459 case Type::DependentSizedArray:
2460 case Type::DependentSizedExtVector:
2462 case Type::ExtVector:
2463 case Type::FunctionProto:
2464 case Type::FunctionNoProto:
2467 case Type::InjectedClassName:
2468 case Type::PackExpansion:
2469 case Type::ObjCObject:
2470 case Type::ObjCInterface:
2474 llvm_unreachable("bad type kind!");
2477 llvm::Optional<NullabilityKind> AttributedType::getImmediateNullability() const {
2478 if (getAttrKind() == AttributedType::attr_nonnull)
2479 return NullabilityKind::NonNull;
2480 if (getAttrKind() == AttributedType::attr_nullable)
2481 return NullabilityKind::Nullable;
2482 if (getAttrKind() == AttributedType::attr_null_unspecified)
2483 return NullabilityKind::Unspecified;
2487 Optional<NullabilityKind> AttributedType::stripOuterNullability(QualType &T) {
2488 if (auto attributed = dyn_cast<AttributedType>(T.getTypePtr())) {
2489 if (auto nullability = attributed->getImmediateNullability()) {
2490 T = attributed->getModifiedType();
2498 Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const {
2499 if (isObjCARCImplicitlyUnretainedType())
2500 return Qualifiers::OCL_ExplicitNone;
2501 return Qualifiers::OCL_Strong;
2504 bool Type::isObjCARCImplicitlyUnretainedType() const {
2505 assert(isObjCLifetimeType() &&
2506 "cannot query implicit lifetime for non-inferrable type");
2508 const Type *canon = getCanonicalTypeInternal().getTypePtr();
2510 // Walk down to the base type. We don't care about qualifiers for this.
2511 while (const ArrayType *array = dyn_cast<ArrayType>(canon))
2512 canon = array->getElementType().getTypePtr();
2514 if (const ObjCObjectPointerType *opt
2515 = dyn_cast<ObjCObjectPointerType>(canon)) {
2516 // Class and Class<Protocol> don't require retension.
2517 if (opt->getObjectType()->isObjCClass())
2524 bool Type::isObjCNSObjectType() const {
2525 if (const TypedefType *typedefType = dyn_cast<TypedefType>(this))
2526 return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>();
2529 bool Type::isObjCIndependentClassType() const {
2530 if (const TypedefType *typedefType = dyn_cast<TypedefType>(this))
2531 return typedefType->getDecl()->hasAttr<ObjCIndependentClassAttr>();
2534 bool Type::isObjCRetainableType() const {
2535 return isObjCObjectPointerType() ||
2536 isBlockPointerType() ||
2537 isObjCNSObjectType();
2539 bool Type::isObjCIndirectLifetimeType() const {
2540 if (isObjCLifetimeType())
2542 if (const PointerType *OPT = getAs<PointerType>())
2543 return OPT->getPointeeType()->isObjCIndirectLifetimeType();
2544 if (const ReferenceType *Ref = getAs<ReferenceType>())
2545 return Ref->getPointeeType()->isObjCIndirectLifetimeType();
2546 if (const MemberPointerType *MemPtr = getAs<MemberPointerType>())
2547 return MemPtr->getPointeeType()->isObjCIndirectLifetimeType();
2551 /// Returns true if objects of this type have lifetime semantics under
2553 bool Type::isObjCLifetimeType() const {
2554 const Type *type = this;
2555 while (const ArrayType *array = type->getAsArrayTypeUnsafe())
2556 type = array->getElementType().getTypePtr();
2557 return type->isObjCRetainableType();
2560 /// \brief Determine whether the given type T is a "bridgable" Objective-C type,
2561 /// which is either an Objective-C object pointer type or an
2562 bool Type::isObjCARCBridgableType() const {
2563 return isObjCObjectPointerType() || isBlockPointerType();
2566 /// \brief Determine whether the given type T is a "bridgeable" C type.
2567 bool Type::isCARCBridgableType() const {
2568 const PointerType *Pointer = getAs<PointerType>();
2572 QualType Pointee = Pointer->getPointeeType();
2573 return Pointee->isVoidType() || Pointee->isRecordType();
2576 bool Type::hasSizedVLAType() const {
2577 if (!isVariablyModifiedType()) return false;
2579 if (const PointerType *ptr = getAs<PointerType>())
2580 return ptr->getPointeeType()->hasSizedVLAType();
2581 if (const ReferenceType *ref = getAs<ReferenceType>())
2582 return ref->getPointeeType()->hasSizedVLAType();
2583 if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
2584 if (isa<VariableArrayType>(arr) &&
2585 cast<VariableArrayType>(arr)->getSizeExpr())
2588 return arr->getElementType()->hasSizedVLAType();
2594 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
2595 switch (type.getObjCLifetime()) {
2596 case Qualifiers::OCL_None:
2597 case Qualifiers::OCL_ExplicitNone:
2598 case Qualifiers::OCL_Autoreleasing:
2601 case Qualifiers::OCL_Strong:
2602 return DK_objc_strong_lifetime;
2603 case Qualifiers::OCL_Weak:
2604 return DK_objc_weak_lifetime;
2607 /// Currently, the only destruction kind we recognize is C++ objects
2608 /// with non-trivial destructors.
2609 const CXXRecordDecl *record =
2610 type->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2611 if (record && record->hasDefinition() && !record->hasTrivialDestructor())
2612 return DK_cxx_destructor;
2617 CXXRecordDecl *MemberPointerType::getMostRecentCXXRecordDecl() const {
2618 return getClass()->getAsCXXRecordDecl()->getMostRecentDecl();