1 //===- Type.cpp - Type representation and manipulation --------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements type-related functionality.
11 //===----------------------------------------------------------------------===//
13 #include "clang/AST/Type.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/CharUnits.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclBase.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclFriend.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/DependenceFlags.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/NestedNameSpecifier.h"
27 #include "clang/AST/NonTrivialTypeVisitor.h"
28 #include "clang/AST/PrettyPrinter.h"
29 #include "clang/AST/TemplateBase.h"
30 #include "clang/AST/TemplateName.h"
31 #include "clang/AST/TypeVisitor.h"
32 #include "clang/Basic/AddressSpaces.h"
33 #include "clang/Basic/ExceptionSpecificationType.h"
34 #include "clang/Basic/IdentifierTable.h"
35 #include "clang/Basic/LLVM.h"
36 #include "clang/Basic/LangOptions.h"
37 #include "clang/Basic/Linkage.h"
38 #include "clang/Basic/Specifiers.h"
39 #include "clang/Basic/TargetCXXABI.h"
40 #include "clang/Basic/TargetInfo.h"
41 #include "clang/Basic/Visibility.h"
42 #include "llvm/ADT/APInt.h"
43 #include "llvm/ADT/APSInt.h"
44 #include "llvm/ADT/ArrayRef.h"
45 #include "llvm/ADT/FoldingSet.h"
46 #include "llvm/ADT/SmallVector.h"
47 #include "llvm/Support/Casting.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/TargetParser/RISCVTargetParser.h"
56 #include <type_traits>
58 using namespace clang
;
60 bool Qualifiers::isStrictSupersetOf(Qualifiers Other
) const {
61 return (*this != Other
) &&
62 // CVR qualifiers superset
63 (((Mask
& CVRMask
) | (Other
.Mask
& CVRMask
)) == (Mask
& CVRMask
)) &&
64 // ObjC GC qualifiers superset
65 ((getObjCGCAttr() == Other
.getObjCGCAttr()) ||
66 (hasObjCGCAttr() && !Other
.hasObjCGCAttr())) &&
67 // Address space superset.
68 ((getAddressSpace() == Other
.getAddressSpace()) ||
69 (hasAddressSpace()&& !Other
.hasAddressSpace())) &&
70 // Lifetime qualifier superset.
71 ((getObjCLifetime() == Other
.getObjCLifetime()) ||
72 (hasObjCLifetime() && !Other
.hasObjCLifetime()));
75 const IdentifierInfo
* QualType::getBaseTypeIdentifier() const {
76 const Type
* ty
= getTypePtr();
77 NamedDecl
*ND
= nullptr;
78 if (ty
->isPointerType() || ty
->isReferenceType())
79 return ty
->getPointeeType().getBaseTypeIdentifier();
80 else if (ty
->isRecordType())
81 ND
= ty
->castAs
<RecordType
>()->getDecl();
82 else if (ty
->isEnumeralType())
83 ND
= ty
->castAs
<EnumType
>()->getDecl();
84 else if (ty
->getTypeClass() == Type::Typedef
)
85 ND
= ty
->castAs
<TypedefType
>()->getDecl();
86 else if (ty
->isArrayType())
87 return ty
->castAsArrayTypeUnsafe()->
88 getElementType().getBaseTypeIdentifier();
91 return ND
->getIdentifier();
95 bool QualType::mayBeDynamicClass() const {
96 const auto *ClassDecl
= getTypePtr()->getPointeeCXXRecordDecl();
97 return ClassDecl
&& ClassDecl
->mayBeDynamicClass();
100 bool QualType::mayBeNotDynamicClass() const {
101 const auto *ClassDecl
= getTypePtr()->getPointeeCXXRecordDecl();
102 return !ClassDecl
|| ClassDecl
->mayBeNonDynamicClass();
105 bool QualType::isConstant(QualType T
, const ASTContext
&Ctx
) {
106 if (T
.isConstQualified())
109 if (const ArrayType
*AT
= Ctx
.getAsArrayType(T
))
110 return AT
->getElementType().isConstant(Ctx
);
112 return T
.getAddressSpace() == LangAS::opencl_constant
;
115 std::optional
<QualType::NonConstantStorageReason
>
116 QualType::isNonConstantStorage(const ASTContext
&Ctx
, bool ExcludeCtor
,
118 if (!isConstant(Ctx
) && !(*this)->isReferenceType())
119 return NonConstantStorageReason::NonConstNonReferenceType
;
120 if (!Ctx
.getLangOpts().CPlusPlus
)
122 if (const CXXRecordDecl
*Record
=
123 Ctx
.getBaseElementType(*this)->getAsCXXRecordDecl()) {
125 return NonConstantStorageReason::NonTrivialCtor
;
126 if (Record
->hasMutableFields())
127 return NonConstantStorageReason::MutableField
;
128 if (!Record
->hasTrivialDestructor() && !ExcludeDtor
)
129 return NonConstantStorageReason::NonTrivialDtor
;
134 // C++ [temp.dep.type]p1:
135 // A type is dependent if it is...
136 // - an array type constructed from any dependent type or whose
137 // size is specified by a constant expression that is
139 ArrayType::ArrayType(TypeClass tc
, QualType et
, QualType can
,
140 ArraySizeModifier sm
, unsigned tq
, const Expr
*sz
)
141 // Note, we need to check for DependentSizedArrayType explicitly here
142 // because we use a DependentSizedArrayType with no size expression as the
143 // type of a dependent array of unknown bound with a dependent braced
146 // template<int ...N> int arr[] = {N...};
148 et
->getDependence() |
149 (sz
? toTypeDependence(
150 turnValueToTypeDependence(sz
->getDependence()))
151 : TypeDependence::None
) |
152 (tc
== VariableArray
? TypeDependence::VariablyModified
153 : TypeDependence::None
) |
154 (tc
== DependentSizedArray
155 ? TypeDependence::DependentInstantiation
156 : TypeDependence::None
)),
158 ArrayTypeBits
.IndexTypeQuals
= tq
;
159 ArrayTypeBits
.SizeModifier
= llvm::to_underlying(sm
);
162 unsigned ConstantArrayType::getNumAddressingBits(const ASTContext
&Context
,
163 QualType ElementType
,
164 const llvm::APInt
&NumElements
) {
165 uint64_t ElementSize
= Context
.getTypeSizeInChars(ElementType
).getQuantity();
167 // Fast path the common cases so we can avoid the conservative computation
168 // below, which in common cases allocates "large" APSInt values, which are
171 // If the element size is a power of 2, we can directly compute the additional
172 // number of addressing bits beyond those required for the element count.
173 if (llvm::isPowerOf2_64(ElementSize
)) {
174 return NumElements
.getActiveBits() + llvm::Log2_64(ElementSize
);
177 // If both the element count and element size fit in 32-bits, we can do the
178 // computation directly in 64-bits.
179 if ((ElementSize
>> 32) == 0 && NumElements
.getBitWidth() <= 64 &&
180 (NumElements
.getZExtValue() >> 32) == 0) {
181 uint64_t TotalSize
= NumElements
.getZExtValue() * ElementSize
;
182 return llvm::bit_width(TotalSize
);
185 // Otherwise, use APSInt to handle arbitrary sized values.
186 llvm::APSInt
SizeExtended(NumElements
, true);
187 unsigned SizeTypeBits
= Context
.getTypeSize(Context
.getSizeType());
188 SizeExtended
= SizeExtended
.extend(std::max(SizeTypeBits
,
189 SizeExtended
.getBitWidth()) * 2);
191 llvm::APSInt
TotalSize(llvm::APInt(SizeExtended
.getBitWidth(), ElementSize
));
192 TotalSize
*= SizeExtended
;
194 return TotalSize
.getActiveBits();
198 ConstantArrayType::getNumAddressingBits(const ASTContext
&Context
) const {
199 return getNumAddressingBits(Context
, getElementType(), getSize());
202 unsigned ConstantArrayType::getMaxSizeBits(const ASTContext
&Context
) {
203 unsigned Bits
= Context
.getTypeSize(Context
.getSizeType());
205 // Limit the number of bits in size_t so that maximal bit size fits 64 bit
206 // integer (see PR8256). We can do this as currently there is no hardware
207 // that supports full 64-bit virtual space.
214 void ConstantArrayType::Profile(llvm::FoldingSetNodeID
&ID
,
215 const ASTContext
&Context
, QualType ET
,
216 const llvm::APInt
&ArraySize
,
217 const Expr
*SizeExpr
, ArraySizeModifier SizeMod
,
218 unsigned TypeQuals
) {
219 ID
.AddPointer(ET
.getAsOpaquePtr());
220 ID
.AddInteger(ArraySize
.getZExtValue());
221 ID
.AddInteger(llvm::to_underlying(SizeMod
));
222 ID
.AddInteger(TypeQuals
);
223 ID
.AddBoolean(SizeExpr
!= nullptr);
225 SizeExpr
->Profile(ID
, Context
, true);
228 DependentSizedArrayType::DependentSizedArrayType(QualType et
, QualType can
,
229 Expr
*e
, ArraySizeModifier sm
,
231 SourceRange brackets
)
232 : ArrayType(DependentSizedArray
, et
, can
, sm
, tq
, e
), SizeExpr((Stmt
*)e
),
233 Brackets(brackets
) {}
235 void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID
&ID
,
236 const ASTContext
&Context
,
238 ArraySizeModifier SizeMod
,
241 ID
.AddPointer(ET
.getAsOpaquePtr());
242 ID
.AddInteger(llvm::to_underlying(SizeMod
));
243 ID
.AddInteger(TypeQuals
);
244 E
->Profile(ID
, Context
, true);
247 DependentVectorType::DependentVectorType(QualType ElementType
,
248 QualType CanonType
, Expr
*SizeExpr
,
249 SourceLocation Loc
, VectorKind VecKind
)
250 : Type(DependentVector
, CanonType
,
251 TypeDependence::DependentInstantiation
|
252 ElementType
->getDependence() |
253 (SizeExpr
? toTypeDependence(SizeExpr
->getDependence())
254 : TypeDependence::None
)),
255 ElementType(ElementType
), SizeExpr(SizeExpr
), Loc(Loc
) {
256 VectorTypeBits
.VecKind
= llvm::to_underlying(VecKind
);
259 void DependentVectorType::Profile(llvm::FoldingSetNodeID
&ID
,
260 const ASTContext
&Context
,
261 QualType ElementType
, const Expr
*SizeExpr
,
262 VectorKind VecKind
) {
263 ID
.AddPointer(ElementType
.getAsOpaquePtr());
264 ID
.AddInteger(llvm::to_underlying(VecKind
));
265 SizeExpr
->Profile(ID
, Context
, true);
268 DependentSizedExtVectorType::DependentSizedExtVectorType(QualType ElementType
,
272 : Type(DependentSizedExtVector
, can
,
273 TypeDependence::DependentInstantiation
|
274 ElementType
->getDependence() |
275 (SizeExpr
? toTypeDependence(SizeExpr
->getDependence())
276 : TypeDependence::None
)),
277 SizeExpr(SizeExpr
), ElementType(ElementType
), loc(loc
) {}
280 DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID
&ID
,
281 const ASTContext
&Context
,
282 QualType ElementType
, Expr
*SizeExpr
) {
283 ID
.AddPointer(ElementType
.getAsOpaquePtr());
284 SizeExpr
->Profile(ID
, Context
, true);
287 DependentAddressSpaceType::DependentAddressSpaceType(QualType PointeeType
,
291 : Type(DependentAddressSpace
, can
,
292 TypeDependence::DependentInstantiation
|
293 PointeeType
->getDependence() |
294 (AddrSpaceExpr
? toTypeDependence(AddrSpaceExpr
->getDependence())
295 : TypeDependence::None
)),
296 AddrSpaceExpr(AddrSpaceExpr
), PointeeType(PointeeType
), loc(loc
) {}
298 void DependentAddressSpaceType::Profile(llvm::FoldingSetNodeID
&ID
,
299 const ASTContext
&Context
,
300 QualType PointeeType
,
301 Expr
*AddrSpaceExpr
) {
302 ID
.AddPointer(PointeeType
.getAsOpaquePtr());
303 AddrSpaceExpr
->Profile(ID
, Context
, true);
306 MatrixType::MatrixType(TypeClass tc
, QualType matrixType
, QualType canonType
,
307 const Expr
*RowExpr
, const Expr
*ColumnExpr
)
308 : Type(tc
, canonType
,
309 (RowExpr
? (matrixType
->getDependence() | TypeDependence::Dependent
|
310 TypeDependence::Instantiation
|
311 (matrixType
->isVariablyModifiedType()
312 ? TypeDependence::VariablyModified
313 : TypeDependence::None
) |
314 (matrixType
->containsUnexpandedParameterPack() ||
316 RowExpr
->containsUnexpandedParameterPack()) ||
318 ColumnExpr
->containsUnexpandedParameterPack())
319 ? TypeDependence::UnexpandedPack
320 : TypeDependence::None
))
321 : matrixType
->getDependence())),
322 ElementType(matrixType
) {}
324 ConstantMatrixType::ConstantMatrixType(QualType matrixType
, unsigned nRows
,
325 unsigned nColumns
, QualType canonType
)
326 : ConstantMatrixType(ConstantMatrix
, matrixType
, nRows
, nColumns
,
329 ConstantMatrixType::ConstantMatrixType(TypeClass tc
, QualType matrixType
,
330 unsigned nRows
, unsigned nColumns
,
332 : MatrixType(tc
, matrixType
, canonType
), NumRows(nRows
),
333 NumColumns(nColumns
) {}
335 DependentSizedMatrixType::DependentSizedMatrixType(QualType ElementType
,
336 QualType CanonicalType
,
340 : MatrixType(DependentSizedMatrix
, ElementType
, CanonicalType
, RowExpr
,
342 RowExpr(RowExpr
), ColumnExpr(ColumnExpr
), loc(loc
) {}
344 void DependentSizedMatrixType::Profile(llvm::FoldingSetNodeID
&ID
,
345 const ASTContext
&CTX
,
346 QualType ElementType
, Expr
*RowExpr
,
348 ID
.AddPointer(ElementType
.getAsOpaquePtr());
349 RowExpr
->Profile(ID
, CTX
, true);
350 ColumnExpr
->Profile(ID
, CTX
, true);
353 VectorType::VectorType(QualType vecType
, unsigned nElements
, QualType canonType
,
355 : VectorType(Vector
, vecType
, nElements
, canonType
, vecKind
) {}
357 VectorType::VectorType(TypeClass tc
, QualType vecType
, unsigned nElements
,
358 QualType canonType
, VectorKind vecKind
)
359 : Type(tc
, canonType
, vecType
->getDependence()), ElementType(vecType
) {
360 VectorTypeBits
.VecKind
= llvm::to_underlying(vecKind
);
361 VectorTypeBits
.NumElements
= nElements
;
364 BitIntType::BitIntType(bool IsUnsigned
, unsigned NumBits
)
365 : Type(BitInt
, QualType
{}, TypeDependence::None
), IsUnsigned(IsUnsigned
),
368 DependentBitIntType::DependentBitIntType(bool IsUnsigned
, Expr
*NumBitsExpr
)
369 : Type(DependentBitInt
, QualType
{},
370 toTypeDependence(NumBitsExpr
->getDependence())),
371 ExprAndUnsigned(NumBitsExpr
, IsUnsigned
) {}
373 bool DependentBitIntType::isUnsigned() const {
374 return ExprAndUnsigned
.getInt();
377 clang::Expr
*DependentBitIntType::getNumBitsExpr() const {
378 return ExprAndUnsigned
.getPointer();
381 void DependentBitIntType::Profile(llvm::FoldingSetNodeID
&ID
,
382 const ASTContext
&Context
, bool IsUnsigned
,
384 ID
.AddBoolean(IsUnsigned
);
385 NumBitsExpr
->Profile(ID
, Context
, true);
388 /// getArrayElementTypeNoTypeQual - If this is an array type, return the
389 /// element type of the array, potentially with type qualifiers missing.
390 /// This method should never be used when type qualifiers are meaningful.
391 const Type
*Type::getArrayElementTypeNoTypeQual() const {
392 // If this is directly an array type, return it.
393 if (const auto *ATy
= dyn_cast
<ArrayType
>(this))
394 return ATy
->getElementType().getTypePtr();
396 // If the canonical form of this type isn't the right kind, reject it.
397 if (!isa
<ArrayType
>(CanonicalType
))
400 // If this is a typedef for an array type, strip the typedef off without
401 // losing all typedef information.
402 return cast
<ArrayType
>(getUnqualifiedDesugaredType())
403 ->getElementType().getTypePtr();
406 /// getDesugaredType - Return the specified type with any "sugar" removed from
407 /// the type. This takes off typedefs, typeof's etc. If the outer level of
408 /// the type is already concrete, it returns it unmodified. This is similar
409 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
410 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
412 QualType
QualType::getDesugaredType(QualType T
, const ASTContext
&Context
) {
413 SplitQualType split
= getSplitDesugaredType(T
);
414 return Context
.getQualifiedType(split
.Ty
, split
.Quals
);
417 QualType
QualType::getSingleStepDesugaredTypeImpl(QualType type
,
418 const ASTContext
&Context
) {
419 SplitQualType split
= type
.split();
420 QualType desugar
= split
.Ty
->getLocallyUnqualifiedSingleStepDesugaredType();
421 return Context
.getQualifiedType(desugar
, split
.Quals
);
424 // Check that no type class is polymorphic. LLVM style RTTI should be used
425 // instead. If absolutely needed an exception can still be added here by
426 // defining the appropriate macro (but please don't do this).
427 #define TYPE(CLASS, BASE) \
428 static_assert(!std::is_polymorphic<CLASS##Type>::value, \
429 #CLASS "Type should not be polymorphic!");
430 #include "clang/AST/TypeNodes.inc"
432 // Check that no type class has a non-trival destructor. Types are
433 // allocated with the BumpPtrAllocator from ASTContext and therefore
434 // their destructor is not executed.
436 // FIXME: ConstantArrayType is not trivially destructible because of its
437 // APInt member. It should be replaced in favor of ASTContext allocation.
438 #define TYPE(CLASS, BASE) \
439 static_assert(std::is_trivially_destructible<CLASS##Type>::value || \
440 std::is_same<CLASS##Type, ConstantArrayType>::value, \
441 #CLASS "Type should be trivially destructible!");
442 #include "clang/AST/TypeNodes.inc"
444 QualType
Type::getLocallyUnqualifiedSingleStepDesugaredType() const {
445 switch (getTypeClass()) {
446 #define ABSTRACT_TYPE(Class, Parent)
447 #define TYPE(Class, Parent) \
448 case Type::Class: { \
449 const auto *ty = cast<Class##Type>(this); \
450 if (!ty->isSugared()) return QualType(ty, 0); \
451 return ty->desugar(); \
453 #include "clang/AST/TypeNodes.inc"
455 llvm_unreachable("bad type kind!");
458 SplitQualType
QualType::getSplitDesugaredType(QualType T
) {
459 QualifierCollector Qs
;
463 const Type
*CurTy
= Qs
.strip(Cur
);
464 switch (CurTy
->getTypeClass()) {
465 #define ABSTRACT_TYPE(Class, Parent)
466 #define TYPE(Class, Parent) \
467 case Type::Class: { \
468 const auto *Ty = cast<Class##Type>(CurTy); \
469 if (!Ty->isSugared()) \
470 return SplitQualType(Ty, Qs); \
471 Cur = Ty->desugar(); \
474 #include "clang/AST/TypeNodes.inc"
479 SplitQualType
QualType::getSplitUnqualifiedTypeImpl(QualType type
) {
480 SplitQualType split
= type
.split();
482 // All the qualifiers we've seen so far.
483 Qualifiers quals
= split
.Quals
;
485 // The last type node we saw with any nodes inside it.
486 const Type
*lastTypeWithQuals
= split
.Ty
;
491 // Do a single-step desugar, aborting the loop if the type isn't
493 switch (split
.Ty
->getTypeClass()) {
494 #define ABSTRACT_TYPE(Class, Parent)
495 #define TYPE(Class, Parent) \
496 case Type::Class: { \
497 const auto *ty = cast<Class##Type>(split.Ty); \
498 if (!ty->isSugared()) goto done; \
499 next = ty->desugar(); \
502 #include "clang/AST/TypeNodes.inc"
505 // Otherwise, split the underlying type. If that yields qualifiers,
506 // update the information.
507 split
= next
.split();
508 if (!split
.Quals
.empty()) {
509 lastTypeWithQuals
= split
.Ty
;
510 quals
.addConsistentQualifiers(split
.Quals
);
515 return SplitQualType(lastTypeWithQuals
, quals
);
518 QualType
QualType::IgnoreParens(QualType T
) {
519 // FIXME: this seems inherently un-qualifiers-safe.
520 while (const auto *PT
= T
->getAs
<ParenType
>())
521 T
= PT
->getInnerType();
525 /// This will check for a T (which should be a Type which can act as
526 /// sugar, such as a TypedefType) by removing any existing sugar until it
527 /// reaches a T or a non-sugared type.
528 template<typename T
> static const T
*getAsSugar(const Type
*Cur
) {
530 if (const auto *Sugar
= dyn_cast
<T
>(Cur
))
532 switch (Cur
->getTypeClass()) {
533 #define ABSTRACT_TYPE(Class, Parent)
534 #define TYPE(Class, Parent) \
535 case Type::Class: { \
536 const auto *Ty = cast<Class##Type>(Cur); \
537 if (!Ty->isSugared()) return 0; \
538 Cur = Ty->desugar().getTypePtr(); \
541 #include "clang/AST/TypeNodes.inc"
546 template <> const TypedefType
*Type::getAs() const {
547 return getAsSugar
<TypedefType
>(this);
550 template <> const UsingType
*Type::getAs() const {
551 return getAsSugar
<UsingType
>(this);
554 template <> const TemplateSpecializationType
*Type::getAs() const {
555 return getAsSugar
<TemplateSpecializationType
>(this);
558 template <> const AttributedType
*Type::getAs() const {
559 return getAsSugar
<AttributedType
>(this);
562 /// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
563 /// sugar off the given type. This should produce an object of the
564 /// same dynamic type as the canonical type.
565 const Type
*Type::getUnqualifiedDesugaredType() const {
566 const Type
*Cur
= this;
569 switch (Cur
->getTypeClass()) {
570 #define ABSTRACT_TYPE(Class, Parent)
571 #define TYPE(Class, Parent) \
573 const auto *Ty = cast<Class##Type>(Cur); \
574 if (!Ty->isSugared()) return Cur; \
575 Cur = Ty->desugar().getTypePtr(); \
578 #include "clang/AST/TypeNodes.inc"
583 bool Type::isClassType() const {
584 if (const auto *RT
= getAs
<RecordType
>())
585 return RT
->getDecl()->isClass();
589 bool Type::isStructureType() const {
590 if (const auto *RT
= getAs
<RecordType
>())
591 return RT
->getDecl()->isStruct();
595 bool Type::isObjCBoxableRecordType() const {
596 if (const auto *RT
= getAs
<RecordType
>())
597 return RT
->getDecl()->hasAttr
<ObjCBoxableAttr
>();
601 bool Type::isInterfaceType() const {
602 if (const auto *RT
= getAs
<RecordType
>())
603 return RT
->getDecl()->isInterface();
607 bool Type::isStructureOrClassType() const {
608 if (const auto *RT
= getAs
<RecordType
>()) {
609 RecordDecl
*RD
= RT
->getDecl();
610 return RD
->isStruct() || RD
->isClass() || RD
->isInterface();
615 bool Type::isVoidPointerType() const {
616 if (const auto *PT
= getAs
<PointerType
>())
617 return PT
->getPointeeType()->isVoidType();
621 bool Type::isUnionType() const {
622 if (const auto *RT
= getAs
<RecordType
>())
623 return RT
->getDecl()->isUnion();
627 bool Type::isComplexType() const {
628 if (const auto *CT
= dyn_cast
<ComplexType
>(CanonicalType
))
629 return CT
->getElementType()->isFloatingType();
633 bool Type::isComplexIntegerType() const {
634 // Check for GCC complex integer extension.
635 return getAsComplexIntegerType();
638 bool Type::isScopedEnumeralType() const {
639 if (const auto *ET
= getAs
<EnumType
>())
640 return ET
->getDecl()->isScoped();
644 const ComplexType
*Type::getAsComplexIntegerType() const {
645 if (const auto *Complex
= getAs
<ComplexType
>())
646 if (Complex
->getElementType()->isIntegerType())
651 QualType
Type::getPointeeType() const {
652 if (const auto *PT
= getAs
<PointerType
>())
653 return PT
->getPointeeType();
654 if (const auto *OPT
= getAs
<ObjCObjectPointerType
>())
655 return OPT
->getPointeeType();
656 if (const auto *BPT
= getAs
<BlockPointerType
>())
657 return BPT
->getPointeeType();
658 if (const auto *RT
= getAs
<ReferenceType
>())
659 return RT
->getPointeeType();
660 if (const auto *MPT
= getAs
<MemberPointerType
>())
661 return MPT
->getPointeeType();
662 if (const auto *DT
= getAs
<DecayedType
>())
663 return DT
->getPointeeType();
667 const RecordType
*Type::getAsStructureType() const {
668 // If this is directly a structure type, return it.
669 if (const auto *RT
= dyn_cast
<RecordType
>(this)) {
670 if (RT
->getDecl()->isStruct())
674 // If the canonical form of this type isn't the right kind, reject it.
675 if (const auto *RT
= dyn_cast
<RecordType
>(CanonicalType
)) {
676 if (!RT
->getDecl()->isStruct())
679 // If this is a typedef for a structure type, strip the typedef off without
680 // losing all typedef information.
681 return cast
<RecordType
>(getUnqualifiedDesugaredType());
686 const RecordType
*Type::getAsUnionType() const {
687 // If this is directly a union type, return it.
688 if (const auto *RT
= dyn_cast
<RecordType
>(this)) {
689 if (RT
->getDecl()->isUnion())
693 // If the canonical form of this type isn't the right kind, reject it.
694 if (const auto *RT
= dyn_cast
<RecordType
>(CanonicalType
)) {
695 if (!RT
->getDecl()->isUnion())
698 // If this is a typedef for a union type, strip the typedef off without
699 // losing all typedef information.
700 return cast
<RecordType
>(getUnqualifiedDesugaredType());
706 bool Type::isObjCIdOrObjectKindOfType(const ASTContext
&ctx
,
707 const ObjCObjectType
*&bound
) const {
710 const auto *OPT
= getAs
<ObjCObjectPointerType
>();
715 if (OPT
->isObjCIdType())
718 // If it's not a __kindof type, reject it now.
719 if (!OPT
->isKindOfType())
722 // If it's Class or qualified Class, it's not an object type.
723 if (OPT
->isObjCClassType() || OPT
->isObjCQualifiedClassType())
726 // Figure out the type bound for the __kindof type.
727 bound
= OPT
->getObjectType()->stripObjCKindOfTypeAndQuals(ctx
)
728 ->getAs
<ObjCObjectType
>();
732 bool Type::isObjCClassOrClassKindOfType() const {
733 const auto *OPT
= getAs
<ObjCObjectPointerType
>();
738 if (OPT
->isObjCClassType())
741 // If it's not a __kindof type, reject it now.
742 if (!OPT
->isKindOfType())
745 // If it's Class or qualified Class, it's a class __kindof type.
746 return OPT
->isObjCClassType() || OPT
->isObjCQualifiedClassType();
749 ObjCTypeParamType::ObjCTypeParamType(const ObjCTypeParamDecl
*D
, QualType can
,
750 ArrayRef
<ObjCProtocolDecl
*> protocols
)
751 : Type(ObjCTypeParam
, can
, toSemanticDependence(can
->getDependence())),
752 OTPDecl(const_cast<ObjCTypeParamDecl
*>(D
)) {
753 initialize(protocols
);
756 ObjCObjectType::ObjCObjectType(QualType Canonical
, QualType Base
,
757 ArrayRef
<QualType
> typeArgs
,
758 ArrayRef
<ObjCProtocolDecl
*> protocols
,
760 : Type(ObjCObject
, Canonical
, Base
->getDependence()), BaseType(Base
) {
761 ObjCObjectTypeBits
.IsKindOf
= isKindOf
;
763 ObjCObjectTypeBits
.NumTypeArgs
= typeArgs
.size();
764 assert(getTypeArgsAsWritten().size() == typeArgs
.size() &&
765 "bitfield overflow in type argument count");
766 if (!typeArgs
.empty())
767 memcpy(getTypeArgStorage(), typeArgs
.data(),
768 typeArgs
.size() * sizeof(QualType
));
770 for (auto typeArg
: typeArgs
) {
771 addDependence(typeArg
->getDependence() & ~TypeDependence::VariablyModified
);
773 // Initialize the protocol qualifiers. The protocol storage is known
774 // after we set number of type arguments.
775 initialize(protocols
);
778 bool ObjCObjectType::isSpecialized() const {
779 // If we have type arguments written here, the type is specialized.
780 if (ObjCObjectTypeBits
.NumTypeArgs
> 0)
783 // Otherwise, check whether the base type is specialized.
784 if (const auto objcObject
= getBaseType()->getAs
<ObjCObjectType
>()) {
785 // Terminate when we reach an interface type.
786 if (isa
<ObjCInterfaceType
>(objcObject
))
789 return objcObject
->isSpecialized();
796 ArrayRef
<QualType
> ObjCObjectType::getTypeArgs() const {
797 // We have type arguments written on this type.
798 if (isSpecializedAsWritten())
799 return getTypeArgsAsWritten();
801 // Look at the base type, which might have type arguments.
802 if (const auto objcObject
= getBaseType()->getAs
<ObjCObjectType
>()) {
803 // Terminate when we reach an interface type.
804 if (isa
<ObjCInterfaceType
>(objcObject
))
807 return objcObject
->getTypeArgs();
810 // No type arguments.
814 bool ObjCObjectType::isKindOfType() const {
815 if (isKindOfTypeAsWritten())
818 // Look at the base type, which might have type arguments.
819 if (const auto objcObject
= getBaseType()->getAs
<ObjCObjectType
>()) {
820 // Terminate when we reach an interface type.
821 if (isa
<ObjCInterfaceType
>(objcObject
))
824 return objcObject
->isKindOfType();
827 // Not a "__kindof" type.
831 QualType
ObjCObjectType::stripObjCKindOfTypeAndQuals(
832 const ASTContext
&ctx
) const {
833 if (!isKindOfType() && qual_empty())
834 return QualType(this, 0);
836 // Recursively strip __kindof.
837 SplitQualType splitBaseType
= getBaseType().split();
838 QualType
baseType(splitBaseType
.Ty
, 0);
839 if (const auto *baseObj
= splitBaseType
.Ty
->getAs
<ObjCObjectType
>())
840 baseType
= baseObj
->stripObjCKindOfTypeAndQuals(ctx
);
842 return ctx
.getObjCObjectType(ctx
.getQualifiedType(baseType
,
843 splitBaseType
.Quals
),
844 getTypeArgsAsWritten(),
849 ObjCInterfaceDecl
*ObjCInterfaceType::getDecl() const {
850 ObjCInterfaceDecl
*Canon
= Decl
->getCanonicalDecl();
851 if (ObjCInterfaceDecl
*Def
= Canon
->getDefinition())
856 const ObjCObjectPointerType
*ObjCObjectPointerType::stripObjCKindOfTypeAndQuals(
857 const ASTContext
&ctx
) const {
858 if (!isKindOfType() && qual_empty())
861 QualType obj
= getObjectType()->stripObjCKindOfTypeAndQuals(ctx
);
862 return ctx
.getObjCObjectPointerType(obj
)->castAs
<ObjCObjectPointerType
>();
867 /// Visitor used to perform a simple type transformation that does not change
868 /// the semantics of the type.
869 template <typename Derived
>
870 struct SimpleTransformVisitor
: public TypeVisitor
<Derived
, QualType
> {
873 QualType
recurse(QualType type
) {
874 // Split out the qualifiers from the type.
875 SplitQualType splitType
= type
.split();
877 // Visit the type itself.
878 QualType result
= static_cast<Derived
*>(this)->Visit(splitType
.Ty
);
882 // Reconstruct the transformed type by applying the local qualifiers
883 // from the split type.
884 return Ctx
.getQualifiedType(result
, splitType
.Quals
);
888 explicit SimpleTransformVisitor(ASTContext
&ctx
) : Ctx(ctx
) {}
890 // None of the clients of this transformation can occur where
891 // there are dependent types, so skip dependent types.
892 #define TYPE(Class, Base)
893 #define DEPENDENT_TYPE(Class, Base) \
894 QualType Visit##Class##Type(const Class##Type *T) { return QualType(T, 0); }
895 #include "clang/AST/TypeNodes.inc"
897 #define TRIVIAL_TYPE_CLASS(Class) \
898 QualType Visit##Class##Type(const Class##Type *T) { return QualType(T, 0); }
899 #define SUGARED_TYPE_CLASS(Class) \
900 QualType Visit##Class##Type(const Class##Type *T) { \
901 if (!T->isSugared()) \
902 return QualType(T, 0); \
903 QualType desugaredType = recurse(T->desugar()); \
904 if (desugaredType.isNull()) \
906 if (desugaredType.getAsOpaquePtr() == T->desugar().getAsOpaquePtr()) \
907 return QualType(T, 0); \
908 return desugaredType; \
911 TRIVIAL_TYPE_CLASS(Builtin
)
913 QualType
VisitComplexType(const ComplexType
*T
) {
914 QualType elementType
= recurse(T
->getElementType());
915 if (elementType
.isNull())
918 if (elementType
.getAsOpaquePtr() == T
->getElementType().getAsOpaquePtr())
919 return QualType(T
, 0);
921 return Ctx
.getComplexType(elementType
);
924 QualType
VisitPointerType(const PointerType
*T
) {
925 QualType pointeeType
= recurse(T
->getPointeeType());
926 if (pointeeType
.isNull())
929 if (pointeeType
.getAsOpaquePtr() == T
->getPointeeType().getAsOpaquePtr())
930 return QualType(T
, 0);
932 return Ctx
.getPointerType(pointeeType
);
935 QualType
VisitBlockPointerType(const BlockPointerType
*T
) {
936 QualType pointeeType
= recurse(T
->getPointeeType());
937 if (pointeeType
.isNull())
940 if (pointeeType
.getAsOpaquePtr() == T
->getPointeeType().getAsOpaquePtr())
941 return QualType(T
, 0);
943 return Ctx
.getBlockPointerType(pointeeType
);
946 QualType
VisitLValueReferenceType(const LValueReferenceType
*T
) {
947 QualType pointeeType
= recurse(T
->getPointeeTypeAsWritten());
948 if (pointeeType
.isNull())
951 if (pointeeType
.getAsOpaquePtr()
952 == T
->getPointeeTypeAsWritten().getAsOpaquePtr())
953 return QualType(T
, 0);
955 return Ctx
.getLValueReferenceType(pointeeType
, T
->isSpelledAsLValue());
958 QualType
VisitRValueReferenceType(const RValueReferenceType
*T
) {
959 QualType pointeeType
= recurse(T
->getPointeeTypeAsWritten());
960 if (pointeeType
.isNull())
963 if (pointeeType
.getAsOpaquePtr()
964 == T
->getPointeeTypeAsWritten().getAsOpaquePtr())
965 return QualType(T
, 0);
967 return Ctx
.getRValueReferenceType(pointeeType
);
970 QualType
VisitMemberPointerType(const MemberPointerType
*T
) {
971 QualType pointeeType
= recurse(T
->getPointeeType());
972 if (pointeeType
.isNull())
975 if (pointeeType
.getAsOpaquePtr() == T
->getPointeeType().getAsOpaquePtr())
976 return QualType(T
, 0);
978 return Ctx
.getMemberPointerType(pointeeType
, T
->getClass());
981 QualType
VisitConstantArrayType(const ConstantArrayType
*T
) {
982 QualType elementType
= recurse(T
->getElementType());
983 if (elementType
.isNull())
986 if (elementType
.getAsOpaquePtr() == T
->getElementType().getAsOpaquePtr())
987 return QualType(T
, 0);
989 return Ctx
.getConstantArrayType(elementType
, T
->getSize(), T
->getSizeExpr(),
990 T
->getSizeModifier(),
991 T
->getIndexTypeCVRQualifiers());
994 QualType
VisitVariableArrayType(const VariableArrayType
*T
) {
995 QualType elementType
= recurse(T
->getElementType());
996 if (elementType
.isNull())
999 if (elementType
.getAsOpaquePtr() == T
->getElementType().getAsOpaquePtr())
1000 return QualType(T
, 0);
1002 return Ctx
.getVariableArrayType(elementType
, T
->getSizeExpr(),
1003 T
->getSizeModifier(),
1004 T
->getIndexTypeCVRQualifiers(),
1005 T
->getBracketsRange());
1008 QualType
VisitIncompleteArrayType(const IncompleteArrayType
*T
) {
1009 QualType elementType
= recurse(T
->getElementType());
1010 if (elementType
.isNull())
1013 if (elementType
.getAsOpaquePtr() == T
->getElementType().getAsOpaquePtr())
1014 return QualType(T
, 0);
1016 return Ctx
.getIncompleteArrayType(elementType
, T
->getSizeModifier(),
1017 T
->getIndexTypeCVRQualifiers());
1020 QualType
VisitVectorType(const VectorType
*T
) {
1021 QualType elementType
= recurse(T
->getElementType());
1022 if (elementType
.isNull())
1025 if (elementType
.getAsOpaquePtr() == T
->getElementType().getAsOpaquePtr())
1026 return QualType(T
, 0);
1028 return Ctx
.getVectorType(elementType
, T
->getNumElements(),
1029 T
->getVectorKind());
1032 QualType
VisitExtVectorType(const ExtVectorType
*T
) {
1033 QualType elementType
= recurse(T
->getElementType());
1034 if (elementType
.isNull())
1037 if (elementType
.getAsOpaquePtr() == T
->getElementType().getAsOpaquePtr())
1038 return QualType(T
, 0);
1040 return Ctx
.getExtVectorType(elementType
, T
->getNumElements());
1043 QualType
VisitConstantMatrixType(const ConstantMatrixType
*T
) {
1044 QualType elementType
= recurse(T
->getElementType());
1045 if (elementType
.isNull())
1047 if (elementType
.getAsOpaquePtr() == T
->getElementType().getAsOpaquePtr())
1048 return QualType(T
, 0);
1050 return Ctx
.getConstantMatrixType(elementType
, T
->getNumRows(),
1051 T
->getNumColumns());
1054 QualType
VisitFunctionNoProtoType(const FunctionNoProtoType
*T
) {
1055 QualType returnType
= recurse(T
->getReturnType());
1056 if (returnType
.isNull())
1059 if (returnType
.getAsOpaquePtr() == T
->getReturnType().getAsOpaquePtr())
1060 return QualType(T
, 0);
1062 return Ctx
.getFunctionNoProtoType(returnType
, T
->getExtInfo());
1065 QualType
VisitFunctionProtoType(const FunctionProtoType
*T
) {
1066 QualType returnType
= recurse(T
->getReturnType());
1067 if (returnType
.isNull())
1070 // Transform parameter types.
1071 SmallVector
<QualType
, 4> paramTypes
;
1072 bool paramChanged
= false;
1073 for (auto paramType
: T
->getParamTypes()) {
1074 QualType newParamType
= recurse(paramType
);
1075 if (newParamType
.isNull())
1078 if (newParamType
.getAsOpaquePtr() != paramType
.getAsOpaquePtr())
1079 paramChanged
= true;
1081 paramTypes
.push_back(newParamType
);
1084 // Transform extended info.
1085 FunctionProtoType::ExtProtoInfo info
= T
->getExtProtoInfo();
1086 bool exceptionChanged
= false;
1087 if (info
.ExceptionSpec
.Type
== EST_Dynamic
) {
1088 SmallVector
<QualType
, 4> exceptionTypes
;
1089 for (auto exceptionType
: info
.ExceptionSpec
.Exceptions
) {
1090 QualType newExceptionType
= recurse(exceptionType
);
1091 if (newExceptionType
.isNull())
1094 if (newExceptionType
.getAsOpaquePtr() != exceptionType
.getAsOpaquePtr())
1095 exceptionChanged
= true;
1097 exceptionTypes
.push_back(newExceptionType
);
1100 if (exceptionChanged
) {
1101 info
.ExceptionSpec
.Exceptions
=
1102 llvm::ArrayRef(exceptionTypes
).copy(Ctx
);
1106 if (returnType
.getAsOpaquePtr() == T
->getReturnType().getAsOpaquePtr() &&
1107 !paramChanged
&& !exceptionChanged
)
1108 return QualType(T
, 0);
1110 return Ctx
.getFunctionType(returnType
, paramTypes
, info
);
1113 QualType
VisitParenType(const ParenType
*T
) {
1114 QualType innerType
= recurse(T
->getInnerType());
1115 if (innerType
.isNull())
1118 if (innerType
.getAsOpaquePtr() == T
->getInnerType().getAsOpaquePtr())
1119 return QualType(T
, 0);
1121 return Ctx
.getParenType(innerType
);
1124 SUGARED_TYPE_CLASS(Typedef
)
1125 SUGARED_TYPE_CLASS(ObjCTypeParam
)
1126 SUGARED_TYPE_CLASS(MacroQualified
)
1128 QualType
VisitAdjustedType(const AdjustedType
*T
) {
1129 QualType originalType
= recurse(T
->getOriginalType());
1130 if (originalType
.isNull())
1133 QualType adjustedType
= recurse(T
->getAdjustedType());
1134 if (adjustedType
.isNull())
1137 if (originalType
.getAsOpaquePtr()
1138 == T
->getOriginalType().getAsOpaquePtr() &&
1139 adjustedType
.getAsOpaquePtr() == T
->getAdjustedType().getAsOpaquePtr())
1140 return QualType(T
, 0);
1142 return Ctx
.getAdjustedType(originalType
, adjustedType
);
1145 QualType
VisitDecayedType(const DecayedType
*T
) {
1146 QualType originalType
= recurse(T
->getOriginalType());
1147 if (originalType
.isNull())
1150 if (originalType
.getAsOpaquePtr()
1151 == T
->getOriginalType().getAsOpaquePtr())
1152 return QualType(T
, 0);
1154 return Ctx
.getDecayedType(originalType
);
1157 SUGARED_TYPE_CLASS(TypeOfExpr
)
1158 SUGARED_TYPE_CLASS(TypeOf
)
1159 SUGARED_TYPE_CLASS(Decltype
)
1160 SUGARED_TYPE_CLASS(UnaryTransform
)
1161 TRIVIAL_TYPE_CLASS(Record
)
1162 TRIVIAL_TYPE_CLASS(Enum
)
1164 // FIXME: Non-trivial to implement, but important for C++
1165 SUGARED_TYPE_CLASS(Elaborated
)
1167 QualType
VisitAttributedType(const AttributedType
*T
) {
1168 QualType modifiedType
= recurse(T
->getModifiedType());
1169 if (modifiedType
.isNull())
1172 QualType equivalentType
= recurse(T
->getEquivalentType());
1173 if (equivalentType
.isNull())
1176 if (modifiedType
.getAsOpaquePtr()
1177 == T
->getModifiedType().getAsOpaquePtr() &&
1178 equivalentType
.getAsOpaquePtr()
1179 == T
->getEquivalentType().getAsOpaquePtr())
1180 return QualType(T
, 0);
1182 return Ctx
.getAttributedType(T
->getAttrKind(), modifiedType
,
1186 QualType
VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType
*T
) {
1187 QualType replacementType
= recurse(T
->getReplacementType());
1188 if (replacementType
.isNull())
1191 if (replacementType
.getAsOpaquePtr()
1192 == T
->getReplacementType().getAsOpaquePtr())
1193 return QualType(T
, 0);
1195 return Ctx
.getSubstTemplateTypeParmType(replacementType
,
1196 T
->getAssociatedDecl(),
1197 T
->getIndex(), T
->getPackIndex());
1200 // FIXME: Non-trivial to implement, but important for C++
1201 SUGARED_TYPE_CLASS(TemplateSpecialization
)
1203 QualType
VisitAutoType(const AutoType
*T
) {
1204 if (!T
->isDeduced())
1205 return QualType(T
, 0);
1207 QualType deducedType
= recurse(T
->getDeducedType());
1208 if (deducedType
.isNull())
1211 if (deducedType
.getAsOpaquePtr()
1212 == T
->getDeducedType().getAsOpaquePtr())
1213 return QualType(T
, 0);
1215 return Ctx
.getAutoType(deducedType
, T
->getKeyword(),
1216 T
->isDependentType(), /*IsPack=*/false,
1217 T
->getTypeConstraintConcept(),
1218 T
->getTypeConstraintArguments());
1221 QualType
VisitObjCObjectType(const ObjCObjectType
*T
) {
1222 QualType baseType
= recurse(T
->getBaseType());
1223 if (baseType
.isNull())
1226 // Transform type arguments.
1227 bool typeArgChanged
= false;
1228 SmallVector
<QualType
, 4> typeArgs
;
1229 for (auto typeArg
: T
->getTypeArgsAsWritten()) {
1230 QualType newTypeArg
= recurse(typeArg
);
1231 if (newTypeArg
.isNull())
1234 if (newTypeArg
.getAsOpaquePtr() != typeArg
.getAsOpaquePtr())
1235 typeArgChanged
= true;
1237 typeArgs
.push_back(newTypeArg
);
1240 if (baseType
.getAsOpaquePtr() == T
->getBaseType().getAsOpaquePtr() &&
1242 return QualType(T
, 0);
1244 return Ctx
.getObjCObjectType(
1246 llvm::ArrayRef(T
->qual_begin(), T
->getNumProtocols()),
1247 T
->isKindOfTypeAsWritten());
1250 TRIVIAL_TYPE_CLASS(ObjCInterface
)
1252 QualType
VisitObjCObjectPointerType(const ObjCObjectPointerType
*T
) {
1253 QualType pointeeType
= recurse(T
->getPointeeType());
1254 if (pointeeType
.isNull())
1257 if (pointeeType
.getAsOpaquePtr()
1258 == T
->getPointeeType().getAsOpaquePtr())
1259 return QualType(T
, 0);
1261 return Ctx
.getObjCObjectPointerType(pointeeType
);
1264 QualType
VisitAtomicType(const AtomicType
*T
) {
1265 QualType valueType
= recurse(T
->getValueType());
1266 if (valueType
.isNull())
1269 if (valueType
.getAsOpaquePtr()
1270 == T
->getValueType().getAsOpaquePtr())
1271 return QualType(T
, 0);
1273 return Ctx
.getAtomicType(valueType
);
1276 #undef TRIVIAL_TYPE_CLASS
1277 #undef SUGARED_TYPE_CLASS
1280 struct SubstObjCTypeArgsVisitor
1281 : public SimpleTransformVisitor
<SubstObjCTypeArgsVisitor
> {
1282 using BaseType
= SimpleTransformVisitor
<SubstObjCTypeArgsVisitor
>;
1284 ArrayRef
<QualType
> TypeArgs
;
1285 ObjCSubstitutionContext SubstContext
;
1287 SubstObjCTypeArgsVisitor(ASTContext
&ctx
, ArrayRef
<QualType
> typeArgs
,
1288 ObjCSubstitutionContext context
)
1289 : BaseType(ctx
), TypeArgs(typeArgs
), SubstContext(context
) {}
1291 QualType
VisitObjCTypeParamType(const ObjCTypeParamType
*OTPTy
) {
1292 // Replace an Objective-C type parameter reference with the corresponding
1294 ObjCTypeParamDecl
*typeParam
= OTPTy
->getDecl();
1295 // If we have type arguments, use them.
1296 if (!TypeArgs
.empty()) {
1297 QualType argType
= TypeArgs
[typeParam
->getIndex()];
1298 if (OTPTy
->qual_empty())
1301 // Apply protocol lists if exists.
1303 SmallVector
<ObjCProtocolDecl
*, 8> protocolsVec
;
1304 protocolsVec
.append(OTPTy
->qual_begin(), OTPTy
->qual_end());
1305 ArrayRef
<ObjCProtocolDecl
*> protocolsToApply
= protocolsVec
;
1306 return Ctx
.applyObjCProtocolQualifiers(
1307 argType
, protocolsToApply
, hasError
, true/*allowOnPointerType*/);
1310 switch (SubstContext
) {
1311 case ObjCSubstitutionContext::Ordinary
:
1312 case ObjCSubstitutionContext::Parameter
:
1313 case ObjCSubstitutionContext::Superclass
:
1314 // Substitute the bound.
1315 return typeParam
->getUnderlyingType();
1317 case ObjCSubstitutionContext::Result
:
1318 case ObjCSubstitutionContext::Property
: {
1319 // Substitute the __kindof form of the underlying type.
1320 const auto *objPtr
=
1321 typeParam
->getUnderlyingType()->castAs
<ObjCObjectPointerType
>();
1323 // __kindof types, id, and Class don't need an additional
1325 if (objPtr
->isKindOfType() || objPtr
->isObjCIdOrClassType())
1326 return typeParam
->getUnderlyingType();
1329 const auto *obj
= objPtr
->getObjectType();
1330 QualType resultTy
= Ctx
.getObjCObjectType(
1331 obj
->getBaseType(), obj
->getTypeArgsAsWritten(), obj
->getProtocols(),
1334 // Rebuild object pointer type.
1335 return Ctx
.getObjCObjectPointerType(resultTy
);
1338 llvm_unreachable("Unexpected ObjCSubstitutionContext!");
1341 QualType
VisitFunctionType(const FunctionType
*funcType
) {
1342 // If we have a function type, update the substitution context
1345 //Substitute result type.
1346 QualType returnType
= funcType
->getReturnType().substObjCTypeArgs(
1347 Ctx
, TypeArgs
, ObjCSubstitutionContext::Result
);
1348 if (returnType
.isNull())
1351 // Handle non-prototyped functions, which only substitute into the result
1353 if (isa
<FunctionNoProtoType
>(funcType
)) {
1354 // If the return type was unchanged, do nothing.
1355 if (returnType
.getAsOpaquePtr() ==
1356 funcType
->getReturnType().getAsOpaquePtr())
1357 return BaseType::VisitFunctionType(funcType
);
1359 // Otherwise, build a new type.
1360 return Ctx
.getFunctionNoProtoType(returnType
, funcType
->getExtInfo());
1363 const auto *funcProtoType
= cast
<FunctionProtoType
>(funcType
);
1365 // Transform parameter types.
1366 SmallVector
<QualType
, 4> paramTypes
;
1367 bool paramChanged
= false;
1368 for (auto paramType
: funcProtoType
->getParamTypes()) {
1369 QualType newParamType
= paramType
.substObjCTypeArgs(
1370 Ctx
, TypeArgs
, ObjCSubstitutionContext::Parameter
);
1371 if (newParamType
.isNull())
1374 if (newParamType
.getAsOpaquePtr() != paramType
.getAsOpaquePtr())
1375 paramChanged
= true;
1377 paramTypes
.push_back(newParamType
);
1380 // Transform extended info.
1381 FunctionProtoType::ExtProtoInfo info
= funcProtoType
->getExtProtoInfo();
1382 bool exceptionChanged
= false;
1383 if (info
.ExceptionSpec
.Type
== EST_Dynamic
) {
1384 SmallVector
<QualType
, 4> exceptionTypes
;
1385 for (auto exceptionType
: info
.ExceptionSpec
.Exceptions
) {
1386 QualType newExceptionType
= exceptionType
.substObjCTypeArgs(
1387 Ctx
, TypeArgs
, ObjCSubstitutionContext::Ordinary
);
1388 if (newExceptionType
.isNull())
1391 if (newExceptionType
.getAsOpaquePtr() != exceptionType
.getAsOpaquePtr())
1392 exceptionChanged
= true;
1394 exceptionTypes
.push_back(newExceptionType
);
1397 if (exceptionChanged
) {
1398 info
.ExceptionSpec
.Exceptions
=
1399 llvm::ArrayRef(exceptionTypes
).copy(Ctx
);
1403 if (returnType
.getAsOpaquePtr() ==
1404 funcProtoType
->getReturnType().getAsOpaquePtr() &&
1405 !paramChanged
&& !exceptionChanged
)
1406 return BaseType::VisitFunctionType(funcType
);
1408 return Ctx
.getFunctionType(returnType
, paramTypes
, info
);
1411 QualType
VisitObjCObjectType(const ObjCObjectType
*objcObjectType
) {
1412 // Substitute into the type arguments of a specialized Objective-C object
1414 if (objcObjectType
->isSpecializedAsWritten()) {
1415 SmallVector
<QualType
, 4> newTypeArgs
;
1416 bool anyChanged
= false;
1417 for (auto typeArg
: objcObjectType
->getTypeArgsAsWritten()) {
1418 QualType newTypeArg
= typeArg
.substObjCTypeArgs(
1419 Ctx
, TypeArgs
, ObjCSubstitutionContext::Ordinary
);
1420 if (newTypeArg
.isNull())
1423 if (newTypeArg
.getAsOpaquePtr() != typeArg
.getAsOpaquePtr()) {
1424 // If we're substituting based on an unspecialized context type,
1425 // produce an unspecialized type.
1426 ArrayRef
<ObjCProtocolDecl
*> protocols(
1427 objcObjectType
->qual_begin(), objcObjectType
->getNumProtocols());
1428 if (TypeArgs
.empty() &&
1429 SubstContext
!= ObjCSubstitutionContext::Superclass
) {
1430 return Ctx
.getObjCObjectType(
1431 objcObjectType
->getBaseType(), {}, protocols
,
1432 objcObjectType
->isKindOfTypeAsWritten());
1438 newTypeArgs
.push_back(newTypeArg
);
1442 ArrayRef
<ObjCProtocolDecl
*> protocols(
1443 objcObjectType
->qual_begin(), objcObjectType
->getNumProtocols());
1444 return Ctx
.getObjCObjectType(objcObjectType
->getBaseType(), newTypeArgs
,
1446 objcObjectType
->isKindOfTypeAsWritten());
1450 return BaseType::VisitObjCObjectType(objcObjectType
);
1453 QualType
VisitAttributedType(const AttributedType
*attrType
) {
1454 QualType newType
= BaseType::VisitAttributedType(attrType
);
1455 if (newType
.isNull())
1458 const auto *newAttrType
= dyn_cast
<AttributedType
>(newType
.getTypePtr());
1459 if (!newAttrType
|| newAttrType
->getAttrKind() != attr::ObjCKindOf
)
1462 // Find out if it's an Objective-C object or object pointer type;
1463 QualType newEquivType
= newAttrType
->getEquivalentType();
1464 const ObjCObjectPointerType
*ptrType
=
1465 newEquivType
->getAs
<ObjCObjectPointerType
>();
1466 const ObjCObjectType
*objType
= ptrType
1467 ? ptrType
->getObjectType()
1468 : newEquivType
->getAs
<ObjCObjectType
>();
1472 // Rebuild the "equivalent" type, which pushes __kindof down into
1474 newEquivType
= Ctx
.getObjCObjectType(
1475 objType
->getBaseType(), objType
->getTypeArgsAsWritten(),
1476 objType
->getProtocols(),
1477 // There is no need to apply kindof on an unqualified id type.
1478 /*isKindOf=*/objType
->isObjCUnqualifiedId() ? false : true);
1480 // If we started with an object pointer type, rebuild it.
1482 newEquivType
= Ctx
.getObjCObjectPointerType(newEquivType
);
1484 // Rebuild the attributed type.
1485 return Ctx
.getAttributedType(newAttrType
->getAttrKind(),
1486 newAttrType
->getModifiedType(), newEquivType
);
1490 struct StripObjCKindOfTypeVisitor
1491 : public SimpleTransformVisitor
<StripObjCKindOfTypeVisitor
> {
1492 using BaseType
= SimpleTransformVisitor
<StripObjCKindOfTypeVisitor
>;
1494 explicit StripObjCKindOfTypeVisitor(ASTContext
&ctx
) : BaseType(ctx
) {}
1496 QualType
VisitObjCObjectType(const ObjCObjectType
*objType
) {
1497 if (!objType
->isKindOfType())
1498 return BaseType::VisitObjCObjectType(objType
);
1500 QualType baseType
= objType
->getBaseType().stripObjCKindOfType(Ctx
);
1501 return Ctx
.getObjCObjectType(baseType
, objType
->getTypeArgsAsWritten(),
1502 objType
->getProtocols(),
1503 /*isKindOf=*/false);
1509 bool QualType::UseExcessPrecision(const ASTContext
&Ctx
) {
1510 const BuiltinType
*BT
= getTypePtr()->getAs
<BuiltinType
>();
1512 const VectorType
*VT
= getTypePtr()->getAs
<VectorType
>();
1514 QualType ElementType
= VT
->getElementType();
1515 return ElementType
.UseExcessPrecision(Ctx
);
1518 switch (BT
->getKind()) {
1519 case BuiltinType::Kind::Float16
: {
1520 const TargetInfo
&TI
= Ctx
.getTargetInfo();
1521 if (TI
.hasFloat16Type() && !TI
.hasLegalHalfType() &&
1522 Ctx
.getLangOpts().getFloat16ExcessPrecision() !=
1523 Ctx
.getLangOpts().ExcessPrecisionKind::FPP_None
)
1527 case BuiltinType::Kind::BFloat16
: {
1528 const TargetInfo
&TI
= Ctx
.getTargetInfo();
1529 if (TI
.hasBFloat16Type() && !TI
.hasFullBFloat16Type() &&
1530 Ctx
.getLangOpts().getBFloat16ExcessPrecision() !=
1531 Ctx
.getLangOpts().ExcessPrecisionKind::FPP_None
)
1542 /// Substitute the given type arguments for Objective-C type
1543 /// parameters within the given type, recursively.
1544 QualType
QualType::substObjCTypeArgs(ASTContext
&ctx
,
1545 ArrayRef
<QualType
> typeArgs
,
1546 ObjCSubstitutionContext context
) const {
1547 SubstObjCTypeArgsVisitor
visitor(ctx
, typeArgs
, context
);
1548 return visitor
.recurse(*this);
1551 QualType
QualType::substObjCMemberType(QualType objectType
,
1552 const DeclContext
*dc
,
1553 ObjCSubstitutionContext context
) const {
1554 if (auto subs
= objectType
->getObjCSubstitutions(dc
))
1555 return substObjCTypeArgs(dc
->getParentASTContext(), *subs
, context
);
1560 QualType
QualType::stripObjCKindOfType(const ASTContext
&constCtx
) const {
1561 // FIXME: Because ASTContext::getAttributedType() is non-const.
1562 auto &ctx
= const_cast<ASTContext
&>(constCtx
);
1563 StripObjCKindOfTypeVisitor
visitor(ctx
);
1564 return visitor
.recurse(*this);
1567 QualType
QualType::getAtomicUnqualifiedType() const {
1568 if (const auto AT
= getTypePtr()->getAs
<AtomicType
>())
1569 return AT
->getValueType().getUnqualifiedType();
1570 return getUnqualifiedType();
1573 std::optional
<ArrayRef
<QualType
>>
1574 Type::getObjCSubstitutions(const DeclContext
*dc
) const {
1575 // Look through method scopes.
1576 if (const auto method
= dyn_cast
<ObjCMethodDecl
>(dc
))
1577 dc
= method
->getDeclContext();
1579 // Find the class or category in which the type we're substituting
1581 const auto *dcClassDecl
= dyn_cast
<ObjCInterfaceDecl
>(dc
);
1582 const ObjCCategoryDecl
*dcCategoryDecl
= nullptr;
1583 ObjCTypeParamList
*dcTypeParams
= nullptr;
1585 // If the class does not have any type parameters, there's no
1586 // substitution to do.
1587 dcTypeParams
= dcClassDecl
->getTypeParamList();
1589 return std::nullopt
;
1591 // If we are in neither a class nor a category, there's no
1592 // substitution to perform.
1593 dcCategoryDecl
= dyn_cast
<ObjCCategoryDecl
>(dc
);
1594 if (!dcCategoryDecl
)
1595 return std::nullopt
;
1597 // If the category does not have any type parameters, there's no
1598 // substitution to do.
1599 dcTypeParams
= dcCategoryDecl
->getTypeParamList();
1601 return std::nullopt
;
1603 dcClassDecl
= dcCategoryDecl
->getClassInterface();
1605 return std::nullopt
;
1607 assert(dcTypeParams
&& "No substitutions to perform");
1608 assert(dcClassDecl
&& "No class context");
1610 // Find the underlying object type.
1611 const ObjCObjectType
*objectType
;
1612 if (const auto *objectPointerType
= getAs
<ObjCObjectPointerType
>()) {
1613 objectType
= objectPointerType
->getObjectType();
1614 } else if (getAs
<BlockPointerType
>()) {
1615 ASTContext
&ctx
= dc
->getParentASTContext();
1616 objectType
= ctx
.getObjCObjectType(ctx
.ObjCBuiltinIdTy
, {}, {})
1617 ->castAs
<ObjCObjectType
>();
1619 objectType
= getAs
<ObjCObjectType
>();
1622 /// Extract the class from the receiver object type.
1623 ObjCInterfaceDecl
*curClassDecl
= objectType
? objectType
->getInterface()
1625 if (!curClassDecl
) {
1626 // If we don't have a context type (e.g., this is "id" or some
1627 // variant thereof), substitute the bounds.
1628 return llvm::ArrayRef
<QualType
>();
1631 // Follow the superclass chain until we've mapped the receiver type
1632 // to the same class as the context.
1633 while (curClassDecl
!= dcClassDecl
) {
1634 // Map to the superclass type.
1635 QualType superType
= objectType
->getSuperClassType();
1636 if (superType
.isNull()) {
1637 objectType
= nullptr;
1641 objectType
= superType
->castAs
<ObjCObjectType
>();
1642 curClassDecl
= objectType
->getInterface();
1645 // If we don't have a receiver type, or the receiver type does not
1646 // have type arguments, substitute in the defaults.
1647 if (!objectType
|| objectType
->isUnspecialized()) {
1648 return llvm::ArrayRef
<QualType
>();
1651 // The receiver type has the type arguments we want.
1652 return objectType
->getTypeArgs();
1655 bool Type::acceptsObjCTypeParams() const {
1656 if (auto *IfaceT
= getAsObjCInterfaceType()) {
1657 if (auto *ID
= IfaceT
->getInterface()) {
1658 if (ID
->getTypeParamList())
1666 void ObjCObjectType::computeSuperClassTypeSlow() const {
1667 // Retrieve the class declaration for this type. If there isn't one
1668 // (e.g., this is some variant of "id" or "Class"), then there is no
1670 ObjCInterfaceDecl
*classDecl
= getInterface();
1672 CachedSuperClassType
.setInt(true);
1676 // Extract the superclass type.
1677 const ObjCObjectType
*superClassObjTy
= classDecl
->getSuperClassType();
1678 if (!superClassObjTy
) {
1679 CachedSuperClassType
.setInt(true);
1683 ObjCInterfaceDecl
*superClassDecl
= superClassObjTy
->getInterface();
1684 if (!superClassDecl
) {
1685 CachedSuperClassType
.setInt(true);
1689 // If the superclass doesn't have type parameters, then there is no
1690 // substitution to perform.
1691 QualType
superClassType(superClassObjTy
, 0);
1692 ObjCTypeParamList
*superClassTypeParams
= superClassDecl
->getTypeParamList();
1693 if (!superClassTypeParams
) {
1694 CachedSuperClassType
.setPointerAndInt(
1695 superClassType
->castAs
<ObjCObjectType
>(), true);
1699 // If the superclass reference is unspecialized, return it.
1700 if (superClassObjTy
->isUnspecialized()) {
1701 CachedSuperClassType
.setPointerAndInt(superClassObjTy
, true);
1705 // If the subclass is not parameterized, there aren't any type
1706 // parameters in the superclass reference to substitute.
1707 ObjCTypeParamList
*typeParams
= classDecl
->getTypeParamList();
1709 CachedSuperClassType
.setPointerAndInt(
1710 superClassType
->castAs
<ObjCObjectType
>(), true);
1714 // If the subclass type isn't specialized, return the unspecialized
1716 if (isUnspecialized()) {
1717 QualType unspecializedSuper
1718 = classDecl
->getASTContext().getObjCInterfaceType(
1719 superClassObjTy
->getInterface());
1720 CachedSuperClassType
.setPointerAndInt(
1721 unspecializedSuper
->castAs
<ObjCObjectType
>(),
1726 // Substitute the provided type arguments into the superclass type.
1727 ArrayRef
<QualType
> typeArgs
= getTypeArgs();
1728 assert(typeArgs
.size() == typeParams
->size());
1729 CachedSuperClassType
.setPointerAndInt(
1730 superClassType
.substObjCTypeArgs(classDecl
->getASTContext(), typeArgs
,
1731 ObjCSubstitutionContext::Superclass
)
1732 ->castAs
<ObjCObjectType
>(),
1736 const ObjCInterfaceType
*ObjCObjectPointerType::getInterfaceType() const {
1737 if (auto interfaceDecl
= getObjectType()->getInterface()) {
1738 return interfaceDecl
->getASTContext().getObjCInterfaceType(interfaceDecl
)
1739 ->castAs
<ObjCInterfaceType
>();
1745 QualType
ObjCObjectPointerType::getSuperClassType() const {
1746 QualType superObjectType
= getObjectType()->getSuperClassType();
1747 if (superObjectType
.isNull())
1748 return superObjectType
;
1750 ASTContext
&ctx
= getInterfaceDecl()->getASTContext();
1751 return ctx
.getObjCObjectPointerType(superObjectType
);
1754 const ObjCObjectType
*Type::getAsObjCQualifiedInterfaceType() const {
1755 // There is no sugar for ObjCObjectType's, just return the canonical
1756 // type pointer if it is the right class. There is no typedef information to
1757 // return and these cannot be Address-space qualified.
1758 if (const auto *T
= getAs
<ObjCObjectType
>())
1759 if (T
->getNumProtocols() && T
->getInterface())
1764 bool Type::isObjCQualifiedInterfaceType() const {
1765 return getAsObjCQualifiedInterfaceType() != nullptr;
1768 const ObjCObjectPointerType
*Type::getAsObjCQualifiedIdType() const {
1769 // There is no sugar for ObjCQualifiedIdType's, just return the canonical
1770 // type pointer if it is the right class.
1771 if (const auto *OPT
= getAs
<ObjCObjectPointerType
>()) {
1772 if (OPT
->isObjCQualifiedIdType())
1778 const ObjCObjectPointerType
*Type::getAsObjCQualifiedClassType() const {
1779 // There is no sugar for ObjCQualifiedClassType's, just return the canonical
1780 // type pointer if it is the right class.
1781 if (const auto *OPT
= getAs
<ObjCObjectPointerType
>()) {
1782 if (OPT
->isObjCQualifiedClassType())
1788 const ObjCObjectType
*Type::getAsObjCInterfaceType() const {
1789 if (const auto *OT
= getAs
<ObjCObjectType
>()) {
1790 if (OT
->getInterface())
1796 const ObjCObjectPointerType
*Type::getAsObjCInterfacePointerType() const {
1797 if (const auto *OPT
= getAs
<ObjCObjectPointerType
>()) {
1798 if (OPT
->getInterfaceType())
1804 const CXXRecordDecl
*Type::getPointeeCXXRecordDecl() const {
1805 QualType PointeeType
;
1806 if (const auto *PT
= getAs
<PointerType
>())
1807 PointeeType
= PT
->getPointeeType();
1808 else if (const auto *RT
= getAs
<ReferenceType
>())
1809 PointeeType
= RT
->getPointeeType();
1813 if (const auto *RT
= PointeeType
->getAs
<RecordType
>())
1814 return dyn_cast
<CXXRecordDecl
>(RT
->getDecl());
1819 CXXRecordDecl
*Type::getAsCXXRecordDecl() const {
1820 return dyn_cast_or_null
<CXXRecordDecl
>(getAsTagDecl());
1823 RecordDecl
*Type::getAsRecordDecl() const {
1824 return dyn_cast_or_null
<RecordDecl
>(getAsTagDecl());
1827 TagDecl
*Type::getAsTagDecl() const {
1828 if (const auto *TT
= getAs
<TagType
>())
1829 return TT
->getDecl();
1830 if (const auto *Injected
= getAs
<InjectedClassNameType
>())
1831 return Injected
->getDecl();
1836 bool Type::hasAttr(attr::Kind AK
) const {
1837 const Type
*Cur
= this;
1838 while (const auto *AT
= Cur
->getAs
<AttributedType
>()) {
1839 if (AT
->getAttrKind() == AK
)
1841 Cur
= AT
->getEquivalentType().getTypePtr();
1848 class GetContainedDeducedTypeVisitor
:
1849 public TypeVisitor
<GetContainedDeducedTypeVisitor
, Type
*> {
1853 GetContainedDeducedTypeVisitor(bool Syntactic
= false)
1854 : Syntactic(Syntactic
) {}
1856 using TypeVisitor
<GetContainedDeducedTypeVisitor
, Type
*>::Visit
;
1858 Type
*Visit(QualType T
) {
1861 return Visit(T
.getTypePtr());
1864 // The deduced type itself.
1865 Type
*VisitDeducedType(const DeducedType
*AT
) {
1866 return const_cast<DeducedType
*>(AT
);
1869 // Only these types can contain the desired 'auto' type.
1870 Type
*VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType
*T
) {
1871 return Visit(T
->getReplacementType());
1874 Type
*VisitElaboratedType(const ElaboratedType
*T
) {
1875 return Visit(T
->getNamedType());
1878 Type
*VisitPointerType(const PointerType
*T
) {
1879 return Visit(T
->getPointeeType());
1882 Type
*VisitBlockPointerType(const BlockPointerType
*T
) {
1883 return Visit(T
->getPointeeType());
1886 Type
*VisitReferenceType(const ReferenceType
*T
) {
1887 return Visit(T
->getPointeeTypeAsWritten());
1890 Type
*VisitMemberPointerType(const MemberPointerType
*T
) {
1891 return Visit(T
->getPointeeType());
1894 Type
*VisitArrayType(const ArrayType
*T
) {
1895 return Visit(T
->getElementType());
1898 Type
*VisitDependentSizedExtVectorType(
1899 const DependentSizedExtVectorType
*T
) {
1900 return Visit(T
->getElementType());
1903 Type
*VisitVectorType(const VectorType
*T
) {
1904 return Visit(T
->getElementType());
1907 Type
*VisitDependentSizedMatrixType(const DependentSizedMatrixType
*T
) {
1908 return Visit(T
->getElementType());
1911 Type
*VisitConstantMatrixType(const ConstantMatrixType
*T
) {
1912 return Visit(T
->getElementType());
1915 Type
*VisitFunctionProtoType(const FunctionProtoType
*T
) {
1916 if (Syntactic
&& T
->hasTrailingReturn())
1917 return const_cast<FunctionProtoType
*>(T
);
1918 return VisitFunctionType(T
);
1921 Type
*VisitFunctionType(const FunctionType
*T
) {
1922 return Visit(T
->getReturnType());
1925 Type
*VisitParenType(const ParenType
*T
) {
1926 return Visit(T
->getInnerType());
1929 Type
*VisitAttributedType(const AttributedType
*T
) {
1930 return Visit(T
->getModifiedType());
1933 Type
*VisitMacroQualifiedType(const MacroQualifiedType
*T
) {
1934 return Visit(T
->getUnderlyingType());
1937 Type
*VisitAdjustedType(const AdjustedType
*T
) {
1938 return Visit(T
->getOriginalType());
1941 Type
*VisitPackExpansionType(const PackExpansionType
*T
) {
1942 return Visit(T
->getPattern());
1948 DeducedType
*Type::getContainedDeducedType() const {
1949 return cast_or_null
<DeducedType
>(
1950 GetContainedDeducedTypeVisitor().Visit(this));
1953 bool Type::hasAutoForTrailingReturnType() const {
1954 return isa_and_nonnull
<FunctionType
>(
1955 GetContainedDeducedTypeVisitor(true).Visit(this));
1958 bool Type::hasIntegerRepresentation() const {
1959 if (const auto *VT
= dyn_cast
<VectorType
>(CanonicalType
))
1960 return VT
->getElementType()->isIntegerType();
1961 if (CanonicalType
->isSveVLSBuiltinType()) {
1962 const auto *VT
= cast
<BuiltinType
>(CanonicalType
);
1963 return VT
->getKind() == BuiltinType::SveBool
||
1964 (VT
->getKind() >= BuiltinType::SveInt8
&&
1965 VT
->getKind() <= BuiltinType::SveUint64
);
1967 if (CanonicalType
->isRVVVLSBuiltinType()) {
1968 const auto *VT
= cast
<BuiltinType
>(CanonicalType
);
1969 return (VT
->getKind() >= BuiltinType::RvvInt8mf8
&&
1970 VT
->getKind() <= BuiltinType::RvvUint64m8
);
1973 return isIntegerType();
1976 /// Determine whether this type is an integral type.
1978 /// This routine determines whether the given type is an integral type per
1979 /// C++ [basic.fundamental]p7. Although the C standard does not define the
1980 /// term "integral type", it has a similar term "integer type", and in C++
1981 /// the two terms are equivalent. However, C's "integer type" includes
1982 /// enumeration types, while C++'s "integer type" does not. The \c ASTContext
1983 /// parameter is used to determine whether we should be following the C or
1984 /// C++ rules when determining whether this type is an integral/integer type.
1986 /// For cases where C permits "an integer type" and C++ permits "an integral
1987 /// type", use this routine.
1989 /// For cases where C permits "an integer type" and C++ permits "an integral
1990 /// or enumeration type", use \c isIntegralOrEnumerationType() instead.
1992 /// \param Ctx The context in which this type occurs.
1994 /// \returns true if the type is considered an integral type, false otherwise.
1995 bool Type::isIntegralType(const ASTContext
&Ctx
) const {
1996 if (const auto *BT
= dyn_cast
<BuiltinType
>(CanonicalType
))
1997 return BT
->getKind() >= BuiltinType::Bool
&&
1998 BT
->getKind() <= BuiltinType::Int128
;
2000 // Complete enum types are integral in C.
2001 if (!Ctx
.getLangOpts().CPlusPlus
)
2002 if (const auto *ET
= dyn_cast
<EnumType
>(CanonicalType
))
2003 return ET
->getDecl()->isComplete();
2005 return isBitIntType();
2008 bool Type::isIntegralOrUnscopedEnumerationType() const {
2009 if (const auto *BT
= dyn_cast
<BuiltinType
>(CanonicalType
))
2010 return BT
->getKind() >= BuiltinType::Bool
&&
2011 BT
->getKind() <= BuiltinType::Int128
;
2016 return isUnscopedEnumerationType();
2019 bool Type::isUnscopedEnumerationType() const {
2020 if (const auto *ET
= dyn_cast
<EnumType
>(CanonicalType
))
2021 return !ET
->getDecl()->isScoped();
2026 bool Type::isCharType() const {
2027 if (const auto *BT
= dyn_cast
<BuiltinType
>(CanonicalType
))
2028 return BT
->getKind() == BuiltinType::Char_U
||
2029 BT
->getKind() == BuiltinType::UChar
||
2030 BT
->getKind() == BuiltinType::Char_S
||
2031 BT
->getKind() == BuiltinType::SChar
;
2035 bool Type::isWideCharType() const {
2036 if (const auto *BT
= dyn_cast
<BuiltinType
>(CanonicalType
))
2037 return BT
->getKind() == BuiltinType::WChar_S
||
2038 BT
->getKind() == BuiltinType::WChar_U
;
2042 bool Type::isChar8Type() const {
2043 if (const BuiltinType
*BT
= dyn_cast
<BuiltinType
>(CanonicalType
))
2044 return BT
->getKind() == BuiltinType::Char8
;
2048 bool Type::isChar16Type() const {
2049 if (const auto *BT
= dyn_cast
<BuiltinType
>(CanonicalType
))
2050 return BT
->getKind() == BuiltinType::Char16
;
2054 bool Type::isChar32Type() const {
2055 if (const auto *BT
= dyn_cast
<BuiltinType
>(CanonicalType
))
2056 return BT
->getKind() == BuiltinType::Char32
;
2060 /// Determine whether this type is any of the built-in character
2062 bool Type::isAnyCharacterType() const {
2063 const auto *BT
= dyn_cast
<BuiltinType
>(CanonicalType
);
2064 if (!BT
) return false;
2065 switch (BT
->getKind()) {
2066 default: return false;
2067 case BuiltinType::Char_U
:
2068 case BuiltinType::UChar
:
2069 case BuiltinType::WChar_U
:
2070 case BuiltinType::Char8
:
2071 case BuiltinType::Char16
:
2072 case BuiltinType::Char32
:
2073 case BuiltinType::Char_S
:
2074 case BuiltinType::SChar
:
2075 case BuiltinType::WChar_S
:
2080 /// isSignedIntegerType - Return true if this is an integer type that is
2081 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2082 /// an enum decl which has a signed representation
2083 bool Type::isSignedIntegerType() const {
2084 if (const auto *BT
= dyn_cast
<BuiltinType
>(CanonicalType
)) {
2085 return BT
->getKind() >= BuiltinType::Char_S
&&
2086 BT
->getKind() <= BuiltinType::Int128
;
2089 if (const EnumType
*ET
= dyn_cast
<EnumType
>(CanonicalType
)) {
2090 // Incomplete enum types are not treated as integer types.
2091 // FIXME: In C++, enum types are never integer types.
2092 if (ET
->getDecl()->isComplete() && !ET
->getDecl()->isScoped())
2093 return ET
->getDecl()->getIntegerType()->isSignedIntegerType();
2096 if (const auto *IT
= dyn_cast
<BitIntType
>(CanonicalType
))
2097 return IT
->isSigned();
2098 if (const auto *IT
= dyn_cast
<DependentBitIntType
>(CanonicalType
))
2099 return IT
->isSigned();
2104 bool Type::isSignedIntegerOrEnumerationType() const {
2105 if (const auto *BT
= dyn_cast
<BuiltinType
>(CanonicalType
)) {
2106 return BT
->getKind() >= BuiltinType::Char_S
&&
2107 BT
->getKind() <= BuiltinType::Int128
;
2110 if (const auto *ET
= dyn_cast
<EnumType
>(CanonicalType
)) {
2111 if (ET
->getDecl()->isComplete())
2112 return ET
->getDecl()->getIntegerType()->isSignedIntegerType();
2115 if (const auto *IT
= dyn_cast
<BitIntType
>(CanonicalType
))
2116 return IT
->isSigned();
2117 if (const auto *IT
= dyn_cast
<DependentBitIntType
>(CanonicalType
))
2118 return IT
->isSigned();
2123 bool Type::hasSignedIntegerRepresentation() const {
2124 if (const auto *VT
= dyn_cast
<VectorType
>(CanonicalType
))
2125 return VT
->getElementType()->isSignedIntegerOrEnumerationType();
2127 return isSignedIntegerOrEnumerationType();
2130 /// isUnsignedIntegerType - Return true if this is an integer type that is
2131 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
2132 /// decl which has an unsigned representation
2133 bool Type::isUnsignedIntegerType() const {
2134 if (const auto *BT
= dyn_cast
<BuiltinType
>(CanonicalType
)) {
2135 return BT
->getKind() >= BuiltinType::Bool
&&
2136 BT
->getKind() <= BuiltinType::UInt128
;
2139 if (const auto *ET
= dyn_cast
<EnumType
>(CanonicalType
)) {
2140 // Incomplete enum types are not treated as integer types.
2141 // FIXME: In C++, enum types are never integer types.
2142 if (ET
->getDecl()->isComplete() && !ET
->getDecl()->isScoped())
2143 return ET
->getDecl()->getIntegerType()->isUnsignedIntegerType();
2146 if (const auto *IT
= dyn_cast
<BitIntType
>(CanonicalType
))
2147 return IT
->isUnsigned();
2148 if (const auto *IT
= dyn_cast
<DependentBitIntType
>(CanonicalType
))
2149 return IT
->isUnsigned();
2154 bool Type::isUnsignedIntegerOrEnumerationType() const {
2155 if (const auto *BT
= dyn_cast
<BuiltinType
>(CanonicalType
)) {
2156 return BT
->getKind() >= BuiltinType::Bool
&&
2157 BT
->getKind() <= BuiltinType::UInt128
;
2160 if (const auto *ET
= dyn_cast
<EnumType
>(CanonicalType
)) {
2161 if (ET
->getDecl()->isComplete())
2162 return ET
->getDecl()->getIntegerType()->isUnsignedIntegerType();
2165 if (const auto *IT
= dyn_cast
<BitIntType
>(CanonicalType
))
2166 return IT
->isUnsigned();
2167 if (const auto *IT
= dyn_cast
<DependentBitIntType
>(CanonicalType
))
2168 return IT
->isUnsigned();
2173 bool Type::hasUnsignedIntegerRepresentation() const {
2174 if (const auto *VT
= dyn_cast
<VectorType
>(CanonicalType
))
2175 return VT
->getElementType()->isUnsignedIntegerOrEnumerationType();
2176 if (const auto *VT
= dyn_cast
<MatrixType
>(CanonicalType
))
2177 return VT
->getElementType()->isUnsignedIntegerOrEnumerationType();
2178 if (CanonicalType
->isSveVLSBuiltinType()) {
2179 const auto *VT
= cast
<BuiltinType
>(CanonicalType
);
2180 return VT
->getKind() >= BuiltinType::SveUint8
&&
2181 VT
->getKind() <= BuiltinType::SveUint64
;
2183 return isUnsignedIntegerOrEnumerationType();
2186 bool Type::isFloatingType() const {
2187 if (const auto *BT
= dyn_cast
<BuiltinType
>(CanonicalType
))
2188 return BT
->getKind() >= BuiltinType::Half
&&
2189 BT
->getKind() <= BuiltinType::Ibm128
;
2190 if (const auto *CT
= dyn_cast
<ComplexType
>(CanonicalType
))
2191 return CT
->getElementType()->isFloatingType();
2195 bool Type::hasFloatingRepresentation() const {
2196 if (const auto *VT
= dyn_cast
<VectorType
>(CanonicalType
))
2197 return VT
->getElementType()->isFloatingType();
2198 if (const auto *MT
= dyn_cast
<MatrixType
>(CanonicalType
))
2199 return MT
->getElementType()->isFloatingType();
2200 return isFloatingType();
2203 bool Type::isRealFloatingType() const {
2204 if (const auto *BT
= dyn_cast
<BuiltinType
>(CanonicalType
))
2205 return BT
->isFloatingPoint();
2209 bool Type::isRealType() const {
2210 if (const auto *BT
= dyn_cast
<BuiltinType
>(CanonicalType
))
2211 return BT
->getKind() >= BuiltinType::Bool
&&
2212 BT
->getKind() <= BuiltinType::Ibm128
;
2213 if (const auto *ET
= dyn_cast
<EnumType
>(CanonicalType
))
2214 return ET
->getDecl()->isComplete() && !ET
->getDecl()->isScoped();
2215 return isBitIntType();
2218 bool Type::isArithmeticType() const {
2219 if (const auto *BT
= dyn_cast
<BuiltinType
>(CanonicalType
))
2220 return BT
->getKind() >= BuiltinType::Bool
&&
2221 BT
->getKind() <= BuiltinType::Ibm128
;
2222 if (const auto *ET
= dyn_cast
<EnumType
>(CanonicalType
))
2223 // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
2224 // If a body isn't seen by the time we get here, return false.
2226 // C++0x: Enumerations are not arithmetic types. For now, just return
2227 // false for scoped enumerations since that will disable any
2228 // unwanted implicit conversions.
2229 return !ET
->getDecl()->isScoped() && ET
->getDecl()->isComplete();
2230 return isa
<ComplexType
>(CanonicalType
) || isBitIntType();
2233 Type::ScalarTypeKind
Type::getScalarTypeKind() const {
2234 assert(isScalarType());
2236 const Type
*T
= CanonicalType
.getTypePtr();
2237 if (const auto *BT
= dyn_cast
<BuiltinType
>(T
)) {
2238 if (BT
->getKind() == BuiltinType::Bool
) return STK_Bool
;
2239 if (BT
->getKind() == BuiltinType::NullPtr
) return STK_CPointer
;
2240 if (BT
->isInteger()) return STK_Integral
;
2241 if (BT
->isFloatingPoint()) return STK_Floating
;
2242 if (BT
->isFixedPointType()) return STK_FixedPoint
;
2243 llvm_unreachable("unknown scalar builtin type");
2244 } else if (isa
<PointerType
>(T
)) {
2245 return STK_CPointer
;
2246 } else if (isa
<BlockPointerType
>(T
)) {
2247 return STK_BlockPointer
;
2248 } else if (isa
<ObjCObjectPointerType
>(T
)) {
2249 return STK_ObjCObjectPointer
;
2250 } else if (isa
<MemberPointerType
>(T
)) {
2251 return STK_MemberPointer
;
2252 } else if (isa
<EnumType
>(T
)) {
2253 assert(cast
<EnumType
>(T
)->getDecl()->isComplete());
2254 return STK_Integral
;
2255 } else if (const auto *CT
= dyn_cast
<ComplexType
>(T
)) {
2256 if (CT
->getElementType()->isRealFloatingType())
2257 return STK_FloatingComplex
;
2258 return STK_IntegralComplex
;
2259 } else if (isBitIntType()) {
2260 return STK_Integral
;
2263 llvm_unreachable("unknown scalar type");
2266 /// Determines whether the type is a C++ aggregate type or C
2267 /// aggregate or union type.
2269 /// An aggregate type is an array or a class type (struct, union, or
2270 /// class) that has no user-declared constructors, no private or
2271 /// protected non-static data members, no base classes, and no virtual
2272 /// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
2273 /// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
2274 /// includes union types.
2275 bool Type::isAggregateType() const {
2276 if (const auto *Record
= dyn_cast
<RecordType
>(CanonicalType
)) {
2277 if (const auto *ClassDecl
= dyn_cast
<CXXRecordDecl
>(Record
->getDecl()))
2278 return ClassDecl
->isAggregate();
2283 return isa
<ArrayType
>(CanonicalType
);
2286 /// isConstantSizeType - Return true if this is not a variable sized type,
2287 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2288 /// incomplete types or dependent types.
2289 bool Type::isConstantSizeType() const {
2290 assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
2291 assert(!isDependentType() && "This doesn't make sense for dependent types");
2292 // The VAT must have a size, as it is known to be complete.
2293 return !isa
<VariableArrayType
>(CanonicalType
);
2296 /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
2297 /// - a type that can describe objects, but which lacks information needed to
2298 /// determine its size.
2299 bool Type::isIncompleteType(NamedDecl
**Def
) const {
2303 switch (CanonicalType
->getTypeClass()) {
2304 default: return false;
2306 // Void is the only incomplete builtin type. Per C99 6.2.5p19, it can never
2308 return isVoidType();
2310 EnumDecl
*EnumD
= cast
<EnumType
>(CanonicalType
)->getDecl();
2313 return !EnumD
->isComplete();
2316 // A tagged type (struct/union/enum/class) is incomplete if the decl is a
2317 // forward declaration, but not a full definition (C99 6.2.5p22).
2318 RecordDecl
*Rec
= cast
<RecordType
>(CanonicalType
)->getDecl();
2321 return !Rec
->isCompleteDefinition();
2325 // An array is incomplete if its element type is incomplete
2326 // (C++ [dcl.array]p1).
2327 // We don't handle dependent-sized arrays (dependent types are never treated
2329 return cast
<ArrayType
>(CanonicalType
)->getElementType()
2330 ->isIncompleteType(Def
);
2331 case IncompleteArray
:
2332 // An array of unknown size is an incomplete type (C99 6.2.5p22).
2334 case MemberPointer
: {
2335 // Member pointers in the MS ABI have special behavior in
2336 // RequireCompleteType: they attach a MSInheritanceAttr to the CXXRecordDecl
2337 // to indicate which inheritance model to use.
2338 auto *MPTy
= cast
<MemberPointerType
>(CanonicalType
);
2339 const Type
*ClassTy
= MPTy
->getClass();
2340 // Member pointers with dependent class types don't get special treatment.
2341 if (ClassTy
->isDependentType())
2343 const CXXRecordDecl
*RD
= ClassTy
->getAsCXXRecordDecl();
2344 ASTContext
&Context
= RD
->getASTContext();
2345 // Member pointers not in the MS ABI don't get special treatment.
2346 if (!Context
.getTargetInfo().getCXXABI().isMicrosoft())
2348 // The inheritance attribute might only be present on the most recent
2349 // CXXRecordDecl, use that one.
2350 RD
= RD
->getMostRecentNonInjectedDecl();
2351 // Nothing interesting to do if the inheritance attribute is already set.
2352 if (RD
->hasAttr
<MSInheritanceAttr
>())
2357 return cast
<ObjCObjectType
>(CanonicalType
)->getBaseType()
2358 ->isIncompleteType(Def
);
2359 case ObjCInterface
: {
2360 // ObjC interfaces are incomplete if they are @class, not @interface.
2361 ObjCInterfaceDecl
*Interface
2362 = cast
<ObjCInterfaceType
>(CanonicalType
)->getDecl();
2365 return !Interface
->hasDefinition();
2370 bool Type::isSizelessBuiltinType() const {
2371 if (isSizelessVectorType())
2374 if (const BuiltinType
*BT
= getAs
<BuiltinType
>()) {
2375 switch (BT
->getKind()) {
2376 // WebAssembly reference types
2377 #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2378 #include "clang/Basic/WebAssemblyReferenceTypes.def"
2387 bool Type::isWebAssemblyExternrefType() const {
2388 if (const auto *BT
= getAs
<BuiltinType
>())
2389 return BT
->getKind() == BuiltinType::WasmExternRef
;
2393 bool Type::isWebAssemblyTableType() const {
2394 if (const auto *ATy
= dyn_cast
<ArrayType
>(this))
2395 return ATy
->getElementType().isWebAssemblyReferenceType();
2397 if (const auto *PTy
= dyn_cast
<PointerType
>(this))
2398 return PTy
->getPointeeType().isWebAssemblyReferenceType();
2403 bool Type::isSizelessType() const { return isSizelessBuiltinType(); }
2405 bool Type::isSizelessVectorType() const {
2406 return isSVESizelessBuiltinType() || isRVVSizelessBuiltinType();
2409 bool Type::isSVESizelessBuiltinType() const {
2410 if (const BuiltinType
*BT
= getAs
<BuiltinType
>()) {
2411 switch (BT
->getKind()) {
2413 #define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2414 #include "clang/Basic/AArch64SVEACLETypes.def"
2423 bool Type::isRVVSizelessBuiltinType() const {
2424 if (const BuiltinType
*BT
= getAs
<BuiltinType
>()) {
2425 switch (BT
->getKind()) {
2426 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2427 #include "clang/Basic/RISCVVTypes.def"
2436 bool Type::isSveVLSBuiltinType() const {
2437 if (const BuiltinType
*BT
= getAs
<BuiltinType
>()) {
2438 switch (BT
->getKind()) {
2439 case BuiltinType::SveInt8
:
2440 case BuiltinType::SveInt16
:
2441 case BuiltinType::SveInt32
:
2442 case BuiltinType::SveInt64
:
2443 case BuiltinType::SveUint8
:
2444 case BuiltinType::SveUint16
:
2445 case BuiltinType::SveUint32
:
2446 case BuiltinType::SveUint64
:
2447 case BuiltinType::SveFloat16
:
2448 case BuiltinType::SveFloat32
:
2449 case BuiltinType::SveFloat64
:
2450 case BuiltinType::SveBFloat16
:
2451 case BuiltinType::SveBool
:
2452 case BuiltinType::SveBoolx2
:
2453 case BuiltinType::SveBoolx4
:
2462 QualType
Type::getSveEltType(const ASTContext
&Ctx
) const {
2463 assert(isSveVLSBuiltinType() && "unsupported type!");
2465 const BuiltinType
*BTy
= castAs
<BuiltinType
>();
2466 if (BTy
->getKind() == BuiltinType::SveBool
)
2467 // Represent predicates as i8 rather than i1 to avoid any layout issues.
2468 // The type is bitcasted to a scalable predicate type when casting between
2469 // scalable and fixed-length vectors.
2470 return Ctx
.UnsignedCharTy
;
2472 return Ctx
.getBuiltinVectorTypeInfo(BTy
).ElementType
;
2475 bool Type::isRVVVLSBuiltinType() const {
2476 if (const BuiltinType
*BT
= getAs
<BuiltinType
>()) {
2477 switch (BT
->getKind()) {
2478 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, IsFP) \
2479 case BuiltinType::Id: \
2481 #include "clang/Basic/RISCVVTypes.def"
2489 QualType
Type::getRVVEltType(const ASTContext
&Ctx
) const {
2490 assert(isRVVVLSBuiltinType() && "unsupported type!");
2492 const BuiltinType
*BTy
= castAs
<BuiltinType
>();
2493 return Ctx
.getBuiltinVectorTypeInfo(BTy
).ElementType
;
2496 bool QualType::isPODType(const ASTContext
&Context
) const {
2497 // C++11 has a more relaxed definition of POD.
2498 if (Context
.getLangOpts().CPlusPlus11
)
2499 return isCXX11PODType(Context
);
2501 return isCXX98PODType(Context
);
2504 bool QualType::isCXX98PODType(const ASTContext
&Context
) const {
2505 // The compiler shouldn't query this for incomplete types, but the user might.
2506 // We return false for that case. Except for incomplete arrays of PODs, which
2507 // are PODs according to the standard.
2511 if ((*this)->isIncompleteArrayType())
2512 return Context
.getBaseElementType(*this).isCXX98PODType(Context
);
2514 if ((*this)->isIncompleteType())
2517 if (hasNonTrivialObjCLifetime())
2520 QualType CanonicalType
= getTypePtr()->CanonicalType
;
2521 switch (CanonicalType
->getTypeClass()) {
2522 // Everything not explicitly mentioned is not POD.
2523 default: return false;
2524 case Type::VariableArray
:
2525 case Type::ConstantArray
:
2526 // IncompleteArray is handled above.
2527 return Context
.getBaseElementType(*this).isCXX98PODType(Context
);
2529 case Type::ObjCObjectPointer
:
2530 case Type::BlockPointer
:
2534 case Type::MemberPointer
:
2536 case Type::ExtVector
:
2544 if (const auto *ClassDecl
=
2545 dyn_cast
<CXXRecordDecl
>(cast
<RecordType
>(CanonicalType
)->getDecl()))
2546 return ClassDecl
->isPOD();
2548 // C struct/union is POD.
2553 bool QualType::isTrivialType(const ASTContext
&Context
) const {
2554 // The compiler shouldn't query this for incomplete types, but the user might.
2555 // We return false for that case. Except for incomplete arrays of PODs, which
2556 // are PODs according to the standard.
2560 if ((*this)->isArrayType())
2561 return Context
.getBaseElementType(*this).isTrivialType(Context
);
2563 if ((*this)->isSizelessBuiltinType())
2566 // Return false for incomplete types after skipping any incomplete array
2567 // types which are expressly allowed by the standard and thus our API.
2568 if ((*this)->isIncompleteType())
2571 if (hasNonTrivialObjCLifetime())
2574 QualType CanonicalType
= getTypePtr()->CanonicalType
;
2575 if (CanonicalType
->isDependentType())
2578 // C++0x [basic.types]p9:
2579 // Scalar types, trivial class types, arrays of such types, and
2580 // cv-qualified versions of these types are collectively called trivial
2583 // As an extension, Clang treats vector types as Scalar types.
2584 if (CanonicalType
->isScalarType() || CanonicalType
->isVectorType())
2586 if (const auto *RT
= CanonicalType
->getAs
<RecordType
>()) {
2587 if (const auto *ClassDecl
= dyn_cast
<CXXRecordDecl
>(RT
->getDecl())) {
2589 // A trivial class is a class that is trivially copyable, and
2590 // has one or more eligible default constructors such that each is
2592 // FIXME: We should merge this definition of triviality into
2593 // CXXRecordDecl::isTrivial. Currently it computes the wrong thing.
2594 return ClassDecl
->hasTrivialDefaultConstructor() &&
2595 !ClassDecl
->hasNonTrivialDefaultConstructor() &&
2596 ClassDecl
->isTriviallyCopyable();
2602 // No other types can match.
2606 bool QualType::isTriviallyCopyableType(const ASTContext
&Context
) const {
2607 if ((*this)->isArrayType())
2608 return Context
.getBaseElementType(*this).isTriviallyCopyableType(Context
);
2610 if (hasNonTrivialObjCLifetime())
2613 // C++11 [basic.types]p9 - See Core 2094
2614 // Scalar types, trivially copyable class types, arrays of such types, and
2615 // cv-qualified versions of these types are collectively
2616 // called trivially copyable types.
2618 QualType CanonicalType
= getCanonicalType();
2619 if (CanonicalType
->isDependentType())
2622 if (CanonicalType
->isSizelessBuiltinType())
2625 // Return false for incomplete types after skipping any incomplete array types
2626 // which are expressly allowed by the standard and thus our API.
2627 if (CanonicalType
->isIncompleteType())
2630 // As an extension, Clang treats vector types as Scalar types.
2631 if (CanonicalType
->isScalarType() || CanonicalType
->isVectorType())
2634 if (const auto *RT
= CanonicalType
->getAs
<RecordType
>()) {
2635 if (const auto *ClassDecl
= dyn_cast
<CXXRecordDecl
>(RT
->getDecl())) {
2636 if (!ClassDecl
->isTriviallyCopyable()) return false;
2642 // No other types can match.
2646 bool QualType::isTriviallyRelocatableType(const ASTContext
&Context
) const {
2647 QualType BaseElementType
= Context
.getBaseElementType(*this);
2649 if (BaseElementType
->isIncompleteType()) {
2651 } else if (const auto *RD
= BaseElementType
->getAsRecordDecl()) {
2652 return RD
->canPassInRegisters();
2654 switch (isNonTrivialToPrimitiveDestructiveMove()) {
2656 return !isDestructedType();
2666 HasNonDeletedDefaultedEqualityComparison(const CXXRecordDecl
*Decl
) {
2667 if (Decl
->isUnion())
2669 if (Decl
->isLambda())
2670 return Decl
->isCapturelessLambda();
2672 auto IsDefaultedOperatorEqualEqual
= [&](const FunctionDecl
*Function
) {
2673 return Function
->getOverloadedOperator() ==
2674 OverloadedOperatorKind::OO_EqualEqual
&&
2675 Function
->isDefaulted() && Function
->getNumParams() > 0 &&
2676 (Function
->getParamDecl(0)->getType()->isReferenceType() ||
2677 Decl
->isTriviallyCopyable());
2680 if (llvm::none_of(Decl
->methods(), IsDefaultedOperatorEqualEqual
) &&
2681 llvm::none_of(Decl
->friends(), [&](const FriendDecl
*Friend
) {
2682 if (NamedDecl
*ND
= Friend
->getFriendDecl()) {
2683 return ND
->isFunctionOrFunctionTemplate() &&
2684 IsDefaultedOperatorEqualEqual(ND
->getAsFunction());
2690 return llvm::all_of(Decl
->bases(),
2691 [](const CXXBaseSpecifier
&BS
) {
2692 if (const auto *RD
= BS
.getType()->getAsCXXRecordDecl())
2693 return HasNonDeletedDefaultedEqualityComparison(RD
);
2696 llvm::all_of(Decl
->fields(), [](const FieldDecl
*FD
) {
2697 auto Type
= FD
->getType();
2698 if (Type
->isArrayType())
2699 Type
= Type
->getBaseElementTypeUnsafe()->getCanonicalTypeUnqualified();
2701 if (Type
->isReferenceType() || Type
->isEnumeralType())
2703 if (const auto *RD
= Type
->getAsCXXRecordDecl())
2704 return HasNonDeletedDefaultedEqualityComparison(RD
);
2709 bool QualType::isTriviallyEqualityComparableType(
2710 const ASTContext
&Context
) const {
2711 QualType CanonicalType
= getCanonicalType();
2712 if (CanonicalType
->isIncompleteType() || CanonicalType
->isDependentType() ||
2713 CanonicalType
->isEnumeralType() || CanonicalType
->isArrayType())
2716 if (const auto *RD
= CanonicalType
->getAsCXXRecordDecl()) {
2717 if (!HasNonDeletedDefaultedEqualityComparison(RD
))
2721 return Context
.hasUniqueObjectRepresentations(
2722 CanonicalType
, /*CheckIfTriviallyCopyable=*/false);
2725 bool QualType::isNonWeakInMRRWithObjCWeak(const ASTContext
&Context
) const {
2726 return !Context
.getLangOpts().ObjCAutoRefCount
&&
2727 Context
.getLangOpts().ObjCWeak
&&
2728 getObjCLifetime() != Qualifiers::OCL_Weak
;
2731 bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl
*RD
) {
2732 return RD
->hasNonTrivialToPrimitiveDefaultInitializeCUnion();
2735 bool QualType::hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl
*RD
) {
2736 return RD
->hasNonTrivialToPrimitiveDestructCUnion();
2739 bool QualType::hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl
*RD
) {
2740 return RD
->hasNonTrivialToPrimitiveCopyCUnion();
2743 bool QualType::isWebAssemblyReferenceType() const {
2744 return isWebAssemblyExternrefType() || isWebAssemblyFuncrefType();
2747 bool QualType::isWebAssemblyExternrefType() const {
2748 return getTypePtr()->isWebAssemblyExternrefType();
2751 bool QualType::isWebAssemblyFuncrefType() const {
2752 return getTypePtr()->isFunctionPointerType() &&
2753 getAddressSpace() == LangAS::wasm_funcref
;
2756 QualType::PrimitiveDefaultInitializeKind
2757 QualType::isNonTrivialToPrimitiveDefaultInitialize() const {
2758 if (const auto *RT
=
2759 getTypePtr()->getBaseElementTypeUnsafe()->getAs
<RecordType
>())
2760 if (RT
->getDecl()->isNonTrivialToPrimitiveDefaultInitialize())
2763 switch (getQualifiers().getObjCLifetime()) {
2764 case Qualifiers::OCL_Strong
:
2765 return PDIK_ARCStrong
;
2766 case Qualifiers::OCL_Weak
:
2767 return PDIK_ARCWeak
;
2769 return PDIK_Trivial
;
2773 QualType::PrimitiveCopyKind
QualType::isNonTrivialToPrimitiveCopy() const {
2774 if (const auto *RT
=
2775 getTypePtr()->getBaseElementTypeUnsafe()->getAs
<RecordType
>())
2776 if (RT
->getDecl()->isNonTrivialToPrimitiveCopy())
2779 Qualifiers Qs
= getQualifiers();
2780 switch (Qs
.getObjCLifetime()) {
2781 case Qualifiers::OCL_Strong
:
2782 return PCK_ARCStrong
;
2783 case Qualifiers::OCL_Weak
:
2786 return Qs
.hasVolatile() ? PCK_VolatileTrivial
: PCK_Trivial
;
2790 QualType::PrimitiveCopyKind
2791 QualType::isNonTrivialToPrimitiveDestructiveMove() const {
2792 return isNonTrivialToPrimitiveCopy();
2795 bool Type::isLiteralType(const ASTContext
&Ctx
) const {
2796 if (isDependentType())
2799 // C++1y [basic.types]p10:
2800 // A type is a literal type if it is:
2802 if (Ctx
.getLangOpts().CPlusPlus14
&& isVoidType())
2805 // C++11 [basic.types]p10:
2806 // A type is a literal type if it is:
2808 // -- an array of literal type other than an array of runtime bound; or
2809 if (isVariableArrayType())
2811 const Type
*BaseTy
= getBaseElementTypeUnsafe();
2812 assert(BaseTy
&& "NULL element type");
2814 // Return false for incomplete types after skipping any incomplete array
2815 // types; those are expressly allowed by the standard and thus our API.
2816 if (BaseTy
->isIncompleteType())
2819 // C++11 [basic.types]p10:
2820 // A type is a literal type if it is:
2821 // -- a scalar type; or
2822 // As an extension, Clang treats vector types and complex types as
2824 if (BaseTy
->isScalarType() || BaseTy
->isVectorType() ||
2825 BaseTy
->isAnyComplexType())
2827 // -- a reference type; or
2828 if (BaseTy
->isReferenceType())
2830 // -- a class type that has all of the following properties:
2831 if (const auto *RT
= BaseTy
->getAs
<RecordType
>()) {
2832 // -- a trivial destructor,
2833 // -- every constructor call and full-expression in the
2834 // brace-or-equal-initializers for non-static data members (if any)
2835 // is a constant expression,
2836 // -- it is an aggregate type or has at least one constexpr
2837 // constructor or constructor template that is not a copy or move
2839 // -- all non-static data members and base classes of literal types
2841 // We resolve DR1361 by ignoring the second bullet.
2842 if (const auto *ClassDecl
= dyn_cast
<CXXRecordDecl
>(RT
->getDecl()))
2843 return ClassDecl
->isLiteral();
2848 // We treat _Atomic T as a literal type if T is a literal type.
2849 if (const auto *AT
= BaseTy
->getAs
<AtomicType
>())
2850 return AT
->getValueType()->isLiteralType(Ctx
);
2852 // If this type hasn't been deduced yet, then conservatively assume that
2853 // it'll work out to be a literal type.
2854 if (isa
<AutoType
>(BaseTy
->getCanonicalTypeInternal()))
2860 bool Type::isStructuralType() const {
2861 // C++20 [temp.param]p6:
2862 // A structural type is one of the following:
2863 // -- a scalar type; or
2864 // -- a vector type [Clang extension]; or
2865 if (isScalarType() || isVectorType())
2867 // -- an lvalue reference type; or
2868 if (isLValueReferenceType())
2870 // -- a literal class type [...under some conditions]
2871 if (const CXXRecordDecl
*RD
= getAsCXXRecordDecl())
2872 return RD
->isStructural();
2876 bool Type::isStandardLayoutType() const {
2877 if (isDependentType())
2880 // C++0x [basic.types]p9:
2881 // Scalar types, standard-layout class types, arrays of such types, and
2882 // cv-qualified versions of these types are collectively called
2883 // standard-layout types.
2884 const Type
*BaseTy
= getBaseElementTypeUnsafe();
2885 assert(BaseTy
&& "NULL element type");
2887 // Return false for incomplete types after skipping any incomplete array
2888 // types which are expressly allowed by the standard and thus our API.
2889 if (BaseTy
->isIncompleteType())
2892 // As an extension, Clang treats vector types as Scalar types.
2893 if (BaseTy
->isScalarType() || BaseTy
->isVectorType()) return true;
2894 if (const auto *RT
= BaseTy
->getAs
<RecordType
>()) {
2895 if (const auto *ClassDecl
= dyn_cast
<CXXRecordDecl
>(RT
->getDecl()))
2896 if (!ClassDecl
->isStandardLayout())
2899 // Default to 'true' for non-C++ class types.
2900 // FIXME: This is a bit dubious, but plain C structs should trivially meet
2901 // all the requirements of standard layout classes.
2905 // No other types can match.
2909 // This is effectively the intersection of isTrivialType and
2910 // isStandardLayoutType. We implement it directly to avoid redundant
2911 // conversions from a type to a CXXRecordDecl.
2912 bool QualType::isCXX11PODType(const ASTContext
&Context
) const {
2913 const Type
*ty
= getTypePtr();
2914 if (ty
->isDependentType())
2917 if (hasNonTrivialObjCLifetime())
2920 // C++11 [basic.types]p9:
2921 // Scalar types, POD classes, arrays of such types, and cv-qualified
2922 // versions of these types are collectively called trivial types.
2923 const Type
*BaseTy
= ty
->getBaseElementTypeUnsafe();
2924 assert(BaseTy
&& "NULL element type");
2926 if (BaseTy
->isSizelessBuiltinType())
2929 // Return false for incomplete types after skipping any incomplete array
2930 // types which are expressly allowed by the standard and thus our API.
2931 if (BaseTy
->isIncompleteType())
2934 // As an extension, Clang treats vector types as Scalar types.
2935 if (BaseTy
->isScalarType() || BaseTy
->isVectorType()) return true;
2936 if (const auto *RT
= BaseTy
->getAs
<RecordType
>()) {
2937 if (const auto *ClassDecl
= dyn_cast
<CXXRecordDecl
>(RT
->getDecl())) {
2938 // C++11 [class]p10:
2939 // A POD struct is a non-union class that is both a trivial class [...]
2940 if (!ClassDecl
->isTrivial()) return false;
2942 // C++11 [class]p10:
2943 // A POD struct is a non-union class that is both a trivial class and
2944 // a standard-layout class [...]
2945 if (!ClassDecl
->isStandardLayout()) return false;
2947 // C++11 [class]p10:
2948 // A POD struct is a non-union class that is both a trivial class and
2949 // a standard-layout class, and has no non-static data members of type
2950 // non-POD struct, non-POD union (or array of such types). [...]
2952 // We don't directly query the recursive aspect as the requirements for
2953 // both standard-layout classes and trivial classes apply recursively
2960 // No other types can match.
2964 bool Type::isNothrowT() const {
2965 if (const auto *RD
= getAsCXXRecordDecl()) {
2966 IdentifierInfo
*II
= RD
->getIdentifier();
2967 if (II
&& II
->isStr("nothrow_t") && RD
->isInStdNamespace())
2973 bool Type::isAlignValT() const {
2974 if (const auto *ET
= getAs
<EnumType
>()) {
2975 IdentifierInfo
*II
= ET
->getDecl()->getIdentifier();
2976 if (II
&& II
->isStr("align_val_t") && ET
->getDecl()->isInStdNamespace())
2982 bool Type::isStdByteType() const {
2983 if (const auto *ET
= getAs
<EnumType
>()) {
2984 IdentifierInfo
*II
= ET
->getDecl()->getIdentifier();
2985 if (II
&& II
->isStr("byte") && ET
->getDecl()->isInStdNamespace())
2991 bool Type::isSpecifierType() const {
2992 // Note that this intentionally does not use the canonical type.
2993 switch (getTypeClass()) {
3001 case TemplateTypeParm
:
3002 case SubstTemplateTypeParm
:
3003 case TemplateSpecialization
:
3006 case DependentTemplateSpecialization
:
3015 ElaboratedTypeKeyword
3016 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec
) {
3019 return ElaboratedTypeKeyword::None
;
3021 return ElaboratedTypeKeyword::Typename
;
3023 return ElaboratedTypeKeyword::Class
;
3025 return ElaboratedTypeKeyword::Struct
;
3027 return ElaboratedTypeKeyword::Interface
;
3029 return ElaboratedTypeKeyword::Union
;
3031 return ElaboratedTypeKeyword::Enum
;
3036 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec
) {
3038 case TST_class
: return TTK_Class
;
3039 case TST_struct
: return TTK_Struct
;
3040 case TST_interface
: return TTK_Interface
;
3041 case TST_union
: return TTK_Union
;
3042 case TST_enum
: return TTK_Enum
;
3045 llvm_unreachable("Type specifier is not a tag type kind.");
3048 ElaboratedTypeKeyword
3049 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind
) {
3052 return ElaboratedTypeKeyword::Class
;
3054 return ElaboratedTypeKeyword::Struct
;
3056 return ElaboratedTypeKeyword::Interface
;
3058 return ElaboratedTypeKeyword::Union
;
3060 return ElaboratedTypeKeyword::Enum
;
3062 llvm_unreachable("Unknown tag type kind.");
3066 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword
) {
3068 case ElaboratedTypeKeyword::Class
:
3070 case ElaboratedTypeKeyword::Struct
:
3072 case ElaboratedTypeKeyword::Interface
:
3073 return TTK_Interface
;
3074 case ElaboratedTypeKeyword::Union
:
3076 case ElaboratedTypeKeyword::Enum
:
3078 case ElaboratedTypeKeyword::None
: // Fall through.
3079 case ElaboratedTypeKeyword::Typename
:
3080 llvm_unreachable("Elaborated type keyword is not a tag type kind.");
3082 llvm_unreachable("Unknown elaborated type keyword.");
3086 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword
) {
3088 case ElaboratedTypeKeyword::None
:
3089 case ElaboratedTypeKeyword::Typename
:
3091 case ElaboratedTypeKeyword::Class
:
3092 case ElaboratedTypeKeyword::Struct
:
3093 case ElaboratedTypeKeyword::Interface
:
3094 case ElaboratedTypeKeyword::Union
:
3095 case ElaboratedTypeKeyword::Enum
:
3098 llvm_unreachable("Unknown elaborated type keyword.");
3101 StringRef
TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword
) {
3103 case ElaboratedTypeKeyword::None
:
3105 case ElaboratedTypeKeyword::Typename
:
3107 case ElaboratedTypeKeyword::Class
:
3109 case ElaboratedTypeKeyword::Struct
:
3111 case ElaboratedTypeKeyword::Interface
:
3112 return "__interface";
3113 case ElaboratedTypeKeyword::Union
:
3115 case ElaboratedTypeKeyword::Enum
:
3119 llvm_unreachable("Unknown elaborated type keyword.");
3122 DependentTemplateSpecializationType::DependentTemplateSpecializationType(
3123 ElaboratedTypeKeyword Keyword
, NestedNameSpecifier
*NNS
,
3124 const IdentifierInfo
*Name
, ArrayRef
<TemplateArgument
> Args
, QualType Canon
)
3125 : TypeWithKeyword(Keyword
, DependentTemplateSpecialization
, Canon
,
3126 TypeDependence::DependentInstantiation
|
3127 (NNS
? toTypeDependence(NNS
->getDependence())
3128 : TypeDependence::None
)),
3129 NNS(NNS
), Name(Name
) {
3130 DependentTemplateSpecializationTypeBits
.NumArgs
= Args
.size();
3131 assert((!NNS
|| NNS
->isDependent()) &&
3132 "DependentTemplateSpecializatonType requires dependent qualifier");
3133 auto *ArgBuffer
= const_cast<TemplateArgument
*>(template_arguments().data());
3134 for (const TemplateArgument
&Arg
: Args
) {
3135 addDependence(toTypeDependence(Arg
.getDependence() &
3136 TemplateArgumentDependence::UnexpandedPack
));
3138 new (ArgBuffer
++) TemplateArgument(Arg
);
3143 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID
&ID
,
3144 const ASTContext
&Context
,
3145 ElaboratedTypeKeyword Keyword
,
3146 NestedNameSpecifier
*Qualifier
,
3147 const IdentifierInfo
*Name
,
3148 ArrayRef
<TemplateArgument
> Args
) {
3149 ID
.AddInteger(llvm::to_underlying(Keyword
));
3150 ID
.AddPointer(Qualifier
);
3151 ID
.AddPointer(Name
);
3152 for (const TemplateArgument
&Arg
: Args
)
3153 Arg
.Profile(ID
, Context
);
3156 bool Type::isElaboratedTypeSpecifier() const {
3157 ElaboratedTypeKeyword Keyword
;
3158 if (const auto *Elab
= dyn_cast
<ElaboratedType
>(this))
3159 Keyword
= Elab
->getKeyword();
3160 else if (const auto *DepName
= dyn_cast
<DependentNameType
>(this))
3161 Keyword
= DepName
->getKeyword();
3162 else if (const auto *DepTST
=
3163 dyn_cast
<DependentTemplateSpecializationType
>(this))
3164 Keyword
= DepTST
->getKeyword();
3168 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword
);
3171 const char *Type::getTypeClassName() const {
3172 switch (TypeBits
.TC
) {
3173 #define ABSTRACT_TYPE(Derived, Base)
3174 #define TYPE(Derived, Base) case Derived: return #Derived;
3175 #include "clang/AST/TypeNodes.inc"
3178 llvm_unreachable("Invalid type class.");
3181 StringRef
BuiltinType::getName(const PrintingPolicy
&Policy
) const {
3182 switch (getKind()) {
3186 return Policy
.Bool
? "bool" : "_Bool";
3192 return "signed char";
3204 return "unsigned char";
3206 return "unsigned short";
3208 return "unsigned int";
3210 return "unsigned long";
3212 return "unsigned long long";
3214 return "unsigned __int128";
3216 return Policy
.Half
? "half" : "__fp16";
3224 return "long double";
3226 return "short _Accum";
3230 return "long _Accum";
3232 return "unsigned short _Accum";
3234 return "unsigned _Accum";
3236 return "unsigned long _Accum";
3237 case BuiltinType::ShortFract
:
3238 return "short _Fract";
3239 case BuiltinType::Fract
:
3241 case BuiltinType::LongFract
:
3242 return "long _Fract";
3243 case BuiltinType::UShortFract
:
3244 return "unsigned short _Fract";
3245 case BuiltinType::UFract
:
3246 return "unsigned _Fract";
3247 case BuiltinType::ULongFract
:
3248 return "unsigned long _Fract";
3249 case BuiltinType::SatShortAccum
:
3250 return "_Sat short _Accum";
3251 case BuiltinType::SatAccum
:
3252 return "_Sat _Accum";
3253 case BuiltinType::SatLongAccum
:
3254 return "_Sat long _Accum";
3255 case BuiltinType::SatUShortAccum
:
3256 return "_Sat unsigned short _Accum";
3257 case BuiltinType::SatUAccum
:
3258 return "_Sat unsigned _Accum";
3259 case BuiltinType::SatULongAccum
:
3260 return "_Sat unsigned long _Accum";
3261 case BuiltinType::SatShortFract
:
3262 return "_Sat short _Fract";
3263 case BuiltinType::SatFract
:
3264 return "_Sat _Fract";
3265 case BuiltinType::SatLongFract
:
3266 return "_Sat long _Fract";
3267 case BuiltinType::SatUShortFract
:
3268 return "_Sat unsigned short _Fract";
3269 case BuiltinType::SatUFract
:
3270 return "_Sat unsigned _Fract";
3271 case BuiltinType::SatULongFract
:
3272 return "_Sat unsigned long _Fract";
3276 return "__float128";
3281 return Policy
.MSWChar
? "__wchar_t" : "wchar_t";
3289 return Policy
.NullptrTypeInNamespace
? "std::nullptr_t" : "nullptr_t";
3291 return "<overloaded function type>";
3293 return "<bound member function type>";
3295 return "<pseudo-object type>";
3297 return "<dependent type>";
3299 return "<unknown type>";
3300 case ARCUnbridgedCast
:
3301 return "<ARC unbridged cast type>";
3303 return "<builtin fn type>";
3310 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3312 return "__" #Access " " #ImgType "_t";
3313 #include "clang/Basic/OpenCLImageTypes.def"
3319 return "clk_event_t";
3323 return "reserve_id_t";
3324 case IncompleteMatrixIdx
:
3325 return "<incomplete matrix index type>";
3326 case OMPArraySection
:
3327 return "<OpenMP array section type>";
3328 case OMPArrayShaping
:
3329 return "<OpenMP array shaping type>";
3331 return "<OpenMP iterator type>";
3332 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3335 #include "clang/Basic/OpenCLExtensionTypes.def"
3336 #define SVE_TYPE(Name, Id, SingletonId) \
3339 #include "clang/Basic/AArch64SVEACLETypes.def"
3340 #define PPC_VECTOR_TYPE(Name, Id, Size) \
3343 #include "clang/Basic/PPCTypes.def"
3344 #define RVV_TYPE(Name, Id, SingletonId) \
3347 #include "clang/Basic/RISCVVTypes.def"
3348 #define WASM_TYPE(Name, Id, SingletonId) \
3351 #include "clang/Basic/WebAssemblyReferenceTypes.def"
3354 llvm_unreachable("Invalid builtin type.");
3357 QualType
QualType::getNonPackExpansionType() const {
3358 // We never wrap type sugar around a PackExpansionType.
3359 if (auto *PET
= dyn_cast
<PackExpansionType
>(getTypePtr()))
3360 return PET
->getPattern();
3364 QualType
QualType::getNonLValueExprType(const ASTContext
&Context
) const {
3365 if (const auto *RefType
= getTypePtr()->getAs
<ReferenceType
>())
3366 return RefType
->getPointeeType();
3368 // C++0x [basic.lval]:
3369 // Class prvalues can have cv-qualified types; non-class prvalues always
3370 // have cv-unqualified types.
3372 // See also C99 6.3.2.1p2.
3373 if (!Context
.getLangOpts().CPlusPlus
||
3374 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
3375 return getUnqualifiedType();
3380 StringRef
FunctionType::getNameForCallConv(CallingConv CC
) {
3382 case CC_C
: return "cdecl";
3383 case CC_X86StdCall
: return "stdcall";
3384 case CC_X86FastCall
: return "fastcall";
3385 case CC_X86ThisCall
: return "thiscall";
3386 case CC_X86Pascal
: return "pascal";
3387 case CC_X86VectorCall
: return "vectorcall";
3388 case CC_Win64
: return "ms_abi";
3389 case CC_X86_64SysV
: return "sysv_abi";
3390 case CC_X86RegCall
: return "regcall";
3391 case CC_AAPCS
: return "aapcs";
3392 case CC_AAPCS_VFP
: return "aapcs-vfp";
3393 case CC_AArch64VectorCall
: return "aarch64_vector_pcs";
3394 case CC_AArch64SVEPCS
: return "aarch64_sve_pcs";
3395 case CC_AMDGPUKernelCall
: return "amdgpu_kernel";
3396 case CC_IntelOclBicc
: return "intel_ocl_bicc";
3397 case CC_SpirFunction
: return "spir_function";
3398 case CC_OpenCLKernel
: return "opencl_kernel";
3399 case CC_Swift
: return "swiftcall";
3400 case CC_SwiftAsync
: return "swiftasynccall";
3401 case CC_PreserveMost
: return "preserve_most";
3402 case CC_PreserveAll
: return "preserve_all";
3403 case CC_M68kRTD
: return "m68k_rtd";
3406 llvm_unreachable("Invalid calling convention.");
3409 FunctionProtoType::FunctionProtoType(QualType result
, ArrayRef
<QualType
> params
,
3411 const ExtProtoInfo
&epi
)
3412 : FunctionType(FunctionProto
, result
, canonical
, result
->getDependence(),
3414 FunctionTypeBits
.FastTypeQuals
= epi
.TypeQuals
.getFastQualifiers();
3415 FunctionTypeBits
.RefQualifier
= epi
.RefQualifier
;
3416 FunctionTypeBits
.NumParams
= params
.size();
3417 assert(getNumParams() == params
.size() && "NumParams overflow!");
3418 FunctionTypeBits
.ExceptionSpecType
= epi
.ExceptionSpec
.Type
;
3419 FunctionTypeBits
.HasExtParameterInfos
= !!epi
.ExtParameterInfos
;
3420 FunctionTypeBits
.Variadic
= epi
.Variadic
;
3421 FunctionTypeBits
.HasTrailingReturn
= epi
.HasTrailingReturn
;
3423 if (epi
.requiresFunctionProtoTypeExtraBitfields()) {
3424 FunctionTypeBits
.HasExtraBitfields
= true;
3425 auto &ExtraBits
= *getTrailingObjects
<FunctionTypeExtraBitfields
>();
3426 ExtraBits
= FunctionTypeExtraBitfields();
3428 FunctionTypeBits
.HasExtraBitfields
= false;
3432 // Fill in the trailing argument array.
3433 auto *argSlot
= getTrailingObjects
<QualType
>();
3434 for (unsigned i
= 0; i
!= getNumParams(); ++i
) {
3435 addDependence(params
[i
]->getDependence() &
3436 ~TypeDependence::VariablyModified
);
3437 argSlot
[i
] = params
[i
];
3440 // Propagate the SME ACLE attributes.
3441 if (epi
.AArch64SMEAttributes
!= SME_NormalFunction
) {
3442 auto &ExtraBits
= *getTrailingObjects
<FunctionTypeExtraBitfields
>();
3443 assert(epi
.AArch64SMEAttributes
<= SME_AttributeMask
&&
3444 "Not enough bits to encode SME attributes");
3445 ExtraBits
.AArch64SMEAttributes
= epi
.AArch64SMEAttributes
;
3448 // Fill in the exception type array if present.
3449 if (getExceptionSpecType() == EST_Dynamic
) {
3450 auto &ExtraBits
= *getTrailingObjects
<FunctionTypeExtraBitfields
>();
3451 size_t NumExceptions
= epi
.ExceptionSpec
.Exceptions
.size();
3452 assert(NumExceptions
<= 1023 && "Not enough bits to encode exceptions");
3453 ExtraBits
.NumExceptionType
= NumExceptions
;
3455 assert(hasExtraBitfields() && "missing trailing extra bitfields!");
3457 reinterpret_cast<QualType
*>(getTrailingObjects
<ExceptionType
>());
3459 for (QualType ExceptionType
: epi
.ExceptionSpec
.Exceptions
) {
3460 // Note that, before C++17, a dependent exception specification does
3461 // *not* make a type dependent; it's not even part of the C++ type
3464 ExceptionType
->getDependence() &
3465 (TypeDependence::Instantiation
| TypeDependence::UnexpandedPack
));
3467 exnSlot
[I
++] = ExceptionType
;
3470 // Fill in the Expr * in the exception specification if present.
3471 else if (isComputedNoexcept(getExceptionSpecType())) {
3472 assert(epi
.ExceptionSpec
.NoexceptExpr
&& "computed noexcept with no expr");
3473 assert((getExceptionSpecType() == EST_DependentNoexcept
) ==
3474 epi
.ExceptionSpec
.NoexceptExpr
->isValueDependent());
3476 // Store the noexcept expression and context.
3477 *getTrailingObjects
<Expr
*>() = epi
.ExceptionSpec
.NoexceptExpr
;
3480 toTypeDependence(epi
.ExceptionSpec
.NoexceptExpr
->getDependence()) &
3481 (TypeDependence::Instantiation
| TypeDependence::UnexpandedPack
));
3483 // Fill in the FunctionDecl * in the exception specification if present.
3484 else if (getExceptionSpecType() == EST_Uninstantiated
) {
3485 // Store the function decl from which we will resolve our
3486 // exception specification.
3487 auto **slot
= getTrailingObjects
<FunctionDecl
*>();
3488 slot
[0] = epi
.ExceptionSpec
.SourceDecl
;
3489 slot
[1] = epi
.ExceptionSpec
.SourceTemplate
;
3490 // This exception specification doesn't make the type dependent, because
3491 // it's not instantiated as part of instantiating the type.
3492 } else if (getExceptionSpecType() == EST_Unevaluated
) {
3493 // Store the function decl from which we will resolve our
3494 // exception specification.
3495 auto **slot
= getTrailingObjects
<FunctionDecl
*>();
3496 slot
[0] = epi
.ExceptionSpec
.SourceDecl
;
3499 // If this is a canonical type, and its exception specification is dependent,
3500 // then it's a dependent type. This only happens in C++17 onwards.
3501 if (isCanonicalUnqualified()) {
3502 if (getExceptionSpecType() == EST_Dynamic
||
3503 getExceptionSpecType() == EST_DependentNoexcept
) {
3504 assert(hasDependentExceptionSpec() && "type should not be canonical");
3505 addDependence(TypeDependence::DependentInstantiation
);
3507 } else if (getCanonicalTypeInternal()->isDependentType()) {
3508 // Ask our canonical type whether our exception specification was dependent.
3509 addDependence(TypeDependence::DependentInstantiation
);
3512 // Fill in the extra parameter info if present.
3513 if (epi
.ExtParameterInfos
) {
3514 auto *extParamInfos
= getTrailingObjects
<ExtParameterInfo
>();
3515 for (unsigned i
= 0; i
!= getNumParams(); ++i
)
3516 extParamInfos
[i
] = epi
.ExtParameterInfos
[i
];
3519 if (epi
.TypeQuals
.hasNonFastQualifiers()) {
3520 FunctionTypeBits
.HasExtQuals
= 1;
3521 *getTrailingObjects
<Qualifiers
>() = epi
.TypeQuals
;
3523 FunctionTypeBits
.HasExtQuals
= 0;
3526 // Fill in the Ellipsis location info if present.
3528 auto &EllipsisLoc
= *getTrailingObjects
<SourceLocation
>();
3529 EllipsisLoc
= epi
.EllipsisLoc
;
3533 bool FunctionProtoType::hasDependentExceptionSpec() const {
3534 if (Expr
*NE
= getNoexceptExpr())
3535 return NE
->isValueDependent();
3536 for (QualType ET
: exceptions())
3537 // A pack expansion with a non-dependent pattern is still dependent,
3538 // because we don't know whether the pattern is in the exception spec
3539 // or not (that depends on whether the pack has 0 expansions).
3540 if (ET
->isDependentType() || ET
->getAs
<PackExpansionType
>())
3545 bool FunctionProtoType::hasInstantiationDependentExceptionSpec() const {
3546 if (Expr
*NE
= getNoexceptExpr())
3547 return NE
->isInstantiationDependent();
3548 for (QualType ET
: exceptions())
3549 if (ET
->isInstantiationDependentType())
3554 CanThrowResult
FunctionProtoType::canThrow() const {
3555 switch (getExceptionSpecType()) {
3557 case EST_Unevaluated
:
3558 llvm_unreachable("should not call this with unresolved exception specs");
3560 case EST_DynamicNone
:
3561 case EST_BasicNoexcept
:
3562 case EST_NoexceptTrue
:
3568 case EST_NoexceptFalse
:
3572 // A dynamic exception specification is throwing unless every exception
3573 // type is an (unexpanded) pack expansion type.
3574 for (unsigned I
= 0; I
!= getNumExceptions(); ++I
)
3575 if (!getExceptionType(I
)->getAs
<PackExpansionType
>())
3577 return CT_Dependent
;
3579 case EST_Uninstantiated
:
3580 case EST_DependentNoexcept
:
3581 return CT_Dependent
;
3584 llvm_unreachable("unexpected exception specification kind");
3587 bool FunctionProtoType::isTemplateVariadic() const {
3588 for (unsigned ArgIdx
= getNumParams(); ArgIdx
; --ArgIdx
)
3589 if (isa
<PackExpansionType
>(getParamType(ArgIdx
- 1)))
3595 void FunctionProtoType::Profile(llvm::FoldingSetNodeID
&ID
, QualType Result
,
3596 const QualType
*ArgTys
, unsigned NumParams
,
3597 const ExtProtoInfo
&epi
,
3598 const ASTContext
&Context
, bool Canonical
) {
3599 // We have to be careful not to get ambiguous profile encodings.
3600 // Note that valid type pointers are never ambiguous with anything else.
3602 // The encoding grammar begins:
3603 // type type* bool int bool
3604 // If that final bool is true, then there is a section for the EH spec:
3606 // This is followed by an optional "consumed argument" section of the
3607 // same length as the first type sequence:
3609 // This is followed by the ext info:
3611 // Finally we have a trailing return type flag (bool)
3612 // combined with AArch64 SME Attributes, to save space:
3615 // There is no ambiguity between the consumed arguments and an empty EH
3616 // spec because of the leading 'bool' which unambiguously indicates
3617 // whether the following bool is the EH spec or part of the arguments.
3619 ID
.AddPointer(Result
.getAsOpaquePtr());
3620 for (unsigned i
= 0; i
!= NumParams
; ++i
)
3621 ID
.AddPointer(ArgTys
[i
].getAsOpaquePtr());
3622 // This method is relatively performance sensitive, so as a performance
3623 // shortcut, use one AddInteger call instead of four for the next four
3625 assert(!(unsigned(epi
.Variadic
) & ~1) &&
3626 !(unsigned(epi
.RefQualifier
) & ~3) &&
3627 !(unsigned(epi
.ExceptionSpec
.Type
) & ~15) &&
3628 "Values larger than expected.");
3629 ID
.AddInteger(unsigned(epi
.Variadic
) +
3630 (epi
.RefQualifier
<< 1) +
3631 (epi
.ExceptionSpec
.Type
<< 3));
3632 ID
.Add(epi
.TypeQuals
);
3633 if (epi
.ExceptionSpec
.Type
== EST_Dynamic
) {
3634 for (QualType Ex
: epi
.ExceptionSpec
.Exceptions
)
3635 ID
.AddPointer(Ex
.getAsOpaquePtr());
3636 } else if (isComputedNoexcept(epi
.ExceptionSpec
.Type
)) {
3637 epi
.ExceptionSpec
.NoexceptExpr
->Profile(ID
, Context
, Canonical
);
3638 } else if (epi
.ExceptionSpec
.Type
== EST_Uninstantiated
||
3639 epi
.ExceptionSpec
.Type
== EST_Unevaluated
) {
3640 ID
.AddPointer(epi
.ExceptionSpec
.SourceDecl
->getCanonicalDecl());
3642 if (epi
.ExtParameterInfos
) {
3643 for (unsigned i
= 0; i
!= NumParams
; ++i
)
3644 ID
.AddInteger(epi
.ExtParameterInfos
[i
].getOpaqueValue());
3647 epi
.ExtInfo
.Profile(ID
);
3648 ID
.AddInteger((epi
.AArch64SMEAttributes
<< 1) | epi
.HasTrailingReturn
);
3651 void FunctionProtoType::Profile(llvm::FoldingSetNodeID
&ID
,
3652 const ASTContext
&Ctx
) {
3653 Profile(ID
, getReturnType(), param_type_begin(), getNumParams(),
3654 getExtProtoInfo(), Ctx
, isCanonicalUnqualified());
3657 TypedefType::TypedefType(TypeClass tc
, const TypedefNameDecl
*D
,
3658 QualType Underlying
, QualType can
)
3659 : Type(tc
, can
, toSemanticDependence(can
->getDependence())),
3660 Decl(const_cast<TypedefNameDecl
*>(D
)) {
3661 assert(!isa
<TypedefType
>(can
) && "Invalid canonical type");
3662 TypedefBits
.hasTypeDifferentFromDecl
= !Underlying
.isNull();
3663 if (!typeMatchesDecl())
3664 *getTrailingObjects
<QualType
>() = Underlying
;
3667 QualType
TypedefType::desugar() const {
3668 return typeMatchesDecl() ? Decl
->getUnderlyingType()
3669 : *getTrailingObjects
<QualType
>();
3672 UsingType::UsingType(const UsingShadowDecl
*Found
, QualType Underlying
,
3674 : Type(Using
, Canon
, toSemanticDependence(Canon
->getDependence())),
3675 Found(const_cast<UsingShadowDecl
*>(Found
)) {
3676 UsingBits
.hasTypeDifferentFromDecl
= !Underlying
.isNull();
3677 if (!typeMatchesDecl())
3678 *getTrailingObjects
<QualType
>() = Underlying
;
3681 QualType
UsingType::getUnderlyingType() const {
3682 return typeMatchesDecl()
3684 cast
<TypeDecl
>(Found
->getTargetDecl())->getTypeForDecl(), 0)
3685 : *getTrailingObjects
<QualType
>();
3688 QualType
MacroQualifiedType::desugar() const { return getUnderlyingType(); }
3690 QualType
MacroQualifiedType::getModifiedType() const {
3691 // Step over MacroQualifiedTypes from the same macro to find the type
3692 // ultimately qualified by the macro qualifier.
3693 QualType Inner
= cast
<AttributedType
>(getUnderlyingType())->getModifiedType();
3694 while (auto *InnerMQT
= dyn_cast
<MacroQualifiedType
>(Inner
)) {
3695 if (InnerMQT
->getMacroIdentifier() != getMacroIdentifier())
3697 Inner
= InnerMQT
->getModifiedType();
3702 TypeOfExprType::TypeOfExprType(Expr
*E
, TypeOfKind Kind
, QualType Can
)
3704 // We have to protect against 'Can' being invalid through its
3705 // default argument.
3706 Kind
== TypeOfKind::Unqualified
&& !Can
.isNull()
3707 ? Can
.getAtomicUnqualifiedType()
3709 toTypeDependence(E
->getDependence()) |
3710 (E
->getType()->getDependence() &
3711 TypeDependence::VariablyModified
)),
3713 TypeOfBits
.IsUnqual
= Kind
== TypeOfKind::Unqualified
;
3716 bool TypeOfExprType::isSugared() const {
3717 return !TOExpr
->isTypeDependent();
3720 QualType
TypeOfExprType::desugar() const {
3722 QualType QT
= getUnderlyingExpr()->getType();
3723 return TypeOfBits
.IsUnqual
? QT
.getAtomicUnqualifiedType() : QT
;
3725 return QualType(this, 0);
3728 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID
&ID
,
3729 const ASTContext
&Context
, Expr
*E
,
3731 E
->Profile(ID
, Context
, true);
3732 ID
.AddBoolean(IsUnqual
);
3735 DecltypeType::DecltypeType(Expr
*E
, QualType underlyingType
, QualType can
)
3736 // C++11 [temp.type]p2: "If an expression e involves a template parameter,
3737 // decltype(e) denotes a unique dependent type." Hence a decltype type is
3738 // type-dependent even if its expression is only instantiation-dependent.
3739 : Type(Decltype
, can
,
3740 toTypeDependence(E
->getDependence()) |
3741 (E
->isInstantiationDependent() ? TypeDependence::Dependent
3742 : TypeDependence::None
) |
3743 (E
->getType()->getDependence() &
3744 TypeDependence::VariablyModified
)),
3745 E(E
), UnderlyingType(underlyingType
) {}
3747 bool DecltypeType::isSugared() const { return !E
->isInstantiationDependent(); }
3749 QualType
DecltypeType::desugar() const {
3751 return getUnderlyingType();
3753 return QualType(this, 0);
3756 DependentDecltypeType::DependentDecltypeType(Expr
*E
, QualType UnderlyingType
)
3757 : DecltypeType(E
, UnderlyingType
) {}
3759 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID
&ID
,
3760 const ASTContext
&Context
, Expr
*E
) {
3761 E
->Profile(ID
, Context
, true);
3764 UnaryTransformType::UnaryTransformType(QualType BaseType
,
3765 QualType UnderlyingType
, UTTKind UKind
,
3766 QualType CanonicalType
)
3767 : Type(UnaryTransform
, CanonicalType
, BaseType
->getDependence()),
3768 BaseType(BaseType
), UnderlyingType(UnderlyingType
), UKind(UKind
) {}
3770 DependentUnaryTransformType::DependentUnaryTransformType(const ASTContext
&C
,
3773 : UnaryTransformType(BaseType
, C
.DependentTy
, UKind
, QualType()) {}
3775 TagType::TagType(TypeClass TC
, const TagDecl
*D
, QualType can
)
3777 D
->isDependentType() ? TypeDependence::DependentInstantiation
3778 : TypeDependence::None
),
3779 decl(const_cast<TagDecl
*>(D
)) {}
3781 static TagDecl
*getInterestingTagDecl(TagDecl
*decl
) {
3782 for (auto *I
: decl
->redecls()) {
3783 if (I
->isCompleteDefinition() || I
->isBeingDefined())
3786 // If there's no definition (not even in progress), return what we have.
3790 TagDecl
*TagType::getDecl() const {
3791 return getInterestingTagDecl(decl
);
3794 bool TagType::isBeingDefined() const {
3795 return getDecl()->isBeingDefined();
3798 bool RecordType::hasConstFields() const {
3799 std::vector
<const RecordType
*> RecordTypeList
;
3800 RecordTypeList
.push_back(this);
3801 unsigned NextToCheckIndex
= 0;
3803 while (RecordTypeList
.size() > NextToCheckIndex
) {
3804 for (FieldDecl
*FD
:
3805 RecordTypeList
[NextToCheckIndex
]->getDecl()->fields()) {
3806 QualType FieldTy
= FD
->getType();
3807 if (FieldTy
.isConstQualified())
3809 FieldTy
= FieldTy
.getCanonicalType();
3810 if (const auto *FieldRecTy
= FieldTy
->getAs
<RecordType
>()) {
3811 if (!llvm::is_contained(RecordTypeList
, FieldRecTy
))
3812 RecordTypeList
.push_back(FieldRecTy
);
3820 bool AttributedType::isQualifier() const {
3821 // FIXME: Generate this with TableGen.
3822 switch (getAttrKind()) {
3823 // These are type qualifiers in the traditional C sense: they annotate
3824 // something about a specific value/variable of a type. (They aren't
3825 // always part of the canonical type, though.)
3827 case attr::ObjCOwnership
:
3828 case attr::ObjCInertUnsafeUnretained
:
3829 case attr::TypeNonNull
:
3830 case attr::TypeNullable
:
3831 case attr::TypeNullableResult
:
3832 case attr::TypeNullUnspecified
:
3833 case attr::LifetimeBound
:
3834 case attr::AddressSpace
:
3837 // All other type attributes aren't qualifiers; they rewrite the modified
3838 // type to be a semantically different type.
3844 bool AttributedType::isMSTypeSpec() const {
3845 // FIXME: Generate this with TableGen?
3846 switch (getAttrKind()) {
3847 default: return false;
3854 llvm_unreachable("invalid attr kind");
3857 bool AttributedType::isWebAssemblyFuncrefSpec() const {
3858 return getAttrKind() == attr::WebAssemblyFuncref
;
3861 bool AttributedType::isCallingConv() const {
3862 // FIXME: Generate this with TableGen.
3863 switch (getAttrKind()) {
3864 default: return false;
3867 case attr::FastCall
:
3869 case attr::ThisCall
:
3871 case attr::SwiftCall
:
3872 case attr::SwiftAsyncCall
:
3873 case attr::VectorCall
:
3874 case attr::AArch64VectorPcs
:
3875 case attr::AArch64SVEPcs
:
3876 case attr::AMDGPUKernelCall
:
3880 case attr::IntelOclBicc
:
3881 case attr::PreserveMost
:
3882 case attr::PreserveAll
:
3886 llvm_unreachable("invalid attr kind");
3889 CXXRecordDecl
*InjectedClassNameType::getDecl() const {
3890 return cast
<CXXRecordDecl
>(getInterestingTagDecl(Decl
));
3893 IdentifierInfo
*TemplateTypeParmType::getIdentifier() const {
3894 return isCanonicalUnqualified() ? nullptr : getDecl()->getIdentifier();
3897 static const TemplateTypeParmDecl
*getReplacedParameter(Decl
*D
,
3899 if (const auto *TTP
= dyn_cast
<TemplateTypeParmDecl
>(D
))
3901 return cast
<TemplateTypeParmDecl
>(
3902 getReplacedTemplateParameterList(D
)->getParam(Index
));
3905 SubstTemplateTypeParmType::SubstTemplateTypeParmType(
3906 QualType Replacement
, Decl
*AssociatedDecl
, unsigned Index
,
3907 std::optional
<unsigned> PackIndex
)
3908 : Type(SubstTemplateTypeParm
, Replacement
.getCanonicalType(),
3909 Replacement
->getDependence()),
3910 AssociatedDecl(AssociatedDecl
) {
3911 SubstTemplateTypeParmTypeBits
.HasNonCanonicalUnderlyingType
=
3912 Replacement
!= getCanonicalTypeInternal();
3913 if (SubstTemplateTypeParmTypeBits
.HasNonCanonicalUnderlyingType
)
3914 *getTrailingObjects
<QualType
>() = Replacement
;
3916 SubstTemplateTypeParmTypeBits
.Index
= Index
;
3917 SubstTemplateTypeParmTypeBits
.PackIndex
= PackIndex
? *PackIndex
+ 1 : 0;
3918 assert(AssociatedDecl
!= nullptr);
3921 const TemplateTypeParmDecl
*
3922 SubstTemplateTypeParmType::getReplacedParameter() const {
3923 return ::getReplacedParameter(getAssociatedDecl(), getIndex());
3926 SubstTemplateTypeParmPackType::SubstTemplateTypeParmPackType(
3927 QualType Canon
, Decl
*AssociatedDecl
, unsigned Index
, bool Final
,
3928 const TemplateArgument
&ArgPack
)
3929 : Type(SubstTemplateTypeParmPack
, Canon
,
3930 TypeDependence::DependentInstantiation
|
3931 TypeDependence::UnexpandedPack
),
3932 Arguments(ArgPack
.pack_begin()),
3933 AssociatedDeclAndFinal(AssociatedDecl
, Final
) {
3934 SubstTemplateTypeParmPackTypeBits
.Index
= Index
;
3935 SubstTemplateTypeParmPackTypeBits
.NumArgs
= ArgPack
.pack_size();
3936 assert(AssociatedDecl
!= nullptr);
3939 Decl
*SubstTemplateTypeParmPackType::getAssociatedDecl() const {
3940 return AssociatedDeclAndFinal
.getPointer();
3943 bool SubstTemplateTypeParmPackType::getFinal() const {
3944 return AssociatedDeclAndFinal
.getInt();
3947 const TemplateTypeParmDecl
*
3948 SubstTemplateTypeParmPackType::getReplacedParameter() const {
3949 return ::getReplacedParameter(getAssociatedDecl(), getIndex());
3952 IdentifierInfo
*SubstTemplateTypeParmPackType::getIdentifier() const {
3953 return getReplacedParameter()->getIdentifier();
3956 TemplateArgument
SubstTemplateTypeParmPackType::getArgumentPack() const {
3957 return TemplateArgument(llvm::ArrayRef(Arguments
, getNumArgs()));
3960 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID
&ID
) {
3961 Profile(ID
, getAssociatedDecl(), getIndex(), getFinal(), getArgumentPack());
3964 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID
&ID
,
3965 const Decl
*AssociatedDecl
,
3966 unsigned Index
, bool Final
,
3967 const TemplateArgument
&ArgPack
) {
3968 ID
.AddPointer(AssociatedDecl
);
3969 ID
.AddInteger(Index
);
3970 ID
.AddBoolean(Final
);
3971 ID
.AddInteger(ArgPack
.pack_size());
3972 for (const auto &P
: ArgPack
.pack_elements())
3973 ID
.AddPointer(P
.getAsType().getAsOpaquePtr());
3976 bool TemplateSpecializationType::anyDependentTemplateArguments(
3977 const TemplateArgumentListInfo
&Args
, ArrayRef
<TemplateArgument
> Converted
) {
3978 return anyDependentTemplateArguments(Args
.arguments(), Converted
);
3981 bool TemplateSpecializationType::anyDependentTemplateArguments(
3982 ArrayRef
<TemplateArgumentLoc
> Args
, ArrayRef
<TemplateArgument
> Converted
) {
3983 for (const TemplateArgument
&Arg
: Converted
)
3984 if (Arg
.isDependent())
3989 bool TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
3990 ArrayRef
<TemplateArgumentLoc
> Args
) {
3991 for (const TemplateArgumentLoc
&ArgLoc
: Args
) {
3992 if (ArgLoc
.getArgument().isInstantiationDependent())
3998 TemplateSpecializationType::TemplateSpecializationType(
3999 TemplateName T
, ArrayRef
<TemplateArgument
> Args
, QualType Canon
,
4000 QualType AliasedType
)
4001 : Type(TemplateSpecialization
, Canon
.isNull() ? QualType(this, 0) : Canon
,
4003 ? TypeDependence::DependentInstantiation
4004 : toSemanticDependence(Canon
->getDependence())) |
4005 (toTypeDependence(T
.getDependence()) &
4006 TypeDependence::UnexpandedPack
)),
4008 TemplateSpecializationTypeBits
.NumArgs
= Args
.size();
4009 TemplateSpecializationTypeBits
.TypeAlias
= !AliasedType
.isNull();
4011 assert(!T
.getAsDependentTemplateName() &&
4012 "Use DependentTemplateSpecializationType for dependent template-name");
4013 assert((T
.getKind() == TemplateName::Template
||
4014 T
.getKind() == TemplateName::SubstTemplateTemplateParm
||
4015 T
.getKind() == TemplateName::SubstTemplateTemplateParmPack
||
4016 T
.getKind() == TemplateName::UsingTemplate
) &&
4017 "Unexpected template name for TemplateSpecializationType");
4019 auto *TemplateArgs
= reinterpret_cast<TemplateArgument
*>(this + 1);
4020 for (const TemplateArgument
&Arg
: Args
) {
4021 // Update instantiation-dependent, variably-modified, and error bits.
4022 // If the canonical type exists and is non-dependent, the template
4023 // specialization type can be non-dependent even if one of the type
4024 // arguments is. Given:
4025 // template<typename T> using U = int;
4026 // U<T> is always non-dependent, irrespective of the type T.
4027 // However, U<Ts> contains an unexpanded parameter pack, even though
4028 // its expansion (and thus its desugared type) doesn't.
4029 addDependence(toTypeDependence(Arg
.getDependence()) &
4030 ~TypeDependence::Dependent
);
4031 if (Arg
.getKind() == TemplateArgument::Type
)
4032 addDependence(Arg
.getAsType()->getDependence() &
4033 TypeDependence::VariablyModified
);
4034 new (TemplateArgs
++) TemplateArgument(Arg
);
4037 // Store the aliased type if this is a type alias template specialization.
4038 if (isTypeAlias()) {
4039 auto *Begin
= reinterpret_cast<TemplateArgument
*>(this + 1);
4040 *reinterpret_cast<QualType
*>(Begin
+ Args
.size()) = AliasedType
;
4044 QualType
TemplateSpecializationType::getAliasedType() const {
4045 assert(isTypeAlias() && "not a type alias template specialization");
4046 return *reinterpret_cast<const QualType
*>(template_arguments().end());
4049 void TemplateSpecializationType::Profile(llvm::FoldingSetNodeID
&ID
,
4050 const ASTContext
&Ctx
) {
4051 Profile(ID
, Template
, template_arguments(), Ctx
);
4053 getAliasedType().Profile(ID
);
4057 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID
&ID
,
4059 ArrayRef
<TemplateArgument
> Args
,
4060 const ASTContext
&Context
) {
4062 for (const TemplateArgument
&Arg
: Args
)
4063 Arg
.Profile(ID
, Context
);
4067 QualifierCollector::apply(const ASTContext
&Context
, QualType QT
) const {
4068 if (!hasNonFastQualifiers())
4069 return QT
.withFastQualifiers(getFastQualifiers());
4071 return Context
.getQualifiedType(QT
, *this);
4075 QualifierCollector::apply(const ASTContext
&Context
, const Type
*T
) const {
4076 if (!hasNonFastQualifiers())
4077 return QualType(T
, getFastQualifiers());
4079 return Context
.getQualifiedType(T
, *this);
4082 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID
&ID
,
4084 ArrayRef
<QualType
> typeArgs
,
4085 ArrayRef
<ObjCProtocolDecl
*> protocols
,
4087 ID
.AddPointer(BaseType
.getAsOpaquePtr());
4088 ID
.AddInteger(typeArgs
.size());
4089 for (auto typeArg
: typeArgs
)
4090 ID
.AddPointer(typeArg
.getAsOpaquePtr());
4091 ID
.AddInteger(protocols
.size());
4092 for (auto *proto
: protocols
)
4093 ID
.AddPointer(proto
);
4094 ID
.AddBoolean(isKindOf
);
4097 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID
&ID
) {
4098 Profile(ID
, getBaseType(), getTypeArgsAsWritten(),
4099 llvm::ArrayRef(qual_begin(), getNumProtocols()),
4100 isKindOfTypeAsWritten());
4103 void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID
&ID
,
4104 const ObjCTypeParamDecl
*OTPDecl
,
4105 QualType CanonicalType
,
4106 ArrayRef
<ObjCProtocolDecl
*> protocols
) {
4107 ID
.AddPointer(OTPDecl
);
4108 ID
.AddPointer(CanonicalType
.getAsOpaquePtr());
4109 ID
.AddInteger(protocols
.size());
4110 for (auto *proto
: protocols
)
4111 ID
.AddPointer(proto
);
4114 void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID
&ID
) {
4115 Profile(ID
, getDecl(), getCanonicalTypeInternal(),
4116 llvm::ArrayRef(qual_begin(), getNumProtocols()));
4121 /// The cached properties of a type.
4122 class CachedProperties
{
4127 CachedProperties(Linkage L
, bool local
) : L(L
), local(local
) {}
4129 Linkage
getLinkage() const { return L
; }
4130 bool hasLocalOrUnnamedType() const { return local
; }
4132 friend CachedProperties
merge(CachedProperties L
, CachedProperties R
) {
4133 Linkage MergedLinkage
= minLinkage(L
.L
, R
.L
);
4134 return CachedProperties(MergedLinkage
, L
.hasLocalOrUnnamedType() ||
4135 R
.hasLocalOrUnnamedType());
4141 static CachedProperties
computeCachedProperties(const Type
*T
);
4145 /// The type-property cache. This is templated so as to be
4146 /// instantiated at an internal type to prevent unnecessary symbol
4148 template <class Private
> class TypePropertyCache
{
4150 static CachedProperties
get(QualType T
) {
4151 return get(T
.getTypePtr());
4154 static CachedProperties
get(const Type
*T
) {
4156 return CachedProperties(T
->TypeBits
.getLinkage(),
4157 T
->TypeBits
.hasLocalOrUnnamedType());
4160 static void ensure(const Type
*T
) {
4161 // If the cache is valid, we're okay.
4162 if (T
->TypeBits
.isCacheValid()) return;
4164 // If this type is non-canonical, ask its canonical type for the
4165 // relevant information.
4166 if (!T
->isCanonicalUnqualified()) {
4167 const Type
*CT
= T
->getCanonicalTypeInternal().getTypePtr();
4169 T
->TypeBits
.CacheValid
= true;
4170 T
->TypeBits
.CachedLinkage
= CT
->TypeBits
.CachedLinkage
;
4171 T
->TypeBits
.CachedLocalOrUnnamed
= CT
->TypeBits
.CachedLocalOrUnnamed
;
4175 // Compute the cached properties and then set the cache.
4176 CachedProperties Result
= computeCachedProperties(T
);
4177 T
->TypeBits
.CacheValid
= true;
4178 T
->TypeBits
.CachedLinkage
= Result
.getLinkage();
4179 T
->TypeBits
.CachedLocalOrUnnamed
= Result
.hasLocalOrUnnamedType();
4183 } // namespace clang
4185 // Instantiate the friend template at a private class. In a
4186 // reasonable implementation, these symbols will be internal.
4187 // It is terrible that this is the best way to accomplish this.
4194 using Cache
= TypePropertyCache
<Private
>;
4196 static CachedProperties
computeCachedProperties(const Type
*T
) {
4197 switch (T
->getTypeClass()) {
4198 #define TYPE(Class,Base)
4199 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
4200 #include "clang/AST/TypeNodes.inc"
4201 llvm_unreachable("didn't expect a non-canonical type here");
4203 #define TYPE(Class,Base)
4204 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
4205 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
4206 #include "clang/AST/TypeNodes.inc"
4207 // Treat instantiation-dependent types as external.
4208 if (!T
->isInstantiationDependentType()) T
->dump();
4209 assert(T
->isInstantiationDependentType());
4210 return CachedProperties(ExternalLinkage
, false);
4213 case Type::DeducedTemplateSpecialization
:
4214 // Give non-deduced 'auto' types external linkage. We should only see them
4215 // here in error recovery.
4216 return CachedProperties(ExternalLinkage
, false);
4220 // C++ [basic.link]p8:
4221 // A type is said to have linkage if and only if:
4222 // - it is a fundamental type (3.9.1); or
4223 return CachedProperties(ExternalLinkage
, false);
4227 const TagDecl
*Tag
= cast
<TagType
>(T
)->getDecl();
4229 // C++ [basic.link]p8:
4230 // - it is a class or enumeration type that is named (or has a name
4231 // for linkage purposes (7.1.3)) and the name has linkage; or
4232 // - it is a specialization of a class template (14); or
4233 Linkage L
= Tag
->getLinkageInternal();
4234 bool IsLocalOrUnnamed
=
4235 Tag
->getDeclContext()->isFunctionOrMethod() ||
4236 !Tag
->hasNameForLinkage();
4237 return CachedProperties(L
, IsLocalOrUnnamed
);
4240 // C++ [basic.link]p8:
4241 // - it is a compound type (3.9.2) other than a class or enumeration,
4242 // compounded exclusively from types that have linkage; or
4244 return Cache::get(cast
<ComplexType
>(T
)->getElementType());
4246 return Cache::get(cast
<PointerType
>(T
)->getPointeeType());
4247 case Type::BlockPointer
:
4248 return Cache::get(cast
<BlockPointerType
>(T
)->getPointeeType());
4249 case Type::LValueReference
:
4250 case Type::RValueReference
:
4251 return Cache::get(cast
<ReferenceType
>(T
)->getPointeeType());
4252 case Type::MemberPointer
: {
4253 const auto *MPT
= cast
<MemberPointerType
>(T
);
4254 return merge(Cache::get(MPT
->getClass()),
4255 Cache::get(MPT
->getPointeeType()));
4257 case Type::ConstantArray
:
4258 case Type::IncompleteArray
:
4259 case Type::VariableArray
:
4260 return Cache::get(cast
<ArrayType
>(T
)->getElementType());
4262 case Type::ExtVector
:
4263 return Cache::get(cast
<VectorType
>(T
)->getElementType());
4264 case Type::ConstantMatrix
:
4265 return Cache::get(cast
<ConstantMatrixType
>(T
)->getElementType());
4266 case Type::FunctionNoProto
:
4267 return Cache::get(cast
<FunctionType
>(T
)->getReturnType());
4268 case Type::FunctionProto
: {
4269 const auto *FPT
= cast
<FunctionProtoType
>(T
);
4270 CachedProperties result
= Cache::get(FPT
->getReturnType());
4271 for (const auto &ai
: FPT
->param_types())
4272 result
= merge(result
, Cache::get(ai
));
4275 case Type::ObjCInterface
: {
4276 Linkage L
= cast
<ObjCInterfaceType
>(T
)->getDecl()->getLinkageInternal();
4277 return CachedProperties(L
, false);
4279 case Type::ObjCObject
:
4280 return Cache::get(cast
<ObjCObjectType
>(T
)->getBaseType());
4281 case Type::ObjCObjectPointer
:
4282 return Cache::get(cast
<ObjCObjectPointerType
>(T
)->getPointeeType());
4284 return Cache::get(cast
<AtomicType
>(T
)->getValueType());
4286 return Cache::get(cast
<PipeType
>(T
)->getElementType());
4289 llvm_unreachable("unhandled type class");
4292 /// Determine the linkage of this type.
4293 Linkage
Type::getLinkage() const {
4294 Cache::ensure(this);
4295 return TypeBits
.getLinkage();
4298 bool Type::hasUnnamedOrLocalType() const {
4299 Cache::ensure(this);
4300 return TypeBits
.hasLocalOrUnnamedType();
4303 LinkageInfo
LinkageComputer::computeTypeLinkageInfo(const Type
*T
) {
4304 switch (T
->getTypeClass()) {
4305 #define TYPE(Class,Base)
4306 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
4307 #include "clang/AST/TypeNodes.inc"
4308 llvm_unreachable("didn't expect a non-canonical type here");
4310 #define TYPE(Class,Base)
4311 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
4312 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
4313 #include "clang/AST/TypeNodes.inc"
4314 // Treat instantiation-dependent types as external.
4315 assert(T
->isInstantiationDependentType());
4316 return LinkageInfo::external();
4320 return LinkageInfo::external();
4323 case Type::DeducedTemplateSpecialization
:
4324 return LinkageInfo::external();
4328 return getDeclLinkageAndVisibility(cast
<TagType
>(T
)->getDecl());
4331 return computeTypeLinkageInfo(cast
<ComplexType
>(T
)->getElementType());
4333 return computeTypeLinkageInfo(cast
<PointerType
>(T
)->getPointeeType());
4334 case Type::BlockPointer
:
4335 return computeTypeLinkageInfo(cast
<BlockPointerType
>(T
)->getPointeeType());
4336 case Type::LValueReference
:
4337 case Type::RValueReference
:
4338 return computeTypeLinkageInfo(cast
<ReferenceType
>(T
)->getPointeeType());
4339 case Type::MemberPointer
: {
4340 const auto *MPT
= cast
<MemberPointerType
>(T
);
4341 LinkageInfo LV
= computeTypeLinkageInfo(MPT
->getClass());
4342 LV
.merge(computeTypeLinkageInfo(MPT
->getPointeeType()));
4345 case Type::ConstantArray
:
4346 case Type::IncompleteArray
:
4347 case Type::VariableArray
:
4348 return computeTypeLinkageInfo(cast
<ArrayType
>(T
)->getElementType());
4350 case Type::ExtVector
:
4351 return computeTypeLinkageInfo(cast
<VectorType
>(T
)->getElementType());
4352 case Type::ConstantMatrix
:
4353 return computeTypeLinkageInfo(
4354 cast
<ConstantMatrixType
>(T
)->getElementType());
4355 case Type::FunctionNoProto
:
4356 return computeTypeLinkageInfo(cast
<FunctionType
>(T
)->getReturnType());
4357 case Type::FunctionProto
: {
4358 const auto *FPT
= cast
<FunctionProtoType
>(T
);
4359 LinkageInfo LV
= computeTypeLinkageInfo(FPT
->getReturnType());
4360 for (const auto &ai
: FPT
->param_types())
4361 LV
.merge(computeTypeLinkageInfo(ai
));
4364 case Type::ObjCInterface
:
4365 return getDeclLinkageAndVisibility(cast
<ObjCInterfaceType
>(T
)->getDecl());
4366 case Type::ObjCObject
:
4367 return computeTypeLinkageInfo(cast
<ObjCObjectType
>(T
)->getBaseType());
4368 case Type::ObjCObjectPointer
:
4369 return computeTypeLinkageInfo(
4370 cast
<ObjCObjectPointerType
>(T
)->getPointeeType());
4372 return computeTypeLinkageInfo(cast
<AtomicType
>(T
)->getValueType());
4374 return computeTypeLinkageInfo(cast
<PipeType
>(T
)->getElementType());
4377 llvm_unreachable("unhandled type class");
4380 bool Type::isLinkageValid() const {
4381 if (!TypeBits
.isCacheValid())
4384 Linkage L
= LinkageComputer
{}
4385 .computeTypeLinkageInfo(getCanonicalTypeInternal())
4387 return L
== TypeBits
.getLinkage();
4390 LinkageInfo
LinkageComputer::getTypeLinkageAndVisibility(const Type
*T
) {
4391 if (!T
->isCanonicalUnqualified())
4392 return computeTypeLinkageInfo(T
->getCanonicalTypeInternal());
4394 LinkageInfo LV
= computeTypeLinkageInfo(T
);
4395 assert(LV
.getLinkage() == T
->getLinkage());
4399 LinkageInfo
Type::getLinkageAndVisibility() const {
4400 return LinkageComputer
{}.getTypeLinkageAndVisibility(this);
4403 std::optional
<NullabilityKind
> Type::getNullability() const {
4404 QualType
Type(this, 0);
4405 while (const auto *AT
= Type
->getAs
<AttributedType
>()) {
4406 // Check whether this is an attributed type with nullability
4408 if (auto Nullability
= AT
->getImmediateNullability())
4411 Type
= AT
->getEquivalentType();
4413 return std::nullopt
;
4416 bool Type::canHaveNullability(bool ResultIfUnknown
) const {
4417 QualType type
= getCanonicalTypeInternal();
4419 switch (type
->getTypeClass()) {
4420 // We'll only see canonical types here.
4421 #define NON_CANONICAL_TYPE(Class, Parent) \
4423 llvm_unreachable("non-canonical type");
4424 #define TYPE(Class, Parent)
4425 #include "clang/AST/TypeNodes.inc"
4429 case Type::BlockPointer
:
4430 case Type::MemberPointer
:
4431 case Type::ObjCObjectPointer
:
4434 // Dependent types that could instantiate to pointer types.
4435 case Type::UnresolvedUsing
:
4436 case Type::TypeOfExpr
:
4438 case Type::Decltype
:
4439 case Type::UnaryTransform
:
4440 case Type::TemplateTypeParm
:
4441 case Type::SubstTemplateTypeParmPack
:
4442 case Type::DependentName
:
4443 case Type::DependentTemplateSpecialization
:
4445 return ResultIfUnknown
;
4447 // Dependent template specializations can instantiate to pointer
4448 // types unless they're known to be specializations of a class
4450 case Type::TemplateSpecialization
:
4451 if (TemplateDecl
*templateDecl
4452 = cast
<TemplateSpecializationType
>(type
.getTypePtr())
4453 ->getTemplateName().getAsTemplateDecl()) {
4454 if (isa
<ClassTemplateDecl
>(templateDecl
))
4457 return ResultIfUnknown
;
4460 switch (cast
<BuiltinType
>(type
.getTypePtr())->getKind()) {
4461 // Signed, unsigned, and floating-point types cannot have nullability.
4462 #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
4463 #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
4464 #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
4465 #define BUILTIN_TYPE(Id, SingletonId)
4466 #include "clang/AST/BuiltinTypes.def"
4469 // Dependent types that could instantiate to a pointer type.
4470 case BuiltinType::Dependent
:
4471 case BuiltinType::Overload
:
4472 case BuiltinType::BoundMember
:
4473 case BuiltinType::PseudoObject
:
4474 case BuiltinType::UnknownAny
:
4475 case BuiltinType::ARCUnbridgedCast
:
4476 return ResultIfUnknown
;
4478 case BuiltinType::Void
:
4479 case BuiltinType::ObjCId
:
4480 case BuiltinType::ObjCClass
:
4481 case BuiltinType::ObjCSel
:
4482 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
4483 case BuiltinType::Id:
4484 #include "clang/Basic/OpenCLImageTypes.def"
4485 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
4486 case BuiltinType::Id:
4487 #include "clang/Basic/OpenCLExtensionTypes.def"
4488 case BuiltinType::OCLSampler
:
4489 case BuiltinType::OCLEvent
:
4490 case BuiltinType::OCLClkEvent
:
4491 case BuiltinType::OCLQueue
:
4492 case BuiltinType::OCLReserveID
:
4493 #define SVE_TYPE(Name, Id, SingletonId) \
4494 case BuiltinType::Id:
4495 #include "clang/Basic/AArch64SVEACLETypes.def"
4496 #define PPC_VECTOR_TYPE(Name, Id, Size) \
4497 case BuiltinType::Id:
4498 #include "clang/Basic/PPCTypes.def"
4499 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
4500 #include "clang/Basic/RISCVVTypes.def"
4501 #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
4502 #include "clang/Basic/WebAssemblyReferenceTypes.def"
4503 case BuiltinType::BuiltinFn
:
4504 case BuiltinType::NullPtr
:
4505 case BuiltinType::IncompleteMatrixIdx
:
4506 case BuiltinType::OMPArraySection
:
4507 case BuiltinType::OMPArrayShaping
:
4508 case BuiltinType::OMPIterator
:
4511 llvm_unreachable("unknown builtin type");
4513 // Non-pointer types.
4515 case Type::LValueReference
:
4516 case Type::RValueReference
:
4517 case Type::ConstantArray
:
4518 case Type::IncompleteArray
:
4519 case Type::VariableArray
:
4520 case Type::DependentSizedArray
:
4521 case Type::DependentVector
:
4522 case Type::DependentSizedExtVector
:
4524 case Type::ExtVector
:
4525 case Type::ConstantMatrix
:
4526 case Type::DependentSizedMatrix
:
4527 case Type::DependentAddressSpace
:
4528 case Type::FunctionProto
:
4529 case Type::FunctionNoProto
:
4531 case Type::DeducedTemplateSpecialization
:
4533 case Type::InjectedClassName
:
4534 case Type::PackExpansion
:
4535 case Type::ObjCObject
:
4536 case Type::ObjCInterface
:
4540 case Type::DependentBitInt
:
4543 llvm_unreachable("bad type kind!");
4546 std::optional
<NullabilityKind
> AttributedType::getImmediateNullability() const {
4547 if (getAttrKind() == attr::TypeNonNull
)
4548 return NullabilityKind::NonNull
;
4549 if (getAttrKind() == attr::TypeNullable
)
4550 return NullabilityKind::Nullable
;
4551 if (getAttrKind() == attr::TypeNullUnspecified
)
4552 return NullabilityKind::Unspecified
;
4553 if (getAttrKind() == attr::TypeNullableResult
)
4554 return NullabilityKind::NullableResult
;
4555 return std::nullopt
;
4558 std::optional
<NullabilityKind
>
4559 AttributedType::stripOuterNullability(QualType
&T
) {
4560 QualType AttrTy
= T
;
4561 if (auto MacroTy
= dyn_cast
<MacroQualifiedType
>(T
))
4562 AttrTy
= MacroTy
->getUnderlyingType();
4564 if (auto attributed
= dyn_cast
<AttributedType
>(AttrTy
)) {
4565 if (auto nullability
= attributed
->getImmediateNullability()) {
4566 T
= attributed
->getModifiedType();
4571 return std::nullopt
;
4574 bool Type::isBlockCompatibleObjCPointerType(ASTContext
&ctx
) const {
4575 const auto *objcPtr
= getAs
<ObjCObjectPointerType
>();
4579 if (objcPtr
->isObjCIdType()) {
4580 // id is always okay.
4584 // Blocks are NSObjects.
4585 if (ObjCInterfaceDecl
*iface
= objcPtr
->getInterfaceDecl()) {
4586 if (iface
->getIdentifier() != ctx
.getNSObjectName())
4589 // Continue to check qualifiers, below.
4590 } else if (objcPtr
->isObjCQualifiedIdType()) {
4591 // Continue to check qualifiers, below.
4596 // Check protocol qualifiers.
4597 for (ObjCProtocolDecl
*proto
: objcPtr
->quals()) {
4598 // Blocks conform to NSObject and NSCopying.
4599 if (proto
->getIdentifier() != ctx
.getNSObjectName() &&
4600 proto
->getIdentifier() != ctx
.getNSCopyingName())
4607 Qualifiers::ObjCLifetime
Type::getObjCARCImplicitLifetime() const {
4608 if (isObjCARCImplicitlyUnretainedType())
4609 return Qualifiers::OCL_ExplicitNone
;
4610 return Qualifiers::OCL_Strong
;
4613 bool Type::isObjCARCImplicitlyUnretainedType() const {
4614 assert(isObjCLifetimeType() &&
4615 "cannot query implicit lifetime for non-inferrable type");
4617 const Type
*canon
= getCanonicalTypeInternal().getTypePtr();
4619 // Walk down to the base type. We don't care about qualifiers for this.
4620 while (const auto *array
= dyn_cast
<ArrayType
>(canon
))
4621 canon
= array
->getElementType().getTypePtr();
4623 if (const auto *opt
= dyn_cast
<ObjCObjectPointerType
>(canon
)) {
4624 // Class and Class<Protocol> don't require retention.
4625 if (opt
->getObjectType()->isObjCClass())
4632 bool Type::isObjCNSObjectType() const {
4633 if (const auto *typedefType
= getAs
<TypedefType
>())
4634 return typedefType
->getDecl()->hasAttr
<ObjCNSObjectAttr
>();
4638 bool Type::isObjCIndependentClassType() const {
4639 if (const auto *typedefType
= getAs
<TypedefType
>())
4640 return typedefType
->getDecl()->hasAttr
<ObjCIndependentClassAttr
>();
4644 bool Type::isObjCRetainableType() const {
4645 return isObjCObjectPointerType() ||
4646 isBlockPointerType() ||
4647 isObjCNSObjectType();
4650 bool Type::isObjCIndirectLifetimeType() const {
4651 if (isObjCLifetimeType())
4653 if (const auto *OPT
= getAs
<PointerType
>())
4654 return OPT
->getPointeeType()->isObjCIndirectLifetimeType();
4655 if (const auto *Ref
= getAs
<ReferenceType
>())
4656 return Ref
->getPointeeType()->isObjCIndirectLifetimeType();
4657 if (const auto *MemPtr
= getAs
<MemberPointerType
>())
4658 return MemPtr
->getPointeeType()->isObjCIndirectLifetimeType();
4662 /// Returns true if objects of this type have lifetime semantics under
4664 bool Type::isObjCLifetimeType() const {
4665 const Type
*type
= this;
4666 while (const ArrayType
*array
= type
->getAsArrayTypeUnsafe())
4667 type
= array
->getElementType().getTypePtr();
4668 return type
->isObjCRetainableType();
4671 /// Determine whether the given type T is a "bridgable" Objective-C type,
4672 /// which is either an Objective-C object pointer type or an
4673 bool Type::isObjCARCBridgableType() const {
4674 return isObjCObjectPointerType() || isBlockPointerType();
4677 /// Determine whether the given type T is a "bridgeable" C type.
4678 bool Type::isCARCBridgableType() const {
4679 const auto *Pointer
= getAs
<PointerType
>();
4683 QualType Pointee
= Pointer
->getPointeeType();
4684 return Pointee
->isVoidType() || Pointee
->isRecordType();
4687 /// Check if the specified type is the CUDA device builtin surface type.
4688 bool Type::isCUDADeviceBuiltinSurfaceType() const {
4689 if (const auto *RT
= getAs
<RecordType
>())
4690 return RT
->getDecl()->hasAttr
<CUDADeviceBuiltinSurfaceTypeAttr
>();
4694 /// Check if the specified type is the CUDA device builtin texture type.
4695 bool Type::isCUDADeviceBuiltinTextureType() const {
4696 if (const auto *RT
= getAs
<RecordType
>())
4697 return RT
->getDecl()->hasAttr
<CUDADeviceBuiltinTextureTypeAttr
>();
4701 bool Type::hasSizedVLAType() const {
4702 if (!isVariablyModifiedType()) return false;
4704 if (const auto *ptr
= getAs
<PointerType
>())
4705 return ptr
->getPointeeType()->hasSizedVLAType();
4706 if (const auto *ref
= getAs
<ReferenceType
>())
4707 return ref
->getPointeeType()->hasSizedVLAType();
4708 if (const ArrayType
*arr
= getAsArrayTypeUnsafe()) {
4709 if (isa
<VariableArrayType
>(arr
) &&
4710 cast
<VariableArrayType
>(arr
)->getSizeExpr())
4713 return arr
->getElementType()->hasSizedVLAType();
4719 QualType::DestructionKind
QualType::isDestructedTypeImpl(QualType type
) {
4720 switch (type
.getObjCLifetime()) {
4721 case Qualifiers::OCL_None
:
4722 case Qualifiers::OCL_ExplicitNone
:
4723 case Qualifiers::OCL_Autoreleasing
:
4726 case Qualifiers::OCL_Strong
:
4727 return DK_objc_strong_lifetime
;
4728 case Qualifiers::OCL_Weak
:
4729 return DK_objc_weak_lifetime
;
4732 if (const auto *RT
=
4733 type
->getBaseElementTypeUnsafe()->getAs
<RecordType
>()) {
4734 const RecordDecl
*RD
= RT
->getDecl();
4735 if (const auto *CXXRD
= dyn_cast
<CXXRecordDecl
>(RD
)) {
4736 /// Check if this is a C++ object with a non-trivial destructor.
4737 if (CXXRD
->hasDefinition() && !CXXRD
->hasTrivialDestructor())
4738 return DK_cxx_destructor
;
4740 /// Check if this is a C struct that is non-trivial to destroy or an array
4741 /// that contains such a struct.
4742 if (RD
->isNonTrivialToPrimitiveDestroy())
4743 return DK_nontrivial_c_struct
;
4750 CXXRecordDecl
*MemberPointerType::getMostRecentCXXRecordDecl() const {
4751 return getClass()->getAsCXXRecordDecl()->getMostRecentNonInjectedDecl();
4754 void clang::FixedPointValueToString(SmallVectorImpl
<char> &Str
,
4755 llvm::APSInt Val
, unsigned Scale
) {
4756 llvm::FixedPointSemantics
FXSema(Val
.getBitWidth(), Scale
, Val
.isSigned(),
4757 /*IsSaturated=*/false,
4758 /*HasUnsignedPadding=*/false);
4759 llvm::APFixedPoint(Val
, FXSema
).toString(Str
);
4762 AutoType::AutoType(QualType DeducedAsType
, AutoTypeKeyword Keyword
,
4763 TypeDependence ExtraDependence
, QualType Canon
,
4764 ConceptDecl
*TypeConstraintConcept
,
4765 ArrayRef
<TemplateArgument
> TypeConstraintArgs
)
4766 : DeducedType(Auto
, DeducedAsType
, ExtraDependence
, Canon
) {
4767 AutoTypeBits
.Keyword
= llvm::to_underlying(Keyword
);
4768 AutoTypeBits
.NumArgs
= TypeConstraintArgs
.size();
4769 this->TypeConstraintConcept
= TypeConstraintConcept
;
4770 assert(TypeConstraintConcept
|| AutoTypeBits
.NumArgs
== 0);
4771 if (TypeConstraintConcept
) {
4773 const_cast<TemplateArgument
*>(getTypeConstraintArguments().data());
4774 for (const TemplateArgument
&Arg
: TypeConstraintArgs
) {
4775 // We only syntactically depend on the constraint arguments. They don't
4776 // affect the deduced type, only its validity.
4778 toSyntacticDependence(toTypeDependence(Arg
.getDependence())));
4780 new (ArgBuffer
++) TemplateArgument(Arg
);
4785 void AutoType::Profile(llvm::FoldingSetNodeID
&ID
, const ASTContext
&Context
,
4786 QualType Deduced
, AutoTypeKeyword Keyword
,
4787 bool IsDependent
, ConceptDecl
*CD
,
4788 ArrayRef
<TemplateArgument
> Arguments
) {
4789 ID
.AddPointer(Deduced
.getAsOpaquePtr());
4790 ID
.AddInteger((unsigned)Keyword
);
4791 ID
.AddBoolean(IsDependent
);
4793 for (const TemplateArgument
&Arg
: Arguments
)
4794 Arg
.Profile(ID
, Context
);
4797 void AutoType::Profile(llvm::FoldingSetNodeID
&ID
, const ASTContext
&Context
) {
4798 Profile(ID
, Context
, getDeducedType(), getKeyword(), isDependentType(),
4799 getTypeConstraintConcept(), getTypeConstraintArguments());