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