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