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::isInterfaceType() const {
368 if (const RecordType *RT = getAs<RecordType>())
369 return RT->getDecl()->isInterface();
372 bool Type::isStructureOrClassType() const {
373 if (const RecordType *RT = getAs<RecordType>()) {
374 RecordDecl *RD = RT->getDecl();
375 return RD->isStruct() || RD->isClass() || RD->isInterface();
379 bool Type::isVoidPointerType() const {
380 if (const PointerType *PT = getAs<PointerType>())
381 return PT->getPointeeType()->isVoidType();
385 bool Type::isUnionType() const {
386 if (const RecordType *RT = getAs<RecordType>())
387 return RT->getDecl()->isUnion();
391 bool Type::isComplexType() const {
392 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
393 return CT->getElementType()->isFloatingType();
397 bool Type::isComplexIntegerType() const {
398 // Check for GCC complex integer extension.
399 return getAsComplexIntegerType();
402 const ComplexType *Type::getAsComplexIntegerType() const {
403 if (const ComplexType *Complex = getAs<ComplexType>())
404 if (Complex->getElementType()->isIntegerType())
409 QualType Type::getPointeeType() const {
410 if (const PointerType *PT = getAs<PointerType>())
411 return PT->getPointeeType();
412 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
413 return OPT->getPointeeType();
414 if (const BlockPointerType *BPT = getAs<BlockPointerType>())
415 return BPT->getPointeeType();
416 if (const ReferenceType *RT = getAs<ReferenceType>())
417 return RT->getPointeeType();
418 if (const MemberPointerType *MPT = getAs<MemberPointerType>())
419 return MPT->getPointeeType();
420 if (const DecayedType *DT = getAs<DecayedType>())
421 return DT->getPointeeType();
425 const RecordType *Type::getAsStructureType() const {
426 // If this is directly a structure type, return it.
427 if (const RecordType *RT = dyn_cast<RecordType>(this)) {
428 if (RT->getDecl()->isStruct())
432 // If the canonical form of this type isn't the right kind, reject it.
433 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
434 if (!RT->getDecl()->isStruct())
437 // If this is a typedef for a structure type, strip the typedef off without
438 // losing all typedef information.
439 return cast<RecordType>(getUnqualifiedDesugaredType());
444 const RecordType *Type::getAsUnionType() const {
445 // If this is directly a union type, return it.
446 if (const RecordType *RT = dyn_cast<RecordType>(this)) {
447 if (RT->getDecl()->isUnion())
451 // If the canonical form of this type isn't the right kind, reject it.
452 if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
453 if (!RT->getDecl()->isUnion())
456 // If this is a typedef for a union type, strip the typedef off without
457 // losing all typedef information.
458 return cast<RecordType>(getUnqualifiedDesugaredType());
464 ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base,
465 ObjCProtocolDecl * const *Protocols,
466 unsigned NumProtocols)
467 : Type(ObjCObject, Canonical, false, false, false, false),
470 ObjCObjectTypeBits.NumProtocols = NumProtocols;
471 assert(getNumProtocols() == NumProtocols &&
472 "bitfield overflow in protocol count");
474 memcpy(getProtocolStorage(), Protocols,
475 NumProtocols * sizeof(ObjCProtocolDecl*));
478 const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const {
479 // There is no sugar for ObjCObjectType's, just return the canonical
480 // type pointer if it is the right class. There is no typedef information to
481 // return and these cannot be Address-space qualified.
482 if (const ObjCObjectType *T = getAs<ObjCObjectType>())
483 if (T->getNumProtocols() && T->getInterface())
488 bool Type::isObjCQualifiedInterfaceType() const {
489 return getAsObjCQualifiedInterfaceType() != nullptr;
492 const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
493 // There is no sugar for ObjCQualifiedIdType's, just return the canonical
494 // type pointer if it is the right class.
495 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
496 if (OPT->isObjCQualifiedIdType())
502 const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const {
503 // There is no sugar for ObjCQualifiedClassType's, just return the canonical
504 // type pointer if it is the right class.
505 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
506 if (OPT->isObjCQualifiedClassType())
512 const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
513 if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
514 if (OPT->getInterfaceType())
520 const CXXRecordDecl *Type::getPointeeCXXRecordDecl() const {
521 QualType PointeeType;
522 if (const PointerType *PT = getAs<PointerType>())
523 PointeeType = PT->getPointeeType();
524 else if (const ReferenceType *RT = getAs<ReferenceType>())
525 PointeeType = RT->getPointeeType();
529 if (const RecordType *RT = PointeeType->getAs<RecordType>())
530 return dyn_cast<CXXRecordDecl>(RT->getDecl());
535 CXXRecordDecl *Type::getAsCXXRecordDecl() const {
536 return dyn_cast_or_null<CXXRecordDecl>(getAsTagDecl());
539 TagDecl *Type::getAsTagDecl() const {
540 if (const auto *TT = getAs<TagType>())
541 return cast<TagDecl>(TT->getDecl());
542 if (const auto *Injected = getAs<InjectedClassNameType>())
543 return Injected->getDecl();
549 class GetContainedAutoVisitor :
550 public TypeVisitor<GetContainedAutoVisitor, AutoType*> {
552 using TypeVisitor<GetContainedAutoVisitor, AutoType*>::Visit;
553 AutoType *Visit(QualType T) {
556 return Visit(T.getTypePtr());
559 // The 'auto' type itself.
560 AutoType *VisitAutoType(const AutoType *AT) {
561 return const_cast<AutoType*>(AT);
564 // Only these types can contain the desired 'auto' type.
565 AutoType *VisitPointerType(const PointerType *T) {
566 return Visit(T->getPointeeType());
568 AutoType *VisitBlockPointerType(const BlockPointerType *T) {
569 return Visit(T->getPointeeType());
571 AutoType *VisitReferenceType(const ReferenceType *T) {
572 return Visit(T->getPointeeTypeAsWritten());
574 AutoType *VisitMemberPointerType(const MemberPointerType *T) {
575 return Visit(T->getPointeeType());
577 AutoType *VisitArrayType(const ArrayType *T) {
578 return Visit(T->getElementType());
580 AutoType *VisitDependentSizedExtVectorType(
581 const DependentSizedExtVectorType *T) {
582 return Visit(T->getElementType());
584 AutoType *VisitVectorType(const VectorType *T) {
585 return Visit(T->getElementType());
587 AutoType *VisitFunctionType(const FunctionType *T) {
588 return Visit(T->getReturnType());
590 AutoType *VisitParenType(const ParenType *T) {
591 return Visit(T->getInnerType());
593 AutoType *VisitAttributedType(const AttributedType *T) {
594 return Visit(T->getModifiedType());
596 AutoType *VisitAdjustedType(const AdjustedType *T) {
597 return Visit(T->getOriginalType());
602 AutoType *Type::getContainedAutoType() const {
603 return GetContainedAutoVisitor().Visit(this);
606 bool Type::hasIntegerRepresentation() const {
607 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
608 return VT->getElementType()->isIntegerType();
610 return isIntegerType();
613 /// \brief Determine whether this type is an integral type.
615 /// This routine determines whether the given type is an integral type per
616 /// C++ [basic.fundamental]p7. Although the C standard does not define the
617 /// term "integral type", it has a similar term "integer type", and in C++
618 /// the two terms are equivalent. However, C's "integer type" includes
619 /// enumeration types, while C++'s "integer type" does not. The \c ASTContext
620 /// parameter is used to determine whether we should be following the C or
621 /// C++ rules when determining whether this type is an integral/integer type.
623 /// For cases where C permits "an integer type" and C++ permits "an integral
624 /// type", use this routine.
626 /// For cases where C permits "an integer type" and C++ permits "an integral
627 /// or enumeration type", use \c isIntegralOrEnumerationType() instead.
629 /// \param Ctx The context in which this type occurs.
631 /// \returns true if the type is considered an integral type, false otherwise.
632 bool Type::isIntegralType(ASTContext &Ctx) const {
633 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
634 return BT->getKind() >= BuiltinType::Bool &&
635 BT->getKind() <= BuiltinType::Int128;
637 // Complete enum types are integral in C.
638 if (!Ctx.getLangOpts().CPlusPlus)
639 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
640 return ET->getDecl()->isComplete();
646 bool Type::isIntegralOrUnscopedEnumerationType() const {
647 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
648 return BT->getKind() >= BuiltinType::Bool &&
649 BT->getKind() <= BuiltinType::Int128;
651 // Check for a complete enum type; incomplete enum types are not properly an
652 // enumeration type in the sense required here.
653 // C++0x: However, if the underlying type of the enum is fixed, it is
654 // considered complete.
655 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
656 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
663 bool Type::isCharType() const {
664 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
665 return BT->getKind() == BuiltinType::Char_U ||
666 BT->getKind() == BuiltinType::UChar ||
667 BT->getKind() == BuiltinType::Char_S ||
668 BT->getKind() == BuiltinType::SChar;
672 bool Type::isWideCharType() const {
673 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
674 return BT->getKind() == BuiltinType::WChar_S ||
675 BT->getKind() == BuiltinType::WChar_U;
679 bool Type::isChar16Type() const {
680 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
681 return BT->getKind() == BuiltinType::Char16;
685 bool Type::isChar32Type() const {
686 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
687 return BT->getKind() == BuiltinType::Char32;
691 /// \brief Determine whether this type is any of the built-in character
693 bool Type::isAnyCharacterType() const {
694 const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType);
695 if (!BT) return false;
696 switch (BT->getKind()) {
697 default: return false;
698 case BuiltinType::Char_U:
699 case BuiltinType::UChar:
700 case BuiltinType::WChar_U:
701 case BuiltinType::Char16:
702 case BuiltinType::Char32:
703 case BuiltinType::Char_S:
704 case BuiltinType::SChar:
705 case BuiltinType::WChar_S:
710 /// isSignedIntegerType - Return true if this is an integer type that is
711 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
712 /// an enum decl which has a signed representation
713 bool Type::isSignedIntegerType() const {
714 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
715 return BT->getKind() >= BuiltinType::Char_S &&
716 BT->getKind() <= BuiltinType::Int128;
719 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
720 // Incomplete enum types are not treated as integer types.
721 // FIXME: In C++, enum types are never integer types.
722 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
723 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
729 bool Type::isSignedIntegerOrEnumerationType() const {
730 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
731 return BT->getKind() >= BuiltinType::Char_S &&
732 BT->getKind() <= BuiltinType::Int128;
735 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
736 if (ET->getDecl()->isComplete())
737 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
743 bool Type::hasSignedIntegerRepresentation() const {
744 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
745 return VT->getElementType()->isSignedIntegerOrEnumerationType();
747 return isSignedIntegerOrEnumerationType();
750 /// isUnsignedIntegerType - Return true if this is an integer type that is
751 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
752 /// decl which has an unsigned representation
753 bool Type::isUnsignedIntegerType() const {
754 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
755 return BT->getKind() >= BuiltinType::Bool &&
756 BT->getKind() <= BuiltinType::UInt128;
759 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
760 // Incomplete enum types are not treated as integer types.
761 // FIXME: In C++, enum types are never integer types.
762 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
763 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
769 bool Type::isUnsignedIntegerOrEnumerationType() const {
770 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
771 return BT->getKind() >= BuiltinType::Bool &&
772 BT->getKind() <= BuiltinType::UInt128;
775 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
776 if (ET->getDecl()->isComplete())
777 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
783 bool Type::hasUnsignedIntegerRepresentation() const {
784 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
785 return VT->getElementType()->isUnsignedIntegerOrEnumerationType();
787 return isUnsignedIntegerOrEnumerationType();
790 bool Type::isFloatingType() const {
791 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
792 return BT->getKind() >= BuiltinType::Half &&
793 BT->getKind() <= BuiltinType::LongDouble;
794 if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
795 return CT->getElementType()->isFloatingType();
799 bool Type::hasFloatingRepresentation() const {
800 if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
801 return VT->getElementType()->isFloatingType();
803 return isFloatingType();
806 bool Type::isRealFloatingType() const {
807 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
808 return BT->isFloatingPoint();
812 bool Type::isRealType() const {
813 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
814 return BT->getKind() >= BuiltinType::Bool &&
815 BT->getKind() <= BuiltinType::LongDouble;
816 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
817 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
821 bool Type::isArithmeticType() const {
822 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
823 return BT->getKind() >= BuiltinType::Bool &&
824 BT->getKind() <= BuiltinType::LongDouble;
825 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
826 // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
827 // If a body isn't seen by the time we get here, return false.
829 // C++0x: Enumerations are not arithmetic types. For now, just return
830 // false for scoped enumerations since that will disable any
831 // unwanted implicit conversions.
832 return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete();
833 return isa<ComplexType>(CanonicalType);
836 Type::ScalarTypeKind Type::getScalarTypeKind() const {
837 assert(isScalarType());
839 const Type *T = CanonicalType.getTypePtr();
840 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) {
841 if (BT->getKind() == BuiltinType::Bool) return STK_Bool;
842 if (BT->getKind() == BuiltinType::NullPtr) return STK_CPointer;
843 if (BT->isInteger()) return STK_Integral;
844 if (BT->isFloatingPoint()) return STK_Floating;
845 llvm_unreachable("unknown scalar builtin type");
846 } else if (isa<PointerType>(T)) {
848 } else if (isa<BlockPointerType>(T)) {
849 return STK_BlockPointer;
850 } else if (isa<ObjCObjectPointerType>(T)) {
851 return STK_ObjCObjectPointer;
852 } else if (isa<MemberPointerType>(T)) {
853 return STK_MemberPointer;
854 } else if (isa<EnumType>(T)) {
855 assert(cast<EnumType>(T)->getDecl()->isComplete());
857 } else if (const ComplexType *CT = dyn_cast<ComplexType>(T)) {
858 if (CT->getElementType()->isRealFloatingType())
859 return STK_FloatingComplex;
860 return STK_IntegralComplex;
863 llvm_unreachable("unknown scalar type");
866 /// \brief Determines whether the type is a C++ aggregate type or C
867 /// aggregate or union type.
869 /// An aggregate type is an array or a class type (struct, union, or
870 /// class) that has no user-declared constructors, no private or
871 /// protected non-static data members, no base classes, and no virtual
872 /// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
873 /// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
874 /// includes union types.
875 bool Type::isAggregateType() const {
876 if (const RecordType *Record = dyn_cast<RecordType>(CanonicalType)) {
877 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
878 return ClassDecl->isAggregate();
883 return isa<ArrayType>(CanonicalType);
886 /// isConstantSizeType - Return true if this is not a variable sized type,
887 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
888 /// incomplete types or dependent types.
889 bool Type::isConstantSizeType() const {
890 assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
891 assert(!isDependentType() && "This doesn't make sense for dependent types");
892 // The VAT must have a size, as it is known to be complete.
893 return !isa<VariableArrayType>(CanonicalType);
896 /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
897 /// - a type that can describe objects, but which lacks information needed to
898 /// determine its size.
899 bool Type::isIncompleteType(NamedDecl **Def) const {
903 switch (CanonicalType->getTypeClass()) {
904 default: return false;
906 // Void is the only incomplete builtin type. Per C99 6.2.5p19, it can never
910 EnumDecl *EnumD = cast<EnumType>(CanonicalType)->getDecl();
914 // An enumeration with fixed underlying type is complete (C++0x 7.2p3).
915 if (EnumD->isFixed())
918 return !EnumD->isCompleteDefinition();
921 // A tagged type (struct/union/enum/class) is incomplete if the decl is a
922 // forward declaration, but not a full definition (C99 6.2.5p22).
923 RecordDecl *Rec = cast<RecordType>(CanonicalType)->getDecl();
926 return !Rec->isCompleteDefinition();
929 // An array is incomplete if its element type is incomplete
930 // (C++ [dcl.array]p1).
931 // We don't handle variable arrays (they're not allowed in C++) or
932 // dependent-sized arrays (dependent types are never treated as incomplete).
933 return cast<ArrayType>(CanonicalType)->getElementType()
934 ->isIncompleteType(Def);
935 case IncompleteArray:
936 // An array of unknown size is an incomplete type (C99 6.2.5p22).
939 return cast<ObjCObjectType>(CanonicalType)->getBaseType()
940 ->isIncompleteType(Def);
941 case ObjCInterface: {
942 // ObjC interfaces are incomplete if they are @class, not @interface.
943 ObjCInterfaceDecl *Interface
944 = cast<ObjCInterfaceType>(CanonicalType)->getDecl();
947 return !Interface->hasDefinition();
952 bool QualType::isPODType(ASTContext &Context) const {
953 // C++11 has a more relaxed definition of POD.
954 if (Context.getLangOpts().CPlusPlus11)
955 return isCXX11PODType(Context);
957 return isCXX98PODType(Context);
960 bool QualType::isCXX98PODType(ASTContext &Context) const {
961 // The compiler shouldn't query this for incomplete types, but the user might.
962 // We return false for that case. Except for incomplete arrays of PODs, which
963 // are PODs according to the standard.
967 if ((*this)->isIncompleteArrayType())
968 return Context.getBaseElementType(*this).isCXX98PODType(Context);
970 if ((*this)->isIncompleteType())
973 if (Context.getLangOpts().ObjCAutoRefCount) {
974 switch (getObjCLifetime()) {
975 case Qualifiers::OCL_ExplicitNone:
978 case Qualifiers::OCL_Strong:
979 case Qualifiers::OCL_Weak:
980 case Qualifiers::OCL_Autoreleasing:
983 case Qualifiers::OCL_None:
988 QualType CanonicalType = getTypePtr()->CanonicalType;
989 switch (CanonicalType->getTypeClass()) {
990 // Everything not explicitly mentioned is not POD.
991 default: return false;
992 case Type::VariableArray:
993 case Type::ConstantArray:
994 // IncompleteArray is handled above.
995 return Context.getBaseElementType(*this).isCXX98PODType(Context);
997 case Type::ObjCObjectPointer:
998 case Type::BlockPointer:
1002 case Type::MemberPointer:
1004 case Type::ExtVector:
1011 if (CXXRecordDecl *ClassDecl
1012 = dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
1013 return ClassDecl->isPOD();
1015 // C struct/union is POD.
1020 bool QualType::isTrivialType(ASTContext &Context) const {
1021 // The compiler shouldn't query this for incomplete types, but the user might.
1022 // We return false for that case. Except for incomplete arrays of PODs, which
1023 // are PODs according to the standard.
1027 if ((*this)->isArrayType())
1028 return Context.getBaseElementType(*this).isTrivialType(Context);
1030 // Return false for incomplete types after skipping any incomplete array
1031 // types which are expressly allowed by the standard and thus our API.
1032 if ((*this)->isIncompleteType())
1035 if (Context.getLangOpts().ObjCAutoRefCount) {
1036 switch (getObjCLifetime()) {
1037 case Qualifiers::OCL_ExplicitNone:
1040 case Qualifiers::OCL_Strong:
1041 case Qualifiers::OCL_Weak:
1042 case Qualifiers::OCL_Autoreleasing:
1045 case Qualifiers::OCL_None:
1046 if ((*this)->isObjCLifetimeType())
1052 QualType CanonicalType = getTypePtr()->CanonicalType;
1053 if (CanonicalType->isDependentType())
1056 // C++0x [basic.types]p9:
1057 // Scalar types, trivial class types, arrays of such types, and
1058 // cv-qualified versions of these types are collectively called trivial
1061 // As an extension, Clang treats vector types as Scalar types.
1062 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
1064 if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
1065 if (const CXXRecordDecl *ClassDecl =
1066 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1068 // A trivial class is a class that has a default constructor,
1069 // has no non-trivial default constructors, and is trivially
1071 return ClassDecl->hasDefaultConstructor() &&
1072 !ClassDecl->hasNonTrivialDefaultConstructor() &&
1073 ClassDecl->isTriviallyCopyable();
1079 // No other types can match.
1083 bool QualType::isTriviallyCopyableType(ASTContext &Context) const {
1084 if ((*this)->isArrayType())
1085 return Context.getBaseElementType(*this).isTriviallyCopyableType(Context);
1087 if (Context.getLangOpts().ObjCAutoRefCount) {
1088 switch (getObjCLifetime()) {
1089 case Qualifiers::OCL_ExplicitNone:
1092 case Qualifiers::OCL_Strong:
1093 case Qualifiers::OCL_Weak:
1094 case Qualifiers::OCL_Autoreleasing:
1097 case Qualifiers::OCL_None:
1098 if ((*this)->isObjCLifetimeType())
1104 // C++11 [basic.types]p9
1105 // Scalar types, trivially copyable class types, arrays of such types, and
1106 // non-volatile const-qualified versions of these types are collectively
1107 // called trivially copyable types.
1109 QualType CanonicalType = getCanonicalType();
1110 if (CanonicalType->isDependentType())
1113 if (CanonicalType.isVolatileQualified())
1116 // Return false for incomplete types after skipping any incomplete array types
1117 // which are expressly allowed by the standard and thus our API.
1118 if (CanonicalType->isIncompleteType())
1121 // As an extension, Clang treats vector types as Scalar types.
1122 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
1125 if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
1126 if (const CXXRecordDecl *ClassDecl =
1127 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1128 if (!ClassDecl->isTriviallyCopyable()) return false;
1134 // No other types can match.
1140 bool Type::isLiteralType(const ASTContext &Ctx) const {
1141 if (isDependentType())
1144 // C++1y [basic.types]p10:
1145 // A type is a literal type if it is:
1147 if (Ctx.getLangOpts().CPlusPlus14 && isVoidType())
1150 // C++11 [basic.types]p10:
1151 // A type is a literal type if it is:
1153 // -- an array of literal type other than an array of runtime bound; or
1154 if (isVariableArrayType())
1156 const Type *BaseTy = getBaseElementTypeUnsafe();
1157 assert(BaseTy && "NULL element type");
1159 // Return false for incomplete types after skipping any incomplete array
1160 // types; those are expressly allowed by the standard and thus our API.
1161 if (BaseTy->isIncompleteType())
1164 // C++11 [basic.types]p10:
1165 // A type is a literal type if it is:
1166 // -- a scalar type; or
1167 // As an extension, Clang treats vector types and complex types as
1169 if (BaseTy->isScalarType() || BaseTy->isVectorType() ||
1170 BaseTy->isAnyComplexType())
1172 // -- a reference type; or
1173 if (BaseTy->isReferenceType())
1175 // -- a class type that has all of the following properties:
1176 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1177 // -- a trivial destructor,
1178 // -- every constructor call and full-expression in the
1179 // brace-or-equal-initializers for non-static data members (if any)
1180 // is a constant expression,
1181 // -- it is an aggregate type or has at least one constexpr
1182 // constructor or constructor template that is not a copy or move
1184 // -- all non-static data members and base classes of literal types
1186 // We resolve DR1361 by ignoring the second bullet.
1187 if (const CXXRecordDecl *ClassDecl =
1188 dyn_cast<CXXRecordDecl>(RT->getDecl()))
1189 return ClassDecl->isLiteral();
1194 // We treat _Atomic T as a literal type if T is a literal type.
1195 if (const AtomicType *AT = BaseTy->getAs<AtomicType>())
1196 return AT->getValueType()->isLiteralType(Ctx);
1198 // If this type hasn't been deduced yet, then conservatively assume that
1199 // it'll work out to be a literal type.
1200 if (isa<AutoType>(BaseTy->getCanonicalTypeInternal()))
1206 bool Type::isStandardLayoutType() const {
1207 if (isDependentType())
1210 // C++0x [basic.types]p9:
1211 // Scalar types, standard-layout class types, arrays of such types, and
1212 // cv-qualified versions of these types are collectively called
1213 // standard-layout types.
1214 const Type *BaseTy = getBaseElementTypeUnsafe();
1215 assert(BaseTy && "NULL element type");
1217 // Return false for incomplete types after skipping any incomplete array
1218 // types which are expressly allowed by the standard and thus our API.
1219 if (BaseTy->isIncompleteType())
1222 // As an extension, Clang treats vector types as Scalar types.
1223 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
1224 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1225 if (const CXXRecordDecl *ClassDecl =
1226 dyn_cast<CXXRecordDecl>(RT->getDecl()))
1227 if (!ClassDecl->isStandardLayout())
1230 // Default to 'true' for non-C++ class types.
1231 // FIXME: This is a bit dubious, but plain C structs should trivially meet
1232 // all the requirements of standard layout classes.
1236 // No other types can match.
1240 // This is effectively the intersection of isTrivialType and
1241 // isStandardLayoutType. We implement it directly to avoid redundant
1242 // conversions from a type to a CXXRecordDecl.
1243 bool QualType::isCXX11PODType(ASTContext &Context) const {
1244 const Type *ty = getTypePtr();
1245 if (ty->isDependentType())
1248 if (Context.getLangOpts().ObjCAutoRefCount) {
1249 switch (getObjCLifetime()) {
1250 case Qualifiers::OCL_ExplicitNone:
1253 case Qualifiers::OCL_Strong:
1254 case Qualifiers::OCL_Weak:
1255 case Qualifiers::OCL_Autoreleasing:
1258 case Qualifiers::OCL_None:
1263 // C++11 [basic.types]p9:
1264 // Scalar types, POD classes, arrays of such types, and cv-qualified
1265 // versions of these types are collectively called trivial types.
1266 const Type *BaseTy = ty->getBaseElementTypeUnsafe();
1267 assert(BaseTy && "NULL element type");
1269 // Return false for incomplete types after skipping any incomplete array
1270 // types which are expressly allowed by the standard and thus our API.
1271 if (BaseTy->isIncompleteType())
1274 // As an extension, Clang treats vector types as Scalar types.
1275 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
1276 if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1277 if (const CXXRecordDecl *ClassDecl =
1278 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1279 // C++11 [class]p10:
1280 // A POD struct is a non-union class that is both a trivial class [...]
1281 if (!ClassDecl->isTrivial()) return false;
1283 // C++11 [class]p10:
1284 // A POD struct is a non-union class that is both a trivial class and
1285 // a standard-layout class [...]
1286 if (!ClassDecl->isStandardLayout()) 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, and has no non-static data members of type
1291 // non-POD struct, non-POD union (or array of such types). [...]
1293 // We don't directly query the recursive aspect as the requiremets for
1294 // both standard-layout classes and trivial classes apply recursively
1301 // No other types can match.
1305 bool Type::isPromotableIntegerType() const {
1306 if (const BuiltinType *BT = getAs<BuiltinType>())
1307 switch (BT->getKind()) {
1308 case BuiltinType::Bool:
1309 case BuiltinType::Char_S:
1310 case BuiltinType::Char_U:
1311 case BuiltinType::SChar:
1312 case BuiltinType::UChar:
1313 case BuiltinType::Short:
1314 case BuiltinType::UShort:
1315 case BuiltinType::WChar_S:
1316 case BuiltinType::WChar_U:
1317 case BuiltinType::Char16:
1318 case BuiltinType::Char32:
1324 // Enumerated types are promotable to their compatible integer types
1325 // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1326 if (const EnumType *ET = getAs<EnumType>()){
1327 if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull()
1328 || ET->getDecl()->isScoped())
1337 bool Type::isSpecifierType() const {
1338 // Note that this intentionally does not use the canonical type.
1339 switch (getTypeClass()) {
1347 case TemplateTypeParm:
1348 case SubstTemplateTypeParm:
1349 case TemplateSpecialization:
1352 case DependentTemplateSpecialization:
1355 case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers
1362 ElaboratedTypeKeyword
1363 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) {
1365 default: return ETK_None;
1366 case TST_typename: return ETK_Typename;
1367 case TST_class: return ETK_Class;
1368 case TST_struct: return ETK_Struct;
1369 case TST_interface: return ETK_Interface;
1370 case TST_union: return ETK_Union;
1371 case TST_enum: return ETK_Enum;
1376 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
1378 case TST_class: return TTK_Class;
1379 case TST_struct: return TTK_Struct;
1380 case TST_interface: return TTK_Interface;
1381 case TST_union: return TTK_Union;
1382 case TST_enum: return TTK_Enum;
1385 llvm_unreachable("Type specifier is not a tag type kind.");
1388 ElaboratedTypeKeyword
1389 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) {
1391 case TTK_Class: return ETK_Class;
1392 case TTK_Struct: return ETK_Struct;
1393 case TTK_Interface: return ETK_Interface;
1394 case TTK_Union: return ETK_Union;
1395 case TTK_Enum: return ETK_Enum;
1397 llvm_unreachable("Unknown tag type kind.");
1401 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
1403 case ETK_Class: return TTK_Class;
1404 case ETK_Struct: return TTK_Struct;
1405 case ETK_Interface: return TTK_Interface;
1406 case ETK_Union: return TTK_Union;
1407 case ETK_Enum: return TTK_Enum;
1408 case ETK_None: // Fall through.
1410 llvm_unreachable("Elaborated type keyword is not a tag type kind.");
1412 llvm_unreachable("Unknown elaborated type keyword.");
1416 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
1428 llvm_unreachable("Unknown elaborated type keyword.");
1431 StringRef TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) {
1433 case ETK_None: return "";
1434 case ETK_Typename: return "typename";
1435 case ETK_Class: return "class";
1436 case ETK_Struct: return "struct";
1437 case ETK_Interface: return "__interface";
1438 case ETK_Union: return "union";
1439 case ETK_Enum: return "enum";
1442 llvm_unreachable("Unknown elaborated type keyword.");
1445 DependentTemplateSpecializationType::DependentTemplateSpecializationType(
1446 ElaboratedTypeKeyword Keyword,
1447 NestedNameSpecifier *NNS, const IdentifierInfo *Name,
1448 unsigned NumArgs, const TemplateArgument *Args,
1450 : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true, true,
1451 /*VariablyModified=*/false,
1452 NNS && NNS->containsUnexpandedParameterPack()),
1453 NNS(NNS), Name(Name), NumArgs(NumArgs) {
1454 assert((!NNS || NNS->isDependent()) &&
1455 "DependentTemplateSpecializatonType requires dependent qualifier");
1456 for (unsigned I = 0; I != NumArgs; ++I) {
1457 if (Args[I].containsUnexpandedParameterPack())
1458 setContainsUnexpandedParameterPack();
1460 new (&getArgBuffer()[I]) TemplateArgument(Args[I]);
1465 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1466 const ASTContext &Context,
1467 ElaboratedTypeKeyword Keyword,
1468 NestedNameSpecifier *Qualifier,
1469 const IdentifierInfo *Name,
1471 const TemplateArgument *Args) {
1472 ID.AddInteger(Keyword);
1473 ID.AddPointer(Qualifier);
1474 ID.AddPointer(Name);
1475 for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1476 Args[Idx].Profile(ID, Context);
1479 bool Type::isElaboratedTypeSpecifier() const {
1480 ElaboratedTypeKeyword Keyword;
1481 if (const ElaboratedType *Elab = dyn_cast<ElaboratedType>(this))
1482 Keyword = Elab->getKeyword();
1483 else if (const DependentNameType *DepName = dyn_cast<DependentNameType>(this))
1484 Keyword = DepName->getKeyword();
1485 else if (const DependentTemplateSpecializationType *DepTST =
1486 dyn_cast<DependentTemplateSpecializationType>(this))
1487 Keyword = DepTST->getKeyword();
1491 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
1494 const char *Type::getTypeClassName() const {
1495 switch (TypeBits.TC) {
1496 #define ABSTRACT_TYPE(Derived, Base)
1497 #define TYPE(Derived, Base) case Derived: return #Derived;
1498 #include "clang/AST/TypeNodes.def"
1501 llvm_unreachable("Invalid type class.");
1504 StringRef BuiltinType::getName(const PrintingPolicy &Policy) const {
1505 switch (getKind()) {
1506 case Void: return "void";
1507 case Bool: return Policy.Bool ? "bool" : "_Bool";
1508 case Char_S: return "char";
1509 case Char_U: return "char";
1510 case SChar: return "signed char";
1511 case Short: return "short";
1512 case Int: return "int";
1513 case Long: return "long";
1514 case LongLong: return "long long";
1515 case Int128: return "__int128";
1516 case UChar: return "unsigned char";
1517 case UShort: return "unsigned short";
1518 case UInt: return "unsigned int";
1519 case ULong: return "unsigned long";
1520 case ULongLong: return "unsigned long long";
1521 case UInt128: return "unsigned __int128";
1522 case Half: return Policy.Half ? "half" : "__fp16";
1523 case Float: return "float";
1524 case Double: return "double";
1525 case LongDouble: return "long double";
1527 case WChar_U: return Policy.MSWChar ? "__wchar_t" : "wchar_t";
1528 case Char16: return "char16_t";
1529 case Char32: return "char32_t";
1530 case NullPtr: return "nullptr_t";
1531 case Overload: return "<overloaded function type>";
1532 case BoundMember: return "<bound member function type>";
1533 case PseudoObject: return "<pseudo-object type>";
1534 case Dependent: return "<dependent type>";
1535 case UnknownAny: return "<unknown type>";
1536 case ARCUnbridgedCast: return "<ARC unbridged cast type>";
1537 case BuiltinFn: return "<builtin fn type>";
1538 case ObjCId: return "id";
1539 case ObjCClass: return "Class";
1540 case ObjCSel: return "SEL";
1541 case OCLImage1d: return "image1d_t";
1542 case OCLImage1dArray: return "image1d_array_t";
1543 case OCLImage1dBuffer: return "image1d_buffer_t";
1544 case OCLImage2d: return "image2d_t";
1545 case OCLImage2dArray: return "image2d_array_t";
1546 case OCLImage3d: return "image3d_t";
1547 case OCLSampler: return "sampler_t";
1548 case OCLEvent: return "event_t";
1551 llvm_unreachable("Invalid builtin type.");
1554 QualType QualType::getNonLValueExprType(const ASTContext &Context) const {
1555 if (const ReferenceType *RefType = getTypePtr()->getAs<ReferenceType>())
1556 return RefType->getPointeeType();
1558 // C++0x [basic.lval]:
1559 // Class prvalues can have cv-qualified types; non-class prvalues always
1560 // have cv-unqualified types.
1562 // See also C99 6.3.2.1p2.
1563 if (!Context.getLangOpts().CPlusPlus ||
1564 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
1565 return getUnqualifiedType();
1570 StringRef FunctionType::getNameForCallConv(CallingConv CC) {
1572 case CC_C: return "cdecl";
1573 case CC_X86StdCall: return "stdcall";
1574 case CC_X86FastCall: return "fastcall";
1575 case CC_X86ThisCall: return "thiscall";
1576 case CC_X86Pascal: return "pascal";
1577 case CC_X86VectorCall: return "vectorcall";
1578 case CC_X86_64Win64: return "ms_abi";
1579 case CC_X86_64SysV: return "sysv_abi";
1580 case CC_AAPCS: return "aapcs";
1581 case CC_AAPCS_VFP: return "aapcs-vfp";
1582 case CC_IntelOclBicc: return "intel_ocl_bicc";
1583 case CC_SpirFunction: return "spir_function";
1584 case CC_SpirKernel: return "spir_kernel";
1587 llvm_unreachable("Invalid calling convention.");
1590 FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> params,
1592 const ExtProtoInfo &epi)
1593 : FunctionType(FunctionProto, result, canonical,
1594 result->isDependentType(),
1595 result->isInstantiationDependentType(),
1596 result->isVariablyModifiedType(),
1597 result->containsUnexpandedParameterPack(), epi.ExtInfo),
1598 NumParams(params.size()),
1599 NumExceptions(epi.ExceptionSpec.Exceptions.size()),
1600 ExceptionSpecType(epi.ExceptionSpec.Type),
1601 HasAnyConsumedParams(epi.ConsumedParameters != nullptr),
1602 Variadic(epi.Variadic), HasTrailingReturn(epi.HasTrailingReturn) {
1603 assert(NumParams == params.size() && "function has too many parameters");
1605 FunctionTypeBits.TypeQuals = epi.TypeQuals;
1606 FunctionTypeBits.RefQualifier = epi.RefQualifier;
1608 // Fill in the trailing argument array.
1609 QualType *argSlot = reinterpret_cast<QualType*>(this+1);
1610 for (unsigned i = 0; i != NumParams; ++i) {
1611 if (params[i]->isDependentType())
1613 else if (params[i]->isInstantiationDependentType())
1614 setInstantiationDependent();
1616 if (params[i]->containsUnexpandedParameterPack())
1617 setContainsUnexpandedParameterPack();
1619 argSlot[i] = params[i];
1622 if (getExceptionSpecType() == EST_Dynamic) {
1623 // Fill in the exception array.
1624 QualType *exnSlot = argSlot + NumParams;
1626 for (QualType ExceptionType : epi.ExceptionSpec.Exceptions) {
1627 // Note that a dependent exception specification does *not* make
1628 // a type dependent; it's not even part of the C++ type system.
1629 if (ExceptionType->isInstantiationDependentType())
1630 setInstantiationDependent();
1632 if (ExceptionType->containsUnexpandedParameterPack())
1633 setContainsUnexpandedParameterPack();
1635 exnSlot[I++] = ExceptionType;
1637 } else if (getExceptionSpecType() == EST_ComputedNoexcept) {
1638 // Store the noexcept expression and context.
1639 Expr **noexSlot = reinterpret_cast<Expr **>(argSlot + NumParams);
1640 *noexSlot = epi.ExceptionSpec.NoexceptExpr;
1642 if (epi.ExceptionSpec.NoexceptExpr) {
1643 if (epi.ExceptionSpec.NoexceptExpr->isValueDependent() ||
1644 epi.ExceptionSpec.NoexceptExpr->isInstantiationDependent())
1645 setInstantiationDependent();
1647 if (epi.ExceptionSpec.NoexceptExpr->containsUnexpandedParameterPack())
1648 setContainsUnexpandedParameterPack();
1650 } else if (getExceptionSpecType() == EST_Uninstantiated) {
1651 // Store the function decl from which we will resolve our
1652 // exception specification.
1653 FunctionDecl **slot =
1654 reinterpret_cast<FunctionDecl **>(argSlot + NumParams);
1655 slot[0] = epi.ExceptionSpec.SourceDecl;
1656 slot[1] = epi.ExceptionSpec.SourceTemplate;
1657 // This exception specification doesn't make the type dependent, because
1658 // it's not instantiated as part of instantiating the type.
1659 } else if (getExceptionSpecType() == EST_Unevaluated) {
1660 // Store the function decl from which we will resolve our
1661 // exception specification.
1662 FunctionDecl **slot =
1663 reinterpret_cast<FunctionDecl **>(argSlot + NumParams);
1664 slot[0] = epi.ExceptionSpec.SourceDecl;
1667 if (epi.ConsumedParameters) {
1668 bool *consumedParams = const_cast<bool *>(getConsumedParamsBuffer());
1669 for (unsigned i = 0; i != NumParams; ++i)
1670 consumedParams[i] = epi.ConsumedParameters[i];
1674 bool FunctionProtoType::hasDependentExceptionSpec() const {
1675 if (Expr *NE = getNoexceptExpr())
1676 return NE->isValueDependent();
1677 for (QualType ET : exceptions())
1678 // A pack expansion with a non-dependent pattern is still dependent,
1679 // because we don't know whether the pattern is in the exception spec
1680 // or not (that depends on whether the pack has 0 expansions).
1681 if (ET->isDependentType() || ET->getAs<PackExpansionType>())
1686 FunctionProtoType::NoexceptResult
1687 FunctionProtoType::getNoexceptSpec(const ASTContext &ctx) const {
1688 ExceptionSpecificationType est = getExceptionSpecType();
1689 if (est == EST_BasicNoexcept)
1692 if (est != EST_ComputedNoexcept)
1693 return NR_NoNoexcept;
1695 Expr *noexceptExpr = getNoexceptExpr();
1697 return NR_BadNoexcept;
1698 if (noexceptExpr->isValueDependent())
1699 return NR_Dependent;
1702 bool isICE = noexceptExpr->isIntegerConstantExpr(value, ctx, nullptr,
1703 /*evaluated*/false);
1705 assert(isICE && "AST should not contain bad noexcept expressions.");
1707 return value.getBoolValue() ? NR_Nothrow : NR_Throw;
1710 bool FunctionProtoType::isNothrow(const ASTContext &Ctx,
1711 bool ResultIfDependent) const {
1712 ExceptionSpecificationType EST = getExceptionSpecType();
1713 assert(EST != EST_Unevaluated && EST != EST_Uninstantiated);
1714 if (EST == EST_DynamicNone || EST == EST_BasicNoexcept)
1717 if (EST == EST_Dynamic && ResultIfDependent) {
1718 // A dynamic exception specification is throwing unless every exception
1719 // type is an (unexpanded) pack expansion type.
1720 for (unsigned I = 0, N = NumExceptions; I != N; ++I)
1721 if (!getExceptionType(I)->getAs<PackExpansionType>())
1723 return ResultIfDependent;
1726 if (EST != EST_ComputedNoexcept)
1729 NoexceptResult NR = getNoexceptSpec(Ctx);
1730 if (NR == NR_Dependent)
1731 return ResultIfDependent;
1732 return NR == NR_Nothrow;
1735 bool FunctionProtoType::isTemplateVariadic() const {
1736 for (unsigned ArgIdx = getNumParams(); ArgIdx; --ArgIdx)
1737 if (isa<PackExpansionType>(getParamType(ArgIdx - 1)))
1743 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
1744 const QualType *ArgTys, unsigned NumParams,
1745 const ExtProtoInfo &epi,
1746 const ASTContext &Context) {
1748 // We have to be careful not to get ambiguous profile encodings.
1749 // Note that valid type pointers are never ambiguous with anything else.
1751 // The encoding grammar begins:
1752 // type type* bool int bool
1753 // If that final bool is true, then there is a section for the EH spec:
1755 // This is followed by an optional "consumed argument" section of the
1756 // same length as the first type sequence:
1758 // Finally, we have the ext info and trailing return type flag:
1761 // There is no ambiguity between the consumed arguments and an empty EH
1762 // spec because of the leading 'bool' which unambiguously indicates
1763 // whether the following bool is the EH spec or part of the arguments.
1765 ID.AddPointer(Result.getAsOpaquePtr());
1766 for (unsigned i = 0; i != NumParams; ++i)
1767 ID.AddPointer(ArgTys[i].getAsOpaquePtr());
1768 // This method is relatively performance sensitive, so as a performance
1769 // shortcut, use one AddInteger call instead of four for the next four
1771 assert(!(unsigned(epi.Variadic) & ~1) &&
1772 !(unsigned(epi.TypeQuals) & ~255) &&
1773 !(unsigned(epi.RefQualifier) & ~3) &&
1774 !(unsigned(epi.ExceptionSpec.Type) & ~15) &&
1775 "Values larger than expected.");
1776 ID.AddInteger(unsigned(epi.Variadic) +
1777 (epi.TypeQuals << 1) +
1778 (epi.RefQualifier << 9) +
1779 (epi.ExceptionSpec.Type << 11));
1780 if (epi.ExceptionSpec.Type == EST_Dynamic) {
1781 for (QualType Ex : epi.ExceptionSpec.Exceptions)
1782 ID.AddPointer(Ex.getAsOpaquePtr());
1783 } else if (epi.ExceptionSpec.Type == EST_ComputedNoexcept &&
1784 epi.ExceptionSpec.NoexceptExpr) {
1785 epi.ExceptionSpec.NoexceptExpr->Profile(ID, Context, false);
1786 } else if (epi.ExceptionSpec.Type == EST_Uninstantiated ||
1787 epi.ExceptionSpec.Type == EST_Unevaluated) {
1788 ID.AddPointer(epi.ExceptionSpec.SourceDecl->getCanonicalDecl());
1790 if (epi.ConsumedParameters) {
1791 for (unsigned i = 0; i != NumParams; ++i)
1792 ID.AddBoolean(epi.ConsumedParameters[i]);
1794 epi.ExtInfo.Profile(ID);
1795 ID.AddBoolean(epi.HasTrailingReturn);
1798 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
1799 const ASTContext &Ctx) {
1800 Profile(ID, getReturnType(), param_type_begin(), NumParams, getExtProtoInfo(),
1804 QualType TypedefType::desugar() const {
1805 return getDecl()->getUnderlyingType();
1808 TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
1809 : Type(TypeOfExpr, can, E->isTypeDependent(),
1810 E->isInstantiationDependent(),
1811 E->getType()->isVariablyModifiedType(),
1812 E->containsUnexpandedParameterPack()),
1816 bool TypeOfExprType::isSugared() const {
1817 return !TOExpr->isTypeDependent();
1820 QualType TypeOfExprType::desugar() const {
1822 return getUnderlyingExpr()->getType();
1824 return QualType(this, 0);
1827 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
1828 const ASTContext &Context, Expr *E) {
1829 E->Profile(ID, Context, true);
1832 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
1833 // C++11 [temp.type]p2: "If an expression e involves a template parameter,
1834 // decltype(e) denotes a unique dependent type." Hence a decltype type is
1835 // type-dependent even if its expression is only instantiation-dependent.
1836 : Type(Decltype, can, E->isInstantiationDependent(),
1837 E->isInstantiationDependent(),
1838 E->getType()->isVariablyModifiedType(),
1839 E->containsUnexpandedParameterPack()),
1841 UnderlyingType(underlyingType) {
1844 bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); }
1846 QualType DecltypeType::desugar() const {
1848 return getUnderlyingType();
1850 return QualType(this, 0);
1853 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E)
1854 : DecltypeType(E, Context.DependentTy), Context(Context) { }
1856 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
1857 const ASTContext &Context, Expr *E) {
1858 E->Profile(ID, Context, true);
1861 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
1862 : Type(TC, can, D->isDependentType(),
1863 /*InstantiationDependent=*/D->isDependentType(),
1864 /*VariablyModified=*/false,
1865 /*ContainsUnexpandedParameterPack=*/false),
1866 decl(const_cast<TagDecl*>(D)) {}
1868 static TagDecl *getInterestingTagDecl(TagDecl *decl) {
1869 for (auto I : decl->redecls()) {
1870 if (I->isCompleteDefinition() || I->isBeingDefined())
1873 // If there's no definition (not even in progress), return what we have.
1877 UnaryTransformType::UnaryTransformType(QualType BaseType,
1878 QualType UnderlyingType,
1880 QualType CanonicalType)
1881 : Type(UnaryTransform, CanonicalType, UnderlyingType->isDependentType(),
1882 UnderlyingType->isInstantiationDependentType(),
1883 UnderlyingType->isVariablyModifiedType(),
1884 BaseType->containsUnexpandedParameterPack())
1885 , BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind)
1888 TagDecl *TagType::getDecl() const {
1889 return getInterestingTagDecl(decl);
1892 bool TagType::isBeingDefined() const {
1893 return getDecl()->isBeingDefined();
1896 bool AttributedType::isMSTypeSpec() const {
1897 switch (getAttrKind()) {
1898 default: return false;
1905 llvm_unreachable("invalid attr kind");
1908 bool AttributedType::isCallingConv() const {
1909 switch (getAttrKind()) {
1914 case attr_address_space:
1916 case attr_vector_size:
1917 case attr_neon_vector_type:
1918 case attr_neon_polyvector_type:
1920 case attr_objc_ownership:
1929 case attr_vectorcall:
1933 case attr_inteloclbicc:
1936 llvm_unreachable("invalid attr kind");
1939 CXXRecordDecl *InjectedClassNameType::getDecl() const {
1940 return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
1943 IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
1944 return isCanonicalUnqualified() ? nullptr : getDecl()->getIdentifier();
1947 SubstTemplateTypeParmPackType::
1948 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
1950 const TemplateArgument &ArgPack)
1951 : Type(SubstTemplateTypeParmPack, Canon, true, true, false, true),
1953 Arguments(ArgPack.pack_begin()), NumArguments(ArgPack.pack_size())
1957 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const {
1958 return TemplateArgument(Arguments, NumArguments);
1961 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
1962 Profile(ID, getReplacedParameter(), getArgumentPack());
1965 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
1966 const TemplateTypeParmType *Replaced,
1967 const TemplateArgument &ArgPack) {
1968 ID.AddPointer(Replaced);
1969 ID.AddInteger(ArgPack.pack_size());
1970 for (const auto &P : ArgPack.pack_elements())
1971 ID.AddPointer(P.getAsType().getAsOpaquePtr());
1974 bool TemplateSpecializationType::
1975 anyDependentTemplateArguments(const TemplateArgumentListInfo &Args,
1976 bool &InstantiationDependent) {
1977 return anyDependentTemplateArguments(Args.getArgumentArray(), Args.size(),
1978 InstantiationDependent);
1981 bool TemplateSpecializationType::
1982 anyDependentTemplateArguments(const TemplateArgumentLoc *Args, unsigned N,
1983 bool &InstantiationDependent) {
1984 for (unsigned i = 0; i != N; ++i) {
1985 if (Args[i].getArgument().isDependent()) {
1986 InstantiationDependent = true;
1990 if (Args[i].getArgument().isInstantiationDependent())
1991 InstantiationDependent = true;
1996 TemplateSpecializationType::
1997 TemplateSpecializationType(TemplateName T,
1998 const TemplateArgument *Args, unsigned NumArgs,
1999 QualType Canon, QualType AliasedType)
2000 : Type(TemplateSpecialization,
2001 Canon.isNull()? QualType(this, 0) : Canon,
2002 Canon.isNull()? true : Canon->isDependentType(),
2003 Canon.isNull()? true : Canon->isInstantiationDependentType(),
2005 T.containsUnexpandedParameterPack()),
2006 Template(T), NumArgs(NumArgs), TypeAlias(!AliasedType.isNull()) {
2007 assert(!T.getAsDependentTemplateName() &&
2008 "Use DependentTemplateSpecializationType for dependent template-name");
2009 assert((T.getKind() == TemplateName::Template ||
2010 T.getKind() == TemplateName::SubstTemplateTemplateParm ||
2011 T.getKind() == TemplateName::SubstTemplateTemplateParmPack) &&
2012 "Unexpected template name for TemplateSpecializationType");
2014 TemplateArgument *TemplateArgs
2015 = reinterpret_cast<TemplateArgument *>(this + 1);
2016 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
2017 // Update instantiation-dependent and variably-modified bits.
2018 // If the canonical type exists and is non-dependent, the template
2019 // specialization type can be non-dependent even if one of the type
2020 // arguments is. Given:
2021 // template<typename T> using U = int;
2022 // U<T> is always non-dependent, irrespective of the type T.
2023 // However, U<Ts> contains an unexpanded parameter pack, even though
2024 // its expansion (and thus its desugared type) doesn't.
2025 if (Args[Arg].isInstantiationDependent())
2026 setInstantiationDependent();
2027 if (Args[Arg].getKind() == TemplateArgument::Type &&
2028 Args[Arg].getAsType()->isVariablyModifiedType())
2029 setVariablyModified();
2030 if (Args[Arg].containsUnexpandedParameterPack())
2031 setContainsUnexpandedParameterPack();
2032 new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]);
2035 // Store the aliased type if this is a type alias template specialization.
2037 TemplateArgument *Begin = reinterpret_cast<TemplateArgument *>(this + 1);
2038 *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType;
2043 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
2045 const TemplateArgument *Args,
2047 const ASTContext &Context) {
2049 for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
2050 Args[Idx].Profile(ID, Context);
2054 QualifierCollector::apply(const ASTContext &Context, QualType QT) const {
2055 if (!hasNonFastQualifiers())
2056 return QT.withFastQualifiers(getFastQualifiers());
2058 return Context.getQualifiedType(QT, *this);
2062 QualifierCollector::apply(const ASTContext &Context, const Type *T) const {
2063 if (!hasNonFastQualifiers())
2064 return QualType(T, getFastQualifiers());
2066 return Context.getQualifiedType(T, *this);
2069 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
2071 ObjCProtocolDecl * const *Protocols,
2072 unsigned NumProtocols) {
2073 ID.AddPointer(BaseType.getAsOpaquePtr());
2074 for (unsigned i = 0; i != NumProtocols; i++)
2075 ID.AddPointer(Protocols[i]);
2078 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
2079 Profile(ID, getBaseType(), qual_begin(), getNumProtocols());
2084 /// \brief The cached properties of a type.
2085 class CachedProperties {
2090 CachedProperties(Linkage L, bool local) : L(L), local(local) {}
2092 Linkage getLinkage() const { return L; }
2093 bool hasLocalOrUnnamedType() const { return local; }
2095 friend CachedProperties merge(CachedProperties L, CachedProperties R) {
2096 Linkage MergedLinkage = minLinkage(L.L, R.L);
2097 return CachedProperties(MergedLinkage,
2098 L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType());
2103 static CachedProperties computeCachedProperties(const Type *T);
2106 /// The type-property cache. This is templated so as to be
2107 /// instantiated at an internal type to prevent unnecessary symbol
2109 template <class Private> class TypePropertyCache {
2111 static CachedProperties get(QualType T) {
2112 return get(T.getTypePtr());
2115 static CachedProperties get(const Type *T) {
2117 return CachedProperties(T->TypeBits.getLinkage(),
2118 T->TypeBits.hasLocalOrUnnamedType());
2121 static void ensure(const Type *T) {
2122 // If the cache is valid, we're okay.
2123 if (T->TypeBits.isCacheValid()) return;
2125 // If this type is non-canonical, ask its canonical type for the
2126 // relevant information.
2127 if (!T->isCanonicalUnqualified()) {
2128 const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
2130 T->TypeBits.CacheValid = true;
2131 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
2132 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
2136 // Compute the cached properties and then set the cache.
2137 CachedProperties Result = computeCachedProperties(T);
2138 T->TypeBits.CacheValid = true;
2139 T->TypeBits.CachedLinkage = Result.getLinkage();
2140 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
2145 // Instantiate the friend template at a private class. In a
2146 // reasonable implementation, these symbols will be internal.
2147 // It is terrible that this is the best way to accomplish this.
2148 namespace { class Private {}; }
2149 typedef TypePropertyCache<Private> Cache;
2151 static CachedProperties computeCachedProperties(const Type *T) {
2152 switch (T->getTypeClass()) {
2153 #define TYPE(Class,Base)
2154 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
2155 #include "clang/AST/TypeNodes.def"
2156 llvm_unreachable("didn't expect a non-canonical type here");
2158 #define TYPE(Class,Base)
2159 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
2160 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
2161 #include "clang/AST/TypeNodes.def"
2162 // Treat instantiation-dependent types as external.
2163 assert(T->isInstantiationDependentType());
2164 return CachedProperties(ExternalLinkage, false);
2167 // Give non-deduced 'auto' types external linkage. We should only see them
2168 // here in error recovery.
2169 return CachedProperties(ExternalLinkage, false);
2172 // C++ [basic.link]p8:
2173 // A type is said to have linkage if and only if:
2174 // - it is a fundamental type (3.9.1); or
2175 return CachedProperties(ExternalLinkage, false);
2179 const TagDecl *Tag = cast<TagType>(T)->getDecl();
2181 // C++ [basic.link]p8:
2182 // - it is a class or enumeration type that is named (or has a name
2183 // for linkage purposes (7.1.3)) and the name has linkage; or
2184 // - it is a specialization of a class template (14); or
2185 Linkage L = Tag->getLinkageInternal();
2186 bool IsLocalOrUnnamed =
2187 Tag->getDeclContext()->isFunctionOrMethod() ||
2188 !Tag->hasNameForLinkage();
2189 return CachedProperties(L, IsLocalOrUnnamed);
2192 // C++ [basic.link]p8:
2193 // - it is a compound type (3.9.2) other than a class or enumeration,
2194 // compounded exclusively from types that have linkage; or
2196 return Cache::get(cast<ComplexType>(T)->getElementType());
2198 return Cache::get(cast<PointerType>(T)->getPointeeType());
2199 case Type::BlockPointer:
2200 return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
2201 case Type::LValueReference:
2202 case Type::RValueReference:
2203 return Cache::get(cast<ReferenceType>(T)->getPointeeType());
2204 case Type::MemberPointer: {
2205 const MemberPointerType *MPT = cast<MemberPointerType>(T);
2206 return merge(Cache::get(MPT->getClass()),
2207 Cache::get(MPT->getPointeeType()));
2209 case Type::ConstantArray:
2210 case Type::IncompleteArray:
2211 case Type::VariableArray:
2212 return Cache::get(cast<ArrayType>(T)->getElementType());
2214 case Type::ExtVector:
2215 return Cache::get(cast<VectorType>(T)->getElementType());
2216 case Type::FunctionNoProto:
2217 return Cache::get(cast<FunctionType>(T)->getReturnType());
2218 case Type::FunctionProto: {
2219 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2220 CachedProperties result = Cache::get(FPT->getReturnType());
2221 for (const auto &ai : FPT->param_types())
2222 result = merge(result, Cache::get(ai));
2225 case Type::ObjCInterface: {
2226 Linkage L = cast<ObjCInterfaceType>(T)->getDecl()->getLinkageInternal();
2227 return CachedProperties(L, false);
2229 case Type::ObjCObject:
2230 return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
2231 case Type::ObjCObjectPointer:
2232 return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
2234 return Cache::get(cast<AtomicType>(T)->getValueType());
2237 llvm_unreachable("unhandled type class");
2240 /// \brief Determine the linkage of this type.
2241 Linkage Type::getLinkage() const {
2242 Cache::ensure(this);
2243 return TypeBits.getLinkage();
2246 bool Type::hasUnnamedOrLocalType() const {
2247 Cache::ensure(this);
2248 return TypeBits.hasLocalOrUnnamedType();
2251 static LinkageInfo computeLinkageInfo(QualType T);
2253 static LinkageInfo computeLinkageInfo(const Type *T) {
2254 switch (T->getTypeClass()) {
2255 #define TYPE(Class,Base)
2256 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
2257 #include "clang/AST/TypeNodes.def"
2258 llvm_unreachable("didn't expect a non-canonical type here");
2260 #define TYPE(Class,Base)
2261 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
2262 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
2263 #include "clang/AST/TypeNodes.def"
2264 // Treat instantiation-dependent types as external.
2265 assert(T->isInstantiationDependentType());
2266 return LinkageInfo::external();
2269 return LinkageInfo::external();
2272 return LinkageInfo::external();
2276 return cast<TagType>(T)->getDecl()->getLinkageAndVisibility();
2279 return computeLinkageInfo(cast<ComplexType>(T)->getElementType());
2281 return computeLinkageInfo(cast<PointerType>(T)->getPointeeType());
2282 case Type::BlockPointer:
2283 return computeLinkageInfo(cast<BlockPointerType>(T)->getPointeeType());
2284 case Type::LValueReference:
2285 case Type::RValueReference:
2286 return computeLinkageInfo(cast<ReferenceType>(T)->getPointeeType());
2287 case Type::MemberPointer: {
2288 const MemberPointerType *MPT = cast<MemberPointerType>(T);
2289 LinkageInfo LV = computeLinkageInfo(MPT->getClass());
2290 LV.merge(computeLinkageInfo(MPT->getPointeeType()));
2293 case Type::ConstantArray:
2294 case Type::IncompleteArray:
2295 case Type::VariableArray:
2296 return computeLinkageInfo(cast<ArrayType>(T)->getElementType());
2298 case Type::ExtVector:
2299 return computeLinkageInfo(cast<VectorType>(T)->getElementType());
2300 case Type::FunctionNoProto:
2301 return computeLinkageInfo(cast<FunctionType>(T)->getReturnType());
2302 case Type::FunctionProto: {
2303 const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2304 LinkageInfo LV = computeLinkageInfo(FPT->getReturnType());
2305 for (const auto &ai : FPT->param_types())
2306 LV.merge(computeLinkageInfo(ai));
2309 case Type::ObjCInterface:
2310 return cast<ObjCInterfaceType>(T)->getDecl()->getLinkageAndVisibility();
2311 case Type::ObjCObject:
2312 return computeLinkageInfo(cast<ObjCObjectType>(T)->getBaseType());
2313 case Type::ObjCObjectPointer:
2314 return computeLinkageInfo(cast<ObjCObjectPointerType>(T)->getPointeeType());
2316 return computeLinkageInfo(cast<AtomicType>(T)->getValueType());
2319 llvm_unreachable("unhandled type class");
2322 static LinkageInfo computeLinkageInfo(QualType T) {
2323 return computeLinkageInfo(T.getTypePtr());
2326 bool Type::isLinkageValid() const {
2327 if (!TypeBits.isCacheValid())
2330 return computeLinkageInfo(getCanonicalTypeInternal()).getLinkage() ==
2331 TypeBits.getLinkage();
2334 LinkageInfo Type::getLinkageAndVisibility() const {
2335 if (!isCanonicalUnqualified())
2336 return computeLinkageInfo(getCanonicalTypeInternal());
2338 LinkageInfo LV = computeLinkageInfo(this);
2339 assert(LV.getLinkage() == getLinkage());
2343 Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const {
2344 if (isObjCARCImplicitlyUnretainedType())
2345 return Qualifiers::OCL_ExplicitNone;
2346 return Qualifiers::OCL_Strong;
2349 bool Type::isObjCARCImplicitlyUnretainedType() const {
2350 assert(isObjCLifetimeType() &&
2351 "cannot query implicit lifetime for non-inferrable type");
2353 const Type *canon = getCanonicalTypeInternal().getTypePtr();
2355 // Walk down to the base type. We don't care about qualifiers for this.
2356 while (const ArrayType *array = dyn_cast<ArrayType>(canon))
2357 canon = array->getElementType().getTypePtr();
2359 if (const ObjCObjectPointerType *opt
2360 = dyn_cast<ObjCObjectPointerType>(canon)) {
2361 // Class and Class<Protocol> don't require retension.
2362 if (opt->getObjectType()->isObjCClass())
2369 bool Type::isObjCNSObjectType() const {
2370 if (const TypedefType *typedefType = dyn_cast<TypedefType>(this))
2371 return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>();
2374 bool Type::isObjCIndependentClassType() const {
2375 if (const TypedefType *typedefType = dyn_cast<TypedefType>(this))
2376 return typedefType->getDecl()->hasAttr<ObjCIndependentClassAttr>();
2379 bool Type::isObjCRetainableType() const {
2380 return isObjCObjectPointerType() ||
2381 isBlockPointerType() ||
2382 isObjCNSObjectType();
2384 bool Type::isObjCIndirectLifetimeType() const {
2385 if (isObjCLifetimeType())
2387 if (const PointerType *OPT = getAs<PointerType>())
2388 return OPT->getPointeeType()->isObjCIndirectLifetimeType();
2389 if (const ReferenceType *Ref = getAs<ReferenceType>())
2390 return Ref->getPointeeType()->isObjCIndirectLifetimeType();
2391 if (const MemberPointerType *MemPtr = getAs<MemberPointerType>())
2392 return MemPtr->getPointeeType()->isObjCIndirectLifetimeType();
2396 /// Returns true if objects of this type have lifetime semantics under
2398 bool Type::isObjCLifetimeType() const {
2399 const Type *type = this;
2400 while (const ArrayType *array = type->getAsArrayTypeUnsafe())
2401 type = array->getElementType().getTypePtr();
2402 return type->isObjCRetainableType();
2405 /// \brief Determine whether the given type T is a "bridgable" Objective-C type,
2406 /// which is either an Objective-C object pointer type or an
2407 bool Type::isObjCARCBridgableType() const {
2408 return isObjCObjectPointerType() || isBlockPointerType();
2411 /// \brief Determine whether the given type T is a "bridgeable" C type.
2412 bool Type::isCARCBridgableType() const {
2413 const PointerType *Pointer = getAs<PointerType>();
2417 QualType Pointee = Pointer->getPointeeType();
2418 return Pointee->isVoidType() || Pointee->isRecordType();
2421 bool Type::hasSizedVLAType() const {
2422 if (!isVariablyModifiedType()) return false;
2424 if (const PointerType *ptr = getAs<PointerType>())
2425 return ptr->getPointeeType()->hasSizedVLAType();
2426 if (const ReferenceType *ref = getAs<ReferenceType>())
2427 return ref->getPointeeType()->hasSizedVLAType();
2428 if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
2429 if (isa<VariableArrayType>(arr) &&
2430 cast<VariableArrayType>(arr)->getSizeExpr())
2433 return arr->getElementType()->hasSizedVLAType();
2439 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
2440 switch (type.getObjCLifetime()) {
2441 case Qualifiers::OCL_None:
2442 case Qualifiers::OCL_ExplicitNone:
2443 case Qualifiers::OCL_Autoreleasing:
2446 case Qualifiers::OCL_Strong:
2447 return DK_objc_strong_lifetime;
2448 case Qualifiers::OCL_Weak:
2449 return DK_objc_weak_lifetime;
2452 /// Currently, the only destruction kind we recognize is C++ objects
2453 /// with non-trivial destructors.
2454 const CXXRecordDecl *record =
2455 type->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2456 if (record && record->hasDefinition() && !record->hasTrivialDestructor())
2457 return DK_cxx_destructor;
2462 CXXRecordDecl *MemberPointerType::getMostRecentCXXRecordDecl() const {
2463 return getClass()->getAsCXXRecordDecl()->getMostRecentDecl();