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 == T->getDeducedType())
1331 return QualType(T, 0);
1332
1333 return Ctx.getAutoType(DK: T->getDeducedKind(), DeducedAsType: deducedType, Keyword: T->getKeyword(),
1334 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 if (RD->isInvalidDecl())
2938 return false;
2939
2940 // Never allow memcpy when we're adding poisoned padding bits to the struct.
2941 // Accessing these posioned bits will trigger false alarms on
2942 // SanitizeAddressFieldPadding etc.
2943 if (RD->mayInsertExtraPadding())
2944 return false;
2945
2946 for (auto *const Field : RD->fields()) {
2947 if (!Field->getType().isBitwiseCloneableType(Context))
2948 return false;
2949 }
2950
2951 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
2952 for (auto Base : CXXRD->bases())
2953 if (!Base.getType().isBitwiseCloneableType(Context))
2954 return false;
2955 for (auto VBase : CXXRD->vbases())
2956 if (!VBase.getType().isBitwiseCloneableType(Context))
2957 return false;
2958 }
2959 return true;
2960}
2961
2962bool QualType::isTriviallyCopyConstructibleType(
2963 const ASTContext &Context) const {
2964 return isTriviallyCopyableTypeImpl(type: *this, Context,
2965 /*IsCopyConstructible=*/true);
2966}
2967
2968bool QualType::isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const {
2969 return !Context.getLangOpts().ObjCAutoRefCount &&
2970 Context.getLangOpts().ObjCWeak &&
2971 getObjCLifetime() != Qualifiers::OCL_Weak;
2972}
2973
2974bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion(
2975 const RecordDecl *RD) {
2976 return RD->hasNonTrivialToPrimitiveDefaultInitializeCUnion();
2977}
2978
2979bool QualType::hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD) {
2980 return RD->hasNonTrivialToPrimitiveDestructCUnion();
2981}
2982
2983bool QualType::hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD) {
2984 return RD->hasNonTrivialToPrimitiveCopyCUnion();
2985}
2986
2987bool QualType::isWebAssemblyReferenceType() const {
2988 return isWebAssemblyExternrefType() || isWebAssemblyFuncrefType();
2989}
2990
2991bool QualType::isWebAssemblyExternrefType() const {
2992 return getTypePtr()->isWebAssemblyExternrefType();
2993}
2994
2995bool QualType::isWebAssemblyFuncrefType() const {
2996 return getTypePtr()->isFunctionPointerType() &&
2997 (getTypePtr()->getPointeeType().getAddressSpace() ==
2998 LangAS::wasm_funcref);
2999}
3000
3001bool QualType::isWrapType() const {
3002 if (const auto *OBT = getCanonicalType()->getAs<OverflowBehaviorType>())
3003 return OBT->getBehaviorKind() ==
3004 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
3005
3006 return false;
3007}
3008
3009bool QualType::isTrapType() const {
3010 if (const auto *OBT = getCanonicalType()->getAs<OverflowBehaviorType>())
3011 return OBT->getBehaviorKind() ==
3012 OverflowBehaviorType::OverflowBehaviorKind::Trap;
3013
3014 return false;
3015}
3016
3017QualType::PrimitiveDefaultInitializeKind
3018QualType::isNonTrivialToPrimitiveDefaultInitialize() const {
3019 if (const auto *RD =
3020 getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
3021 if (RD->isNonTrivialToPrimitiveDefaultInitialize())
3022 return PDIK_Struct;
3023
3024 switch (getQualifiers().getObjCLifetime()) {
3025 case Qualifiers::OCL_Strong:
3026 return PDIK_ARCStrong;
3027 case Qualifiers::OCL_Weak:
3028 return PDIK_ARCWeak;
3029 default:
3030 return PDIK_Trivial;
3031 }
3032}
3033
3034QualType::PrimitiveCopyKind QualType::isNonTrivialToPrimitiveCopy() const {
3035 if (const auto *RD =
3036 getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
3037 if (RD->isNonTrivialToPrimitiveCopy())
3038 return PCK_Struct;
3039
3040 Qualifiers Qs = getQualifiers();
3041 switch (Qs.getObjCLifetime()) {
3042 case Qualifiers::OCL_Strong:
3043 return PCK_ARCStrong;
3044 case Qualifiers::OCL_Weak:
3045 return PCK_ARCWeak;
3046 default:
3047 if (hasAddressDiscriminatedPointerAuth())
3048 return PCK_PtrAuth;
3049 return Qs.hasVolatile() ? PCK_VolatileTrivial : PCK_Trivial;
3050 }
3051}
3052
3053QualType::PrimitiveCopyKind
3054QualType::isNonTrivialToPrimitiveDestructiveMove() const {
3055 return isNonTrivialToPrimitiveCopy();
3056}
3057
3058bool Type::isLiteralType(const ASTContext &Ctx) const {
3059 if (isDependentType())
3060 return false;
3061
3062 // C++1y [basic.types]p10:
3063 // A type is a literal type if it is:
3064 // -- cv void; or
3065 if (Ctx.getLangOpts().CPlusPlus14 && isVoidType())
3066 return true;
3067
3068 // C++11 [basic.types]p10:
3069 // A type is a literal type if it is:
3070 // [...]
3071 // -- an array of literal type other than an array of runtime bound; or
3072 if (isVariableArrayType())
3073 return false;
3074 const Type *BaseTy = getBaseElementTypeUnsafe();
3075 assert(BaseTy && "NULL element type");
3076
3077 // Return false for incomplete types after skipping any incomplete array
3078 // types; those are expressly allowed by the standard and thus our API.
3079 if (BaseTy->isIncompleteType())
3080 return false;
3081
3082 // C++11 [basic.types]p10:
3083 // A type is a literal type if it is:
3084 // -- a scalar type; or
3085 // As an extension, Clang treats vector types and complex types as
3086 // literal types.
3087 if (BaseTy->isScalarType() || BaseTy->isVectorType() ||
3088 BaseTy->isAnyComplexType())
3089 return true;
3090 // Matrices with constant numbers of rows and columns are also literal types
3091 // in HLSL.
3092 if (Ctx.getLangOpts().HLSL && BaseTy->isConstantMatrixType())
3093 return true;
3094 // -- a reference type; or
3095 if (BaseTy->isReferenceType())
3096 return true;
3097 // -- a class type that has all of the following properties:
3098 if (const auto *RD = BaseTy->getAsRecordDecl()) {
3099 // -- a trivial destructor,
3100 // -- every constructor call and full-expression in the
3101 // brace-or-equal-initializers for non-static data members (if any)
3102 // is a constant expression,
3103 // -- it is an aggregate type or has at least one constexpr
3104 // constructor or constructor template that is not a copy or move
3105 // constructor, and
3106 // -- all non-static data members and base classes of literal types
3107 //
3108 // We resolve DR1361 by ignoring the second bullet.
3109 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Val: RD))
3110 return ClassDecl->isLiteral();
3111
3112 return true;
3113 }
3114
3115 // We treat _Atomic T as a literal type if T is a literal type.
3116 if (const auto *AT = BaseTy->getAs<AtomicType>())
3117 return AT->getValueType()->isLiteralType(Ctx);
3118
3119 if (const auto *OBT = BaseTy->getAs<OverflowBehaviorType>())
3120 return OBT->getUnderlyingType()->isLiteralType(Ctx);
3121
3122 // If this type hasn't been deduced yet, then conservatively assume that
3123 // it'll work out to be a literal type.
3124 if (isa<AutoType>(Val: BaseTy->getCanonicalTypeInternal()))
3125 return true;
3126
3127 return false;
3128}
3129
3130bool Type::isStructuralType() const {
3131 // C++20 [temp.param]p6:
3132 // A structural type is one of the following:
3133 // -- a scalar type; or
3134 // -- a vector type [Clang extension]; or
3135 if (isScalarType() || isVectorType())
3136 return true;
3137 // -- an lvalue reference type; or
3138 if (isLValueReferenceType())
3139 return true;
3140 // -- a literal class type [...under some conditions]
3141 if (const CXXRecordDecl *RD = getAsCXXRecordDecl())
3142 return RD->isStructural();
3143 return false;
3144}
3145
3146bool Type::isStandardLayoutType() const {
3147 if (isDependentType())
3148 return false;
3149
3150 // C++0x [basic.types]p9:
3151 // Scalar types, standard-layout class types, arrays of such types, and
3152 // cv-qualified versions of these types are collectively called
3153 // standard-layout types.
3154 const Type *BaseTy = getBaseElementTypeUnsafe();
3155 assert(BaseTy && "NULL element type");
3156
3157 // Return false for incomplete types after skipping any incomplete array
3158 // types which are expressly allowed by the standard and thus our API.
3159 if (BaseTy->isIncompleteType())
3160 return false;
3161
3162 // As an extension, Clang treats vector types as Scalar types.
3163 if (BaseTy->isScalarType() || BaseTy->isVectorType())
3164 return true;
3165 if (const auto *RD = BaseTy->getAsRecordDecl()) {
3166 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Val: RD);
3167 ClassDecl && !ClassDecl->isStandardLayout())
3168 return false;
3169
3170 // Default to 'true' for non-C++ class types.
3171 // FIXME: This is a bit dubious, but plain C structs should trivially meet
3172 // all the requirements of standard layout classes.
3173 return true;
3174 }
3175
3176 // No other types can match.
3177 return false;
3178}
3179
3180// This is effectively the intersection of isTrivialType and
3181// isStandardLayoutType. We implement it directly to avoid redundant
3182// conversions from a type to a CXXRecordDecl.
3183bool QualType::isCXX11PODType(const ASTContext &Context) const {
3184 const Type *ty = getTypePtr();
3185 if (ty->isDependentType())
3186 return false;
3187
3188 if (hasNonTrivialObjCLifetime())
3189 return false;
3190
3191 // C++11 [basic.types]p9:
3192 // Scalar types, POD classes, arrays of such types, and cv-qualified
3193 // versions of these types are collectively called trivial types.
3194 const Type *BaseTy = ty->getBaseElementTypeUnsafe();
3195 assert(BaseTy && "NULL element type");
3196
3197 if (BaseTy->isSizelessBuiltinType())
3198 return true;
3199
3200 // Return false for incomplete types after skipping any incomplete array
3201 // types which are expressly allowed by the standard and thus our API.
3202 if (BaseTy->isIncompleteType())
3203 return false;
3204
3205 // Any type that is, or contains, address discriminated data is non-POD.
3206 if (Context.containsAddressDiscriminatedPointerAuth(T: *this))
3207 return false;
3208
3209 // As an extension, Clang treats vector types as Scalar types.
3210 if (BaseTy->isScalarType() || BaseTy->isVectorType())
3211 return true;
3212 if (const auto *RD = BaseTy->getAsRecordDecl()) {
3213 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Val: RD)) {
3214 // C++11 [class]p10:
3215 // A POD struct is a non-union class that is both a trivial class [...]
3216 if (!ClassDecl->isTrivial())
3217 return false;
3218
3219 // C++11 [class]p10:
3220 // A POD struct is a non-union class that is both a trivial class and
3221 // a standard-layout class [...]
3222 if (!ClassDecl->isStandardLayout())
3223 return false;
3224
3225 // C++11 [class]p10:
3226 // A POD struct is a non-union class that is both a trivial class and
3227 // a standard-layout class, and has no non-static data members of type
3228 // non-POD struct, non-POD union (or array of such types). [...]
3229 //
3230 // We don't directly query the recursive aspect as the requirements for
3231 // both standard-layout classes and trivial classes apply recursively
3232 // already.
3233 }
3234
3235 return true;
3236 }
3237
3238 // No other types can match.
3239 return false;
3240}
3241
3242bool Type::isNothrowT() const {
3243 if (const auto *RD = getAsCXXRecordDecl()) {
3244 IdentifierInfo *II = RD->getIdentifier();
3245 if (II && II->isStr(Str: "nothrow_t") && RD->isInStdNamespace())
3246 return true;
3247 }
3248 return false;
3249}
3250
3251bool Type::isAlignValT() const {
3252 if (const auto *ET = getAsCanonical<EnumType>()) {
3253 const auto *ED = ET->getDecl();
3254 IdentifierInfo *II = ED->getIdentifier();
3255 if (II && II->isStr(Str: "align_val_t") && ED->isInStdNamespace())
3256 return true;
3257 }
3258 return false;
3259}
3260
3261bool Type::isStdByteType() const {
3262 if (const auto *ET = getAsCanonical<EnumType>()) {
3263 const auto *ED = ET->getDecl();
3264 IdentifierInfo *II = ED->getIdentifier();
3265 if (II && II->isStr(Str: "byte") && ED->isInStdNamespace())
3266 return true;
3267 }
3268 return false;
3269}
3270
3271bool Type::isSpecifierType() const {
3272 // Note that this intentionally does not use the canonical type.
3273 switch (getTypeClass()) {
3274 case Builtin:
3275 case Record:
3276 case Enum:
3277 case Typedef:
3278 case Complex:
3279 case TypeOfExpr:
3280 case TypeOf:
3281 case TemplateTypeParm:
3282 case SubstTemplateTypeParm:
3283 case TemplateSpecialization:
3284 case DependentName:
3285 case ObjCInterface:
3286 case ObjCObject:
3287 return true;
3288 default:
3289 return false;
3290 }
3291}
3292
3293ElaboratedTypeKeyword KeywordHelpers::getKeywordForTypeSpec(unsigned TypeSpec) {
3294 switch (TypeSpec) {
3295 default:
3296 return ElaboratedTypeKeyword::None;
3297 case TST_typename:
3298 return ElaboratedTypeKeyword::Typename;
3299 case TST_class:
3300 return ElaboratedTypeKeyword::Class;
3301 case TST_struct:
3302 return ElaboratedTypeKeyword::Struct;
3303 case TST_interface:
3304 return ElaboratedTypeKeyword::Interface;
3305 case TST_union:
3306 return ElaboratedTypeKeyword::Union;
3307 case TST_enum:
3308 return ElaboratedTypeKeyword::Enum;
3309 }
3310}
3311
3312TagTypeKind KeywordHelpers::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
3313 switch (TypeSpec) {
3314 case TST_class:
3315 return TagTypeKind::Class;
3316 case TST_struct:
3317 return TagTypeKind::Struct;
3318 case TST_interface:
3319 return TagTypeKind::Interface;
3320 case TST_union:
3321 return TagTypeKind::Union;
3322 case TST_enum:
3323 return TagTypeKind::Enum;
3324 }
3325
3326 llvm_unreachable("Type specifier is not a tag type kind.");
3327}
3328
3329ElaboratedTypeKeyword
3330KeywordHelpers::getKeywordForTagTypeKind(TagTypeKind Kind) {
3331 switch (Kind) {
3332 case TagTypeKind::Class:
3333 return ElaboratedTypeKeyword::Class;
3334 case TagTypeKind::Struct:
3335 return ElaboratedTypeKeyword::Struct;
3336 case TagTypeKind::Interface:
3337 return ElaboratedTypeKeyword::Interface;
3338 case TagTypeKind::Union:
3339 return ElaboratedTypeKeyword::Union;
3340 case TagTypeKind::Enum:
3341 return ElaboratedTypeKeyword::Enum;
3342 }
3343 llvm_unreachable("Unknown tag type kind.");
3344}
3345
3346TagTypeKind
3347KeywordHelpers::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
3348 switch (Keyword) {
3349 case ElaboratedTypeKeyword::Class:
3350 return TagTypeKind::Class;
3351 case ElaboratedTypeKeyword::Struct:
3352 return TagTypeKind::Struct;
3353 case ElaboratedTypeKeyword::Interface:
3354 return TagTypeKind::Interface;
3355 case ElaboratedTypeKeyword::Union:
3356 return TagTypeKind::Union;
3357 case ElaboratedTypeKeyword::Enum:
3358 return TagTypeKind::Enum;
3359 case ElaboratedTypeKeyword::None: // Fall through.
3360 case ElaboratedTypeKeyword::Typename:
3361 llvm_unreachable("Elaborated type keyword is not a tag type kind.");
3362 }
3363 llvm_unreachable("Unknown elaborated type keyword.");
3364}
3365
3366bool KeywordHelpers::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
3367 switch (Keyword) {
3368 case ElaboratedTypeKeyword::None:
3369 case ElaboratedTypeKeyword::Typename:
3370 return false;
3371 case ElaboratedTypeKeyword::Class:
3372 case ElaboratedTypeKeyword::Struct:
3373 case ElaboratedTypeKeyword::Interface:
3374 case ElaboratedTypeKeyword::Union:
3375 case ElaboratedTypeKeyword::Enum:
3376 return true;
3377 }
3378 llvm_unreachable("Unknown elaborated type keyword.");
3379}
3380
3381StringRef KeywordHelpers::getKeywordName(ElaboratedTypeKeyword Keyword) {
3382 switch (Keyword) {
3383 case ElaboratedTypeKeyword::None:
3384 return {};
3385 case ElaboratedTypeKeyword::Typename:
3386 return "typename";
3387 case ElaboratedTypeKeyword::Class:
3388 return "class";
3389 case ElaboratedTypeKeyword::Struct:
3390 return "struct";
3391 case ElaboratedTypeKeyword::Interface:
3392 return "__interface";
3393 case ElaboratedTypeKeyword::Union:
3394 return "union";
3395 case ElaboratedTypeKeyword::Enum:
3396 return "enum";
3397 }
3398
3399 llvm_unreachable("Unknown elaborated type keyword.");
3400}
3401
3402bool Type::isElaboratedTypeSpecifier() const {
3403 ElaboratedTypeKeyword Keyword;
3404 if (const auto *TST = dyn_cast<TemplateSpecializationType>(Val: this))
3405 Keyword = TST->getKeyword();
3406 else if (const auto *DepName = dyn_cast<DependentNameType>(Val: this))
3407 Keyword = DepName->getKeyword();
3408 else if (const auto *T = dyn_cast<TagType>(Val: this))
3409 Keyword = T->getKeyword();
3410 else if (const auto *T = dyn_cast<TypedefType>(Val: this))
3411 Keyword = T->getKeyword();
3412 else if (const auto *T = dyn_cast<UnresolvedUsingType>(Val: this))
3413 Keyword = T->getKeyword();
3414 else if (const auto *T = dyn_cast<UsingType>(Val: this))
3415 Keyword = T->getKeyword();
3416 else
3417 return false;
3418
3419 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
3420}
3421
3422const char *Type::getTypeClassName() const {
3423 switch (TypeBits.TC) {
3424#define ABSTRACT_TYPE(Derived, Base)
3425#define TYPE(Derived, Base) \
3426 case Derived: \
3427 return #Derived;
3428#include "clang/AST/TypeNodes.inc"
3429 }
3430
3431 llvm_unreachable("Invalid type class.");
3432}
3433
3434StringRef BuiltinType::getName(const PrintingPolicy &Policy) const {
3435 switch (getKind()) {
3436 case Void:
3437 return "void";
3438 case Bool:
3439 return Policy.Bool ? "bool" : "_Bool";
3440 case Char_S:
3441 return "char";
3442 case Char_U:
3443 return "char";
3444 case SChar:
3445 return "signed char";
3446 case Short:
3447 return "short";
3448 case Int:
3449 return "int";
3450 case Long:
3451 return "long";
3452 case LongLong:
3453 return "long long";
3454 case Int128:
3455 return "__int128";
3456 case UChar:
3457 return "unsigned char";
3458 case UShort:
3459 return "unsigned short";
3460 case UInt:
3461 return "unsigned int";
3462 case ULong:
3463 return "unsigned long";
3464 case ULongLong:
3465 return "unsigned long long";
3466 case UInt128:
3467 return "unsigned __int128";
3468 case Half:
3469 return Policy.Half ? "half" : "__fp16";
3470 case BFloat16:
3471 return "__bf16";
3472 case Float:
3473 return "float";
3474 case Double:
3475 return "double";
3476 case LongDouble:
3477 return "long double";
3478 case ShortAccum:
3479 return "short _Accum";
3480 case Accum:
3481 return "_Accum";
3482 case LongAccum:
3483 return "long _Accum";
3484 case UShortAccum:
3485 return "unsigned short _Accum";
3486 case UAccum:
3487 return "unsigned _Accum";
3488 case ULongAccum:
3489 return "unsigned long _Accum";
3490 case BuiltinType::ShortFract:
3491 return "short _Fract";
3492 case BuiltinType::Fract:
3493 return "_Fract";
3494 case BuiltinType::LongFract:
3495 return "long _Fract";
3496 case BuiltinType::UShortFract:
3497 return "unsigned short _Fract";
3498 case BuiltinType::UFract:
3499 return "unsigned _Fract";
3500 case BuiltinType::ULongFract:
3501 return "unsigned long _Fract";
3502 case BuiltinType::SatShortAccum:
3503 return "_Sat short _Accum";
3504 case BuiltinType::SatAccum:
3505 return "_Sat _Accum";
3506 case BuiltinType::SatLongAccum:
3507 return "_Sat long _Accum";
3508 case BuiltinType::SatUShortAccum:
3509 return "_Sat unsigned short _Accum";
3510 case BuiltinType::SatUAccum:
3511 return "_Sat unsigned _Accum";
3512 case BuiltinType::SatULongAccum:
3513 return "_Sat unsigned long _Accum";
3514 case BuiltinType::SatShortFract:
3515 return "_Sat short _Fract";
3516 case BuiltinType::SatFract:
3517 return "_Sat _Fract";
3518 case BuiltinType::SatLongFract:
3519 return "_Sat long _Fract";
3520 case BuiltinType::SatUShortFract:
3521 return "_Sat unsigned short _Fract";
3522 case BuiltinType::SatUFract:
3523 return "_Sat unsigned _Fract";
3524 case BuiltinType::SatULongFract:
3525 return "_Sat unsigned long _Fract";
3526 case Float16:
3527 return "_Float16";
3528 case Float128:
3529 return "__float128";
3530 case Ibm128:
3531 return "__ibm128";
3532 case WChar_S:
3533 case WChar_U:
3534 return Policy.MSWChar ? "__wchar_t" : "wchar_t";
3535 case Char8:
3536 return "char8_t";
3537 case Char16:
3538 return "char16_t";
3539 case Char32:
3540 return "char32_t";
3541 case NullPtr:
3542 return Policy.NullptrTypeInNamespace ? "std::nullptr_t" : "nullptr_t";
3543 case Overload:
3544 return "<overloaded function type>";
3545 case BoundMember:
3546 return "<bound member function type>";
3547 case UnresolvedTemplate:
3548 return "<unresolved template type>";
3549 case PseudoObject:
3550 return "<pseudo-object type>";
3551 case Dependent:
3552 return "<dependent type>";
3553 case UnknownAny:
3554 return "<unknown type>";
3555 case ARCUnbridgedCast:
3556 return "<ARC unbridged cast type>";
3557 case BuiltinFn:
3558 return "<builtin fn type>";
3559 case ObjCId:
3560 return "id";
3561 case ObjCClass:
3562 return "Class";
3563 case ObjCSel:
3564 return "SEL";
3565#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3566 case Id: \
3567 return "__" #Access " " #ImgType "_t";
3568#include "clang/Basic/OpenCLImageTypes.def"
3569 case OCLSampler:
3570 return "sampler_t";
3571 case OCLEvent:
3572 return "event_t";
3573 case OCLClkEvent:
3574 return "clk_event_t";
3575 case OCLQueue:
3576 return "queue_t";
3577 case OCLReserveID:
3578 return "reserve_id_t";
3579 case IncompleteMatrixIdx:
3580 return "<incomplete matrix index type>";
3581 case ArraySection:
3582 return "<array section type>";
3583 case OMPArrayShaping:
3584 return "<OpenMP array shaping type>";
3585 case OMPIterator:
3586 return "<OpenMP iterator type>";
3587#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3588 case Id: \
3589 return #ExtType;
3590#include "clang/Basic/OpenCLExtensionTypes.def"
3591#define SVE_TYPE(Name, Id, SingletonId) \
3592 case Id: \
3593 return #Name;
3594#include "clang/Basic/AArch64ACLETypes.def"
3595#define PPC_VECTOR_TYPE(Name, Id, Size) \
3596 case Id: \
3597 return #Name;
3598#include "clang/Basic/PPCTypes.def"
3599#define RVV_TYPE(Name, Id, SingletonId) \
3600 case Id: \
3601 return Name;
3602#include "clang/Basic/RISCVVTypes.def"
3603#define WASM_TYPE(Name, Id, SingletonId) \
3604 case Id: \
3605 return Name;
3606#include "clang/Basic/WebAssemblyReferenceTypes.def"
3607#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) \
3608 case Id: \
3609 return Name;
3610#include "clang/Basic/AMDGPUTypes.def"
3611#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
3612 case Id: \
3613 return #Name;
3614#include "clang/Basic/HLSLIntangibleTypes.def"
3615 }
3616
3617 llvm_unreachable("Invalid builtin type.");
3618}
3619
3620QualType QualType::getNonPackExpansionType() const {
3621 // We never wrap type sugar around a PackExpansionType.
3622 if (auto *PET = dyn_cast<PackExpansionType>(Val: getTypePtr()))
3623 return PET->getPattern();
3624 return *this;
3625}
3626
3627QualType QualType::getNonLValueExprType(const ASTContext &Context) const {
3628 if (const auto *RefType = getTypePtr()->getAs<ReferenceType>())
3629 return RefType->getPointeeType();
3630
3631 // C++0x [basic.lval]:
3632 // Class prvalues can have cv-qualified types; non-class prvalues always
3633 // have cv-unqualified types.
3634 //
3635 // See also C99 6.3.2.1p2.
3636 if (!Context.getLangOpts().CPlusPlus ||
3637 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
3638 return getUnqualifiedType();
3639
3640 return *this;
3641}
3642
3643bool FunctionType::getCFIUncheckedCalleeAttr() const {
3644 if (const auto *FPT = getAs<FunctionProtoType>())
3645 return FPT->hasCFIUncheckedCallee();
3646 return false;
3647}
3648
3649StringRef FunctionType::getNameForCallConv(CallingConv CC) {
3650 switch (CC) {
3651 case CC_C:
3652 return "cdecl";
3653 case CC_X86StdCall:
3654 return "stdcall";
3655 case CC_X86FastCall:
3656 return "fastcall";
3657 case CC_X86ThisCall:
3658 return "thiscall";
3659 case CC_X86Pascal:
3660 return "pascal";
3661 case CC_X86VectorCall:
3662 return "vectorcall";
3663 case CC_Win64:
3664 return "ms_abi";
3665 case CC_X86_64SysV:
3666 return "sysv_abi";
3667 case CC_X86RegCall:
3668 return "regcall";
3669 case CC_AAPCS:
3670 return "aapcs";
3671 case CC_AAPCS_VFP:
3672 return "aapcs-vfp";
3673 case CC_AArch64VectorCall:
3674 return "aarch64_vector_pcs";
3675 case CC_AArch64SVEPCS:
3676 return "aarch64_sve_pcs";
3677 case CC_IntelOclBicc:
3678 return "intel_ocl_bicc";
3679 case CC_SpirFunction:
3680 return "spir_function";
3681 case CC_DeviceKernel:
3682 return "device_kernel";
3683 case CC_Swift:
3684 return "swiftcall";
3685 case CC_SwiftAsync:
3686 return "swiftasynccall";
3687 case CC_PreserveMost:
3688 return "preserve_most";
3689 case CC_PreserveAll:
3690 return "preserve_all";
3691 case CC_M68kRTD:
3692 return "m68k_rtd";
3693 case CC_PreserveNone:
3694 return "preserve_none";
3695 // clang-format off
3696 case CC_RISCVVectorCall: return "riscv_vector_cc";
3697#define CC_VLS_CASE(ABI_VLEN) \
3698 case CC_RISCVVLSCall_##ABI_VLEN: return "riscv_vls_cc(" #ABI_VLEN ")";
3699 CC_VLS_CASE(32)
3700 CC_VLS_CASE(64)
3701 CC_VLS_CASE(128)
3702 CC_VLS_CASE(256)
3703 CC_VLS_CASE(512)
3704 CC_VLS_CASE(1024)
3705 CC_VLS_CASE(2048)
3706 CC_VLS_CASE(4096)
3707 CC_VLS_CASE(8192)
3708 CC_VLS_CASE(16384)
3709 CC_VLS_CASE(32768)
3710 CC_VLS_CASE(65536)
3711#undef CC_VLS_CASE
3712 // clang-format on
3713 }
3714
3715 llvm_unreachable("Invalid calling convention.");
3716}
3717
3718void FunctionProtoType::ExceptionSpecInfo::instantiate() {
3719 assert(Type == EST_Uninstantiated);
3720 NoexceptExpr =
3721 cast<FunctionProtoType>(Val: SourceTemplate->getType())->getNoexceptExpr();
3722 Type = EST_DependentNoexcept;
3723}
3724
3725FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> params,
3726 QualType canonical,
3727 const ExtProtoInfo &epi)
3728 : FunctionType(FunctionProto, result, canonical, result->getDependence(),
3729 epi.ExtInfo) {
3730 FunctionTypeBits.FastTypeQuals = epi.TypeQuals.getFastQualifiers();
3731 FunctionTypeBits.RefQualifier = epi.RefQualifier;
3732 FunctionTypeBits.NumParams = params.size();
3733 assert(getNumParams() == params.size() && "NumParams overflow!");
3734 FunctionTypeBits.ExceptionSpecType = epi.ExceptionSpec.Type;
3735 FunctionTypeBits.HasExtParameterInfos = !!epi.ExtParameterInfos;
3736 FunctionTypeBits.Variadic = epi.Variadic;
3737 FunctionTypeBits.HasTrailingReturn = epi.HasTrailingReturn;
3738 FunctionTypeBits.CFIUncheckedCallee = epi.CFIUncheckedCallee;
3739
3740 if (epi.requiresFunctionProtoTypeExtraBitfields()) {
3741 FunctionTypeBits.HasExtraBitfields = true;
3742 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
3743 ExtraBits = FunctionTypeExtraBitfields();
3744 } else {
3745 FunctionTypeBits.HasExtraBitfields = false;
3746 }
3747
3748 // Propagate any extra attribute information.
3749 if (epi.requiresFunctionProtoTypeExtraAttributeInfo()) {
3750 auto &ExtraAttrInfo = *getTrailingObjects<FunctionTypeExtraAttributeInfo>();
3751 ExtraAttrInfo.CFISalt = epi.ExtraAttributeInfo.CFISalt;
3752
3753 // Also set the bit in FunctionTypeExtraBitfields.
3754 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
3755 ExtraBits.HasExtraAttributeInfo = true;
3756 }
3757
3758 if (epi.requiresFunctionProtoTypeArmAttributes()) {
3759 auto &ArmTypeAttrs = *getTrailingObjects<FunctionTypeArmAttributes>();
3760 ArmTypeAttrs = FunctionTypeArmAttributes();
3761
3762 // Also set the bit in FunctionTypeExtraBitfields
3763 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
3764 ExtraBits.HasArmTypeAttributes = true;
3765 }
3766
3767 // Fill in the trailing argument array.
3768 auto *argSlot = getTrailingObjects<QualType>();
3769 for (unsigned i = 0; i != getNumParams(); ++i) {
3770 addDependence(D: params[i]->getDependence() &
3771 ~TypeDependence::VariablyModified);
3772 argSlot[i] = params[i];
3773 }
3774
3775 // Propagate the SME ACLE attributes.
3776 if (epi.AArch64SMEAttributes != SME_NormalFunction) {
3777 auto &ArmTypeAttrs = *getTrailingObjects<FunctionTypeArmAttributes>();
3778 assert(epi.AArch64SMEAttributes <= SME_AttributeMask &&
3779 "Not enough bits to encode SME attributes");
3780 ArmTypeAttrs.AArch64SMEAttributes = epi.AArch64SMEAttributes;
3781 }
3782
3783 // Fill in the exception type array if present.
3784 if (getExceptionSpecType() == EST_Dynamic) {
3785 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
3786 size_t NumExceptions = epi.ExceptionSpec.Exceptions.size();
3787 assert(NumExceptions <= 1023 && "Not enough bits to encode exceptions");
3788 ExtraBits.NumExceptionType = NumExceptions;
3789
3790 assert(hasExtraBitfields() && "missing trailing extra bitfields!");
3791 auto *exnSlot =
3792 reinterpret_cast<QualType *>(getTrailingObjects<ExceptionType>());
3793 unsigned I = 0;
3794 for (QualType ExceptionType : epi.ExceptionSpec.Exceptions) {
3795 // Note that, before C++17, a dependent exception specification does
3796 // *not* make a type dependent; it's not even part of the C++ type
3797 // system.
3798 addDependence(
3799 D: ExceptionType->getDependence() &
3800 (TypeDependence::Instantiation | TypeDependence::UnexpandedPack));
3801
3802 exnSlot[I++] = ExceptionType;
3803 }
3804 }
3805 // Fill in the Expr * in the exception specification if present.
3806 else if (isComputedNoexcept(ESpecType: getExceptionSpecType())) {
3807 assert(epi.ExceptionSpec.NoexceptExpr && "computed noexcept with no expr");
3808 assert((getExceptionSpecType() == EST_DependentNoexcept) ==
3809 epi.ExceptionSpec.NoexceptExpr->isValueDependent());
3810
3811 // Store the noexcept expression and context.
3812 *getTrailingObjects<Expr *>() = epi.ExceptionSpec.NoexceptExpr;
3813
3814 addDependence(
3815 D: toTypeDependence(D: epi.ExceptionSpec.NoexceptExpr->getDependence()) &
3816 (TypeDependence::Instantiation | TypeDependence::UnexpandedPack));
3817 }
3818 // Fill in the FunctionDecl * in the exception specification if present.
3819 else if (getExceptionSpecType() == EST_Uninstantiated) {
3820 // Store the function decl from which we will resolve our
3821 // exception specification.
3822 auto **slot = getTrailingObjects<FunctionDecl *>();
3823 slot[0] = epi.ExceptionSpec.SourceDecl;
3824 slot[1] = epi.ExceptionSpec.SourceTemplate;
3825 // This exception specification doesn't make the type dependent, because
3826 // it's not instantiated as part of instantiating the type.
3827 } else if (getExceptionSpecType() == EST_Unevaluated) {
3828 // Store the function decl from which we will resolve our
3829 // exception specification.
3830 auto **slot = getTrailingObjects<FunctionDecl *>();
3831 slot[0] = epi.ExceptionSpec.SourceDecl;
3832 }
3833
3834 // If this is a canonical type, and its exception specification is dependent,
3835 // then it's a dependent type. This only happens in C++17 onwards.
3836 if (isCanonicalUnqualified()) {
3837 if (getExceptionSpecType() == EST_Dynamic ||
3838 getExceptionSpecType() == EST_DependentNoexcept) {
3839 assert(hasDependentExceptionSpec() && "type should not be canonical");
3840 addDependence(D: TypeDependence::DependentInstantiation);
3841 }
3842 } else if (getCanonicalTypeInternal()->isDependentType()) {
3843 // Ask our canonical type whether our exception specification was dependent.
3844 addDependence(D: TypeDependence::DependentInstantiation);
3845 }
3846
3847 // Fill in the extra parameter info if present.
3848 if (epi.ExtParameterInfos) {
3849 auto *extParamInfos = getTrailingObjects<ExtParameterInfo>();
3850 for (unsigned i = 0; i != getNumParams(); ++i)
3851 extParamInfos[i] = epi.ExtParameterInfos[i];
3852 }
3853
3854 if (epi.TypeQuals.hasNonFastQualifiers()) {
3855 FunctionTypeBits.HasExtQuals = 1;
3856 *getTrailingObjects<Qualifiers>() = epi.TypeQuals;
3857 } else {
3858 FunctionTypeBits.HasExtQuals = 0;
3859 }
3860
3861 // Fill in the Ellipsis location info if present.
3862 if (epi.Variadic) {
3863 auto &EllipsisLoc = *getTrailingObjects<SourceLocation>();
3864 EllipsisLoc = epi.EllipsisLoc;
3865 }
3866
3867 if (!epi.FunctionEffects.empty()) {
3868 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
3869 size_t EffectsCount = epi.FunctionEffects.size();
3870 ExtraBits.NumFunctionEffects = EffectsCount;
3871 assert(ExtraBits.NumFunctionEffects == EffectsCount &&
3872 "effect bitfield overflow");
3873
3874 ArrayRef<FunctionEffect> SrcFX = epi.FunctionEffects.effects();
3875 auto *DestFX = getTrailingObjects<FunctionEffect>();
3876 llvm::uninitialized_copy(Src&: SrcFX, Dst: DestFX);
3877
3878 ArrayRef<EffectConditionExpr> SrcConds = epi.FunctionEffects.conditions();
3879 if (!SrcConds.empty()) {
3880 ExtraBits.EffectsHaveConditions = true;
3881 auto *DestConds = getTrailingObjects<EffectConditionExpr>();
3882 llvm::uninitialized_copy(Src&: SrcConds, Dst: DestConds);
3883 assert(llvm::any_of(SrcConds,
3884 [](const EffectConditionExpr &EC) {
3885 if (const Expr *E = EC.getCondition())
3886 return E->isTypeDependent() ||
3887 E->isValueDependent();
3888 return false;
3889 }) &&
3890 "expected a dependent expression among the conditions");
3891 addDependence(D: TypeDependence::DependentInstantiation);
3892 }
3893 }
3894}
3895
3896bool FunctionProtoType::hasDependentExceptionSpec() const {
3897 if (Expr *NE = getNoexceptExpr())
3898 return NE->isValueDependent();
3899 for (QualType ET : exceptions())
3900 // A pack expansion with a non-dependent pattern is still dependent,
3901 // because we don't know whether the pattern is in the exception spec
3902 // or not (that depends on whether the pack has 0 expansions).
3903 if (ET->isDependentType() || ET->getAs<PackExpansionType>())
3904 return true;
3905 return false;
3906}
3907
3908bool FunctionProtoType::hasInstantiationDependentExceptionSpec() const {
3909 if (Expr *NE = getNoexceptExpr())
3910 return NE->isInstantiationDependent();
3911 for (QualType ET : exceptions())
3912 if (ET->isInstantiationDependentType())
3913 return true;
3914 return false;
3915}
3916
3917CanThrowResult FunctionProtoType::canThrow() const {
3918 switch (getExceptionSpecType()) {
3919 case EST_Unparsed:
3920 case EST_Unevaluated:
3921 llvm_unreachable("should not call this with unresolved exception specs");
3922
3923 case EST_DynamicNone:
3924 case EST_BasicNoexcept:
3925 case EST_NoexceptTrue:
3926 case EST_NoThrow:
3927 return CT_Cannot;
3928
3929 case EST_None:
3930 case EST_MSAny:
3931 case EST_NoexceptFalse:
3932 return CT_Can;
3933
3934 case EST_Dynamic:
3935 // A dynamic exception specification is throwing unless every exception
3936 // type is an (unexpanded) pack expansion type.
3937 for (unsigned I = 0; I != getNumExceptions(); ++I)
3938 if (!getExceptionType(i: I)->getAs<PackExpansionType>())
3939 return CT_Can;
3940 return CT_Dependent;
3941
3942 case EST_Uninstantiated:
3943 case EST_DependentNoexcept:
3944 return CT_Dependent;
3945 }
3946
3947 llvm_unreachable("unexpected exception specification kind");
3948}
3949
3950bool FunctionProtoType::isTemplateVariadic() const {
3951 for (unsigned ArgIdx = getNumParams(); ArgIdx; --ArgIdx)
3952 if (isa<PackExpansionType>(Val: getParamType(i: ArgIdx - 1)))
3953 return true;
3954
3955 return false;
3956}
3957
3958void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
3959 const QualType *ArgTys, unsigned NumParams,
3960 const ExtProtoInfo &epi,
3961 const ASTContext &Context, bool Canonical) {
3962 // We have to be careful not to get ambiguous profile encodings.
3963 // Note that valid type pointers are never ambiguous with anything else.
3964 //
3965 // The encoding grammar begins:
3966 // type type* bool int bool
3967 // If that final bool is true, then there is a section for the EH spec:
3968 // bool type*
3969 // This is followed by an optional "consumed argument" section of the
3970 // same length as the first type sequence:
3971 // bool*
3972 // This is followed by the ext info:
3973 // int
3974 // Finally we have a trailing return type flag (bool)
3975 // combined with AArch64 SME Attributes and extra attribute info, to save
3976 // space:
3977 // int
3978 // combined with any FunctionEffects
3979 //
3980 // There is no ambiguity between the consumed arguments and an empty EH
3981 // spec because of the leading 'bool' which unambiguously indicates
3982 // whether the following bool is the EH spec or part of the arguments.
3983
3984 ID.AddPointer(Ptr: Result.getAsOpaquePtr());
3985 for (unsigned i = 0; i != NumParams; ++i)
3986 ID.AddPointer(Ptr: ArgTys[i].getAsOpaquePtr());
3987 // This method is relatively performance sensitive, so as a performance
3988 // shortcut, use one AddInteger call instead of four for the next four
3989 // fields.
3990 assert(!(unsigned(epi.Variadic) & ~1) && !(unsigned(epi.RefQualifier) & ~3) &&
3991 !(unsigned(epi.ExceptionSpec.Type) & ~15) &&
3992 "Values larger than expected.");
3993 ID.AddInteger(I: unsigned(epi.Variadic) + (epi.RefQualifier << 1) +
3994 (epi.ExceptionSpec.Type << 3));
3995 ID.Add(x: epi.TypeQuals);
3996 if (epi.ExceptionSpec.Type == EST_Dynamic) {
3997 for (QualType Ex : epi.ExceptionSpec.Exceptions)
3998 ID.AddPointer(Ptr: Ex.getAsOpaquePtr());
3999 } else if (isComputedNoexcept(ESpecType: epi.ExceptionSpec.Type)) {
4000 epi.ExceptionSpec.NoexceptExpr->Profile(ID, Context, Canonical);
4001 } else if (epi.ExceptionSpec.Type == EST_Uninstantiated ||
4002 epi.ExceptionSpec.Type == EST_Unevaluated) {
4003 ID.AddPointer(Ptr: epi.ExceptionSpec.SourceDecl->getCanonicalDecl());
4004 }
4005 if (epi.ExtParameterInfos) {
4006 for (unsigned i = 0; i != NumParams; ++i)
4007 ID.AddInteger(I: epi.ExtParameterInfos[i].getOpaqueValue());
4008 }
4009
4010 epi.ExtInfo.Profile(ID);
4011 epi.ExtraAttributeInfo.Profile(ID);
4012
4013 unsigned EffectCount = epi.FunctionEffects.size();
4014 bool HasConds = !epi.FunctionEffects.Conditions.empty();
4015
4016 ID.AddInteger(I: (EffectCount << 3) | (HasConds << 2) |
4017 (epi.AArch64SMEAttributes << 1) | epi.HasTrailingReturn);
4018 ID.AddInteger(I: epi.CFIUncheckedCallee);
4019
4020 for (unsigned Idx = 0; Idx != EffectCount; ++Idx) {
4021 ID.AddInteger(I: epi.FunctionEffects.Effects[Idx].toOpaqueInt32());
4022 if (HasConds)
4023 ID.AddPointer(Ptr: epi.FunctionEffects.Conditions[Idx].getCondition());
4024 }
4025}
4026
4027void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
4028 const ASTContext &Ctx) {
4029 Profile(ID, Result: getReturnType(), ArgTys: param_type_begin(), NumParams: getNumParams(),
4030 epi: getExtProtoInfo(), Context: Ctx, Canonical: isCanonicalUnqualified());
4031}
4032
4033TypeCoupledDeclRefInfo::TypeCoupledDeclRefInfo(ValueDecl *D, bool Deref)
4034 : Data(D, Deref << DerefShift) {}
4035
4036bool TypeCoupledDeclRefInfo::isDeref() const {
4037 return Data.getInt() & DerefMask;
4038}
4039ValueDecl *TypeCoupledDeclRefInfo::getDecl() const { return Data.getPointer(); }
4040unsigned TypeCoupledDeclRefInfo::getInt() const { return Data.getInt(); }
4041void *TypeCoupledDeclRefInfo::getOpaqueValue() const {
4042 return Data.getOpaqueValue();
4043}
4044bool TypeCoupledDeclRefInfo::operator==(
4045 const TypeCoupledDeclRefInfo &Other) const {
4046 return getOpaqueValue() == Other.getOpaqueValue();
4047}
4048void TypeCoupledDeclRefInfo::setFromOpaqueValue(void *V) {
4049 Data.setFromOpaqueValue(V);
4050}
4051
4052OverflowBehaviorType::OverflowBehaviorType(
4053 QualType Canon, QualType Underlying,
4054 OverflowBehaviorType::OverflowBehaviorKind Kind)
4055 : Type(OverflowBehavior, Canon, Underlying->getDependence()),
4056 UnderlyingType(Underlying), BehaviorKind(Kind) {}
4057
4058BoundsAttributedType::BoundsAttributedType(TypeClass TC, QualType Wrapped,
4059 QualType Canon)
4060 : Type(TC, Canon, Wrapped->getDependence()), WrappedTy(Wrapped) {}
4061
4062CountAttributedType::CountAttributedType(
4063 QualType Wrapped, QualType Canon, Expr *CountExpr, bool CountInBytes,
4064 bool OrNull, ArrayRef<TypeCoupledDeclRefInfo> CoupledDecls)
4065 : BoundsAttributedType(CountAttributed, Wrapped, Canon),
4066 CountExpr(CountExpr) {
4067 CountAttributedTypeBits.NumCoupledDecls = CoupledDecls.size();
4068 CountAttributedTypeBits.CountInBytes = CountInBytes;
4069 CountAttributedTypeBits.OrNull = OrNull;
4070 auto *DeclSlot = getTrailingObjects();
4071 llvm::copy(Range&: CoupledDecls, Out: DeclSlot);
4072 Decls = llvm::ArrayRef(DeclSlot, CoupledDecls.size());
4073}
4074
4075StringRef CountAttributedType::getAttributeName(bool WithMacroPrefix) const {
4076// TODO: This method isn't really ideal because it doesn't return the spelling
4077// of the attribute that was used in the user's code. This method is used for
4078// diagnostics so the fact it doesn't use the spelling of the attribute in
4079// the user's code could be confusing (#113585).
4080#define ENUMERATE_ATTRS(PREFIX) \
4081 do { \
4082 if (isCountInBytes()) { \
4083 if (isOrNull()) \
4084 return PREFIX "sized_by_or_null"; \
4085 return PREFIX "sized_by"; \
4086 } \
4087 if (isOrNull()) \
4088 return PREFIX "counted_by_or_null"; \
4089 return PREFIX "counted_by"; \
4090 } while (0)
4091
4092 if (WithMacroPrefix)
4093 ENUMERATE_ATTRS("__");
4094 else
4095 ENUMERATE_ATTRS("");
4096
4097#undef ENUMERATE_ATTRS
4098}
4099
4100TypedefType::TypedefType(TypeClass TC, ElaboratedTypeKeyword Keyword,
4101 NestedNameSpecifier Qualifier,
4102 const TypedefNameDecl *D, QualType UnderlyingType,
4103 bool HasTypeDifferentFromDecl)
4104 : TypeWithKeyword(
4105 Keyword, TC, UnderlyingType.getCanonicalType(),
4106 toSemanticDependence(D: UnderlyingType->getDependence()) |
4107 (Qualifier
4108 ? toTypeDependence(D: Qualifier.getDependence() &
4109 ~NestedNameSpecifierDependence::Dependent)
4110 : TypeDependence{})),
4111 Decl(const_cast<TypedefNameDecl *>(D)) {
4112 if ((TypedefBits.hasQualifier = !!Qualifier))
4113 *getTrailingObjects<NestedNameSpecifier>() = Qualifier;
4114 if ((TypedefBits.hasTypeDifferentFromDecl = HasTypeDifferentFromDecl))
4115 *getTrailingObjects<QualType>() = UnderlyingType;
4116}
4117
4118QualType TypedefType::desugar() const {
4119 return typeMatchesDecl() ? Decl->getUnderlyingType()
4120 : *getTrailingObjects<QualType>();
4121}
4122
4123UnresolvedUsingType::UnresolvedUsingType(ElaboratedTypeKeyword Keyword,
4124 NestedNameSpecifier Qualifier,
4125 const UnresolvedUsingTypenameDecl *D,
4126 const Type *CanonicalType)
4127 : TypeWithKeyword(
4128 Keyword, UnresolvedUsing, QualType(CanonicalType, 0),
4129 TypeDependence::DependentInstantiation |
4130 (Qualifier
4131 ? toTypeDependence(D: Qualifier.getDependence() &
4132 ~NestedNameSpecifierDependence::Dependent)
4133 : TypeDependence{})),
4134 Decl(const_cast<UnresolvedUsingTypenameDecl *>(D)) {
4135 if ((UnresolvedUsingBits.hasQualifier = !!Qualifier))
4136 *getTrailingObjects<NestedNameSpecifier>() = Qualifier;
4137}
4138
4139UsingType::UsingType(ElaboratedTypeKeyword Keyword,
4140 NestedNameSpecifier Qualifier, const UsingShadowDecl *D,
4141 QualType UnderlyingType)
4142 : TypeWithKeyword(Keyword, Using, UnderlyingType.getCanonicalType(),
4143 toSemanticDependence(D: UnderlyingType->getDependence())),
4144 D(const_cast<UsingShadowDecl *>(D)), UnderlyingType(UnderlyingType) {
4145 if ((UsingBits.hasQualifier = !!Qualifier))
4146 *getTrailingObjects() = Qualifier;
4147}
4148
4149QualType MacroQualifiedType::desugar() const { return getUnderlyingType(); }
4150
4151QualType MacroQualifiedType::getModifiedType() const {
4152 // Step over MacroQualifiedTypes from the same macro to find the type
4153 // ultimately qualified by the macro qualifier.
4154 QualType Inner = cast<AttributedType>(Val: getUnderlyingType())->getModifiedType();
4155 while (auto *InnerMQT = dyn_cast<MacroQualifiedType>(Val&: Inner)) {
4156 if (InnerMQT->getMacroIdentifier() != getMacroIdentifier())
4157 break;
4158 Inner = InnerMQT->getModifiedType();
4159 }
4160 return Inner;
4161}
4162
4163TypeOfExprType::TypeOfExprType(const ASTContext &Context, Expr *E,
4164 TypeOfKind Kind, QualType Can)
4165 : Type(TypeOfExpr,
4166 // We have to protect against 'Can' being invalid through its
4167 // default argument.
4168 Kind == TypeOfKind::Unqualified && !Can.isNull()
4169 ? Context.getUnqualifiedArrayType(T: Can).getAtomicUnqualifiedType()
4170 : Can,
4171 toTypeDependence(D: E->getDependence()) |
4172 (E->getType()->getDependence() &
4173 TypeDependence::VariablyModified)),
4174 TOExpr(E), Context(Context) {
4175 TypeOfBits.Kind = static_cast<unsigned>(Kind);
4176}
4177
4178bool TypeOfExprType::isSugared() const { return !TOExpr->isTypeDependent(); }
4179
4180QualType TypeOfExprType::desugar() const {
4181 if (isSugared()) {
4182 QualType QT = getUnderlyingExpr()->getType();
4183 return getKind() == TypeOfKind::Unqualified
4184 ? Context.getUnqualifiedArrayType(T: QT).getAtomicUnqualifiedType()
4185 : QT;
4186 }
4187 return QualType(this, 0);
4188}
4189
4190void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
4191 const ASTContext &Context, Expr *E,
4192 bool IsUnqual) {
4193 E->Profile(ID, Context, Canonical: true);
4194 ID.AddBoolean(B: IsUnqual);
4195}
4196
4197TypeOfType::TypeOfType(const ASTContext &Context, QualType T, QualType Can,
4198 TypeOfKind Kind)
4199 : Type(TypeOf,
4200 Kind == TypeOfKind::Unqualified
4201 ? Context.getUnqualifiedArrayType(T: Can).getAtomicUnqualifiedType()
4202 : Can,
4203 T->getDependence()),
4204 TOType(T), Context(Context) {
4205 TypeOfBits.Kind = static_cast<unsigned>(Kind);
4206}
4207
4208QualType TypeOfType::desugar() const {
4209 QualType QT = getUnmodifiedType();
4210 return getKind() == TypeOfKind::Unqualified
4211 ? Context.getUnqualifiedArrayType(T: QT).getAtomicUnqualifiedType()
4212 : QT;
4213}
4214
4215DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
4216 // C++11 [temp.type]p2: "If an expression e involves a template parameter,
4217 // decltype(e) denotes a unique dependent type." Hence a decltype type is
4218 // type-dependent even if its expression is only instantiation-dependent.
4219 : Type(Decltype, can,
4220 toTypeDependence(D: E->getDependence()) |
4221 (E->isInstantiationDependent() ? TypeDependence::Dependent
4222 : TypeDependence::None) |
4223 (E->getType()->getDependence() &
4224 TypeDependence::VariablyModified)),
4225 E(E), UnderlyingType(underlyingType) {}
4226
4227bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); }
4228
4229QualType DecltypeType::desugar() const {
4230 if (isSugared())
4231 return getUnderlyingType();
4232
4233 return QualType(this, 0);
4234}
4235
4236DependentDecltypeType::DependentDecltypeType(Expr *E)
4237 : DecltypeType(E, QualType()) {}
4238
4239void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
4240 const ASTContext &Context, Expr *E) {
4241 E->Profile(ID, Context, Canonical: true);
4242}
4243
4244PackIndexingType::PackIndexingType(QualType Canonical, QualType Pattern,
4245 Expr *IndexExpr, bool FullySubstituted,
4246 ArrayRef<QualType> Expansions)
4247 : Type(PackIndexing, Canonical,
4248 computeDependence(Pattern, IndexExpr, Expansions)),
4249 Pattern(Pattern), IndexExpr(IndexExpr), Size(Expansions.size()),
4250 FullySubstituted(FullySubstituted) {
4251
4252 llvm::uninitialized_copy(Src&: Expansions, Dst: getTrailingObjects());
4253}
4254
4255UnsignedOrNone PackIndexingType::getSelectedIndex() const {
4256 if (isInstantiationDependentType())
4257 return std::nullopt;
4258 // Should only be not a constant for error recovery.
4259 ConstantExpr *CE = dyn_cast<ConstantExpr>(Val: getIndexExpr());
4260 if (!CE)
4261 return std::nullopt;
4262 auto Index = CE->getResultAsAPSInt();
4263 assert(Index.isNonNegative() && "Invalid index");
4264 return static_cast<unsigned>(Index.getExtValue());
4265}
4266
4267TypeDependence
4268PackIndexingType::computeDependence(QualType Pattern, Expr *IndexExpr,
4269 ArrayRef<QualType> Expansions) {
4270 TypeDependence IndexD = toTypeDependence(D: IndexExpr->getDependence());
4271
4272 TypeDependence TD = IndexD | (IndexExpr->isInstantiationDependent()
4273 ? TypeDependence::DependentInstantiation
4274 : TypeDependence::None);
4275 if (Expansions.empty())
4276 TD |= Pattern->getDependence() & TypeDependence::DependentInstantiation;
4277 else
4278 for (const QualType &T : Expansions)
4279 TD |= T->getDependence();
4280
4281 if (!(IndexD & TypeDependence::UnexpandedPack))
4282 TD &= ~TypeDependence::UnexpandedPack;
4283
4284 // If the pattern does not contain an unexpended pack,
4285 // the type is still dependent, and invalid
4286 if (!Pattern->containsUnexpandedParameterPack())
4287 TD |= TypeDependence::Error | TypeDependence::DependentInstantiation;
4288
4289 return TD;
4290}
4291
4292void PackIndexingType::Profile(llvm::FoldingSetNodeID &ID,
4293 const ASTContext &Context) {
4294 Profile(ID, Context, Pattern: getPattern(), E: getIndexExpr(), FullySubstituted: isFullySubstituted(),
4295 Expansions: getExpansions());
4296}
4297
4298void PackIndexingType::Profile(llvm::FoldingSetNodeID &ID,
4299 const ASTContext &Context, QualType Pattern,
4300 Expr *E, bool FullySubstituted,
4301 ArrayRef<QualType> Expansions) {
4302
4303 E->Profile(ID, Context, Canonical: true);
4304 ID.AddBoolean(B: FullySubstituted);
4305 if (!Expansions.empty()) {
4306 ID.AddInteger(I: Expansions.size());
4307 for (QualType T : Expansions)
4308 T.getCanonicalType().Profile(ID);
4309 } else {
4310 Pattern.Profile(ID);
4311 }
4312}
4313
4314UnaryTransformType::UnaryTransformType(QualType BaseType,
4315 QualType UnderlyingType, UTTKind UKind,
4316 QualType CanonicalType)
4317 : Type(UnaryTransform, CanonicalType, BaseType->getDependence()),
4318 BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind) {}
4319
4320TagType::TagType(TypeClass TC, ElaboratedTypeKeyword Keyword,
4321 NestedNameSpecifier Qualifier, const TagDecl *Tag,
4322 bool OwnsTag, bool ISInjected, const Type *CanonicalType)
4323 : TypeWithKeyword(
4324 Keyword, TC, QualType(CanonicalType, 0),
4325 (Tag->isDependentType() ? TypeDependence::DependentInstantiation
4326 : TypeDependence::None) |
4327 (Qualifier
4328 ? toTypeDependence(D: Qualifier.getDependence() &
4329 ~NestedNameSpecifierDependence::Dependent)
4330 : TypeDependence{})),
4331 decl(const_cast<TagDecl *>(Tag)) {
4332 if ((TagTypeBits.HasQualifier = !!Qualifier))
4333 getTrailingQualifier() = Qualifier;
4334 TagTypeBits.OwnsTag = !!OwnsTag;
4335 TagTypeBits.IsInjected = ISInjected;
4336}
4337
4338void *TagType::getTrailingPointer() const {
4339 switch (getTypeClass()) {
4340 case Type::Enum:
4341 return const_cast<EnumType *>(cast<EnumType>(Val: this) + 1);
4342 case Type::Record:
4343 return const_cast<RecordType *>(cast<RecordType>(Val: this) + 1);
4344 case Type::InjectedClassName:
4345 return const_cast<InjectedClassNameType *>(
4346 cast<InjectedClassNameType>(Val: this) + 1);
4347 default:
4348 llvm_unreachable("unexpected type class");
4349 }
4350}
4351
4352NestedNameSpecifier &TagType::getTrailingQualifier() const {
4353 assert(TagTypeBits.HasQualifier);
4354 return *reinterpret_cast<NestedNameSpecifier *>(llvm::alignAddr(
4355 Addr: getTrailingPointer(), Alignment: llvm::Align::Of<NestedNameSpecifier *>()));
4356}
4357
4358NestedNameSpecifier TagType::getQualifier() const {
4359 return TagTypeBits.HasQualifier ? getTrailingQualifier() : std::nullopt;
4360}
4361
4362ClassTemplateDecl *TagType::getTemplateDecl() const {
4363 auto *Decl = dyn_cast<CXXRecordDecl>(Val: decl);
4364 if (!Decl)
4365 return nullptr;
4366 if (auto *RD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Decl))
4367 return RD->getSpecializedTemplate();
4368 return Decl->getDescribedClassTemplate();
4369}
4370
4371TemplateName TagType::getTemplateName(const ASTContext &Ctx) const {
4372 auto *TD = getTemplateDecl();
4373 if (!TD)
4374 return TemplateName();
4375 if (isCanonicalUnqualified())
4376 return TemplateName(TD);
4377 return Ctx.getQualifiedTemplateName(Qualifier: getQualifier(), /*TemplateKeyword=*/false,
4378 Template: TemplateName(TD));
4379}
4380
4381ArrayRef<TemplateArgument>
4382TagType::getTemplateArgs(const ASTContext &Ctx) const {
4383 auto *Decl = dyn_cast<CXXRecordDecl>(Val: decl);
4384 if (!Decl)
4385 return {};
4386
4387 if (auto *RD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Decl))
4388 return RD->getTemplateArgs().asArray();
4389 if (ClassTemplateDecl *TD = Decl->getDescribedClassTemplate())
4390 return TD->getTemplateParameters()->getInjectedTemplateArgs(Context: Ctx);
4391 return {};
4392}
4393
4394bool RecordType::hasConstFields() const {
4395 std::vector<const RecordType *> RecordTypeList;
4396 RecordTypeList.push_back(x: this);
4397 unsigned NextToCheckIndex = 0;
4398
4399 while (RecordTypeList.size() > NextToCheckIndex) {
4400 for (FieldDecl *FD : RecordTypeList[NextToCheckIndex]
4401 ->getDecl()
4402 ->getDefinitionOrSelf()
4403 ->fields()) {
4404 QualType FieldTy = FD->getType();
4405 if (FieldTy.isConstQualified())
4406 return true;
4407 FieldTy = FieldTy.getCanonicalType();
4408 if (const auto *FieldRecTy = FieldTy->getAsCanonical<RecordType>()) {
4409 if (!llvm::is_contained(Range&: RecordTypeList, Element: FieldRecTy))
4410 RecordTypeList.push_back(x: FieldRecTy);
4411 }
4412 }
4413 ++NextToCheckIndex;
4414 }
4415 return false;
4416}
4417
4418InjectedClassNameType::InjectedClassNameType(ElaboratedTypeKeyword Keyword,
4419 NestedNameSpecifier Qualifier,
4420 const TagDecl *TD, bool IsInjected,
4421 const Type *CanonicalType)
4422 : TagType(TypeClass::InjectedClassName, Keyword, Qualifier, TD,
4423 /*OwnsTag=*/false, IsInjected, CanonicalType) {}
4424
4425AttributedType::AttributedType(QualType canon, const Attr *attr,
4426 QualType modified, QualType equivalent)
4427 : AttributedType(canon, attr->getKind(), attr, modified, equivalent) {}
4428
4429AttributedType::AttributedType(QualType canon, attr::Kind attrKind,
4430 const Attr *attr, QualType modified,
4431 QualType equivalent)
4432 : Type(Attributed, canon, equivalent->getDependence()), Attribute(attr),
4433 ModifiedType(modified), EquivalentType(equivalent) {
4434 AttributedTypeBits.AttrKind = attrKind;
4435 assert(!attr || attr->getKind() == attrKind);
4436}
4437
4438bool AttributedType::isQualifier() const {
4439 // FIXME: Generate this with TableGen.
4440 switch (getAttrKind()) {
4441 // These are type qualifiers in the traditional C sense: they annotate
4442 // something about a specific value/variable of a type. (They aren't
4443 // always part of the canonical type, though.)
4444 case attr::ObjCGC:
4445 case attr::ObjCOwnership:
4446 case attr::ObjCInertUnsafeUnretained:
4447 case attr::TypeNonNull:
4448 case attr::TypeNullable:
4449 case attr::TypeNullableResult:
4450 case attr::TypeNullUnspecified:
4451 case attr::LifetimeBound:
4452 case attr::AddressSpace:
4453 return true;
4454
4455 // All other type attributes aren't qualifiers; they rewrite the modified
4456 // type to be a semantically different type.
4457 default:
4458 return false;
4459 }
4460}
4461
4462bool AttributedType::isMSTypeSpec() const {
4463 // FIXME: Generate this with TableGen?
4464 switch (getAttrKind()) {
4465 default:
4466 return false;
4467 case attr::Ptr32:
4468 case attr::Ptr64:
4469 case attr::SPtr:
4470 case attr::UPtr:
4471 return true;
4472 }
4473 llvm_unreachable("invalid attr kind");
4474}
4475
4476bool AttributedType::isWebAssemblyFuncrefSpec() const {
4477 return getAttrKind() == attr::WebAssemblyFuncref;
4478}
4479
4480bool AttributedType::isCallingConv() const {
4481 // FIXME: Generate this with TableGen.
4482 switch (getAttrKind()) {
4483 default:
4484 return false;
4485 case attr::Pcs:
4486 case attr::CDecl:
4487 case attr::FastCall:
4488 case attr::StdCall:
4489 case attr::ThisCall:
4490 case attr::RegCall:
4491 case attr::SwiftCall:
4492 case attr::SwiftAsyncCall:
4493 case attr::VectorCall:
4494 case attr::AArch64VectorPcs:
4495 case attr::AArch64SVEPcs:
4496 case attr::DeviceKernel:
4497 case attr::Pascal:
4498 case attr::MSABI:
4499 case attr::SysVABI:
4500 case attr::IntelOclBicc:
4501 case attr::PreserveMost:
4502 case attr::PreserveAll:
4503 case attr::M68kRTD:
4504 case attr::PreserveNone:
4505 case attr::RISCVVectorCC:
4506 case attr::RISCVVLSCC:
4507 return true;
4508 }
4509 llvm_unreachable("invalid attr kind");
4510}
4511
4512IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
4513 return isCanonicalUnqualified() ? nullptr : getDecl()->getIdentifier();
4514}
4515
4516SubstTemplateTypeParmType::SubstTemplateTypeParmType(QualType Replacement,
4517 Decl *AssociatedDecl,
4518 unsigned Index,
4519 UnsignedOrNone PackIndex,
4520 bool Final)
4521 : Type(SubstTemplateTypeParm, Replacement.getCanonicalType(),
4522 Replacement->getDependence()),
4523 AssociatedDecl(AssociatedDecl) {
4524 SubstTemplateTypeParmTypeBits.HasNonCanonicalUnderlyingType =
4525 Replacement != getCanonicalTypeInternal();
4526 if (SubstTemplateTypeParmTypeBits.HasNonCanonicalUnderlyingType)
4527 *getTrailingObjects() = Replacement;
4528
4529 SubstTemplateTypeParmTypeBits.Index = Index;
4530 SubstTemplateTypeParmTypeBits.Final = Final;
4531 SubstTemplateTypeParmTypeBits.PackIndex =
4532 PackIndex.toInternalRepresentation();
4533 assert(AssociatedDecl != nullptr);
4534}
4535
4536const TemplateTypeParmDecl *
4537SubstTemplateTypeParmType::getReplacedParameter() const {
4538 return cast<TemplateTypeParmDecl>(Val: std::get<0>(
4539 t: getReplacedTemplateParameter(D: getAssociatedDecl(), Index: getIndex())));
4540}
4541
4542void SubstTemplateTypeParmType::Profile(llvm::FoldingSetNodeID &ID,
4543 QualType Replacement,
4544 const Decl *AssociatedDecl,
4545 unsigned Index,
4546 UnsignedOrNone PackIndex, bool Final) {
4547 Replacement.Profile(ID);
4548 ID.AddPointer(Ptr: AssociatedDecl);
4549 ID.AddInteger(I: Index);
4550 ID.AddInteger(I: PackIndex.toInternalRepresentation());
4551 ID.AddBoolean(B: Final);
4552}
4553
4554SubstPackType::SubstPackType(TypeClass Derived, QualType Canon,
4555 const TemplateArgument &ArgPack)
4556 : Type(Derived, Canon,
4557 TypeDependence::DependentInstantiation |
4558 TypeDependence::UnexpandedPack),
4559 Arguments(ArgPack.pack_begin()) {
4560 assert(llvm::all_of(
4561 ArgPack.pack_elements(),
4562 [](auto &P) { return P.getKind() == TemplateArgument::Type; }) &&
4563 "non-type argument to SubstPackType?");
4564 SubstPackTypeBits.NumArgs = ArgPack.pack_size();
4565}
4566
4567TemplateArgument SubstPackType::getArgumentPack() const {
4568 return TemplateArgument(llvm::ArrayRef(Arguments, getNumArgs()));
4569}
4570
4571void SubstPackType::Profile(llvm::FoldingSetNodeID &ID) {
4572 Profile(ID, ArgPack: getArgumentPack());
4573}
4574
4575void SubstPackType::Profile(llvm::FoldingSetNodeID &ID,
4576 const TemplateArgument &ArgPack) {
4577 ID.AddInteger(I: ArgPack.pack_size());
4578 for (const auto &P : ArgPack.pack_elements())
4579 ID.AddPointer(Ptr: P.getAsType().getAsOpaquePtr());
4580}
4581
4582SubstTemplateTypeParmPackType::SubstTemplateTypeParmPackType(
4583 QualType Canon, Decl *AssociatedDecl, unsigned Index, bool Final,
4584 const TemplateArgument &ArgPack)
4585 : SubstPackType(SubstTemplateTypeParmPack, Canon, ArgPack),
4586 AssociatedDeclAndFinal(AssociatedDecl, Final) {
4587 assert(AssociatedDecl != nullptr);
4588
4589 SubstPackTypeBits.SubstTemplTypeParmPackIndex = Index;
4590 assert(getNumArgs() == ArgPack.pack_size() &&
4591 "Parent bitfields in SubstPackType were overwritten."
4592 "Check NumSubstPackTypeBits.");
4593}
4594
4595Decl *SubstTemplateTypeParmPackType::getAssociatedDecl() const {
4596 return AssociatedDeclAndFinal.getPointer();
4597}
4598
4599bool SubstTemplateTypeParmPackType::getFinal() const {
4600 return AssociatedDeclAndFinal.getInt();
4601}
4602
4603const TemplateTypeParmDecl *
4604SubstTemplateTypeParmPackType::getReplacedParameter() const {
4605 return cast<TemplateTypeParmDecl>(Val: std::get<0>(
4606 t: getReplacedTemplateParameter(D: getAssociatedDecl(), Index: getIndex())));
4607}
4608
4609IdentifierInfo *SubstTemplateTypeParmPackType::getIdentifier() const {
4610 return getReplacedParameter()->getIdentifier();
4611}
4612
4613void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
4614 Profile(ID, AssociatedDecl: getAssociatedDecl(), Index: getIndex(), Final: getFinal(), ArgPack: getArgumentPack());
4615}
4616
4617void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
4618 const Decl *AssociatedDecl,
4619 unsigned Index, bool Final,
4620 const TemplateArgument &ArgPack) {
4621 ID.AddPointer(Ptr: AssociatedDecl);
4622 ID.AddInteger(I: Index);
4623 ID.AddBoolean(B: Final);
4624 SubstPackType::Profile(ID, ArgPack);
4625}
4626
4627SubstBuiltinTemplatePackType::SubstBuiltinTemplatePackType(
4628 QualType Canon, const TemplateArgument &ArgPack)
4629 : SubstPackType(SubstBuiltinTemplatePack, Canon, ArgPack) {}
4630
4631bool TemplateSpecializationType::anyDependentTemplateArguments(
4632 const TemplateArgumentListInfo &Args,
4633 ArrayRef<TemplateArgument> Converted) {
4634 return anyDependentTemplateArguments(Args: Args.arguments(), Converted);
4635}
4636
4637bool TemplateSpecializationType::anyDependentTemplateArguments(
4638 ArrayRef<TemplateArgumentLoc> Args, ArrayRef<TemplateArgument> Converted) {
4639 for (const TemplateArgument &Arg : Converted)
4640 if (Arg.isDependent())
4641 return true;
4642 return false;
4643}
4644
4645bool TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
4646 ArrayRef<TemplateArgumentLoc> Args) {
4647 for (const TemplateArgumentLoc &ArgLoc : Args) {
4648 if (ArgLoc.getArgument().isInstantiationDependent())
4649 return true;
4650 }
4651 return false;
4652}
4653
4654static TypeDependence
4655getTemplateSpecializationTypeDependence(QualType Underlying, TemplateName T) {
4656 TypeDependence D = Underlying.isNull()
4657 ? TypeDependence::DependentInstantiation
4658 : toSemanticDependence(D: Underlying->getDependence());
4659 D |= toTypeDependence(D: T.getDependence()) & TypeDependence::UnexpandedPack;
4660 if (isPackProducingBuiltinTemplateName(N: T)) {
4661 if (Underlying.isNull()) // Dependent, will produce a pack on substitution.
4662 D |= TypeDependence::UnexpandedPack;
4663 else
4664 D |= (Underlying->getDependence() & TypeDependence::UnexpandedPack);
4665 }
4666 return D;
4667}
4668
4669TemplateSpecializationType::TemplateSpecializationType(
4670 ElaboratedTypeKeyword Keyword, TemplateName T, bool IsAlias,
4671 ArrayRef<TemplateArgument> Args, QualType Underlying)
4672 : TypeWithKeyword(Keyword, TemplateSpecialization,
4673 Underlying.isNull() ? QualType(this, 0)
4674 : Underlying.getCanonicalType(),
4675 getTemplateSpecializationTypeDependence(Underlying, T)),
4676 Template(T) {
4677 TemplateSpecializationTypeBits.NumArgs = Args.size();
4678 TemplateSpecializationTypeBits.TypeAlias = IsAlias;
4679
4680 auto *TemplateArgs =
4681 const_cast<TemplateArgument *>(template_arguments().data());
4682 for (const TemplateArgument &Arg : Args) {
4683 // Update instantiation-dependent, variably-modified, and error bits.
4684 // If the canonical type exists and is non-dependent, the template
4685 // specialization type can be non-dependent even if one of the type
4686 // arguments is. Given:
4687 // template<typename T> using U = int;
4688 // U<T> is always non-dependent, irrespective of the type T.
4689 // However, U<Ts> contains an unexpanded parameter pack, even though
4690 // its expansion (and thus its desugared type) doesn't.
4691 addDependence(D: toTypeDependence(D: Arg.getDependence()) &
4692 ~TypeDependence::Dependent);
4693 if (Arg.getKind() == TemplateArgument::Type)
4694 addDependence(D: Arg.getAsType()->getDependence() &
4695 TypeDependence::VariablyModified);
4696 new (TemplateArgs++) TemplateArgument(Arg);
4697 }
4698
4699 // Store the aliased type after the template arguments, if this is a type
4700 // alias template specialization.
4701 if (IsAlias)
4702 *reinterpret_cast<QualType *>(TemplateArgs) = Underlying;
4703}
4704
4705QualType TemplateSpecializationType::getAliasedType() const {
4706 assert(isTypeAlias() && "not a type alias template specialization");
4707 return *reinterpret_cast<const QualType *>(template_arguments().end());
4708}
4709
4710bool clang::TemplateSpecializationType::isSugared() const {
4711 return !isDependentType() || isCurrentInstantiation() || isTypeAlias() ||
4712 (isPackProducingBuiltinTemplateName(N: Template) &&
4713 isa<SubstBuiltinTemplatePackType>(Val: *getCanonicalTypeInternal()));
4714}
4715
4716void TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
4717 const ASTContext &Ctx) {
4718 Profile(ID, Keyword: getKeyword(), T: Template, Args: template_arguments(),
4719 Underlying: isSugared() ? desugar() : QualType(), Context: Ctx);
4720}
4721
4722void TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
4723 ElaboratedTypeKeyword Keyword,
4724 TemplateName T,
4725 ArrayRef<TemplateArgument> Args,
4726 QualType Underlying,
4727 const ASTContext &Context) {
4728 ID.AddInteger(I: llvm::to_underlying(E: Keyword));
4729 T.Profile(ID);
4730 Underlying.Profile(ID);
4731
4732 ID.AddInteger(I: Args.size());
4733 for (const TemplateArgument &Arg : Args)
4734 Arg.Profile(ID, Context);
4735}
4736
4737QualType QualifierCollector::apply(const ASTContext &Context,
4738 QualType QT) const {
4739 if (!hasNonFastQualifiers())
4740 return QT.withFastQualifiers(TQs: getFastQualifiers());
4741
4742 return Context.getQualifiedType(T: QT, Qs: *this);
4743}
4744
4745QualType QualifierCollector::apply(const ASTContext &Context,
4746 const Type *T) const {
4747 if (!hasNonFastQualifiers())
4748 return QualType(T, getFastQualifiers());
4749
4750 return Context.getQualifiedType(T, Qs: *this);
4751}
4752
4753void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
4754 ArrayRef<QualType> typeArgs,
4755 ArrayRef<ObjCProtocolDecl *> protocols,
4756 bool isKindOf) {
4757 ID.AddPointer(Ptr: BaseType.getAsOpaquePtr());
4758 ID.AddInteger(I: typeArgs.size());
4759 for (auto typeArg : typeArgs)
4760 ID.AddPointer(Ptr: typeArg.getAsOpaquePtr());
4761 ID.AddInteger(I: protocols.size());
4762 for (auto *proto : protocols)
4763 ID.AddPointer(Ptr: proto);
4764 ID.AddBoolean(B: isKindOf);
4765}
4766
4767void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
4768 Profile(ID, BaseType: getBaseType(), typeArgs: getTypeArgsAsWritten(),
4769 protocols: llvm::ArrayRef(qual_begin(), getNumProtocols()),
4770 isKindOf: isKindOfTypeAsWritten());
4771}
4772
4773void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID,
4774 const ObjCTypeParamDecl *OTPDecl,
4775 QualType CanonicalType,
4776 ArrayRef<ObjCProtocolDecl *> protocols) {
4777 ID.AddPointer(Ptr: OTPDecl);
4778 ID.AddPointer(Ptr: CanonicalType.getAsOpaquePtr());
4779 ID.AddInteger(I: protocols.size());
4780 for (auto *proto : protocols)
4781 ID.AddPointer(Ptr: proto);
4782}
4783
4784void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID) {
4785 Profile(ID, OTPDecl: getDecl(), CanonicalType: getCanonicalTypeInternal(),
4786 protocols: llvm::ArrayRef(qual_begin(), getNumProtocols()));
4787}
4788
4789namespace {
4790
4791/// The cached properties of a type.
4792class CachedProperties {
4793 Linkage L;
4794 bool local;
4795
4796public:
4797 CachedProperties(Linkage L, bool local) : L(L), local(local) {}
4798
4799 Linkage getLinkage() const { return L; }
4800 bool hasLocalOrUnnamedType() const { return local; }
4801
4802 friend CachedProperties merge(CachedProperties L, CachedProperties R) {
4803 Linkage MergedLinkage = minLinkage(L1: L.L, L2: R.L);
4804 return CachedProperties(MergedLinkage, L.hasLocalOrUnnamedType() ||
4805 R.hasLocalOrUnnamedType());
4806 }
4807};
4808
4809} // namespace
4810
4811static CachedProperties computeCachedProperties(const Type *T);
4812
4813namespace clang {
4814
4815/// The type-property cache. This is templated so as to be
4816/// instantiated at an internal type to prevent unnecessary symbol
4817/// leakage.
4818template <class Private> class TypePropertyCache {
4819public:
4820 static CachedProperties get(QualType T) { return get(T.getTypePtr()); }
4821
4822 static CachedProperties get(const Type *T) {
4823 ensure(T);
4824 return CachedProperties(T->TypeBits.getLinkage(),
4825 T->TypeBits.hasLocalOrUnnamedType());
4826 }
4827
4828 static void ensure(const Type *T) {
4829 // If the cache is valid, we're okay.
4830 if (T->TypeBits.isCacheValid())
4831 return;
4832
4833 // If this type is non-canonical, ask its canonical type for the
4834 // relevant information.
4835 if (!T->isCanonicalUnqualified()) {
4836 const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
4837 ensure(T: CT);
4838 T->TypeBits.CacheValid = true;
4839 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
4840 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
4841 return;
4842 }
4843
4844 // Compute the cached properties and then set the cache.
4845 CachedProperties Result = computeCachedProperties(T);
4846 T->TypeBits.CacheValid = true;
4847 T->TypeBits.CachedLinkage = llvm::to_underlying(E: Result.getLinkage());
4848 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
4849 }
4850};
4851
4852} // namespace clang
4853
4854// Instantiate the friend template at a private class. In a
4855// reasonable implementation, these symbols will be internal.
4856// It is terrible that this is the best way to accomplish this.
4857namespace {
4858
4859class Private {};
4860
4861} // namespace
4862
4863using Cache = TypePropertyCache<Private>;
4864
4865static CachedProperties computeCachedProperties(const Type *T) {
4866 switch (T->getTypeClass()) {
4867#define TYPE(Class, Base)
4868#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4869#include "clang/AST/TypeNodes.inc"
4870 llvm_unreachable("didn't expect a non-canonical type here");
4871
4872#define TYPE(Class, Base)
4873#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4874#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
4875#include "clang/AST/TypeNodes.inc"
4876 // Treat instantiation-dependent types as external.
4877 assert(T->isInstantiationDependentType());
4878 return CachedProperties(Linkage::External, false);
4879
4880 case Type::Auto:
4881 case Type::DeducedTemplateSpecialization:
4882 // Give non-deduced 'auto' types external linkage. We should only see them
4883 // here in error recovery.
4884 return CachedProperties(Linkage::External, false);
4885
4886 case Type::BitInt:
4887 case Type::Builtin:
4888 // C++ [basic.link]p8:
4889 // A type is said to have linkage if and only if:
4890 // - it is a fundamental type (3.9.1); or
4891 return CachedProperties(Linkage::External, false);
4892
4893 case Type::Record:
4894 case Type::Enum: {
4895 const auto *Tag = cast<TagType>(Val: T)->getDecl()->getDefinitionOrSelf();
4896
4897 // C++ [basic.link]p8:
4898 // - it is a class or enumeration type that is named (or has a name
4899 // for linkage purposes (7.1.3)) and the name has linkage; or
4900 // - it is a specialization of a class template (14); or
4901 Linkage L = Tag->getLinkageInternal();
4902 bool IsLocalOrUnnamed = Tag->getDeclContext()->isFunctionOrMethod() ||
4903 !Tag->hasNameForLinkage();
4904 return CachedProperties(L, IsLocalOrUnnamed);
4905 }
4906
4907 // C++ [basic.link]p8:
4908 // - it is a compound type (3.9.2) other than a class or enumeration,
4909 // compounded exclusively from types that have linkage; or
4910 case Type::Complex:
4911 return Cache::get(T: cast<ComplexType>(Val: T)->getElementType());
4912 case Type::Pointer:
4913 return Cache::get(T: cast<PointerType>(Val: T)->getPointeeType());
4914 case Type::BlockPointer:
4915 return Cache::get(T: cast<BlockPointerType>(Val: T)->getPointeeType());
4916 case Type::LValueReference:
4917 case Type::RValueReference:
4918 return Cache::get(T: cast<ReferenceType>(Val: T)->getPointeeType());
4919 case Type::MemberPointer: {
4920 const auto *MPT = cast<MemberPointerType>(Val: T);
4921 CachedProperties Cls = [&] {
4922 if (MPT->isSugared())
4923 MPT = cast<MemberPointerType>(Val: MPT->getCanonicalTypeInternal());
4924 return Cache::get(T: MPT->getQualifier().getAsType());
4925 }();
4926 return merge(L: Cls, R: Cache::get(T: MPT->getPointeeType()));
4927 }
4928 case Type::ConstantArray:
4929 case Type::IncompleteArray:
4930 case Type::VariableArray:
4931 case Type::ArrayParameter:
4932 return Cache::get(T: cast<ArrayType>(Val: T)->getElementType());
4933 case Type::Vector:
4934 case Type::ExtVector:
4935 return Cache::get(T: cast<VectorType>(Val: T)->getElementType());
4936 case Type::ConstantMatrix:
4937 return Cache::get(T: cast<ConstantMatrixType>(Val: T)->getElementType());
4938 case Type::FunctionNoProto:
4939 return Cache::get(T: cast<FunctionType>(Val: T)->getReturnType());
4940 case Type::FunctionProto: {
4941 const auto *FPT = cast<FunctionProtoType>(Val: T);
4942 CachedProperties result = Cache::get(T: FPT->getReturnType());
4943 for (const auto &ai : FPT->param_types())
4944 result = merge(L: result, R: Cache::get(T: ai));
4945 return result;
4946 }
4947 case Type::ObjCInterface: {
4948 Linkage L = cast<ObjCInterfaceType>(Val: T)->getDecl()->getLinkageInternal();
4949 return CachedProperties(L, false);
4950 }
4951 case Type::ObjCObject:
4952 return Cache::get(T: cast<ObjCObjectType>(Val: T)->getBaseType());
4953 case Type::ObjCObjectPointer:
4954 return Cache::get(T: cast<ObjCObjectPointerType>(Val: T)->getPointeeType());
4955 case Type::Atomic:
4956 return Cache::get(T: cast<AtomicType>(Val: T)->getValueType());
4957 case Type::Pipe:
4958 return Cache::get(T: cast<PipeType>(Val: T)->getElementType());
4959 case Type::HLSLAttributedResource:
4960 return Cache::get(T: cast<HLSLAttributedResourceType>(Val: T)->getWrappedType());
4961 case Type::HLSLInlineSpirv:
4962 return CachedProperties(Linkage::External, false);
4963 case Type::OverflowBehavior:
4964 return Cache::get(T: cast<OverflowBehaviorType>(Val: T)->getUnderlyingType());
4965 }
4966
4967 llvm_unreachable("unhandled type class");
4968}
4969
4970/// Determine the linkage of this type.
4971Linkage Type::getLinkage() const {
4972 Cache::ensure(T: this);
4973 return TypeBits.getLinkage();
4974}
4975
4976bool Type::hasUnnamedOrLocalType() const {
4977 Cache::ensure(T: this);
4978 return TypeBits.hasLocalOrUnnamedType();
4979}
4980
4981LinkageInfo LinkageComputer::computeTypeLinkageInfo(const Type *T) {
4982 switch (T->getTypeClass()) {
4983#define TYPE(Class, Base)
4984#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4985#include "clang/AST/TypeNodes.inc"
4986 llvm_unreachable("didn't expect a non-canonical type here");
4987
4988#define TYPE(Class, Base)
4989#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4990#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
4991#include "clang/AST/TypeNodes.inc"
4992 // Treat instantiation-dependent types as external.
4993 assert(T->isInstantiationDependentType());
4994 return LinkageInfo::external();
4995
4996 case Type::BitInt:
4997 case Type::Builtin:
4998 return LinkageInfo::external();
4999
5000 case Type::Auto:
5001 case Type::DeducedTemplateSpecialization:
5002 return LinkageInfo::external();
5003
5004 case Type::Record:
5005 case Type::Enum:
5006 return getDeclLinkageAndVisibility(
5007 D: cast<TagType>(Val: T)->getDecl()->getDefinitionOrSelf());
5008
5009 case Type::Complex:
5010 return computeTypeLinkageInfo(T: cast<ComplexType>(Val: T)->getElementType());
5011 case Type::Pointer:
5012 return computeTypeLinkageInfo(T: cast<PointerType>(Val: T)->getPointeeType());
5013 case Type::BlockPointer:
5014 return computeTypeLinkageInfo(T: cast<BlockPointerType>(Val: T)->getPointeeType());
5015 case Type::LValueReference:
5016 case Type::RValueReference:
5017 return computeTypeLinkageInfo(T: cast<ReferenceType>(Val: T)->getPointeeType());
5018 case Type::MemberPointer: {
5019 const auto *MPT = cast<MemberPointerType>(Val: T);
5020 LinkageInfo LV;
5021 if (auto *D = MPT->getMostRecentCXXRecordDecl()) {
5022 LV.merge(other: getDeclLinkageAndVisibility(D));
5023 } else {
5024 LV.merge(other: computeTypeLinkageInfo(T: MPT->getQualifier().getAsType()));
5025 }
5026 LV.merge(other: computeTypeLinkageInfo(T: MPT->getPointeeType()));
5027 return LV;
5028 }
5029 case Type::ConstantArray:
5030 case Type::IncompleteArray:
5031 case Type::VariableArray:
5032 case Type::ArrayParameter:
5033 return computeTypeLinkageInfo(T: cast<ArrayType>(Val: T)->getElementType());
5034 case Type::Vector:
5035 case Type::ExtVector:
5036 return computeTypeLinkageInfo(T: cast<VectorType>(Val: T)->getElementType());
5037 case Type::ConstantMatrix:
5038 return computeTypeLinkageInfo(
5039 T: cast<ConstantMatrixType>(Val: T)->getElementType());
5040 case Type::FunctionNoProto:
5041 return computeTypeLinkageInfo(T: cast<FunctionType>(Val: T)->getReturnType());
5042 case Type::FunctionProto: {
5043 const auto *FPT = cast<FunctionProtoType>(Val: T);
5044 LinkageInfo LV = computeTypeLinkageInfo(T: FPT->getReturnType());
5045 for (const auto &ai : FPT->param_types())
5046 LV.merge(other: computeTypeLinkageInfo(T: ai));
5047 return LV;
5048 }
5049 case Type::ObjCInterface:
5050 return getDeclLinkageAndVisibility(D: cast<ObjCInterfaceType>(Val: T)->getDecl());
5051 case Type::ObjCObject:
5052 return computeTypeLinkageInfo(T: cast<ObjCObjectType>(Val: T)->getBaseType());
5053 case Type::ObjCObjectPointer:
5054 return computeTypeLinkageInfo(
5055 T: cast<ObjCObjectPointerType>(Val: T)->getPointeeType());
5056 case Type::Atomic:
5057 return computeTypeLinkageInfo(T: cast<AtomicType>(Val: T)->getValueType());
5058 case Type::Pipe:
5059 return computeTypeLinkageInfo(T: cast<PipeType>(Val: T)->getElementType());
5060 case Type::OverflowBehavior:
5061 return computeTypeLinkageInfo(
5062 T: cast<OverflowBehaviorType>(Val: T)->getUnderlyingType());
5063 case Type::HLSLAttributedResource:
5064 return computeTypeLinkageInfo(T: cast<HLSLAttributedResourceType>(Val: T)
5065 ->getContainedType()
5066 ->getCanonicalTypeInternal());
5067 case Type::HLSLInlineSpirv:
5068 return LinkageInfo::external();
5069 }
5070
5071 llvm_unreachable("unhandled type class");
5072}
5073
5074bool Type::isLinkageValid() const {
5075 if (!TypeBits.isCacheValid())
5076 return true;
5077
5078 Linkage L = LinkageComputer{}
5079 .computeTypeLinkageInfo(T: getCanonicalTypeInternal())
5080 .getLinkage();
5081 return L == TypeBits.getLinkage();
5082}
5083
5084LinkageInfo LinkageComputer::getTypeLinkageAndVisibility(const Type *T) {
5085 if (!T->isCanonicalUnqualified())
5086 return computeTypeLinkageInfo(T: T->getCanonicalTypeInternal());
5087
5088 LinkageInfo LV = computeTypeLinkageInfo(T);
5089 assert(LV.getLinkage() == T->getLinkage());
5090 return LV;
5091}
5092
5093LinkageInfo Type::getLinkageAndVisibility() const {
5094 return LinkageComputer{}.getTypeLinkageAndVisibility(T: this);
5095}
5096
5097std::optional<NullabilityKind> Type::getNullability() const {
5098 QualType Type(this, 0);
5099 while (const auto *AT = Type->getAs<AttributedType>()) {
5100 // Check whether this is an attributed type with nullability
5101 // information.
5102 if (auto Nullability = AT->getImmediateNullability())
5103 return Nullability;
5104
5105 Type = AT->getEquivalentType();
5106 }
5107 return std::nullopt;
5108}
5109
5110bool Type::canHaveNullability(bool ResultIfUnknown) const {
5111 QualType type = getCanonicalTypeInternal();
5112
5113 switch (type->getTypeClass()) {
5114#define NON_CANONICAL_TYPE(Class, Parent) \
5115 /* We'll only see canonical types here. */ \
5116 case Type::Class: \
5117 llvm_unreachable("non-canonical type");
5118#define TYPE(Class, Parent)
5119#include "clang/AST/TypeNodes.inc"
5120
5121 // Pointer types.
5122 case Type::Pointer:
5123 case Type::BlockPointer:
5124 case Type::MemberPointer:
5125 case Type::ObjCObjectPointer:
5126 return true;
5127
5128 // Dependent types that could instantiate to pointer types.
5129 case Type::UnresolvedUsing:
5130 case Type::TypeOfExpr:
5131 case Type::TypeOf:
5132 case Type::Decltype:
5133 case Type::PackIndexing:
5134 case Type::UnaryTransform:
5135 case Type::TemplateTypeParm:
5136 case Type::SubstTemplateTypeParmPack:
5137 case Type::SubstBuiltinTemplatePack:
5138 case Type::DependentName:
5139 case Type::Auto:
5140 return ResultIfUnknown;
5141
5142 // Dependent template specializations could instantiate to pointer types.
5143 case Type::TemplateSpecialization:
5144 // If it's a known class template, we can already check if it's nullable.
5145 if (TemplateDecl *templateDecl =
5146 cast<TemplateSpecializationType>(Val: type.getTypePtr())
5147 ->getTemplateName()
5148 .getAsTemplateDecl())
5149 if (auto *CTD = dyn_cast<ClassTemplateDecl>(Val: templateDecl))
5150 return llvm::any_of(
5151 Range: CTD->redecls(), P: [](const RedeclarableTemplateDecl *RTD) {
5152 return RTD->getTemplatedDecl()->hasAttr<TypeNullableAttr>();
5153 });
5154 return ResultIfUnknown;
5155
5156 case Type::Builtin:
5157 switch (cast<BuiltinType>(Val: type.getTypePtr())->getKind()) {
5158 // Signed, unsigned, and floating-point types cannot have nullability.
5159#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
5160#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
5161#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
5162#define BUILTIN_TYPE(Id, SingletonId)
5163#include "clang/AST/BuiltinTypes.def"
5164 return false;
5165
5166 case BuiltinType::UnresolvedTemplate:
5167 // Dependent types that could instantiate to a pointer type.
5168 case BuiltinType::Dependent:
5169 case BuiltinType::Overload:
5170 case BuiltinType::BoundMember:
5171 case BuiltinType::PseudoObject:
5172 case BuiltinType::UnknownAny:
5173 case BuiltinType::ARCUnbridgedCast:
5174 return ResultIfUnknown;
5175
5176 case BuiltinType::Void:
5177 case BuiltinType::ObjCId:
5178 case BuiltinType::ObjCClass:
5179 case BuiltinType::ObjCSel:
5180#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5181 case BuiltinType::Id:
5182#include "clang/Basic/OpenCLImageTypes.def"
5183#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) case BuiltinType::Id:
5184#include "clang/Basic/OpenCLExtensionTypes.def"
5185 case BuiltinType::OCLSampler:
5186 case BuiltinType::OCLEvent:
5187 case BuiltinType::OCLClkEvent:
5188 case BuiltinType::OCLQueue:
5189 case BuiltinType::OCLReserveID:
5190#define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
5191#include "clang/Basic/AArch64ACLETypes.def"
5192#define PPC_VECTOR_TYPE(Name, Id, Size) case BuiltinType::Id:
5193#include "clang/Basic/PPCTypes.def"
5194#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
5195#include "clang/Basic/RISCVVTypes.def"
5196#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
5197#include "clang/Basic/WebAssemblyReferenceTypes.def"
5198#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
5199#include "clang/Basic/AMDGPUTypes.def"
5200#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
5201#include "clang/Basic/HLSLIntangibleTypes.def"
5202 case BuiltinType::BuiltinFn:
5203 case BuiltinType::NullPtr:
5204 case BuiltinType::IncompleteMatrixIdx:
5205 case BuiltinType::ArraySection:
5206 case BuiltinType::OMPArrayShaping:
5207 case BuiltinType::OMPIterator:
5208 return false;
5209 }
5210 llvm_unreachable("unknown builtin type");
5211
5212 case Type::Record: {
5213 const auto *RD = cast<RecordType>(Val&: type)->getDecl();
5214 // For template specializations, look only at primary template attributes.
5215 // This is a consistent regardless of whether the instantiation is known.
5216 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: RD))
5217 return llvm::any_of(
5218 Range: CTSD->getSpecializedTemplate()->redecls(),
5219 P: [](const RedeclarableTemplateDecl *RTD) {
5220 return RTD->getTemplatedDecl()->hasAttr<TypeNullableAttr>();
5221 });
5222 return llvm::any_of(Range: RD->redecls(), P: [](const TagDecl *RD) {
5223 return RD->hasAttr<TypeNullableAttr>();
5224 });
5225 }
5226
5227 // Non-pointer types.
5228 case Type::Complex:
5229 case Type::LValueReference:
5230 case Type::RValueReference:
5231 case Type::ConstantArray:
5232 case Type::IncompleteArray:
5233 case Type::VariableArray:
5234 case Type::DependentSizedArray:
5235 case Type::DependentVector:
5236 case Type::DependentSizedExtVector:
5237 case Type::Vector:
5238 case Type::ExtVector:
5239 case Type::ConstantMatrix:
5240 case Type::DependentSizedMatrix:
5241 case Type::DependentAddressSpace:
5242 case Type::FunctionProto:
5243 case Type::FunctionNoProto:
5244 case Type::DeducedTemplateSpecialization:
5245 case Type::Enum:
5246 case Type::InjectedClassName:
5247 case Type::PackExpansion:
5248 case Type::ObjCObject:
5249 case Type::ObjCInterface:
5250 case Type::Atomic:
5251 case Type::Pipe:
5252 case Type::BitInt:
5253 case Type::DependentBitInt:
5254 case Type::ArrayParameter:
5255 case Type::HLSLAttributedResource:
5256 case Type::HLSLInlineSpirv:
5257 case Type::OverflowBehavior:
5258 return false;
5259 }
5260 llvm_unreachable("bad type kind!");
5261}
5262
5263std::optional<NullabilityKind> AttributedType::getImmediateNullability() const {
5264 if (getAttrKind() == attr::TypeNonNull)
5265 return NullabilityKind::NonNull;
5266 if (getAttrKind() == attr::TypeNullable)
5267 return NullabilityKind::Nullable;
5268 if (getAttrKind() == attr::TypeNullUnspecified)
5269 return NullabilityKind::Unspecified;
5270 if (getAttrKind() == attr::TypeNullableResult)
5271 return NullabilityKind::NullableResult;
5272 return std::nullopt;
5273}
5274
5275std::optional<NullabilityKind>
5276AttributedType::stripOuterNullability(QualType &T) {
5277 QualType AttrTy = T;
5278 if (auto MacroTy = dyn_cast<MacroQualifiedType>(Val&: T))
5279 AttrTy = MacroTy->getUnderlyingType();
5280
5281 if (auto attributed = dyn_cast<AttributedType>(Val&: AttrTy)) {
5282 if (auto nullability = attributed->getImmediateNullability()) {
5283 T = attributed->getModifiedType();
5284 return nullability;
5285 }
5286 }
5287
5288 return std::nullopt;
5289}
5290
5291bool Type::isSignableIntegerType(const ASTContext &Ctx) const {
5292 if (!isIntegralType(Ctx) || isEnumeralType())
5293 return false;
5294 return Ctx.getTypeSize(T: this) == Ctx.getTypeSize(T: Ctx.VoidPtrTy);
5295}
5296
5297bool Type::isBlockCompatibleObjCPointerType(ASTContext &ctx) const {
5298 const auto *objcPtr = getAs<ObjCObjectPointerType>();
5299 if (!objcPtr)
5300 return false;
5301
5302 if (objcPtr->isObjCIdType()) {
5303 // id is always okay.
5304 return true;
5305 }
5306
5307 // Blocks are NSObjects.
5308 if (ObjCInterfaceDecl *iface = objcPtr->getInterfaceDecl()) {
5309 if (iface->getIdentifier() != ctx.getNSObjectName())
5310 return false;
5311
5312 // Continue to check qualifiers, below.
5313 } else if (objcPtr->isObjCQualifiedIdType()) {
5314 // Continue to check qualifiers, below.
5315 } else {
5316 return false;
5317 }
5318
5319 // Check protocol qualifiers.
5320 for (ObjCProtocolDecl *proto : objcPtr->quals()) {
5321 // Blocks conform to NSObject and NSCopying.
5322 if (proto->getIdentifier() != ctx.getNSObjectName() &&
5323 proto->getIdentifier() != ctx.getNSCopyingName())
5324 return false;
5325 }
5326
5327 return true;
5328}
5329
5330Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const {
5331 if (isObjCARCImplicitlyUnretainedType())
5332 return Qualifiers::OCL_ExplicitNone;
5333 return Qualifiers::OCL_Strong;
5334}
5335
5336bool Type::isObjCARCImplicitlyUnretainedType() const {
5337 assert(isObjCLifetimeType() &&
5338 "cannot query implicit lifetime for non-inferrable type");
5339
5340 const Type *canon = getCanonicalTypeInternal().getTypePtr();
5341
5342 // Walk down to the base type. We don't care about qualifiers for this.
5343 while (const auto *array = dyn_cast<ArrayType>(Val: canon))
5344 canon = array->getElementType().getTypePtr();
5345
5346 if (const auto *opt = dyn_cast<ObjCObjectPointerType>(Val: canon)) {
5347 // Class and Class<Protocol> don't require retention.
5348 if (opt->getObjectType()->isObjCClass())
5349 return true;
5350 }
5351
5352 return false;
5353}
5354
5355bool Type::isObjCNSObjectType() const {
5356 if (const auto *typedefType = getAs<TypedefType>())
5357 return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>();
5358 return false;
5359}
5360
5361bool Type::isObjCIndependentClassType() const {
5362 if (const auto *typedefType = getAs<TypedefType>())
5363 return typedefType->getDecl()->hasAttr<ObjCIndependentClassAttr>();
5364 return false;
5365}
5366
5367bool Type::isObjCRetainableType() const {
5368 return isObjCObjectPointerType() || isBlockPointerType() ||
5369 isObjCNSObjectType();
5370}
5371
5372bool Type::isObjCIndirectLifetimeType() const {
5373 if (isObjCLifetimeType())
5374 return true;
5375 if (const auto *OPT = getAs<PointerType>())
5376 return OPT->getPointeeType()->isObjCIndirectLifetimeType();
5377 if (const auto *Ref = getAs<ReferenceType>())
5378 return Ref->getPointeeType()->isObjCIndirectLifetimeType();
5379 if (const auto *MemPtr = getAs<MemberPointerType>())
5380 return MemPtr->getPointeeType()->isObjCIndirectLifetimeType();
5381 return false;
5382}
5383
5384/// Returns true if objects of this type have lifetime semantics under
5385/// ARC.
5386bool Type::isObjCLifetimeType() const {
5387 const Type *type = this;
5388 while (const ArrayType *array = type->getAsArrayTypeUnsafe())
5389 type = array->getElementType().getTypePtr();
5390 return type->isObjCRetainableType();
5391}
5392
5393/// Determine whether the given type T is a "bridgable" Objective-C type,
5394/// which is either an Objective-C object pointer type or an
5395bool Type::isObjCARCBridgableType() const {
5396 return isObjCObjectPointerType() || isBlockPointerType();
5397}
5398
5399/// Determine whether the given type T is a "bridgeable" C type.
5400bool Type::isCARCBridgableType() const {
5401 const auto *Pointer = getAsCanonical<PointerType>();
5402 if (!Pointer)
5403 return false;
5404
5405 QualType Pointee = Pointer->getPointeeType();
5406 return Pointee->isVoidType() || Pointee->isRecordType();
5407}
5408
5409/// Check if the specified type is the CUDA device builtin surface type.
5410bool Type::isCUDADeviceBuiltinSurfaceType() const {
5411 if (const auto *RT = getAsCanonical<RecordType>())
5412 return RT->getDecl()
5413 ->getMostRecentDecl()
5414 ->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>();
5415 return false;
5416}
5417
5418/// Check if the specified type is the CUDA device builtin texture type.
5419bool Type::isCUDADeviceBuiltinTextureType() const {
5420 if (const auto *RT = getAsCanonical<RecordType>())
5421 return RT->getDecl()
5422 ->getMostRecentDecl()
5423 ->hasAttr<CUDADeviceBuiltinTextureTypeAttr>();
5424 return false;
5425}
5426
5427bool Type::hasSizedVLAType() const {
5428 if (!isVariablyModifiedType())
5429 return false;
5430
5431 if (const auto *ptr = getAs<PointerType>())
5432 return ptr->getPointeeType()->hasSizedVLAType();
5433 if (const auto *ref = getAs<ReferenceType>())
5434 return ref->getPointeeType()->hasSizedVLAType();
5435 if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
5436 if (isa<VariableArrayType>(Val: arr) &&
5437 cast<VariableArrayType>(Val: arr)->getSizeExpr())
5438 return true;
5439
5440 return arr->getElementType()->hasSizedVLAType();
5441 }
5442
5443 return false;
5444}
5445
5446bool Type::isHLSLResourceRecord() const {
5447 return HLSLAttributedResourceType::findHandleTypeOnResource(RT: this) != nullptr;
5448}
5449
5450bool Type::isHLSLResourceRecordArray() const {
5451 const Type *Ty = getUnqualifiedDesugaredType();
5452 if (!Ty->isArrayType())
5453 return false;
5454 while (isa<ArrayType>(Val: Ty))
5455 Ty = Ty->getArrayElementTypeNoTypeQual();
5456 return Ty->isHLSLResourceRecord();
5457}
5458
5459bool Type::isHLSLIntangibleType() const {
5460 const Type *Ty = getUnqualifiedDesugaredType();
5461
5462 // check if it's a builtin type first
5463 if (Ty->isBuiltinType())
5464 return Ty->isHLSLBuiltinIntangibleType();
5465
5466 // unwrap arrays
5467 while (isa<ArrayType>(Val: Ty))
5468 Ty = Ty->getArrayElementTypeNoTypeQual();
5469
5470 const RecordType *RT =
5471 dyn_cast<RecordType>(Val: Ty->getUnqualifiedDesugaredType());
5472 if (!RT)
5473 return false;
5474
5475 CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
5476 assert(RD != nullptr &&
5477 "all HLSL structs and classes should be CXXRecordDecl");
5478 assert(RD->isCompleteDefinition() && "expecting complete type");
5479 return RD->isHLSLIntangible();
5480}
5481
5482QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
5483 switch (type.getObjCLifetime()) {
5484 case Qualifiers::OCL_None:
5485 case Qualifiers::OCL_ExplicitNone:
5486 case Qualifiers::OCL_Autoreleasing:
5487 break;
5488
5489 case Qualifiers::OCL_Strong:
5490 return DK_objc_strong_lifetime;
5491 case Qualifiers::OCL_Weak:
5492 return DK_objc_weak_lifetime;
5493 }
5494
5495 if (const auto *RD = type->getBaseElementTypeUnsafe()->getAsRecordDecl()) {
5496 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
5497 /// Check if this is a C++ object with a non-trivial destructor.
5498 if (CXXRD->hasDefinition() && !CXXRD->hasTrivialDestructor())
5499 return DK_cxx_destructor;
5500 } else {
5501 /// Check if this is a C struct that is non-trivial to destroy or an array
5502 /// that contains such a struct.
5503 if (RD->isNonTrivialToPrimitiveDestroy())
5504 return DK_nontrivial_c_struct;
5505 }
5506 }
5507
5508 return DK_none;
5509}
5510
5511bool MemberPointerType::isSugared() const {
5512 CXXRecordDecl *D1 = getMostRecentCXXRecordDecl(),
5513 *D2 = getQualifier().getAsRecordDecl();
5514 assert(!D1 == !D2);
5515 return D1 != D2 && D1->getCanonicalDecl() != D2->getCanonicalDecl();
5516}
5517
5518void MemberPointerType::Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
5519 const NestedNameSpecifier Qualifier,
5520 const CXXRecordDecl *Cls) {
5521 ID.AddPointer(Ptr: Pointee.getAsOpaquePtr());
5522 Qualifier.Profile(ID);
5523 if (Cls)
5524 ID.AddPointer(Ptr: Cls->getCanonicalDecl());
5525}
5526
5527CXXRecordDecl *MemberPointerType::getCXXRecordDecl() const {
5528 return dyn_cast<MemberPointerType>(Val: getCanonicalTypeInternal())
5529 ->getQualifier()
5530 .getAsRecordDecl();
5531}
5532
5533CXXRecordDecl *MemberPointerType::getMostRecentCXXRecordDecl() const {
5534 auto *RD = getCXXRecordDecl();
5535 if (!RD)
5536 return nullptr;
5537 return RD->getMostRecentDecl();
5538}
5539
5540void clang::FixedPointValueToString(SmallVectorImpl<char> &Str,
5541 llvm::APSInt Val, unsigned Scale) {
5542 llvm::FixedPointSemantics FXSema(Val.getBitWidth(), Scale, Val.isSigned(),
5543 /*IsSaturated=*/false,
5544 /*HasUnsignedPadding=*/false);
5545 llvm::APFixedPoint(Val, FXSema).toString(Str);
5546}
5547
5548DeducedType::DeducedType(TypeClass TC, DeducedKind DK,
5549 QualType DeducedAsTypeOrCanon)
5550 : Type(TC, /*canon=*/DK == DeducedKind::Deduced
5551 ? DeducedAsTypeOrCanon.getCanonicalType()
5552 : DeducedAsTypeOrCanon,
5553 TypeDependence::None) {
5554 DeducedTypeBits.Kind = llvm::to_underlying(E: DK);
5555 switch (DK) {
5556 case DeducedKind::Undeduced:
5557 break;
5558 case DeducedKind::Deduced:
5559 assert(!DeducedAsTypeOrCanon.isNull() && "Deduced type cannot be null");
5560 addDependence(D: DeducedAsTypeOrCanon->getDependence() &
5561 ~TypeDependence::VariablyModified);
5562 DeducedAsType = DeducedAsTypeOrCanon;
5563 break;
5564 case DeducedKind::DeducedAsPack:
5565 addDependence(D: TypeDependence::UnexpandedPack);
5566 [[fallthrough]];
5567 case DeducedKind::DeducedAsDependent:
5568 addDependence(D: TypeDependence::DependentInstantiation);
5569 break;
5570 }
5571 assert(getDeducedKind() == DK && "DeducedKind does not match the type state");
5572}
5573
5574AutoType::AutoType(DeducedKind DK, QualType DeducedAsTypeOrCanon,
5575 AutoTypeKeyword Keyword, TemplateDecl *TypeConstraintConcept,
5576 ArrayRef<TemplateArgument> TypeConstraintArgs)
5577 : DeducedType(Auto, DK, DeducedAsTypeOrCanon) {
5578 AutoTypeBits.Keyword = llvm::to_underlying(E: Keyword);
5579 AutoTypeBits.NumArgs = TypeConstraintArgs.size();
5580 this->TypeConstraintConcept = TypeConstraintConcept;
5581 assert(TypeConstraintConcept || AutoTypeBits.NumArgs == 0);
5582 if (TypeConstraintConcept) {
5583 auto Dep = TypeDependence::None;
5584 if (const auto *TTP =
5585 dyn_cast<TemplateTemplateParmDecl>(Val: TypeConstraintConcept))
5586 Dep = TypeDependence::DependentInstantiation |
5587 (TTP->isParameterPack() ? TypeDependence::UnexpandedPack
5588 : TypeDependence::None);
5589
5590 auto *ArgBuffer =
5591 const_cast<TemplateArgument *>(getTypeConstraintArguments().data());
5592 for (const TemplateArgument &Arg : TypeConstraintArgs) {
5593 Dep |= toTypeDependence(D: Arg.getDependence());
5594 new (ArgBuffer++) TemplateArgument(Arg);
5595 }
5596 // A deduced AutoType only syntactically depends on its constraints.
5597 if (DK == DeducedKind::Deduced)
5598 Dep = toSyntacticDependence(D: Dep);
5599 addDependence(D: Dep);
5600 }
5601}
5602
5603void AutoType::Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
5604 DeducedKind DK, QualType Deduced,
5605 AutoTypeKeyword Keyword, TemplateDecl *CD,
5606 ArrayRef<TemplateArgument> Arguments) {
5607 DeducedType::Profile(ID, DK, Deduced);
5608 ID.AddInteger(I: llvm::to_underlying(E: Keyword));
5609 ID.AddPointer(Ptr: CD);
5610 for (const TemplateArgument &Arg : Arguments)
5611 Arg.Profile(ID, Context);
5612}
5613
5614void AutoType::Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5615 Profile(ID, Context, DK: getDeducedKind(), Deduced: getDeducedType(), Keyword: getKeyword(),
5616 CD: getTypeConstraintConcept(), Arguments: getTypeConstraintArguments());
5617}
5618
5619FunctionEffect::Kind FunctionEffect::oppositeKind() const {
5620 switch (kind()) {
5621 case Kind::NonBlocking:
5622 return Kind::Blocking;
5623 case Kind::Blocking:
5624 return Kind::NonBlocking;
5625 case Kind::NonAllocating:
5626 return Kind::Allocating;
5627 case Kind::Allocating:
5628 return Kind::NonAllocating;
5629 }
5630 llvm_unreachable("unknown effect kind");
5631}
5632
5633StringRef FunctionEffect::name() const {
5634 switch (kind()) {
5635 case Kind::NonBlocking:
5636 return "nonblocking";
5637 case Kind::NonAllocating:
5638 return "nonallocating";
5639 case Kind::Blocking:
5640 return "blocking";
5641 case Kind::Allocating:
5642 return "allocating";
5643 }
5644 llvm_unreachable("unknown effect kind");
5645}
5646
5647std::optional<FunctionEffect> FunctionEffect::effectProhibitingInference(
5648 const Decl &Callee, FunctionEffectKindSet CalleeFX) const {
5649 switch (kind()) {
5650 case Kind::NonAllocating:
5651 case Kind::NonBlocking: {
5652 for (FunctionEffect Effect : CalleeFX) {
5653 // nonblocking/nonallocating cannot call allocating.
5654 if (Effect.kind() == Kind::Allocating)
5655 return Effect;
5656 // nonblocking cannot call blocking.
5657 if (kind() == Kind::NonBlocking && Effect.kind() == Kind::Blocking)
5658 return Effect;
5659 }
5660 return std::nullopt;
5661 }
5662
5663 case Kind::Allocating:
5664 case Kind::Blocking:
5665 assert(0 && "effectProhibitingInference with non-inferable effect kind");
5666 break;
5667 }
5668 llvm_unreachable("unknown effect kind");
5669}
5670
5671bool FunctionEffect::shouldDiagnoseFunctionCall(
5672 bool Direct, FunctionEffectKindSet CalleeFX) const {
5673 switch (kind()) {
5674 case Kind::NonAllocating:
5675 case Kind::NonBlocking: {
5676 const Kind CallerKind = kind();
5677 for (FunctionEffect Effect : CalleeFX) {
5678 const Kind EK = Effect.kind();
5679 // Does callee have same or stronger constraint?
5680 if (EK == CallerKind ||
5681 (CallerKind == Kind::NonAllocating && EK == Kind::NonBlocking)) {
5682 return false; // no diagnostic
5683 }
5684 }
5685 return true; // warning
5686 }
5687 case Kind::Allocating:
5688 case Kind::Blocking:
5689 return false;
5690 }
5691 llvm_unreachable("unknown effect kind");
5692}
5693
5694// =====
5695
5696bool FunctionEffectSet::insert(const FunctionEffectWithCondition &NewEC,
5697 Conflicts &Errs) {
5698 FunctionEffect::Kind NewOppositeKind = NewEC.Effect.oppositeKind();
5699 Expr *NewCondition = NewEC.Cond.getCondition();
5700
5701 // The index at which insertion will take place; default is at end
5702 // but we might find an earlier insertion point.
5703 unsigned InsertIdx = Effects.size();
5704 unsigned Idx = 0;
5705 for (const FunctionEffectWithCondition &EC : *this) {
5706 // Note about effects with conditions: They are considered distinct from
5707 // those without conditions; they are potentially unique, redundant, or
5708 // in conflict, but we can't tell which until the condition is evaluated.
5709 if (EC.Cond.getCondition() == nullptr && NewCondition == nullptr) {
5710 if (EC.Effect.kind() == NewEC.Effect.kind()) {
5711 // There is no condition, and the effect kind is already present,
5712 // so just fail to insert the new one (creating a duplicate),
5713 // and return success.
5714 return true;
5715 }
5716
5717 if (EC.Effect.kind() == NewOppositeKind) {
5718 Errs.push_back(Elt: {.Kept: EC, .Rejected: NewEC});
5719 return false;
5720 }
5721 }
5722
5723 if (NewEC.Effect.kind() < EC.Effect.kind() && InsertIdx > Idx)
5724 InsertIdx = Idx;
5725
5726 ++Idx;
5727 }
5728
5729 if (NewCondition || !Conditions.empty()) {
5730 if (Conditions.empty() && !Effects.empty())
5731 Conditions.resize(N: Effects.size());
5732 Conditions.insert(I: Conditions.begin() + InsertIdx,
5733 Elt: NewEC.Cond.getCondition());
5734 }
5735 Effects.insert(I: Effects.begin() + InsertIdx, Elt: NewEC.Effect);
5736 return true;
5737}
5738
5739bool FunctionEffectSet::insert(const FunctionEffectsRef &Set, Conflicts &Errs) {
5740 for (const auto &Item : Set)
5741 insert(NewEC: Item, Errs);
5742 return Errs.empty();
5743}
5744
5745FunctionEffectSet FunctionEffectSet::getIntersection(FunctionEffectsRef LHS,
5746 FunctionEffectsRef RHS) {
5747 FunctionEffectSet Result;
5748 FunctionEffectSet::Conflicts Errs;
5749
5750 // We could use std::set_intersection but that would require expanding the
5751 // container interface to include push_back, making it available to clients
5752 // who might fail to maintain invariants.
5753 auto IterA = LHS.begin(), EndA = LHS.end();
5754 auto IterB = RHS.begin(), EndB = RHS.end();
5755
5756 auto FEWCLess = [](const FunctionEffectWithCondition &LHS,
5757 const FunctionEffectWithCondition &RHS) {
5758 return std::tuple(LHS.Effect, uintptr_t(LHS.Cond.getCondition())) <
5759 std::tuple(RHS.Effect, uintptr_t(RHS.Cond.getCondition()));
5760 };
5761
5762 while (IterA != EndA && IterB != EndB) {
5763 FunctionEffectWithCondition A = *IterA;
5764 FunctionEffectWithCondition B = *IterB;
5765 if (FEWCLess(A, B))
5766 ++IterA;
5767 else if (FEWCLess(B, A))
5768 ++IterB;
5769 else {
5770 Result.insert(NewEC: A, Errs);
5771 ++IterA;
5772 ++IterB;
5773 }
5774 }
5775
5776 // Insertion shouldn't be able to fail; that would mean both input
5777 // sets contained conflicts.
5778 assert(Errs.empty() && "conflict shouldn't be possible in getIntersection");
5779
5780 return Result;
5781}
5782
5783FunctionEffectSet FunctionEffectSet::getUnion(FunctionEffectsRef LHS,
5784 FunctionEffectsRef RHS,
5785 Conflicts &Errs) {
5786 // Optimize for either of the two sets being empty (very common).
5787 if (LHS.empty())
5788 return FunctionEffectSet(RHS);
5789
5790 FunctionEffectSet Combined(LHS);
5791 Combined.insert(Set: RHS, Errs);
5792 return Combined;
5793}
5794
5795namespace clang {
5796
5797raw_ostream &operator<<(raw_ostream &OS,
5798 const FunctionEffectWithCondition &CFE) {
5799 OS << CFE.Effect.name();
5800 if (Expr *E = CFE.Cond.getCondition()) {
5801 OS << '(';
5802 E->dump();
5803 OS << ')';
5804 }
5805 return OS;
5806}
5807
5808} // namespace clang
5809
5810LLVM_DUMP_METHOD void FunctionEffectsRef::dump(llvm::raw_ostream &OS) const {
5811 OS << "Effects{";
5812 llvm::interleaveComma(c: *this, os&: OS);
5813 OS << "}";
5814}
5815
5816LLVM_DUMP_METHOD void FunctionEffectSet::dump(llvm::raw_ostream &OS) const {
5817 FunctionEffectsRef(*this).dump(OS);
5818}
5819
5820LLVM_DUMP_METHOD void FunctionEffectKindSet::dump(llvm::raw_ostream &OS) const {
5821 OS << "Effects{";
5822 llvm::interleaveComma(c: *this, os&: OS);
5823 OS << "}";
5824}
5825
5826FunctionEffectsRef
5827FunctionEffectsRef::create(ArrayRef<FunctionEffect> FX,
5828 ArrayRef<EffectConditionExpr> Conds) {
5829 assert(llvm::is_sorted(FX) && "effects should be sorted");
5830 assert((Conds.empty() || Conds.size() == FX.size()) &&
5831 "effects size should match conditions size");
5832 return FunctionEffectsRef(FX, Conds);
5833}
5834
5835std::string FunctionEffectWithCondition::description() const {
5836 std::string Result(Effect.name().str());
5837 if (Cond.getCondition() != nullptr)
5838 Result += "(expr)";
5839 return Result;
5840}
5841
5842const HLSLAttributedResourceType *
5843HLSLAttributedResourceType::findHandleTypeOnResource(const Type *RT) {
5844 // If the type RT is an HLSL resource class, the first field must
5845 // be the resource handle of type HLSLAttributedResourceType
5846 const clang::Type *Ty = RT->getUnqualifiedDesugaredType();
5847 if (const RecordDecl *RD = Ty->getAsCXXRecordDecl()) {
5848 if (!RD->fields().empty()) {
5849 const auto &FirstFD = RD->fields().begin();
5850 return dyn_cast<HLSLAttributedResourceType>(
5851 Val: FirstFD->getType().getTypePtr());
5852 }
5853 }
5854 return nullptr;
5855}
5856
5857StringRef PredefinedSugarType::getName(Kind KD) {
5858 switch (KD) {
5859 case Kind::SizeT:
5860 return "__size_t";
5861 case Kind::SignedSizeT:
5862 return "__signed_size_t";
5863 case Kind::PtrdiffT:
5864 return "__ptrdiff_t";
5865 }
5866 llvm_unreachable("unexpected kind");
5867}
5868