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"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Attr.h"
17#include "clang/AST/CharUnits.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclBase.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclFriend.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/DependenceFlags.h"
25#include "clang/AST/Expr.h"
26#include "clang/AST/NestedNameSpecifier.h"
27#include "clang/AST/PrettyPrinter.h"
28#include "clang/AST/TemplateBase.h"
29#include "clang/AST/TemplateName.h"
30#include "clang/AST/TypeVisitor.h"
31#include "clang/Basic/AddressSpaces.h"
32#include "clang/Basic/ExceptionSpecificationType.h"
33#include "clang/Basic/IdentifierTable.h"
34#include "clang/Basic/LLVM.h"
35#include "clang/Basic/LangOptions.h"
36#include "clang/Basic/Linkage.h"
37#include "clang/Basic/Specifiers.h"
38#include "clang/Basic/TargetCXXABI.h"
39#include "clang/Basic/TargetInfo.h"
40#include "clang/Basic/Visibility.h"
41#include "llvm/ADT/APInt.h"
42#include "llvm/ADT/APSInt.h"
43#include "llvm/ADT/ArrayRef.h"
44#include "llvm/ADT/FoldingSet.h"
45#include "llvm/ADT/STLExtras.h"
46#include "llvm/ADT/SmallVector.h"
47#include "llvm/Support/ErrorHandling.h"
48#include "llvm/Support/MathExtras.h"
49#include <algorithm>
50#include <cassert>
51#include <cstdint>
52#include <cstring>
53#include <optional>
54
55using namespace clang;
56
57bool Qualifiers::isStrictSupersetOf(Qualifiers Other) const {
58 return (*this != Other) &&
59 // CVR qualifiers superset
60 (((Mask & CVRMask) | (Other.Mask & CVRMask)) == (Mask & CVRMask)) &&
61 // ObjC GC qualifiers superset
62 ((getObjCGCAttr() == Other.getObjCGCAttr()) ||
63 (hasObjCGCAttr() && !Other.hasObjCGCAttr())) &&
64 // Address space superset.
65 ((getAddressSpace() == Other.getAddressSpace()) ||
66 (hasAddressSpace() && !Other.hasAddressSpace())) &&
67 // Lifetime qualifier superset.
68 ((getObjCLifetime() == Other.getObjCLifetime()) ||
69 (hasObjCLifetime() && !Other.hasObjCLifetime()));
70}
71
72bool Qualifiers::isTargetAddressSpaceSupersetOf(LangAS A, LangAS B,
73 const ASTContext &Ctx) {
74 // In OpenCLC v2.0 s6.5.5: every address space except for __constant can be
75 // used as __generic.
76 return (A == LangAS::opencl_generic && B != LangAS::opencl_constant) ||
77 // We also define global_device and global_host address spaces,
78 // to distinguish global pointers allocated on host from pointers
79 // allocated on device, which are a subset of __global.
80 (A == LangAS::opencl_global && (B == LangAS::opencl_global_device ||
81 B == LangAS::opencl_global_host)) ||
82 (A == LangAS::sycl_global &&
83 (B == LangAS::sycl_global_device || B == LangAS::sycl_global_host)) ||
84 // Consider pointer size address spaces to be equivalent to default.
85 ((isPtrSizeAddressSpace(AS: A) || A == LangAS::Default) &&
86 (isPtrSizeAddressSpace(AS: B) || B == LangAS::Default)) ||
87 // Default is a superset of SYCL address spaces.
88 (A == LangAS::Default &&
89 (B == LangAS::sycl_private || B == LangAS::sycl_local ||
90 B == LangAS::sycl_global || B == LangAS::sycl_global_device ||
91 B == LangAS::sycl_global_host)) ||
92 // In HIP device compilation, any cuda address space is allowed
93 // to implicitly cast into the default address space.
94 (A == LangAS::Default &&
95 (B == LangAS::cuda_constant || B == LangAS::cuda_device ||
96 B == LangAS::cuda_shared)) ||
97 // In HLSL, the this pointer for member functions points to the default
98 // address space. This causes a problem if the structure is in
99 // a different address space. We want to allow casting from these
100 // address spaces to default to work around this problem.
101 (A == LangAS::Default && B == LangAS::hlsl_private) ||
102 (A == LangAS::Default && B == LangAS::hlsl_device) ||
103 (A == LangAS::Default && B == LangAS::hlsl_input) ||
104 (A == LangAS::Default && B == LangAS::hlsl_push_constant) ||
105 // Conversions from target specific address spaces may be legal
106 // depending on the target information.
107 Ctx.getTargetInfo().isAddressSpaceSupersetOf(A, B);
108}
109
110const IdentifierInfo *QualType::getBaseTypeIdentifier() const {
111 const Type *ty = getTypePtr();
112 NamedDecl *ND = nullptr;
113 if (const auto *DNT = ty->getAs<DependentNameType>())
114 return DNT->getIdentifier();
115 if (ty->isPointerOrReferenceType())
116 return ty->getPointeeType().getBaseTypeIdentifier();
117 if (const auto *TT = ty->getAs<TagType>())
118 ND = TT->getDecl();
119 else if (ty->getTypeClass() == Type::Typedef)
120 ND = ty->castAs<TypedefType>()->getDecl();
121 else if (ty->isArrayType())
122 return ty->castAsArrayTypeUnsafe()
123 ->getElementType()
124 .getBaseTypeIdentifier();
125
126 if (ND)
127 return ND->getIdentifier();
128 return nullptr;
129}
130
131bool QualType::mayBeDynamicClass() const {
132 const auto *ClassDecl = getTypePtr()->getPointeeCXXRecordDecl();
133 return ClassDecl && ClassDecl->mayBeDynamicClass();
134}
135
136bool QualType::mayBeNotDynamicClass() const {
137 const auto *ClassDecl = getTypePtr()->getPointeeCXXRecordDecl();
138 return !ClassDecl || ClassDecl->mayBeNonDynamicClass();
139}
140
141bool QualType::isConstant(QualType T, const ASTContext &Ctx) {
142 if (T.isConstQualified())
143 return true;
144
145 if (const ArrayType *AT = Ctx.getAsArrayType(T))
146 return AT->getElementType().isConstant(Ctx);
147
148 return T.getAddressSpace() == LangAS::opencl_constant;
149}
150
151std::optional<QualType::NonConstantStorageReason>
152QualType::isNonConstantStorage(const ASTContext &Ctx, bool ExcludeCtor,
153 bool ExcludeDtor) {
154 if (!isConstant(Ctx) && !(*this)->isReferenceType())
155 return NonConstantStorageReason::NonConstNonReferenceType;
156 if (!Ctx.getLangOpts().CPlusPlus)
157 return std::nullopt;
158 if (const CXXRecordDecl *Record =
159 Ctx.getBaseElementType(QT: *this)->getAsCXXRecordDecl()) {
160 if (!ExcludeCtor)
161 return NonConstantStorageReason::NonTrivialCtor;
162 if (Record->hasMutableFields())
163 return NonConstantStorageReason::MutableField;
164 if (!Record->hasTrivialDestructor() && !ExcludeDtor)
165 return NonConstantStorageReason::NonTrivialDtor;
166 }
167 return std::nullopt;
168}
169
170// C++ [temp.dep.type]p1:
171// A type is dependent if it is...
172// - an array type constructed from any dependent type or whose
173// size is specified by a constant expression that is
174// value-dependent,
175ArrayType::ArrayType(TypeClass tc, QualType et, QualType can,
176 ArraySizeModifier sm, unsigned tq, const Expr *sz)
177 // Note, we need to check for DependentSizedArrayType explicitly here
178 // because we use a DependentSizedArrayType with no size expression as the
179 // type of a dependent array of unknown bound with a dependent braced
180 // initializer:
181 //
182 // template<int ...N> int arr[] = {N...};
183 : Type(tc, can,
184 et->getDependence() |
185 (sz ? toTypeDependence(
186 D: turnValueToTypeDependence(D: sz->getDependence()))
187 : TypeDependence::None) |
188 (tc == VariableArray ? TypeDependence::VariablyModified
189 : TypeDependence::None) |
190 (tc == DependentSizedArray
191 ? TypeDependence::DependentInstantiation
192 : TypeDependence::None)),
193 ElementType(et) {
194 ArrayTypeBits.IndexTypeQuals = tq;
195 ArrayTypeBits.SizeModifier = llvm::to_underlying(E: sm);
196}
197
198ConstantArrayType *
199ConstantArrayType::Create(const ASTContext &Ctx, QualType ET, QualType Can,
200 const llvm::APInt &Sz, const Expr *SzExpr,
201 ArraySizeModifier SzMod, unsigned Qual) {
202 bool NeedsExternalSize = SzExpr != nullptr || Sz.ugt(RHS: 0x0FFFFFFFFFFFFFFF) ||
203 Sz.getBitWidth() > 0xFF;
204 if (!NeedsExternalSize)
205 return new (Ctx, alignof(ConstantArrayType)) ConstantArrayType(
206 ET, Can, Sz.getBitWidth(), Sz.getZExtValue(), SzMod, Qual);
207
208 auto *SzPtr = new (Ctx, alignof(ConstantArrayType::ExternalSize))
209 ConstantArrayType::ExternalSize(Sz, SzExpr);
210 return new (Ctx, alignof(ConstantArrayType))
211 ConstantArrayType(ET, Can, SzPtr, SzMod, Qual);
212}
213
214unsigned
215ConstantArrayType::getNumAddressingBits(const ASTContext &Context,
216 QualType ElementType,
217 const llvm::APInt &NumElements) {
218 uint64_t ElementSize = Context.getTypeSizeInChars(T: ElementType).getQuantity();
219
220 // Fast path the common cases so we can avoid the conservative computation
221 // below, which in common cases allocates "large" APSInt values, which are
222 // slow.
223
224 // If the element size is a power of 2, we can directly compute the additional
225 // number of addressing bits beyond those required for the element count.
226 if (llvm::isPowerOf2_64(Value: ElementSize)) {
227 return NumElements.getActiveBits() + llvm::Log2_64(Value: ElementSize);
228 }
229
230 // If both the element count and element size fit in 32-bits, we can do the
231 // computation directly in 64-bits.
232 if ((ElementSize >> 32) == 0 && NumElements.getBitWidth() <= 64 &&
233 (NumElements.getZExtValue() >> 32) == 0) {
234 uint64_t TotalSize = NumElements.getZExtValue() * ElementSize;
235 return llvm::bit_width(Value: TotalSize);
236 }
237
238 // Otherwise, use APSInt to handle arbitrary sized values.
239 llvm::APSInt SizeExtended(NumElements, true);
240 unsigned SizeTypeBits = Context.getTypeSize(T: Context.getSizeType());
241 SizeExtended = SizeExtended.extend(
242 width: std::max(a: SizeTypeBits, b: SizeExtended.getBitWidth()) * 2);
243
244 llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize));
245 TotalSize *= SizeExtended;
246
247 return TotalSize.getActiveBits();
248}
249
250unsigned
251ConstantArrayType::getNumAddressingBits(const ASTContext &Context) const {
252 return getNumAddressingBits(Context, ElementType: getElementType(), NumElements: getSize());
253}
254
255unsigned ConstantArrayType::getMaxSizeBits(const ASTContext &Context) {
256 unsigned Bits = Context.getTypeSize(T: Context.getSizeType());
257
258 // Limit the number of bits in size_t so that maximal bit size fits 64 bit
259 // integer (see PR8256). We can do this as currently there is no hardware
260 // that supports full 64-bit virtual space.
261 if (Bits > 61)
262 Bits = 61;
263
264 return Bits;
265}
266
267void ConstantArrayType::Profile(llvm::FoldingSetNodeID &ID,
268 const ASTContext &Context, QualType ET,
269 uint64_t ArraySize, const Expr *SizeExpr,
270 ArraySizeModifier SizeMod, unsigned TypeQuals) {
271 ID.AddPointer(Ptr: ET.getAsOpaquePtr());
272 ID.AddInteger(I: ArraySize);
273 ID.AddInteger(I: llvm::to_underlying(E: SizeMod));
274 ID.AddInteger(I: TypeQuals);
275 ID.AddBoolean(B: SizeExpr != nullptr);
276 if (SizeExpr)
277 SizeExpr->Profile(ID, Context, Canonical: true);
278}
279
280QualType ArrayParameterType::getConstantArrayType(const ASTContext &Ctx) const {
281 return Ctx.getConstantArrayType(EltTy: getElementType(), ArySize: getSize(), SizeExpr: getSizeExpr(),
282 ASM: getSizeModifier(),
283 IndexTypeQuals: getIndexTypeQualifiers().getAsOpaqueValue());
284}
285
286DependentSizedArrayType::DependentSizedArrayType(QualType et, QualType can,
287 Expr *e, ArraySizeModifier sm,
288 unsigned tq)
289 : ArrayType(DependentSizedArray, et, can, sm, tq, e), SizeExpr((Stmt *)e) {}
290
291void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID,
292 const ASTContext &Context, QualType ET,
293 ArraySizeModifier SizeMod,
294 unsigned TypeQuals, Expr *E) {
295 ID.AddPointer(Ptr: ET.getAsOpaquePtr());
296 ID.AddInteger(I: llvm::to_underlying(E: SizeMod));
297 ID.AddInteger(I: TypeQuals);
298 if (E)
299 E->Profile(ID, Context, Canonical: true);
300}
301
302DependentVectorType::DependentVectorType(QualType ElementType,
303 QualType CanonType, Expr *SizeExpr,
304 SourceLocation Loc, VectorKind VecKind)
305 : Type(DependentVector, CanonType,
306 TypeDependence::DependentInstantiation |
307 ElementType->getDependence() |
308 (SizeExpr ? toTypeDependence(D: SizeExpr->getDependence())
309 : TypeDependence::None)),
310 ElementType(ElementType), SizeExpr(SizeExpr), Loc(Loc) {
311 VectorTypeBits.VecKind = llvm::to_underlying(E: VecKind);
312}
313
314void DependentVectorType::Profile(llvm::FoldingSetNodeID &ID,
315 const ASTContext &Context,
316 QualType ElementType, const Expr *SizeExpr,
317 VectorKind VecKind) {
318 ID.AddPointer(Ptr: ElementType.getAsOpaquePtr());
319 ID.AddInteger(I: llvm::to_underlying(E: VecKind));
320 SizeExpr->Profile(ID, Context, Canonical: true);
321}
322
323DependentSizedExtVectorType::DependentSizedExtVectorType(QualType ElementType,
324 QualType can,
325 Expr *SizeExpr,
326 SourceLocation loc)
327 : Type(DependentSizedExtVector, can,
328 TypeDependence::DependentInstantiation |
329 ElementType->getDependence() |
330 (SizeExpr ? toTypeDependence(D: SizeExpr->getDependence())
331 : TypeDependence::None)),
332 SizeExpr(SizeExpr), ElementType(ElementType), loc(loc) {}
333
334void DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID,
335 const ASTContext &Context,
336 QualType ElementType,
337 Expr *SizeExpr) {
338 ID.AddPointer(Ptr: ElementType.getAsOpaquePtr());
339 SizeExpr->Profile(ID, Context, Canonical: true);
340}
341
342DependentAddressSpaceType::DependentAddressSpaceType(QualType PointeeType,
343 QualType can,
344 Expr *AddrSpaceExpr,
345 SourceLocation loc)
346 : Type(DependentAddressSpace, can,
347 TypeDependence::DependentInstantiation |
348 PointeeType->getDependence() |
349 (AddrSpaceExpr ? toTypeDependence(D: AddrSpaceExpr->getDependence())
350 : TypeDependence::None)),
351 AddrSpaceExpr(AddrSpaceExpr), PointeeType(PointeeType), loc(loc) {}
352
353void DependentAddressSpaceType::Profile(llvm::FoldingSetNodeID &ID,
354 const ASTContext &Context,
355 QualType PointeeType,
356 Expr *AddrSpaceExpr) {
357 ID.AddPointer(Ptr: PointeeType.getAsOpaquePtr());
358 AddrSpaceExpr->Profile(ID, Context, Canonical: true);
359}
360
361MatrixType::MatrixType(TypeClass tc, QualType matrixType, QualType canonType,
362 const Expr *RowExpr, const Expr *ColumnExpr)
363 : Type(tc, canonType,
364 (RowExpr ? (matrixType->getDependence() | TypeDependence::Dependent |
365 TypeDependence::Instantiation |
366 (matrixType->isVariablyModifiedType()
367 ? TypeDependence::VariablyModified
368 : TypeDependence::None) |
369 (matrixType->containsUnexpandedParameterPack() ||
370 (RowExpr &&
371 RowExpr->containsUnexpandedParameterPack()) ||
372 (ColumnExpr &&
373 ColumnExpr->containsUnexpandedParameterPack())
374 ? TypeDependence::UnexpandedPack
375 : TypeDependence::None))
376 : matrixType->getDependence())),
377 ElementType(matrixType) {}
378
379ConstantMatrixType::ConstantMatrixType(QualType matrixType, unsigned nRows,
380 unsigned nColumns, QualType canonType)
381 : ConstantMatrixType(ConstantMatrix, matrixType, nRows, nColumns,
382 canonType) {}
383
384ConstantMatrixType::ConstantMatrixType(TypeClass tc, QualType matrixType,
385 unsigned nRows, unsigned nColumns,
386 QualType canonType)
387 : MatrixType(tc, matrixType, canonType), NumRows(nRows),
388 NumColumns(nColumns) {}
389
390DependentSizedMatrixType::DependentSizedMatrixType(QualType ElementType,
391 QualType CanonicalType,
392 Expr *RowExpr,
393 Expr *ColumnExpr,
394 SourceLocation loc)
395 : MatrixType(DependentSizedMatrix, ElementType, CanonicalType, RowExpr,
396 ColumnExpr),
397 RowExpr(RowExpr), ColumnExpr(ColumnExpr), loc(loc) {}
398
399void DependentSizedMatrixType::Profile(llvm::FoldingSetNodeID &ID,
400 const ASTContext &CTX,
401 QualType ElementType, Expr *RowExpr,
402 Expr *ColumnExpr) {
403 ID.AddPointer(Ptr: ElementType.getAsOpaquePtr());
404 RowExpr->Profile(ID, Context: CTX, Canonical: true);
405 ColumnExpr->Profile(ID, Context: CTX, Canonical: true);
406}
407
408VectorType::VectorType(QualType vecType, unsigned nElements, QualType canonType,
409 VectorKind vecKind)
410 : VectorType(Vector, vecType, nElements, canonType, vecKind) {}
411
412VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements,
413 QualType canonType, VectorKind vecKind)
414 : Type(tc, canonType, vecType->getDependence()), ElementType(vecType) {
415 VectorTypeBits.VecKind = llvm::to_underlying(E: vecKind);
416 VectorTypeBits.NumElements = nElements;
417}
418
419bool Type::isPackedVectorBoolType(const ASTContext &ctx) const {
420 if (ctx.getLangOpts().HLSL)
421 return false;
422 return isExtVectorBoolType();
423}
424
425BitIntType::BitIntType(bool IsUnsigned, unsigned NumBits)
426 : Type(BitInt, QualType{}, TypeDependence::None), IsUnsigned(IsUnsigned),
427 NumBits(NumBits) {}
428
429DependentBitIntType::DependentBitIntType(bool IsUnsigned, Expr *NumBitsExpr)
430 : Type(DependentBitInt, QualType{},
431 toTypeDependence(D: NumBitsExpr->getDependence())),
432 ExprAndUnsigned(NumBitsExpr, IsUnsigned) {}
433
434bool DependentBitIntType::isUnsigned() const {
435 return ExprAndUnsigned.getInt();
436}
437
438clang::Expr *DependentBitIntType::getNumBitsExpr() const {
439 return ExprAndUnsigned.getPointer();
440}
441
442void DependentBitIntType::Profile(llvm::FoldingSetNodeID &ID,
443 const ASTContext &Context, bool IsUnsigned,
444 Expr *NumBitsExpr) {
445 ID.AddBoolean(B: IsUnsigned);
446 NumBitsExpr->Profile(ID, Context, Canonical: true);
447}
448
449bool BoundsAttributedType::referencesFieldDecls() const {
450 return llvm::any_of(Range: dependent_decls(),
451 P: [](const TypeCoupledDeclRefInfo &Info) {
452 return isa<FieldDecl>(Val: Info.getDecl());
453 });
454}
455
456void CountAttributedType::Profile(llvm::FoldingSetNodeID &ID,
457 QualType WrappedTy, Expr *CountExpr,
458 bool CountInBytes, bool OrNull) {
459 ID.AddPointer(Ptr: WrappedTy.getAsOpaquePtr());
460 ID.AddBoolean(B: CountInBytes);
461 ID.AddBoolean(B: OrNull);
462 // We profile it as a pointer as the StmtProfiler considers parameter
463 // expressions on function declaration and function definition as the
464 // same, resulting in count expression being evaluated with ParamDecl
465 // not in the function scope.
466 ID.AddPointer(Ptr: CountExpr);
467}
468
469/// getArrayElementTypeNoTypeQual - If this is an array type, return the
470/// element type of the array, potentially with type qualifiers missing.
471/// This method should never be used when type qualifiers are meaningful.
472const Type *Type::getArrayElementTypeNoTypeQual() const {
473 // If this is directly an array type, return it.
474 if (const auto *ATy = dyn_cast<ArrayType>(Val: this))
475 return ATy->getElementType().getTypePtr();
476
477 // If the canonical form of this type isn't the right kind, reject it.
478 if (!isa<ArrayType>(Val: CanonicalType))
479 return nullptr;
480
481 // If this is a typedef for an array type, strip the typedef off without
482 // losing all typedef information.
483 return cast<ArrayType>(Val: getUnqualifiedDesugaredType())
484 ->getElementType()
485 .getTypePtr();
486}
487
488/// getDesugaredType - Return the specified type with any "sugar" removed from
489/// the type. This takes off typedefs, typeof's etc. If the outer level of
490/// the type is already concrete, it returns it unmodified. This is similar
491/// to getting the canonical type, but it doesn't remove *all* typedefs. For
492/// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
493/// concrete.
494QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) {
495 SplitQualType split = getSplitDesugaredType(T);
496 return Context.getQualifiedType(T: split.Ty, Qs: split.Quals);
497}
498
499QualType QualType::getSingleStepDesugaredTypeImpl(QualType type,
500 const ASTContext &Context) {
501 SplitQualType split = type.split();
502 QualType desugar = split.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
503 return Context.getQualifiedType(T: desugar, Qs: split.Quals);
504}
505
506// Check that no type class is polymorphic. LLVM style RTTI should be used
507// instead. If absolutely needed an exception can still be added here by
508// defining the appropriate macro (but please don't do this).
509#define TYPE(CLASS, BASE) \
510 static_assert(!std::is_polymorphic<CLASS##Type>::value, \
511 #CLASS "Type should not be polymorphic!");
512#include "clang/AST/TypeNodes.inc"
513
514// Check that no type class has a non-trival destructor. Types are
515// allocated with the BumpPtrAllocator from ASTContext and therefore
516// their destructor is not executed.
517#define TYPE(CLASS, BASE) \
518 static_assert(std::is_trivially_destructible<CLASS##Type>::value, \
519 #CLASS "Type should be trivially destructible!");
520#include "clang/AST/TypeNodes.inc"
521
522QualType Type::getLocallyUnqualifiedSingleStepDesugaredType() const {
523 switch (getTypeClass()) {
524#define ABSTRACT_TYPE(Class, Parent)
525#define TYPE(Class, Parent) \
526 case Type::Class: { \
527 const auto *ty = cast<Class##Type>(this); \
528 if (!ty->isSugared()) \
529 return QualType(ty, 0); \
530 return ty->desugar(); \
531 }
532#include "clang/AST/TypeNodes.inc"
533 }
534 llvm_unreachable("bad type kind!");
535}
536
537SplitQualType QualType::getSplitDesugaredType(QualType T) {
538 QualifierCollector Qs;
539
540 QualType Cur = T;
541 while (true) {
542 const Type *CurTy = Qs.strip(type: Cur);
543 switch (CurTy->getTypeClass()) {
544#define ABSTRACT_TYPE(Class, Parent)
545#define TYPE(Class, Parent) \
546 case Type::Class: { \
547 const auto *Ty = cast<Class##Type>(CurTy); \
548 if (!Ty->isSugared()) \
549 return SplitQualType(Ty, Qs); \
550 Cur = Ty->desugar(); \
551 break; \
552 }
553#include "clang/AST/TypeNodes.inc"
554 }
555 }
556}
557
558SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) {
559 SplitQualType split = type.split();
560
561 // All the qualifiers we've seen so far.
562 Qualifiers quals = split.Quals;
563
564 // The last type node we saw with any nodes inside it.
565 const Type *lastTypeWithQuals = split.Ty;
566
567 while (true) {
568 QualType next;
569
570 // Do a single-step desugar, aborting the loop if the type isn't
571 // sugared.
572 switch (split.Ty->getTypeClass()) {
573#define ABSTRACT_TYPE(Class, Parent)
574#define TYPE(Class, Parent) \
575 case Type::Class: { \
576 const auto *ty = cast<Class##Type>(split.Ty); \
577 if (!ty->isSugared()) \
578 goto done; \
579 next = ty->desugar(); \
580 break; \
581 }
582#include "clang/AST/TypeNodes.inc"
583 }
584
585 // Otherwise, split the underlying type. If that yields qualifiers,
586 // update the information.
587 split = next.split();
588 if (!split.Quals.empty()) {
589 lastTypeWithQuals = split.Ty;
590 quals.addConsistentQualifiers(qs: split.Quals);
591 }
592 }
593
594done:
595 return SplitQualType(lastTypeWithQuals, quals);
596}
597
598QualType QualType::IgnoreParens(QualType T) {
599 // FIXME: this seems inherently un-qualifiers-safe.
600 while (const auto *PT = T->getAs<ParenType>())
601 T = PT->getInnerType();
602 return T;
603}
604
605/// This will check for a T (which should be a Type which can act as
606/// sugar, such as a TypedefType) by removing any existing sugar until it
607/// reaches a T or a non-sugared type.
608template <typename T> static const T *getAsSugar(const Type *Cur) {
609 while (true) {
610 if (const auto *Sugar = dyn_cast<T>(Cur))
611 return Sugar;
612 switch (Cur->getTypeClass()) {
613#define ABSTRACT_TYPE(Class, Parent)
614#define TYPE(Class, Parent) \
615 case Type::Class: { \
616 const auto *Ty = cast<Class##Type>(Cur); \
617 if (!Ty->isSugared()) \
618 return 0; \
619 Cur = Ty->desugar().getTypePtr(); \
620 break; \
621 }
622#include "clang/AST/TypeNodes.inc"
623 }
624 }
625}
626
627template <> const TypedefType *Type::getAs() const {
628 return getAsSugar<TypedefType>(Cur: this);
629}
630
631template <> const UsingType *Type::getAs() const {
632 return getAsSugar<UsingType>(Cur: this);
633}
634
635template <> const TemplateSpecializationType *Type::getAs() const {
636 return getAsSugar<TemplateSpecializationType>(Cur: this);
637}
638
639template <> const AttributedType *Type::getAs() const {
640 return getAsSugar<AttributedType>(Cur: this);
641}
642
643template <> const BoundsAttributedType *Type::getAs() const {
644 return getAsSugar<BoundsAttributedType>(Cur: this);
645}
646
647template <> const CountAttributedType *Type::getAs() const {
648 return getAsSugar<CountAttributedType>(Cur: this);
649}
650
651/// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
652/// sugar off the given type. This should produce an object of the
653/// same dynamic type as the canonical type.
654const Type *Type::getUnqualifiedDesugaredType() const {
655 const Type *Cur = this;
656
657 while (true) {
658 switch (Cur->getTypeClass()) {
659#define ABSTRACT_TYPE(Class, Parent)
660#define TYPE(Class, Parent) \
661 case Class: { \
662 const auto *Ty = cast<Class##Type>(Cur); \
663 if (!Ty->isSugared()) \
664 return Cur; \
665 Cur = Ty->desugar().getTypePtr(); \
666 break; \
667 }
668#include "clang/AST/TypeNodes.inc"
669 }
670 }
671}
672
673bool Type::isClassType() const {
674 if (const auto *RT = getAsCanonical<RecordType>())
675 return RT->getDecl()->isClass();
676 return false;
677}
678
679bool Type::isStructureType() const {
680 if (const auto *RT = getAsCanonical<RecordType>())
681 return RT->getDecl()->isStruct();
682 return false;
683}
684
685bool Type::isStructureTypeWithFlexibleArrayMember() const {
686 const auto *RT = getAsCanonical<RecordType>();
687 if (!RT)
688 return false;
689 const auto *Decl = RT->getDecl();
690 if (!Decl->isStruct())
691 return false;
692 return Decl->getDefinitionOrSelf()->hasFlexibleArrayMember();
693}
694
695bool Type::isObjCBoxableRecordType() const {
696 if (const auto *RD = getAsRecordDecl())
697 return RD->hasAttr<ObjCBoxableAttr>();
698 return false;
699}
700
701bool Type::isInterfaceType() const {
702 if (const auto *RT = getAsCanonical<RecordType>())
703 return RT->getDecl()->isInterface();
704 return false;
705}
706
707bool Type::isStructureOrClassType() const {
708 if (const auto *RT = getAsCanonical<RecordType>())
709 return RT->getDecl()->isStructureOrClass();
710 return false;
711}
712
713bool Type::isVoidPointerType() const {
714 if (const auto *PT = getAsCanonical<PointerType>())
715 return PT->getPointeeType()->isVoidType();
716 return false;
717}
718
719bool Type::isUnionType() const {
720 if (const auto *RT = getAsCanonical<RecordType>())
721 return RT->getDecl()->isUnion();
722 return false;
723}
724
725bool Type::isComplexType() const {
726 if (const auto *CT = getAsCanonical<ComplexType>())
727 return CT->getElementType()->isFloatingType();
728 return false;
729}
730
731bool Type::isComplexIntegerType() const {
732 // Check for GCC complex integer extension.
733 return getAsComplexIntegerType();
734}
735
736bool Type::isScopedEnumeralType() const {
737 if (const auto *ET = getAsCanonical<EnumType>())
738 return ET->getDecl()->isScoped();
739 return false;
740}
741
742bool Type::isCountAttributedType() const {
743 return getAs<CountAttributedType>();
744}
745
746const ComplexType *Type::getAsComplexIntegerType() const {
747 if (const auto *Complex = getAs<ComplexType>())
748 if (Complex->getElementType()->isIntegerType())
749 return Complex;
750 return nullptr;
751}
752
753QualType Type::getPointeeType() const {
754 if (const auto *PT = getAs<PointerType>())
755 return PT->getPointeeType();
756 if (const auto *OPT = getAs<ObjCObjectPointerType>())
757 return OPT->getPointeeType();
758 if (const auto *BPT = getAs<BlockPointerType>())
759 return BPT->getPointeeType();
760 if (const auto *RT = getAs<ReferenceType>())
761 return RT->getPointeeType();
762 if (const auto *MPT = getAs<MemberPointerType>())
763 return MPT->getPointeeType();
764 if (const auto *DT = getAs<DecayedType>())
765 return DT->getPointeeType();
766 return {};
767}
768
769const RecordType *Type::getAsStructureType() const {
770 // If this is directly a structure type, return it.
771 if (const auto *RT = dyn_cast<RecordType>(Val: this)) {
772 if (RT->getDecl()->isStruct())
773 return RT;
774 }
775
776 // If the canonical form of this type isn't the right kind, reject it.
777 if (const auto *RT = dyn_cast<RecordType>(Val: CanonicalType)) {
778 if (!RT->getDecl()->isStruct())
779 return nullptr;
780
781 // If this is a typedef for a structure type, strip the typedef off without
782 // losing all typedef information.
783 return cast<RecordType>(Val: getUnqualifiedDesugaredType());
784 }
785 return nullptr;
786}
787
788const RecordType *Type::getAsUnionType() const {
789 // If this is directly a union type, return it.
790 if (const auto *RT = dyn_cast<RecordType>(Val: this)) {
791 if (RT->getDecl()->isUnion())
792 return RT;
793 }
794
795 // If the canonical form of this type isn't the right kind, reject it.
796 if (const auto *RT = dyn_cast<RecordType>(Val: CanonicalType)) {
797 if (!RT->getDecl()->isUnion())
798 return nullptr;
799
800 // If this is a typedef for a union type, strip the typedef off without
801 // losing all typedef information.
802 return cast<RecordType>(Val: getUnqualifiedDesugaredType());
803 }
804
805 return nullptr;
806}
807
808bool Type::isObjCIdOrObjectKindOfType(const ASTContext &ctx,
809 const ObjCObjectType *&bound) const {
810 bound = nullptr;
811
812 const auto *OPT = getAs<ObjCObjectPointerType>();
813 if (!OPT)
814 return false;
815
816 // Easy case: id.
817 if (OPT->isObjCIdType())
818 return true;
819
820 // If it's not a __kindof type, reject it now.
821 if (!OPT->isKindOfType())
822 return false;
823
824 // If it's Class or qualified Class, it's not an object type.
825 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType())
826 return false;
827
828 // Figure out the type bound for the __kindof type.
829 bound = OPT->getObjectType()
830 ->stripObjCKindOfTypeAndQuals(ctx)
831 ->getAs<ObjCObjectType>();
832 return true;
833}
834
835bool Type::isObjCClassOrClassKindOfType() const {
836 const auto *OPT = getAs<ObjCObjectPointerType>();
837 if (!OPT)
838 return false;
839
840 // Easy case: Class.
841 if (OPT->isObjCClassType())
842 return true;
843
844 // If it's not a __kindof type, reject it now.
845 if (!OPT->isKindOfType())
846 return false;
847
848 // If it's Class or qualified Class, it's a class __kindof type.
849 return OPT->isObjCClassType() || OPT->isObjCQualifiedClassType();
850}
851
852ObjCTypeParamType::ObjCTypeParamType(const ObjCTypeParamDecl *D, QualType can,
853 ArrayRef<ObjCProtocolDecl *> protocols)
854 : Type(ObjCTypeParam, can, toSemanticDependence(D: can->getDependence())),
855 OTPDecl(const_cast<ObjCTypeParamDecl *>(D)) {
856 initialize(protocols);
857}
858
859ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base,
860 ArrayRef<QualType> typeArgs,
861 ArrayRef<ObjCProtocolDecl *> protocols,
862 bool isKindOf)
863 : Type(ObjCObject, Canonical, Base->getDependence()), BaseType(Base) {
864 ObjCObjectTypeBits.IsKindOf = isKindOf;
865
866 ObjCObjectTypeBits.NumTypeArgs = typeArgs.size();
867 assert(getTypeArgsAsWritten().size() == typeArgs.size() &&
868 "bitfield overflow in type argument count");
869 if (!typeArgs.empty())
870 memcpy(dest: getTypeArgStorage(), src: typeArgs.data(),
871 n: typeArgs.size() * sizeof(QualType));
872
873 for (auto typeArg : typeArgs) {
874 addDependence(D: typeArg->getDependence() & ~TypeDependence::VariablyModified);
875 }
876 // Initialize the protocol qualifiers. The protocol storage is known
877 // after we set number of type arguments.
878 initialize(protocols);
879}
880
881bool ObjCObjectType::isSpecialized() const {
882 // If we have type arguments written here, the type is specialized.
883 if (ObjCObjectTypeBits.NumTypeArgs > 0)
884 return true;
885
886 // Otherwise, check whether the base type is specialized.
887 if (const auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
888 // Terminate when we reach an interface type.
889 if (isa<ObjCInterfaceType>(Val: objcObject))
890 return false;
891
892 return objcObject->isSpecialized();
893 }
894
895 // Not specialized.
896 return false;
897}
898
899ArrayRef<QualType> ObjCObjectType::getTypeArgs() const {
900 // We have type arguments written on this type.
901 if (isSpecializedAsWritten())
902 return getTypeArgsAsWritten();
903
904 // Look at the base type, which might have type arguments.
905 if (const auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
906 // Terminate when we reach an interface type.
907 if (isa<ObjCInterfaceType>(Val: objcObject))
908 return {};
909
910 return objcObject->getTypeArgs();
911 }
912
913 // No type arguments.
914 return {};
915}
916
917bool ObjCObjectType::isKindOfType() const {
918 if (isKindOfTypeAsWritten())
919 return true;
920
921 // Look at the base type, which might have type arguments.
922 if (const auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
923 // Terminate when we reach an interface type.
924 if (isa<ObjCInterfaceType>(Val: objcObject))
925 return false;
926
927 return objcObject->isKindOfType();
928 }
929
930 // Not a "__kindof" type.
931 return false;
932}
933
934QualType
935ObjCObjectType::stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const {
936 if (!isKindOfType() && qual_empty())
937 return QualType(this, 0);
938
939 // Recursively strip __kindof.
940 SplitQualType splitBaseType = getBaseType().split();
941 QualType baseType(splitBaseType.Ty, 0);
942 if (const auto *baseObj = splitBaseType.Ty->getAs<ObjCObjectType>())
943 baseType = baseObj->stripObjCKindOfTypeAndQuals(ctx);
944
945 return ctx.getObjCObjectType(
946 Base: ctx.getQualifiedType(T: baseType, Qs: splitBaseType.Quals),
947 typeArgs: getTypeArgsAsWritten(),
948 /*protocols=*/{},
949 /*isKindOf=*/false);
950}
951
952ObjCInterfaceDecl *ObjCInterfaceType::getDecl() const {
953 ObjCInterfaceDecl *Canon = Decl->getCanonicalDecl();
954 if (ObjCInterfaceDecl *Def = Canon->getDefinition())
955 return Def;
956 return Canon;
957}
958
959const ObjCObjectPointerType *ObjCObjectPointerType::stripObjCKindOfTypeAndQuals(
960 const ASTContext &ctx) const {
961 if (!isKindOfType() && qual_empty())
962 return this;
963
964 QualType obj = getObjectType()->stripObjCKindOfTypeAndQuals(ctx);
965 return ctx.getObjCObjectPointerType(OIT: obj)->castAs<ObjCObjectPointerType>();
966}
967
968namespace {
969
970/// Visitor used to perform a simple type transformation that does not change
971/// the semantics of the type.
972template <typename Derived>
973struct SimpleTransformVisitor : public TypeVisitor<Derived, QualType> {
974 ASTContext &Ctx;
975
976 QualType recurse(QualType type) {
977 // Split out the qualifiers from the type.
978 SplitQualType splitType = type.split();
979
980 // Visit the type itself.
981 QualType result = static_cast<Derived *>(this)->Visit(splitType.Ty);
982 if (result.isNull())
983 return result;
984
985 // Reconstruct the transformed type by applying the local qualifiers
986 // from the split type.
987 return Ctx.getQualifiedType(T: result, Qs: splitType.Quals);
988 }
989
990public:
991 explicit SimpleTransformVisitor(ASTContext &ctx) : Ctx(ctx) {}
992
993 // None of the clients of this transformation can occur where
994 // there are dependent types, so skip dependent types.
995#define TYPE(Class, Base)
996#define DEPENDENT_TYPE(Class, Base) \
997 QualType Visit##Class##Type(const Class##Type *T) { return QualType(T, 0); }
998#include "clang/AST/TypeNodes.inc"
999
1000#define TRIVIAL_TYPE_CLASS(Class) \
1001 QualType Visit##Class##Type(const Class##Type *T) { return QualType(T, 0); }
1002#define SUGARED_TYPE_CLASS(Class) \
1003 QualType Visit##Class##Type(const Class##Type *T) { \
1004 if (!T->isSugared()) \
1005 return QualType(T, 0); \
1006 QualType desugaredType = recurse(T->desugar()); \
1007 if (desugaredType.isNull()) \
1008 return {}; \
1009 if (desugaredType.getAsOpaquePtr() == T->desugar().getAsOpaquePtr()) \
1010 return QualType(T, 0); \
1011 return desugaredType; \
1012 }
1013
1014 TRIVIAL_TYPE_CLASS(Builtin)
1015
1016 QualType VisitComplexType(const ComplexType *T) {
1017 QualType elementType = recurse(type: T->getElementType());
1018 if (elementType.isNull())
1019 return {};
1020
1021 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
1022 return QualType(T, 0);
1023
1024 return Ctx.getComplexType(T: elementType);
1025 }
1026
1027 QualType VisitPointerType(const PointerType *T) {
1028 QualType pointeeType = recurse(type: T->getPointeeType());
1029 if (pointeeType.isNull())
1030 return {};
1031
1032 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
1033 return QualType(T, 0);
1034
1035 return Ctx.getPointerType(T: pointeeType);
1036 }
1037
1038 QualType VisitBlockPointerType(const BlockPointerType *T) {
1039 QualType pointeeType = recurse(type: T->getPointeeType());
1040 if (pointeeType.isNull())
1041 return {};
1042
1043 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
1044 return QualType(T, 0);
1045
1046 return Ctx.getBlockPointerType(T: pointeeType);
1047 }
1048
1049 QualType VisitLValueReferenceType(const LValueReferenceType *T) {
1050 QualType pointeeType = recurse(type: T->getPointeeTypeAsWritten());
1051 if (pointeeType.isNull())
1052 return {};
1053
1054 if (pointeeType.getAsOpaquePtr() ==
1055 T->getPointeeTypeAsWritten().getAsOpaquePtr())
1056 return QualType(T, 0);
1057
1058 return Ctx.getLValueReferenceType(T: pointeeType, SpelledAsLValue: T->isSpelledAsLValue());
1059 }
1060
1061 QualType VisitRValueReferenceType(const RValueReferenceType *T) {
1062 QualType pointeeType = recurse(type: T->getPointeeTypeAsWritten());
1063 if (pointeeType.isNull())
1064 return {};
1065
1066 if (pointeeType.getAsOpaquePtr() ==
1067 T->getPointeeTypeAsWritten().getAsOpaquePtr())
1068 return QualType(T, 0);
1069
1070 return Ctx.getRValueReferenceType(T: pointeeType);
1071 }
1072
1073 QualType VisitMemberPointerType(const MemberPointerType *T) {
1074 QualType pointeeType = recurse(type: T->getPointeeType());
1075 if (pointeeType.isNull())
1076 return {};
1077
1078 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
1079 return QualType(T, 0);
1080
1081 return Ctx.getMemberPointerType(T: pointeeType, Qualifier: T->getQualifier(),
1082 Cls: T->getMostRecentCXXRecordDecl());
1083 }
1084
1085 QualType VisitConstantArrayType(const ConstantArrayType *T) {
1086 QualType elementType = recurse(type: T->getElementType());
1087 if (elementType.isNull())
1088 return {};
1089
1090 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
1091 return QualType(T, 0);
1092
1093 return Ctx.getConstantArrayType(EltTy: elementType, ArySize: T->getSize(), SizeExpr: T->getSizeExpr(),
1094 ASM: T->getSizeModifier(),
1095 IndexTypeQuals: T->getIndexTypeCVRQualifiers());
1096 }
1097
1098 QualType VisitVariableArrayType(const VariableArrayType *T) {
1099 QualType elementType = recurse(type: T->getElementType());
1100 if (elementType.isNull())
1101 return {};
1102
1103 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
1104 return QualType(T, 0);
1105
1106 return Ctx.getVariableArrayType(EltTy: elementType, NumElts: T->getSizeExpr(),
1107 ASM: T->getSizeModifier(),
1108 IndexTypeQuals: T->getIndexTypeCVRQualifiers());
1109 }
1110
1111 QualType VisitIncompleteArrayType(const IncompleteArrayType *T) {
1112 QualType elementType = recurse(type: T->getElementType());
1113 if (elementType.isNull())
1114 return {};
1115
1116 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
1117 return QualType(T, 0);
1118
1119 return Ctx.getIncompleteArrayType(EltTy: elementType, ASM: T->getSizeModifier(),
1120 IndexTypeQuals: T->getIndexTypeCVRQualifiers());
1121 }
1122
1123 QualType VisitVectorType(const VectorType *T) {
1124 QualType elementType = recurse(type: T->getElementType());
1125 if (elementType.isNull())
1126 return {};
1127
1128 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
1129 return QualType(T, 0);
1130
1131 return Ctx.getVectorType(VectorType: elementType, NumElts: T->getNumElements(),
1132 VecKind: T->getVectorKind());
1133 }
1134
1135 QualType VisitExtVectorType(const ExtVectorType *T) {
1136 QualType elementType = recurse(type: T->getElementType());
1137 if (elementType.isNull())
1138 return {};
1139
1140 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
1141 return QualType(T, 0);
1142
1143 return Ctx.getExtVectorType(VectorType: elementType, NumElts: T->getNumElements());
1144 }
1145
1146 QualType VisitConstantMatrixType(const ConstantMatrixType *T) {
1147 QualType elementType = recurse(type: T->getElementType());
1148 if (elementType.isNull())
1149 return {};
1150 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
1151 return QualType(T, 0);
1152
1153 return Ctx.getConstantMatrixType(ElementType: elementType, NumRows: T->getNumRows(),
1154 NumColumns: T->getNumColumns());
1155 }
1156
1157 QualType VisitOverflowBehaviorType(const OverflowBehaviorType *T) {
1158 QualType UnderlyingType = recurse(type: T->getUnderlyingType());
1159 if (UnderlyingType.isNull())
1160 return {};
1161
1162 if (UnderlyingType.getAsOpaquePtr() ==
1163 T->getUnderlyingType().getAsOpaquePtr())
1164 return QualType(T, 0);
1165
1166 return Ctx.getOverflowBehaviorType(Kind: T->getBehaviorKind(), Wrapped: UnderlyingType);
1167 }
1168
1169 QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
1170 QualType returnType = recurse(type: T->getReturnType());
1171 if (returnType.isNull())
1172 return {};
1173
1174 if (returnType.getAsOpaquePtr() == T->getReturnType().getAsOpaquePtr())
1175 return QualType(T, 0);
1176
1177 return Ctx.getFunctionNoProtoType(ResultTy: returnType, Info: T->getExtInfo());
1178 }
1179
1180 QualType VisitFunctionProtoType(const FunctionProtoType *T) {
1181 QualType returnType = recurse(type: T->getReturnType());
1182 if (returnType.isNull())
1183 return {};
1184
1185 // Transform parameter types.
1186 SmallVector<QualType, 4> paramTypes;
1187 bool paramChanged = false;
1188 for (auto paramType : T->getParamTypes()) {
1189 QualType newParamType = recurse(type: paramType);
1190 if (newParamType.isNull())
1191 return {};
1192
1193 if (newParamType.getAsOpaquePtr() != paramType.getAsOpaquePtr())
1194 paramChanged = true;
1195
1196 paramTypes.push_back(Elt: newParamType);
1197 }
1198
1199 // Transform extended info.
1200 FunctionProtoType::ExtProtoInfo info = T->getExtProtoInfo();
1201 bool exceptionChanged = false;
1202 if (info.ExceptionSpec.Type == EST_Dynamic) {
1203 SmallVector<QualType, 4> exceptionTypes;
1204 for (auto exceptionType : info.ExceptionSpec.Exceptions) {
1205 QualType newExceptionType = recurse(type: exceptionType);
1206 if (newExceptionType.isNull())
1207 return {};
1208
1209 if (newExceptionType.getAsOpaquePtr() != exceptionType.getAsOpaquePtr())
1210 exceptionChanged = true;
1211
1212 exceptionTypes.push_back(Elt: newExceptionType);
1213 }
1214
1215 if (exceptionChanged) {
1216 info.ExceptionSpec.Exceptions =
1217 llvm::ArrayRef(exceptionTypes).copy(A&: Ctx);
1218 }
1219 }
1220
1221 if (returnType.getAsOpaquePtr() == T->getReturnType().getAsOpaquePtr() &&
1222 !paramChanged && !exceptionChanged)
1223 return QualType(T, 0);
1224
1225 return Ctx.getFunctionType(ResultTy: returnType, Args: paramTypes, EPI: info);
1226 }
1227
1228 QualType VisitParenType(const ParenType *T) {
1229 QualType innerType = recurse(type: T->getInnerType());
1230 if (innerType.isNull())
1231 return {};
1232
1233 if (innerType.getAsOpaquePtr() == T->getInnerType().getAsOpaquePtr())
1234 return QualType(T, 0);
1235
1236 return Ctx.getParenType(NamedType: innerType);
1237 }
1238
1239 SUGARED_TYPE_CLASS(Typedef)
1240 SUGARED_TYPE_CLASS(ObjCTypeParam)
1241 SUGARED_TYPE_CLASS(MacroQualified)
1242
1243 QualType VisitAdjustedType(const AdjustedType *T) {
1244 QualType originalType = recurse(type: T->getOriginalType());
1245 if (originalType.isNull())
1246 return {};
1247
1248 QualType adjustedType = recurse(type: T->getAdjustedType());
1249 if (adjustedType.isNull())
1250 return {};
1251
1252 if (originalType.getAsOpaquePtr() ==
1253 T->getOriginalType().getAsOpaquePtr() &&
1254 adjustedType.getAsOpaquePtr() == T->getAdjustedType().getAsOpaquePtr())
1255 return QualType(T, 0);
1256
1257 return Ctx.getAdjustedType(Orig: originalType, New: adjustedType);
1258 }
1259
1260 QualType VisitDecayedType(const DecayedType *T) {
1261 QualType originalType = recurse(type: T->getOriginalType());
1262 if (originalType.isNull())
1263 return {};
1264
1265 if (originalType.getAsOpaquePtr() == T->getOriginalType().getAsOpaquePtr())
1266 return QualType(T, 0);
1267
1268 return Ctx.getDecayedType(T: originalType);
1269 }
1270
1271 QualType VisitArrayParameterType(const ArrayParameterType *T) {
1272 QualType ArrTy = VisitConstantArrayType(T);
1273 if (ArrTy.isNull())
1274 return {};
1275
1276 return Ctx.getArrayParameterType(Ty: ArrTy);
1277 }
1278
1279 SUGARED_TYPE_CLASS(TypeOfExpr)
1280 SUGARED_TYPE_CLASS(TypeOf)
1281 SUGARED_TYPE_CLASS(Decltype)
1282 SUGARED_TYPE_CLASS(UnaryTransform)
1283 TRIVIAL_TYPE_CLASS(Record)
1284 TRIVIAL_TYPE_CLASS(Enum)
1285
1286 QualType VisitAttributedType(const AttributedType *T) {
1287 QualType modifiedType = recurse(type: T->getModifiedType());
1288 if (modifiedType.isNull())
1289 return {};
1290
1291 QualType equivalentType = recurse(type: T->getEquivalentType());
1292 if (equivalentType.isNull())
1293 return {};
1294
1295 if (modifiedType.getAsOpaquePtr() ==
1296 T->getModifiedType().getAsOpaquePtr() &&
1297 equivalentType.getAsOpaquePtr() ==
1298 T->getEquivalentType().getAsOpaquePtr())
1299 return QualType(T, 0);
1300
1301 return Ctx.getAttributedType(attrKind: T->getAttrKind(), modifiedType, equivalentType,
1302 attr: T->getAttr());
1303 }
1304
1305 QualType VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1306 QualType replacementType = recurse(type: T->getReplacementType());
1307 if (replacementType.isNull())
1308 return {};
1309
1310 if (replacementType.getAsOpaquePtr() ==
1311 T->getReplacementType().getAsOpaquePtr())
1312 return QualType(T, 0);
1313
1314 return Ctx.getSubstTemplateTypeParmType(
1315 Replacement: replacementType, AssociatedDecl: T->getAssociatedDecl(), Index: T->getIndex(),
1316 PackIndex: T->getPackIndex(), Final: T->getFinal());
1317 }
1318
1319 // FIXME: Non-trivial to implement, but important for C++
1320 SUGARED_TYPE_CLASS(TemplateSpecialization)
1321
1322 QualType VisitAutoType(const AutoType *T) {
1323 if (!T->isDeduced())
1324 return QualType(T, 0);
1325
1326 QualType deducedType = recurse(type: T->getDeducedType());
1327 if (deducedType.isNull())
1328 return {};
1329
1330 if (deducedType.getAsOpaquePtr() == T->getDeducedType().getAsOpaquePtr())
1331 return QualType(T, 0);
1332
1333 return Ctx.getAutoType(DeducedType: deducedType, Keyword: T->getKeyword(), IsDependent: T->isDependentType(),
1334 /*IsPack=*/false, TypeConstraintConcept: T->getTypeConstraintConcept(),
1335 TypeConstraintArgs: T->getTypeConstraintArguments());
1336 }
1337
1338 QualType VisitObjCObjectType(const ObjCObjectType *T) {
1339 QualType baseType = recurse(type: T->getBaseType());
1340 if (baseType.isNull())
1341 return {};
1342
1343 // Transform type arguments.
1344 bool typeArgChanged = false;
1345 SmallVector<QualType, 4> typeArgs;
1346 for (auto typeArg : T->getTypeArgsAsWritten()) {
1347 QualType newTypeArg = recurse(type: typeArg);
1348 if (newTypeArg.isNull())
1349 return {};
1350
1351 if (newTypeArg.getAsOpaquePtr() != typeArg.getAsOpaquePtr())
1352 typeArgChanged = true;
1353
1354 typeArgs.push_back(Elt: newTypeArg);
1355 }
1356
1357 if (baseType.getAsOpaquePtr() == T->getBaseType().getAsOpaquePtr() &&
1358 !typeArgChanged)
1359 return QualType(T, 0);
1360
1361 return Ctx.getObjCObjectType(
1362 Base: baseType, typeArgs,
1363 protocols: llvm::ArrayRef(T->qual_begin(), T->getNumProtocols()),
1364 isKindOf: T->isKindOfTypeAsWritten());
1365 }
1366
1367 TRIVIAL_TYPE_CLASS(ObjCInterface)
1368
1369 QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
1370 QualType pointeeType = recurse(type: T->getPointeeType());
1371 if (pointeeType.isNull())
1372 return {};
1373
1374 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
1375 return QualType(T, 0);
1376
1377 return Ctx.getObjCObjectPointerType(OIT: pointeeType);
1378 }
1379
1380 QualType VisitAtomicType(const AtomicType *T) {
1381 QualType valueType = recurse(type: T->getValueType());
1382 if (valueType.isNull())
1383 return {};
1384
1385 if (valueType.getAsOpaquePtr() == T->getValueType().getAsOpaquePtr())
1386 return QualType(T, 0);
1387
1388 return Ctx.getAtomicType(T: valueType);
1389 }
1390
1391#undef TRIVIAL_TYPE_CLASS
1392#undef SUGARED_TYPE_CLASS
1393};
1394
1395struct SubstObjCTypeArgsVisitor
1396 : public SimpleTransformVisitor<SubstObjCTypeArgsVisitor> {
1397 using BaseType = SimpleTransformVisitor<SubstObjCTypeArgsVisitor>;
1398
1399 ArrayRef<QualType> TypeArgs;
1400 ObjCSubstitutionContext SubstContext;
1401
1402 SubstObjCTypeArgsVisitor(ASTContext &ctx, ArrayRef<QualType> typeArgs,
1403 ObjCSubstitutionContext context)
1404 : BaseType(ctx), TypeArgs(typeArgs), SubstContext(context) {}
1405
1406 QualType VisitObjCTypeParamType(const ObjCTypeParamType *OTPTy) {
1407 // Replace an Objective-C type parameter reference with the corresponding
1408 // type argument.
1409 ObjCTypeParamDecl *typeParam = OTPTy->getDecl();
1410 // If we have type arguments, use them.
1411 if (!TypeArgs.empty()) {
1412 QualType argType = TypeArgs[typeParam->getIndex()];
1413 if (OTPTy->qual_empty())
1414 return argType;
1415
1416 // Apply protocol lists if exists.
1417 bool hasError;
1418 SmallVector<ObjCProtocolDecl *, 8> protocolsVec;
1419 protocolsVec.append(in_start: OTPTy->qual_begin(), in_end: OTPTy->qual_end());
1420 ArrayRef<ObjCProtocolDecl *> protocolsToApply = protocolsVec;
1421 return Ctx.applyObjCProtocolQualifiers(
1422 type: argType, protocols: protocolsToApply, hasError, allowOnPointerType: true /*allowOnPointerType*/);
1423 }
1424
1425 switch (SubstContext) {
1426 case ObjCSubstitutionContext::Ordinary:
1427 case ObjCSubstitutionContext::Parameter:
1428 case ObjCSubstitutionContext::Superclass:
1429 // Substitute the bound.
1430 return typeParam->getUnderlyingType();
1431
1432 case ObjCSubstitutionContext::Result:
1433 case ObjCSubstitutionContext::Property: {
1434 // Substitute the __kindof form of the underlying type.
1435 const auto *objPtr =
1436 typeParam->getUnderlyingType()->castAs<ObjCObjectPointerType>();
1437
1438 // __kindof types, id, and Class don't need an additional
1439 // __kindof.
1440 if (objPtr->isKindOfType() || objPtr->isObjCIdOrClassType())
1441 return typeParam->getUnderlyingType();
1442
1443 // Add __kindof.
1444 const auto *obj = objPtr->getObjectType();
1445 QualType resultTy = Ctx.getObjCObjectType(
1446 Base: obj->getBaseType(), typeArgs: obj->getTypeArgsAsWritten(), protocols: obj->getProtocols(),
1447 /*isKindOf=*/true);
1448
1449 // Rebuild object pointer type.
1450 return Ctx.getObjCObjectPointerType(OIT: resultTy);
1451 }
1452 }
1453 llvm_unreachable("Unexpected ObjCSubstitutionContext!");
1454 }
1455
1456 QualType VisitFunctionType(const FunctionType *funcType) {
1457 // If we have a function type, update the substitution context
1458 // appropriately.
1459
1460 // Substitute result type.
1461 QualType returnType = funcType->getReturnType().substObjCTypeArgs(
1462 ctx&: Ctx, typeArgs: TypeArgs, context: ObjCSubstitutionContext::Result);
1463 if (returnType.isNull())
1464 return {};
1465
1466 // Handle non-prototyped functions, which only substitute into the result
1467 // type.
1468 if (isa<FunctionNoProtoType>(Val: funcType)) {
1469 // If the return type was unchanged, do nothing.
1470 if (returnType.getAsOpaquePtr() ==
1471 funcType->getReturnType().getAsOpaquePtr())
1472 return BaseType::VisitFunctionType(T: funcType);
1473
1474 // Otherwise, build a new type.
1475 return Ctx.getFunctionNoProtoType(ResultTy: returnType, Info: funcType->getExtInfo());
1476 }
1477
1478 const auto *funcProtoType = cast<FunctionProtoType>(Val: funcType);
1479
1480 // Transform parameter types.
1481 SmallVector<QualType, 4> paramTypes;
1482 bool paramChanged = false;
1483 for (auto paramType : funcProtoType->getParamTypes()) {
1484 QualType newParamType = paramType.substObjCTypeArgs(
1485 ctx&: Ctx, typeArgs: TypeArgs, context: ObjCSubstitutionContext::Parameter);
1486 if (newParamType.isNull())
1487 return {};
1488
1489 if (newParamType.getAsOpaquePtr() != paramType.getAsOpaquePtr())
1490 paramChanged = true;
1491
1492 paramTypes.push_back(Elt: newParamType);
1493 }
1494
1495 // Transform extended info.
1496 FunctionProtoType::ExtProtoInfo info = funcProtoType->getExtProtoInfo();
1497 bool exceptionChanged = false;
1498 if (info.ExceptionSpec.Type == EST_Dynamic) {
1499 SmallVector<QualType, 4> exceptionTypes;
1500 for (auto exceptionType : info.ExceptionSpec.Exceptions) {
1501 QualType newExceptionType = exceptionType.substObjCTypeArgs(
1502 ctx&: Ctx, typeArgs: TypeArgs, context: ObjCSubstitutionContext::Ordinary);
1503 if (newExceptionType.isNull())
1504 return {};
1505
1506 if (newExceptionType.getAsOpaquePtr() != exceptionType.getAsOpaquePtr())
1507 exceptionChanged = true;
1508
1509 exceptionTypes.push_back(Elt: newExceptionType);
1510 }
1511
1512 if (exceptionChanged) {
1513 info.ExceptionSpec.Exceptions =
1514 llvm::ArrayRef(exceptionTypes).copy(A&: Ctx);
1515 }
1516 }
1517
1518 if (returnType.getAsOpaquePtr() ==
1519 funcProtoType->getReturnType().getAsOpaquePtr() &&
1520 !paramChanged && !exceptionChanged)
1521 return BaseType::VisitFunctionType(T: funcType);
1522
1523 return Ctx.getFunctionType(ResultTy: returnType, Args: paramTypes, EPI: info);
1524 }
1525
1526 QualType VisitObjCObjectType(const ObjCObjectType *objcObjectType) {
1527 // Substitute into the type arguments of a specialized Objective-C object
1528 // type.
1529 if (objcObjectType->isSpecializedAsWritten()) {
1530 SmallVector<QualType, 4> newTypeArgs;
1531 bool anyChanged = false;
1532 for (auto typeArg : objcObjectType->getTypeArgsAsWritten()) {
1533 QualType newTypeArg = typeArg.substObjCTypeArgs(
1534 ctx&: Ctx, typeArgs: TypeArgs, context: ObjCSubstitutionContext::Ordinary);
1535 if (newTypeArg.isNull())
1536 return {};
1537
1538 if (newTypeArg.getAsOpaquePtr() != typeArg.getAsOpaquePtr()) {
1539 // If we're substituting based on an unspecialized context type,
1540 // produce an unspecialized type.
1541 ArrayRef<ObjCProtocolDecl *> protocols(
1542 objcObjectType->qual_begin(), objcObjectType->getNumProtocols());
1543 if (TypeArgs.empty() &&
1544 SubstContext != ObjCSubstitutionContext::Superclass) {
1545 return Ctx.getObjCObjectType(
1546 Base: objcObjectType->getBaseType(), typeArgs: {}, protocols,
1547 isKindOf: objcObjectType->isKindOfTypeAsWritten());
1548 }
1549
1550 anyChanged = true;
1551 }
1552
1553 newTypeArgs.push_back(Elt: newTypeArg);
1554 }
1555
1556 if (anyChanged) {
1557 ArrayRef<ObjCProtocolDecl *> protocols(
1558 objcObjectType->qual_begin(), objcObjectType->getNumProtocols());
1559 return Ctx.getObjCObjectType(Base: objcObjectType->getBaseType(), typeArgs: newTypeArgs,
1560 protocols,
1561 isKindOf: objcObjectType->isKindOfTypeAsWritten());
1562 }
1563 }
1564
1565 return BaseType::VisitObjCObjectType(T: objcObjectType);
1566 }
1567
1568 QualType VisitAttributedType(const AttributedType *attrType) {
1569 QualType newType = BaseType::VisitAttributedType(T: attrType);
1570 if (newType.isNull())
1571 return {};
1572
1573 const auto *newAttrType = dyn_cast<AttributedType>(Val: newType.getTypePtr());
1574 if (!newAttrType || newAttrType->getAttrKind() != attr::ObjCKindOf)
1575 return newType;
1576
1577 // Find out if it's an Objective-C object or object pointer type;
1578 QualType newEquivType = newAttrType->getEquivalentType();
1579 const ObjCObjectPointerType *ptrType =
1580 newEquivType->getAs<ObjCObjectPointerType>();
1581 const ObjCObjectType *objType = ptrType
1582 ? ptrType->getObjectType()
1583 : newEquivType->getAs<ObjCObjectType>();
1584 if (!objType)
1585 return newType;
1586
1587 // Rebuild the "equivalent" type, which pushes __kindof down into
1588 // the object type.
1589 newEquivType = Ctx.getObjCObjectType(
1590 Base: objType->getBaseType(), typeArgs: objType->getTypeArgsAsWritten(),
1591 protocols: objType->getProtocols(),
1592 // There is no need to apply kindof on an unqualified id type.
1593 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
1594
1595 // If we started with an object pointer type, rebuild it.
1596 if (ptrType)
1597 newEquivType = Ctx.getObjCObjectPointerType(OIT: newEquivType);
1598
1599 // Rebuild the attributed type.
1600 return Ctx.getAttributedType(attrKind: newAttrType->getAttrKind(),
1601 modifiedType: newAttrType->getModifiedType(), equivalentType: newEquivType,
1602 attr: newAttrType->getAttr());
1603 }
1604};
1605
1606struct StripObjCKindOfTypeVisitor
1607 : public SimpleTransformVisitor<StripObjCKindOfTypeVisitor> {
1608 using BaseType = SimpleTransformVisitor<StripObjCKindOfTypeVisitor>;
1609
1610 explicit StripObjCKindOfTypeVisitor(ASTContext &ctx) : BaseType(ctx) {}
1611
1612 QualType VisitObjCObjectType(const ObjCObjectType *objType) {
1613 if (!objType->isKindOfType())
1614 return BaseType::VisitObjCObjectType(T: objType);
1615
1616 QualType baseType = objType->getBaseType().stripObjCKindOfType(ctx: Ctx);
1617 return Ctx.getObjCObjectType(Base: baseType, typeArgs: objType->getTypeArgsAsWritten(),
1618 protocols: objType->getProtocols(),
1619 /*isKindOf=*/false);
1620 }
1621};
1622
1623} // namespace
1624
1625bool QualType::UseExcessPrecision(const ASTContext &Ctx) {
1626 const BuiltinType *BT = getTypePtr()->getAs<BuiltinType>();
1627 if (!BT) {
1628 const VectorType *VT = getTypePtr()->getAs<VectorType>();
1629 if (VT) {
1630 QualType ElementType = VT->getElementType();
1631 return ElementType.UseExcessPrecision(Ctx);
1632 }
1633 } else {
1634 switch (BT->getKind()) {
1635 case BuiltinType::Kind::Float16: {
1636 const TargetInfo &TI = Ctx.getTargetInfo();
1637 if (TI.hasFloat16Type() && !TI.hasFastHalfType() &&
1638 Ctx.getLangOpts().getFloat16ExcessPrecision() !=
1639 Ctx.getLangOpts().ExcessPrecisionKind::FPP_None)
1640 return true;
1641 break;
1642 }
1643 case BuiltinType::Kind::BFloat16: {
1644 const TargetInfo &TI = Ctx.getTargetInfo();
1645 if (TI.hasBFloat16Type() && !TI.hasFullBFloat16Type() &&
1646 Ctx.getLangOpts().getBFloat16ExcessPrecision() !=
1647 Ctx.getLangOpts().ExcessPrecisionKind::FPP_None)
1648 return true;
1649 break;
1650 }
1651 default:
1652 return false;
1653 }
1654 }
1655 return false;
1656}
1657
1658/// Substitute the given type arguments for Objective-C type
1659/// parameters within the given type, recursively.
1660QualType QualType::substObjCTypeArgs(ASTContext &ctx,
1661 ArrayRef<QualType> typeArgs,
1662 ObjCSubstitutionContext context) const {
1663 SubstObjCTypeArgsVisitor visitor(ctx, typeArgs, context);
1664 return visitor.recurse(type: *this);
1665}
1666
1667QualType QualType::substObjCMemberType(QualType objectType,
1668 const DeclContext *dc,
1669 ObjCSubstitutionContext context) const {
1670 if (auto subs = objectType->getObjCSubstitutions(dc))
1671 return substObjCTypeArgs(ctx&: dc->getParentASTContext(), typeArgs: *subs, context);
1672
1673 return *this;
1674}
1675
1676QualType QualType::stripObjCKindOfType(const ASTContext &constCtx) const {
1677 // FIXME: Because ASTContext::getAttributedType() is non-const.
1678 auto &ctx = const_cast<ASTContext &>(constCtx);
1679 StripObjCKindOfTypeVisitor visitor(ctx);
1680 return visitor.recurse(type: *this);
1681}
1682
1683QualType QualType::getAtomicUnqualifiedType() const {
1684 QualType T = *this;
1685 if (const auto AT = T.getTypePtr()->getAs<AtomicType>())
1686 T = AT->getValueType();
1687 return T.getUnqualifiedType();
1688}
1689
1690std::optional<ArrayRef<QualType>>
1691Type::getObjCSubstitutions(const DeclContext *dc) const {
1692 // Look through method scopes.
1693 if (const auto method = dyn_cast<ObjCMethodDecl>(Val: dc))
1694 dc = method->getDeclContext();
1695
1696 // Find the class or category in which the type we're substituting
1697 // was declared.
1698 const auto *dcClassDecl = dyn_cast<ObjCInterfaceDecl>(Val: dc);
1699 const ObjCCategoryDecl *dcCategoryDecl = nullptr;
1700 ObjCTypeParamList *dcTypeParams = nullptr;
1701 if (dcClassDecl) {
1702 // If the class does not have any type parameters, there's no
1703 // substitution to do.
1704 dcTypeParams = dcClassDecl->getTypeParamList();
1705 if (!dcTypeParams)
1706 return std::nullopt;
1707 } else {
1708 // If we are in neither a class nor a category, there's no
1709 // substitution to perform.
1710 dcCategoryDecl = dyn_cast<ObjCCategoryDecl>(Val: dc);
1711 if (!dcCategoryDecl)
1712 return std::nullopt;
1713
1714 // If the category does not have any type parameters, there's no
1715 // substitution to do.
1716 dcTypeParams = dcCategoryDecl->getTypeParamList();
1717 if (!dcTypeParams)
1718 return std::nullopt;
1719
1720 dcClassDecl = dcCategoryDecl->getClassInterface();
1721 if (!dcClassDecl)
1722 return std::nullopt;
1723 }
1724 assert(dcTypeParams && "No substitutions to perform");
1725 assert(dcClassDecl && "No class context");
1726
1727 // Find the underlying object type.
1728 const ObjCObjectType *objectType;
1729 if (const auto *objectPointerType = getAs<ObjCObjectPointerType>()) {
1730 objectType = objectPointerType->getObjectType();
1731 } else if (getAs<BlockPointerType>()) {
1732 ASTContext &ctx = dc->getParentASTContext();
1733 objectType = ctx.getObjCObjectType(Base: ctx.ObjCBuiltinIdTy, Protocols: {}, NumProtocols: {})
1734 ->castAs<ObjCObjectType>();
1735 } else {
1736 objectType = getAs<ObjCObjectType>();
1737 }
1738
1739 /// Extract the class from the receiver object type.
1740 ObjCInterfaceDecl *curClassDecl =
1741 objectType ? objectType->getInterface() : nullptr;
1742 if (!curClassDecl) {
1743 // If we don't have a context type (e.g., this is "id" or some
1744 // variant thereof), substitute the bounds.
1745 return llvm::ArrayRef<QualType>();
1746 }
1747
1748 // Follow the superclass chain until we've mapped the receiver type
1749 // to the same class as the context.
1750 while (curClassDecl != dcClassDecl) {
1751 // Map to the superclass type.
1752 QualType superType = objectType->getSuperClassType();
1753 if (superType.isNull()) {
1754 objectType = nullptr;
1755 break;
1756 }
1757
1758 objectType = superType->castAs<ObjCObjectType>();
1759 curClassDecl = objectType->getInterface();
1760 }
1761
1762 // If we don't have a receiver type, or the receiver type does not
1763 // have type arguments, substitute in the defaults.
1764 if (!objectType || objectType->isUnspecialized()) {
1765 return llvm::ArrayRef<QualType>();
1766 }
1767
1768 // The receiver type has the type arguments we want.
1769 return objectType->getTypeArgs();
1770}
1771
1772bool Type::acceptsObjCTypeParams() const {
1773 if (auto *IfaceT = getAsObjCInterfaceType()) {
1774 if (auto *ID = IfaceT->getInterface()) {
1775 if (ID->getTypeParamList())
1776 return true;
1777 }
1778 }
1779
1780 return false;
1781}
1782
1783void ObjCObjectType::computeSuperClassTypeSlow() const {
1784 // Retrieve the class declaration for this type. If there isn't one
1785 // (e.g., this is some variant of "id" or "Class"), then there is no
1786 // superclass type.
1787 ObjCInterfaceDecl *classDecl = getInterface();
1788 if (!classDecl) {
1789 CachedSuperClassType.setInt(true);
1790 return;
1791 }
1792
1793 // Extract the superclass type.
1794 const ObjCObjectType *superClassObjTy = classDecl->getSuperClassType();
1795 if (!superClassObjTy) {
1796 CachedSuperClassType.setInt(true);
1797 return;
1798 }
1799
1800 ObjCInterfaceDecl *superClassDecl = superClassObjTy->getInterface();
1801 if (!superClassDecl) {
1802 CachedSuperClassType.setInt(true);
1803 return;
1804 }
1805
1806 // If the superclass doesn't have type parameters, then there is no
1807 // substitution to perform.
1808 QualType superClassType(superClassObjTy, 0);
1809 ObjCTypeParamList *superClassTypeParams = superClassDecl->getTypeParamList();
1810 if (!superClassTypeParams) {
1811 CachedSuperClassType.setPointerAndInt(
1812 PtrVal: superClassType->castAs<ObjCObjectType>(), IntVal: true);
1813 return;
1814 }
1815
1816 // If the superclass reference is unspecialized, return it.
1817 if (superClassObjTy->isUnspecialized()) {
1818 CachedSuperClassType.setPointerAndInt(PtrVal: superClassObjTy, IntVal: true);
1819 return;
1820 }
1821
1822 // If the subclass is not parameterized, there aren't any type
1823 // parameters in the superclass reference to substitute.
1824 ObjCTypeParamList *typeParams = classDecl->getTypeParamList();
1825 if (!typeParams) {
1826 CachedSuperClassType.setPointerAndInt(
1827 PtrVal: superClassType->castAs<ObjCObjectType>(), IntVal: true);
1828 return;
1829 }
1830
1831 // If the subclass type isn't specialized, return the unspecialized
1832 // superclass.
1833 if (isUnspecialized()) {
1834 QualType unspecializedSuper =
1835 classDecl->getASTContext().getObjCInterfaceType(
1836 Decl: superClassObjTy->getInterface());
1837 CachedSuperClassType.setPointerAndInt(
1838 PtrVal: unspecializedSuper->castAs<ObjCObjectType>(), IntVal: true);
1839 return;
1840 }
1841
1842 // Substitute the provided type arguments into the superclass type.
1843 ArrayRef<QualType> typeArgs = getTypeArgs();
1844 assert(typeArgs.size() == typeParams->size());
1845 CachedSuperClassType.setPointerAndInt(
1846 PtrVal: superClassType
1847 .substObjCTypeArgs(ctx&: classDecl->getASTContext(), typeArgs,
1848 context: ObjCSubstitutionContext::Superclass)
1849 ->castAs<ObjCObjectType>(),
1850 IntVal: true);
1851}
1852
1853const ObjCInterfaceType *ObjCObjectPointerType::getInterfaceType() const {
1854 if (auto interfaceDecl = getObjectType()->getInterface()) {
1855 return interfaceDecl->getASTContext()
1856 .getObjCInterfaceType(Decl: interfaceDecl)
1857 ->castAs<ObjCInterfaceType>();
1858 }
1859
1860 return nullptr;
1861}
1862
1863QualType ObjCObjectPointerType::getSuperClassType() const {
1864 QualType superObjectType = getObjectType()->getSuperClassType();
1865 if (superObjectType.isNull())
1866 return superObjectType;
1867
1868 ASTContext &ctx = getInterfaceDecl()->getASTContext();
1869 return ctx.getObjCObjectPointerType(OIT: superObjectType);
1870}
1871
1872const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const {
1873 // There is no sugar for ObjCObjectType's, just return the canonical
1874 // type pointer if it is the right class. There is no typedef information to
1875 // return and these cannot be Address-space qualified.
1876 if (const auto *T = getAs<ObjCObjectType>())
1877 if (T->getNumProtocols() && T->getInterface())
1878 return T;
1879 return nullptr;
1880}
1881
1882bool Type::isObjCQualifiedInterfaceType() const {
1883 return getAsObjCQualifiedInterfaceType() != nullptr;
1884}
1885
1886const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
1887 // There is no sugar for ObjCQualifiedIdType's, just return the canonical
1888 // type pointer if it is the right class.
1889 if (const auto *OPT = getAs<ObjCObjectPointerType>()) {
1890 if (OPT->isObjCQualifiedIdType())
1891 return OPT;
1892 }
1893 return nullptr;
1894}
1895
1896const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const {
1897 // There is no sugar for ObjCQualifiedClassType's, just return the canonical
1898 // type pointer if it is the right class.
1899 if (const auto *OPT = getAs<ObjCObjectPointerType>()) {
1900 if (OPT->isObjCQualifiedClassType())
1901 return OPT;
1902 }
1903 return nullptr;
1904}
1905
1906const ObjCObjectType *Type::getAsObjCInterfaceType() const {
1907 if (const auto *OT = getAs<ObjCObjectType>()) {
1908 if (OT->getInterface())
1909 return OT;
1910 }
1911 return nullptr;
1912}
1913
1914const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
1915 if (const auto *OPT = getAs<ObjCObjectPointerType>()) {
1916 if (OPT->getInterfaceType())
1917 return OPT;
1918 }
1919 return nullptr;
1920}
1921
1922const CXXRecordDecl *Type::getPointeeCXXRecordDecl() const {
1923 QualType PointeeType;
1924 if (const auto *PT = getAsCanonical<PointerType>())
1925 PointeeType = PT->getPointeeType();
1926 else if (const auto *RT = getAsCanonical<ReferenceType>())
1927 PointeeType = RT->getPointeeType();
1928 else
1929 return nullptr;
1930 return PointeeType->getAsCXXRecordDecl();
1931}
1932
1933const TemplateSpecializationType *
1934Type::getAsNonAliasTemplateSpecializationType() const {
1935 const auto *TST = getAs<TemplateSpecializationType>();
1936 while (TST && TST->isTypeAlias())
1937 TST = TST->desugar()->getAs<TemplateSpecializationType>();
1938 return TST;
1939}
1940
1941NestedNameSpecifier Type::getPrefix() const {
1942 switch (getTypeClass()) {
1943 case Type::DependentName:
1944 return cast<DependentNameType>(Val: this)->getQualifier();
1945 case Type::TemplateSpecialization:
1946 return cast<TemplateSpecializationType>(Val: this)
1947 ->getTemplateName()
1948 .getQualifier();
1949 case Type::Enum:
1950 case Type::Record:
1951 case Type::InjectedClassName:
1952 return cast<TagType>(Val: this)->getQualifier();
1953 case Type::Typedef:
1954 return cast<TypedefType>(Val: this)->getQualifier();
1955 case Type::UnresolvedUsing:
1956 return cast<UnresolvedUsingType>(Val: this)->getQualifier();
1957 case Type::Using:
1958 return cast<UsingType>(Val: this)->getQualifier();
1959 default:
1960 return std::nullopt;
1961 }
1962}
1963
1964bool Type::hasAttr(attr::Kind AK) const {
1965 const Type *Cur = this;
1966 while (const auto *AT = Cur->getAs<AttributedType>()) {
1967 if (AT->getAttrKind() == AK)
1968 return true;
1969 Cur = AT->getEquivalentType().getTypePtr();
1970 }
1971 return false;
1972}
1973
1974namespace {
1975
1976class GetContainedDeducedTypeVisitor
1977 : public TypeVisitor<GetContainedDeducedTypeVisitor, Type *> {
1978 bool Syntactic;
1979
1980public:
1981 GetContainedDeducedTypeVisitor(bool Syntactic = false)
1982 : Syntactic(Syntactic) {}
1983
1984 using TypeVisitor<GetContainedDeducedTypeVisitor, Type *>::Visit;
1985
1986 Type *Visit(QualType T) {
1987 if (T.isNull())
1988 return nullptr;
1989 return Visit(T: T.getTypePtr());
1990 }
1991
1992 // The deduced type itself.
1993 Type *VisitDeducedType(const DeducedType *AT) {
1994 return const_cast<DeducedType *>(AT);
1995 }
1996
1997 // Only these types can contain the desired 'auto' type.
1998 Type *VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1999 return Visit(T: T->getReplacementType());
2000 }
2001
2002 Type *VisitPointerType(const PointerType *T) {
2003 return Visit(T: T->getPointeeType());
2004 }
2005
2006 Type *VisitBlockPointerType(const BlockPointerType *T) {
2007 return Visit(T: T->getPointeeType());
2008 }
2009
2010 Type *VisitReferenceType(const ReferenceType *T) {
2011 return Visit(T: T->getPointeeTypeAsWritten());
2012 }
2013
2014 Type *VisitMemberPointerType(const MemberPointerType *T) {
2015 return Visit(T: T->getPointeeType());
2016 }
2017
2018 Type *VisitArrayType(const ArrayType *T) {
2019 return Visit(T: T->getElementType());
2020 }
2021
2022 Type *VisitDependentSizedExtVectorType(const DependentSizedExtVectorType *T) {
2023 return Visit(T: T->getElementType());
2024 }
2025
2026 Type *VisitVectorType(const VectorType *T) {
2027 return Visit(T: T->getElementType());
2028 }
2029
2030 Type *VisitDependentSizedMatrixType(const DependentSizedMatrixType *T) {
2031 return Visit(T: T->getElementType());
2032 }
2033
2034 Type *VisitConstantMatrixType(const ConstantMatrixType *T) {
2035 return Visit(T: T->getElementType());
2036 }
2037
2038 Type *VisitFunctionProtoType(const FunctionProtoType *T) {
2039 if (Syntactic && T->hasTrailingReturn())
2040 return const_cast<FunctionProtoType *>(T);
2041 return VisitFunctionType(T);
2042 }
2043
2044 Type *VisitFunctionType(const FunctionType *T) {
2045 return Visit(T: T->getReturnType());
2046 }
2047
2048 Type *VisitParenType(const ParenType *T) { return Visit(T: T->getInnerType()); }
2049
2050 Type *VisitAttributedType(const AttributedType *T) {
2051 return Visit(T: T->getModifiedType());
2052 }
2053
2054 Type *VisitMacroQualifiedType(const MacroQualifiedType *T) {
2055 return Visit(T: T->getUnderlyingType());
2056 }
2057
2058 Type *VisitOverflowBehaviorType(const OverflowBehaviorType *T) {
2059 return Visit(T: T->getUnderlyingType());
2060 }
2061
2062 Type *VisitAdjustedType(const AdjustedType *T) {
2063 return Visit(T: T->getOriginalType());
2064 }
2065
2066 Type *VisitPackExpansionType(const PackExpansionType *T) {
2067 return Visit(T: T->getPattern());
2068 }
2069};
2070
2071} // namespace
2072
2073DeducedType *Type::getContainedDeducedType() const {
2074 return cast_or_null<DeducedType>(
2075 Val: GetContainedDeducedTypeVisitor().Visit(T: this));
2076}
2077
2078bool Type::hasAutoForTrailingReturnType() const {
2079 return isa_and_nonnull<FunctionType>(
2080 Val: GetContainedDeducedTypeVisitor(true).Visit(T: this));
2081}
2082
2083bool Type::hasIntegerRepresentation() const {
2084 if (const auto *VT = dyn_cast<VectorType>(Val: CanonicalType))
2085 return VT->getElementType()->isIntegerType();
2086 if (CanonicalType->isSveVLSBuiltinType()) {
2087 const auto *VT = cast<BuiltinType>(Val: CanonicalType);
2088 return VT->getKind() == BuiltinType::SveBool ||
2089 (VT->getKind() >= BuiltinType::SveInt8 &&
2090 VT->getKind() <= BuiltinType::SveUint64);
2091 }
2092 if (CanonicalType->isRVVVLSBuiltinType()) {
2093 const auto *VT = cast<BuiltinType>(Val: CanonicalType);
2094 return (VT->getKind() >= BuiltinType::RvvInt8mf8 &&
2095 VT->getKind() <= BuiltinType::RvvUint64m8);
2096 }
2097
2098 return isIntegerType();
2099}
2100
2101/// Determine whether this type is an integral type.
2102///
2103/// This routine determines whether the given type is an integral type per
2104/// C++ [basic.fundamental]p7. Although the C standard does not define the
2105/// term "integral type", it has a similar term "integer type", and in C++
2106/// the two terms are equivalent. However, C's "integer type" includes
2107/// enumeration types, while C++'s "integer type" does not. The \c ASTContext
2108/// parameter is used to determine whether we should be following the C or
2109/// C++ rules when determining whether this type is an integral/integer type.
2110///
2111/// For cases where C permits "an integer type" and C++ permits "an integral
2112/// type", use this routine.
2113///
2114/// For cases where C permits "an integer type" and C++ permits "an integral
2115/// or enumeration type", use \c isIntegralOrEnumerationType() instead.
2116///
2117/// \param Ctx The context in which this type occurs.
2118///
2119/// \returns true if the type is considered an integral type, false otherwise.
2120bool Type::isIntegralType(const ASTContext &Ctx) const {
2121 if (const auto *BT = dyn_cast<BuiltinType>(Val: CanonicalType))
2122 return BT->isInteger();
2123
2124 // Complete enum types are integral in C.
2125 if (!Ctx.getLangOpts().CPlusPlus) {
2126 if (const auto *ET = dyn_cast<EnumType>(Val: CanonicalType))
2127 return IsEnumDeclComplete(ED: ET->getDecl());
2128
2129 if (const OverflowBehaviorType *OBT =
2130 dyn_cast<OverflowBehaviorType>(Val: CanonicalType))
2131 return OBT->getUnderlyingType()->isIntegralOrEnumerationType();
2132 }
2133
2134 return isBitIntType();
2135}
2136
2137bool Type::isIntegralOrUnscopedEnumerationType() const {
2138 if (const auto *BT = dyn_cast<BuiltinType>(Val: CanonicalType))
2139 return BT->isInteger();
2140
2141 if (const auto *OBT = dyn_cast<OverflowBehaviorType>(Val: CanonicalType))
2142 return OBT->getUnderlyingType()->isIntegerType();
2143
2144 if (isBitIntType())
2145 return true;
2146
2147 return isUnscopedEnumerationType();
2148}
2149
2150bool Type::isUnscopedEnumerationType() const {
2151 if (const auto *ET = dyn_cast<EnumType>(Val: CanonicalType))
2152 return !ET->getDecl()->isScoped();
2153
2154 return false;
2155}
2156
2157bool Type::isCharType() const {
2158 if (const auto *BT = dyn_cast<BuiltinType>(Val: CanonicalType))
2159 return BT->getKind() == BuiltinType::Char_U ||
2160 BT->getKind() == BuiltinType::UChar ||
2161 BT->getKind() == BuiltinType::Char_S ||
2162 BT->getKind() == BuiltinType::SChar;
2163 return false;
2164}
2165
2166bool Type::isWideCharType() const {
2167 if (const auto *BT = dyn_cast<BuiltinType>(Val: CanonicalType))
2168 return BT->getKind() == BuiltinType::WChar_S ||
2169 BT->getKind() == BuiltinType::WChar_U;
2170 return false;
2171}
2172
2173bool Type::isChar8Type() const {
2174 if (const BuiltinType *BT = dyn_cast<BuiltinType>(Val: CanonicalType))
2175 return BT->getKind() == BuiltinType::Char8;
2176 return false;
2177}
2178
2179bool Type::isChar16Type() const {
2180 if (const auto *BT = dyn_cast<BuiltinType>(Val: CanonicalType))
2181 return BT->getKind() == BuiltinType::Char16;
2182 return false;
2183}
2184
2185bool Type::isChar32Type() const {
2186 if (const auto *BT = dyn_cast<BuiltinType>(Val: CanonicalType))
2187 return BT->getKind() == BuiltinType::Char32;
2188 return false;
2189}
2190
2191/// Determine whether this type is any of the built-in character
2192/// types.
2193bool Type::isAnyCharacterType() const {
2194 const auto *BT = dyn_cast<BuiltinType>(Val: CanonicalType);
2195 if (!BT)
2196 return false;
2197 switch (BT->getKind()) {
2198 default:
2199 return false;
2200 case BuiltinType::Char_U:
2201 case BuiltinType::UChar:
2202 case BuiltinType::WChar_U:
2203 case BuiltinType::Char8:
2204 case BuiltinType::Char16:
2205 case BuiltinType::Char32:
2206 case BuiltinType::Char_S:
2207 case BuiltinType::SChar:
2208 case BuiltinType::WChar_S:
2209 return true;
2210 }
2211}
2212
2213bool Type::isUnicodeCharacterType() const {
2214 const auto *BT = dyn_cast<BuiltinType>(Val: CanonicalType);
2215 if (!BT)
2216 return false;
2217 switch (BT->getKind()) {
2218 default:
2219 return false;
2220 case BuiltinType::Char8:
2221 case BuiltinType::Char16:
2222 case BuiltinType::Char32:
2223 return true;
2224 }
2225}
2226
2227/// isSignedIntegerType - Return true if this is an integer type that is
2228/// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2229/// an enum decl which has a signed representation
2230bool Type::isSignedIntegerType() const {
2231 if (const auto *BT = dyn_cast<BuiltinType>(Val: CanonicalType))
2232 return BT->isSignedInteger();
2233
2234 if (const auto *ED = getAsEnumDecl()) {
2235 // Incomplete enum types are not treated as integer types.
2236 // FIXME: In C++, enum types are never integer types.
2237 if (!ED->isComplete() || ED->isScoped())
2238 return false;
2239 return ED->getIntegerType()->isSignedIntegerType();
2240 }
2241
2242 if (const auto *IT = dyn_cast<BitIntType>(Val: CanonicalType))
2243 return IT->isSigned();
2244 if (const auto *IT = dyn_cast<DependentBitIntType>(Val: CanonicalType))
2245 return IT->isSigned();
2246
2247 if (const auto *OBT = dyn_cast<OverflowBehaviorType>(Val: CanonicalType))
2248 return OBT->getUnderlyingType()->isSignedIntegerType();
2249
2250 return false;
2251}
2252
2253bool Type::isSignedIntegerOrEnumerationType() const {
2254 if (const auto *BT = dyn_cast<BuiltinType>(Val: CanonicalType))
2255 return BT->isSignedInteger();
2256
2257 if (const auto *ED = getAsEnumDecl()) {
2258 if (!ED->isComplete())
2259 return false;
2260 return ED->getIntegerType()->isSignedIntegerType();
2261 }
2262
2263 if (const auto *IT = dyn_cast<BitIntType>(Val: CanonicalType))
2264 return IT->isSigned();
2265 if (const auto *IT = dyn_cast<DependentBitIntType>(Val: CanonicalType))
2266 return IT->isSigned();
2267
2268 if (const auto *OBT = dyn_cast<OverflowBehaviorType>(Val: CanonicalType))
2269 return OBT->getUnderlyingType()->isSignedIntegerOrEnumerationType();
2270
2271 return false;
2272}
2273
2274bool Type::hasSignedIntegerRepresentation() const {
2275 if (const auto *VT = dyn_cast<VectorType>(Val: CanonicalType))
2276 return VT->getElementType()->isSignedIntegerOrEnumerationType();
2277 else
2278 return isSignedIntegerOrEnumerationType();
2279}
2280
2281/// isUnsignedIntegerType - Return true if this is an integer type that is
2282/// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
2283/// decl which has an unsigned representation
2284bool Type::isUnsignedIntegerType() const {
2285 if (const auto *BT = dyn_cast<BuiltinType>(Val: CanonicalType))
2286 return BT->isUnsignedInteger();
2287
2288 if (const auto *ED = getAsEnumDecl()) {
2289 // Incomplete enum types are not treated as integer types.
2290 // FIXME: In C++, enum types are never integer types.
2291 if (!ED->isComplete() || ED->isScoped())
2292 return false;
2293 return ED->getIntegerType()->isUnsignedIntegerType();
2294 }
2295
2296 if (const auto *IT = dyn_cast<BitIntType>(Val: CanonicalType))
2297 return IT->isUnsigned();
2298 if (const auto *IT = dyn_cast<DependentBitIntType>(Val: CanonicalType))
2299 return IT->isUnsigned();
2300
2301 if (const auto *OBT = dyn_cast<OverflowBehaviorType>(Val: CanonicalType))
2302 return OBT->getUnderlyingType()->isUnsignedIntegerType();
2303
2304 return false;
2305}
2306
2307bool Type::isUnsignedIntegerOrEnumerationType() const {
2308 if (const auto *BT = dyn_cast<BuiltinType>(Val: CanonicalType))
2309 return BT->isUnsignedInteger();
2310
2311 if (const auto *ED = getAsEnumDecl()) {
2312 if (!ED->isComplete())
2313 return false;
2314 return ED->getIntegerType()->isUnsignedIntegerType();
2315 }
2316
2317 if (const auto *IT = dyn_cast<BitIntType>(Val: CanonicalType))
2318 return IT->isUnsigned();
2319 if (const auto *IT = dyn_cast<DependentBitIntType>(Val: CanonicalType))
2320 return IT->isUnsigned();
2321
2322 if (const auto *OBT = dyn_cast<OverflowBehaviorType>(Val: CanonicalType))
2323 return OBT->getUnderlyingType()->isUnsignedIntegerOrEnumerationType();
2324
2325 return false;
2326}
2327
2328bool Type::hasUnsignedIntegerRepresentation() const {
2329 if (const auto *VT = dyn_cast<VectorType>(Val: CanonicalType))
2330 return VT->getElementType()->isUnsignedIntegerOrEnumerationType();
2331 if (const auto *VT = dyn_cast<MatrixType>(Val: CanonicalType))
2332 return VT->getElementType()->isUnsignedIntegerOrEnumerationType();
2333 if (CanonicalType->isSveVLSBuiltinType()) {
2334 const auto *VT = cast<BuiltinType>(Val: CanonicalType);
2335 return VT->getKind() >= BuiltinType::SveUint8 &&
2336 VT->getKind() <= BuiltinType::SveUint64;
2337 }
2338 return isUnsignedIntegerOrEnumerationType();
2339}
2340
2341bool Type::isFloatingType() const {
2342 if (const auto *BT = dyn_cast<BuiltinType>(Val: CanonicalType))
2343 return BT->isFloatingPoint();
2344 if (const auto *CT = dyn_cast<ComplexType>(Val: CanonicalType))
2345 return CT->getElementType()->isFloatingType();
2346 return false;
2347}
2348
2349bool Type::hasFloatingRepresentation() const {
2350 if (const auto *VT = dyn_cast<VectorType>(Val: CanonicalType))
2351 return VT->getElementType()->isFloatingType();
2352 if (const auto *MT = dyn_cast<MatrixType>(Val: CanonicalType))
2353 return MT->getElementType()->isFloatingType();
2354 return isFloatingType();
2355}
2356
2357bool Type::isRealFloatingType() const {
2358 if (const auto *BT = dyn_cast<BuiltinType>(Val: CanonicalType))
2359 return BT->isFloatingPoint();
2360 return false;
2361}
2362
2363bool Type::isRealType() const {
2364 if (const auto *BT = dyn_cast<BuiltinType>(Val: CanonicalType))
2365 return BT->getKind() >= BuiltinType::Bool &&
2366 BT->getKind() <= BuiltinType::Ibm128;
2367 if (const auto *ET = dyn_cast<EnumType>(Val: CanonicalType)) {
2368 const auto *ED = ET->getDecl();
2369 return !ED->isScoped() && ED->getDefinitionOrSelf()->isComplete();
2370 }
2371 return isBitIntType();
2372}
2373
2374bool Type::isArithmeticType() const {
2375 if (const auto *BT = dyn_cast<BuiltinType>(Val: CanonicalType))
2376 return BT->getKind() >= BuiltinType::Bool &&
2377 BT->getKind() <= BuiltinType::Ibm128;
2378 if (const auto *ET = dyn_cast<EnumType>(Val: CanonicalType)) {
2379 // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
2380 // If a body isn't seen by the time we get here, return false.
2381 //
2382 // C++0x: Enumerations are not arithmetic types. For now, just return
2383 // false for scoped enumerations since that will disable any
2384 // unwanted implicit conversions.
2385 const auto *ED = ET->getDecl();
2386 return !ED->isScoped() && ED->getDefinitionOrSelf()->isComplete();
2387 }
2388
2389 if (isOverflowBehaviorType() &&
2390 getAs<OverflowBehaviorType>()->getUnderlyingType()->isArithmeticType())
2391 return true;
2392
2393 return isa<ComplexType>(Val: CanonicalType) || isBitIntType();
2394}
2395
2396bool Type::hasBooleanRepresentation() const {
2397 if (const auto *VT = dyn_cast<VectorType>(Val: CanonicalType))
2398 return VT->getElementType()->isBooleanType();
2399 if (const auto *ED = getAsEnumDecl())
2400 return ED->isComplete() && ED->getIntegerType()->isBooleanType();
2401 if (const auto *IT = dyn_cast<BitIntType>(Val: CanonicalType))
2402 return IT->getNumBits() == 1;
2403 return isBooleanType();
2404}
2405
2406Type::ScalarTypeKind Type::getScalarTypeKind() const {
2407 assert(isScalarType());
2408
2409 const Type *T = CanonicalType.getTypePtr();
2410 if (const auto *BT = dyn_cast<BuiltinType>(Val: T)) {
2411 if (BT->getKind() == BuiltinType::Bool)
2412 return STK_Bool;
2413 if (BT->getKind() == BuiltinType::NullPtr)
2414 return STK_CPointer;
2415 if (BT->isInteger())
2416 return STK_Integral;
2417 if (BT->isFloatingPoint())
2418 return STK_Floating;
2419 if (BT->isFixedPointType())
2420 return STK_FixedPoint;
2421 llvm_unreachable("unknown scalar builtin type");
2422 } else if (isa<PointerType>(Val: T)) {
2423 return STK_CPointer;
2424 } else if (isa<BlockPointerType>(Val: T)) {
2425 return STK_BlockPointer;
2426 } else if (isa<ObjCObjectPointerType>(Val: T)) {
2427 return STK_ObjCObjectPointer;
2428 } else if (isa<MemberPointerType>(Val: T)) {
2429 return STK_MemberPointer;
2430 } else if (isa<EnumType>(Val: T)) {
2431 assert(T->castAsEnumDecl()->isComplete());
2432 return STK_Integral;
2433 } else if (const auto *CT = dyn_cast<ComplexType>(Val: T)) {
2434 if (CT->getElementType()->isRealFloatingType())
2435 return STK_FloatingComplex;
2436 return STK_IntegralComplex;
2437 } else if (isBitIntType()) {
2438 return STK_Integral;
2439 } else if (isa<OverflowBehaviorType>(Val: T)) {
2440 return STK_Integral;
2441 }
2442
2443 llvm_unreachable("unknown scalar type");
2444}
2445
2446/// Determines whether the type is a C++ aggregate type or C
2447/// aggregate or union type.
2448///
2449/// An aggregate type is an array or a class type (struct, union, or
2450/// class) that has no user-declared constructors, no private or
2451/// protected non-static data members, no base classes, and no virtual
2452/// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
2453/// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
2454/// includes union types.
2455bool Type::isAggregateType() const {
2456 if (const auto *Record = dyn_cast<RecordType>(Val: CanonicalType)) {
2457 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Val: Record->getDecl()))
2458 return ClassDecl->isAggregate();
2459
2460 return true;
2461 }
2462
2463 return isa<ArrayType>(Val: CanonicalType);
2464}
2465
2466/// isConstantSizeType - Return true if this is not a variable sized type,
2467/// according to the rules of C99 6.7.5p3. It is not legal to call this on
2468/// incomplete types or dependent types.
2469bool Type::isConstantSizeType() const {
2470 assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
2471 assert(!isDependentType() && "This doesn't make sense for dependent types");
2472 // The VAT must have a size, as it is known to be complete.
2473 return !isa<VariableArrayType>(Val: CanonicalType);
2474}
2475
2476/// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
2477/// - a type that can describe objects, but which lacks information needed to
2478/// determine its size.
2479bool Type::isIncompleteType(NamedDecl **Def) const {
2480 if (Def)
2481 *Def = nullptr;
2482
2483 switch (CanonicalType->getTypeClass()) {
2484 default:
2485 return false;
2486 case Builtin:
2487 // Void is the only incomplete builtin type. Per C99 6.2.5p19, it can never
2488 // be completed.
2489 return isVoidType();
2490 case Enum: {
2491 auto *EnumD = castAsEnumDecl();
2492 if (Def)
2493 *Def = EnumD;
2494 return !EnumD->isComplete();
2495 }
2496 case Record: {
2497 // A tagged type (struct/union/enum/class) is incomplete if the decl is a
2498 // forward declaration, but not a full definition (C99 6.2.5p22).
2499 auto *Rec = castAsRecordDecl();
2500 if (Def)
2501 *Def = Rec;
2502 return !Rec->isCompleteDefinition();
2503 }
2504 case InjectedClassName: {
2505 auto *Rec = castAsCXXRecordDecl();
2506 if (!Rec->isBeingDefined())
2507 return false;
2508 if (Def)
2509 *Def = Rec;
2510 return true;
2511 }
2512 case ConstantArray:
2513 case VariableArray:
2514 // An array is incomplete if its element type is incomplete
2515 // (C++ [dcl.array]p1).
2516 // We don't handle dependent-sized arrays (dependent types are never treated
2517 // as incomplete).
2518 return cast<ArrayType>(Val: CanonicalType)
2519 ->getElementType()
2520 ->isIncompleteType(Def);
2521 case IncompleteArray:
2522 // An array of unknown size is an incomplete type (C99 6.2.5p22).
2523 return true;
2524 case MemberPointer: {
2525 // Member pointers in the MS ABI have special behavior in
2526 // RequireCompleteType: they attach a MSInheritanceAttr to the CXXRecordDecl
2527 // to indicate which inheritance model to use.
2528 // The inheritance attribute might only be present on the most recent
2529 // CXXRecordDecl.
2530 const CXXRecordDecl *RD =
2531 cast<MemberPointerType>(Val: CanonicalType)->getMostRecentCXXRecordDecl();
2532 // Member pointers with dependent class types don't get special treatment.
2533 if (!RD || RD->isDependentType())
2534 return false;
2535 ASTContext &Context = RD->getASTContext();
2536 // Member pointers not in the MS ABI don't get special treatment.
2537 if (!Context.getTargetInfo().getCXXABI().isMicrosoft())
2538 return false;
2539 // Nothing interesting to do if the inheritance attribute is already set.
2540 if (RD->hasAttr<MSInheritanceAttr>())
2541 return false;
2542 return true;
2543 }
2544 case ObjCObject:
2545 return cast<ObjCObjectType>(Val: CanonicalType)
2546 ->getBaseType()
2547 ->isIncompleteType(Def);
2548 case ObjCInterface: {
2549 // ObjC interfaces are incomplete if they are @class, not @interface.
2550 ObjCInterfaceDecl *Interface =
2551 cast<ObjCInterfaceType>(Val: CanonicalType)->getDecl();
2552 if (Def)
2553 *Def = Interface;
2554 return !Interface->hasDefinition();
2555 }
2556 }
2557}
2558
2559bool Type::isAlwaysIncompleteType() const {
2560 if (!isIncompleteType())
2561 return false;
2562
2563 // Forward declarations of structs, classes, enums, and unions could be later
2564 // completed in a compilation unit by providing a type definition.
2565 if (isa<TagType>(Val: CanonicalType))
2566 return false;
2567
2568 // Other types are incompletable.
2569 //
2570 // E.g. `char[]` and `void`. The type is incomplete and no future
2571 // type declarations can make the type complete.
2572 return true;
2573}
2574
2575bool Type::isSizelessBuiltinType() const {
2576 if (isSizelessVectorType())
2577 return true;
2578
2579 if (const BuiltinType *BT = getAs<BuiltinType>()) {
2580 switch (BT->getKind()) {
2581 // WebAssembly reference types
2582#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2583#include "clang/Basic/WebAssemblyReferenceTypes.def"
2584 // HLSL intangible types
2585#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2586#include "clang/Basic/HLSLIntangibleTypes.def"
2587 return true;
2588 default:
2589 return false;
2590 }
2591 }
2592 return false;
2593}
2594
2595bool Type::isWebAssemblyExternrefType() const {
2596 if (const auto *BT = getAs<BuiltinType>())
2597 return BT->getKind() == BuiltinType::WasmExternRef;
2598 return false;
2599}
2600
2601bool Type::isWebAssemblyTableType() const {
2602 if (const auto *ATy = dyn_cast<ArrayType>(Val: this))
2603 return ATy->getElementType().isWebAssemblyReferenceType();
2604
2605 if (const auto *PTy = dyn_cast<PointerType>(Val: this))
2606 return PTy->getPointeeType().isWebAssemblyReferenceType();
2607
2608 return false;
2609}
2610
2611bool Type::isSizelessType() const { return isSizelessBuiltinType(); }
2612
2613bool Type::isSizelessVectorType() const {
2614 return isSVESizelessBuiltinType() || isRVVSizelessBuiltinType();
2615}
2616
2617bool Type::isSVESizelessBuiltinType() const {
2618 if (const BuiltinType *BT = getAs<BuiltinType>()) {
2619 switch (BT->getKind()) {
2620 // SVE Types
2621#define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId) \
2622 case BuiltinType::Id: \
2623 return true;
2624#define SVE_OPAQUE_TYPE(Name, MangledName, Id, SingletonId) \
2625 case BuiltinType::Id: \
2626 return true;
2627#define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId) \
2628 case BuiltinType::Id: \
2629 return true;
2630#include "clang/Basic/AArch64ACLETypes.def"
2631 default:
2632 return false;
2633 }
2634 }
2635 return false;
2636}
2637
2638bool Type::isRVVSizelessBuiltinType() const {
2639 if (const BuiltinType *BT = getAs<BuiltinType>()) {
2640 switch (BT->getKind()) {
2641#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2642#include "clang/Basic/RISCVVTypes.def"
2643 return true;
2644 default:
2645 return false;
2646 }
2647 }
2648 return false;
2649}
2650
2651bool Type::isSveVLSBuiltinType() const {
2652 if (const BuiltinType *BT = getAs<BuiltinType>()) {
2653 switch (BT->getKind()) {
2654 case BuiltinType::SveInt8:
2655 case BuiltinType::SveInt16:
2656 case BuiltinType::SveInt32:
2657 case BuiltinType::SveInt64:
2658 case BuiltinType::SveUint8:
2659 case BuiltinType::SveUint16:
2660 case BuiltinType::SveUint32:
2661 case BuiltinType::SveUint64:
2662 case BuiltinType::SveFloat16:
2663 case BuiltinType::SveFloat32:
2664 case BuiltinType::SveFloat64:
2665 case BuiltinType::SveBFloat16:
2666 case BuiltinType::SveBool:
2667 case BuiltinType::SveBoolx2:
2668 case BuiltinType::SveBoolx4:
2669 case BuiltinType::SveMFloat8:
2670 return true;
2671 default:
2672 return false;
2673 }
2674 }
2675 return false;
2676}
2677
2678QualType Type::getSizelessVectorEltType(const ASTContext &Ctx) const {
2679 assert(isSizelessVectorType() && "Must be sizeless vector type");
2680 // Currently supports SVE and RVV
2681 if (isSVESizelessBuiltinType())
2682 return getSveEltType(Ctx);
2683
2684 if (isRVVSizelessBuiltinType())
2685 return getRVVEltType(Ctx);
2686
2687 llvm_unreachable("Unhandled type");
2688}
2689
2690QualType Type::getSveEltType(const ASTContext &Ctx) const {
2691 assert(isSveVLSBuiltinType() && "unsupported type!");
2692
2693 const BuiltinType *BTy = castAs<BuiltinType>();
2694 if (BTy->getKind() == BuiltinType::SveBool)
2695 // Represent predicates as i8 rather than i1 to avoid any layout issues.
2696 // The type is bitcasted to a scalable predicate type when casting between
2697 // scalable and fixed-length vectors.
2698 return Ctx.UnsignedCharTy;
2699 else
2700 return Ctx.getBuiltinVectorTypeInfo(VecTy: BTy).ElementType;
2701}
2702
2703bool Type::isRVVVLSBuiltinType() const {
2704 if (const BuiltinType *BT = getAs<BuiltinType>()) {
2705 switch (BT->getKind()) {
2706#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
2707 IsFP, IsBF) \
2708 case BuiltinType::Id: \
2709 return NF == 1;
2710#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
2711 case BuiltinType::Id: \
2712 return true;
2713#include "clang/Basic/RISCVVTypes.def"
2714 default:
2715 return false;
2716 }
2717 }
2718 return false;
2719}
2720
2721QualType Type::getRVVEltType(const ASTContext &Ctx) const {
2722 assert(isRVVVLSBuiltinType() && "unsupported type!");
2723
2724 const BuiltinType *BTy = castAs<BuiltinType>();
2725
2726 switch (BTy->getKind()) {
2727#define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
2728 case BuiltinType::Id: \
2729 return Ctx.UnsignedCharTy;
2730 default:
2731 return Ctx.getBuiltinVectorTypeInfo(VecTy: BTy).ElementType;
2732#include "clang/Basic/RISCVVTypes.def"
2733 }
2734
2735 llvm_unreachable("Unhandled type");
2736}
2737
2738bool QualType::isPODType(const ASTContext &Context) const {
2739 // C++11 has a more relaxed definition of POD.
2740 if (Context.getLangOpts().CPlusPlus11)
2741 return isCXX11PODType(Context);
2742
2743 return isCXX98PODType(Context);
2744}
2745
2746bool QualType::isCXX98PODType(const ASTContext &Context) const {
2747 // The compiler shouldn't query this for incomplete types, but the user might.
2748 // We return false for that case. Except for incomplete arrays of PODs, which
2749 // are PODs according to the standard.
2750 if (isNull())
2751 return false;
2752
2753 if ((*this)->isIncompleteArrayType())
2754 return Context.getBaseElementType(QT: *this).isCXX98PODType(Context);
2755
2756 if ((*this)->isIncompleteType())
2757 return false;
2758
2759 if (hasNonTrivialObjCLifetime())
2760 return false;
2761
2762 QualType CanonicalType = getTypePtr()->CanonicalType;
2763
2764 // Any type that is, or contains, address discriminated data is never POD.
2765 if (Context.containsAddressDiscriminatedPointerAuth(T: CanonicalType))
2766 return false;
2767
2768 switch (CanonicalType->getTypeClass()) {
2769 // Everything not explicitly mentioned is not POD.
2770 default:
2771 return false;
2772 case Type::VariableArray:
2773 case Type::ConstantArray:
2774 // IncompleteArray is handled above.
2775 return Context.getBaseElementType(QT: *this).isCXX98PODType(Context);
2776
2777 case Type::ObjCObjectPointer:
2778 case Type::BlockPointer:
2779 case Type::Builtin:
2780 case Type::Complex:
2781 case Type::Pointer:
2782 case Type::MemberPointer:
2783 case Type::Vector:
2784 case Type::ExtVector:
2785 case Type::BitInt:
2786 case Type::OverflowBehavior:
2787 return true;
2788
2789 case Type::Enum:
2790 return true;
2791
2792 case Type::Record:
2793 if (const auto *ClassDecl =
2794 dyn_cast<CXXRecordDecl>(Val: cast<RecordType>(Val&: CanonicalType)->getDecl()))
2795 return ClassDecl->isPOD();
2796
2797 // C struct/union is POD.
2798 return true;
2799 }
2800}
2801
2802bool QualType::isTrivialType(const ASTContext &Context) const {
2803 // The compiler shouldn't query this for incomplete types, but the user might.
2804 // We return false for that case. Except for incomplete arrays of PODs, which
2805 // are PODs according to the standard.
2806 if (isNull())
2807 return false;
2808
2809 if ((*this)->isArrayType())
2810 return Context.getBaseElementType(QT: *this).isTrivialType(Context);
2811
2812 if ((*this)->isSizelessBuiltinType())
2813 return true;
2814
2815 // Return false for incomplete types after skipping any incomplete array
2816 // types which are expressly allowed by the standard and thus our API.
2817 if ((*this)->isIncompleteType())
2818 return false;
2819
2820 if (hasNonTrivialObjCLifetime())
2821 return false;
2822
2823 QualType CanonicalType = getTypePtr()->CanonicalType;
2824 if (CanonicalType->isDependentType())
2825 return false;
2826
2827 // Any type that is, or contains, address discriminated data is never a
2828 // trivial type.
2829 if (Context.containsAddressDiscriminatedPointerAuth(T: CanonicalType))
2830 return false;
2831
2832 // C++0x [basic.types]p9:
2833 // Scalar types, trivial class types, arrays of such types, and
2834 // cv-qualified versions of these types are collectively called trivial
2835 // types.
2836
2837 // As an extension, Clang treats vector types as Scalar types.
2838 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
2839 return true;
2840
2841 if (const auto *ClassDecl = CanonicalType->getAsCXXRecordDecl()) {
2842 // C++20 [class]p6:
2843 // A trivial class is a class that is trivially copyable, and
2844 // has one or more eligible default constructors such that each is
2845 // trivial.
2846 // FIXME: We should merge this definition of triviality into
2847 // CXXRecordDecl::isTrivial. Currently it computes the wrong thing.
2848 return ClassDecl->hasTrivialDefaultConstructor() &&
2849 !ClassDecl->hasNonTrivialDefaultConstructor() &&
2850 ClassDecl->isTriviallyCopyable();
2851 }
2852
2853 if (isa<RecordType>(Val: CanonicalType))
2854 return true;
2855
2856 // No other types can match.
2857 return false;
2858}
2859
2860static bool isTriviallyCopyableTypeImpl(const QualType &type,
2861 const ASTContext &Context,
2862 bool IsCopyConstructible) {
2863 if (type->isArrayType())
2864 return isTriviallyCopyableTypeImpl(type: Context.getBaseElementType(QT: type),
2865 Context, IsCopyConstructible);
2866
2867 if (type.hasNonTrivialObjCLifetime())
2868 return false;
2869
2870 // C++11 [basic.types]p9 - See Core 2094
2871 // Scalar types, trivially copyable class types, arrays of such types, and
2872 // cv-qualified versions of these types are collectively
2873 // called trivially copy constructible types.
2874
2875 QualType CanonicalType = type.getCanonicalType();
2876 if (CanonicalType->isDependentType())
2877 return false;
2878
2879 if (CanonicalType->isSizelessBuiltinType())
2880 return true;
2881
2882 // Return false for incomplete types after skipping any incomplete array types
2883 // which are expressly allowed by the standard and thus our API.
2884 if (CanonicalType->isIncompleteType())
2885 return false;
2886
2887 if (CanonicalType.hasAddressDiscriminatedPointerAuth())
2888 return false;
2889
2890 // As an extension, Clang treats vector types as Scalar types.
2891 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
2892 return true;
2893
2894 // Mfloat8 type is a special case as it not scalar, but is still trivially
2895 // copyable.
2896 if (CanonicalType->isMFloat8Type())
2897 return true;
2898
2899 if (const auto *RD = CanonicalType->getAsRecordDecl()) {
2900 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Val: RD)) {
2901 if (IsCopyConstructible)
2902 return ClassDecl->isTriviallyCopyConstructible();
2903 return ClassDecl->isTriviallyCopyable();
2904 }
2905 return !RD->isNonTrivialToPrimitiveCopy();
2906 }
2907 // No other types can match.
2908 return false;
2909}
2910
2911bool QualType::isTriviallyCopyableType(const ASTContext &Context) const {
2912 return isTriviallyCopyableTypeImpl(type: *this, Context,
2913 /*IsCopyConstructible=*/false);
2914}
2915
2916// FIXME: each call will trigger a full computation, cache the result.
2917bool QualType::isBitwiseCloneableType(const ASTContext &Context) const {
2918 auto CanonicalType = getCanonicalType();
2919 if (CanonicalType.hasNonTrivialObjCLifetime())
2920 return false;
2921 if (CanonicalType->isArrayType())
2922 return Context.getBaseElementType(QT: CanonicalType)
2923 .isBitwiseCloneableType(Context);
2924
2925 if (CanonicalType->isIncompleteType())
2926 return false;
2927
2928 // Any type that is, or contains, address discriminated data is never
2929 // bitwise clonable.
2930 if (Context.containsAddressDiscriminatedPointerAuth(T: CanonicalType))
2931 return false;
2932
2933 const auto *RD = CanonicalType->getAsRecordDecl(); // struct/union/class
2934 if (!RD)
2935 return true;
2936
2937 // Never allow memcpy when we're adding poisoned padding bits to the struct.
2938 // Accessing these posioned bits will trigger false alarms on
2939 // SanitizeAddressFieldPadding etc.
2940 if (RD->mayInsertExtraPadding())
2941 return false;
2942
2943 for (auto *const Field : RD->fields()) {
2944 if (!Field->getType().isBitwiseCloneableType(Context))
2945 return false;
2946 }
2947
2948 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
2949 for (auto Base : CXXRD->bases())
2950 if (!Base.getType().isBitwiseCloneableType(Context))
2951 return false;
2952 for (auto VBase : CXXRD->vbases())
2953 if (!VBase.getType().isBitwiseCloneableType(Context))
2954 return false;
2955 }
2956 return true;
2957}
2958
2959bool QualType::isTriviallyCopyConstructibleType(
2960 const ASTContext &Context) const {
2961 return isTriviallyCopyableTypeImpl(type: *this, Context,
2962 /*IsCopyConstructible=*/true);
2963}
2964
2965bool QualType::isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const {
2966 return !Context.getLangOpts().ObjCAutoRefCount &&
2967 Context.getLangOpts().ObjCWeak &&
2968 getObjCLifetime() != Qualifiers::OCL_Weak;
2969}
2970
2971bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion(
2972 const RecordDecl *RD) {
2973 return RD->hasNonTrivialToPrimitiveDefaultInitializeCUnion();
2974}
2975
2976bool QualType::hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD) {
2977 return RD->hasNonTrivialToPrimitiveDestructCUnion();
2978}
2979
2980bool QualType::hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD) {
2981 return RD->hasNonTrivialToPrimitiveCopyCUnion();
2982}
2983
2984bool QualType::isWebAssemblyReferenceType() const {
2985 return isWebAssemblyExternrefType() || isWebAssemblyFuncrefType();
2986}
2987
2988bool QualType::isWebAssemblyExternrefType() const {
2989 return getTypePtr()->isWebAssemblyExternrefType();
2990}
2991
2992bool QualType::isWebAssemblyFuncrefType() const {
2993 return getTypePtr()->isFunctionPointerType() &&
2994 (getTypePtr()->getPointeeType().getAddressSpace() ==
2995 LangAS::wasm_funcref);
2996}
2997
2998bool QualType::isWrapType() const {
2999 if (const auto *OBT = getCanonicalType()->getAs<OverflowBehaviorType>())
3000 return OBT->getBehaviorKind() ==
3001 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
3002
3003 return false;
3004}
3005
3006bool QualType::isTrapType() const {
3007 if (const auto *OBT = getCanonicalType()->getAs<OverflowBehaviorType>())
3008 return OBT->getBehaviorKind() ==
3009 OverflowBehaviorType::OverflowBehaviorKind::Trap;
3010
3011 return false;
3012}
3013
3014QualType::PrimitiveDefaultInitializeKind
3015QualType::isNonTrivialToPrimitiveDefaultInitialize() const {
3016 if (const auto *RD =
3017 getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
3018 if (RD->isNonTrivialToPrimitiveDefaultInitialize())
3019 return PDIK_Struct;
3020
3021 switch (getQualifiers().getObjCLifetime()) {
3022 case Qualifiers::OCL_Strong:
3023 return PDIK_ARCStrong;
3024 case Qualifiers::OCL_Weak:
3025 return PDIK_ARCWeak;
3026 default:
3027 return PDIK_Trivial;
3028 }
3029}
3030
3031QualType::PrimitiveCopyKind QualType::isNonTrivialToPrimitiveCopy() const {
3032 if (const auto *RD =
3033 getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
3034 if (RD->isNonTrivialToPrimitiveCopy())
3035 return PCK_Struct;
3036
3037 Qualifiers Qs = getQualifiers();
3038 switch (Qs.getObjCLifetime()) {
3039 case Qualifiers::OCL_Strong:
3040 return PCK_ARCStrong;
3041 case Qualifiers::OCL_Weak:
3042 return PCK_ARCWeak;
3043 default:
3044 if (hasAddressDiscriminatedPointerAuth())
3045 return PCK_PtrAuth;
3046 return Qs.hasVolatile() ? PCK_VolatileTrivial : PCK_Trivial;
3047 }
3048}
3049
3050QualType::PrimitiveCopyKind
3051QualType::isNonTrivialToPrimitiveDestructiveMove() const {
3052 return isNonTrivialToPrimitiveCopy();
3053}
3054
3055bool Type::isLiteralType(const ASTContext &Ctx) const {
3056 if (isDependentType())
3057 return false;
3058
3059 // C++1y [basic.types]p10:
3060 // A type is a literal type if it is:
3061 // -- cv void; or
3062 if (Ctx.getLangOpts().CPlusPlus14 && isVoidType())
3063 return true;
3064
3065 // C++11 [basic.types]p10:
3066 // A type is a literal type if it is:
3067 // [...]
3068 // -- an array of literal type other than an array of runtime bound; or
3069 if (isVariableArrayType())
3070 return false;
3071 const Type *BaseTy = getBaseElementTypeUnsafe();
3072 assert(BaseTy && "NULL element type");
3073
3074 // Return false for incomplete types after skipping any incomplete array
3075 // types; those are expressly allowed by the standard and thus our API.
3076 if (BaseTy->isIncompleteType())
3077 return false;
3078
3079 // C++11 [basic.types]p10:
3080 // A type is a literal type if it is:
3081 // -- a scalar type; or
3082 // As an extension, Clang treats vector types and complex types as
3083 // literal types.
3084 if (BaseTy->isScalarType() || BaseTy->isVectorType() ||
3085 BaseTy->isAnyComplexType())
3086 return true;
3087 // -- a reference type; or
3088 if (BaseTy->isReferenceType())
3089 return true;
3090 // -- a class type that has all of the following properties:
3091 if (const auto *RD = BaseTy->getAsRecordDecl()) {
3092 // -- a trivial destructor,
3093 // -- every constructor call and full-expression in the
3094 // brace-or-equal-initializers for non-static data members (if any)
3095 // is a constant expression,
3096 // -- it is an aggregate type or has at least one constexpr
3097 // constructor or constructor template that is not a copy or move
3098 // constructor, and
3099 // -- all non-static data members and base classes of literal types
3100 //
3101 // We resolve DR1361 by ignoring the second bullet.
3102 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Val: RD))
3103 return ClassDecl->isLiteral();
3104
3105 return true;
3106 }
3107
3108 // We treat _Atomic T as a literal type if T is a literal type.
3109 if (const auto *AT = BaseTy->getAs<AtomicType>())
3110 return AT->getValueType()->isLiteralType(Ctx);
3111
3112 if (const auto *OBT = BaseTy->getAs<OverflowBehaviorType>())
3113 return OBT->getUnderlyingType()->isLiteralType(Ctx);
3114
3115 // If this type hasn't been deduced yet, then conservatively assume that
3116 // it'll work out to be a literal type.
3117 if (isa<AutoType>(Val: BaseTy->getCanonicalTypeInternal()))
3118 return true;
3119
3120 return false;
3121}
3122
3123bool Type::isStructuralType() const {
3124 // C++20 [temp.param]p6:
3125 // A structural type is one of the following:
3126 // -- a scalar type; or
3127 // -- a vector type [Clang extension]; or
3128 if (isScalarType() || isVectorType())
3129 return true;
3130 // -- an lvalue reference type; or
3131 if (isLValueReferenceType())
3132 return true;
3133 // -- a literal class type [...under some conditions]
3134 if (const CXXRecordDecl *RD = getAsCXXRecordDecl())
3135 return RD->isStructural();
3136 return false;
3137}
3138
3139bool Type::isStandardLayoutType() const {
3140 if (isDependentType())
3141 return false;
3142
3143 // C++0x [basic.types]p9:
3144 // Scalar types, standard-layout class types, arrays of such types, and
3145 // cv-qualified versions of these types are collectively called
3146 // standard-layout types.
3147 const Type *BaseTy = getBaseElementTypeUnsafe();
3148 assert(BaseTy && "NULL element type");
3149
3150 // Return false for incomplete types after skipping any incomplete array
3151 // types which are expressly allowed by the standard and thus our API.
3152 if (BaseTy->isIncompleteType())
3153 return false;
3154
3155 // As an extension, Clang treats vector types as Scalar types.
3156 if (BaseTy->isScalarType() || BaseTy->isVectorType())
3157 return true;
3158 if (const auto *RD = BaseTy->getAsRecordDecl()) {
3159 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Val: RD);
3160 ClassDecl && !ClassDecl->isStandardLayout())
3161 return false;
3162
3163 // Default to 'true' for non-C++ class types.
3164 // FIXME: This is a bit dubious, but plain C structs should trivially meet
3165 // all the requirements of standard layout classes.
3166 return true;
3167 }
3168
3169 // No other types can match.
3170 return false;
3171}
3172
3173// This is effectively the intersection of isTrivialType and
3174// isStandardLayoutType. We implement it directly to avoid redundant
3175// conversions from a type to a CXXRecordDecl.
3176bool QualType::isCXX11PODType(const ASTContext &Context) const {
3177 const Type *ty = getTypePtr();
3178 if (ty->isDependentType())
3179 return false;
3180
3181 if (hasNonTrivialObjCLifetime())
3182 return false;
3183
3184 // C++11 [basic.types]p9:
3185 // Scalar types, POD classes, arrays of such types, and cv-qualified
3186 // versions of these types are collectively called trivial types.
3187 const Type *BaseTy = ty->getBaseElementTypeUnsafe();
3188 assert(BaseTy && "NULL element type");
3189
3190 if (BaseTy->isSizelessBuiltinType())
3191 return true;
3192
3193 // Return false for incomplete types after skipping any incomplete array
3194 // types which are expressly allowed by the standard and thus our API.
3195 if (BaseTy->isIncompleteType())
3196 return false;
3197
3198 // Any type that is, or contains, address discriminated data is non-POD.
3199 if (Context.containsAddressDiscriminatedPointerAuth(T: *this))
3200 return false;
3201
3202 // As an extension, Clang treats vector types as Scalar types.
3203 if (BaseTy->isScalarType() || BaseTy->isVectorType())
3204 return true;
3205 if (const auto *RD = BaseTy->getAsRecordDecl()) {
3206 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Val: RD)) {
3207 // C++11 [class]p10:
3208 // A POD struct is a non-union class that is both a trivial class [...]
3209 if (!ClassDecl->isTrivial())
3210 return false;
3211
3212 // C++11 [class]p10:
3213 // A POD struct is a non-union class that is both a trivial class and
3214 // a standard-layout class [...]
3215 if (!ClassDecl->isStandardLayout())
3216 return false;
3217
3218 // C++11 [class]p10:
3219 // A POD struct is a non-union class that is both a trivial class and
3220 // a standard-layout class, and has no non-static data members of type
3221 // non-POD struct, non-POD union (or array of such types). [...]
3222 //
3223 // We don't directly query the recursive aspect as the requirements for
3224 // both standard-layout classes and trivial classes apply recursively
3225 // already.
3226 }
3227
3228 return true;
3229 }
3230
3231 // No other types can match.
3232 return false;
3233}
3234
3235bool Type::isNothrowT() const {
3236 if (const auto *RD = getAsCXXRecordDecl()) {
3237 IdentifierInfo *II = RD->getIdentifier();
3238 if (II && II->isStr(Str: "nothrow_t") && RD->isInStdNamespace())
3239 return true;
3240 }
3241 return false;
3242}
3243
3244bool Type::isAlignValT() const {
3245 if (const auto *ET = getAsCanonical<EnumType>()) {
3246 const auto *ED = ET->getDecl();
3247 IdentifierInfo *II = ED->getIdentifier();
3248 if (II && II->isStr(Str: "align_val_t") && ED->isInStdNamespace())
3249 return true;
3250 }
3251 return false;
3252}
3253
3254bool Type::isStdByteType() const {
3255 if (const auto *ET = getAsCanonical<EnumType>()) {
3256 const auto *ED = ET->getDecl();
3257 IdentifierInfo *II = ED->getIdentifier();
3258 if (II && II->isStr(Str: "byte") && ED->isInStdNamespace())
3259 return true;
3260 }
3261 return false;
3262}
3263
3264bool Type::isSpecifierType() const {
3265 // Note that this intentionally does not use the canonical type.
3266 switch (getTypeClass()) {
3267 case Builtin:
3268 case Record:
3269 case Enum:
3270 case Typedef:
3271 case Complex:
3272 case TypeOfExpr:
3273 case TypeOf:
3274 case TemplateTypeParm:
3275 case SubstTemplateTypeParm:
3276 case TemplateSpecialization:
3277 case DependentName:
3278 case ObjCInterface:
3279 case ObjCObject:
3280 return true;
3281 default:
3282 return false;
3283 }
3284}
3285
3286ElaboratedTypeKeyword KeywordHelpers::getKeywordForTypeSpec(unsigned TypeSpec) {
3287 switch (TypeSpec) {
3288 default:
3289 return ElaboratedTypeKeyword::None;
3290 case TST_typename:
3291 return ElaboratedTypeKeyword::Typename;
3292 case TST_class:
3293 return ElaboratedTypeKeyword::Class;
3294 case TST_struct:
3295 return ElaboratedTypeKeyword::Struct;
3296 case TST_interface:
3297 return ElaboratedTypeKeyword::Interface;
3298 case TST_union:
3299 return ElaboratedTypeKeyword::Union;
3300 case TST_enum:
3301 return ElaboratedTypeKeyword::Enum;
3302 }
3303}
3304
3305TagTypeKind KeywordHelpers::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
3306 switch (TypeSpec) {
3307 case TST_class:
3308 return TagTypeKind::Class;
3309 case TST_struct:
3310 return TagTypeKind::Struct;
3311 case TST_interface:
3312 return TagTypeKind::Interface;
3313 case TST_union:
3314 return TagTypeKind::Union;
3315 case TST_enum:
3316 return TagTypeKind::Enum;
3317 }
3318
3319 llvm_unreachable("Type specifier is not a tag type kind.");
3320}
3321
3322ElaboratedTypeKeyword
3323KeywordHelpers::getKeywordForTagTypeKind(TagTypeKind Kind) {
3324 switch (Kind) {
3325 case TagTypeKind::Class:
3326 return ElaboratedTypeKeyword::Class;
3327 case TagTypeKind::Struct:
3328 return ElaboratedTypeKeyword::Struct;
3329 case TagTypeKind::Interface:
3330 return ElaboratedTypeKeyword::Interface;
3331 case TagTypeKind::Union:
3332 return ElaboratedTypeKeyword::Union;
3333 case TagTypeKind::Enum:
3334 return ElaboratedTypeKeyword::Enum;
3335 }
3336 llvm_unreachable("Unknown tag type kind.");
3337}
3338
3339TagTypeKind
3340KeywordHelpers::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
3341 switch (Keyword) {
3342 case ElaboratedTypeKeyword::Class:
3343 return TagTypeKind::Class;
3344 case ElaboratedTypeKeyword::Struct:
3345 return TagTypeKind::Struct;
3346 case ElaboratedTypeKeyword::Interface:
3347 return TagTypeKind::Interface;
3348 case ElaboratedTypeKeyword::Union:
3349 return TagTypeKind::Union;
3350 case ElaboratedTypeKeyword::Enum:
3351 return TagTypeKind::Enum;
3352 case ElaboratedTypeKeyword::None: // Fall through.
3353 case ElaboratedTypeKeyword::Typename:
3354 llvm_unreachable("Elaborated type keyword is not a tag type kind.");
3355 }
3356 llvm_unreachable("Unknown elaborated type keyword.");
3357}
3358
3359bool KeywordHelpers::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
3360 switch (Keyword) {
3361 case ElaboratedTypeKeyword::None:
3362 case ElaboratedTypeKeyword::Typename:
3363 return false;
3364 case ElaboratedTypeKeyword::Class:
3365 case ElaboratedTypeKeyword::Struct:
3366 case ElaboratedTypeKeyword::Interface:
3367 case ElaboratedTypeKeyword::Union:
3368 case ElaboratedTypeKeyword::Enum:
3369 return true;
3370 }
3371 llvm_unreachable("Unknown elaborated type keyword.");
3372}
3373
3374StringRef KeywordHelpers::getKeywordName(ElaboratedTypeKeyword Keyword) {
3375 switch (Keyword) {
3376 case ElaboratedTypeKeyword::None:
3377 return {};
3378 case ElaboratedTypeKeyword::Typename:
3379 return "typename";
3380 case ElaboratedTypeKeyword::Class:
3381 return "class";
3382 case ElaboratedTypeKeyword::Struct:
3383 return "struct";
3384 case ElaboratedTypeKeyword::Interface:
3385 return "__interface";
3386 case ElaboratedTypeKeyword::Union:
3387 return "union";
3388 case ElaboratedTypeKeyword::Enum:
3389 return "enum";
3390 }
3391
3392 llvm_unreachable("Unknown elaborated type keyword.");
3393}
3394
3395bool Type::isElaboratedTypeSpecifier() const {
3396 ElaboratedTypeKeyword Keyword;
3397 if (const auto *TST = dyn_cast<TemplateSpecializationType>(Val: this))
3398 Keyword = TST->getKeyword();
3399 else if (const auto *DepName = dyn_cast<DependentNameType>(Val: this))
3400 Keyword = DepName->getKeyword();
3401 else if (const auto *T = dyn_cast<TagType>(Val: this))
3402 Keyword = T->getKeyword();
3403 else if (const auto *T = dyn_cast<TypedefType>(Val: this))
3404 Keyword = T->getKeyword();
3405 else if (const auto *T = dyn_cast<UnresolvedUsingType>(Val: this))
3406 Keyword = T->getKeyword();
3407 else if (const auto *T = dyn_cast<UsingType>(Val: this))
3408 Keyword = T->getKeyword();
3409 else
3410 return false;
3411
3412 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
3413}
3414
3415const char *Type::getTypeClassName() const {
3416 switch (TypeBits.TC) {
3417#define ABSTRACT_TYPE(Derived, Base)
3418#define TYPE(Derived, Base) \
3419 case Derived: \
3420 return #Derived;
3421#include "clang/AST/TypeNodes.inc"
3422 }
3423
3424 llvm_unreachable("Invalid type class.");
3425}
3426
3427StringRef BuiltinType::getName(const PrintingPolicy &Policy) const {
3428 switch (getKind()) {
3429 case Void:
3430 return "void";
3431 case Bool:
3432 return Policy.Bool ? "bool" : "_Bool";
3433 case Char_S:
3434 return "char";
3435 case Char_U:
3436 return "char";
3437 case SChar:
3438 return "signed char";
3439 case Short:
3440 return "short";
3441 case Int:
3442 return "int";
3443 case Long:
3444 return "long";
3445 case LongLong:
3446 return "long long";
3447 case Int128:
3448 return "__int128";
3449 case UChar:
3450 return "unsigned char";
3451 case UShort:
3452 return "unsigned short";
3453 case UInt:
3454 return "unsigned int";
3455 case ULong:
3456 return "unsigned long";
3457 case ULongLong:
3458 return "unsigned long long";
3459 case UInt128:
3460 return "unsigned __int128";
3461 case Half:
3462 return Policy.Half ? "half" : "__fp16";
3463 case BFloat16:
3464 return "__bf16";
3465 case Float:
3466 return "float";
3467 case Double:
3468 return "double";
3469 case LongDouble:
3470 return "long double";
3471 case ShortAccum:
3472 return "short _Accum";
3473 case Accum:
3474 return "_Accum";
3475 case LongAccum:
3476 return "long _Accum";
3477 case UShortAccum:
3478 return "unsigned short _Accum";
3479 case UAccum:
3480 return "unsigned _Accum";
3481 case ULongAccum:
3482 return "unsigned long _Accum";
3483 case BuiltinType::ShortFract:
3484 return "short _Fract";
3485 case BuiltinType::Fract:
3486 return "_Fract";
3487 case BuiltinType::LongFract:
3488 return "long _Fract";
3489 case BuiltinType::UShortFract:
3490 return "unsigned short _Fract";
3491 case BuiltinType::UFract:
3492 return "unsigned _Fract";
3493 case BuiltinType::ULongFract:
3494 return "unsigned long _Fract";
3495 case BuiltinType::SatShortAccum:
3496 return "_Sat short _Accum";
3497 case BuiltinType::SatAccum:
3498 return "_Sat _Accum";
3499 case BuiltinType::SatLongAccum:
3500 return "_Sat long _Accum";
3501 case BuiltinType::SatUShortAccum:
3502 return "_Sat unsigned short _Accum";
3503 case BuiltinType::SatUAccum:
3504 return "_Sat unsigned _Accum";
3505 case BuiltinType::SatULongAccum:
3506 return "_Sat unsigned long _Accum";
3507 case BuiltinType::SatShortFract:
3508 return "_Sat short _Fract";
3509 case BuiltinType::SatFract:
3510 return "_Sat _Fract";
3511 case BuiltinType::SatLongFract:
3512 return "_Sat long _Fract";
3513 case BuiltinType::SatUShortFract:
3514 return "_Sat unsigned short _Fract";
3515 case BuiltinType::SatUFract:
3516 return "_Sat unsigned _Fract";
3517 case BuiltinType::SatULongFract:
3518 return "_Sat unsigned long _Fract";
3519 case Float16:
3520 return "_Float16";
3521 case Float128:
3522 return "__float128";
3523 case Ibm128:
3524 return "__ibm128";
3525 case WChar_S:
3526 case WChar_U:
3527 return Policy.MSWChar ? "__wchar_t" : "wchar_t";
3528 case Char8:
3529 return "char8_t";
3530 case Char16:
3531 return "char16_t";
3532 case Char32:
3533 return "char32_t";
3534 case NullPtr:
3535 return Policy.NullptrTypeInNamespace ? "std::nullptr_t" : "nullptr_t";
3536 case Overload:
3537 return "<overloaded function type>";
3538 case BoundMember:
3539 return "<bound member function type>";
3540 case UnresolvedTemplate:
3541 return "<unresolved template type>";
3542 case PseudoObject:
3543 return "<pseudo-object type>";
3544 case Dependent:
3545 return "<dependent type>";
3546 case UnknownAny:
3547 return "<unknown type>";
3548 case ARCUnbridgedCast:
3549 return "<ARC unbridged cast type>";
3550 case BuiltinFn:
3551 return "<builtin fn type>";
3552 case ObjCId:
3553 return "id";
3554 case ObjCClass:
3555 return "Class";
3556 case ObjCSel:
3557 return "SEL";
3558#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3559 case Id: \
3560 return "__" #Access " " #ImgType "_t";
3561#include "clang/Basic/OpenCLImageTypes.def"
3562 case OCLSampler:
3563 return "sampler_t";
3564 case OCLEvent:
3565 return "event_t";
3566 case OCLClkEvent:
3567 return "clk_event_t";
3568 case OCLQueue:
3569 return "queue_t";
3570 case OCLReserveID:
3571 return "reserve_id_t";
3572 case IncompleteMatrixIdx:
3573 return "<incomplete matrix index type>";
3574 case ArraySection:
3575 return "<array section type>";
3576 case OMPArrayShaping:
3577 return "<OpenMP array shaping type>";
3578 case OMPIterator:
3579 return "<OpenMP iterator type>";
3580#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3581 case Id: \
3582 return #ExtType;
3583#include "clang/Basic/OpenCLExtensionTypes.def"
3584#define SVE_TYPE(Name, Id, SingletonId) \
3585 case Id: \
3586 return #Name;
3587#include "clang/Basic/AArch64ACLETypes.def"
3588#define PPC_VECTOR_TYPE(Name, Id, Size) \
3589 case Id: \
3590 return #Name;
3591#include "clang/Basic/PPCTypes.def"
3592#define RVV_TYPE(Name, Id, SingletonId) \
3593 case Id: \
3594 return Name;
3595#include "clang/Basic/RISCVVTypes.def"
3596#define WASM_TYPE(Name, Id, SingletonId) \
3597 case Id: \
3598 return Name;
3599#include "clang/Basic/WebAssemblyReferenceTypes.def"
3600#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
3601 case Id: \
3602 return Name;
3603#include "clang/Basic/AMDGPUTypes.def"
3604#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3605 case Id: \
3606 return #Name;
3607#include "clang/Basic/HLSLIntangibleTypes.def"
3608 }
3609
3610 llvm_unreachable("Invalid builtin type.");
3611}
3612
3613QualType QualType::getNonPackExpansionType() const {
3614 // We never wrap type sugar around a PackExpansionType.
3615 if (auto *PET = dyn_cast<PackExpansionType>(Val: getTypePtr()))
3616 return PET->getPattern();
3617 return *this;
3618}
3619
3620QualType QualType::getNonLValueExprType(const ASTContext &Context) const {
3621 if (const auto *RefType = getTypePtr()->getAs<ReferenceType>())
3622 return RefType->getPointeeType();
3623
3624 // C++0x [basic.lval]:
3625 // Class prvalues can have cv-qualified types; non-class prvalues always
3626 // have cv-unqualified types.
3627 //
3628 // See also C99 6.3.2.1p2.
3629 if (!Context.getLangOpts().CPlusPlus ||
3630 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
3631 return getUnqualifiedType();
3632
3633 return *this;
3634}
3635
3636bool FunctionType::getCFIUncheckedCalleeAttr() const {
3637 if (const auto *FPT = getAs<FunctionProtoType>())
3638 return FPT->hasCFIUncheckedCallee();
3639 return false;
3640}
3641
3642StringRef FunctionType::getNameForCallConv(CallingConv CC) {
3643 switch (CC) {
3644 case CC_C:
3645 return "cdecl";
3646 case CC_X86StdCall:
3647 return "stdcall";
3648 case CC_X86FastCall:
3649 return "fastcall";
3650 case CC_X86ThisCall:
3651 return "thiscall";
3652 case CC_X86Pascal:
3653 return "pascal";
3654 case CC_X86VectorCall:
3655 return "vectorcall";
3656 case CC_Win64:
3657 return "ms_abi";
3658 case CC_X86_64SysV:
3659 return "sysv_abi";
3660 case CC_X86RegCall:
3661 return "regcall";
3662 case CC_AAPCS:
3663 return "aapcs";
3664 case CC_AAPCS_VFP:
3665 return "aapcs-vfp";
3666 case CC_AArch64VectorCall:
3667 return "aarch64_vector_pcs";
3668 case CC_AArch64SVEPCS:
3669 return "aarch64_sve_pcs";
3670 case CC_IntelOclBicc:
3671 return "intel_ocl_bicc";
3672 case CC_SpirFunction:
3673 return "spir_function";
3674 case CC_DeviceKernel:
3675 return "device_kernel";
3676 case CC_Swift:
3677 return "swiftcall";
3678 case CC_SwiftAsync:
3679 return "swiftasynccall";
3680 case CC_PreserveMost:
3681 return "preserve_most";
3682 case CC_PreserveAll:
3683 return "preserve_all";
3684 case CC_M68kRTD:
3685 return "m68k_rtd";
3686 case CC_PreserveNone:
3687 return "preserve_none";
3688 // clang-format off
3689 case CC_RISCVVectorCall: return "riscv_vector_cc";
3690#define CC_VLS_CASE(ABI_VLEN) \
3691 case CC_RISCVVLSCall_##ABI_VLEN: return "riscv_vls_cc(" #ABI_VLEN ")";
3692 CC_VLS_CASE(32)
3693 CC_VLS_CASE(64)
3694 CC_VLS_CASE(128)
3695 CC_VLS_CASE(256)
3696 CC_VLS_CASE(512)
3697 CC_VLS_CASE(1024)
3698 CC_VLS_CASE(2048)
3699 CC_VLS_CASE(4096)
3700 CC_VLS_CASE(8192)
3701 CC_VLS_CASE(16384)
3702 CC_VLS_CASE(32768)
3703 CC_VLS_CASE(65536)
3704#undef CC_VLS_CASE
3705 // clang-format on
3706 }
3707
3708 llvm_unreachable("Invalid calling convention.");
3709}
3710
3711void FunctionProtoType::ExceptionSpecInfo::instantiate() {
3712 assert(Type == EST_Uninstantiated);
3713 NoexceptExpr =
3714 cast<FunctionProtoType>(Val: SourceTemplate->getType())->getNoexceptExpr();
3715 Type = EST_DependentNoexcept;
3716}
3717
3718FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> params,
3719 QualType canonical,
3720 const ExtProtoInfo &epi)
3721 : FunctionType(FunctionProto, result, canonical, result->getDependence(),
3722 epi.ExtInfo) {
3723 FunctionTypeBits.FastTypeQuals = epi.TypeQuals.getFastQualifiers();
3724 FunctionTypeBits.RefQualifier = epi.RefQualifier;
3725 FunctionTypeBits.NumParams = params.size();
3726 assert(getNumParams() == params.size() && "NumParams overflow!");
3727 FunctionTypeBits.ExceptionSpecType = epi.ExceptionSpec.Type;
3728 FunctionTypeBits.HasExtParameterInfos = !!epi.ExtParameterInfos;
3729 FunctionTypeBits.Variadic = epi.Variadic;
3730 FunctionTypeBits.HasTrailingReturn = epi.HasTrailingReturn;
3731 FunctionTypeBits.CFIUncheckedCallee = epi.CFIUncheckedCallee;
3732
3733 if (epi.requiresFunctionProtoTypeExtraBitfields()) {
3734 FunctionTypeBits.HasExtraBitfields = true;
3735 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
3736 ExtraBits = FunctionTypeExtraBitfields();
3737 } else {
3738 FunctionTypeBits.HasExtraBitfields = false;
3739 }
3740
3741 // Propagate any extra attribute information.
3742 if (epi.requiresFunctionProtoTypeExtraAttributeInfo()) {
3743 auto &ExtraAttrInfo = *getTrailingObjects<FunctionTypeExtraAttributeInfo>();
3744 ExtraAttrInfo.CFISalt = epi.ExtraAttributeInfo.CFISalt;
3745
3746 // Also set the bit in FunctionTypeExtraBitfields.
3747 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
3748 ExtraBits.HasExtraAttributeInfo = true;
3749 }
3750
3751 if (epi.requiresFunctionProtoTypeArmAttributes()) {
3752 auto &ArmTypeAttrs = *getTrailingObjects<FunctionTypeArmAttributes>();
3753 ArmTypeAttrs = FunctionTypeArmAttributes();
3754
3755 // Also set the bit in FunctionTypeExtraBitfields
3756 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
3757 ExtraBits.HasArmTypeAttributes = true;
3758 }
3759
3760 // Fill in the trailing argument array.
3761 auto *argSlot = getTrailingObjects<QualType>();
3762 for (unsigned i = 0; i != getNumParams(); ++i) {
3763 addDependence(D: params[i]->getDependence() &
3764 ~TypeDependence::VariablyModified);
3765 argSlot[i] = params[i];
3766 }
3767
3768 // Propagate the SME ACLE attributes.
3769 if (epi.AArch64SMEAttributes != SME_NormalFunction) {
3770 auto &ArmTypeAttrs = *getTrailingObjects<FunctionTypeArmAttributes>();
3771 assert(epi.AArch64SMEAttributes <= SME_AttributeMask &&
3772 "Not enough bits to encode SME attributes");
3773 ArmTypeAttrs.AArch64SMEAttributes = epi.AArch64SMEAttributes;
3774 }
3775
3776 // Fill in the exception type array if present.
3777 if (getExceptionSpecType() == EST_Dynamic) {
3778 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
3779 size_t NumExceptions = epi.ExceptionSpec.Exceptions.size();
3780 assert(NumExceptions <= 1023 && "Not enough bits to encode exceptions");
3781 ExtraBits.NumExceptionType = NumExceptions;
3782
3783 assert(hasExtraBitfields() && "missing trailing extra bitfields!");
3784 auto *exnSlot =
3785 reinterpret_cast<QualType *>(getTrailingObjects<ExceptionType>());
3786 unsigned I = 0;
3787 for (QualType ExceptionType : epi.ExceptionSpec.Exceptions) {
3788 // Note that, before C++17, a dependent exception specification does
3789 // *not* make a type dependent; it's not even part of the C++ type
3790 // system.
3791 addDependence(
3792 D: ExceptionType->getDependence() &
3793 (TypeDependence::Instantiation | TypeDependence::UnexpandedPack));
3794
3795 exnSlot[I++] = ExceptionType;
3796 }
3797 }
3798 // Fill in the Expr * in the exception specification if present.
3799 else if (isComputedNoexcept(ESpecType: getExceptionSpecType())) {
3800 assert(epi.ExceptionSpec.NoexceptExpr && "computed noexcept with no expr");
3801 assert((getExceptionSpecType() == EST_DependentNoexcept) ==
3802 epi.ExceptionSpec.NoexceptExpr->isValueDependent());
3803
3804 // Store the noexcept expression and context.
3805 *getTrailingObjects<Expr *>() = epi.ExceptionSpec.NoexceptExpr;
3806
3807 addDependence(
3808 D: toTypeDependence(D: epi.ExceptionSpec.NoexceptExpr->getDependence()) &
3809 (TypeDependence::Instantiation | TypeDependence::UnexpandedPack));
3810 }
3811 // Fill in the FunctionDecl * in the exception specification if present.
3812 else if (getExceptionSpecType() == EST_Uninstantiated) {
3813 // Store the function decl from which we will resolve our
3814 // exception specification.
3815 auto **slot = getTrailingObjects<FunctionDecl *>();
3816 slot[0] = epi.ExceptionSpec.SourceDecl;
3817 slot[1] = epi.ExceptionSpec.SourceTemplate;
3818 // This exception specification doesn't make the type dependent, because
3819 // it's not instantiated as part of instantiating the type.
3820 } else if (getExceptionSpecType() == EST_Unevaluated) {
3821 // Store the function decl from which we will resolve our
3822 // exception specification.
3823 auto **slot = getTrailingObjects<FunctionDecl *>();
3824 slot[0] = epi.ExceptionSpec.SourceDecl;
3825 }
3826
3827 // If this is a canonical type, and its exception specification is dependent,
3828 // then it's a dependent type. This only happens in C++17 onwards.
3829 if (isCanonicalUnqualified()) {
3830 if (getExceptionSpecType() == EST_Dynamic ||
3831 getExceptionSpecType() == EST_DependentNoexcept) {
3832 assert(hasDependentExceptionSpec() && "type should not be canonical");
3833 addDependence(D: TypeDependence::DependentInstantiation);
3834 }
3835 } else if (getCanonicalTypeInternal()->isDependentType()) {
3836 // Ask our canonical type whether our exception specification was dependent.
3837 addDependence(D: TypeDependence::DependentInstantiation);
3838 }
3839
3840 // Fill in the extra parameter info if present.
3841 if (epi.ExtParameterInfos) {
3842 auto *extParamInfos = getTrailingObjects<ExtParameterInfo>();
3843 for (unsigned i = 0; i != getNumParams(); ++i)
3844 extParamInfos[i] = epi.ExtParameterInfos[i];
3845 }
3846
3847 if (epi.TypeQuals.hasNonFastQualifiers()) {
3848 FunctionTypeBits.HasExtQuals = 1;
3849 *getTrailingObjects<Qualifiers>() = epi.TypeQuals;
3850 } else {
3851 FunctionTypeBits.HasExtQuals = 0;
3852 }
3853
3854 // Fill in the Ellipsis location info if present.
3855 if (epi.Variadic) {
3856 auto &EllipsisLoc = *getTrailingObjects<SourceLocation>();
3857 EllipsisLoc = epi.EllipsisLoc;
3858 }
3859
3860 if (!epi.FunctionEffects.empty()) {
3861 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
3862 size_t EffectsCount = epi.FunctionEffects.size();
3863 ExtraBits.NumFunctionEffects = EffectsCount;
3864 assert(ExtraBits.NumFunctionEffects == EffectsCount &&
3865 "effect bitfield overflow");
3866
3867 ArrayRef<FunctionEffect> SrcFX = epi.FunctionEffects.effects();
3868 auto *DestFX = getTrailingObjects<FunctionEffect>();
3869 llvm::uninitialized_copy(Src&: SrcFX, Dst: DestFX);
3870
3871 ArrayRef<EffectConditionExpr> SrcConds = epi.FunctionEffects.conditions();
3872 if (!SrcConds.empty()) {
3873 ExtraBits.EffectsHaveConditions = true;
3874 auto *DestConds = getTrailingObjects<EffectConditionExpr>();
3875 llvm::uninitialized_copy(Src&: SrcConds, Dst: DestConds);
3876 assert(llvm::any_of(SrcConds,
3877 [](const EffectConditionExpr &EC) {
3878 if (const Expr *E = EC.getCondition())
3879 return E->isTypeDependent() ||
3880 E->isValueDependent();
3881 return false;
3882 }) &&
3883 "expected a dependent expression among the conditions");
3884 addDependence(D: TypeDependence::DependentInstantiation);
3885 }
3886 }
3887}
3888
3889bool FunctionProtoType::hasDependentExceptionSpec() const {
3890 if (Expr *NE = getNoexceptExpr())
3891 return NE->isValueDependent();
3892 for (QualType ET : exceptions())
3893 // A pack expansion with a non-dependent pattern is still dependent,
3894 // because we don't know whether the pattern is in the exception spec
3895 // or not (that depends on whether the pack has 0 expansions).
3896 if (ET->isDependentType() || ET->getAs<PackExpansionType>())
3897 return true;
3898 return false;
3899}
3900
3901bool FunctionProtoType::hasInstantiationDependentExceptionSpec() const {
3902 if (Expr *NE = getNoexceptExpr())
3903 return NE->isInstantiationDependent();
3904 for (QualType ET : exceptions())
3905 if (ET->isInstantiationDependentType())
3906 return true;
3907 return false;
3908}
3909
3910CanThrowResult FunctionProtoType::canThrow() const {
3911 switch (getExceptionSpecType()) {
3912 case EST_Unparsed:
3913 case EST_Unevaluated:
3914 llvm_unreachable("should not call this with unresolved exception specs");
3915
3916 case EST_DynamicNone:
3917 case EST_BasicNoexcept:
3918 case EST_NoexceptTrue:
3919 case EST_NoThrow:
3920 return CT_Cannot;
3921
3922 case EST_None:
3923 case EST_MSAny:
3924 case EST_NoexceptFalse:
3925 return CT_Can;
3926
3927 case EST_Dynamic:
3928 // A dynamic exception specification is throwing unless every exception
3929 // type is an (unexpanded) pack expansion type.
3930 for (unsigned I = 0; I != getNumExceptions(); ++I)
3931 if (!getExceptionType(i: I)->getAs<PackExpansionType>())
3932 return CT_Can;
3933 return CT_Dependent;
3934
3935 case EST_Uninstantiated:
3936 case EST_DependentNoexcept:
3937 return CT_Dependent;
3938 }
3939
3940 llvm_unreachable("unexpected exception specification kind");
3941}
3942
3943bool FunctionProtoType::isTemplateVariadic() const {
3944 for (unsigned ArgIdx = getNumParams(); ArgIdx; --ArgIdx)
3945 if (isa<PackExpansionType>(Val: getParamType(i: ArgIdx - 1)))
3946 return true;
3947
3948 return false;
3949}
3950
3951void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
3952 const QualType *ArgTys, unsigned NumParams,
3953 const ExtProtoInfo &epi,
3954 const ASTContext &Context, bool Canonical) {
3955 // We have to be careful not to get ambiguous profile encodings.
3956 // Note that valid type pointers are never ambiguous with anything else.
3957 //
3958 // The encoding grammar begins:
3959 // type type* bool int bool
3960 // If that final bool is true, then there is a section for the EH spec:
3961 // bool type*
3962 // This is followed by an optional "consumed argument" section of the
3963 // same length as the first type sequence:
3964 // bool*
3965 // This is followed by the ext info:
3966 // int
3967 // Finally we have a trailing return type flag (bool)
3968 // combined with AArch64 SME Attributes and extra attribute info, to save
3969 // space:
3970 // int
3971 // combined with any FunctionEffects
3972 //
3973 // There is no ambiguity between the consumed arguments and an empty EH
3974 // spec because of the leading 'bool' which unambiguously indicates
3975 // whether the following bool is the EH spec or part of the arguments.
3976
3977 ID.AddPointer(Ptr: Result.getAsOpaquePtr());
3978 for (unsigned i = 0; i != NumParams; ++i)
3979 ID.AddPointer(Ptr: ArgTys[i].getAsOpaquePtr());
3980 // This method is relatively performance sensitive, so as a performance
3981 // shortcut, use one AddInteger call instead of four for the next four
3982 // fields.
3983 assert(!(unsigned(epi.Variadic) & ~1) && !(unsigned(epi.RefQualifier) & ~3) &&
3984 !(unsigned(epi.ExceptionSpec.Type) & ~15) &&
3985 "Values larger than expected.");
3986 ID.AddInteger(I: unsigned(epi.Variadic) + (epi.RefQualifier << 1) +
3987 (epi.ExceptionSpec.Type << 3));
3988 ID.Add(x: epi.TypeQuals);
3989 if (epi.ExceptionSpec.Type == EST_Dynamic) {
3990 for (QualType Ex : epi.ExceptionSpec.Exceptions)
3991 ID.AddPointer(Ptr: Ex.getAsOpaquePtr());
3992 } else if (isComputedNoexcept(ESpecType: epi.ExceptionSpec.Type)) {
3993 epi.ExceptionSpec.NoexceptExpr->Profile(ID, Context, Canonical);
3994 } else if (epi.ExceptionSpec.Type == EST_Uninstantiated ||
3995 epi.ExceptionSpec.Type == EST_Unevaluated) {
3996 ID.AddPointer(Ptr: epi.ExceptionSpec.SourceDecl->getCanonicalDecl());
3997 }
3998 if (epi.ExtParameterInfos) {
3999 for (unsigned i = 0; i != NumParams; ++i)
4000 ID.AddInteger(I: epi.ExtParameterInfos[i].getOpaqueValue());
4001 }
4002
4003 epi.ExtInfo.Profile(ID);
4004 epi.ExtraAttributeInfo.Profile(ID);
4005
4006 unsigned EffectCount = epi.FunctionEffects.size();
4007 bool HasConds = !epi.FunctionEffects.Conditions.empty();
4008
4009 ID.AddInteger(I: (EffectCount << 3) | (HasConds << 2) |
4010 (epi.AArch64SMEAttributes << 1) | epi.HasTrailingReturn);
4011 ID.AddInteger(I: epi.CFIUncheckedCallee);
4012
4013 for (unsigned Idx = 0; Idx != EffectCount; ++Idx) {
4014 ID.AddInteger(I: epi.FunctionEffects.Effects[Idx].toOpaqueInt32());
4015 if (HasConds)
4016 ID.AddPointer(Ptr: epi.FunctionEffects.Conditions[Idx].getCondition());
4017 }
4018}
4019
4020void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
4021 const ASTContext &Ctx) {
4022 Profile(ID, Result: getReturnType(), ArgTys: param_type_begin(), NumParams: getNumParams(),
4023 epi: getExtProtoInfo(), Context: Ctx, Canonical: isCanonicalUnqualified());
4024}
4025
4026TypeCoupledDeclRefInfo::TypeCoupledDeclRefInfo(ValueDecl *D, bool Deref)
4027 : Data(D, Deref << DerefShift) {}
4028
4029bool TypeCoupledDeclRefInfo::isDeref() const {
4030 return Data.getInt() & DerefMask;
4031}
4032ValueDecl *TypeCoupledDeclRefInfo::getDecl() const { return Data.getPointer(); }
4033unsigned TypeCoupledDeclRefInfo::getInt() const { return Data.getInt(); }
4034void *TypeCoupledDeclRefInfo::getOpaqueValue() const {
4035 return Data.getOpaqueValue();
4036}
4037bool TypeCoupledDeclRefInfo::operator==(
4038 const TypeCoupledDeclRefInfo &Other) const {
4039 return getOpaqueValue() == Other.getOpaqueValue();
4040}
4041void TypeCoupledDeclRefInfo::setFromOpaqueValue(void *V) {
4042 Data.setFromOpaqueValue(V);
4043}
4044
4045OverflowBehaviorType::OverflowBehaviorType(
4046 QualType Canon, QualType Underlying,
4047 OverflowBehaviorType::OverflowBehaviorKind Kind)
4048 : Type(OverflowBehavior, Canon, Underlying->getDependence()),
4049 UnderlyingType(Underlying), BehaviorKind(Kind) {}
4050
4051BoundsAttributedType::BoundsAttributedType(TypeClass TC, QualType Wrapped,
4052 QualType Canon)
4053 : Type(TC, Canon, Wrapped->getDependence()), WrappedTy(Wrapped) {}
4054
4055CountAttributedType::CountAttributedType(
4056 QualType Wrapped, QualType Canon, Expr *CountExpr, bool CountInBytes,
4057 bool OrNull, ArrayRef<TypeCoupledDeclRefInfo> CoupledDecls)
4058 : BoundsAttributedType(CountAttributed, Wrapped, Canon),
4059 CountExpr(CountExpr) {
4060 CountAttributedTypeBits.NumCoupledDecls = CoupledDecls.size();
4061 CountAttributedTypeBits.CountInBytes = CountInBytes;
4062 CountAttributedTypeBits.OrNull = OrNull;
4063 auto *DeclSlot = getTrailingObjects();
4064 llvm::copy(Range&: CoupledDecls, Out: DeclSlot);
4065 Decls = llvm::ArrayRef(DeclSlot, CoupledDecls.size());
4066}
4067
4068StringRef CountAttributedType::getAttributeName(bool WithMacroPrefix) const {
4069// TODO: This method isn't really ideal because it doesn't return the spelling
4070// of the attribute that was used in the user's code. This method is used for
4071// diagnostics so the fact it doesn't use the spelling of the attribute in
4072// the user's code could be confusing (#113585).
4073#define ENUMERATE_ATTRS(PREFIX) \
4074 do { \
4075 if (isCountInBytes()) { \
4076 if (isOrNull()) \
4077 return PREFIX "sized_by_or_null"; \
4078 return PREFIX "sized_by"; \
4079 } \
4080 if (isOrNull()) \
4081 return PREFIX "counted_by_or_null"; \
4082 return PREFIX "counted_by"; \
4083 } while (0)
4084
4085 if (WithMacroPrefix)
4086 ENUMERATE_ATTRS("__");
4087 else
4088 ENUMERATE_ATTRS("");
4089
4090#undef ENUMERATE_ATTRS
4091}
4092
4093TypedefType::TypedefType(TypeClass TC, ElaboratedTypeKeyword Keyword,
4094 NestedNameSpecifier Qualifier,
4095 const TypedefNameDecl *D, QualType UnderlyingType,
4096 bool HasTypeDifferentFromDecl)
4097 : TypeWithKeyword(
4098 Keyword, TC, UnderlyingType.getCanonicalType(),
4099 toSemanticDependence(D: UnderlyingType->getDependence()) |
4100 (Qualifier
4101 ? toTypeDependence(D: Qualifier.getDependence() &
4102 ~NestedNameSpecifierDependence::Dependent)
4103 : TypeDependence{})),
4104 Decl(const_cast<TypedefNameDecl *>(D)) {
4105 if ((TypedefBits.hasQualifier = !!Qualifier))
4106 *getTrailingObjects<NestedNameSpecifier>() = Qualifier;
4107 if ((TypedefBits.hasTypeDifferentFromDecl = HasTypeDifferentFromDecl))
4108 *getTrailingObjects<QualType>() = UnderlyingType;
4109}
4110
4111QualType TypedefType::desugar() const {
4112 return typeMatchesDecl() ? Decl->getUnderlyingType()
4113 : *getTrailingObjects<QualType>();
4114}
4115
4116UnresolvedUsingType::UnresolvedUsingType(ElaboratedTypeKeyword Keyword,
4117 NestedNameSpecifier Qualifier,
4118 const UnresolvedUsingTypenameDecl *D,
4119 const Type *CanonicalType)
4120 : TypeWithKeyword(
4121 Keyword, UnresolvedUsing, QualType(CanonicalType, 0),
4122 TypeDependence::DependentInstantiation |
4123 (Qualifier
4124 ? toTypeDependence(D: Qualifier.getDependence() &
4125 ~NestedNameSpecifierDependence::Dependent)
4126 : TypeDependence{})),
4127 Decl(const_cast<UnresolvedUsingTypenameDecl *>(D)) {
4128 if ((UnresolvedUsingBits.hasQualifier = !!Qualifier))
4129 *getTrailingObjects<NestedNameSpecifier>() = Qualifier;
4130}
4131
4132UsingType::UsingType(ElaboratedTypeKeyword Keyword,
4133 NestedNameSpecifier Qualifier, const UsingShadowDecl *D,
4134 QualType UnderlyingType)
4135 : TypeWithKeyword(Keyword, Using, UnderlyingType.getCanonicalType(),
4136 toSemanticDependence(D: UnderlyingType->getDependence())),
4137 D(const_cast<UsingShadowDecl *>(D)), UnderlyingType(UnderlyingType) {
4138 if ((UsingBits.hasQualifier = !!Qualifier))
4139 *getTrailingObjects() = Qualifier;
4140}
4141
4142QualType MacroQualifiedType::desugar() const { return getUnderlyingType(); }
4143
4144QualType MacroQualifiedType::getModifiedType() const {
4145 // Step over MacroQualifiedTypes from the same macro to find the type
4146 // ultimately qualified by the macro qualifier.
4147 QualType Inner = cast<AttributedType>(Val: getUnderlyingType())->getModifiedType();
4148 while (auto *InnerMQT = dyn_cast<MacroQualifiedType>(Val&: Inner)) {
4149 if (InnerMQT->getMacroIdentifier() != getMacroIdentifier())
4150 break;
4151 Inner = InnerMQT->getModifiedType();
4152 }
4153 return Inner;
4154}
4155
4156TypeOfExprType::TypeOfExprType(const ASTContext &Context, Expr *E,
4157 TypeOfKind Kind, QualType Can)
4158 : Type(TypeOfExpr,
4159 // We have to protect against 'Can' being invalid through its
4160 // default argument.
4161 Kind == TypeOfKind::Unqualified && !Can.isNull()
4162 ? Context.getUnqualifiedArrayType(T: Can).getAtomicUnqualifiedType()
4163 : Can,
4164 toTypeDependence(D: E->getDependence()) |
4165 (E->getType()->getDependence() &
4166 TypeDependence::VariablyModified)),
4167 TOExpr(E), Context(Context) {
4168 TypeOfBits.Kind = static_cast<unsigned>(Kind);
4169}
4170
4171bool TypeOfExprType::isSugared() const { return !TOExpr->isTypeDependent(); }
4172
4173QualType TypeOfExprType::desugar() const {
4174 if (isSugared()) {
4175 QualType QT = getUnderlyingExpr()->getType();
4176 return getKind() == TypeOfKind::Unqualified
4177 ? Context.getUnqualifiedArrayType(T: QT).getAtomicUnqualifiedType()
4178 : QT;
4179 }
4180 return QualType(this, 0);
4181}
4182
4183void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
4184 const ASTContext &Context, Expr *E,
4185 bool IsUnqual) {
4186 E->Profile(ID, Context, Canonical: true);
4187 ID.AddBoolean(B: IsUnqual);
4188}
4189
4190TypeOfType::TypeOfType(const ASTContext &Context, QualType T, QualType Can,
4191 TypeOfKind Kind)
4192 : Type(TypeOf,
4193 Kind == TypeOfKind::Unqualified
4194 ? Context.getUnqualifiedArrayType(T: Can).getAtomicUnqualifiedType()
4195 : Can,
4196 T->getDependence()),
4197 TOType(T), Context(Context) {
4198 TypeOfBits.Kind = static_cast<unsigned>(Kind);
4199}
4200
4201QualType TypeOfType::desugar() const {
4202 QualType QT = getUnmodifiedType();
4203 return getKind() == TypeOfKind::Unqualified
4204 ? Context.getUnqualifiedArrayType(T: QT).getAtomicUnqualifiedType()
4205 : QT;
4206}
4207
4208DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
4209 // C++11 [temp.type]p2: "If an expression e involves a template parameter,
4210 // decltype(e) denotes a unique dependent type." Hence a decltype type is
4211 // type-dependent even if its expression is only instantiation-dependent.
4212 : Type(Decltype, can,
4213 toTypeDependence(D: E->getDependence()) |
4214 (E->isInstantiationDependent() ? TypeDependence::Dependent
4215 : TypeDependence::None) |
4216 (E->getType()->getDependence() &
4217 TypeDependence::VariablyModified)),
4218 E(E), UnderlyingType(underlyingType) {}
4219
4220bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); }
4221
4222QualType DecltypeType::desugar() const {
4223 if (isSugared())
4224 return getUnderlyingType();
4225
4226 return QualType(this, 0);
4227}
4228
4229DependentDecltypeType::DependentDecltypeType(Expr *E)
4230 : DecltypeType(E, QualType()) {}
4231
4232void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
4233 const ASTContext &Context, Expr *E) {
4234 E->Profile(ID, Context, Canonical: true);
4235}
4236
4237PackIndexingType::PackIndexingType(QualType Canonical, QualType Pattern,
4238 Expr *IndexExpr, bool FullySubstituted,
4239 ArrayRef<QualType> Expansions)
4240 : Type(PackIndexing, Canonical,
4241 computeDependence(Pattern, IndexExpr, Expansions)),
4242 Pattern(Pattern), IndexExpr(IndexExpr), Size(Expansions.size()),
4243 FullySubstituted(FullySubstituted) {
4244
4245 llvm::uninitialized_copy(Src&: Expansions, Dst: getTrailingObjects());
4246}
4247
4248UnsignedOrNone PackIndexingType::getSelectedIndex() const {
4249 if (isInstantiationDependentType())
4250 return std::nullopt;
4251 // Should only be not a constant for error recovery.
4252 ConstantExpr *CE = dyn_cast<ConstantExpr>(Val: getIndexExpr());
4253 if (!CE)
4254 return std::nullopt;
4255 auto Index = CE->getResultAsAPSInt();
4256 assert(Index.isNonNegative() && "Invalid index");
4257 return static_cast<unsigned>(Index.getExtValue());
4258}
4259
4260TypeDependence
4261PackIndexingType::computeDependence(QualType Pattern, Expr *IndexExpr,
4262 ArrayRef<QualType> Expansions) {
4263 TypeDependence IndexD = toTypeDependence(D: IndexExpr->getDependence());
4264
4265 TypeDependence TD = IndexD | (IndexExpr->isInstantiationDependent()
4266 ? TypeDependence::DependentInstantiation
4267 : TypeDependence::None);
4268 if (Expansions.empty())
4269 TD |= Pattern->getDependence() & TypeDependence::DependentInstantiation;
4270 else
4271 for (const QualType &T : Expansions)
4272 TD |= T->getDependence();
4273
4274 if (!(IndexD & TypeDependence::UnexpandedPack))
4275 TD &= ~TypeDependence::UnexpandedPack;
4276
4277 // If the pattern does not contain an unexpended pack,
4278 // the type is still dependent, and invalid
4279 if (!Pattern->containsUnexpandedParameterPack())
4280 TD |= TypeDependence::Error | TypeDependence::DependentInstantiation;
4281
4282 return TD;
4283}
4284
4285void PackIndexingType::Profile(llvm::FoldingSetNodeID &ID,
4286 const ASTContext &Context) {
4287 Profile(ID, Context, Pattern: getPattern(), E: getIndexExpr(), FullySubstituted: isFullySubstituted(),
4288 Expansions: getExpansions());
4289}
4290
4291void PackIndexingType::Profile(llvm::FoldingSetNodeID &ID,
4292 const ASTContext &Context, QualType Pattern,
4293 Expr *E, bool FullySubstituted,
4294 ArrayRef<QualType> Expansions) {
4295
4296 E->Profile(ID, Context, Canonical: true);
4297 ID.AddBoolean(B: FullySubstituted);
4298 if (!Expansions.empty()) {
4299 ID.AddInteger(I: Expansions.size());
4300 for (QualType T : Expansions)
4301 T.getCanonicalType().Profile(ID);
4302 } else {
4303 Pattern.Profile(ID);
4304 }
4305}
4306
4307UnaryTransformType::UnaryTransformType(QualType BaseType,
4308 QualType UnderlyingType, UTTKind UKind,
4309 QualType CanonicalType)
4310 : Type(UnaryTransform, CanonicalType, BaseType->getDependence()),
4311 BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind) {}
4312
4313TagType::TagType(TypeClass TC, ElaboratedTypeKeyword Keyword,
4314 NestedNameSpecifier Qualifier, const TagDecl *Tag,
4315 bool OwnsTag, bool ISInjected, const Type *CanonicalType)
4316 : TypeWithKeyword(
4317 Keyword, TC, QualType(CanonicalType, 0),
4318 (Tag->isDependentType() ? TypeDependence::DependentInstantiation
4319 : TypeDependence::None) |
4320 (Qualifier
4321 ? toTypeDependence(D: Qualifier.getDependence() &
4322 ~NestedNameSpecifierDependence::Dependent)
4323 : TypeDependence{})),
4324 decl(const_cast<TagDecl *>(Tag)) {
4325 if ((TagTypeBits.HasQualifier = !!Qualifier))
4326 getTrailingQualifier() = Qualifier;
4327 TagTypeBits.OwnsTag = !!OwnsTag;
4328 TagTypeBits.IsInjected = ISInjected;
4329}
4330
4331void *TagType::getTrailingPointer() const {
4332 switch (getTypeClass()) {
4333 case Type::Enum:
4334 return const_cast<EnumType *>(cast<EnumType>(Val: this) + 1);
4335 case Type::Record:
4336 return const_cast<RecordType *>(cast<RecordType>(Val: this) + 1);
4337 case Type::InjectedClassName:
4338 return const_cast<InjectedClassNameType *>(
4339 cast<InjectedClassNameType>(Val: this) + 1);
4340 default:
4341 llvm_unreachable("unexpected type class");
4342 }
4343}
4344
4345NestedNameSpecifier &TagType::getTrailingQualifier() const {
4346 assert(TagTypeBits.HasQualifier);
4347 return *reinterpret_cast<NestedNameSpecifier *>(llvm::alignAddr(
4348 Addr: getTrailingPointer(), Alignment: llvm::Align::Of<NestedNameSpecifier *>()));
4349}
4350
4351NestedNameSpecifier TagType::getQualifier() const {
4352 return TagTypeBits.HasQualifier ? getTrailingQualifier() : std::nullopt;
4353}
4354
4355ClassTemplateDecl *TagType::getTemplateDecl() const {
4356 auto *Decl = dyn_cast<CXXRecordDecl>(Val: decl);
4357 if (!Decl)
4358 return nullptr;
4359 if (auto *RD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Decl))
4360 return RD->getSpecializedTemplate();
4361 return Decl->getDescribedClassTemplate();
4362}
4363
4364TemplateName TagType::getTemplateName(const ASTContext &Ctx) const {
4365 auto *TD = getTemplateDecl();
4366 if (!TD)
4367 return TemplateName();
4368 if (isCanonicalUnqualified())
4369 return TemplateName(TD);
4370 return Ctx.getQualifiedTemplateName(Qualifier: getQualifier(), /*TemplateKeyword=*/false,
4371 Template: TemplateName(TD));
4372}
4373
4374ArrayRef<TemplateArgument>
4375TagType::getTemplateArgs(const ASTContext &Ctx) const {
4376 auto *Decl = dyn_cast<CXXRecordDecl>(Val: decl);
4377 if (!Decl)
4378 return {};
4379
4380 if (auto *RD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Decl))
4381 return RD->getTemplateArgs().asArray();
4382 if (ClassTemplateDecl *TD = Decl->getDescribedClassTemplate())
4383 return TD->getTemplateParameters()->getInjectedTemplateArgs(Context: Ctx);
4384 return {};
4385}
4386
4387bool RecordType::hasConstFields() const {
4388 std::vector<const RecordType *> RecordTypeList;
4389 RecordTypeList.push_back(x: this);
4390 unsigned NextToCheckIndex = 0;
4391
4392 while (RecordTypeList.size() > NextToCheckIndex) {
4393 for (FieldDecl *FD : RecordTypeList[NextToCheckIndex]
4394 ->getDecl()
4395 ->getDefinitionOrSelf()
4396 ->fields()) {
4397 QualType FieldTy = FD->getType();
4398 if (FieldTy.isConstQualified())
4399 return true;
4400 FieldTy = FieldTy.getCanonicalType();
4401 if (const auto *FieldRecTy = FieldTy->getAsCanonical<RecordType>()) {
4402 if (!llvm::is_contained(Range&: RecordTypeList, Element: FieldRecTy))
4403 RecordTypeList.push_back(x: FieldRecTy);
4404 }
4405 }
4406 ++NextToCheckIndex;
4407 }
4408 return false;
4409}
4410
4411InjectedClassNameType::InjectedClassNameType(ElaboratedTypeKeyword Keyword,
4412 NestedNameSpecifier Qualifier,
4413 const TagDecl *TD, bool IsInjected,
4414 const Type *CanonicalType)
4415 : TagType(TypeClass::InjectedClassName, Keyword, Qualifier, TD,
4416 /*OwnsTag=*/false, IsInjected, CanonicalType) {}
4417
4418AttributedType::AttributedType(QualType canon, const Attr *attr,
4419 QualType modified, QualType equivalent)
4420 : AttributedType(canon, attr->getKind(), attr, modified, equivalent) {}
4421
4422AttributedType::AttributedType(QualType canon, attr::Kind attrKind,
4423 const Attr *attr, QualType modified,
4424 QualType equivalent)
4425 : Type(Attributed, canon, equivalent->getDependence()), Attribute(attr),
4426 ModifiedType(modified), EquivalentType(equivalent) {
4427 AttributedTypeBits.AttrKind = attrKind;
4428 assert(!attr || attr->getKind() == attrKind);
4429}
4430
4431bool AttributedType::isQualifier() const {
4432 // FIXME: Generate this with TableGen.
4433 switch (getAttrKind()) {
4434 // These are type qualifiers in the traditional C sense: they annotate
4435 // something about a specific value/variable of a type. (They aren't
4436 // always part of the canonical type, though.)
4437 case attr::ObjCGC:
4438 case attr::ObjCOwnership:
4439 case attr::ObjCInertUnsafeUnretained:
4440 case attr::TypeNonNull:
4441 case attr::TypeNullable:
4442 case attr::TypeNullableResult:
4443 case attr::TypeNullUnspecified:
4444 case attr::LifetimeBound:
4445 case attr::AddressSpace:
4446 return true;
4447
4448 // All other type attributes aren't qualifiers; they rewrite the modified
4449 // type to be a semantically different type.
4450 default:
4451 return false;
4452 }
4453}
4454
4455bool AttributedType::isMSTypeSpec() const {
4456 // FIXME: Generate this with TableGen?
4457 switch (getAttrKind()) {
4458 default:
4459 return false;
4460 case attr::Ptr32:
4461 case attr::Ptr64:
4462 case attr::SPtr:
4463 case attr::UPtr:
4464 return true;
4465 }
4466 llvm_unreachable("invalid attr kind");
4467}
4468
4469bool AttributedType::isWebAssemblyFuncrefSpec() const {
4470 return getAttrKind() == attr::WebAssemblyFuncref;
4471}
4472
4473bool AttributedType::isCallingConv() const {
4474 // FIXME: Generate this with TableGen.
4475 switch (getAttrKind()) {
4476 default:
4477 return false;
4478 case attr::Pcs:
4479 case attr::CDecl:
4480 case attr::FastCall:
4481 case attr::StdCall:
4482 case attr::ThisCall:
4483 case attr::RegCall:
4484 case attr::SwiftCall:
4485 case attr::SwiftAsyncCall:
4486 case attr::VectorCall:
4487 case attr::AArch64VectorPcs:
4488 case attr::AArch64SVEPcs:
4489 case attr::DeviceKernel:
4490 case attr::Pascal:
4491 case attr::MSABI:
4492 case attr::SysVABI:
4493 case attr::IntelOclBicc:
4494 case attr::PreserveMost:
4495 case attr::PreserveAll:
4496 case attr::M68kRTD:
4497 case attr::PreserveNone:
4498 case attr::RISCVVectorCC:
4499 case attr::RISCVVLSCC:
4500 return true;
4501 }
4502 llvm_unreachable("invalid attr kind");
4503}
4504
4505IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
4506 return isCanonicalUnqualified() ? nullptr : getDecl()->getIdentifier();
4507}
4508
4509SubstTemplateTypeParmType::SubstTemplateTypeParmType(QualType Replacement,
4510 Decl *AssociatedDecl,
4511 unsigned Index,
4512 UnsignedOrNone PackIndex,
4513 bool Final)
4514 : Type(SubstTemplateTypeParm, Replacement.getCanonicalType(),
4515 Replacement->getDependence()),
4516 AssociatedDecl(AssociatedDecl) {
4517 SubstTemplateTypeParmTypeBits.HasNonCanonicalUnderlyingType =
4518 Replacement != getCanonicalTypeInternal();
4519 if (SubstTemplateTypeParmTypeBits.HasNonCanonicalUnderlyingType)
4520 *getTrailingObjects() = Replacement;
4521
4522 SubstTemplateTypeParmTypeBits.Index = Index;
4523 SubstTemplateTypeParmTypeBits.Final = Final;
4524 SubstTemplateTypeParmTypeBits.PackIndex =
4525 PackIndex.toInternalRepresentation();
4526 assert(AssociatedDecl != nullptr);
4527}
4528
4529const TemplateTypeParmDecl *
4530SubstTemplateTypeParmType::getReplacedParameter() const {
4531 return cast<TemplateTypeParmDecl>(Val: std::get<0>(
4532 t: getReplacedTemplateParameter(D: getAssociatedDecl(), Index: getIndex())));
4533}
4534
4535void SubstTemplateTypeParmType::Profile(llvm::FoldingSetNodeID &ID,
4536 QualType Replacement,
4537 const Decl *AssociatedDecl,
4538 unsigned Index,
4539 UnsignedOrNone PackIndex, bool Final) {
4540 Replacement.Profile(ID);
4541 ID.AddPointer(Ptr: AssociatedDecl);
4542 ID.AddInteger(I: Index);
4543 ID.AddInteger(I: PackIndex.toInternalRepresentation());
4544 ID.AddBoolean(B: Final);
4545}
4546
4547SubstPackType::SubstPackType(TypeClass Derived, QualType Canon,
4548 const TemplateArgument &ArgPack)
4549 : Type(Derived, Canon,
4550 TypeDependence::DependentInstantiation |
4551 TypeDependence::UnexpandedPack),
4552 Arguments(ArgPack.pack_begin()) {
4553 assert(llvm::all_of(
4554 ArgPack.pack_elements(),
4555 [](auto &P) { return P.getKind() == TemplateArgument::Type; }) &&
4556 "non-type argument to SubstPackType?");
4557 SubstPackTypeBits.NumArgs = ArgPack.pack_size();
4558}
4559
4560TemplateArgument SubstPackType::getArgumentPack() const {
4561 return TemplateArgument(llvm::ArrayRef(Arguments, getNumArgs()));
4562}
4563
4564void SubstPackType::Profile(llvm::FoldingSetNodeID &ID) {
4565 Profile(ID, ArgPack: getArgumentPack());
4566}
4567
4568void SubstPackType::Profile(llvm::FoldingSetNodeID &ID,
4569 const TemplateArgument &ArgPack) {
4570 ID.AddInteger(I: ArgPack.pack_size());
4571 for (const auto &P : ArgPack.pack_elements())
4572 ID.AddPointer(Ptr: P.getAsType().getAsOpaquePtr());
4573}
4574
4575SubstTemplateTypeParmPackType::SubstTemplateTypeParmPackType(
4576 QualType Canon, Decl *AssociatedDecl, unsigned Index, bool Final,
4577 const TemplateArgument &ArgPack)
4578 : SubstPackType(SubstTemplateTypeParmPack, Canon, ArgPack),
4579 AssociatedDeclAndFinal(AssociatedDecl, Final) {
4580 assert(AssociatedDecl != nullptr);
4581
4582 SubstPackTypeBits.SubstTemplTypeParmPackIndex = Index;
4583 assert(getNumArgs() == ArgPack.pack_size() &&
4584 "Parent bitfields in SubstPackType were overwritten."
4585 "Check NumSubstPackTypeBits.");
4586}
4587
4588Decl *SubstTemplateTypeParmPackType::getAssociatedDecl() const {
4589 return AssociatedDeclAndFinal.getPointer();
4590}
4591
4592bool SubstTemplateTypeParmPackType::getFinal() const {
4593 return AssociatedDeclAndFinal.getInt();
4594}
4595
4596const TemplateTypeParmDecl *
4597SubstTemplateTypeParmPackType::getReplacedParameter() const {
4598 return cast<TemplateTypeParmDecl>(Val: std::get<0>(
4599 t: getReplacedTemplateParameter(D: getAssociatedDecl(), Index: getIndex())));
4600}
4601
4602IdentifierInfo *SubstTemplateTypeParmPackType::getIdentifier() const {
4603 return getReplacedParameter()->getIdentifier();
4604}
4605
4606void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
4607 Profile(ID, AssociatedDecl: getAssociatedDecl(), Index: getIndex(), Final: getFinal(), ArgPack: getArgumentPack());
4608}
4609
4610void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
4611 const Decl *AssociatedDecl,
4612 unsigned Index, bool Final,
4613 const TemplateArgument &ArgPack) {
4614 ID.AddPointer(Ptr: AssociatedDecl);
4615 ID.AddInteger(I: Index);
4616 ID.AddBoolean(B: Final);
4617 SubstPackType::Profile(ID, ArgPack);
4618}
4619
4620SubstBuiltinTemplatePackType::SubstBuiltinTemplatePackType(
4621 QualType Canon, const TemplateArgument &ArgPack)
4622 : SubstPackType(SubstBuiltinTemplatePack, Canon, ArgPack) {}
4623
4624bool TemplateSpecializationType::anyDependentTemplateArguments(
4625 const TemplateArgumentListInfo &Args,
4626 ArrayRef<TemplateArgument> Converted) {
4627 return anyDependentTemplateArguments(Args: Args.arguments(), Converted);
4628}
4629
4630bool TemplateSpecializationType::anyDependentTemplateArguments(
4631 ArrayRef<TemplateArgumentLoc> Args, ArrayRef<TemplateArgument> Converted) {
4632 for (const TemplateArgument &Arg : Converted)
4633 if (Arg.isDependent())
4634 return true;
4635 return false;
4636}
4637
4638bool TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
4639 ArrayRef<TemplateArgumentLoc> Args) {
4640 for (const TemplateArgumentLoc &ArgLoc : Args) {
4641 if (ArgLoc.getArgument().isInstantiationDependent())
4642 return true;
4643 }
4644 return false;
4645}
4646
4647static TypeDependence
4648getTemplateSpecializationTypeDependence(QualType Underlying, TemplateName T) {
4649 TypeDependence D = Underlying.isNull()
4650 ? TypeDependence::DependentInstantiation
4651 : toSemanticDependence(D: Underlying->getDependence());
4652 D |= toTypeDependence(D: T.getDependence()) & TypeDependence::UnexpandedPack;
4653 if (isPackProducingBuiltinTemplateName(N: T)) {
4654 if (Underlying.isNull()) // Dependent, will produce a pack on substitution.
4655 D |= TypeDependence::UnexpandedPack;
4656 else
4657 D |= (Underlying->getDependence() & TypeDependence::UnexpandedPack);
4658 }
4659 return D;
4660}
4661
4662TemplateSpecializationType::TemplateSpecializationType(
4663 ElaboratedTypeKeyword Keyword, TemplateName T, bool IsAlias,
4664 ArrayRef<TemplateArgument> Args, QualType Underlying)
4665 : TypeWithKeyword(Keyword, TemplateSpecialization,
4666 Underlying.isNull() ? QualType(this, 0)
4667 : Underlying.getCanonicalType(),
4668 getTemplateSpecializationTypeDependence(Underlying, T)),
4669 Template(T) {
4670 TemplateSpecializationTypeBits.NumArgs = Args.size();
4671 TemplateSpecializationTypeBits.TypeAlias = IsAlias;
4672
4673 auto *TemplateArgs =
4674 const_cast<TemplateArgument *>(template_arguments().data());
4675 for (const TemplateArgument &Arg : Args) {
4676 // Update instantiation-dependent, variably-modified, and error bits.
4677 // If the canonical type exists and is non-dependent, the template
4678 // specialization type can be non-dependent even if one of the type
4679 // arguments is. Given:
4680 // template<typename T> using U = int;
4681 // U<T> is always non-dependent, irrespective of the type T.
4682 // However, U<Ts> contains an unexpanded parameter pack, even though
4683 // its expansion (and thus its desugared type) doesn't.
4684 addDependence(D: toTypeDependence(D: Arg.getDependence()) &
4685 ~TypeDependence::Dependent);
4686 if (Arg.getKind() == TemplateArgument::Type)
4687 addDependence(D: Arg.getAsType()->getDependence() &
4688 TypeDependence::VariablyModified);
4689 new (TemplateArgs++) TemplateArgument(Arg);
4690 }
4691
4692 // Store the aliased type after the template arguments, if this is a type
4693 // alias template specialization.
4694 if (IsAlias)
4695 *reinterpret_cast<QualType *>(TemplateArgs) = Underlying;
4696}
4697
4698QualType TemplateSpecializationType::getAliasedType() const {
4699 assert(isTypeAlias() && "not a type alias template specialization");
4700 return *reinterpret_cast<const QualType *>(template_arguments().end());
4701}
4702
4703bool clang::TemplateSpecializationType::isSugared() const {
4704 return !isDependentType() || isCurrentInstantiation() || isTypeAlias() ||
4705 (isPackProducingBuiltinTemplateName(N: Template) &&
4706 isa<SubstBuiltinTemplatePackType>(Val: *getCanonicalTypeInternal()));
4707}
4708
4709void TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
4710 const ASTContext &Ctx) {
4711 Profile(ID, Keyword: getKeyword(), T: Template, Args: template_arguments(),
4712 Underlying: isSugared() ? desugar() : QualType(), Context: Ctx);
4713}
4714
4715void TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
4716 ElaboratedTypeKeyword Keyword,
4717 TemplateName T,
4718 ArrayRef<TemplateArgument> Args,
4719 QualType Underlying,
4720 const ASTContext &Context) {
4721 ID.AddInteger(I: llvm::to_underlying(E: Keyword));
4722 T.Profile(ID);
4723 Underlying.Profile(ID);
4724
4725 ID.AddInteger(I: Args.size());
4726 for (const TemplateArgument &Arg : Args)
4727 Arg.Profile(ID, Context);
4728}
4729
4730QualType QualifierCollector::apply(const ASTContext &Context,
4731 QualType QT) const {
4732 if (!hasNonFastQualifiers())
4733 return QT.withFastQualifiers(TQs: getFastQualifiers());
4734
4735 return Context.getQualifiedType(T: QT, Qs: *this);
4736}
4737
4738QualType QualifierCollector::apply(const ASTContext &Context,
4739 const Type *T) const {
4740 if (!hasNonFastQualifiers())
4741 return QualType(T, getFastQualifiers());
4742
4743 return Context.getQualifiedType(T, Qs: *this);
4744}
4745
4746void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
4747 ArrayRef<QualType> typeArgs,
4748 ArrayRef<ObjCProtocolDecl *> protocols,
4749 bool isKindOf) {
4750 ID.AddPointer(Ptr: BaseType.getAsOpaquePtr());
4751 ID.AddInteger(I: typeArgs.size());
4752 for (auto typeArg : typeArgs)
4753 ID.AddPointer(Ptr: typeArg.getAsOpaquePtr());
4754 ID.AddInteger(I: protocols.size());
4755 for (auto *proto : protocols)
4756 ID.AddPointer(Ptr: proto);
4757 ID.AddBoolean(B: isKindOf);
4758}
4759
4760void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
4761 Profile(ID, BaseType: getBaseType(), typeArgs: getTypeArgsAsWritten(),
4762 protocols: llvm::ArrayRef(qual_begin(), getNumProtocols()),
4763 isKindOf: isKindOfTypeAsWritten());
4764}
4765
4766void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID,
4767 const ObjCTypeParamDecl *OTPDecl,
4768 QualType CanonicalType,
4769 ArrayRef<ObjCProtocolDecl *> protocols) {
4770 ID.AddPointer(Ptr: OTPDecl);
4771 ID.AddPointer(Ptr: CanonicalType.getAsOpaquePtr());
4772 ID.AddInteger(I: protocols.size());
4773 for (auto *proto : protocols)
4774 ID.AddPointer(Ptr: proto);
4775}
4776
4777void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID) {
4778 Profile(ID, OTPDecl: getDecl(), CanonicalType: getCanonicalTypeInternal(),
4779 protocols: llvm::ArrayRef(qual_begin(), getNumProtocols()));
4780}
4781
4782namespace {
4783
4784/// The cached properties of a type.
4785class CachedProperties {
4786 Linkage L;
4787 bool local;
4788
4789public:
4790 CachedProperties(Linkage L, bool local) : L(L), local(local) {}
4791
4792 Linkage getLinkage() const { return L; }
4793 bool hasLocalOrUnnamedType() const { return local; }
4794
4795 friend CachedProperties merge(CachedProperties L, CachedProperties R) {
4796 Linkage MergedLinkage = minLinkage(L1: L.L, L2: R.L);
4797 return CachedProperties(MergedLinkage, L.hasLocalOrUnnamedType() ||
4798 R.hasLocalOrUnnamedType());
4799 }
4800};
4801
4802} // namespace
4803
4804static CachedProperties computeCachedProperties(const Type *T);
4805
4806namespace clang {
4807
4808/// The type-property cache. This is templated so as to be
4809/// instantiated at an internal type to prevent unnecessary symbol
4810/// leakage.
4811template <class Private> class TypePropertyCache {
4812public:
4813 static CachedProperties get(QualType T) { return get(T.getTypePtr()); }
4814
4815 static CachedProperties get(const Type *T) {
4816 ensure(T);
4817 return CachedProperties(T->TypeBits.getLinkage(),
4818 T->TypeBits.hasLocalOrUnnamedType());
4819 }
4820
4821 static void ensure(const Type *T) {
4822 // If the cache is valid, we're okay.
4823 if (T->TypeBits.isCacheValid())
4824 return;
4825
4826 // If this type is non-canonical, ask its canonical type for the
4827 // relevant information.
4828 if (!T->isCanonicalUnqualified()) {
4829 const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
4830 ensure(T: CT);
4831 T->TypeBits.CacheValid = true;
4832 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
4833 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
4834 return;
4835 }
4836
4837 // Compute the cached properties and then set the cache.
4838 CachedProperties Result = computeCachedProperties(T);
4839 T->TypeBits.CacheValid = true;
4840 T->TypeBits.CachedLinkage = llvm::to_underlying(E: Result.getLinkage());
4841 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
4842 }
4843};
4844
4845} // namespace clang
4846
4847// Instantiate the friend template at a private class. In a
4848// reasonable implementation, these symbols will be internal.
4849// It is terrible that this is the best way to accomplish this.
4850namespace {
4851
4852class Private {};
4853
4854} // namespace
4855
4856using Cache = TypePropertyCache<Private>;
4857
4858static CachedProperties computeCachedProperties(const Type *T) {
4859 switch (T->getTypeClass()) {
4860#define TYPE(Class, Base)
4861#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4862#include "clang/AST/TypeNodes.inc"
4863 llvm_unreachable("didn't expect a non-canonical type here");
4864
4865#define TYPE(Class, Base)
4866#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4867#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
4868#include "clang/AST/TypeNodes.inc"
4869 // Treat instantiation-dependent types as external.
4870 assert(T->isInstantiationDependentType());
4871 return CachedProperties(Linkage::External, false);
4872
4873 case Type::Auto:
4874 case Type::DeducedTemplateSpecialization:
4875 // Give non-deduced 'auto' types external linkage. We should only see them
4876 // here in error recovery.
4877 return CachedProperties(Linkage::External, false);
4878
4879 case Type::BitInt:
4880 case Type::Builtin:
4881 // C++ [basic.link]p8:
4882 // A type is said to have linkage if and only if:
4883 // - it is a fundamental type (3.9.1); or
4884 return CachedProperties(Linkage::External, false);
4885
4886 case Type::Record:
4887 case Type::Enum: {
4888 const auto *Tag = cast<TagType>(Val: T)->getDecl()->getDefinitionOrSelf();
4889
4890 // C++ [basic.link]p8:
4891 // - it is a class or enumeration type that is named (or has a name
4892 // for linkage purposes (7.1.3)) and the name has linkage; or
4893 // - it is a specialization of a class template (14); or
4894 Linkage L = Tag->getLinkageInternal();
4895 bool IsLocalOrUnnamed = Tag->getDeclContext()->isFunctionOrMethod() ||
4896 !Tag->hasNameForLinkage();
4897 return CachedProperties(L, IsLocalOrUnnamed);
4898 }
4899
4900 // C++ [basic.link]p8:
4901 // - it is a compound type (3.9.2) other than a class or enumeration,
4902 // compounded exclusively from types that have linkage; or
4903 case Type::Complex:
4904 return Cache::get(T: cast<ComplexType>(Val: T)->getElementType());
4905 case Type::Pointer:
4906 return Cache::get(T: cast<PointerType>(Val: T)->getPointeeType());
4907 case Type::BlockPointer:
4908 return Cache::get(T: cast<BlockPointerType>(Val: T)->getPointeeType());
4909 case Type::LValueReference:
4910 case Type::RValueReference:
4911 return Cache::get(T: cast<ReferenceType>(Val: T)->getPointeeType());
4912 case Type::MemberPointer: {
4913 const auto *MPT = cast<MemberPointerType>(Val: T);
4914 CachedProperties Cls = [&] {
4915 if (MPT->isSugared())
4916 MPT = cast<MemberPointerType>(Val: MPT->getCanonicalTypeInternal());
4917 return Cache::get(T: MPT->getQualifier().getAsType());
4918 }();
4919 return merge(L: Cls, R: Cache::get(T: MPT->getPointeeType()));
4920 }
4921 case Type::ConstantArray:
4922 case Type::IncompleteArray:
4923 case Type::VariableArray:
4924 case Type::ArrayParameter:
4925 return Cache::get(T: cast<ArrayType>(Val: T)->getElementType());
4926 case Type::Vector:
4927 case Type::ExtVector:
4928 return Cache::get(T: cast<VectorType>(Val: T)->getElementType());
4929 case Type::ConstantMatrix:
4930 return Cache::get(T: cast<ConstantMatrixType>(Val: T)->getElementType());
4931 case Type::FunctionNoProto:
4932 return Cache::get(T: cast<FunctionType>(Val: T)->getReturnType());
4933 case Type::FunctionProto: {
4934 const auto *FPT = cast<FunctionProtoType>(Val: T);
4935 CachedProperties result = Cache::get(T: FPT->getReturnType());
4936 for (const auto &ai : FPT->param_types())
4937 result = merge(L: result, R: Cache::get(T: ai));
4938 return result;
4939 }
4940 case Type::ObjCInterface: {
4941 Linkage L = cast<ObjCInterfaceType>(Val: T)->getDecl()->getLinkageInternal();
4942 return CachedProperties(L, false);
4943 }
4944 case Type::ObjCObject:
4945 return Cache::get(T: cast<ObjCObjectType>(Val: T)->getBaseType());
4946 case Type::ObjCObjectPointer:
4947 return Cache::get(T: cast<ObjCObjectPointerType>(Val: T)->getPointeeType());
4948 case Type::Atomic:
4949 return Cache::get(T: cast<AtomicType>(Val: T)->getValueType());
4950 case Type::Pipe:
4951 return Cache::get(T: cast<PipeType>(Val: T)->getElementType());
4952 case Type::HLSLAttributedResource:
4953 return Cache::get(T: cast<HLSLAttributedResourceType>(Val: T)->getWrappedType());
4954 case Type::HLSLInlineSpirv:
4955 return CachedProperties(Linkage::External, false);
4956 case Type::OverflowBehavior:
4957 return Cache::get(T: cast<OverflowBehaviorType>(Val: T)->getUnderlyingType());
4958 }
4959
4960 llvm_unreachable("unhandled type class");
4961}
4962
4963/// Determine the linkage of this type.
4964Linkage Type::getLinkage() const {
4965 Cache::ensure(T: this);
4966 return TypeBits.getLinkage();
4967}
4968
4969bool Type::hasUnnamedOrLocalType() const {
4970 Cache::ensure(T: this);
4971 return TypeBits.hasLocalOrUnnamedType();
4972}
4973
4974LinkageInfo LinkageComputer::computeTypeLinkageInfo(const Type *T) {
4975 switch (T->getTypeClass()) {
4976#define TYPE(Class, Base)
4977#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4978#include "clang/AST/TypeNodes.inc"
4979 llvm_unreachable("didn't expect a non-canonical type here");
4980
4981#define TYPE(Class, Base)
4982#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4983#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
4984#include "clang/AST/TypeNodes.inc"
4985 // Treat instantiation-dependent types as external.
4986 assert(T->isInstantiationDependentType());
4987 return LinkageInfo::external();
4988
4989 case Type::BitInt:
4990 case Type::Builtin:
4991 return LinkageInfo::external();
4992
4993 case Type::Auto:
4994 case Type::DeducedTemplateSpecialization:
4995 return LinkageInfo::external();
4996
4997 case Type::Record:
4998 case Type::Enum:
4999 return getDeclLinkageAndVisibility(
5000 D: cast<TagType>(Val: T)->getDecl()->getDefinitionOrSelf());
5001
5002 case Type::Complex:
5003 return computeTypeLinkageInfo(T: cast<ComplexType>(Val: T)->getElementType());
5004 case Type::Pointer:
5005 return computeTypeLinkageInfo(T: cast<PointerType>(Val: T)->getPointeeType());
5006 case Type::BlockPointer:
5007 return computeTypeLinkageInfo(T: cast<BlockPointerType>(Val: T)->getPointeeType());
5008 case Type::LValueReference:
5009 case Type::RValueReference:
5010 return computeTypeLinkageInfo(T: cast<ReferenceType>(Val: T)->getPointeeType());
5011 case Type::MemberPointer: {
5012 const auto *MPT = cast<MemberPointerType>(Val: T);
5013 LinkageInfo LV;
5014 if (auto *D = MPT->getMostRecentCXXRecordDecl()) {
5015 LV.merge(other: getDeclLinkageAndVisibility(D));
5016 } else {
5017 LV.merge(other: computeTypeLinkageInfo(T: MPT->getQualifier().getAsType()));
5018 }
5019 LV.merge(other: computeTypeLinkageInfo(T: MPT->getPointeeType()));
5020 return LV;
5021 }
5022 case Type::ConstantArray:
5023 case Type::IncompleteArray:
5024 case Type::VariableArray:
5025 case Type::ArrayParameter:
5026 return computeTypeLinkageInfo(T: cast<ArrayType>(Val: T)->getElementType());
5027 case Type::Vector:
5028 case Type::ExtVector:
5029 return computeTypeLinkageInfo(T: cast<VectorType>(Val: T)->getElementType());
5030 case Type::ConstantMatrix:
5031 return computeTypeLinkageInfo(
5032 T: cast<ConstantMatrixType>(Val: T)->getElementType());
5033 case Type::FunctionNoProto:
5034 return computeTypeLinkageInfo(T: cast<FunctionType>(Val: T)->getReturnType());
5035 case Type::FunctionProto: {
5036 const auto *FPT = cast<FunctionProtoType>(Val: T);
5037 LinkageInfo LV = computeTypeLinkageInfo(T: FPT->getReturnType());
5038 for (const auto &ai : FPT->param_types())
5039 LV.merge(other: computeTypeLinkageInfo(T: ai));
5040 return LV;
5041 }
5042 case Type::ObjCInterface:
5043 return getDeclLinkageAndVisibility(D: cast<ObjCInterfaceType>(Val: T)->getDecl());
5044 case Type::ObjCObject:
5045 return computeTypeLinkageInfo(T: cast<ObjCObjectType>(Val: T)->getBaseType());
5046 case Type::ObjCObjectPointer:
5047 return computeTypeLinkageInfo(
5048 T: cast<ObjCObjectPointerType>(Val: T)->getPointeeType());
5049 case Type::Atomic:
5050 return computeTypeLinkageInfo(T: cast<AtomicType>(Val: T)->getValueType());
5051 case Type::Pipe:
5052 return computeTypeLinkageInfo(T: cast<PipeType>(Val: T)->getElementType());
5053 case Type::OverflowBehavior:
5054 return computeTypeLinkageInfo(
5055 T: cast<OverflowBehaviorType>(Val: T)->getUnderlyingType());
5056 case Type::HLSLAttributedResource:
5057 return computeTypeLinkageInfo(T: cast<HLSLAttributedResourceType>(Val: T)
5058 ->getContainedType()
5059 ->getCanonicalTypeInternal());
5060 case Type::HLSLInlineSpirv:
5061 return LinkageInfo::external();
5062 }
5063
5064 llvm_unreachable("unhandled type class");
5065}
5066
5067bool Type::isLinkageValid() const {
5068 if (!TypeBits.isCacheValid())
5069 return true;
5070
5071 Linkage L = LinkageComputer{}
5072 .computeTypeLinkageInfo(T: getCanonicalTypeInternal())
5073 .getLinkage();
5074 return L == TypeBits.getLinkage();
5075}
5076
5077LinkageInfo LinkageComputer::getTypeLinkageAndVisibility(const Type *T) {
5078 if (!T->isCanonicalUnqualified())
5079 return computeTypeLinkageInfo(T: T->getCanonicalTypeInternal());
5080
5081 LinkageInfo LV = computeTypeLinkageInfo(T);
5082 assert(LV.getLinkage() == T->getLinkage());
5083 return LV;
5084}
5085
5086LinkageInfo Type::getLinkageAndVisibility() const {
5087 return LinkageComputer{}.getTypeLinkageAndVisibility(T: this);
5088}
5089
5090std::optional<NullabilityKind> Type::getNullability() const {
5091 QualType Type(this, 0);
5092 while (const auto *AT = Type->getAs<AttributedType>()) {
5093 // Check whether this is an attributed type with nullability
5094 // information.
5095 if (auto Nullability = AT->getImmediateNullability())
5096 return Nullability;
5097
5098 Type = AT->getEquivalentType();
5099 }
5100 return std::nullopt;
5101}
5102
5103bool Type::canHaveNullability(bool ResultIfUnknown) const {
5104 QualType type = getCanonicalTypeInternal();
5105
5106 switch (type->getTypeClass()) {
5107#define NON_CANONICAL_TYPE(Class, Parent) \
5108 /* We'll only see canonical types here. */ \
5109 case Type::Class: \
5110 llvm_unreachable("non-canonical type");
5111#define TYPE(Class, Parent)
5112#include "clang/AST/TypeNodes.inc"
5113
5114 // Pointer types.
5115 case Type::Pointer:
5116 case Type::BlockPointer:
5117 case Type::MemberPointer:
5118 case Type::ObjCObjectPointer:
5119 return true;
5120
5121 // Dependent types that could instantiate to pointer types.
5122 case Type::UnresolvedUsing:
5123 case Type::TypeOfExpr:
5124 case Type::TypeOf:
5125 case Type::Decltype:
5126 case Type::PackIndexing:
5127 case Type::UnaryTransform:
5128 case Type::TemplateTypeParm:
5129 case Type::SubstTemplateTypeParmPack:
5130 case Type::SubstBuiltinTemplatePack:
5131 case Type::DependentName:
5132 case Type::Auto:
5133 return ResultIfUnknown;
5134
5135 // Dependent template specializations could instantiate to pointer types.
5136 case Type::TemplateSpecialization:
5137 // If it's a known class template, we can already check if it's nullable.
5138 if (TemplateDecl *templateDecl =
5139 cast<TemplateSpecializationType>(Val: type.getTypePtr())
5140 ->getTemplateName()
5141 .getAsTemplateDecl())
5142 if (auto *CTD = dyn_cast<ClassTemplateDecl>(Val: templateDecl))
5143 return llvm::any_of(
5144 Range: CTD->redecls(), P: [](const RedeclarableTemplateDecl *RTD) {
5145 return RTD->getTemplatedDecl()->hasAttr<TypeNullableAttr>();
5146 });
5147 return ResultIfUnknown;
5148
5149 case Type::Builtin:
5150 switch (cast<BuiltinType>(Val: type.getTypePtr())->getKind()) {
5151 // Signed, unsigned, and floating-point types cannot have nullability.
5152#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
5153#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
5154#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
5155#define BUILTIN_TYPE(Id, SingletonId)
5156#include "clang/AST/BuiltinTypes.def"
5157 return false;
5158
5159 case BuiltinType::UnresolvedTemplate:
5160 // Dependent types that could instantiate to a pointer type.
5161 case BuiltinType::Dependent:
5162 case BuiltinType::Overload:
5163 case BuiltinType::BoundMember:
5164 case BuiltinType::PseudoObject:
5165 case BuiltinType::UnknownAny:
5166 case BuiltinType::ARCUnbridgedCast:
5167 return ResultIfUnknown;
5168
5169 case BuiltinType::Void:
5170 case BuiltinType::ObjCId:
5171 case BuiltinType::ObjCClass:
5172 case BuiltinType::ObjCSel:
5173#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5174 case BuiltinType::Id:
5175#include "clang/Basic/OpenCLImageTypes.def"
5176#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) case BuiltinType::Id:
5177#include "clang/Basic/OpenCLExtensionTypes.def"
5178 case BuiltinType::OCLSampler:
5179 case BuiltinType::OCLEvent:
5180 case BuiltinType::OCLClkEvent:
5181 case BuiltinType::OCLQueue:
5182 case BuiltinType::OCLReserveID:
5183#define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
5184#include "clang/Basic/AArch64ACLETypes.def"
5185#define PPC_VECTOR_TYPE(Name, Id, Size) case BuiltinType::Id:
5186#include "clang/Basic/PPCTypes.def"
5187#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
5188#include "clang/Basic/RISCVVTypes.def"
5189#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
5190#include "clang/Basic/WebAssemblyReferenceTypes.def"
5191#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
5192#include "clang/Basic/AMDGPUTypes.def"
5193#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
5194#include "clang/Basic/HLSLIntangibleTypes.def"
5195 case BuiltinType::BuiltinFn:
5196 case BuiltinType::NullPtr:
5197 case BuiltinType::IncompleteMatrixIdx:
5198 case BuiltinType::ArraySection:
5199 case BuiltinType::OMPArrayShaping:
5200 case BuiltinType::OMPIterator:
5201 return false;
5202 }
5203 llvm_unreachable("unknown builtin type");
5204
5205 case Type::Record: {
5206 const auto *RD = cast<RecordType>(Val&: type)->getDecl();
5207 // For template specializations, look only at primary template attributes.
5208 // This is a consistent regardless of whether the instantiation is known.
5209 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: RD))
5210 return llvm::any_of(
5211 Range: CTSD->getSpecializedTemplate()->redecls(),
5212 P: [](const RedeclarableTemplateDecl *RTD) {
5213 return RTD->getTemplatedDecl()->hasAttr<TypeNullableAttr>();
5214 });
5215 return llvm::any_of(Range: RD->redecls(), P: [](const TagDecl *RD) {
5216 return RD->hasAttr<TypeNullableAttr>();
5217 });
5218 }
5219
5220 // Non-pointer types.
5221 case Type::Complex:
5222 case Type::LValueReference:
5223 case Type::RValueReference:
5224 case Type::ConstantArray:
5225 case Type::IncompleteArray:
5226 case Type::VariableArray:
5227 case Type::DependentSizedArray:
5228 case Type::DependentVector:
5229 case Type::DependentSizedExtVector:
5230 case Type::Vector:
5231 case Type::ExtVector:
5232 case Type::ConstantMatrix:
5233 case Type::DependentSizedMatrix:
5234 case Type::DependentAddressSpace:
5235 case Type::FunctionProto:
5236 case Type::FunctionNoProto:
5237 case Type::DeducedTemplateSpecialization:
5238 case Type::Enum:
5239 case Type::InjectedClassName:
5240 case Type::PackExpansion:
5241 case Type::ObjCObject:
5242 case Type::ObjCInterface:
5243 case Type::Atomic:
5244 case Type::Pipe:
5245 case Type::BitInt:
5246 case Type::DependentBitInt:
5247 case Type::ArrayParameter:
5248 case Type::HLSLAttributedResource:
5249 case Type::HLSLInlineSpirv:
5250 case Type::OverflowBehavior:
5251 return false;
5252 }
5253 llvm_unreachable("bad type kind!");
5254}
5255
5256std::optional<NullabilityKind> AttributedType::getImmediateNullability() const {
5257 if (getAttrKind() == attr::TypeNonNull)
5258 return NullabilityKind::NonNull;
5259 if (getAttrKind() == attr::TypeNullable)
5260 return NullabilityKind::Nullable;
5261 if (getAttrKind() == attr::TypeNullUnspecified)
5262 return NullabilityKind::Unspecified;
5263 if (getAttrKind() == attr::TypeNullableResult)
5264 return NullabilityKind::NullableResult;
5265 return std::nullopt;
5266}
5267
5268std::optional<NullabilityKind>
5269AttributedType::stripOuterNullability(QualType &T) {
5270 QualType AttrTy = T;
5271 if (auto MacroTy = dyn_cast<MacroQualifiedType>(Val&: T))
5272 AttrTy = MacroTy->getUnderlyingType();
5273
5274 if (auto attributed = dyn_cast<AttributedType>(Val&: AttrTy)) {
5275 if (auto nullability = attributed->getImmediateNullability()) {
5276 T = attributed->getModifiedType();
5277 return nullability;
5278 }
5279 }
5280
5281 return std::nullopt;
5282}
5283
5284bool Type::isSignableIntegerType(const ASTContext &Ctx) const {
5285 if (!isIntegralType(Ctx) || isEnumeralType())
5286 return false;
5287 return Ctx.getTypeSize(T: this) == Ctx.getTypeSize(T: Ctx.VoidPtrTy);
5288}
5289
5290bool Type::isBlockCompatibleObjCPointerType(ASTContext &ctx) const {
5291 const auto *objcPtr = getAs<ObjCObjectPointerType>();
5292 if (!objcPtr)
5293 return false;
5294
5295 if (objcPtr->isObjCIdType()) {
5296 // id is always okay.
5297 return true;
5298 }
5299
5300 // Blocks are NSObjects.
5301 if (ObjCInterfaceDecl *iface = objcPtr->getInterfaceDecl()) {
5302 if (iface->getIdentifier() != ctx.getNSObjectName())
5303 return false;
5304
5305 // Continue to check qualifiers, below.
5306 } else if (objcPtr->isObjCQualifiedIdType()) {
5307 // Continue to check qualifiers, below.
5308 } else {
5309 return false;
5310 }
5311
5312 // Check protocol qualifiers.
5313 for (ObjCProtocolDecl *proto : objcPtr->quals()) {
5314 // Blocks conform to NSObject and NSCopying.
5315 if (proto->getIdentifier() != ctx.getNSObjectName() &&
5316 proto->getIdentifier() != ctx.getNSCopyingName())
5317 return false;
5318 }
5319
5320 return true;
5321}
5322
5323Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const {
5324 if (isObjCARCImplicitlyUnretainedType())
5325 return Qualifiers::OCL_ExplicitNone;
5326 return Qualifiers::OCL_Strong;
5327}
5328
5329bool Type::isObjCARCImplicitlyUnretainedType() const {
5330 assert(isObjCLifetimeType() &&
5331 "cannot query implicit lifetime for non-inferrable type");
5332
5333 const Type *canon = getCanonicalTypeInternal().getTypePtr();
5334
5335 // Walk down to the base type. We don't care about qualifiers for this.
5336 while (const auto *array = dyn_cast<ArrayType>(Val: canon))
5337 canon = array->getElementType().getTypePtr();
5338
5339 if (const auto *opt = dyn_cast<ObjCObjectPointerType>(Val: canon)) {
5340 // Class and Class<Protocol> don't require retention.
5341 if (opt->getObjectType()->isObjCClass())
5342 return true;
5343 }
5344
5345 return false;
5346}
5347
5348bool Type::isObjCNSObjectType() const {
5349 if (const auto *typedefType = getAs<TypedefType>())
5350 return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>();
5351 return false;
5352}
5353
5354bool Type::isObjCIndependentClassType() const {
5355 if (const auto *typedefType = getAs<TypedefType>())
5356 return typedefType->getDecl()->hasAttr<ObjCIndependentClassAttr>();
5357 return false;
5358}
5359
5360bool Type::isObjCRetainableType() const {
5361 return isObjCObjectPointerType() || isBlockPointerType() ||
5362 isObjCNSObjectType();
5363}
5364
5365bool Type::isObjCIndirectLifetimeType() const {
5366 if (isObjCLifetimeType())
5367 return true;
5368 if (const auto *OPT = getAs<PointerType>())
5369 return OPT->getPointeeType()->isObjCIndirectLifetimeType();
5370 if (const auto *Ref = getAs<ReferenceType>())
5371 return Ref->getPointeeType()->isObjCIndirectLifetimeType();
5372 if (const auto *MemPtr = getAs<MemberPointerType>())
5373 return MemPtr->getPointeeType()->isObjCIndirectLifetimeType();
5374 return false;
5375}
5376
5377/// Returns true if objects of this type have lifetime semantics under
5378/// ARC.
5379bool Type::isObjCLifetimeType() const {
5380 const Type *type = this;
5381 while (const ArrayType *array = type->getAsArrayTypeUnsafe())
5382 type = array->getElementType().getTypePtr();
5383 return type->isObjCRetainableType();
5384}
5385
5386/// Determine whether the given type T is a "bridgable" Objective-C type,
5387/// which is either an Objective-C object pointer type or an
5388bool Type::isObjCARCBridgableType() const {
5389 return isObjCObjectPointerType() || isBlockPointerType();
5390}
5391
5392/// Determine whether the given type T is a "bridgeable" C type.
5393bool Type::isCARCBridgableType() const {
5394 const auto *Pointer = getAsCanonical<PointerType>();
5395 if (!Pointer)
5396 return false;
5397
5398 QualType Pointee = Pointer->getPointeeType();
5399 return Pointee->isVoidType() || Pointee->isRecordType();
5400}
5401
5402/// Check if the specified type is the CUDA device builtin surface type.
5403bool Type::isCUDADeviceBuiltinSurfaceType() const {
5404 if (const auto *RT = getAsCanonical<RecordType>())
5405 return RT->getDecl()
5406 ->getMostRecentDecl()
5407 ->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>();
5408 return false;
5409}
5410
5411/// Check if the specified type is the CUDA device builtin texture type.
5412bool Type::isCUDADeviceBuiltinTextureType() const {
5413 if (const auto *RT = getAsCanonical<RecordType>())
5414 return RT->getDecl()
5415 ->getMostRecentDecl()
5416 ->hasAttr<CUDADeviceBuiltinTextureTypeAttr>();
5417 return false;
5418}
5419
5420bool Type::hasSizedVLAType() const {
5421 if (!isVariablyModifiedType())
5422 return false;
5423
5424 if (const auto *ptr = getAs<PointerType>())
5425 return ptr->getPointeeType()->hasSizedVLAType();
5426 if (const auto *ref = getAs<ReferenceType>())
5427 return ref->getPointeeType()->hasSizedVLAType();
5428 if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
5429 if (isa<VariableArrayType>(Val: arr) &&
5430 cast<VariableArrayType>(Val: arr)->getSizeExpr())
5431 return true;
5432
5433 return arr->getElementType()->hasSizedVLAType();
5434 }
5435
5436 return false;
5437}
5438
5439bool Type::isHLSLResourceRecord() const {
5440 return HLSLAttributedResourceType::findHandleTypeOnResource(RT: this) != nullptr;
5441}
5442
5443bool Type::isHLSLResourceRecordArray() const {
5444 const Type *Ty = getUnqualifiedDesugaredType();
5445 if (!Ty->isArrayType())
5446 return false;
5447 while (isa<ArrayType>(Val: Ty))
5448 Ty = Ty->getArrayElementTypeNoTypeQual();
5449 return Ty->isHLSLResourceRecord();
5450}
5451
5452bool Type::isHLSLIntangibleType() const {
5453 const Type *Ty = getUnqualifiedDesugaredType();
5454
5455 // check if it's a builtin type first
5456 if (Ty->isBuiltinType())
5457 return Ty->isHLSLBuiltinIntangibleType();
5458
5459 // unwrap arrays
5460 while (isa<ArrayType>(Val: Ty))
5461 Ty = Ty->getArrayElementTypeNoTypeQual();
5462
5463 const RecordType *RT =
5464 dyn_cast<RecordType>(Val: Ty->getUnqualifiedDesugaredType());
5465 if (!RT)
5466 return false;
5467
5468 CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
5469 assert(RD != nullptr &&
5470 "all HLSL structs and classes should be CXXRecordDecl");
5471 assert(RD->isCompleteDefinition() && "expecting complete type");
5472 return RD->isHLSLIntangible();
5473}
5474
5475QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
5476 switch (type.getObjCLifetime()) {
5477 case Qualifiers::OCL_None:
5478 case Qualifiers::OCL_ExplicitNone:
5479 case Qualifiers::OCL_Autoreleasing:
5480 break;
5481
5482 case Qualifiers::OCL_Strong:
5483 return DK_objc_strong_lifetime;
5484 case Qualifiers::OCL_Weak:
5485 return DK_objc_weak_lifetime;
5486 }
5487
5488 if (const auto *RD = type->getBaseElementTypeUnsafe()->getAsRecordDecl()) {
5489 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
5490 /// Check if this is a C++ object with a non-trivial destructor.
5491 if (CXXRD->hasDefinition() && !CXXRD->hasTrivialDestructor())
5492 return DK_cxx_destructor;
5493 } else {
5494 /// Check if this is a C struct that is non-trivial to destroy or an array
5495 /// that contains such a struct.
5496 if (RD->isNonTrivialToPrimitiveDestroy())
5497 return DK_nontrivial_c_struct;
5498 }
5499 }
5500
5501 return DK_none;
5502}
5503
5504bool MemberPointerType::isSugared() const {
5505 CXXRecordDecl *D1 = getMostRecentCXXRecordDecl(),
5506 *D2 = getQualifier().getAsRecordDecl();
5507 assert(!D1 == !D2);
5508 return D1 != D2 && D1->getCanonicalDecl() != D2->getCanonicalDecl();
5509}
5510
5511void MemberPointerType::Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
5512 const NestedNameSpecifier Qualifier,
5513 const CXXRecordDecl *Cls) {
5514 ID.AddPointer(Ptr: Pointee.getAsOpaquePtr());
5515 Qualifier.Profile(ID);
5516 if (Cls)
5517 ID.AddPointer(Ptr: Cls->getCanonicalDecl());
5518}
5519
5520CXXRecordDecl *MemberPointerType::getCXXRecordDecl() const {
5521 return dyn_cast<MemberPointerType>(Val: getCanonicalTypeInternal())
5522 ->getQualifier()
5523 .getAsRecordDecl();
5524}
5525
5526CXXRecordDecl *MemberPointerType::getMostRecentCXXRecordDecl() const {
5527 auto *RD = getCXXRecordDecl();
5528 if (!RD)
5529 return nullptr;
5530 return RD->getMostRecentDecl();
5531}
5532
5533void clang::FixedPointValueToString(SmallVectorImpl<char> &Str,
5534 llvm::APSInt Val, unsigned Scale) {
5535 llvm::FixedPointSemantics FXSema(Val.getBitWidth(), Scale, Val.isSigned(),
5536 /*IsSaturated=*/false,
5537 /*HasUnsignedPadding=*/false);
5538 llvm::APFixedPoint(Val, FXSema).toString(Str);
5539}
5540
5541AutoType::AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
5542 TypeDependence ExtraDependence, QualType Canon,
5543 TemplateDecl *TypeConstraintConcept,
5544 ArrayRef<TemplateArgument> TypeConstraintArgs)
5545 : DeducedType(Auto, DeducedAsType, ExtraDependence, Canon) {
5546 AutoTypeBits.Keyword = llvm::to_underlying(E: Keyword);
5547 AutoTypeBits.NumArgs = TypeConstraintArgs.size();
5548 this->TypeConstraintConcept = TypeConstraintConcept;
5549 assert(TypeConstraintConcept || AutoTypeBits.NumArgs == 0);
5550 if (TypeConstraintConcept) {
5551 if (isa<TemplateTemplateParmDecl>(Val: TypeConstraintConcept))
5552 addDependence(D: TypeDependence::DependentInstantiation);
5553
5554 auto *ArgBuffer =
5555 const_cast<TemplateArgument *>(getTypeConstraintArguments().data());
5556 for (const TemplateArgument &Arg : TypeConstraintArgs) {
5557 // We only syntactically depend on the constraint arguments. They don't
5558 // affect the deduced type, only its validity.
5559 addDependence(
5560 D: toSyntacticDependence(D: toTypeDependence(D: Arg.getDependence())));
5561
5562 new (ArgBuffer++) TemplateArgument(Arg);
5563 }
5564 }
5565}
5566
5567void AutoType::Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
5568 QualType Deduced, AutoTypeKeyword Keyword,
5569 bool IsDependent, TemplateDecl *CD,
5570 ArrayRef<TemplateArgument> Arguments) {
5571 ID.AddPointer(Ptr: Deduced.getAsOpaquePtr());
5572 ID.AddInteger(I: (unsigned)Keyword);
5573 ID.AddBoolean(B: IsDependent);
5574 ID.AddPointer(Ptr: CD);
5575 for (const TemplateArgument &Arg : Arguments)
5576 Arg.Profile(ID, Context);
5577}
5578
5579void AutoType::Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5580 Profile(ID, Context, Deduced: getDeducedType(), Keyword: getKeyword(), IsDependent: isDependentType(),
5581 CD: getTypeConstraintConcept(), Arguments: getTypeConstraintArguments());
5582}
5583
5584FunctionEffect::Kind FunctionEffect::oppositeKind() const {
5585 switch (kind()) {
5586 case Kind::NonBlocking:
5587 return Kind::Blocking;
5588 case Kind::Blocking:
5589 return Kind::NonBlocking;
5590 case Kind::NonAllocating:
5591 return Kind::Allocating;
5592 case Kind::Allocating:
5593 return Kind::NonAllocating;
5594 }
5595 llvm_unreachable("unknown effect kind");
5596}
5597
5598StringRef FunctionEffect::name() const {
5599 switch (kind()) {
5600 case Kind::NonBlocking:
5601 return "nonblocking";
5602 case Kind::NonAllocating:
5603 return "nonallocating";
5604 case Kind::Blocking:
5605 return "blocking";
5606 case Kind::Allocating:
5607 return "allocating";
5608 }
5609 llvm_unreachable("unknown effect kind");
5610}
5611
5612std::optional<FunctionEffect> FunctionEffect::effectProhibitingInference(
5613 const Decl &Callee, FunctionEffectKindSet CalleeFX) const {
5614 switch (kind()) {
5615 case Kind::NonAllocating:
5616 case Kind::NonBlocking: {
5617 for (FunctionEffect Effect : CalleeFX) {
5618 // nonblocking/nonallocating cannot call allocating.
5619 if (Effect.kind() == Kind::Allocating)
5620 return Effect;
5621 // nonblocking cannot call blocking.
5622 if (kind() == Kind::NonBlocking && Effect.kind() == Kind::Blocking)
5623 return Effect;
5624 }
5625 return std::nullopt;
5626 }
5627
5628 case Kind::Allocating:
5629 case Kind::Blocking:
5630 assert(0 && "effectProhibitingInference with non-inferable effect kind");
5631 break;
5632 }
5633 llvm_unreachable("unknown effect kind");
5634}
5635
5636bool FunctionEffect::shouldDiagnoseFunctionCall(
5637 bool Direct, FunctionEffectKindSet CalleeFX) const {
5638 switch (kind()) {
5639 case Kind::NonAllocating:
5640 case Kind::NonBlocking: {
5641 const Kind CallerKind = kind();
5642 for (FunctionEffect Effect : CalleeFX) {
5643 const Kind EK = Effect.kind();
5644 // Does callee have same or stronger constraint?
5645 if (EK == CallerKind ||
5646 (CallerKind == Kind::NonAllocating && EK == Kind::NonBlocking)) {
5647 return false; // no diagnostic
5648 }
5649 }
5650 return true; // warning
5651 }
5652 case Kind::Allocating:
5653 case Kind::Blocking:
5654 return false;
5655 }
5656 llvm_unreachable("unknown effect kind");
5657}
5658
5659// =====
5660
5661bool FunctionEffectSet::insert(const FunctionEffectWithCondition &NewEC,
5662 Conflicts &Errs) {
5663 FunctionEffect::Kind NewOppositeKind = NewEC.Effect.oppositeKind();
5664 Expr *NewCondition = NewEC.Cond.getCondition();
5665
5666 // The index at which insertion will take place; default is at end
5667 // but we might find an earlier insertion point.
5668 unsigned InsertIdx = Effects.size();
5669 unsigned Idx = 0;
5670 for (const FunctionEffectWithCondition &EC : *this) {
5671 // Note about effects with conditions: They are considered distinct from
5672 // those without conditions; they are potentially unique, redundant, or
5673 // in conflict, but we can't tell which until the condition is evaluated.
5674 if (EC.Cond.getCondition() == nullptr && NewCondition == nullptr) {
5675 if (EC.Effect.kind() == NewEC.Effect.kind()) {
5676 // There is no condition, and the effect kind is already present,
5677 // so just fail to insert the new one (creating a duplicate),
5678 // and return success.
5679 return true;
5680 }
5681
5682 if (EC.Effect.kind() == NewOppositeKind) {
5683 Errs.push_back(Elt: {.Kept: EC, .Rejected: NewEC});
5684 return false;
5685 }
5686 }
5687
5688 if (NewEC.Effect.kind() < EC.Effect.kind() && InsertIdx > Idx)
5689 InsertIdx = Idx;
5690
5691 ++Idx;
5692 }
5693
5694 if (NewCondition || !Conditions.empty()) {
5695 if (Conditions.empty() && !Effects.empty())
5696 Conditions.resize(N: Effects.size());
5697 Conditions.insert(I: Conditions.begin() + InsertIdx,
5698 Elt: NewEC.Cond.getCondition());
5699 }
5700 Effects.insert(I: Effects.begin() + InsertIdx, Elt: NewEC.Effect);
5701 return true;
5702}
5703
5704bool FunctionEffectSet::insert(const FunctionEffectsRef &Set, Conflicts &Errs) {
5705 for (const auto &Item : Set)
5706 insert(NewEC: Item, Errs);
5707 return Errs.empty();
5708}
5709
5710FunctionEffectSet FunctionEffectSet::getIntersection(FunctionEffectsRef LHS,
5711 FunctionEffectsRef RHS) {
5712 FunctionEffectSet Result;
5713 FunctionEffectSet::Conflicts Errs;
5714
5715 // We could use std::set_intersection but that would require expanding the
5716 // container interface to include push_back, making it available to clients
5717 // who might fail to maintain invariants.
5718 auto IterA = LHS.begin(), EndA = LHS.end();
5719 auto IterB = RHS.begin(), EndB = RHS.end();
5720
5721 auto FEWCLess = [](const FunctionEffectWithCondition &LHS,
5722 const FunctionEffectWithCondition &RHS) {
5723 return std::tuple(LHS.Effect, uintptr_t(LHS.Cond.getCondition())) <
5724 std::tuple(RHS.Effect, uintptr_t(RHS.Cond.getCondition()));
5725 };
5726
5727 while (IterA != EndA && IterB != EndB) {
5728 FunctionEffectWithCondition A = *IterA;
5729 FunctionEffectWithCondition B = *IterB;
5730 if (FEWCLess(A, B))
5731 ++IterA;
5732 else if (FEWCLess(B, A))
5733 ++IterB;
5734 else {
5735 Result.insert(NewEC: A, Errs);
5736 ++IterA;
5737 ++IterB;
5738 }
5739 }
5740
5741 // Insertion shouldn't be able to fail; that would mean both input
5742 // sets contained conflicts.
5743 assert(Errs.empty() && "conflict shouldn't be possible in getIntersection");
5744
5745 return Result;
5746}
5747
5748FunctionEffectSet FunctionEffectSet::getUnion(FunctionEffectsRef LHS,
5749 FunctionEffectsRef RHS,
5750 Conflicts &Errs) {
5751 // Optimize for either of the two sets being empty (very common).
5752 if (LHS.empty())
5753 return FunctionEffectSet(RHS);
5754
5755 FunctionEffectSet Combined(LHS);
5756 Combined.insert(Set: RHS, Errs);
5757 return Combined;
5758}
5759
5760namespace clang {
5761
5762raw_ostream &operator<<(raw_ostream &OS,
5763 const FunctionEffectWithCondition &CFE) {
5764 OS << CFE.Effect.name();
5765 if (Expr *E = CFE.Cond.getCondition()) {
5766 OS << '(';
5767 E->dump();
5768 OS << ')';
5769 }
5770 return OS;
5771}
5772
5773} // namespace clang
5774
5775LLVM_DUMP_METHOD void FunctionEffectsRef::dump(llvm::raw_ostream &OS) const {
5776 OS << "Effects{";
5777 llvm::interleaveComma(c: *this, os&: OS);
5778 OS << "}";
5779}
5780
5781LLVM_DUMP_METHOD void FunctionEffectSet::dump(llvm::raw_ostream &OS) const {
5782 FunctionEffectsRef(*this).dump(OS);
5783}
5784
5785LLVM_DUMP_METHOD void FunctionEffectKindSet::dump(llvm::raw_ostream &OS) const {
5786 OS << "Effects{";
5787 llvm::interleaveComma(c: *this, os&: OS);
5788 OS << "}";
5789}
5790
5791FunctionEffectsRef
5792FunctionEffectsRef::create(ArrayRef<FunctionEffect> FX,
5793 ArrayRef<EffectConditionExpr> Conds) {
5794 assert(llvm::is_sorted(FX) && "effects should be sorted");
5795 assert((Conds.empty() || Conds.size() == FX.size()) &&
5796 "effects size should match conditions size");
5797 return FunctionEffectsRef(FX, Conds);
5798}
5799
5800std::string FunctionEffectWithCondition::description() const {
5801 std::string Result(Effect.name().str());
5802 if (Cond.getCondition() != nullptr)
5803 Result += "(expr)";
5804 return Result;
5805}
5806
5807const HLSLAttributedResourceType *
5808HLSLAttributedResourceType::findHandleTypeOnResource(const Type *RT) {
5809 // If the type RT is an HLSL resource class, the first field must
5810 // be the resource handle of type HLSLAttributedResourceType
5811 const clang::Type *Ty = RT->getUnqualifiedDesugaredType();
5812 if (const RecordDecl *RD = Ty->getAsCXXRecordDecl()) {
5813 if (!RD->fields().empty()) {
5814 const auto &FirstFD = RD->fields().begin();
5815 return dyn_cast<HLSLAttributedResourceType>(
5816 Val: FirstFD->getType().getTypePtr());
5817 }
5818 }
5819 return nullptr;
5820}
5821
5822StringRef PredefinedSugarType::getName(Kind KD) {
5823 switch (KD) {
5824 case Kind::SizeT:
5825 return "__size_t";
5826 case Kind::SignedSizeT:
5827 return "__signed_size_t";
5828 case Kind::PtrdiffT:
5829 return "__ptrdiff_t";
5830 }
5831 llvm_unreachable("unexpected kind");
5832}
5833