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