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