clang 18.0.0git
Type.cpp
Go to the documentation of this file.
1//===- Type.cpp - Type representation and manipulation --------------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements type-related functionality.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/Type.h"
14#include "Linkage.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"
22#include "clang/AST/DeclObjC.h"
25#include "clang/AST/Expr.h"
35#include "clang/Basic/LLVM.h"
37#include "clang/Basic/Linkage.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"
51#include <algorithm>
52#include <cassert>
53#include <cstdint>
54#include <cstring>
55#include <optional>
56#include <type_traits>
57
58using namespace clang;
59
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()));
73}
74
76 const Type* ty = getTypePtr();
77 NamedDecl *ND = nullptr;
78 if (ty->isPointerType() || ty->isReferenceType())
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();
89
90 if (ND)
91 return ND->getIdentifier();
92 return nullptr;
93}
94
96 const auto *ClassDecl = getTypePtr()->getPointeeCXXRecordDecl();
97 return ClassDecl && ClassDecl->mayBeDynamicClass();
98}
99
101 const auto *ClassDecl = getTypePtr()->getPointeeCXXRecordDecl();
102 return !ClassDecl || ClassDecl->mayBeNonDynamicClass();
103}
104
105bool QualType::isConstant(QualType T, const ASTContext &Ctx) {
106 if (T.isConstQualified())
107 return true;
108
109 if (const ArrayType *AT = Ctx.getAsArrayType(T))
110 return AT->getElementType().isConstant(Ctx);
111
113}
114
115std::optional<QualType::NonConstantStorageReason>
116QualType::isNonConstantStorage(const ASTContext &Ctx, bool ExcludeCtor,
117 bool ExcludeDtor) {
118 if (!isConstant(Ctx) && !(*this)->isReferenceType())
120 if (!Ctx.getLangOpts().CPlusPlus)
121 return std::nullopt;
122 if (const CXXRecordDecl *Record =
124 if (!ExcludeCtor)
126 if (Record->hasMutableFields())
128 if (!Record->hasTrivialDestructor() && !ExcludeDtor)
130 }
131 return std::nullopt;
132}
133
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
138// value-dependent,
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
144 // initializer:
145 //
146 // template<int ...N> int arr[] = {N...};
147 : Type(tc, can,
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)),
157 ElementType(et) {
158 ArrayTypeBits.IndexTypeQuals = tq;
159 ArrayTypeBits.SizeModifier = sm;
160}
161
163 QualType ElementType,
164 const llvm::APInt &NumElements) {
165 uint64_t ElementSize = Context.getTypeSizeInChars(ElementType).getQuantity();
166
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
169 // slow.
170
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);
175 }
176
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);
183 }
184
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);
190
191 llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize));
192 TotalSize *= SizeExtended;
193
194 return TotalSize.getActiveBits();
195}
196
197unsigned
199 return getNumAddressingBits(Context, getElementType(), getSize());
200}
201
203 unsigned Bits = Context.getTypeSize(Context.getSizeType());
204
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.
208 if (Bits > 61)
209 Bits = 61;
210
211 return Bits;
212}
213
214void 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(SizeMod);
222 ID.AddInteger(TypeQuals);
223 ID.AddBoolean(SizeExpr != nullptr);
224 if (SizeExpr)
225 SizeExpr->Profile(ID, Context, true);
226}
227
228DependentSizedArrayType::DependentSizedArrayType(const ASTContext &Context,
229 QualType et, QualType can,
230 Expr *e, ArraySizeModifier sm,
231 unsigned tq,
232 SourceRange brackets)
233 : ArrayType(DependentSizedArray, et, can, sm, tq, e),
234 Context(Context), SizeExpr((Stmt*) e), Brackets(brackets) {}
235
236void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID,
237 const ASTContext &Context,
238 QualType ET,
239 ArraySizeModifier SizeMod,
240 unsigned TypeQuals,
241 Expr *E) {
242 ID.AddPointer(ET.getAsOpaquePtr());
243 ID.AddInteger(SizeMod);
244 ID.AddInteger(TypeQuals);
245 E->Profile(ID, Context, true);
246}
247
248DependentVectorType::DependentVectorType(const ASTContext &Context,
249 QualType ElementType,
250 QualType CanonType, Expr *SizeExpr,
251 SourceLocation Loc,
253 : Type(DependentVector, CanonType,
254 TypeDependence::DependentInstantiation |
255 ElementType->getDependence() |
256 (SizeExpr ? toTypeDependence(SizeExpr->getDependence())
257 : TypeDependence::None)),
258 Context(Context), ElementType(ElementType), SizeExpr(SizeExpr), Loc(Loc) {
259 VectorTypeBits.VecKind = VecKind;
260}
261
262void DependentVectorType::Profile(llvm::FoldingSetNodeID &ID,
263 const ASTContext &Context,
264 QualType ElementType, const Expr *SizeExpr,
265 VectorType::VectorKind VecKind) {
266 ID.AddPointer(ElementType.getAsOpaquePtr());
267 ID.AddInteger(VecKind);
268 SizeExpr->Profile(ID, Context, true);
269}
270
271DependentSizedExtVectorType::DependentSizedExtVectorType(
272 const ASTContext &Context, QualType ElementType, QualType can,
273 Expr *SizeExpr, SourceLocation loc)
274 : Type(DependentSizedExtVector, can,
275 TypeDependence::DependentInstantiation |
276 ElementType->getDependence() |
277 (SizeExpr ? toTypeDependence(SizeExpr->getDependence())
278 : TypeDependence::None)),
279 Context(Context), SizeExpr(SizeExpr), ElementType(ElementType), loc(loc) {
280}
281
282void
283DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID,
284 const ASTContext &Context,
285 QualType ElementType, Expr *SizeExpr) {
286 ID.AddPointer(ElementType.getAsOpaquePtr());
287 SizeExpr->Profile(ID, Context, true);
288}
289
290DependentAddressSpaceType::DependentAddressSpaceType(const ASTContext &Context,
291 QualType PointeeType,
292 QualType can,
293 Expr *AddrSpaceExpr,
294 SourceLocation loc)
295 : Type(DependentAddressSpace, can,
296 TypeDependence::DependentInstantiation |
297 PointeeType->getDependence() |
298 (AddrSpaceExpr ? toTypeDependence(AddrSpaceExpr->getDependence())
299 : TypeDependence::None)),
300 Context(Context), AddrSpaceExpr(AddrSpaceExpr), PointeeType(PointeeType),
301 loc(loc) {}
302
303void DependentAddressSpaceType::Profile(llvm::FoldingSetNodeID &ID,
304 const ASTContext &Context,
305 QualType PointeeType,
306 Expr *AddrSpaceExpr) {
307 ID.AddPointer(PointeeType.getAsOpaquePtr());
308 AddrSpaceExpr->Profile(ID, Context, true);
309}
310
312 const Expr *RowExpr, const Expr *ColumnExpr)
313 : Type(tc, canonType,
314 (RowExpr ? (matrixType->getDependence() | TypeDependence::Dependent |
315 TypeDependence::Instantiation |
316 (matrixType->isVariablyModifiedType()
317 ? TypeDependence::VariablyModified
318 : TypeDependence::None) |
319 (matrixType->containsUnexpandedParameterPack() ||
320 (RowExpr &&
321 RowExpr->containsUnexpandedParameterPack()) ||
322 (ColumnExpr &&
323 ColumnExpr->containsUnexpandedParameterPack())
324 ? TypeDependence::UnexpandedPack
326 : matrixType->getDependence())),
327 ElementType(matrixType) {}
328
330 unsigned nColumns, QualType canonType)
331 : ConstantMatrixType(ConstantMatrix, matrixType, nRows, nColumns,
332 canonType) {}
333
335 unsigned nRows, unsigned nColumns,
336 QualType canonType)
337 : MatrixType(tc, matrixType, canonType), NumRows(nRows),
338 NumColumns(nColumns) {}
339
340DependentSizedMatrixType::DependentSizedMatrixType(
341 const ASTContext &CTX, QualType ElementType, QualType CanonicalType,
342 Expr *RowExpr, Expr *ColumnExpr, SourceLocation loc)
343 : MatrixType(DependentSizedMatrix, ElementType, CanonicalType, RowExpr,
344 ColumnExpr),
345 Context(CTX), RowExpr(RowExpr), ColumnExpr(ColumnExpr), loc(loc) {}
346
347void DependentSizedMatrixType::Profile(llvm::FoldingSetNodeID &ID,
348 const ASTContext &CTX,
349 QualType ElementType, Expr *RowExpr,
350 Expr *ColumnExpr) {
351 ID.AddPointer(ElementType.getAsOpaquePtr());
352 RowExpr->Profile(ID, CTX, true);
353 ColumnExpr->Profile(ID, CTX, true);
354}
355
356VectorType::VectorType(QualType vecType, unsigned nElements, QualType canonType,
357 VectorKind vecKind)
358 : VectorType(Vector, vecType, nElements, canonType, vecKind) {}
359
360VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements,
361 QualType canonType, VectorKind vecKind)
362 : Type(tc, canonType, vecType->getDependence()), ElementType(vecType) {
363 VectorTypeBits.VecKind = vecKind;
364 VectorTypeBits.NumElements = nElements;
365}
366
367BitIntType::BitIntType(bool IsUnsigned, unsigned NumBits)
368 : Type(BitInt, QualType{}, TypeDependence::None), IsUnsigned(IsUnsigned),
369 NumBits(NumBits) {}
370
372 bool IsUnsigned, Expr *NumBitsExpr)
373 : Type(DependentBitInt, QualType{},
374 toTypeDependence(NumBitsExpr->getDependence())),
375 Context(Context), ExprAndUnsigned(NumBitsExpr, IsUnsigned) {}
376
378 return ExprAndUnsigned.getInt();
379}
380
382 return ExprAndUnsigned.getPointer();
383}
384
385void DependentBitIntType::Profile(llvm::FoldingSetNodeID &ID,
386 const ASTContext &Context, bool IsUnsigned,
387 Expr *NumBitsExpr) {
388 ID.AddBoolean(IsUnsigned);
389 NumBitsExpr->Profile(ID, Context, true);
390}
391
392/// getArrayElementTypeNoTypeQual - If this is an array type, return the
393/// element type of the array, potentially with type qualifiers missing.
394/// This method should never be used when type qualifiers are meaningful.
396 // If this is directly an array type, return it.
397 if (const auto *ATy = dyn_cast<ArrayType>(this))
398 return ATy->getElementType().getTypePtr();
399
400 // If the canonical form of this type isn't the right kind, reject it.
401 if (!isa<ArrayType>(CanonicalType))
402 return nullptr;
403
404 // If this is a typedef for an array type, strip the typedef off without
405 // losing all typedef information.
406 return cast<ArrayType>(getUnqualifiedDesugaredType())
407 ->getElementType().getTypePtr();
408}
409
410/// getDesugaredType - Return the specified type with any "sugar" removed from
411/// the type. This takes off typedefs, typeof's etc. If the outer level of
412/// the type is already concrete, it returns it unmodified. This is similar
413/// to getting the canonical type, but it doesn't remove *all* typedefs. For
414/// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
415/// concrete.
418 return Context.getQualifiedType(split.Ty, split.Quals);
419}
420
421QualType QualType::getSingleStepDesugaredTypeImpl(QualType type,
422 const ASTContext &Context) {
423 SplitQualType split = type.split();
425 return Context.getQualifiedType(desugar, split.Quals);
426}
427
428// Check that no type class is polymorphic. LLVM style RTTI should be used
429// instead. If absolutely needed an exception can still be added here by
430// defining the appropriate macro (but please don't do this).
431#define TYPE(CLASS, BASE) \
432 static_assert(!std::is_polymorphic<CLASS##Type>::value, \
433 #CLASS "Type should not be polymorphic!");
434#include "clang/AST/TypeNodes.inc"
435
436// Check that no type class has a non-trival destructor. Types are
437// allocated with the BumpPtrAllocator from ASTContext and therefore
438// their destructor is not executed.
439//
440// FIXME: ConstantArrayType is not trivially destructible because of its
441// APInt member. It should be replaced in favor of ASTContext allocation.
442#define TYPE(CLASS, BASE) \
443 static_assert(std::is_trivially_destructible<CLASS##Type>::value || \
444 std::is_same<CLASS##Type, ConstantArrayType>::value, \
445 #CLASS "Type should be trivially destructible!");
446#include "clang/AST/TypeNodes.inc"
447
449 switch (getTypeClass()) {
450#define ABSTRACT_TYPE(Class, Parent)
451#define TYPE(Class, Parent) \
452 case Type::Class: { \
453 const auto *ty = cast<Class##Type>(this); \
454 if (!ty->isSugared()) return QualType(ty, 0); \
455 return ty->desugar(); \
456 }
457#include "clang/AST/TypeNodes.inc"
458 }
459 llvm_unreachable("bad type kind!");
460}
461
464
465 QualType Cur = T;
466 while (true) {
467 const Type *CurTy = Qs.strip(Cur);
468 switch (CurTy->getTypeClass()) {
469#define ABSTRACT_TYPE(Class, Parent)
470#define TYPE(Class, Parent) \
471 case Type::Class: { \
472 const auto *Ty = cast<Class##Type>(CurTy); \
473 if (!Ty->isSugared()) \
474 return SplitQualType(Ty, Qs); \
475 Cur = Ty->desugar(); \
476 break; \
477 }
478#include "clang/AST/TypeNodes.inc"
479 }
480 }
481}
482
483SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) {
484 SplitQualType split = type.split();
485
486 // All the qualifiers we've seen so far.
487 Qualifiers quals = split.Quals;
488
489 // The last type node we saw with any nodes inside it.
490 const Type *lastTypeWithQuals = split.Ty;
491
492 while (true) {
493 QualType next;
494
495 // Do a single-step desugar, aborting the loop if the type isn't
496 // sugared.
497 switch (split.Ty->getTypeClass()) {
498#define ABSTRACT_TYPE(Class, Parent)
499#define TYPE(Class, Parent) \
500 case Type::Class: { \
501 const auto *ty = cast<Class##Type>(split.Ty); \
502 if (!ty->isSugared()) goto done; \
503 next = ty->desugar(); \
504 break; \
505 }
506#include "clang/AST/TypeNodes.inc"
507 }
508
509 // Otherwise, split the underlying type. If that yields qualifiers,
510 // update the information.
511 split = next.split();
512 if (!split.Quals.empty()) {
513 lastTypeWithQuals = split.Ty;
515 }
516 }
517
518 done:
519 return SplitQualType(lastTypeWithQuals, quals);
520}
521
523 // FIXME: this seems inherently un-qualifiers-safe.
524 while (const auto *PT = T->getAs<ParenType>())
525 T = PT->getInnerType();
526 return T;
527}
528
529/// This will check for a T (which should be a Type which can act as
530/// sugar, such as a TypedefType) by removing any existing sugar until it
531/// reaches a T or a non-sugared type.
532template<typename T> static const T *getAsSugar(const Type *Cur) {
533 while (true) {
534 if (const auto *Sugar = dyn_cast<T>(Cur))
535 return Sugar;
536 switch (Cur->getTypeClass()) {
537#define ABSTRACT_TYPE(Class, Parent)
538#define TYPE(Class, Parent) \
539 case Type::Class: { \
540 const auto *Ty = cast<Class##Type>(Cur); \
541 if (!Ty->isSugared()) return 0; \
542 Cur = Ty->desugar().getTypePtr(); \
543 break; \
544 }
545#include "clang/AST/TypeNodes.inc"
546 }
547 }
548}
549
550template <> const TypedefType *Type::getAs() const {
551 return getAsSugar<TypedefType>(this);
552}
553
554template <> const UsingType *Type::getAs() const {
555 return getAsSugar<UsingType>(this);
556}
557
558template <> const TemplateSpecializationType *Type::getAs() const {
559 return getAsSugar<TemplateSpecializationType>(this);
560}
561
562template <> const AttributedType *Type::getAs() const {
563 return getAsSugar<AttributedType>(this);
564}
565
566/// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
567/// sugar off the given type. This should produce an object of the
568/// same dynamic type as the canonical type.
570 const Type *Cur = this;
571
572 while (true) {
573 switch (Cur->getTypeClass()) {
574#define ABSTRACT_TYPE(Class, Parent)
575#define TYPE(Class, Parent) \
576 case Class: { \
577 const auto *Ty = cast<Class##Type>(Cur); \
578 if (!Ty->isSugared()) return Cur; \
579 Cur = Ty->desugar().getTypePtr(); \
580 break; \
581 }
582#include "clang/AST/TypeNodes.inc"
583 }
584 }
585}
586
587bool Type::isClassType() const {
588 if (const auto *RT = getAs<RecordType>())
589 return RT->getDecl()->isClass();
590 return false;
591}
592
594 if (const auto *RT = getAs<RecordType>())
595 return RT->getDecl()->isStruct();
596 return false;
597}
598
600 if (const auto *RT = getAs<RecordType>())
601 return RT->getDecl()->hasAttr<ObjCBoxableAttr>();
602 return false;
603}
604
606 if (const auto *RT = getAs<RecordType>())
607 return RT->getDecl()->isInterface();
608 return false;
609}
610
612 if (const auto *RT = getAs<RecordType>()) {
613 RecordDecl *RD = RT->getDecl();
614 return RD->isStruct() || RD->isClass() || RD->isInterface();
615 }
616 return false;
617}
618
620 if (const auto *PT = getAs<PointerType>())
621 return PT->getPointeeType()->isVoidType();
622 return false;
623}
624
625bool Type::isUnionType() const {
626 if (const auto *RT = getAs<RecordType>())
627 return RT->getDecl()->isUnion();
628 return false;
629}
630
632 if (const auto *CT = dyn_cast<ComplexType>(CanonicalType))
633 return CT->getElementType()->isFloatingType();
634 return false;
635}
636
638 // Check for GCC complex integer extension.
640}
641
643 if (const auto *ET = getAs<EnumType>())
644 return ET->getDecl()->isScoped();
645 return false;
646}
647
649 if (const auto *Complex = getAs<ComplexType>())
650 if (Complex->getElementType()->isIntegerType())
651 return Complex;
652 return nullptr;
653}
654
656 if (const auto *PT = getAs<PointerType>())
657 return PT->getPointeeType();
658 if (const auto *OPT = getAs<ObjCObjectPointerType>())
659 return OPT->getPointeeType();
660 if (const auto *BPT = getAs<BlockPointerType>())
661 return BPT->getPointeeType();
662 if (const auto *RT = getAs<ReferenceType>())
663 return RT->getPointeeType();
664 if (const auto *MPT = getAs<MemberPointerType>())
665 return MPT->getPointeeType();
666 if (const auto *DT = getAs<DecayedType>())
667 return DT->getPointeeType();
668 return {};
669}
670
672 // If this is directly a structure type, return it.
673 if (const auto *RT = dyn_cast<RecordType>(this)) {
674 if (RT->getDecl()->isStruct())
675 return RT;
676 }
677
678 // If the canonical form of this type isn't the right kind, reject it.
679 if (const auto *RT = dyn_cast<RecordType>(CanonicalType)) {
680 if (!RT->getDecl()->isStruct())
681 return nullptr;
682
683 // If this is a typedef for a structure type, strip the typedef off without
684 // losing all typedef information.
685 return cast<RecordType>(getUnqualifiedDesugaredType());
686 }
687 return nullptr;
688}
689
691 // If this is directly a union type, return it.
692 if (const auto *RT = dyn_cast<RecordType>(this)) {
693 if (RT->getDecl()->isUnion())
694 return RT;
695 }
696
697 // If the canonical form of this type isn't the right kind, reject it.
698 if (const auto *RT = dyn_cast<RecordType>(CanonicalType)) {
699 if (!RT->getDecl()->isUnion())
700 return nullptr;
701
702 // If this is a typedef for a union type, strip the typedef off without
703 // losing all typedef information.
704 return cast<RecordType>(getUnqualifiedDesugaredType());
705 }
706
707 return nullptr;
708}
709
711 const ObjCObjectType *&bound) const {
712 bound = nullptr;
713
714 const auto *OPT = getAs<ObjCObjectPointerType>();
715 if (!OPT)
716 return false;
717
718 // Easy case: id.
719 if (OPT->isObjCIdType())
720 return true;
721
722 // If it's not a __kindof type, reject it now.
723 if (!OPT->isKindOfType())
724 return false;
725
726 // If it's Class or qualified Class, it's not an object type.
727 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType())
728 return false;
729
730 // Figure out the type bound for the __kindof type.
731 bound = OPT->getObjectType()->stripObjCKindOfTypeAndQuals(ctx)
733 return true;
734}
735
737 const auto *OPT = getAs<ObjCObjectPointerType>();
738 if (!OPT)
739 return false;
740
741 // Easy case: Class.
742 if (OPT->isObjCClassType())
743 return true;
744
745 // If it's not a __kindof type, reject it now.
746 if (!OPT->isKindOfType())
747 return false;
748
749 // If it's Class or qualified Class, it's a class __kindof type.
750 return OPT->isObjCClassType() || OPT->isObjCQualifiedClassType();
751}
752
753ObjCTypeParamType::ObjCTypeParamType(const ObjCTypeParamDecl *D, QualType can,
755 : Type(ObjCTypeParam, can, toSemanticDependence(can->getDependence())),
756 OTPDecl(const_cast<ObjCTypeParamDecl *>(D)) {
757 initialize(protocols);
758}
759
761 ArrayRef<QualType> typeArgs,
763 bool isKindOf)
764 : Type(ObjCObject, Canonical, Base->getDependence()), BaseType(Base) {
765 ObjCObjectTypeBits.IsKindOf = isKindOf;
766
767 ObjCObjectTypeBits.NumTypeArgs = typeArgs.size();
768 assert(getTypeArgsAsWritten().size() == typeArgs.size() &&
769 "bitfield overflow in type argument count");
770 if (!typeArgs.empty())
771 memcpy(getTypeArgStorage(), typeArgs.data(),
772 typeArgs.size() * sizeof(QualType));
773
774 for (auto typeArg : typeArgs) {
775 addDependence(typeArg->getDependence() & ~TypeDependence::VariablyModified);
776 }
777 // Initialize the protocol qualifiers. The protocol storage is known
778 // after we set number of type arguments.
779 initialize(protocols);
780}
781
783 // If we have type arguments written here, the type is specialized.
784 if (ObjCObjectTypeBits.NumTypeArgs > 0)
785 return true;
786
787 // Otherwise, check whether the base type is specialized.
788 if (const auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
789 // Terminate when we reach an interface type.
790 if (isa<ObjCInterfaceType>(objcObject))
791 return false;
792
793 return objcObject->isSpecialized();
794 }
795
796 // Not specialized.
797 return false;
798}
799
801 // We have type arguments written on this type.
803 return getTypeArgsAsWritten();
804
805 // Look at the base type, which might have type arguments.
806 if (const auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
807 // Terminate when we reach an interface type.
808 if (isa<ObjCInterfaceType>(objcObject))
809 return {};
810
811 return objcObject->getTypeArgs();
812 }
813
814 // No type arguments.
815 return {};
816}
817
820 return true;
821
822 // Look at the base type, which might have type arguments.
823 if (const auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
824 // Terminate when we reach an interface type.
825 if (isa<ObjCInterfaceType>(objcObject))
826 return false;
827
828 return objcObject->isKindOfType();
829 }
830
831 // Not a "__kindof" type.
832 return false;
833}
834
836 const ASTContext &ctx) const {
837 if (!isKindOfType() && qual_empty())
838 return QualType(this, 0);
839
840 // Recursively strip __kindof.
841 SplitQualType splitBaseType = getBaseType().split();
842 QualType baseType(splitBaseType.Ty, 0);
843 if (const auto *baseObj = splitBaseType.Ty->getAs<ObjCObjectType>())
844 baseType = baseObj->stripObjCKindOfTypeAndQuals(ctx);
845
846 return ctx.getObjCObjectType(ctx.getQualifiedType(baseType,
847 splitBaseType.Quals),
849 /*protocols=*/{},
850 /*isKindOf=*/false);
851}
852
855 if (ObjCInterfaceDecl *Def = Canon->getDefinition())
856 return Def;
857 return Canon;
858}
859
861 const ASTContext &ctx) const {
862 if (!isKindOfType() && qual_empty())
863 return this;
864
867}
868
869namespace {
870
871/// Visitor used to perform a simple type transformation that does not change
872/// the semantics of the type.
873template <typename Derived>
874struct SimpleTransformVisitor : public TypeVisitor<Derived, QualType> {
875 ASTContext &Ctx;
876
877 QualType recurse(QualType type) {
878 // Split out the qualifiers from the type.
879 SplitQualType splitType = type.split();
880
881 // Visit the type itself.
882 QualType result = static_cast<Derived *>(this)->Visit(splitType.Ty);
883 if (result.isNull())
884 return result;
885
886 // Reconstruct the transformed type by applying the local qualifiers
887 // from the split type.
888 return Ctx.getQualifiedType(result, splitType.Quals);
889 }
890
891public:
892 explicit SimpleTransformVisitor(ASTContext &ctx) : Ctx(ctx) {}
893
894 // None of the clients of this transformation can occur where
895 // there are dependent types, so skip dependent types.
896#define TYPE(Class, Base)
897#define DEPENDENT_TYPE(Class, Base) \
898 QualType Visit##Class##Type(const Class##Type *T) { return QualType(T, 0); }
899#include "clang/AST/TypeNodes.inc"
900
901#define TRIVIAL_TYPE_CLASS(Class) \
902 QualType Visit##Class##Type(const Class##Type *T) { return QualType(T, 0); }
903#define SUGARED_TYPE_CLASS(Class) \
904 QualType Visit##Class##Type(const Class##Type *T) { \
905 if (!T->isSugared()) \
906 return QualType(T, 0); \
907 QualType desugaredType = recurse(T->desugar()); \
908 if (desugaredType.isNull()) \
909 return {}; \
910 if (desugaredType.getAsOpaquePtr() == T->desugar().getAsOpaquePtr()) \
911 return QualType(T, 0); \
912 return desugaredType; \
913 }
914
915 TRIVIAL_TYPE_CLASS(Builtin)
916
917 QualType VisitComplexType(const ComplexType *T) {
918 QualType elementType = recurse(T->getElementType());
919 if (elementType.isNull())
920 return {};
921
922 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
923 return QualType(T, 0);
924
925 return Ctx.getComplexType(elementType);
926 }
927
928 QualType VisitPointerType(const PointerType *T) {
929 QualType pointeeType = recurse(T->getPointeeType());
930 if (pointeeType.isNull())
931 return {};
932
933 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
934 return QualType(T, 0);
935
936 return Ctx.getPointerType(pointeeType);
937 }
938
939 QualType VisitBlockPointerType(const BlockPointerType *T) {
940 QualType pointeeType = recurse(T->getPointeeType());
941 if (pointeeType.isNull())
942 return {};
943
944 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
945 return QualType(T, 0);
946
947 return Ctx.getBlockPointerType(pointeeType);
948 }
949
950 QualType VisitLValueReferenceType(const LValueReferenceType *T) {
951 QualType pointeeType = recurse(T->getPointeeTypeAsWritten());
952 if (pointeeType.isNull())
953 return {};
954
955 if (pointeeType.getAsOpaquePtr()
957 return QualType(T, 0);
958
959 return Ctx.getLValueReferenceType(pointeeType, T->isSpelledAsLValue());
960 }
961
962 QualType VisitRValueReferenceType(const RValueReferenceType *T) {
963 QualType pointeeType = recurse(T->getPointeeTypeAsWritten());
964 if (pointeeType.isNull())
965 return {};
966
967 if (pointeeType.getAsOpaquePtr()
969 return QualType(T, 0);
970
971 return Ctx.getRValueReferenceType(pointeeType);
972 }
973
974 QualType VisitMemberPointerType(const MemberPointerType *T) {
975 QualType pointeeType = recurse(T->getPointeeType());
976 if (pointeeType.isNull())
977 return {};
978
979 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
980 return QualType(T, 0);
981
982 return Ctx.getMemberPointerType(pointeeType, T->getClass());
983 }
984
985 QualType VisitConstantArrayType(const ConstantArrayType *T) {
986 QualType elementType = recurse(T->getElementType());
987 if (elementType.isNull())
988 return {};
989
990 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
991 return QualType(T, 0);
992
993 return Ctx.getConstantArrayType(elementType, T->getSize(), T->getSizeExpr(),
994 T->getSizeModifier(),
996 }
997
998 QualType VisitVariableArrayType(const VariableArrayType *T) {
999 QualType elementType = recurse(T->getElementType());
1000 if (elementType.isNull())
1001 return {};
1002
1003 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
1004 return QualType(T, 0);
1005
1006 return Ctx.getVariableArrayType(elementType, T->getSizeExpr(),
1007 T->getSizeModifier(),
1009 T->getBracketsRange());
1010 }
1011
1012 QualType VisitIncompleteArrayType(const IncompleteArrayType *T) {
1013 QualType elementType = recurse(T->getElementType());
1014 if (elementType.isNull())
1015 return {};
1016
1017 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
1018 return QualType(T, 0);
1019
1020 return Ctx.getIncompleteArrayType(elementType, T->getSizeModifier(),
1022 }
1023
1024 QualType VisitVectorType(const VectorType *T) {
1025 QualType elementType = recurse(T->getElementType());
1026 if (elementType.isNull())
1027 return {};
1028
1029 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
1030 return QualType(T, 0);
1031
1032 return Ctx.getVectorType(elementType, T->getNumElements(),
1033 T->getVectorKind());
1034 }
1035
1036 QualType VisitExtVectorType(const ExtVectorType *T) {
1037 QualType elementType = recurse(T->getElementType());
1038 if (elementType.isNull())
1039 return {};
1040
1041 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
1042 return QualType(T, 0);
1043
1044 return Ctx.getExtVectorType(elementType, T->getNumElements());
1045 }
1046
1047 QualType VisitConstantMatrixType(const ConstantMatrixType *T) {
1048 QualType elementType = recurse(T->getElementType());
1049 if (elementType.isNull())
1050 return {};
1051 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
1052 return QualType(T, 0);
1053
1054 return Ctx.getConstantMatrixType(elementType, T->getNumRows(),
1055 T->getNumColumns());
1056 }
1057
1058 QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
1059 QualType returnType = recurse(T->getReturnType());
1060 if (returnType.isNull())
1061 return {};
1062
1063 if (returnType.getAsOpaquePtr() == T->getReturnType().getAsOpaquePtr())
1064 return QualType(T, 0);
1065
1066 return Ctx.getFunctionNoProtoType(returnType, T->getExtInfo());
1067 }
1068
1069 QualType VisitFunctionProtoType(const FunctionProtoType *T) {
1070 QualType returnType = recurse(T->getReturnType());
1071 if (returnType.isNull())
1072 return {};
1073
1074 // Transform parameter types.
1075 SmallVector<QualType, 4> paramTypes;
1076 bool paramChanged = false;
1077 for (auto paramType : T->getParamTypes()) {
1078 QualType newParamType = recurse(paramType);
1079 if (newParamType.isNull())
1080 return {};
1081
1082 if (newParamType.getAsOpaquePtr() != paramType.getAsOpaquePtr())
1083 paramChanged = true;
1084
1085 paramTypes.push_back(newParamType);
1086 }
1087
1088 // Transform extended info.
1090 bool exceptionChanged = false;
1091 if (info.ExceptionSpec.Type == EST_Dynamic) {
1092 SmallVector<QualType, 4> exceptionTypes;
1093 for (auto exceptionType : info.ExceptionSpec.Exceptions) {
1094 QualType newExceptionType = recurse(exceptionType);
1095 if (newExceptionType.isNull())
1096 return {};
1097
1098 if (newExceptionType.getAsOpaquePtr() != exceptionType.getAsOpaquePtr())
1099 exceptionChanged = true;
1100
1101 exceptionTypes.push_back(newExceptionType);
1102 }
1103
1104 if (exceptionChanged) {
1106 llvm::ArrayRef(exceptionTypes).copy(Ctx);
1107 }
1108 }
1109
1110 if (returnType.getAsOpaquePtr() == T->getReturnType().getAsOpaquePtr() &&
1111 !paramChanged && !exceptionChanged)
1112 return QualType(T, 0);
1113
1114 return Ctx.getFunctionType(returnType, paramTypes, info);
1115 }
1116
1117 QualType VisitParenType(const ParenType *T) {
1118 QualType innerType = recurse(T->getInnerType());
1119 if (innerType.isNull())
1120 return {};
1121
1122 if (innerType.getAsOpaquePtr() == T->getInnerType().getAsOpaquePtr())
1123 return QualType(T, 0);
1124
1125 return Ctx.getParenType(innerType);
1126 }
1127
1128 SUGARED_TYPE_CLASS(Typedef)
1129 SUGARED_TYPE_CLASS(ObjCTypeParam)
1130 SUGARED_TYPE_CLASS(MacroQualified)
1131
1132 QualType VisitAdjustedType(const AdjustedType *T) {
1133 QualType originalType = recurse(T->getOriginalType());
1134 if (originalType.isNull())
1135 return {};
1136
1137 QualType adjustedType = recurse(T->getAdjustedType());
1138 if (adjustedType.isNull())
1139 return {};
1140
1141 if (originalType.getAsOpaquePtr()
1142 == T->getOriginalType().getAsOpaquePtr() &&
1143 adjustedType.getAsOpaquePtr() == T->getAdjustedType().getAsOpaquePtr())
1144 return QualType(T, 0);
1145
1146 return Ctx.getAdjustedType(originalType, adjustedType);
1147 }
1148
1149 QualType VisitDecayedType(const DecayedType *T) {
1150 QualType originalType = recurse(T->getOriginalType());
1151 if (originalType.isNull())
1152 return {};
1153
1154 if (originalType.getAsOpaquePtr()
1156 return QualType(T, 0);
1157
1158 return Ctx.getDecayedType(originalType);
1159 }
1160
1161 SUGARED_TYPE_CLASS(TypeOfExpr)
1162 SUGARED_TYPE_CLASS(TypeOf)
1163 SUGARED_TYPE_CLASS(Decltype)
1164 SUGARED_TYPE_CLASS(UnaryTransform)
1165 TRIVIAL_TYPE_CLASS(Record)
1167
1168 // FIXME: Non-trivial to implement, but important for C++
1169 SUGARED_TYPE_CLASS(Elaborated)
1170
1171 QualType VisitAttributedType(const AttributedType *T) {
1172 QualType modifiedType = recurse(T->getModifiedType());
1173 if (modifiedType.isNull())
1174 return {};
1175
1176 QualType equivalentType = recurse(T->getEquivalentType());
1177 if (equivalentType.isNull())
1178 return {};
1179
1180 if (modifiedType.getAsOpaquePtr()
1181 == T->getModifiedType().getAsOpaquePtr() &&
1182 equivalentType.getAsOpaquePtr()
1184 return QualType(T, 0);
1185
1186 return Ctx.getAttributedType(T->getAttrKind(), modifiedType,
1187 equivalentType);
1188 }
1189
1190 QualType VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1191 QualType replacementType = recurse(T->getReplacementType());
1192 if (replacementType.isNull())
1193 return {};
1194
1195 if (replacementType.getAsOpaquePtr()
1197 return QualType(T, 0);
1198
1199 return Ctx.getSubstTemplateTypeParmType(replacementType,
1200 T->getAssociatedDecl(),
1201 T->getIndex(), T->getPackIndex());
1202 }
1203
1204 // FIXME: Non-trivial to implement, but important for C++
1205 SUGARED_TYPE_CLASS(TemplateSpecialization)
1206
1207 QualType VisitAutoType(const AutoType *T) {
1208 if (!T->isDeduced())
1209 return QualType(T, 0);
1210
1211 QualType deducedType = recurse(T->getDeducedType());
1212 if (deducedType.isNull())
1213 return {};
1214
1215 if (deducedType.getAsOpaquePtr()
1217 return QualType(T, 0);
1218
1219 return Ctx.getAutoType(deducedType, T->getKeyword(),
1220 T->isDependentType(), /*IsPack=*/false,
1223 }
1224
1225 QualType VisitObjCObjectType(const ObjCObjectType *T) {
1226 QualType baseType = recurse(T->getBaseType());
1227 if (baseType.isNull())
1228 return {};
1229
1230 // Transform type arguments.
1231 bool typeArgChanged = false;
1232 SmallVector<QualType, 4> typeArgs;
1233 for (auto typeArg : T->getTypeArgsAsWritten()) {
1234 QualType newTypeArg = recurse(typeArg);
1235 if (newTypeArg.isNull())
1236 return {};
1237
1238 if (newTypeArg.getAsOpaquePtr() != typeArg.getAsOpaquePtr())
1239 typeArgChanged = true;
1240
1241 typeArgs.push_back(newTypeArg);
1242 }
1243
1244 if (baseType.getAsOpaquePtr() == T->getBaseType().getAsOpaquePtr() &&
1245 !typeArgChanged)
1246 return QualType(T, 0);
1247
1248 return Ctx.getObjCObjectType(
1249 baseType, typeArgs,
1252 }
1253
1254 TRIVIAL_TYPE_CLASS(ObjCInterface)
1255
1256 QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
1257 QualType pointeeType = recurse(T->getPointeeType());
1258 if (pointeeType.isNull())
1259 return {};
1260
1261 if (pointeeType.getAsOpaquePtr()
1263 return QualType(T, 0);
1264
1265 return Ctx.getObjCObjectPointerType(pointeeType);
1266 }
1267
1268 QualType VisitAtomicType(const AtomicType *T) {
1269 QualType valueType = recurse(T->getValueType());
1270 if (valueType.isNull())
1271 return {};
1272
1273 if (valueType.getAsOpaquePtr()
1274 == T->getValueType().getAsOpaquePtr())
1275 return QualType(T, 0);
1276
1277 return Ctx.getAtomicType(valueType);
1278 }
1279
1280#undef TRIVIAL_TYPE_CLASS
1281#undef SUGARED_TYPE_CLASS
1282};
1283
1284struct SubstObjCTypeArgsVisitor
1285 : public SimpleTransformVisitor<SubstObjCTypeArgsVisitor> {
1286 using BaseType = SimpleTransformVisitor<SubstObjCTypeArgsVisitor>;
1287
1288 ArrayRef<QualType> TypeArgs;
1289 ObjCSubstitutionContext SubstContext;
1290
1291 SubstObjCTypeArgsVisitor(ASTContext &ctx, ArrayRef<QualType> typeArgs,
1293 : BaseType(ctx), TypeArgs(typeArgs), SubstContext(context) {}
1294
1295 QualType VisitObjCTypeParamType(const ObjCTypeParamType *OTPTy) {
1296 // Replace an Objective-C type parameter reference with the corresponding
1297 // type argument.
1298 ObjCTypeParamDecl *typeParam = OTPTy->getDecl();
1299 // If we have type arguments, use them.
1300 if (!TypeArgs.empty()) {
1301 QualType argType = TypeArgs[typeParam->getIndex()];
1302 if (OTPTy->qual_empty())
1303 return argType;
1304
1305 // Apply protocol lists if exists.
1306 bool hasError;
1308 protocolsVec.append(OTPTy->qual_begin(), OTPTy->qual_end());
1309 ArrayRef<ObjCProtocolDecl *> protocolsToApply = protocolsVec;
1310 return Ctx.applyObjCProtocolQualifiers(
1311 argType, protocolsToApply, hasError, true/*allowOnPointerType*/);
1312 }
1313
1314 switch (SubstContext) {
1315 case ObjCSubstitutionContext::Ordinary:
1316 case ObjCSubstitutionContext::Parameter:
1317 case ObjCSubstitutionContext::Superclass:
1318 // Substitute the bound.
1319 return typeParam->getUnderlyingType();
1320
1321 case ObjCSubstitutionContext::Result:
1322 case ObjCSubstitutionContext::Property: {
1323 // Substitute the __kindof form of the underlying type.
1324 const auto *objPtr =
1326
1327 // __kindof types, id, and Class don't need an additional
1328 // __kindof.
1329 if (objPtr->isKindOfType() || objPtr->isObjCIdOrClassType())
1330 return typeParam->getUnderlyingType();
1331
1332 // Add __kindof.
1333 const auto *obj = objPtr->getObjectType();
1334 QualType resultTy = Ctx.getObjCObjectType(
1335 obj->getBaseType(), obj->getTypeArgsAsWritten(), obj->getProtocols(),
1336 /*isKindOf=*/true);
1337
1338 // Rebuild object pointer type.
1339 return Ctx.getObjCObjectPointerType(resultTy);
1340 }
1341 }
1342 llvm_unreachable("Unexpected ObjCSubstitutionContext!");
1343 }
1344
1345 QualType VisitFunctionType(const FunctionType *funcType) {
1346 // If we have a function type, update the substitution context
1347 // appropriately.
1348
1349 //Substitute result type.
1350 QualType returnType = funcType->getReturnType().substObjCTypeArgs(
1351 Ctx, TypeArgs, ObjCSubstitutionContext::Result);
1352 if (returnType.isNull())
1353 return {};
1354
1355 // Handle non-prototyped functions, which only substitute into the result
1356 // type.
1357 if (isa<FunctionNoProtoType>(funcType)) {
1358 // If the return type was unchanged, do nothing.
1359 if (returnType.getAsOpaquePtr() ==
1360 funcType->getReturnType().getAsOpaquePtr())
1361 return BaseType::VisitFunctionType(funcType);
1362
1363 // Otherwise, build a new type.
1364 return Ctx.getFunctionNoProtoType(returnType, funcType->getExtInfo());
1365 }
1366
1367 const auto *funcProtoType = cast<FunctionProtoType>(funcType);
1368
1369 // Transform parameter types.
1370 SmallVector<QualType, 4> paramTypes;
1371 bool paramChanged = false;
1372 for (auto paramType : funcProtoType->getParamTypes()) {
1373 QualType newParamType = paramType.substObjCTypeArgs(
1374 Ctx, TypeArgs, ObjCSubstitutionContext::Parameter);
1375 if (newParamType.isNull())
1376 return {};
1377
1378 if (newParamType.getAsOpaquePtr() != paramType.getAsOpaquePtr())
1379 paramChanged = true;
1380
1381 paramTypes.push_back(newParamType);
1382 }
1383
1384 // Transform extended info.
1385 FunctionProtoType::ExtProtoInfo info = funcProtoType->getExtProtoInfo();
1386 bool exceptionChanged = false;
1387 if (info.ExceptionSpec.Type == EST_Dynamic) {
1388 SmallVector<QualType, 4> exceptionTypes;
1389 for (auto exceptionType : info.ExceptionSpec.Exceptions) {
1390 QualType newExceptionType = exceptionType.substObjCTypeArgs(
1391 Ctx, TypeArgs, ObjCSubstitutionContext::Ordinary);
1392 if (newExceptionType.isNull())
1393 return {};
1394
1395 if (newExceptionType.getAsOpaquePtr() != exceptionType.getAsOpaquePtr())
1396 exceptionChanged = true;
1397
1398 exceptionTypes.push_back(newExceptionType);
1399 }
1400
1401 if (exceptionChanged) {
1403 llvm::ArrayRef(exceptionTypes).copy(Ctx);
1404 }
1405 }
1406
1407 if (returnType.getAsOpaquePtr() ==
1408 funcProtoType->getReturnType().getAsOpaquePtr() &&
1409 !paramChanged && !exceptionChanged)
1410 return BaseType::VisitFunctionType(funcType);
1411
1412 return Ctx.getFunctionType(returnType, paramTypes, info);
1413 }
1414
1415 QualType VisitObjCObjectType(const ObjCObjectType *objcObjectType) {
1416 // Substitute into the type arguments of a specialized Objective-C object
1417 // type.
1418 if (objcObjectType->isSpecializedAsWritten()) {
1419 SmallVector<QualType, 4> newTypeArgs;
1420 bool anyChanged = false;
1421 for (auto typeArg : objcObjectType->getTypeArgsAsWritten()) {
1422 QualType newTypeArg = typeArg.substObjCTypeArgs(
1423 Ctx, TypeArgs, ObjCSubstitutionContext::Ordinary);
1424 if (newTypeArg.isNull())
1425 return {};
1426
1427 if (newTypeArg.getAsOpaquePtr() != typeArg.getAsOpaquePtr()) {
1428 // If we're substituting based on an unspecialized context type,
1429 // produce an unspecialized type.
1431 objcObjectType->qual_begin(), objcObjectType->getNumProtocols());
1432 if (TypeArgs.empty() &&
1433 SubstContext != ObjCSubstitutionContext::Superclass) {
1434 return Ctx.getObjCObjectType(
1435 objcObjectType->getBaseType(), {}, protocols,
1436 objcObjectType->isKindOfTypeAsWritten());
1437 }
1438
1439 anyChanged = true;
1440 }
1441
1442 newTypeArgs.push_back(newTypeArg);
1443 }
1444
1445 if (anyChanged) {
1447 objcObjectType->qual_begin(), objcObjectType->getNumProtocols());
1448 return Ctx.getObjCObjectType(objcObjectType->getBaseType(), newTypeArgs,
1449 protocols,
1450 objcObjectType->isKindOfTypeAsWritten());
1451 }
1452 }
1453
1454 return BaseType::VisitObjCObjectType(objcObjectType);
1455 }
1456
1457 QualType VisitAttributedType(const AttributedType *attrType) {
1458 QualType newType = BaseType::VisitAttributedType(attrType);
1459 if (newType.isNull())
1460 return {};
1461
1462 const auto *newAttrType = dyn_cast<AttributedType>(newType.getTypePtr());
1463 if (!newAttrType || newAttrType->getAttrKind() != attr::ObjCKindOf)
1464 return newType;
1465
1466 // Find out if it's an Objective-C object or object pointer type;
1467 QualType newEquivType = newAttrType->getEquivalentType();
1468 const ObjCObjectPointerType *ptrType =
1469 newEquivType->getAs<ObjCObjectPointerType>();
1470 const ObjCObjectType *objType = ptrType
1471 ? ptrType->getObjectType()
1472 : newEquivType->getAs<ObjCObjectType>();
1473 if (!objType)
1474 return newType;
1475
1476 // Rebuild the "equivalent" type, which pushes __kindof down into
1477 // the object type.
1478 newEquivType = Ctx.getObjCObjectType(
1479 objType->getBaseType(), objType->getTypeArgsAsWritten(),
1480 objType->getProtocols(),
1481 // There is no need to apply kindof on an unqualified id type.
1482 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
1483
1484 // If we started with an object pointer type, rebuild it.
1485 if (ptrType)
1486 newEquivType = Ctx.getObjCObjectPointerType(newEquivType);
1487
1488 // Rebuild the attributed type.
1489 return Ctx.getAttributedType(newAttrType->getAttrKind(),
1490 newAttrType->getModifiedType(), newEquivType);
1491 }
1492};
1493
1494struct StripObjCKindOfTypeVisitor
1495 : public SimpleTransformVisitor<StripObjCKindOfTypeVisitor> {
1496 using BaseType = SimpleTransformVisitor<StripObjCKindOfTypeVisitor>;
1497
1498 explicit StripObjCKindOfTypeVisitor(ASTContext &ctx) : BaseType(ctx) {}
1499
1500 QualType VisitObjCObjectType(const ObjCObjectType *objType) {
1501 if (!objType->isKindOfType())
1502 return BaseType::VisitObjCObjectType(objType);
1503
1504 QualType baseType = objType->getBaseType().stripObjCKindOfType(Ctx);
1505 return Ctx.getObjCObjectType(baseType, objType->getTypeArgsAsWritten(),
1506 objType->getProtocols(),
1507 /*isKindOf=*/false);
1508 }
1509};
1510
1511} // namespace
1512
1514 const BuiltinType *BT = getTypePtr()->getAs<BuiltinType>();
1515 if (!BT) {
1516 const VectorType *VT = getTypePtr()->getAs<VectorType>();
1517 if (VT) {
1518 QualType ElementType = VT->getElementType();
1519 return ElementType.UseExcessPrecision(Ctx);
1520 }
1521 } else {
1522 switch (BT->getKind()) {
1523 case BuiltinType::Kind::Float16: {
1524 const TargetInfo &TI = Ctx.getTargetInfo();
1525 if (TI.hasFloat16Type() && !TI.hasLegalHalfType() &&
1526 Ctx.getLangOpts().getFloat16ExcessPrecision() !=
1527 Ctx.getLangOpts().ExcessPrecisionKind::FPP_None)
1528 return true;
1529 break;
1530 }
1531 case BuiltinType::Kind::BFloat16: {
1532 const TargetInfo &TI = Ctx.getTargetInfo();
1533 if (TI.hasBFloat16Type() && !TI.hasFullBFloat16Type() &&
1534 Ctx.getLangOpts().getBFloat16ExcessPrecision() !=
1535 Ctx.getLangOpts().ExcessPrecisionKind::FPP_None)
1536 return true;
1537 break;
1538 }
1539 default:
1540 return false;
1541 }
1542 }
1543 return false;
1544}
1545
1546/// Substitute the given type arguments for Objective-C type
1547/// parameters within the given type, recursively.
1549 ArrayRef<QualType> typeArgs,
1550 ObjCSubstitutionContext context) const {
1551 SubstObjCTypeArgsVisitor visitor(ctx, typeArgs, context);
1552 return visitor.recurse(*this);
1553}
1554
1556 const DeclContext *dc,
1557 ObjCSubstitutionContext context) const {
1558 if (auto subs = objectType->getObjCSubstitutions(dc))
1559 return substObjCTypeArgs(dc->getParentASTContext(), *subs, context);
1560
1561 return *this;
1562}
1563
1565 // FIXME: Because ASTContext::getAttributedType() is non-const.
1566 auto &ctx = const_cast<ASTContext &>(constCtx);
1567 StripObjCKindOfTypeVisitor visitor(ctx);
1568 return visitor.recurse(*this);
1569}
1570
1572 if (const auto AT = getTypePtr()->getAs<AtomicType>())
1573 return AT->getValueType().getUnqualifiedType();
1574 return getUnqualifiedType();
1575}
1576
1577std::optional<ArrayRef<QualType>>
1579 // Look through method scopes.
1580 if (const auto method = dyn_cast<ObjCMethodDecl>(dc))
1581 dc = method->getDeclContext();
1582
1583 // Find the class or category in which the type we're substituting
1584 // was declared.
1585 const auto *dcClassDecl = dyn_cast<ObjCInterfaceDecl>(dc);
1586 const ObjCCategoryDecl *dcCategoryDecl = nullptr;
1587 ObjCTypeParamList *dcTypeParams = nullptr;
1588 if (dcClassDecl) {
1589 // If the class does not have any type parameters, there's no
1590 // substitution to do.
1591 dcTypeParams = dcClassDecl->getTypeParamList();
1592 if (!dcTypeParams)
1593 return std::nullopt;
1594 } else {
1595 // If we are in neither a class nor a category, there's no
1596 // substitution to perform.
1597 dcCategoryDecl = dyn_cast<ObjCCategoryDecl>(dc);
1598 if (!dcCategoryDecl)
1599 return std::nullopt;
1600
1601 // If the category does not have any type parameters, there's no
1602 // substitution to do.
1603 dcTypeParams = dcCategoryDecl->getTypeParamList();
1604 if (!dcTypeParams)
1605 return std::nullopt;
1606
1607 dcClassDecl = dcCategoryDecl->getClassInterface();
1608 if (!dcClassDecl)
1609 return std::nullopt;
1610 }
1611 assert(dcTypeParams && "No substitutions to perform");
1612 assert(dcClassDecl && "No class context");
1613
1614 // Find the underlying object type.
1615 const ObjCObjectType *objectType;
1616 if (const auto *objectPointerType = getAs<ObjCObjectPointerType>()) {
1617 objectType = objectPointerType->getObjectType();
1618 } else if (getAs<BlockPointerType>()) {
1619 ASTContext &ctx = dc->getParentASTContext();
1620 objectType = ctx.getObjCObjectType(ctx.ObjCBuiltinIdTy, {}, {})
1622 } else {
1623 objectType = getAs<ObjCObjectType>();
1624 }
1625
1626 /// Extract the class from the receiver object type.
1627 ObjCInterfaceDecl *curClassDecl = objectType ? objectType->getInterface()
1628 : nullptr;
1629 if (!curClassDecl) {
1630 // If we don't have a context type (e.g., this is "id" or some
1631 // variant thereof), substitute the bounds.
1632 return llvm::ArrayRef<QualType>();
1633 }
1634
1635 // Follow the superclass chain until we've mapped the receiver type
1636 // to the same class as the context.
1637 while (curClassDecl != dcClassDecl) {
1638 // Map to the superclass type.
1639 QualType superType = objectType->getSuperClassType();
1640 if (superType.isNull()) {
1641 objectType = nullptr;
1642 break;
1643 }
1644
1645 objectType = superType->castAs<ObjCObjectType>();
1646 curClassDecl = objectType->getInterface();
1647 }
1648
1649 // If we don't have a receiver type, or the receiver type does not
1650 // have type arguments, substitute in the defaults.
1651 if (!objectType || objectType->isUnspecialized()) {
1652 return llvm::ArrayRef<QualType>();
1653 }
1654
1655 // The receiver type has the type arguments we want.
1656 return objectType->getTypeArgs();
1657}
1658
1660 if (auto *IfaceT = getAsObjCInterfaceType()) {
1661 if (auto *ID = IfaceT->getInterface()) {
1662 if (ID->getTypeParamList())
1663 return true;
1664 }
1665 }
1666
1667 return false;
1668}
1669
1671 // Retrieve the class declaration for this type. If there isn't one
1672 // (e.g., this is some variant of "id" or "Class"), then there is no
1673 // superclass type.
1674 ObjCInterfaceDecl *classDecl = getInterface();
1675 if (!classDecl) {
1676 CachedSuperClassType.setInt(true);
1677 return;
1678 }
1679
1680 // Extract the superclass type.
1681 const ObjCObjectType *superClassObjTy = classDecl->getSuperClassType();
1682 if (!superClassObjTy) {
1683 CachedSuperClassType.setInt(true);
1684 return;
1685 }
1686
1687 ObjCInterfaceDecl *superClassDecl = superClassObjTy->getInterface();
1688 if (!superClassDecl) {
1689 CachedSuperClassType.setInt(true);
1690 return;
1691 }
1692
1693 // If the superclass doesn't have type parameters, then there is no
1694 // substitution to perform.
1695 QualType superClassType(superClassObjTy, 0);
1696 ObjCTypeParamList *superClassTypeParams = superClassDecl->getTypeParamList();
1697 if (!superClassTypeParams) {
1698 CachedSuperClassType.setPointerAndInt(
1699 superClassType->castAs<ObjCObjectType>(), true);
1700 return;
1701 }
1702
1703 // If the superclass reference is unspecialized, return it.
1704 if (superClassObjTy->isUnspecialized()) {
1705 CachedSuperClassType.setPointerAndInt(superClassObjTy, true);
1706 return;
1707 }
1708
1709 // If the subclass is not parameterized, there aren't any type
1710 // parameters in the superclass reference to substitute.
1711 ObjCTypeParamList *typeParams = classDecl->getTypeParamList();
1712 if (!typeParams) {
1713 CachedSuperClassType.setPointerAndInt(
1714 superClassType->castAs<ObjCObjectType>(), true);
1715 return;
1716 }
1717
1718 // If the subclass type isn't specialized, return the unspecialized
1719 // superclass.
1720 if (isUnspecialized()) {
1721 QualType unspecializedSuper
1722 = classDecl->getASTContext().getObjCInterfaceType(
1723 superClassObjTy->getInterface());
1724 CachedSuperClassType.setPointerAndInt(
1725 unspecializedSuper->castAs<ObjCObjectType>(),
1726 true);
1727 return;
1728 }
1729
1730 // Substitute the provided type arguments into the superclass type.
1731 ArrayRef<QualType> typeArgs = getTypeArgs();
1732 assert(typeArgs.size() == typeParams->size());
1733 CachedSuperClassType.setPointerAndInt(
1734 superClassType.substObjCTypeArgs(classDecl->getASTContext(), typeArgs,
1737 true);
1738}
1739
1741 if (auto interfaceDecl = getObjectType()->getInterface()) {
1742 return interfaceDecl->getASTContext().getObjCInterfaceType(interfaceDecl)
1744 }
1745
1746 return nullptr;
1747}
1748
1750 QualType superObjectType = getObjectType()->getSuperClassType();
1751 if (superObjectType.isNull())
1752 return superObjectType;
1753
1755 return ctx.getObjCObjectPointerType(superObjectType);
1756}
1757
1759 // There is no sugar for ObjCObjectType's, just return the canonical
1760 // type pointer if it is the right class. There is no typedef information to
1761 // return and these cannot be Address-space qualified.
1762 if (const auto *T = getAs<ObjCObjectType>())
1763 if (T->getNumProtocols() && T->getInterface())
1764 return T;
1765 return nullptr;
1766}
1767
1769 return getAsObjCQualifiedInterfaceType() != nullptr;
1770}
1771
1773 // There is no sugar for ObjCQualifiedIdType's, just return the canonical
1774 // type pointer if it is the right class.
1775 if (const auto *OPT = getAs<ObjCObjectPointerType>()) {
1776 if (OPT->isObjCQualifiedIdType())
1777 return OPT;
1778 }
1779 return nullptr;
1780}
1781
1783 // There is no sugar for ObjCQualifiedClassType's, just return the canonical
1784 // type pointer if it is the right class.
1785 if (const auto *OPT = getAs<ObjCObjectPointerType>()) {
1786 if (OPT->isObjCQualifiedClassType())
1787 return OPT;
1788 }
1789 return nullptr;
1790}
1791
1793 if (const auto *OT = getAs<ObjCObjectType>()) {
1794 if (OT->getInterface())
1795 return OT;
1796 }
1797 return nullptr;
1798}
1799
1801 if (const auto *OPT = getAs<ObjCObjectPointerType>()) {
1802 if (OPT->getInterfaceType())
1803 return OPT;
1804 }
1805 return nullptr;
1806}
1807
1809 QualType PointeeType;
1810 if (const auto *PT = getAs<PointerType>())
1811 PointeeType = PT->getPointeeType();
1812 else if (const auto *RT = getAs<ReferenceType>())
1813 PointeeType = RT->getPointeeType();
1814 else
1815 return nullptr;
1816
1817 if (const auto *RT = PointeeType->getAs<RecordType>())
1818 return dyn_cast<CXXRecordDecl>(RT->getDecl());
1819
1820 return nullptr;
1821}
1822
1824 return dyn_cast_or_null<CXXRecordDecl>(getAsTagDecl());
1825}
1826
1828 return dyn_cast_or_null<RecordDecl>(getAsTagDecl());
1829}
1830
1832 if (const auto *TT = getAs<TagType>())
1833 return TT->getDecl();
1834 if (const auto *Injected = getAs<InjectedClassNameType>())
1835 return Injected->getDecl();
1836
1837 return nullptr;
1838}
1839
1841 const Type *Cur = this;
1842 while (const auto *AT = Cur->getAs<AttributedType>()) {
1843 if (AT->getAttrKind() == AK)
1844 return true;
1845 Cur = AT->getEquivalentType().getTypePtr();
1846 }
1847 return false;
1848}
1849
1850namespace {
1851
1852 class GetContainedDeducedTypeVisitor :
1853 public TypeVisitor<GetContainedDeducedTypeVisitor, Type*> {
1854 bool Syntactic;
1855
1856 public:
1857 GetContainedDeducedTypeVisitor(bool Syntactic = false)
1858 : Syntactic(Syntactic) {}
1859
1860 using TypeVisitor<GetContainedDeducedTypeVisitor, Type*>::Visit;
1861
1862 Type *Visit(QualType T) {
1863 if (T.isNull())
1864 return nullptr;
1865 return Visit(T.getTypePtr());
1866 }
1867
1868 // The deduced type itself.
1869 Type *VisitDeducedType(const DeducedType *AT) {
1870 return const_cast<DeducedType*>(AT);
1871 }
1872
1873 // Only these types can contain the desired 'auto' type.
1874 Type *VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1875 return Visit(T->getReplacementType());
1876 }
1877
1878 Type *VisitElaboratedType(const ElaboratedType *T) {
1879 return Visit(T->getNamedType());
1880 }
1881
1882 Type *VisitPointerType(const PointerType *T) {
1883 return Visit(T->getPointeeType());
1884 }
1885
1886 Type *VisitBlockPointerType(const BlockPointerType *T) {
1887 return Visit(T->getPointeeType());
1888 }
1889
1890 Type *VisitReferenceType(const ReferenceType *T) {
1891 return Visit(T->getPointeeTypeAsWritten());
1892 }
1893
1894 Type *VisitMemberPointerType(const MemberPointerType *T) {
1895 return Visit(T->getPointeeType());
1896 }
1897
1898 Type *VisitArrayType(const ArrayType *T) {
1899 return Visit(T->getElementType());
1900 }
1901
1902 Type *VisitDependentSizedExtVectorType(
1903 const DependentSizedExtVectorType *T) {
1904 return Visit(T->getElementType());
1905 }
1906
1907 Type *VisitVectorType(const VectorType *T) {
1908 return Visit(T->getElementType());
1909 }
1910
1911 Type *VisitDependentSizedMatrixType(const DependentSizedMatrixType *T) {
1912 return Visit(T->getElementType());
1913 }
1914
1915 Type *VisitConstantMatrixType(const ConstantMatrixType *T) {
1916 return Visit(T->getElementType());
1917 }
1918
1919 Type *VisitFunctionProtoType(const FunctionProtoType *T) {
1920 if (Syntactic && T->hasTrailingReturn())
1921 return const_cast<FunctionProtoType*>(T);
1922 return VisitFunctionType(T);
1923 }
1924
1925 Type *VisitFunctionType(const FunctionType *T) {
1926 return Visit(T->getReturnType());
1927 }
1928
1929 Type *VisitParenType(const ParenType *T) {
1930 return Visit(T->getInnerType());
1931 }
1932
1933 Type *VisitAttributedType(const AttributedType *T) {
1934 return Visit(T->getModifiedType());
1935 }
1936
1937 Type *VisitMacroQualifiedType(const MacroQualifiedType *T) {
1938 return Visit(T->getUnderlyingType());
1939 }
1940
1941 Type *VisitAdjustedType(const AdjustedType *T) {
1942 return Visit(T->getOriginalType());
1943 }
1944
1945 Type *VisitPackExpansionType(const PackExpansionType *T) {
1946 return Visit(T->getPattern());
1947 }
1948 };
1949
1950} // namespace
1951
1953 return cast_or_null<DeducedType>(
1954 GetContainedDeducedTypeVisitor().Visit(this));
1955}
1956
1958 return isa_and_nonnull<FunctionType>(
1959 GetContainedDeducedTypeVisitor(true).Visit(this));
1960}
1961
1963 if (const auto *VT = dyn_cast<VectorType>(CanonicalType))
1964 return VT->getElementType()->isIntegerType();
1965 if (CanonicalType->isSveVLSBuiltinType()) {
1966 const auto *VT = cast<BuiltinType>(CanonicalType);
1967 return VT->getKind() == BuiltinType::SveBool ||
1968 (VT->getKind() >= BuiltinType::SveInt8 &&
1969 VT->getKind() <= BuiltinType::SveUint64);
1970 }
1971 if (CanonicalType->isRVVVLSBuiltinType()) {
1972 const auto *VT = cast<BuiltinType>(CanonicalType);
1973 return (VT->getKind() >= BuiltinType::RvvInt8mf8 &&
1974 VT->getKind() <= BuiltinType::RvvUint64m8);
1975 }
1976
1977 return isIntegerType();
1978}
1979
1980/// Determine whether this type is an integral type.
1981///
1982/// This routine determines whether the given type is an integral type per
1983/// C++ [basic.fundamental]p7. Although the C standard does not define the
1984/// term "integral type", it has a similar term "integer type", and in C++
1985/// the two terms are equivalent. However, C's "integer type" includes
1986/// enumeration types, while C++'s "integer type" does not. The \c ASTContext
1987/// parameter is used to determine whether we should be following the C or
1988/// C++ rules when determining whether this type is an integral/integer type.
1989///
1990/// For cases where C permits "an integer type" and C++ permits "an integral
1991/// type", use this routine.
1992///
1993/// For cases where C permits "an integer type" and C++ permits "an integral
1994/// or enumeration type", use \c isIntegralOrEnumerationType() instead.
1995///
1996/// \param Ctx The context in which this type occurs.
1997///
1998/// \returns true if the type is considered an integral type, false otherwise.
1999bool Type::isIntegralType(const ASTContext &Ctx) const {
2000 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2001 return BT->getKind() >= BuiltinType::Bool &&
2002 BT->getKind() <= BuiltinType::Int128;
2003
2004 // Complete enum types are integral in C.
2005 if (!Ctx.getLangOpts().CPlusPlus)
2006 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
2007 return ET->getDecl()->isComplete();
2008
2009 return isBitIntType();
2010}
2011
2013 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2014 return BT->getKind() >= BuiltinType::Bool &&
2015 BT->getKind() <= BuiltinType::Int128;
2016
2017 if (isBitIntType())
2018 return true;
2019
2021}
2022
2024 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
2025 return !ET->getDecl()->isScoped();
2026
2027 return false;
2028}
2029
2030bool Type::isCharType() const {
2031 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2032 return BT->getKind() == BuiltinType::Char_U ||
2033 BT->getKind() == BuiltinType::UChar ||
2034 BT->getKind() == BuiltinType::Char_S ||
2035 BT->getKind() == BuiltinType::SChar;
2036 return false;
2037}
2038
2040 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2041 return BT->getKind() == BuiltinType::WChar_S ||
2042 BT->getKind() == BuiltinType::WChar_U;
2043 return false;
2044}
2045
2046bool Type::isChar8Type() const {
2047 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
2048 return BT->getKind() == BuiltinType::Char8;
2049 return false;
2050}
2051
2053 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2054 return BT->getKind() == BuiltinType::Char16;
2055 return false;
2056}
2057
2059 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2060 return BT->getKind() == BuiltinType::Char32;
2061 return false;
2062}
2063
2064/// Determine whether this type is any of the built-in character
2065/// types.
2067 const auto *BT = dyn_cast<BuiltinType>(CanonicalType);
2068 if (!BT) return false;
2069 switch (BT->getKind()) {
2070 default: return false;
2071 case BuiltinType::Char_U:
2072 case BuiltinType::UChar:
2073 case BuiltinType::WChar_U:
2074 case BuiltinType::Char8:
2075 case BuiltinType::Char16:
2076 case BuiltinType::Char32:
2077 case BuiltinType::Char_S:
2078 case BuiltinType::SChar:
2079 case BuiltinType::WChar_S:
2080 return true;
2081 }
2082}
2083
2084/// isSignedIntegerType - Return true if this is an integer type that is
2085/// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2086/// an enum decl which has a signed representation
2088 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
2089 return BT->getKind() >= BuiltinType::Char_S &&
2090 BT->getKind() <= BuiltinType::Int128;
2091 }
2092
2093 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
2094 // Incomplete enum types are not treated as integer types.
2095 // FIXME: In C++, enum types are never integer types.
2096 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
2097 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
2098 }
2099
2100 if (const auto *IT = dyn_cast<BitIntType>(CanonicalType))
2101 return IT->isSigned();
2102 if (const auto *IT = dyn_cast<DependentBitIntType>(CanonicalType))
2103 return IT->isSigned();
2104
2105 return false;
2106}
2107
2109 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
2110 return BT->getKind() >= BuiltinType::Char_S &&
2111 BT->getKind() <= BuiltinType::Int128;
2112 }
2113
2114 if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) {
2115 if (ET->getDecl()->isComplete())
2116 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
2117 }
2118
2119 if (const auto *IT = dyn_cast<BitIntType>(CanonicalType))
2120 return IT->isSigned();
2121 if (const auto *IT = dyn_cast<DependentBitIntType>(CanonicalType))
2122 return IT->isSigned();
2123
2124 return false;
2125}
2126
2128 if (const auto *VT = dyn_cast<VectorType>(CanonicalType))
2129 return VT->getElementType()->isSignedIntegerOrEnumerationType();
2130 else
2132}
2133
2134/// isUnsignedIntegerType - Return true if this is an integer type that is
2135/// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
2136/// decl which has an unsigned representation
2138 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
2139 return BT->getKind() >= BuiltinType::Bool &&
2140 BT->getKind() <= BuiltinType::UInt128;
2141 }
2142
2143 if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) {
2144 // Incomplete enum types are not treated as integer types.
2145 // FIXME: In C++, enum types are never integer types.
2146 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
2147 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
2148 }
2149
2150 if (const auto *IT = dyn_cast<BitIntType>(CanonicalType))
2151 return IT->isUnsigned();
2152 if (const auto *IT = dyn_cast<DependentBitIntType>(CanonicalType))
2153 return IT->isUnsigned();
2154
2155 return false;
2156}
2157
2159 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
2160 return BT->getKind() >= BuiltinType::Bool &&
2161 BT->getKind() <= BuiltinType::UInt128;
2162 }
2163
2164 if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) {
2165 if (ET->getDecl()->isComplete())
2166 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
2167 }
2168
2169 if (const auto *IT = dyn_cast<BitIntType>(CanonicalType))
2170 return IT->isUnsigned();
2171 if (const auto *IT = dyn_cast<DependentBitIntType>(CanonicalType))
2172 return IT->isUnsigned();
2173
2174 return false;
2175}
2176
2178 if (const auto *VT = dyn_cast<VectorType>(CanonicalType))
2179 return VT->getElementType()->isUnsignedIntegerOrEnumerationType();
2180 if (const auto *VT = dyn_cast<MatrixType>(CanonicalType))
2181 return VT->getElementType()->isUnsignedIntegerOrEnumerationType();
2182 if (CanonicalType->isSveVLSBuiltinType()) {
2183 const auto *VT = cast<BuiltinType>(CanonicalType);
2184 return VT->getKind() >= BuiltinType::SveUint8 &&
2185 VT->getKind() <= BuiltinType::SveUint64;
2186 }
2188}
2189
2191 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2192 return BT->getKind() >= BuiltinType::Half &&
2193 BT->getKind() <= BuiltinType::Ibm128;
2194 if (const auto *CT = dyn_cast<ComplexType>(CanonicalType))
2195 return CT->getElementType()->isFloatingType();
2196 return false;
2197}
2198
2200 if (const auto *VT = dyn_cast<VectorType>(CanonicalType))
2201 return VT->getElementType()->isFloatingType();
2202 if (const auto *MT = dyn_cast<MatrixType>(CanonicalType))
2203 return MT->getElementType()->isFloatingType();
2204 return isFloatingType();
2205}
2206
2208 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2209 return BT->isFloatingPoint();
2210 return false;
2211}
2212
2213bool Type::isRealType() const {
2214 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2215 return BT->getKind() >= BuiltinType::Bool &&
2216 BT->getKind() <= BuiltinType::Ibm128;
2217 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
2218 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
2219 return isBitIntType();
2220}
2221
2223 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2224 return BT->getKind() >= BuiltinType::Bool &&
2225 BT->getKind() <= BuiltinType::Ibm128;
2226 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
2227 // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
2228 // If a body isn't seen by the time we get here, return false.
2229 //
2230 // C++0x: Enumerations are not arithmetic types. For now, just return
2231 // false for scoped enumerations since that will disable any
2232 // unwanted implicit conversions.
2233 return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete();
2234 return isa<ComplexType>(CanonicalType) || isBitIntType();
2235}
2236
2238 assert(isScalarType());
2239
2240 const Type *T = CanonicalType.getTypePtr();
2241 if (const auto *BT = dyn_cast<BuiltinType>(T)) {
2242 if (BT->getKind() == BuiltinType::Bool) return STK_Bool;
2243 if (BT->getKind() == BuiltinType::NullPtr) return STK_CPointer;
2244 if (BT->isInteger()) return STK_Integral;
2245 if (BT->isFloatingPoint()) return STK_Floating;
2246 if (BT->isFixedPointType()) return STK_FixedPoint;
2247 llvm_unreachable("unknown scalar builtin type");
2248 } else if (isa<PointerType>(T)) {
2249 return STK_CPointer;
2250 } else if (isa<BlockPointerType>(T)) {
2251 return STK_BlockPointer;
2252 } else if (isa<ObjCObjectPointerType>(T)) {
2253 return STK_ObjCObjectPointer;
2254 } else if (isa<MemberPointerType>(T)) {
2255 return STK_MemberPointer;
2256 } else if (isa<EnumType>(T)) {
2257 assert(cast<EnumType>(T)->getDecl()->isComplete());
2258 return STK_Integral;
2259 } else if (const auto *CT = dyn_cast<ComplexType>(T)) {
2260 if (CT->getElementType()->isRealFloatingType())
2261 return STK_FloatingComplex;
2262 return STK_IntegralComplex;
2263 } else if (isBitIntType()) {
2264 return STK_Integral;
2265 }
2266
2267 llvm_unreachable("unknown scalar type");
2268}
2269
2270/// Determines whether the type is a C++ aggregate type or C
2271/// aggregate or union type.
2272///
2273/// An aggregate type is an array or a class type (struct, union, or
2274/// class) that has no user-declared constructors, no private or
2275/// protected non-static data members, no base classes, and no virtual
2276/// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
2277/// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
2278/// includes union types.
2280 if (const auto *Record = dyn_cast<RecordType>(CanonicalType)) {
2281 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
2282 return ClassDecl->isAggregate();
2283
2284 return true;
2285 }
2286
2287 return isa<ArrayType>(CanonicalType);
2288}
2289
2290/// isConstantSizeType - Return true if this is not a variable sized type,
2291/// according to the rules of C99 6.7.5p3. It is not legal to call this on
2292/// incomplete types or dependent types.
2294 assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
2295 assert(!isDependentType() && "This doesn't make sense for dependent types");
2296 // The VAT must have a size, as it is known to be complete.
2297 return !isa<VariableArrayType>(CanonicalType);
2298}
2299
2300/// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
2301/// - a type that can describe objects, but which lacks information needed to
2302/// determine its size.
2304 if (Def)
2305 *Def = nullptr;
2306
2307 switch (CanonicalType->getTypeClass()) {
2308 default: return false;
2309 case Builtin:
2310 // Void is the only incomplete builtin type. Per C99 6.2.5p19, it can never
2311 // be completed.
2312 return isVoidType();
2313 case Enum: {
2314 EnumDecl *EnumD = cast<EnumType>(CanonicalType)->getDecl();
2315 if (Def)
2316 *Def = EnumD;
2317 return !EnumD->isComplete();
2318 }
2319 case Record: {
2320 // A tagged type (struct/union/enum/class) is incomplete if the decl is a
2321 // forward declaration, but not a full definition (C99 6.2.5p22).
2322 RecordDecl *Rec = cast<RecordType>(CanonicalType)->getDecl();
2323 if (Def)
2324 *Def = Rec;
2325 return !Rec->isCompleteDefinition();
2326 }
2327 case ConstantArray:
2328 case VariableArray:
2329 // An array is incomplete if its element type is incomplete
2330 // (C++ [dcl.array]p1).
2331 // We don't handle dependent-sized arrays (dependent types are never treated
2332 // as incomplete).
2333 return cast<ArrayType>(CanonicalType)->getElementType()
2334 ->isIncompleteType(Def);
2335 case IncompleteArray:
2336 // An array of unknown size is an incomplete type (C99 6.2.5p22).
2337 return true;
2338 case MemberPointer: {
2339 // Member pointers in the MS ABI have special behavior in
2340 // RequireCompleteType: they attach a MSInheritanceAttr to the CXXRecordDecl
2341 // to indicate which inheritance model to use.
2342 auto *MPTy = cast<MemberPointerType>(CanonicalType);
2343 const Type *ClassTy = MPTy->getClass();
2344 // Member pointers with dependent class types don't get special treatment.
2345 if (ClassTy->isDependentType())
2346 return false;
2347 const CXXRecordDecl *RD = ClassTy->getAsCXXRecordDecl();
2348 ASTContext &Context = RD->getASTContext();
2349 // Member pointers not in the MS ABI don't get special treatment.
2350 if (!Context.getTargetInfo().getCXXABI().isMicrosoft())
2351 return false;
2352 // The inheritance attribute might only be present on the most recent
2353 // CXXRecordDecl, use that one.
2355 // Nothing interesting to do if the inheritance attribute is already set.
2356 if (RD->hasAttr<MSInheritanceAttr>())
2357 return false;
2358 return true;
2359 }
2360 case ObjCObject:
2361 return cast<ObjCObjectType>(CanonicalType)->getBaseType()
2362 ->isIncompleteType(Def);
2363 case ObjCInterface: {
2364 // ObjC interfaces are incomplete if they are @class, not @interface.
2365 ObjCInterfaceDecl *Interface
2366 = cast<ObjCInterfaceType>(CanonicalType)->getDecl();
2367 if (Def)
2368 *Def = Interface;
2369 return !Interface->hasDefinition();
2370 }
2371 }
2372}
2373
2376 return true;
2377
2378 if (const BuiltinType *BT = getAs<BuiltinType>()) {
2379 switch (BT->getKind()) {
2380 // WebAssembly reference types
2381#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2382#include "clang/Basic/WebAssemblyReferenceTypes.def"
2383 return true;
2384 default:
2385 return false;
2386 }
2387 }
2388 return false;
2389}
2390
2392 if (const auto *BT = getAs<BuiltinType>())
2393 return BT->getKind() == BuiltinType::WasmExternRef;
2394 return false;
2395}
2396
2398 if (const auto *ATy = dyn_cast<ArrayType>(this))
2399 return ATy->getElementType().isWebAssemblyReferenceType();
2400
2401 if (const auto *PTy = dyn_cast<PointerType>(this))
2402 return PTy->getPointeeType().isWebAssemblyReferenceType();
2403
2404 return false;
2405}
2406
2408
2410 if (const BuiltinType *BT = getAs<BuiltinType>()) {
2411 switch (BT->getKind()) {
2412 // SVE Types
2413#define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2414#include "clang/Basic/AArch64SVEACLETypes.def"
2415 return true;
2416 default:
2417 return false;
2418 }
2419 }
2420 return false;
2421}
2422
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"
2428 return true;
2429 default:
2430 return false;
2431 }
2432 }
2433 return false;
2434}
2435
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:
2454 return true;
2455 default:
2456 return false;
2457 }
2458 }
2459 return false;
2460}
2461
2463 assert(isSveVLSBuiltinType() && "unsupported type!");
2464
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;
2471 else
2472 return Ctx.getBuiltinVectorTypeInfo(BTy).ElementType;
2473}
2474
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: \
2480 return NF == 1;
2481#include "clang/Basic/RISCVVTypes.def"
2482 default:
2483 return false;
2484 }
2485 }
2486 return false;
2487}
2488
2490 assert(isRVVVLSBuiltinType() && "unsupported type!");
2491
2492 const BuiltinType *BTy = castAs<BuiltinType>();
2493 return Ctx.getBuiltinVectorTypeInfo(BTy).ElementType;
2494}
2495
2496bool 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);
2500
2501 return isCXX98PODType(Context);
2502}
2503
2504bool 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.
2508 if (isNull())
2509 return false;
2510
2511 if ((*this)->isIncompleteArrayType())
2512 return Context.getBaseElementType(*this).isCXX98PODType(Context);
2513
2514 if ((*this)->isIncompleteType())
2515 return false;
2516
2518 return false;
2519
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);
2528
2529 case Type::ObjCObjectPointer:
2530 case Type::BlockPointer:
2531 case Type::Builtin:
2532 case Type::Complex:
2533 case Type::Pointer:
2534 case Type::MemberPointer:
2535 case Type::Vector:
2536 case Type::ExtVector:
2537 case Type::BitInt:
2538 return true;
2539
2540 case Type::Enum:
2541 return true;
2542
2543 case Type::Record:
2544 if (const auto *ClassDecl =
2545 dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
2546 return ClassDecl->isPOD();
2547
2548 // C struct/union is POD.
2549 return true;
2550 }
2551}
2552
2553bool 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.
2557 if (isNull())
2558 return false;
2559
2560 if ((*this)->isArrayType())
2561 return Context.getBaseElementType(*this).isTrivialType(Context);
2562
2563 if ((*this)->isSizelessBuiltinType())
2564 return true;
2565
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())
2569 return false;
2570
2572 return false;
2573
2574 QualType CanonicalType = getTypePtr()->CanonicalType;
2575 if (CanonicalType->isDependentType())
2576 return false;
2577
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
2581 // types.
2582
2583 // As an extension, Clang treats vector types as Scalar types.
2584 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
2585 return true;
2586 if (const auto *RT = CanonicalType->getAs<RecordType>()) {
2587 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2588 // C++20 [class]p6:
2589 // A trivial class is a class that is trivially copyable, and
2590 // has one or more eligible default constructors such that each is
2591 // trivial.
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();
2597 }
2598
2599 return true;
2600 }
2601
2602 // No other types can match.
2603 return false;
2604}
2605
2607 if ((*this)->isArrayType())
2608 return Context.getBaseElementType(*this).isTriviallyCopyableType(Context);
2609
2611 return false;
2612
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.
2617
2618 QualType CanonicalType = getCanonicalType();
2619 if (CanonicalType->isDependentType())
2620 return false;
2621
2622 if (CanonicalType->isSizelessBuiltinType())
2623 return true;
2624
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())
2628 return false;
2629
2630 // As an extension, Clang treats vector types as Scalar types.
2631 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
2632 return true;
2633
2634 if (const auto *RT = CanonicalType->getAs<RecordType>()) {
2635 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2636 if (!ClassDecl->isTriviallyCopyable()) return false;
2637 }
2638
2639 return true;
2640 }
2641
2642 // No other types can match.
2643 return false;
2644}
2645
2647 QualType BaseElementType = Context.getBaseElementType(*this);
2648
2649 if (BaseElementType->isIncompleteType()) {
2650 return false;
2651 } else if (const auto *RD = BaseElementType->getAsRecordDecl()) {
2652 return RD->canPassInRegisters();
2653 } else {
2655 case PCK_Trivial:
2656 return !isDestructedType();
2657 case PCK_ARCStrong:
2658 return true;
2659 default:
2660 return false;
2661 }
2662 }
2663}
2664
2665static bool
2667 if (Decl->isUnion())
2668 return false;
2669
2670 auto IsDefaultedOperatorEqualEqual = [&](const FunctionDecl *Function) {
2671 return Function->getOverloadedOperator() ==
2672 OverloadedOperatorKind::OO_EqualEqual &&
2673 Function->isDefaulted() && Function->getNumParams() > 0 &&
2674 (Function->getParamDecl(0)->getType()->isReferenceType() ||
2675 Decl->isTriviallyCopyable());
2676 };
2677
2678 if (llvm::none_of(Decl->methods(), IsDefaultedOperatorEqualEqual) &&
2679 llvm::none_of(Decl->friends(), [&](const FriendDecl *Friend) {
2680 if (NamedDecl *ND = Friend->getFriendDecl()) {
2681 return ND->isFunctionOrFunctionTemplate() &&
2682 IsDefaultedOperatorEqualEqual(ND->getAsFunction());
2683 }
2684 return false;
2685 }))
2686 return false;
2687
2688 return llvm::all_of(Decl->bases(),
2689 [](const CXXBaseSpecifier &BS) {
2690 if (const auto *RD = BS.getType()->getAsCXXRecordDecl())
2691 return HasNonDeletedDefaultedEqualityComparison(RD);
2692 return true;
2693 }) &&
2694 llvm::all_of(Decl->fields(), [](const FieldDecl *FD) {
2695 auto Type = FD->getType();
2696 if (Type->isArrayType())
2697 Type = Type->getBaseElementTypeUnsafe()->getCanonicalTypeUnqualified();
2698
2699 if (Type->isReferenceType() || Type->isEnumeralType())
2700 return false;
2701 if (const auto *RD = Type->getAsCXXRecordDecl())
2702 return HasNonDeletedDefaultedEqualityComparison(RD);
2703 return true;
2704 });
2705}
2706
2708 const ASTContext &Context) const {
2709 QualType CanonicalType = getCanonicalType();
2710 if (CanonicalType->isIncompleteType() || CanonicalType->isDependentType() ||
2711 CanonicalType->isEnumeralType() || CanonicalType->isArrayType())
2712 return false;
2713
2714 if (const auto *RD = CanonicalType->getAsCXXRecordDecl()) {
2716 return false;
2717 }
2718
2719 return Context.hasUniqueObjectRepresentations(
2720 CanonicalType, /*CheckIfTriviallyCopyable=*/false);
2721}
2722
2724 return !Context.getLangOpts().ObjCAutoRefCount &&
2725 Context.getLangOpts().ObjCWeak &&
2727}
2728
2731}
2732
2735}
2736
2739}
2740
2743}
2744
2747}
2748
2750 return getTypePtr()->isFunctionPointerType() &&
2752}
2753
2756 if (const auto *RT =
2757 getTypePtr()->getBaseElementTypeUnsafe()->getAs<RecordType>())
2758 if (RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize())
2759 return PDIK_Struct;
2760
2761 switch (getQualifiers().getObjCLifetime()) {
2763 return PDIK_ARCStrong;
2765 return PDIK_ARCWeak;
2766 default:
2767 return PDIK_Trivial;
2768 }
2769}
2770
2772 if (const auto *RT =
2773 getTypePtr()->getBaseElementTypeUnsafe()->getAs<RecordType>())
2774 if (RT->getDecl()->isNonTrivialToPrimitiveCopy())
2775 return PCK_Struct;
2776
2778 switch (Qs.getObjCLifetime()) {
2780 return PCK_ARCStrong;
2782 return PCK_ARCWeak;
2783 default:
2785 }
2786}
2787
2791}
2792
2793bool Type::isLiteralType(const ASTContext &Ctx) const {
2794 if (isDependentType())
2795 return false;
2796
2797 // C++1y [basic.types]p10:
2798 // A type is a literal type if it is:
2799 // -- cv void; or
2800 if (Ctx.getLangOpts().CPlusPlus14 && isVoidType())
2801 return true;
2802
2803 // C++11 [basic.types]p10:
2804 // A type is a literal type if it is:
2805 // [...]
2806 // -- an array of literal type other than an array of runtime bound; or
2807 if (isVariableArrayType())
2808 return false;
2809 const Type *BaseTy = getBaseElementTypeUnsafe();
2810 assert(BaseTy && "NULL element type");
2811
2812 // Return false for incomplete types after skipping any incomplete array
2813 // types; those are expressly allowed by the standard and thus our API.
2814 if (BaseTy->isIncompleteType())
2815 return false;
2816
2817 // C++11 [basic.types]p10:
2818 // A type is a literal type if it is:
2819 // -- a scalar type; or
2820 // As an extension, Clang treats vector types and complex types as
2821 // literal types.
2822 if (BaseTy->isScalarType() || BaseTy->isVectorType() ||
2823 BaseTy->isAnyComplexType())
2824 return true;
2825 // -- a reference type; or
2826 if (BaseTy->isReferenceType())
2827 return true;
2828 // -- a class type that has all of the following properties:
2829 if (const auto *RT = BaseTy->getAs<RecordType>()) {
2830 // -- a trivial destructor,
2831 // -- every constructor call and full-expression in the
2832 // brace-or-equal-initializers for non-static data members (if any)
2833 // is a constant expression,
2834 // -- it is an aggregate type or has at least one constexpr
2835 // constructor or constructor template that is not a copy or move
2836 // constructor, and
2837 // -- all non-static data members and base classes of literal types
2838 //
2839 // We resolve DR1361 by ignoring the second bullet.
2840 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2841 return ClassDecl->isLiteral();
2842
2843 return true;
2844 }
2845
2846 // We treat _Atomic T as a literal type if T is a literal type.
2847 if (const auto *AT = BaseTy->getAs<AtomicType>())
2848 return AT->getValueType()->isLiteralType(Ctx);
2849
2850 // If this type hasn't been deduced yet, then conservatively assume that
2851 // it'll work out to be a literal type.
2852 if (isa<AutoType>(BaseTy->getCanonicalTypeInternal()))
2853 return true;
2854
2855 return false;
2856}
2857
2859 // C++20 [temp.param]p6:
2860 // A structural type is one of the following:
2861 // -- a scalar type; or
2862 // -- a vector type [Clang extension]; or
2863 if (isScalarType() || isVectorType())
2864 return true;
2865 // -- an lvalue reference type; or
2867 return true;
2868 // -- a literal class type [...under some conditions]
2869 if (const CXXRecordDecl *RD = getAsCXXRecordDecl())
2870 return RD->isStructural();
2871 return false;
2872}
2873
2875 if (isDependentType())
2876 return false;
2877
2878 // C++0x [basic.types]p9:
2879 // Scalar types, standard-layout class types, arrays of such types, and
2880 // cv-qualified versions of these types are collectively called
2881 // standard-layout types.
2882 const Type *BaseTy = getBaseElementTypeUnsafe();
2883 assert(BaseTy && "NULL element type");
2884
2885 // Return false for incomplete types after skipping any incomplete array
2886 // types which are expressly allowed by the standard and thus our API.
2887 if (BaseTy->isIncompleteType())
2888 return false;
2889
2890 // As an extension, Clang treats vector types as Scalar types.
2891 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
2892 if (const auto *RT = BaseTy->getAs<RecordType>()) {
2893 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2894 if (!ClassDecl->isStandardLayout())
2895 return false;
2896
2897 // Default to 'true' for non-C++ class types.
2898 // FIXME: This is a bit dubious, but plain C structs should trivially meet
2899 // all the requirements of standard layout classes.
2900 return true;
2901 }
2902
2903 // No other types can match.
2904 return false;
2905}
2906
2907// This is effectively the intersection of isTrivialType and
2908// isStandardLayoutType. We implement it directly to avoid redundant
2909// conversions from a type to a CXXRecordDecl.
2910bool QualType::isCXX11PODType(const ASTContext &Context) const {
2911 const Type *ty = getTypePtr();
2912 if (ty->isDependentType())
2913 return false;
2914
2916 return false;
2917
2918 // C++11 [basic.types]p9:
2919 // Scalar types, POD classes, arrays of such types, and cv-qualified
2920 // versions of these types are collectively called trivial types.
2921 const Type *BaseTy = ty->getBaseElementTypeUnsafe();
2922 assert(BaseTy && "NULL element type");
2923
2924 if (BaseTy->isSizelessBuiltinType())
2925 return true;
2926
2927 // Return false for incomplete types after skipping any incomplete array
2928 // types which are expressly allowed by the standard and thus our API.
2929 if (BaseTy->isIncompleteType())
2930 return false;
2931
2932 // As an extension, Clang treats vector types as Scalar types.
2933 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
2934 if (const auto *RT = BaseTy->getAs<RecordType>()) {
2935 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2936 // C++11 [class]p10:
2937 // A POD struct is a non-union class that is both a trivial class [...]
2938 if (!ClassDecl->isTrivial()) return false;
2939
2940 // C++11 [class]p10:
2941 // A POD struct is a non-union class that is both a trivial class and
2942 // a standard-layout class [...]
2943 if (!ClassDecl->isStandardLayout()) return false;
2944
2945 // C++11 [class]p10:
2946 // A POD struct is a non-union class that is both a trivial class and
2947 // a standard-layout class, and has no non-static data members of type
2948 // non-POD struct, non-POD union (or array of such types). [...]
2949 //
2950 // We don't directly query the recursive aspect as the requirements for
2951 // both standard-layout classes and trivial classes apply recursively
2952 // already.
2953 }
2954
2955 return true;
2956 }
2957
2958 // No other types can match.
2959 return false;
2960}
2961
2962bool Type::isNothrowT() const {
2963 if (const auto *RD = getAsCXXRecordDecl()) {
2964 IdentifierInfo *II = RD->getIdentifier();
2965 if (II && II->isStr("nothrow_t") && RD->isInStdNamespace())
2966 return true;
2967 }
2968 return false;
2969}
2970
2971bool Type::isAlignValT() const {
2972 if (const auto *ET = getAs<EnumType>()) {
2973 IdentifierInfo *II = ET->getDecl()->getIdentifier();
2974 if (II && II->isStr("align_val_t") && ET->getDecl()->isInStdNamespace())
2975 return true;
2976 }
2977 return false;
2978}
2979
2981 if (const auto *ET = getAs<EnumType>()) {
2982 IdentifierInfo *II = ET->getDecl()->getIdentifier();
2983 if (II && II->isStr("byte") && ET->getDecl()->isInStdNamespace())
2984 return true;
2985 }
2986 return false;
2987}
2988
2990 // Note that this intentionally does not use the canonical type.
2991 switch (getTypeClass()) {
2992 case Builtin:
2993 case Record:
2994 case Enum:
2995 case Typedef:
2996 case Complex:
2997 case TypeOfExpr:
2998 case TypeOf:
2999 case TemplateTypeParm:
3000 case SubstTemplateTypeParm:
3001 case TemplateSpecialization:
3002 case Elaborated:
3003 case DependentName:
3004 case DependentTemplateSpecialization:
3005 case ObjCInterface:
3006 case ObjCObject:
3007 return true;
3008 default:
3009 return false;
3010 }
3011}
3012
3015 switch (TypeSpec) {
3016 default: return ETK_None;
3017 case TST_typename: return ETK_Typename;
3018 case TST_class: return ETK_Class;
3019 case TST_struct: return ETK_Struct;
3020 case TST_interface: return ETK_Interface;
3021 case TST_union: return ETK_Union;
3022 case TST_enum: return ETK_Enum;
3023 }
3024}
3025
3028 switch(TypeSpec) {
3029 case TST_class: return TTK_Class;
3030 case TST_struct: return TTK_Struct;
3031 case TST_interface: return TTK_Interface;
3032 case TST_union: return TTK_Union;
3033 case TST_enum: return TTK_Enum;
3034 }
3035
3036 llvm_unreachable("Type specifier is not a tag type kind.");
3037}
3038
3041 switch (Kind) {
3042 case TTK_Class: return ETK_Class;
3043 case TTK_Struct: return ETK_Struct;
3044 case TTK_Interface: return ETK_Interface;
3045 case TTK_Union: return ETK_Union;
3046 case TTK_Enum: return ETK_Enum;
3047 }
3048 llvm_unreachable("Unknown tag type kind.");
3049}
3050
3053 switch (Keyword) {
3054 case ETK_Class: return TTK_Class;
3055 case ETK_Struct: return TTK_Struct;
3056 case ETK_Interface: return TTK_Interface;
3057 case ETK_Union: return TTK_Union;
3058 case ETK_Enum: return TTK_Enum;
3059 case ETK_None: // Fall through.
3060 case ETK_Typename:
3061 llvm_unreachable("Elaborated type keyword is not a tag type kind.");
3062 }
3063 llvm_unreachable("Unknown elaborated type keyword.");
3064}
3065
3066bool
3068 switch (Keyword) {
3069 case ETK_None:
3070 case ETK_Typename:
3071 return false;
3072 case ETK_Class:
3073 case ETK_Struct:
3074 case ETK_Interface:
3075 case ETK_Union:
3076 case ETK_Enum:
3077 return true;
3078 }
3079 llvm_unreachable("Unknown elaborated type keyword.");
3080}
3081
3083 switch (Keyword) {
3084 case ETK_None: return {};
3085 case ETK_Typename: return "typename";
3086 case ETK_Class: return "class";
3087 case ETK_Struct: return "struct";
3088 case ETK_Interface: return "__interface";
3089 case ETK_Union: return "union";
3090 case ETK_Enum: return "enum";
3091 }
3092
3093 llvm_unreachable("Unknown elaborated type keyword.");
3094}
3095
3096DependentTemplateSpecializationType::DependentTemplateSpecializationType(
3098 const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args, QualType Canon)
3099 : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon,
3100 TypeDependence::DependentInstantiation |
3101 (NNS ? toTypeDependence(NNS->getDependence())
3102 : TypeDependence::None)),
3103 NNS(NNS), Name(Name) {
3104 DependentTemplateSpecializationTypeBits.NumArgs = Args.size();
3105 assert((!NNS || NNS->isDependent()) &&
3106 "DependentTemplateSpecializatonType requires dependent qualifier");
3107 auto *ArgBuffer = const_cast<TemplateArgument *>(template_arguments().data());
3108 for (const TemplateArgument &Arg : Args) {
3109 addDependence(toTypeDependence(Arg.getDependence() &
3110 TemplateArgumentDependence::UnexpandedPack));
3111
3112 new (ArgBuffer++) TemplateArgument(Arg);
3113 }
3114}
3115
3116void
3118 const ASTContext &Context,
3119 ElaboratedTypeKeyword Keyword,
3120 NestedNameSpecifier *Qualifier,
3121 const IdentifierInfo *Name,
3123 ID.AddInteger(Keyword);
3124 ID.AddPointer(Qualifier);
3125 ID.AddPointer(Name);
3126 for (const TemplateArgument &Arg : Args)
3127 Arg.Profile(ID, Context);
3128}
3129
3131 ElaboratedTypeKeyword Keyword;
3132 if (const auto *Elab = dyn_cast<ElaboratedType>(this))
3133 Keyword = Elab->getKeyword();
3134 else if (const auto *DepName = dyn_cast<DependentNameType>(this))
3135 Keyword = DepName->getKeyword();
3136 else if (const auto *DepTST =
3137 dyn_cast<DependentTemplateSpecializationType>(this))
3138 Keyword = DepTST->getKeyword();
3139 else
3140 return false;
3141
3143}
3144
3145const char *Type::getTypeClassName() const {
3146 switch (TypeBits.TC) {
3147#define ABSTRACT_TYPE(Derived, Base)
3148#define TYPE(Derived, Base) case Derived: return #Derived;
3149#include "clang/AST/TypeNodes.inc"
3150 }
3151
3152 llvm_unreachable("Invalid type class.");
3153}
3154
3155StringRef BuiltinType::getName(const PrintingPolicy &Policy) const {
3156 switch (getKind()) {
3157 case Void:
3158 return "void";
3159 case Bool:
3160 return Policy.Bool ? "bool" : "_Bool";
3161 case Char_S:
3162 return "char";
3163 case Char_U:
3164 return "char";
3165 case SChar:
3166 return "signed char";
3167 case Short:
3168 return "short";
3169 case Int:
3170 return "int";
3171 case Long:
3172 return "long";
3173 case LongLong:
3174 return "long long";
3175 case Int128:
3176 return "__int128";
3177 case UChar:
3178 return "unsigned char";
3179 case UShort:
3180 return "unsigned short";
3181 case UInt:
3182 return "unsigned int";
3183 case ULong:
3184 return "unsigned long";
3185 case ULongLong:
3186 return "unsigned long long";
3187 case UInt128:
3188 return "unsigned __int128";
3189 case Half:
3190 return Policy.Half ? "half" : "__fp16";
3191 case BFloat16:
3192 return "__bf16";
3193 case Float:
3194 return "float";
3195 case Double:
3196 return "double";
3197 case LongDouble:
3198 return "long double";
3199 case ShortAccum:
3200 return "short _Accum";
3201 case Accum:
3202 return "_Accum";
3203 case LongAccum:
3204 return "long _Accum";
3205 case UShortAccum:
3206 return "unsigned short _Accum";
3207 case UAccum:
3208 return "unsigned _Accum";
3209 case ULongAccum:
3210 return "unsigned long _Accum";
3211 case BuiltinType::ShortFract:
3212 return "short _Fract";
3213 case BuiltinType::Fract:
3214 return "_Fract";
3215 case BuiltinType::LongFract:
3216 return "long _Fract";
3217 case BuiltinType::UShortFract:
3218 return "unsigned short _Fract";
3219 case BuiltinType::UFract:
3220 return "unsigned _Fract";
3221 case BuiltinType::ULongFract:
3222 return "unsigned long _Fract";
3223 case BuiltinType::SatShortAccum:
3224 return "_Sat short _Accum";
3225 case BuiltinType::SatAccum:
3226 return "_Sat _Accum";
3227 case BuiltinType::SatLongAccum:
3228 return "_Sat long _Accum";
3229 case BuiltinType::SatUShortAccum:
3230 return "_Sat unsigned short _Accum";
3231 case BuiltinType::SatUAccum:
3232 return "_Sat unsigned _Accum";
3233 case BuiltinType::SatULongAccum:
3234 return "_Sat unsigned long _Accum";
3235 case BuiltinType::SatShortFract:
3236 return "_Sat short _Fract";
3237 case BuiltinType::SatFract:
3238 return "_Sat _Fract";
3239 case BuiltinType::SatLongFract:
3240 return "_Sat long _Fract";
3241 case BuiltinType::SatUShortFract:
3242 return "_Sat unsigned short _Fract";
3243 case BuiltinType::SatUFract:
3244 return "_Sat unsigned _Fract";
3245 case BuiltinType::SatULongFract:
3246 return "_Sat unsigned long _Fract";
3247 case Float16:
3248 return "_Float16";
3249 case Float128:
3250 return "__float128";
3251 case Ibm128:
3252 return "__ibm128";
3253 case WChar_S:
3254 case WChar_U:
3255 return Policy.MSWChar ? "__wchar_t" : "wchar_t";
3256 case Char8:
3257 return "char8_t";
3258 case Char16:
3259 return "char16_t";
3260 case Char32:
3261 return "char32_t";
3262 case NullPtr:
3263 return Policy.NullptrTypeInNamespace ? "std::nullptr_t" : "nullptr_t";
3264 case Overload:
3265 return "<overloaded function type>";
3266 case BoundMember:
3267 return "<bound member function type>";
3268 case PseudoObject:
3269 return "<pseudo-object type>";
3270 case Dependent:
3271 return "<dependent type>";
3272 case UnknownAny:
3273 return "<unknown type>";
3274 case ARCUnbridgedCast:
3275 return "<ARC unbridged cast type>";
3276 case BuiltinFn:
3277 return "<builtin fn type>";
3278 case ObjCId:
3279 return "id";
3280 case ObjCClass:
3281 return "Class";
3282 case ObjCSel:
3283 return "SEL";
3284#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3285 case Id: \
3286 return "__" #Access " " #ImgType "_t";
3287#include "clang/Basic/OpenCLImageTypes.def"
3288 case OCLSampler:
3289 return "sampler_t";
3290 case OCLEvent:
3291 return "event_t";
3292 case OCLClkEvent:
3293 return "clk_event_t";
3294 case OCLQueue:
3295 return "queue_t";
3296 case OCLReserveID:
3297 return "reserve_id_t";
3298 case IncompleteMatrixIdx:
3299 return "<incomplete matrix index type>";
3300 case OMPArraySection:
3301 return "<OpenMP array section type>";
3302 case OMPArrayShaping:
3303 return "<OpenMP array shaping type>";
3304 case OMPIterator:
3305 return "<OpenMP iterator type>";
3306#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3307 case Id: \
3308 return #ExtType;
3309#include "clang/Basic/OpenCLExtensionTypes.def"
3310#define SVE_TYPE(Name, Id, SingletonId) \
3311 case Id: \
3312 return Name;
3313#include "clang/Basic/AArch64SVEACLETypes.def"
3314#define PPC_VECTOR_TYPE(Name, Id, Size) \
3315 case Id: \
3316 return #Name;
3317#include "clang/Basic/PPCTypes.def"
3318#define RVV_TYPE(Name, Id, SingletonId) \
3319 case Id: \
3320 return Name;
3321#include "clang/Basic/RISCVVTypes.def"
3322#define WASM_TYPE(Name, Id, SingletonId) \
3323 case Id: \
3324 return Name;
3325#include "clang/Basic/WebAssemblyReferenceTypes.def"
3326 }
3327
3328 llvm_unreachable("Invalid builtin type.");
3329}
3330
3332 // We never wrap type sugar around a PackExpansionType.
3333 if (auto *PET = dyn_cast<PackExpansionType>(getTypePtr()))
3334 return PET->getPattern();
3335 return *this;
3336}
3337
3339 if (const auto *RefType = getTypePtr()->getAs<ReferenceType>())
3340 return RefType->getPointeeType();
3341
3342 // C++0x [basic.lval]:
3343 // Class prvalues can have cv-qualified types; non-class prvalues always
3344 // have cv-unqualified types.
3345 //
3346 // See also C99 6.3.2.1p2.
3347 if (!Context.getLangOpts().CPlusPlus ||
3348 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
3349 return getUnqualifiedType();
3350
3351 return *this;
3352}
3353
3355 switch (CC) {
3356 case CC_C: return "cdecl";
3357 case CC_X86StdCall: return "stdcall";
3358 case CC_X86FastCall: return "fastcall";
3359 case CC_X86ThisCall: return "thiscall";
3360 case CC_X86Pascal: return "pascal";
3361 case CC_X86VectorCall: return "vectorcall";
3362 case CC_Win64: return "ms_abi";
3363 case CC_X86_64SysV: return "sysv_abi";
3364 case CC_X86RegCall : return "regcall";
3365 case CC_AAPCS: return "aapcs";
3366 case CC_AAPCS_VFP: return "aapcs-vfp";
3367 case CC_AArch64VectorCall: return "aarch64_vector_pcs";
3368 case CC_AArch64SVEPCS: return "aarch64_sve_pcs";
3369 case CC_AMDGPUKernelCall: return "amdgpu_kernel";
3370 case CC_IntelOclBicc: return "intel_ocl_bicc";
3371 case CC_SpirFunction: return "spir_function";
3372 case CC_OpenCLKernel: return "opencl_kernel";
3373 case CC_Swift: return "swiftcall";
3374 case CC_SwiftAsync: return "swiftasynccall";
3375 case CC_PreserveMost: return "preserve_most";
3376 case CC_PreserveAll: return "preserve_all";
3377 }
3378
3379 llvm_unreachable("Invalid calling convention.");
3380}
3381
3382FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> params,
3383 QualType canonical,
3384 const ExtProtoInfo &epi)
3385 : FunctionType(FunctionProto, result, canonical, result->getDependence(),
3386 epi.ExtInfo) {
3387 FunctionTypeBits.FastTypeQuals = epi.TypeQuals.getFastQualifiers();
3388 FunctionTypeBits.RefQualifier = epi.RefQualifier;
3389 FunctionTypeBits.NumParams = params.size();
3390 assert(getNumParams() == params.size() && "NumParams overflow!");
3391 FunctionTypeBits.ExceptionSpecType = epi.ExceptionSpec.Type;
3392 FunctionTypeBits.HasExtParameterInfos = !!epi.ExtParameterInfos;
3393 FunctionTypeBits.Variadic = epi.Variadic;
3394 FunctionTypeBits.HasTrailingReturn = epi.HasTrailingReturn;
3395
3396 if (epi.requiresFunctionProtoTypeExtraBitfields()) {
3397 FunctionTypeBits.HasExtraBitfields = true;
3398 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
3399 ExtraBits = FunctionTypeExtraBitfields();
3400 } else {
3401 FunctionTypeBits.HasExtraBitfields = false;
3402 }
3403
3404
3405 // Fill in the trailing argument array.
3406 auto *argSlot = getTrailingObjects<QualType>();
3407 for (unsigned i = 0; i != getNumParams(); ++i) {
3408 addDependence(params[i]->getDependence() &
3409 ~TypeDependence::VariablyModified);
3410 argSlot[i] = params[i];
3411 }
3412
3413 // Propagate the SME ACLE attributes.
3414 if (epi.AArch64SMEAttributes != SME_NormalFunction) {
3415 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
3416 assert(epi.AArch64SMEAttributes <= SME_AttributeMask &&
3417 "Not enough bits to encode SME attributes");
3418 ExtraBits.AArch64SMEAttributes = epi.AArch64SMEAttributes;
3419 }
3420
3421 // Fill in the exception type array if present.
3422 if (getExceptionSpecType() == EST_Dynamic) {
3423 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
3424 size_t NumExceptions = epi.ExceptionSpec.Exceptions.size();
3425 assert(NumExceptions <= 1023 && "Not enough bits to encode exceptions");
3426 ExtraBits.NumExceptionType = NumExceptions;
3427
3428 assert(hasExtraBitfields() && "missing trailing extra bitfields!");
3429 auto *exnSlot =
3430 reinterpret_cast<QualType *>(getTrailingObjects<ExceptionType>());
3431 unsigned I = 0;
3432 for (QualType ExceptionType : epi.ExceptionSpec.Exceptions) {
3433 // Note that, before C++17, a dependent exception specification does
3434 // *not* make a type dependent; it's not even part of the C++ type
3435 // system.
3437 ExceptionType->getDependence() &
3438 (TypeDependence::Instantiation | TypeDependence::UnexpandedPack));
3439
3440 exnSlot[I++] = ExceptionType;
3441 }
3442 }
3443 // Fill in the Expr * in the exception specification if present.
3444 else if (isComputedNoexcept(getExceptionSpecType())) {
3445 assert(epi.ExceptionSpec.NoexceptExpr && "computed noexcept with no expr");
3446 assert((getExceptionSpecType() == EST_DependentNoexcept) ==
3447 epi.ExceptionSpec.NoexceptExpr->isValueDependent());
3448
3449 // Store the noexcept expression and context.
3450 *getTrailingObjects<Expr *>() = epi.ExceptionSpec.NoexceptExpr;
3451
3453 toTypeDependence(epi.ExceptionSpec.NoexceptExpr->getDependence()) &
3454 (TypeDependence::Instantiation | TypeDependence::UnexpandedPack));
3455 }
3456 // Fill in the FunctionDecl * in the exception specification if present.
3457 else if (getExceptionSpecType() == EST_Uninstantiated) {
3458 // Store the function decl from which we will resolve our
3459 // exception specification.
3460 auto **slot = getTrailingObjects<FunctionDecl *>();
3461 slot[0] = epi.ExceptionSpec.SourceDecl;
3462 slot[1] = epi.ExceptionSpec.SourceTemplate;
3463 // This exception specification doesn't make the type dependent, because
3464 // it's not instantiated as part of instantiating the type.
3465 } else if (getExceptionSpecType() == EST_Unevaluated) {
3466 // Store the function decl from which we will resolve our
3467 // exception specification.
3468 auto **slot = getTrailingObjects<FunctionDecl *>();
3469 slot[0] = epi.ExceptionSpec.SourceDecl;
3470 }
3471
3472 // If this is a canonical type, and its exception specification is dependent,
3473 // then it's a dependent type. This only happens in C++17 onwards.
3474 if (isCanonicalUnqualified()) {
3475 if (getExceptionSpecType() == EST_Dynamic ||
3476 getExceptionSpecType() == EST_DependentNoexcept) {
3477 assert(hasDependentExceptionSpec() && "type should not be canonical");
3478 addDependence(TypeDependence::DependentInstantiation);
3479 }
3480 } else if (getCanonicalTypeInternal()->isDependentType()) {
3481 // Ask our canonical type whether our exception specification was dependent.
3482 addDependence(TypeDependence::DependentInstantiation);
3483 }
3484
3485 // Fill in the extra parameter info if present.
3486 if (epi.ExtParameterInfos) {
3487 auto *extParamInfos = getTrailingObjects<ExtParameterInfo>();
3488 for (unsigned i = 0; i != getNumParams(); ++i)
3489 extParamInfos[i] = epi.ExtParameterInfos[i];
3490 }
3491
3492 if (epi.TypeQuals.hasNonFastQualifiers()) {
3493 FunctionTypeBits.HasExtQuals = 1;
3494 *getTrailingObjects<Qualifiers>() = epi.TypeQuals;
3495 } else {
3496 FunctionTypeBits.HasExtQuals = 0;
3497 }
3498
3499 // Fill in the Ellipsis location info if present.
3500 if (epi.Variadic) {
3501 auto &EllipsisLoc = *getTrailingObjects<SourceLocation>();
3502 EllipsisLoc = epi.EllipsisLoc;
3503 }
3504}
3505
3507 if (Expr *NE = getNoexceptExpr())
3508 return NE->isValueDependent();
3509 for (QualType ET : exceptions())
3510 // A pack expansion with a non-dependent pattern is still dependent,
3511 // because we don't know whether the pattern is in the exception spec
3512 // or not (that depends on whether the pack has 0 expansions).
3513 if (ET->isDependentType() || ET->getAs<PackExpansionType>())
3514 return true;
3515 return false;
3516}
3517
3519 if (Expr *NE = getNoexceptExpr())
3520 return NE->isInstantiationDependent();
3521 for (QualType ET : exceptions())
3522 if (ET->isInstantiationDependentType())
3523 return true;
3524 return false;
3525}
3526
3528 switch (getExceptionSpecType()) {
3529 case EST_Unparsed:
3530 case EST_Unevaluated:
3531 llvm_unreachable("should not call this with unresolved exception specs");
3532
3533 case EST_DynamicNone:
3534 case EST_BasicNoexcept:
3535 case EST_NoexceptTrue:
3536 case EST_NoThrow:
3537 return CT_Cannot;
3538
3539 case EST_None:
3540 case EST_MSAny:
3541 case EST_NoexceptFalse:
3542 return CT_Can;
3543
3544 case EST_Dynamic:
3545 // A dynamic exception specification is throwing unless every exception
3546 // type is an (unexpanded) pack expansion type.
3547 for (unsigned I = 0; I != getNumExceptions(); ++I)
3549 return CT_Can;
3550 return CT_Dependent;
3551
3552 case EST_Uninstantiated:
3554 return CT_Dependent;
3555 }
3556
3557 llvm_unreachable("unexpected exception specification kind");
3558}
3559
3561 for (unsigned ArgIdx = getNumParams(); ArgIdx; --ArgIdx)
3562 if (isa<PackExpansionType>(getParamType(ArgIdx - 1)))
3563 return true;
3564
3565 return false;
3566}
3567
3568void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
3569 const QualType *ArgTys, unsigned NumParams,
3570 const ExtProtoInfo &epi,
3571 const ASTContext &Context, bool Canonical) {
3572 // We have to be careful not to get ambiguous profile encodings.
3573 // Note that valid type pointers are never ambiguous with anything else.
3574 //
3575 // The encoding grammar begins:
3576 // type type* bool int bool
3577 // If that final bool is true, then there is a section for the EH spec:
3578 // bool type*
3579 // This is followed by an optional "consumed argument" section of the
3580 // same length as the first type sequence:
3581 // bool*
3582 // This is followed by the ext info:
3583 // int
3584 // Finally we have a trailing return type flag (bool)
3585 // combined with AArch64 SME Attributes, to save space:
3586 // int
3587 //
3588 // There is no ambiguity between the consumed arguments and an empty EH
3589 // spec because of the leading 'bool' which unambiguously indicates
3590 // whether the following bool is the EH spec or part of the arguments.
3591
3592 ID.AddPointer(Result.getAsOpaquePtr());
3593 for (unsigned i = 0; i != NumParams; ++i)
3594 ID.AddPointer(ArgTys[i].getAsOpaquePtr());
3595 // This method is relatively performance sensitive, so as a performance
3596 // shortcut, use one AddInteger call instead of four for the next four
3597 // fields.
3598 assert(!(unsigned(epi.Variadic) & ~1) &&
3599 !(unsigned(epi.RefQualifier) & ~3) &&
3600 !(unsigned(epi.ExceptionSpec.Type) & ~15) &&
3601 "Values larger than expected.");
3602 ID.AddInteger(unsigned(epi.Variadic) +
3603 (epi.RefQualifier << 1) +
3604 (epi.ExceptionSpec.Type << 3));
3605 ID.Add(epi.TypeQuals);
3606 if (epi.ExceptionSpec.Type == EST_Dynamic) {
3607 for (QualType Ex : epi.ExceptionSpec.Exceptions)
3608 ID.AddPointer(Ex.getAsOpaquePtr());
3609 } else if (isComputedNoexcept(epi.ExceptionSpec.Type)) {
3610 epi.ExceptionSpec.NoexceptExpr->Profile(ID, Context, Canonical);
3611 } else if (epi.ExceptionSpec.Type == EST_Uninstantiated ||
3612 epi.ExceptionSpec.Type == EST_Unevaluated) {
3613 ID.AddPointer(epi.ExceptionSpec.SourceDecl->getCanonicalDecl());
3614 }
3615 if (epi.ExtParameterInfos) {
3616 for (unsigned i = 0; i != NumParams; ++i)
3617 ID.AddInteger(epi.ExtParameterInfos[i].getOpaqueValue());
3618 }
3619
3620 epi.ExtInfo.Profile(ID);
3621 ID.AddInteger((epi.AArch64SMEAttributes << 1) | epi.HasTrailingReturn);
3622}
3623
3624void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
3625 const ASTContext &Ctx) {
3628}
3629
3630TypedefType::TypedefType(TypeClass tc, const TypedefNameDecl *D,
3631 QualType Underlying, QualType can)
3632 : Type(tc, can, toSemanticDependence(can->getDependence())),
3633 Decl(const_cast<TypedefNameDecl *>(D)) {
3634 assert(!isa<TypedefType>(can) && "Invalid canonical type");
3635 TypedefBits.hasTypeDifferentFromDecl = !Underlying.isNull();
3636 if (!typeMatchesDecl())
3637 *getTrailingObjects<QualType>() = Underlying;
3638}
3639
3641 return typeMatchesDecl() ? Decl->getUnderlyingType()
3642 : *getTrailingObjects<QualType>();
3643}
3644
3645UsingType::UsingType(const UsingShadowDecl *Found, QualType Underlying,
3646 QualType Canon)
3647 : Type(Using, Canon, toSemanticDependence(Canon->getDependence())),
3648 Found(const_cast<UsingShadowDecl *>(Found)) {
3649 UsingBits.hasTypeDifferentFromDecl = !Underlying.isNull();
3650 if (!typeMatchesDecl())
3651 *getTrailingObjects<QualType>() = Underlying;
3652}
3653
3655 return typeMatchesDecl()
3656 ? QualType(
3657 cast<TypeDecl>(Found->getTargetDecl())->getTypeForDecl(), 0)
3658 : *getTrailingObjects<QualType>();
3659}
3660
3662
3664 // Step over MacroQualifiedTypes from the same macro to find the type
3665 // ultimately qualified by the macro qualifier.
3666 QualType Inner = cast<AttributedType>(getUnderlyingType())->getModifiedType();
3667 while (auto *InnerMQT = dyn_cast<MacroQualifiedType>(Inner)) {
3668 if (InnerMQT->getMacroIdentifier() != getMacroIdentifier())
3669 break;
3670 Inner = InnerMQT->getModifiedType();
3671 }
3672 return Inner;
3673}
3674
3676 : Type(TypeOfExpr,
3677 // We have to protect against 'Can' being invalid through its
3678 // default argument.
3679 Kind == TypeOfKind::Unqualified && !Can.isNull()
3680 ? Can.getAtomicUnqualifiedType()
3681 : Can,
3682 toTypeDependence(E->getDependence()) |
3683 (E->getType()->getDependence() &
3684 TypeDependence::VariablyModified)),
3685 TOExpr(E) {
3686 TypeOfBits.IsUnqual = Kind == TypeOfKind::Unqualified;
3687}
3688
3690 return !TOExpr->isTypeDependent();
3691}
3692
3694 if (isSugared()) {
3696 return TypeOfBits.IsUnqual ? QT.getAtomicUnqualifiedType() : QT;
3697 }
3698 return QualType(this, 0);
3699}
3700
3701void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
3702 const ASTContext &Context, Expr *E,
3703 bool IsUnqual) {
3704 E->Profile(ID, Context, true);
3705 ID.AddBoolean(IsUnqual);
3706}
3707
3709 // C++11 [temp.type]p2: "If an expression e involves a template parameter,
3710 // decltype(e) denotes a unique dependent type." Hence a decltype type is
3711 // type-dependent even if its expression is only instantiation-dependent.
3712 : Type(Decltype, can,
3713 toTypeDependence(E->getDependence()) |
3714 (E->isInstantiationDependent() ? TypeDependence::Dependent
3715 : TypeDependence::None) |
3716 (E->getType()->getDependence() &
3717 TypeDependence::VariablyModified)),
3718 E(E), UnderlyingType(underlyingType) {}
3719
3721
3723 if (isSugared())
3724 return getUnderlyingType();
3725
3726 return QualType(this, 0);
3727}
3728
3730 : DecltypeType(E, Context.DependentTy), Context(Context) {}
3731
3732void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
3733 const ASTContext &Context, Expr *E) {
3734 E->Profile(ID, Context, true);
3735}
3736
3738 QualType UnderlyingType, UTTKind UKind,
3739 QualType CanonicalType)
3740 : Type(UnaryTransform, CanonicalType, BaseType->getDependence()),
3741 BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind) {}
3742
3744 QualType BaseType,
3745 UTTKind UKind)
3746 : UnaryTransformType(BaseType, C.DependentTy, UKind, QualType()) {}
3747
3749 : Type(TC, can,
3750 D->isDependentType() ? TypeDependence::DependentInstantiation
3751 : TypeDependence::None),
3752 decl(const_cast<TagDecl *>(D)) {}
3753
3755 for (auto *I : decl->redecls()) {
3756 if (I->isCompleteDefinition() || I->isBeingDefined())
3757 return I;
3758 }
3759 // If there's no definition (not even in progress), return what we have.
3760 return decl;
3761}
3762
3764 return getInterestingTagDecl(decl);
3765}
3766
3768 return getDecl()->isBeingDefined();
3769}
3770
3772 std::vector<const RecordType*> RecordTypeList;
3773 RecordTypeList.push_back(this);
3774 unsigned NextToCheckIndex = 0;
3775
3776 while (RecordTypeList.size() > NextToCheckIndex) {
3777 for (FieldDecl *FD :
3778 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
3779 QualType FieldTy = FD->getType();
3780 if (FieldTy.isConstQualified())
3781 return true;
3782 FieldTy = FieldTy.getCanonicalType();
3783 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
3784 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
3785 RecordTypeList.push_back(FieldRecTy);
3786 }
3787 }
3788 ++NextToCheckIndex;
3789 }
3790 return false;
3791}
3792
3794 // FIXME: Generate this with TableGen.
3795 switch (getAttrKind()) {
3796 // These are type qualifiers in the traditional C sense: they annotate
3797 // something about a specific value/variable of a type. (They aren't
3798 // always part of the canonical type, though.)
3799 case attr::ObjCGC:
3800 case attr::ObjCOwnership:
3801 case attr::ObjCInertUnsafeUnretained:
3802 case attr::TypeNonNull:
3803 case attr::TypeNullable:
3804 case attr::TypeNullableResult:
3805 case attr::TypeNullUnspecified:
3806 case attr::LifetimeBound:
3807 case attr::AddressSpace:
3808 return true;
3809
3810 // All other type attributes aren't qualifiers; they rewrite the modified
3811 // type to be a semantically different type.
3812 default:
3813 return false;
3814 }
3815}
3816
3818 // FIXME: Generate this with TableGen?
3819 switch (getAttrKind()) {
3820 default: return false;
3821 case attr::Ptr32:
3822 case attr::Ptr64:
3823 case attr::SPtr:
3824 case attr::UPtr:
3825 return true;
3826 }
3827 llvm_unreachable("invalid attr kind");
3828}
3829
3831 return getAttrKind() == attr::WebAssemblyFuncref;
3832}
3833
3835 // FIXME: Generate this with TableGen.
3836 switch (getAttrKind()) {
3837 default: return false;
3838 case attr::Pcs:
3839 case attr::CDecl:
3840 case attr::FastCall:
3841 case attr::StdCall:
3842 case attr::ThisCall:
3843 case attr::RegCall:
3844 case attr::SwiftCall:
3845 case attr::SwiftAsyncCall:
3846 case attr::VectorCall:
3847 case attr::AArch64VectorPcs:
3848 case attr::AArch64SVEPcs:
3849 case attr::AMDGPUKernelCall:
3850 case attr::Pascal:
3851 case attr::MSABI:
3852 case attr::SysVABI:
3853 case attr::IntelOclBicc:
3854 case attr::PreserveMost:
3855 case attr::PreserveAll:
3856 return true;
3857 }
3858 llvm_unreachable("invalid attr kind");
3859}
3860
3862 return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
3863}
3864
3866 return isCanonicalUnqualified() ? nullptr : getDecl()->getIdentifier();
3867}
3868
3870 unsigned Index) {
3871 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(D))
3872 return TTP;
3873 return cast<TemplateTypeParmDecl>(
3874 getReplacedTemplateParameterList(D)->getParam(Index));
3875}
3876
3877SubstTemplateTypeParmType::SubstTemplateTypeParmType(
3878 QualType Replacement, Decl *AssociatedDecl, unsigned Index,
3879 std::optional<unsigned> PackIndex)
3880 : Type(SubstTemplateTypeParm, Replacement.getCanonicalType(),
3881 Replacement->getDependence()),
3882 AssociatedDecl(AssociatedDecl) {
3883 SubstTemplateTypeParmTypeBits.HasNonCanonicalUnderlyingType =
3884 Replacement != getCanonicalTypeInternal();
3885 if (SubstTemplateTypeParmTypeBits.HasNonCanonicalUnderlyingType)
3886 *getTrailingObjects<QualType>() = Replacement;
3887
3888 SubstTemplateTypeParmTypeBits.Index = Index;
3889 SubstTemplateTypeParmTypeBits.PackIndex = PackIndex ? *PackIndex + 1 : 0;
3890 assert(AssociatedDecl != nullptr);
3891}
3892
3895 return ::getReplacedParameter(getAssociatedDecl(), getIndex());
3896}
3897
3898SubstTemplateTypeParmPackType::SubstTemplateTypeParmPackType(
3899 QualType Canon, Decl *AssociatedDecl, unsigned Index, bool Final,
3900 const TemplateArgument &ArgPack)
3901 : Type(SubstTemplateTypeParmPack, Canon,
3902 TypeDependence::DependentInstantiation |
3903 TypeDependence::UnexpandedPack),
3904 Arguments(ArgPack.pack_begin()),
3905 AssociatedDeclAndFinal(AssociatedDecl, Final) {
3907 SubstTemplateTypeParmPackTypeBits.NumArgs = ArgPack.pack_size();
3908 assert(AssociatedDecl != nullptr);
3909}
3910
3912 return AssociatedDeclAndFinal.getPointer();
3913}
3914
3916 return AssociatedDeclAndFinal.getInt();
3917}
3918
3921 return ::getReplacedParameter(getAssociatedDecl(), getIndex());
3922}
3923
3926}
3927
3929 return TemplateArgument(llvm::ArrayRef(Arguments, getNumArgs()));
3930}
3931
3932void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
3934}
3935
3936void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
3937 const Decl *AssociatedDecl,
3938 unsigned Index, bool Final,
3939 const TemplateArgument &ArgPack) {
3940 ID.AddPointer(AssociatedDecl);
3941 ID.AddInteger(Index);
3942 ID.AddBoolean(Final);
3943 ID.AddInteger(ArgPack.pack_size());
3944 for (const auto &P : ArgPack.pack_elements())
3945 ID.AddPointer(P.getAsType().getAsOpaquePtr());
3946}
3947
3950 return anyDependentTemplateArguments(Args.arguments(), Converted);
3951}
3952
3955 for (const TemplateArgument &Arg : Converted)
3956 if (Arg.isDependent())
3957 return true;
3958 return false;
3959}
3960
3963 for (const TemplateArgumentLoc &ArgLoc : Args) {
3964 if (ArgLoc.getArgument().isInstantiationDependent())
3965 return true;
3966 }
3967 return false;
3968}
3969
3970TemplateSpecializationType::TemplateSpecializationType(
3972 QualType AliasedType)
3973 : Type(TemplateSpecialization, Canon.isNull() ? QualType(this, 0) : Canon,
3974 (Canon.isNull()
3975 ? TypeDependence::DependentInstantiation
3976 : toSemanticDependence(Canon->getDependence())) |
3977 (toTypeDependence(T.getDependence()) &
3978 TypeDependence::UnexpandedPack)),
3979 Template(T) {
3980 TemplateSpecializationTypeBits.NumArgs = Args.size();
3981 TemplateSpecializationTypeBits.TypeAlias = !AliasedType.isNull();
3982
3983 assert(!T.getAsDependentTemplateName() &&
3984 "Use DependentTemplateSpecializationType for dependent template-name");
3985 assert((T.getKind() == TemplateName::Template ||
3989 "Unexpected template name for TemplateSpecializationType");
3990
3991 auto *TemplateArgs = reinterpret_cast<TemplateArgument *>(this + 1);
3992 for (const TemplateArgument &Arg : Args) {
3993 // Update instantiation-dependent, variably-modified, and error bits.
3994 // If the canonical type exists and is non-dependent, the template
3995 // specialization type can be non-dependent even if one of the type
3996 // arguments is. Given:
3997 // template<typename T> using U = int;
3998 // U<T> is always non-dependent, irrespective of the type T.
3999 // However, U<Ts> contains an unexpanded parameter pack, even though
4000 // its expansion (and thus its desugared type) doesn't.
4001 addDependence(toTypeDependence(Arg.getDependence()) &
4002 ~TypeDependence::Dependent);
4003 if (Arg.getKind() == TemplateArgument::Type)
4004 addDependence(Arg.getAsType()->getDependence() &
4005 TypeDependence::VariablyModified);
4006 new (TemplateArgs++) TemplateArgument(Arg);
4007 }
4008
4009 // Store the aliased type if this is a type alias template specialization.
4010 if (isTypeAlias()) {
4011 auto *Begin = reinterpret_cast<TemplateArgument *>(this + 1);
4012 *reinterpret_cast<QualType *>(Begin + Args.size()) = AliasedType;
4013 }
4014}
4015
4017 assert(isTypeAlias() && "not a type alias template specialization");
4018 return *reinterpret_cast<const QualType *>(template_arguments().end());
4019}
4020
4021void TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
4022 const ASTContext &Ctx) {
4023 Profile(ID, Template, template_arguments(), Ctx);
4024 if (isTypeAlias())
4025 getAliasedType().Profile(ID);
4026}
4027
4028void
4029TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
4030 TemplateName T,
4032 const ASTContext &Context) {
4033 T.Profile(ID);
4034 for (const TemplateArgument &Arg : Args)
4035 Arg.Profile(ID, Context);
4036}
4037
4040 if (!hasNonFastQualifiers())
4042
4043 return Context.getQualifiedType(QT, *this);
4044}
4045
4047QualifierCollector::apply(const ASTContext &Context, const Type *T) const {
4048 if (!hasNonFastQualifiers())
4049 return QualType(T, getFastQualifiers());
4050
4051 return Context.getQualifiedType(T, *this);
4052}
4053
4054void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
4055 QualType BaseType,
4056 ArrayRef<QualType> typeArgs,
4058 bool isKindOf) {
4059 ID.AddPointer(BaseType.getAsOpaquePtr());
4060 ID.AddInteger(typeArgs.size());
4061 for (auto typeArg : typeArgs)
4062 ID.AddPointer(typeArg.getAsOpaquePtr());
4063 ID.AddInteger(protocols.size());
4064 for (auto *proto : protocols)
4065 ID.AddPointer(proto);
4066 ID.AddBoolean(isKindOf);
4067}
4068
4069void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
4073}
4074
4075void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID,
4076 const ObjCTypeParamDecl *OTPDecl,
4077 QualType CanonicalType,
4078 ArrayRef<ObjCProtocolDecl *> protocols) {
4079 ID.AddPointer(OTPDecl);
4080 ID.AddPointer(CanonicalType.getAsOpaquePtr());
4081 ID.AddInteger(protocols.size());
4082 for (auto *proto : protocols)
4083 ID.AddPointer(proto);
4084}
4085
4086void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID) {
4089}
4090
4091namespace {
4092
4093/// The cached properties of a type.
4094class CachedProperties {
4095 Linkage L;
4096 bool local;
4097
4098public:
4099 CachedProperties(Linkage L, bool local) : L(L), local(local) {}
4100
4101 Linkage getLinkage() const { return L; }
4102 bool hasLocalOrUnnamedType() const { return local; }
4103
4104 friend CachedProperties merge(CachedProperties L, CachedProperties R) {
4105 Linkage MergedLinkage = minLinkage(L.L, R.L);
4106 return CachedProperties(MergedLinkage, L.hasLocalOrUnnamedType() ||
4107 R.hasLocalOrUnnamedType());
4108 }
4109};
4110
4111} // namespace
4112
4113static CachedProperties computeCachedProperties(const Type *T);
4114
4115namespace clang {
4116
4117/// The type-property cache. This is templated so as to be
4118/// instantiated at an internal type to prevent unnecessary symbol
4119/// leakage.
4120template <class Private> class TypePropertyCache {
4121public:
4122 static CachedProperties get(QualType T) {
4123 return get(T.getTypePtr());
4124 }
4125
4126 static CachedProperties get(const Type *T) {
4127 ensure(T);
4128 return CachedProperties(T->TypeBits.getLinkage(),
4129 T->TypeBits.hasLocalOrUnnamedType());
4130 }
4131
4132 static void ensure(const Type *T) {
4133 // If the cache is valid, we're okay.
4134 if (T->TypeBits.isCacheValid()) return;
4135
4136 // If this type is non-canonical, ask its canonical type for the
4137 // relevant information.
4138 if (!T->isCanonicalUnqualified()) {
4139 const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
4140 ensure(CT);
4141 T->TypeBits.CacheValid = true;
4142 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
4143 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
4144 return;
4145 }
4146
4147 // Compute the cached properties and then set the cache.
4148 CachedProperties Result = computeCachedProperties(T);
4149 T->TypeBits.CacheValid = true;
4150 T->TypeBits.CachedLinkage = Result.getLinkage();
4151 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
4152 }
4153};
4154
4155} // namespace clang
4156
4157// Instantiate the friend template at a private class. In a
4158// reasonable implementation, these symbols will be internal.
4159// It is terrible that this is the best way to accomplish this.
4160namespace {
4161
4162class Private {};
4163
4164} // namespace
4165
4167
4168static CachedProperties computeCachedProperties(const Type *T) {
4169 switch (T->getTypeClass()) {
4170#define TYPE(Class,Base)
4171#define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
4172#include "clang/AST/TypeNodes.inc"
4173 llvm_unreachable("didn't expect a non-canonical type here");
4174
4175#define TYPE(Class,Base)
4176#define DEPENDENT_TYPE(Class,Base) case Type::Class:
4177#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
4178#include "clang/AST/TypeNodes.inc"
4179 // Treat instantiation-dependent types as external.
4180 if (!T->isInstantiationDependentType()) T->dump();
4181 assert(T->isInstantiationDependentType());
4182 return CachedProperties(ExternalLinkage, false);
4183
4184 case Type::Auto:
4185 case Type::DeducedTemplateSpecialization:
4186 // Give non-deduced 'auto' types external linkage. We should only see them
4187 // here in error recovery.
4188 return CachedProperties(ExternalLinkage, false);
4189
4190 case Type::BitInt:
4191 case Type::Builtin:
4192 // C++ [basic.link]p8:
4193 // A type is said to have linkage if and only if:
4194 // - it is a fundamental type (3.9.1); or
4195 return CachedProperties(ExternalLinkage, false);
4196
4197 case Type::Record:
4198 case Type::Enum: {
4199 const TagDecl *Tag = cast<TagType>(T)->getDecl();
4200
4201 // C++ [basic.link]p8:
4202 // - it is a class or enumeration type that is named (or has a name
4203 // for linkage purposes (7.1.3)) and the name has linkage; or
4204 // - it is a specialization of a class template (14); or
4205 Linkage L = Tag->getLinkageInternal();
4206 bool IsLocalOrUnnamed =
4208 !Tag->hasNameForLinkage();
4209 return CachedProperties(L, IsLocalOrUnnamed);
4210 }
4211
4212 // C++ [basic.link]p8:
4213 // - it is a compound type (3.9.2) other than a class or enumeration,
4214 // compounded exclusively from types that have linkage; or
4215 case Type::Complex:
4216 return Cache::get(cast<ComplexType>(T)->getElementType());
4217 case Type::Pointer:
4218 return Cache::get(cast<PointerType>(T)->getPointeeType());
4219 case Type::BlockPointer:
4220 return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
4221 case Type::LValueReference:
4222 case Type::RValueReference:
4223 return Cache::get(cast<ReferenceType>(T)->getPointeeType());
4224 case Type::MemberPointer: {
4225 const auto *MPT = cast<MemberPointerType>(T);
4226 return merge(Cache::get(MPT->getClass()),
4227 Cache::get(MPT->getPointeeType()));
4228 }
4229 case Type::ConstantArray:
4230 case Type::IncompleteArray:
4231 case Type::VariableArray:
4232 return Cache::get(cast<ArrayType>(T)->getElementType());
4233 case Type::Vector:
4234 case Type::ExtVector:
4235 return Cache::get(cast<VectorType>(T)->getElementType());
4236 case Type::ConstantMatrix:
4237 return Cache::get(cast<ConstantMatrixType>(T)->getElementType());
4238 case Type::FunctionNoProto:
4239 return Cache::get(cast<FunctionType>(T)->getReturnType());
4240 case Type::FunctionProto: {
4241 const auto *FPT = cast<FunctionProtoType>(T);
4242 CachedProperties result = Cache::get(FPT->getReturnType());
4243 for (const auto &ai : FPT->param_types())
4244 result = merge(result, Cache::get(ai));
4245 return result;
4246 }
4247 case Type::ObjCInterface: {
4248 Linkage L = cast<ObjCInterfaceType>(T)->getDecl()->getLinkageInternal();
4249 return CachedProperties(L, false);
4250 }
4251 case Type::ObjCObject:
4252 return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
4253 case Type::ObjCObjectPointer:
4254 return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
4255 case Type::Atomic:
4256 return Cache::get(cast<AtomicType>(T)->getValueType());
4257 case Type::Pipe:
4258 return Cache::get(cast<PipeType>(T)->getElementType());
4259 }
4260
4261 llvm_unreachable("unhandled type class");
4262}
4263
4264/// Determine the linkage of this type.
4266 Cache::ensure(this);
4267 return TypeBits.getLinkage();
4268}
4269
4271 Cache::ensure(this);
4272 return TypeBits.hasLocalOrUnnamedType();
4273}
4274
4276 switch (T->getTypeClass()) {
4277#define TYPE(Class,Base)
4278#define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
4279#include "clang/AST/TypeNodes.inc"
4280 llvm_unreachable("didn't expect a non-canonical type here");
4281
4282#define TYPE(Class,Base)
4283#define DEPENDENT_TYPE(Class,Base) case Type::Class:
4284#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
4285#include "clang/AST/TypeNodes.inc"
4286 // Treat instantiation-dependent types as external.
4287 assert(T->isInstantiationDependentType());
4288 return LinkageInfo::external();
4289
4290 case Type::BitInt:
4291 case Type::Builtin:
4292 return LinkageInfo::external();
4293
4294 case Type::Auto:
4295 case Type::DeducedTemplateSpecialization:
4296 return LinkageInfo::external();
4297
4298 case Type::Record:
4299 case Type::Enum:
4300 return getDeclLinkageAndVisibility(cast<TagType>(T)->getDecl());
4301
4302 case Type::Complex:
4303 return computeTypeLinkageInfo(cast<ComplexType>(T)->getElementType());
4304 case Type::Pointer:
4305 return computeTypeLinkageInfo(cast<PointerType>(T)->getPointeeType());
4306 case Type::BlockPointer:
4307 return computeTypeLinkageInfo(cast<BlockPointerType>(T)->getPointeeType());
4308 case Type::LValueReference:
4309 case Type::RValueReference:
4310 return computeTypeLinkageInfo(cast<ReferenceType>(T)->getPointeeType());
4311 case Type::MemberPointer: {
4312 const auto *MPT = cast<MemberPointerType>(T);
4313 LinkageInfo LV = computeTypeLinkageInfo(MPT->getClass());
4314 LV.merge(computeTypeLinkageInfo(MPT->getPointeeType()));
4315 return LV;
4316 }
4317 case Type::ConstantArray:
4318 case Type::IncompleteArray:
4319 case Type::VariableArray:
4320 return computeTypeLinkageInfo(cast<ArrayType>(T)->getElementType());
4321 case Type::Vector:
4322 case Type::ExtVector:
4323 return computeTypeLinkageInfo(cast<VectorType>(T)->getElementType());
4324 case Type::ConstantMatrix:
4326 cast<ConstantMatrixType>(T)->getElementType());
4327 case Type::FunctionNoProto:
4328 return computeTypeLinkageInfo(cast<FunctionType>(T)->getReturnType());
4329 case Type::FunctionProto: {
4330 const auto *FPT = cast<FunctionProtoType>(T);
4331 LinkageInfo LV = computeTypeLinkageInfo(FPT->getReturnType());
4332 for (const auto &ai : FPT->param_types())
4334 return LV;
4335 }
4336 case Type::ObjCInterface:
4337 return getDeclLinkageAndVisibility(cast<ObjCInterfaceType>(T)->getDecl());
4338 case Type::ObjCObject:
4339 return computeTypeLinkageInfo(cast<ObjCObjectType>(T)->getBaseType());
4340 case Type::ObjCObjectPointer:
4342 cast<ObjCObjectPointerType>(T)->getPointeeType());
4343 case Type::Atomic:
4344 return computeTypeLinkageInfo(cast<AtomicType>(T)->getValueType());
4345 case Type::Pipe:
4346 return computeTypeLinkageInfo(cast<PipeType>(T)->getElementType());
4347 }
4348
4349 llvm_unreachable("unhandled type class");
4350}
4351
4353 if (!TypeBits.isCacheValid())
4354 return true;
4355
4358 .getLinkage();
4359 return L == TypeBits.getLinkage();
4360}
4361
4363 if (!T->isCanonicalUnqualified())
4365
4367 assert(LV.getLinkage() == T->getLinkage());
4368 return LV;
4369}
4370
4373}
4374
4375std::optional<NullabilityKind> Type::getNullability() const {
4376 QualType Type(this, 0);
4377 while (const auto *AT = Type->getAs<AttributedType>()) {
4378 // Check whether this is an attributed type with nullability
4379 // information.
4380 if (auto Nullability = AT->getImmediateNullability())
4381 return Nullability;
4382
4383 Type = AT->getEquivalentType();
4384 }
4385 return std::nullopt;
4386}
4387
4388bool Type::canHaveNullability(bool ResultIfUnknown) const {
4390
4391 switch (type->getTypeClass()) {
4392 // We'll only see canonical types here.
4393#define NON_CANONICAL_TYPE(Class, Parent) \
4394 case Type::Class: \
4395 llvm_unreachable("non-canonical type");
4396#define TYPE(Class, Parent)
4397#include "clang/AST/TypeNodes.inc"
4398
4399 // Pointer types.
4400 case Type::Pointer:
4401 case Type::BlockPointer:
4402 case Type::MemberPointer:
4403 case Type::ObjCObjectPointer:
4404 return true;
4405
4406 // Dependent types that could instantiate to pointer types.
4407 case Type::UnresolvedUsing:
4408 case Type::TypeOfExpr:
4409 case Type::TypeOf:
4410 case Type::Decltype:
4411 case Type::UnaryTransform:
4412 case Type::TemplateTypeParm:
4413 case Type::SubstTemplateTypeParmPack:
4414 case Type::DependentName:
4415 case Type::DependentTemplateSpecialization:
4416 case Type::Auto:
4417 return ResultIfUnknown;
4418
4419 // Dependent template specializations can instantiate to pointer
4420 // types unless they're known to be specializations of a class
4421 // template.
4422 case Type::TemplateSpecialization:
4423 if (TemplateDecl *templateDecl
4424 = cast<TemplateSpecializationType>(type.getTypePtr())
4425 ->getTemplateName().getAsTemplateDecl()) {
4426 if (isa<ClassTemplateDecl>(templateDecl))
4427 return false;
4428 }
4429 return ResultIfUnknown;
4430
4431 case Type::Builtin:
4432 switch (cast<BuiltinType>(type.getTypePtr())->getKind()) {
4433 // Signed, unsigned, and floating-point types cannot have nullability.
4434#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
4435#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
4436#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
4437#define BUILTIN_TYPE(Id, SingletonId)
4438#include "clang/AST/BuiltinTypes.def"
4439 return false;
4440
4441 // Dependent types that could instantiate to a pointer type.
4442 case BuiltinType::Dependent:
4443 case BuiltinType::Overload:
4444 case BuiltinType::BoundMember:
4445 case BuiltinType::PseudoObject:
4446 case BuiltinType::UnknownAny:
4447 case BuiltinType::ARCUnbridgedCast:
4448 return ResultIfUnknown;
4449
4450 case BuiltinType::Void:
4451 case BuiltinType::ObjCId:
4452 case BuiltinType::ObjCClass:
4453 case BuiltinType::ObjCSel:
4454#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
4455 case BuiltinType::Id:
4456#include "clang/Basic/OpenCLImageTypes.def"
4457#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
4458 case BuiltinType::Id:
4459#include "clang/Basic/OpenCLExtensionTypes.def"
4460 case BuiltinType::OCLSampler:
4461 case BuiltinType::OCLEvent:
4462 case BuiltinType::OCLClkEvent:
4463 case BuiltinType::OCLQueue:
4464 case BuiltinType::OCLReserveID:
4465#define SVE_TYPE(Name, Id, SingletonId) \
4466 case BuiltinType::Id:
4467#include "clang/Basic/AArch64SVEACLETypes.def"
4468#define PPC_VECTOR_TYPE(Name, Id, Size) \
4469 case BuiltinType::Id:
4470#include "clang/Basic/PPCTypes.def"
4471#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
4472#include "clang/Basic/RISCVVTypes.def"
4473#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
4474#include "clang/Basic/WebAssemblyReferenceTypes.def"
4475 case BuiltinType::BuiltinFn:
4476 case BuiltinType::NullPtr:
4477 case BuiltinType::IncompleteMatrixIdx:
4478 case BuiltinType::OMPArraySection:
4479 case BuiltinType::OMPArrayShaping:
4480 case BuiltinType::OMPIterator:
4481 return false;
4482 }
4483 llvm_unreachable("unknown builtin type");
4484
4485 // Non-pointer types.
4486 case Type::Complex:
4487 case Type::LValueReference:
4488 case Type::RValueReference:
4489 case Type::ConstantArray:
4490 case Type::IncompleteArray:
4491 case Type::VariableArray:
4492 case Type::DependentSizedArray:
4493 case Type::DependentVector:
4494 case Type::DependentSizedExtVector:
4495 case Type::Vector:
4496 case Type::ExtVector:
4497 case Type::ConstantMatrix:
4498 case Type::DependentSizedMatrix:
4499 case Type::DependentAddressSpace:
4500 case Type::FunctionProto:
4501 case Type::FunctionNoProto:
4502 case Type::Record:
4503 case Type::DeducedTemplateSpecialization:
4504 case Type::Enum:
4505 case Type::InjectedClassName:
4506 case Type::PackExpansion:
4507 case Type::ObjCObject:
4508 case Type::ObjCInterface:
4509 case Type::Atomic:
4510 case Type::Pipe:
4511 case Type::BitInt:
4512 case Type::DependentBitInt:
4513 return false;
4514 }
4515 llvm_unreachable("bad type kind!");
4516}
4517
4518std::optional<NullabilityKind> AttributedType::getImmediateNullability() const {
4519 if (getAttrKind() == attr::TypeNonNull)
4521 if (getAttrKind() == attr::TypeNullable)
4523 if (getAttrKind() == attr::TypeNullUnspecified)
4525 if (getAttrKind() == attr::TypeNullableResult)
4527 return std::nullopt;
4528}
4529
4530std::optional<NullabilityKind>
4532 QualType AttrTy = T;
4533 if (auto MacroTy = dyn_cast<MacroQualifiedType>(T))
4534 AttrTy = MacroTy->getUnderlyingType();
4535
4536 if (auto attributed = dyn_cast<AttributedType>(AttrTy)) {
4537 if (auto nullability = attributed->getImmediateNullability()) {
4538 T = attributed->getModifiedType();
4539 return nullability;
4540 }
4541 }
4542
4543 return std::nullopt;
4544}
4545
4547 const auto *objcPtr = getAs<ObjCObjectPointerType>();
4548 if (!objcPtr)
4549 return false;
4550
4551 if (objcPtr->isObjCIdType()) {
4552 // id is always okay.
4553 return true;
4554 }
4555
4556 // Blocks are NSObjects.
4557 if (ObjCInterfaceDecl *iface = objcPtr->getInterfaceDecl()) {
4558 if (iface->getIdentifier() != ctx.getNSObjectName())
4559 return false;
4560
4561 // Continue to check qualifiers, below.
4562 } else if (objcPtr->isObjCQualifiedIdType()) {
4563 // Continue to check qualifiers, below.
4564 } else {
4565 return false;
4566 }
4567
4568 // Check protocol qualifiers.
4569 for (ObjCProtocolDecl *proto : objcPtr->quals()) {
4570 // Blocks conform to NSObject and NSCopying.
4571 if (proto->getIdentifier() != ctx.getNSObjectName() &&
4572 proto->getIdentifier() != ctx.getNSCopyingName())
4573 return false;
4574 }
4575
4576 return true;
4577}
4578
4583}
4584
4586 assert(isObjCLifetimeType() &&
4587 "cannot query implicit lifetime for non-inferrable type");
4588
4589 const Type *canon = getCanonicalTypeInternal().getTypePtr();
4590
4591 // Walk down to the base type. We don't care about qualifiers for this.
4592 while (const auto *array = dyn_cast<ArrayType>(canon))
4593 canon = array->getElementType().getTypePtr();
4594
4595 if (const auto *opt = dyn_cast<ObjCObjectPointerType>(canon)) {
4596 // Class and Class<Protocol> don't require retention.
4597 if (opt->getObjectType()->isObjCClass())
4598 return true;
4599 }
4600
4601 return false;
4602}
4603
4605 if (const auto *typedefType = getAs<TypedefType>())
4606 return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>();
4607 return false;
4608}
4609
4611 if (const auto *typedefType = getAs<TypedefType>())
4612 return typedefType->getDecl()->hasAttr<ObjCIndependentClassAttr>();
4613 return false;
4614}
4615
4617 return isObjCObjectPointerType() ||
4620}
4621
4623 if (isObjCLifetimeType())
4624 return true;
4625 if (const auto *OPT = getAs<PointerType>())
4626 return OPT->getPointeeType()->isObjCIndirectLifetimeType();
4627 if (const auto *Ref = getAs<ReferenceType>())
4628 return Ref->getPointeeType()->isObjCIndirectLifetimeType();
4629 if (const auto *MemPtr = getAs<MemberPointerType>())
4630 return MemPtr->getPointeeType()->isObjCIndirectLifetimeType();
4631 return false;
4632}
4633
4634/// Returns true if objects of this type have lifetime semantics under
4635/// ARC.
4637 const Type *type = this;
4638 while (const ArrayType *array = type->getAsArrayTypeUnsafe())
4639 type = array->getElementType().getTypePtr();
4640 return type->isObjCRetainableType();
4641}
4642
4643/// Determine whether the given type T is a "bridgable" Objective-C type,
4644/// which is either an Objective-C object pointer type or an
4647}
4648
4649/// Determine whether the given type T is a "bridgeable" C type.
4651 const auto *Pointer = getAs<PointerType>();
4652 if (!Pointer)
4653 return false;
4654
4655 QualType Pointee = Pointer->getPointeeType();
4656 return Pointee->isVoidType() || Pointee->isRecordType();
4657}
4658
4659/// Check if the specified type is the CUDA device builtin surface type.
4661 if (const auto *RT = getAs<RecordType>())
4662 return RT->getDecl()->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>();
4663 return false;
4664}
4665
4666/// Check if the specified type is the CUDA device builtin texture type.
4668 if (const auto *RT = getAs<RecordType>())
4669 return RT->getDecl()->hasAttr<CUDADeviceBuiltinTextureTypeAttr>();
4670 return false;
4671}
4672
4674 if (!isVariablyModifiedType()) return false;
4675
4676 if (const auto *ptr = getAs<PointerType>())
4677 return ptr->getPointeeType()->hasSizedVLAType();
4678 if (const auto *ref = getAs<ReferenceType>())
4679 return ref->getPointeeType()->hasSizedVLAType();
4680 if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
4681 if (isa<VariableArrayType>(arr) &&
4682 cast<VariableArrayType>(arr)->getSizeExpr())
4683 return true;
4684
4685 return arr->getElementType()->hasSizedVLAType();
4686 }
4687
4688 return false;
4689}
4690
4691QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
4692 switch (type.getObjCLifetime()) {
4696 break;
4697
4701 return DK_objc_weak_lifetime;
4702 }
4703
4704 if (const auto *RT =
4705 type->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
4706 const RecordDecl *RD = RT->getDecl();
4707 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4708 /// Check if this is a C++ object with a non-trivial destructor.
4709 if (CXXRD->hasDefinition() && !CXXRD->hasTrivialDestructor())
4710 return DK_cxx_destructor;
4711 } else {
4712 /// Check if this is a C struct that is non-trivial to destroy or an array
4713 /// that contains such a struct.
4716 }
4717 }
4718
4719 return DK_none;
4720}
4721
4724}
4725
4727 llvm::APSInt Val, unsigned Scale) {
4728 llvm::FixedPointSemantics FXSema(Val.getBitWidth(), Scale, Val.isSigned(),
4729 /*IsSaturated=*/false,
4730 /*HasUnsignedPadding=*/false);
4731 llvm::APFixedPoint(Val, FXSema).toString(Str);
4732}
4733
4734AutoType::AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
4735 TypeDependence ExtraDependence, QualType Canon,
4736 ConceptDecl *TypeConstraintConcept,
4737 ArrayRef<TemplateArgument> TypeConstraintArgs)
4738 : DeducedType(Auto, DeducedAsType, ExtraDependence, Canon) {
4739 AutoTypeBits.Keyword = (unsigned)Keyword;
4740 AutoTypeBits.NumArgs = TypeConstraintArgs.size();
4741 this->TypeConstraintConcept = TypeConstraintConcept;
4742 assert(TypeConstraintConcept || AutoTypeBits.NumArgs == 0);
4743 if (TypeConstraintConcept) {
4744 auto *ArgBuffer =
4745 const_cast<TemplateArgument *>(getTypeConstraintArguments().data());
4746 for (const TemplateArgument &Arg : TypeConstraintArgs) {
4747 // We only syntactically depend on the constraint arguments. They don't
4748 // affect the deduced type, only its validity.
4749 addDependence(
4750 toSyntacticDependence(toTypeDependence(Arg.getDependence())));
4751
4752 new (ArgBuffer++) TemplateArgument(Arg);
4753 }
4754 }
4755}
4756
4757void AutoType::Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4758 QualType Deduced, AutoTypeKeyword Keyword,
4759 bool IsDependent, ConceptDecl *CD,
4760 ArrayRef<TemplateArgument> Arguments) {
4761 ID.AddPointer(Deduced.getAsOpaquePtr());
4762 ID.AddInteger((unsigned)Keyword);
4763 ID.AddBoolean(IsDependent);
4764 ID.AddPointer(CD);
4765 for (const TemplateArgument &Arg : Arguments)
4766 Arg.Profile(ID, Context);
4767}
4768
4769void AutoType::Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
4770 Profile(ID, Context, getDeducedType(), getKeyword(), isDependentType(),
4772}
Defines the clang::ASTContext interface.
StringRef P
Provides definitions for the various language-specific address spaces.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the ExceptionSpecificationType enumeration and various utility functions.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
static bool isRecordType(QualType T)
Defines various enumerations that describe declaration and type specifiers.
Defines the TargetCXXABI class, which abstracts details of the C++ ABI that we're targeting.
static TagDecl * getInterestingTagDecl(TagDecl *decl)
Definition: Type.cpp:3754
#define SUGARED_TYPE_CLASS(Class)
Definition: Type.cpp:903
static bool HasNonDeletedDefaultedEqualityComparison(const CXXRecordDecl *Decl)
Definition: Type.cpp:2666
static const TemplateTypeParmDecl * getReplacedParameter(Decl *D, unsigned Index)
Definition: Type.cpp:3869
static const T * getAsSugar(const Type *Cur)
This will check for a T (which should be a Type which can act as sugar, such as a TypedefType) by rem...
Definition: Type.cpp:532
#define TRIVIAL_TYPE_CLASS(Class)
Definition: Type.cpp:901
static CachedProperties computeCachedProperties(const Type *T)
Definition: Type.cpp:4168
C Language Family Type Representation.
SourceLocation Begin
Defines the clang::Visibility enumeration and various utility functions.
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
QualType getParenType(QualType NamedType) const
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType) const
QualType getIncompleteArrayType(QualType EltTy, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a unique reference to the type for an incomplete array of the specified element type.
QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent, bool IsPack=false, ConceptDecl *TypeConstraintConcept=nullptr, ArrayRef< TemplateArgument > TypeConstraintArgs={}) const
C++11 deduced auto type.
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl.
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:761
QualType applyObjCProtocolQualifiers(QualType type, ArrayRef< ObjCProtocolDecl * > protocols, bool &hasError, bool allowOnPointerType=false) const
Apply Objective-C protocol qualifiers to the given type.
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
bool hasUniqueObjectRepresentations(QualType Ty, bool CheckIfTriviallyCopyable=true) const
Return true if the specified type has unique object representations according to (C++17 [meta....
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
CanQualType ObjCBuiltinIdTy
Definition: ASTContext.h:1108
IdentifierInfo * getNSObjectName() const
Retrieve the identifier 'NSObject'.
Definition: ASTContext.h:1871
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType getVariableArrayType(QualType EltTy, Expr *NumElts, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals, SourceRange Brackets) const
Return a non-unique reference to the type for a variable array of the specified element type.
QualType getAdjustedType(QualType Orig, QualType New) const
Return the uniqued reference to a type adjusted from the original type to a new type.
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorType::VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2125
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
QualType getObjCObjectType(QualType Base, ObjCProtocolDecl *const *Protocols, unsigned NumProtocols) const
Legacy interface: cannot provide type arguments or __kindof.
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2299
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType UnsignedCharTy
Definition: ASTContext.h:1087
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1542
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:743
QualType getSubstTemplateTypeParmType(QualType Replacement, Decl *AssociatedDecl, unsigned Index, std::optional< unsigned > PackIndex) const
Retrieve a substitution-result type.
QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, unsigned NumColumns) const
Return the unique reference to the matrix type of the specified element type and size.
IdentifierInfo * getNSCopyingName()
Retrieve the identifier 'NSCopying'.
Definition: ASTContext.h:1880
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition: Type.h:2869
QualType getAdjustedType() const
Definition: Type.h:2883
QualType getOriginalType() const
Definition: Type.h:2882
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3083
ArraySizeModifier
Capture whether this is a normal array (e.g.
Definition: Type.h:3089
ArraySizeModifier getSizeModifier() const
Definition: Type.h:3106
QualType getElementType() const
Definition: Type.h:3104
ArrayType(TypeClass tc, QualType et, QualType can, ArraySizeModifier sm, unsigned tq, const Expr *sz=nullptr)
Definition: Type.cpp:139
unsigned getIndexTypeCVRQualifiers() const
Definition: Type.h:3114
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:6576
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:4988
QualType getModifiedType() const
Definition: Type.h:5010
bool isCallingConv() const
Definition: Type.cpp:3834
std::optional< NullabilityKind > getImmediateNullability() const
Definition: Type.cpp:4518
static std::optional< NullabilityKind > stripOuterNullability(QualType &T)
Strip off the top-level nullability annotation on the given type, if it's there.
Definition: Type.cpp:4531
bool isMSTypeSpec() const
Definition: Type.cpp:3817
QualType getEquivalentType() const
Definition: Type.h:5011
Kind getAttrKind() const
Definition: Type.h:5006
bool isWebAssemblyFuncrefSpec() const
Definition: Type.cpp:3830
bool isQualifier() const
Does this attribute behave like a type qualifier?
Definition: Type.cpp:3793
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:5365
ArrayRef< TemplateArgument > getTypeConstraintArguments() const
Definition: Type.h:5375
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.cpp:4769
ConceptDecl * getTypeConstraintConcept() const
Definition: Type.h:5380
AutoTypeKeyword getKeyword() const
Definition: Type.h:5396
BitIntType(bool isUnsigned, unsigned NumBits)
Definition: Type.cpp:367
Pointer to a block type.
Definition: Type.h:2920
QualType getPointeeType() const
Definition: Type.h:2932
This class is used for builtin types like 'int'.
Definition: Type.h:2682
Kind getKind() const
Definition: Type.h:2724
StringRef getName(const PrintingPolicy &Policy) const
Definition: Type.cpp:3155
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
Represents a C++ struct/union/class.
Definition: DeclCXX.h:254
bool mayBeNonDynamicClass() const
Definition: DeclCXX.h:584
CXXRecordDecl * getMostRecentNonInjectedDecl()
Definition: DeclCXX.h:537
bool mayBeDynamicClass() const
Definition: DeclCXX.h:578
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
Complex values, per C99 6.2.5p11.
Definition: Type.h:2787
QualType getElementType() const
Definition: Type.h:2797
Declaration of a C++20 concept.
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3131
const llvm::APInt & getSize() const
Definition: Type.h:3152
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition: Type.cpp:162
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition: Type.cpp:202
const Expr * getSizeExpr() const
Definition: Type.h:3153
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.h:3173
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:3660
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: Type.h:3681
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: Type.h:3678
ConstantMatrixType(QualType MatrixElementType, unsigned NRows, unsigned NColumns, QualType CanonElementType)
Definition: Type.cpp:329
Represents a pointer type decayed from an array or function type.
Definition: Type.h:2903
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1409
ASTContext & getParentASTContext() const
Definition: DeclBase.h:1980
bool isFunctionOrMethod() const
Definition: DeclBase.h:2003
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:83
bool isInStdNamespace() const
Definition: DeclBase.cpp:404
bool isFunctionOrFunctionTemplate() const
Whether this declaration is a function or function template.
Definition: DeclBase.h:1087
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:429
DeclContext * getDeclContext()
Definition: DeclBase.h:441
bool hasAttr() const
Definition: DeclBase.h:560
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:946
Represents the type decltype(expr) (C++11).
Definition: Type.h:4807
QualType desugar() const
Remove a single level of sugar.
Definition: Type.cpp:3722
bool isSugared() const
Returns whether this type directly provides sugar.
Definition: Type.cpp:3720
DecltypeType(Expr *E, QualType underlyingType, QualType can=QualType())
Definition: Type.cpp:3708
QualType getUnderlyingType() const
Definition: Type.h:4818
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:5331
QualType getDeducedType() const
Get the type deduced for this placeholder type, or null if it has not been deduced.
Definition: Type.h:5352
bool isDeduced() const
Definition: Type.h:5353
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3373
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6675
Expr * getNumBitsExpr() const
Definition: Type.cpp:381
bool isUnsigned() const
Definition: Type.cpp:377
DependentBitIntType(const ASTContext &Context, bool IsUnsigned, Expr *NumBits)
Definition: Type.cpp:371
DependentDecltypeType(const ASTContext &Context, Expr *E)
Definition: Type.cpp:3729
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4841
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3328
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3391
QualType getElementType() const
Definition: Type.h:3407
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3417
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition: Type.h:3719
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3741
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:5918
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4760
DependentUnaryTransformType(const ASTContext &C, QualType BaseType, UTTKind UKind)
Definition: Type.cpp:3743
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3540
Represents a type that was referred to using an elaborated type keyword, e.g., struct S,...
Definition: Type.h:5757
QualType getNamedType() const
Retrieve the type named by the qualified-id.
Definition: Type.h:5795
Represents an enum.
Definition: Decl.h:3758
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:3977
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:4959
This represents one expression.
Definition: Expr.h:110
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:186
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition: Expr.h:215
QualType getType() const
Definition: Expr.h:142
ExtVectorType - Extended vector type.
Definition: Type.h:3555
Represents a member of a struct/union/class.
Definition: Decl.h:2962
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition: DeclFriend.h:54
Represents a function declaration or definition.
Definition: Decl.h:1919
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition: Type.h:4073
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4117
bool hasDependentExceptionSpec() const
Return whether this function has a dependent exception spec.
Definition: Type.cpp:3506
param_type_iterator param_type_begin() const
Definition: Type.h:4493
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:4360
bool isTemplateVariadic() const
Determines whether this function prototype contains a parameter pack at the end.
Definition: Type.cpp:3560
unsigned getNumParams() const
Definition: Type.h:4334
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition: Type.h:4473
QualType getParamType(unsigned i) const
Definition: Type.h:4336
QualType getExceptionType(unsigned i) const
Return the ith exception type, where 0 <= i < getNumExceptions().
Definition: Type.h:4411
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.cpp:3624
unsigned getNumExceptions() const
Return the number of types in the exception specification.
Definition: Type.h:4403
CanThrowResult canThrow() const
Determine whether this function type has a non-throwing exception specification.
Definition: Type.cpp:3527
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4345
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition: Type.h:4418
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4341
ArrayRef< QualType > exceptions() const
Definition: Type.h:4503
bool hasInstantiationDependentExceptionSpec() const
Return whether this function has an instantiation-dependent exception spec.
Definition: Type.cpp:3518
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3751
ExtInfo getExtInfo() const
Definition: Type.h:4047
static StringRef getNameForCallConv(CallingConv CC)
Definition: Type.cpp:3354
QualType getReturnType() const
Definition: Type.h:4035
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
Represents a C array with an unspecified size.
Definition: Type.h:3191
CXXRecordDecl * getDecl() const
Definition: Type.cpp:3861
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2995
LinkageInfo computeTypeLinkageInfo(const Type *T)
Definition: Type.cpp:4275
LinkageInfo getTypeLinkageAndVisibility(const Type *T)
Definition: Type.cpp:4362
LinkageInfo getDeclLinkageAndVisibility(const NamedDecl *D)
Definition: Decl.cpp:1611
static LinkageInfo external()
Definition: Visibility.h:67
Linkage getLinkage() const
Definition: Visibility.h:83
void merge(LinkageInfo other)
Merge both linkage and visibility.
Definition: Visibility.h:132
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition: Type.h:4688
QualType desugar() const
Definition: Type.cpp:3661
QualType getModifiedType() const
Return this attributed type's modified type with no qualifiers attached to it.
Definition: Type.cpp:3663
QualType getUnderlyingType() const
Definition: Type.h:4704
const IdentifierInfo * getMacroIdentifier() const
Definition: Type.h:4703
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition: Type.h:3624
QualType getElementType() const