clang 17.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"
35#include "clang/Basic/LLVM.h"
37#include "clang/Basic/Linkage.h"
42#include "llvm/ADT/APInt.h"
43#include "llvm/ADT/APSInt.h"
44#include "llvm/ADT/ArrayRef.h"
45#include "llvm/ADT/FoldingSet.h"
46#include "llvm/ADT/SmallVector.h"
47#include "llvm/Support/Casting.h"
48#include "llvm/Support/ErrorHandling.h"
49#include "llvm/Support/MathExtras.h"
50#include "llvm/TargetParser/RISCVTargetParser.h"
51#include <algorithm>
52#include <cassert>
53#include <cstdint>
54#include <cstring>
55#include <optional>
56#include <type_traits>
57
58using namespace clang;
59
61 return (*this != Other) &&
62 // CVR qualifiers superset
63 (((Mask & CVRMask) | (Other.Mask & CVRMask)) == (Mask & CVRMask)) &&
64 // ObjC GC qualifiers superset
65 ((getObjCGCAttr() == Other.getObjCGCAttr()) ||
66 (hasObjCGCAttr() && !Other.hasObjCGCAttr())) &&
67 // Address space superset.
68 ((getAddressSpace() == Other.getAddressSpace()) ||
69 (hasAddressSpace()&& !Other.hasAddressSpace())) &&
70 // Lifetime qualifier superset.
71 ((getObjCLifetime() == Other.getObjCLifetime()) ||
72 (hasObjCLifetime() && !Other.hasObjCLifetime()));
73}
74
76 const Type* ty = getTypePtr();
77 NamedDecl *ND = nullptr;
78 if (ty->isPointerType() || ty->isReferenceType())
80 else if (ty->isRecordType())
81 ND = ty->castAs<RecordType>()->getDecl();
82 else if (ty->isEnumeralType())
83 ND = ty->castAs<EnumType>()->getDecl();
84 else if (ty->getTypeClass() == Type::Typedef)
85 ND = ty->castAs<TypedefType>()->getDecl();
86 else if (ty->isArrayType())
87 return ty->castAsArrayTypeUnsafe()->
88 getElementType().getBaseTypeIdentifier();
89
90 if (ND)
91 return ND->getIdentifier();
92 return nullptr;
93}
94
96 const auto *ClassDecl = getTypePtr()->getPointeeCXXRecordDecl();
97 return ClassDecl && ClassDecl->mayBeDynamicClass();
98}
99
101 const auto *ClassDecl = getTypePtr()->getPointeeCXXRecordDecl();
102 return !ClassDecl || ClassDecl->mayBeNonDynamicClass();
103}
104
105bool QualType::isConstant(QualType T, const ASTContext &Ctx) {
106 if (T.isConstQualified())
107 return true;
108
109 if (const ArrayType *AT = Ctx.getAsArrayType(T))
110 return AT->getElementType().isConstant(Ctx);
111
113}
114
115// C++ [temp.dep.type]p1:
116// A type is dependent if it is...
117// - an array type constructed from any dependent type or whose
118// size is specified by a constant expression that is
119// value-dependent,
121 ArraySizeModifier sm, unsigned tq, const Expr *sz)
122 // Note, we need to check for DependentSizedArrayType explicitly here
123 // because we use a DependentSizedArrayType with no size expression as the
124 // type of a dependent array of unknown bound with a dependent braced
125 // initializer:
126 //
127 // template<int ...N> int arr[] = {N...};
128 : Type(tc, can,
129 et->getDependence() |
130 (sz ? toTypeDependence(
131 turnValueToTypeDependence(sz->getDependence()))
132 : TypeDependence::None) |
133 (tc == VariableArray ? TypeDependence::VariablyModified
134 : TypeDependence::None) |
135 (tc == DependentSizedArray
136 ? TypeDependence::DependentInstantiation
137 : TypeDependence::None)),
138 ElementType(et) {
139 ArrayTypeBits.IndexTypeQuals = tq;
140 ArrayTypeBits.SizeModifier = sm;
141}
142
144 QualType ElementType,
145 const llvm::APInt &NumElements) {
146 uint64_t ElementSize = Context.getTypeSizeInChars(ElementType).getQuantity();
147
148 // Fast path the common cases so we can avoid the conservative computation
149 // below, which in common cases allocates "large" APSInt values, which are
150 // slow.
151
152 // If the element size is a power of 2, we can directly compute the additional
153 // number of addressing bits beyond those required for the element count.
154 if (llvm::isPowerOf2_64(ElementSize)) {
155 return NumElements.getActiveBits() + llvm::Log2_64(ElementSize);
156 }
157
158 // If both the element count and element size fit in 32-bits, we can do the
159 // computation directly in 64-bits.
160 if ((ElementSize >> 32) == 0 && NumElements.getBitWidth() <= 64 &&
161 (NumElements.getZExtValue() >> 32) == 0) {
162 uint64_t TotalSize = NumElements.getZExtValue() * ElementSize;
163 return llvm::bit_width(TotalSize);
164 }
165
166 // Otherwise, use APSInt to handle arbitrary sized values.
167 llvm::APSInt SizeExtended(NumElements, true);
168 unsigned SizeTypeBits = Context.getTypeSize(Context.getSizeType());
169 SizeExtended = SizeExtended.extend(std::max(SizeTypeBits,
170 SizeExtended.getBitWidth()) * 2);
171
172 llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize));
173 TotalSize *= SizeExtended;
174
175 return TotalSize.getActiveBits();
176}
177
179 unsigned Bits = Context.getTypeSize(Context.getSizeType());
180
181 // Limit the number of bits in size_t so that maximal bit size fits 64 bit
182 // integer (see PR8256). We can do this as currently there is no hardware
183 // that supports full 64-bit virtual space.
184 if (Bits > 61)
185 Bits = 61;
186
187 return Bits;
188}
189
190void ConstantArrayType::Profile(llvm::FoldingSetNodeID &ID,
191 const ASTContext &Context, QualType ET,
192 const llvm::APInt &ArraySize,
193 const Expr *SizeExpr, ArraySizeModifier SizeMod,
194 unsigned TypeQuals) {
195 ID.AddPointer(ET.getAsOpaquePtr());
196 ID.AddInteger(ArraySize.getZExtValue());
197 ID.AddInteger(SizeMod);
198 ID.AddInteger(TypeQuals);
199 ID.AddBoolean(SizeExpr != nullptr);
200 if (SizeExpr)
201 SizeExpr->Profile(ID, Context, true);
202}
203
204DependentSizedArrayType::DependentSizedArrayType(const ASTContext &Context,
205 QualType et, QualType can,
206 Expr *e, ArraySizeModifier sm,
207 unsigned tq,
208 SourceRange brackets)
209 : ArrayType(DependentSizedArray, et, can, sm, tq, e),
210 Context(Context), SizeExpr((Stmt*) e), Brackets(brackets) {}
211
212void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID,
213 const ASTContext &Context,
214 QualType ET,
215 ArraySizeModifier SizeMod,
216 unsigned TypeQuals,
217 Expr *E) {
218 ID.AddPointer(ET.getAsOpaquePtr());
219 ID.AddInteger(SizeMod);
220 ID.AddInteger(TypeQuals);
221 E->Profile(ID, Context, true);
222}
223
224DependentVectorType::DependentVectorType(const ASTContext &Context,
225 QualType ElementType,
226 QualType CanonType, Expr *SizeExpr,
227 SourceLocation Loc,
229 : Type(DependentVector, CanonType,
230 TypeDependence::DependentInstantiation |
231 ElementType->getDependence() |
232 (SizeExpr ? toTypeDependence(SizeExpr->getDependence())
233 : TypeDependence::None)),
234 Context(Context), ElementType(ElementType), SizeExpr(SizeExpr), Loc(Loc) {
235 VectorTypeBits.VecKind = VecKind;
236}
237
238void DependentVectorType::Profile(llvm::FoldingSetNodeID &ID,
239 const ASTContext &Context,
240 QualType ElementType, const Expr *SizeExpr,
241 VectorType::VectorKind VecKind) {
242 ID.AddPointer(ElementType.getAsOpaquePtr());
243 ID.AddInteger(VecKind);
244 SizeExpr->Profile(ID, Context, true);
245}
246
247DependentSizedExtVectorType::DependentSizedExtVectorType(
248 const ASTContext &Context, QualType ElementType, QualType can,
249 Expr *SizeExpr, SourceLocation loc)
250 : Type(DependentSizedExtVector, can,
251 TypeDependence::DependentInstantiation |
252 ElementType->getDependence() |
253 (SizeExpr ? toTypeDependence(SizeExpr->getDependence())
254 : TypeDependence::None)),
255 Context(Context), SizeExpr(SizeExpr), ElementType(ElementType), loc(loc) {
256}
257
258void
259DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID,
260 const ASTContext &Context,
261 QualType ElementType, Expr *SizeExpr) {
262 ID.AddPointer(ElementType.getAsOpaquePtr());
263 SizeExpr->Profile(ID, Context, true);
264}
265
266DependentAddressSpaceType::DependentAddressSpaceType(const ASTContext &Context,
267 QualType PointeeType,
268 QualType can,
269 Expr *AddrSpaceExpr,
270 SourceLocation loc)
271 : Type(DependentAddressSpace, can,
272 TypeDependence::DependentInstantiation |
273 PointeeType->getDependence() |
274 (AddrSpaceExpr ? toTypeDependence(AddrSpaceExpr->getDependence())
275 : TypeDependence::None)),
276 Context(Context), AddrSpaceExpr(AddrSpaceExpr), PointeeType(PointeeType),
277 loc(loc) {}
278
279void DependentAddressSpaceType::Profile(llvm::FoldingSetNodeID &ID,
280 const ASTContext &Context,
281 QualType PointeeType,
282 Expr *AddrSpaceExpr) {
283 ID.AddPointer(PointeeType.getAsOpaquePtr());
284 AddrSpaceExpr->Profile(ID, Context, true);
285}
286
288 const Expr *RowExpr, const Expr *ColumnExpr)
289 : Type(tc, canonType,
290 (RowExpr ? (matrixType->getDependence() | TypeDependence::Dependent |
291 TypeDependence::Instantiation |
292 (matrixType->isVariablyModifiedType()
293 ? TypeDependence::VariablyModified
294 : TypeDependence::None) |
295 (matrixType->containsUnexpandedParameterPack() ||
296 (RowExpr &&
297 RowExpr->containsUnexpandedParameterPack()) ||
298 (ColumnExpr &&
299 ColumnExpr->containsUnexpandedParameterPack())
300 ? TypeDependence::UnexpandedPack
302 : matrixType->getDependence())),
303 ElementType(matrixType) {}
304
306 unsigned nColumns, QualType canonType)
307 : ConstantMatrixType(ConstantMatrix, matrixType, nRows, nColumns,
308 canonType) {}
309
311 unsigned nRows, unsigned nColumns,
312 QualType canonType)
313 : MatrixType(tc, matrixType, canonType), NumRows(nRows),
314 NumColumns(nColumns) {}
315
316DependentSizedMatrixType::DependentSizedMatrixType(
317 const ASTContext &CTX, QualType ElementType, QualType CanonicalType,
318 Expr *RowExpr, Expr *ColumnExpr, SourceLocation loc)
319 : MatrixType(DependentSizedMatrix, ElementType, CanonicalType, RowExpr,
320 ColumnExpr),
321 Context(CTX), RowExpr(RowExpr), ColumnExpr(ColumnExpr), loc(loc) {}
322
323void DependentSizedMatrixType::Profile(llvm::FoldingSetNodeID &ID,
324 const ASTContext &CTX,
325 QualType ElementType, Expr *RowExpr,
326 Expr *ColumnExpr) {
327 ID.AddPointer(ElementType.getAsOpaquePtr());
328 RowExpr->Profile(ID, CTX, true);
329 ColumnExpr->Profile(ID, CTX, true);
330}
331
332VectorType::VectorType(QualType vecType, unsigned nElements, QualType canonType,
333 VectorKind vecKind)
334 : VectorType(Vector, vecType, nElements, canonType, vecKind) {}
335
336VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements,
337 QualType canonType, VectorKind vecKind)
338 : Type(tc, canonType, vecType->getDependence()), ElementType(vecType) {
339 VectorTypeBits.VecKind = vecKind;
340 VectorTypeBits.NumElements = nElements;
341}
342
343BitIntType::BitIntType(bool IsUnsigned, unsigned NumBits)
344 : Type(BitInt, QualType{}, TypeDependence::None), IsUnsigned(IsUnsigned),
345 NumBits(NumBits) {}
346
348 bool IsUnsigned, Expr *NumBitsExpr)
349 : Type(DependentBitInt, QualType{},
350 toTypeDependence(NumBitsExpr->getDependence())),
351 Context(Context), ExprAndUnsigned(NumBitsExpr, IsUnsigned) {}
352
354 return ExprAndUnsigned.getInt();
355}
356
358 return ExprAndUnsigned.getPointer();
359}
360
361void DependentBitIntType::Profile(llvm::FoldingSetNodeID &ID,
362 const ASTContext &Context, bool IsUnsigned,
363 Expr *NumBitsExpr) {
364 ID.AddBoolean(IsUnsigned);
365 NumBitsExpr->Profile(ID, Context, true);
366}
367
368/// getArrayElementTypeNoTypeQual - If this is an array type, return the
369/// element type of the array, potentially with type qualifiers missing.
370/// This method should never be used when type qualifiers are meaningful.
372 // If this is directly an array type, return it.
373 if (const auto *ATy = dyn_cast<ArrayType>(this))
374 return ATy->getElementType().getTypePtr();
375
376 // If the canonical form of this type isn't the right kind, reject it.
377 if (!isa<ArrayType>(CanonicalType))
378 return nullptr;
379
380 // If this is a typedef for an array type, strip the typedef off without
381 // losing all typedef information.
382 return cast<ArrayType>(getUnqualifiedDesugaredType())
383 ->getElementType().getTypePtr();
384}
385
386/// getDesugaredType - Return the specified type with any "sugar" removed from
387/// the type. This takes off typedefs, typeof's etc. If the outer level of
388/// the type is already concrete, it returns it unmodified. This is similar
389/// to getting the canonical type, but it doesn't remove *all* typedefs. For
390/// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
391/// concrete.
394 return Context.getQualifiedType(split.Ty, split.Quals);
395}
396
397QualType QualType::getSingleStepDesugaredTypeImpl(QualType type,
398 const ASTContext &Context) {
399 SplitQualType split = type.split();
401 return Context.getQualifiedType(desugar, split.Quals);
402}
403
404// Check that no type class is polymorphic. LLVM style RTTI should be used
405// instead. If absolutely needed an exception can still be added here by
406// defining the appropriate macro (but please don't do this).
407#define TYPE(CLASS, BASE) \
408 static_assert(!std::is_polymorphic<CLASS##Type>::value, \
409 #CLASS "Type should not be polymorphic!");
410#include "clang/AST/TypeNodes.inc"
411
412// Check that no type class has a non-trival destructor. Types are
413// allocated with the BumpPtrAllocator from ASTContext and therefore
414// their destructor is not executed.
415//
416// FIXME: ConstantArrayType is not trivially destructible because of its
417// APInt member. It should be replaced in favor of ASTContext allocation.
418#define TYPE(CLASS, BASE) \
419 static_assert(std::is_trivially_destructible<CLASS##Type>::value || \
420 std::is_same<CLASS##Type, ConstantArrayType>::value, \
421 #CLASS "Type should be trivially destructible!");
422#include "clang/AST/TypeNodes.inc"
423
425 switch (getTypeClass()) {
426#define ABSTRACT_TYPE(Class, Parent)
427#define TYPE(Class, Parent) \
428 case Type::Class: { \
429 const auto *ty = cast<Class##Type>(this); \
430 if (!ty->isSugared()) return QualType(ty, 0); \
431 return ty->desugar(); \
432 }
433#include "clang/AST/TypeNodes.inc"
434 }
435 llvm_unreachable("bad type kind!");
436}
437
440
441 QualType Cur = T;
442 while (true) {
443 const Type *CurTy = Qs.strip(Cur);
444 switch (CurTy->getTypeClass()) {
445#define ABSTRACT_TYPE(Class, Parent)
446#define TYPE(Class, Parent) \
447 case Type::Class: { \
448 const auto *Ty = cast<Class##Type>(CurTy); \
449 if (!Ty->isSugared()) \
450 return SplitQualType(Ty, Qs); \
451 Cur = Ty->desugar(); \
452 break; \
453 }
454#include "clang/AST/TypeNodes.inc"
455 }
456 }
457}
458
459SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) {
460 SplitQualType split = type.split();
461
462 // All the qualifiers we've seen so far.
463 Qualifiers quals = split.Quals;
464
465 // The last type node we saw with any nodes inside it.
466 const Type *lastTypeWithQuals = split.Ty;
467
468 while (true) {
469 QualType next;
470
471 // Do a single-step desugar, aborting the loop if the type isn't
472 // sugared.
473 switch (split.Ty->getTypeClass()) {
474#define ABSTRACT_TYPE(Class, Parent)
475#define TYPE(Class, Parent) \
476 case Type::Class: { \
477 const auto *ty = cast<Class##Type>(split.Ty); \
478 if (!ty->isSugared()) goto done; \
479 next = ty->desugar(); \
480 break; \
481 }
482#include "clang/AST/TypeNodes.inc"
483 }
484
485 // Otherwise, split the underlying type. If that yields qualifiers,
486 // update the information.
487 split = next.split();
488 if (!split.Quals.empty()) {
489 lastTypeWithQuals = split.Ty;
491 }
492 }
493
494 done:
495 return SplitQualType(lastTypeWithQuals, quals);
496}
497
499 // FIXME: this seems inherently un-qualifiers-safe.
500 while (const auto *PT = T->getAs<ParenType>())
501 T = PT->getInnerType();
502 return T;
503}
504
505/// This will check for a T (which should be a Type which can act as
506/// sugar, such as a TypedefType) by removing any existing sugar until it
507/// reaches a T or a non-sugared type.
508template<typename T> static const T *getAsSugar(const Type *Cur) {
509 while (true) {
510 if (const auto *Sugar = dyn_cast<T>(Cur))
511 return Sugar;
512 switch (Cur->getTypeClass()) {
513#define ABSTRACT_TYPE(Class, Parent)
514#define TYPE(Class, Parent) \
515 case Type::Class: { \
516 const auto *Ty = cast<Class##Type>(Cur); \
517 if (!Ty->isSugared()) return 0; \
518 Cur = Ty->desugar().getTypePtr(); \
519 break; \
520 }
521#include "clang/AST/TypeNodes.inc"
522 }
523 }
524}
525
526template <> const TypedefType *Type::getAs() const {
527 return getAsSugar<TypedefType>(this);
528}
529
530template <> const UsingType *Type::getAs() const {
531 return getAsSugar<UsingType>(this);
532}
533
534template <> const TemplateSpecializationType *Type::getAs() const {
535 return getAsSugar<TemplateSpecializationType>(this);
536}
537
538template <> const AttributedType *Type::getAs() const {
539 return getAsSugar<AttributedType>(this);
540}
541
542/// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
543/// sugar off the given type. This should produce an object of the
544/// same dynamic type as the canonical type.
546 const Type *Cur = this;
547
548 while (true) {
549 switch (Cur->getTypeClass()) {
550#define ABSTRACT_TYPE(Class, Parent)
551#define TYPE(Class, Parent) \
552 case Class: { \
553 const auto *Ty = cast<Class##Type>(Cur); \
554 if (!Ty->isSugared()) return Cur; \
555 Cur = Ty->desugar().getTypePtr(); \
556 break; \
557 }
558#include "clang/AST/TypeNodes.inc"
559 }
560 }
561}
562
563bool Type::isClassType() const {
564 if (const auto *RT = getAs<RecordType>())
565 return RT->getDecl()->isClass();
566 return false;
567}
568
570 if (const auto *RT = getAs<RecordType>())
571 return RT->getDecl()->isStruct();
572 return false;
573}
574
576 if (const auto *RT = getAs<RecordType>())
577 return RT->getDecl()->hasAttr<ObjCBoxableAttr>();
578 return false;
579}
580
582 if (const auto *RT = getAs<RecordType>())
583 return RT->getDecl()->isInterface();
584 return false;
585}
586
588 if (const auto *RT = getAs<RecordType>()) {
589 RecordDecl *RD = RT->getDecl();
590 return RD->isStruct() || RD->isClass() || RD->isInterface();
591 }
592 return false;
593}
594
596 if (const auto *PT = getAs<PointerType>())
597 return PT->getPointeeType()->isVoidType();
598 return false;
599}
600
601bool Type::isUnionType() const {
602 if (const auto *RT = getAs<RecordType>())
603 return RT->getDecl()->isUnion();
604 return false;
605}
606
608 if (const auto *CT = dyn_cast<ComplexType>(CanonicalType))
609 return CT->getElementType()->isFloatingType();
610 return false;
611}
612
614 // Check for GCC complex integer extension.
616}
617
619 if (const auto *ET = getAs<EnumType>())
620 return ET->getDecl()->isScoped();
621 return false;
622}
623
625 if (const auto *Complex = getAs<ComplexType>())
626 if (Complex->getElementType()->isIntegerType())
627 return Complex;
628 return nullptr;
629}
630
632 if (const auto *PT = getAs<PointerType>())
633 return PT->getPointeeType();
634 if (const auto *OPT = getAs<ObjCObjectPointerType>())
635 return OPT->getPointeeType();
636 if (const auto *BPT = getAs<BlockPointerType>())
637 return BPT->getPointeeType();
638 if (const auto *RT = getAs<ReferenceType>())
639 return RT->getPointeeType();
640 if (const auto *MPT = getAs<MemberPointerType>())
641 return MPT->getPointeeType();
642 if (const auto *DT = getAs<DecayedType>())
643 return DT->getPointeeType();
644 return {};
645}
646
648 // If this is directly a structure type, return it.
649 if (const auto *RT = dyn_cast<RecordType>(this)) {
650 if (RT->getDecl()->isStruct())
651 return RT;
652 }
653
654 // If the canonical form of this type isn't the right kind, reject it.
655 if (const auto *RT = dyn_cast<RecordType>(CanonicalType)) {
656 if (!RT->getDecl()->isStruct())
657 return nullptr;
658
659 // If this is a typedef for a structure type, strip the typedef off without
660 // losing all typedef information.
661 return cast<RecordType>(getUnqualifiedDesugaredType());
662 }
663 return nullptr;
664}
665
667 // If this is directly a union type, return it.
668 if (const auto *RT = dyn_cast<RecordType>(this)) {
669 if (RT->getDecl()->isUnion())
670 return RT;
671 }
672
673 // If the canonical form of this type isn't the right kind, reject it.
674 if (const auto *RT = dyn_cast<RecordType>(CanonicalType)) {
675 if (!RT->getDecl()->isUnion())
676 return nullptr;
677
678 // If this is a typedef for a union type, strip the typedef off without
679 // losing all typedef information.
680 return cast<RecordType>(getUnqualifiedDesugaredType());
681 }
682
683 return nullptr;
684}
685
687 const ObjCObjectType *&bound) const {
688 bound = nullptr;
689
690 const auto *OPT = getAs<ObjCObjectPointerType>();
691 if (!OPT)
692 return false;
693
694 // Easy case: id.
695 if (OPT->isObjCIdType())
696 return true;
697
698 // If it's not a __kindof type, reject it now.
699 if (!OPT->isKindOfType())
700 return false;
701
702 // If it's Class or qualified Class, it's not an object type.
703 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType())
704 return false;
705
706 // Figure out the type bound for the __kindof type.
707 bound = OPT->getObjectType()->stripObjCKindOfTypeAndQuals(ctx)
709 return true;
710}
711
713 const auto *OPT = getAs<ObjCObjectPointerType>();
714 if (!OPT)
715 return false;
716
717 // Easy case: Class.
718 if (OPT->isObjCClassType())
719 return true;
720
721 // If it's not a __kindof type, reject it now.
722 if (!OPT->isKindOfType())
723 return false;
724
725 // If it's Class or qualified Class, it's a class __kindof type.
726 return OPT->isObjCClassType() || OPT->isObjCQualifiedClassType();
727}
728
729ObjCTypeParamType::ObjCTypeParamType(const ObjCTypeParamDecl *D, QualType can,
731 : Type(ObjCTypeParam, can, toSemanticDependence(can->getDependence())),
732 OTPDecl(const_cast<ObjCTypeParamDecl *>(D)) {
733 initialize(protocols);
734}
735
737 ArrayRef<QualType> typeArgs,
739 bool isKindOf)
740 : Type(ObjCObject, Canonical, Base->getDependence()), BaseType(Base) {
741 ObjCObjectTypeBits.IsKindOf = isKindOf;
742
743 ObjCObjectTypeBits.NumTypeArgs = typeArgs.size();
744 assert(getTypeArgsAsWritten().size() == typeArgs.size() &&
745 "bitfield overflow in type argument count");
746 if (!typeArgs.empty())
747 memcpy(getTypeArgStorage(), typeArgs.data(),
748 typeArgs.size() * sizeof(QualType));
749
750 for (auto typeArg : typeArgs) {
751 addDependence(typeArg->getDependence() & ~TypeDependence::VariablyModified);
752 }
753 // Initialize the protocol qualifiers. The protocol storage is known
754 // after we set number of type arguments.
755 initialize(protocols);
756}
757
759 // If we have type arguments written here, the type is specialized.
760 if (ObjCObjectTypeBits.NumTypeArgs > 0)
761 return true;
762
763 // Otherwise, check whether the base type is specialized.
764 if (const auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
765 // Terminate when we reach an interface type.
766 if (isa<ObjCInterfaceType>(objcObject))
767 return false;
768
769 return objcObject->isSpecialized();
770 }
771
772 // Not specialized.
773 return false;
774}
775
777 // We have type arguments written on this type.
779 return getTypeArgsAsWritten();
780
781 // Look at the base type, which might have type arguments.
782 if (const auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
783 // Terminate when we reach an interface type.
784 if (isa<ObjCInterfaceType>(objcObject))
785 return {};
786
787 return objcObject->getTypeArgs();
788 }
789
790 // No type arguments.
791 return {};
792}
793
796 return true;
797
798 // Look at the base type, which might have type arguments.
799 if (const auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
800 // Terminate when we reach an interface type.
801 if (isa<ObjCInterfaceType>(objcObject))
802 return false;
803
804 return objcObject->isKindOfType();
805 }
806
807 // Not a "__kindof" type.
808 return false;
809}
810
812 const ASTContext &ctx) const {
813 if (!isKindOfType() && qual_empty())
814 return QualType(this, 0);
815
816 // Recursively strip __kindof.
817 SplitQualType splitBaseType = getBaseType().split();
818 QualType baseType(splitBaseType.Ty, 0);
819 if (const auto *baseObj = splitBaseType.Ty->getAs<ObjCObjectType>())
820 baseType = baseObj->stripObjCKindOfTypeAndQuals(ctx);
821
822 return ctx.getObjCObjectType(ctx.getQualifiedType(baseType,
823 splitBaseType.Quals),
825 /*protocols=*/{},
826 /*isKindOf=*/false);
827}
828
831 if (ObjCInterfaceDecl *Def = Canon->getDefinition())
832 return Def;
833 return Canon;
834}
835
837 const ASTContext &ctx) const {
838 if (!isKindOfType() && qual_empty())
839 return this;
840
843}
844
845namespace {
846
847/// Visitor used to perform a simple type transformation that does not change
848/// the semantics of the type.
849template <typename Derived>
850struct SimpleTransformVisitor : public TypeVisitor<Derived, QualType> {
851 ASTContext &Ctx;
852
853 QualType recurse(QualType type) {
854 // Split out the qualifiers from the type.
855 SplitQualType splitType = type.split();
856
857 // Visit the type itself.
858 QualType result = static_cast<Derived *>(this)->Visit(splitType.Ty);
859 if (result.isNull())
860 return result;
861
862 // Reconstruct the transformed type by applying the local qualifiers
863 // from the split type.
864 return Ctx.getQualifiedType(result, splitType.Quals);
865 }
866
867public:
868 explicit SimpleTransformVisitor(ASTContext &ctx) : Ctx(ctx) {}
869
870 // None of the clients of this transformation can occur where
871 // there are dependent types, so skip dependent types.
872#define TYPE(Class, Base)
873#define DEPENDENT_TYPE(Class, Base) \
874 QualType Visit##Class##Type(const Class##Type *T) { return QualType(T, 0); }
875#include "clang/AST/TypeNodes.inc"
876
877#define TRIVIAL_TYPE_CLASS(Class) \
878 QualType Visit##Class##Type(const Class##Type *T) { return QualType(T, 0); }
879#define SUGARED_TYPE_CLASS(Class) \
880 QualType Visit##Class##Type(const Class##Type *T) { \
881 if (!T->isSugared()) \
882 return QualType(T, 0); \
883 QualType desugaredType = recurse(T->desugar()); \
884 if (desugaredType.isNull()) \
885 return {}; \
886 if (desugaredType.getAsOpaquePtr() == T->desugar().getAsOpaquePtr()) \
887 return QualType(T, 0); \
888 return desugaredType; \
889 }
890
891 TRIVIAL_TYPE_CLASS(Builtin)
892
893 QualType VisitComplexType(const ComplexType *T) {
894 QualType elementType = recurse(T->getElementType());
895 if (elementType.isNull())
896 return {};
897
898 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
899 return QualType(T, 0);
900
901 return Ctx.getComplexType(elementType);
902 }
903
904 QualType VisitPointerType(const PointerType *T) {
905 QualType pointeeType = recurse(T->getPointeeType());
906 if (pointeeType.isNull())
907 return {};
908
909 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
910 return QualType(T, 0);
911
912 return Ctx.getPointerType(pointeeType);
913 }
914
915 QualType VisitBlockPointerType(const BlockPointerType *T) {
916 QualType pointeeType = recurse(T->getPointeeType());
917 if (pointeeType.isNull())
918 return {};
919
920 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
921 return QualType(T, 0);
922
923 return Ctx.getBlockPointerType(pointeeType);
924 }
925
926 QualType VisitLValueReferenceType(const LValueReferenceType *T) {
927 QualType pointeeType = recurse(T->getPointeeTypeAsWritten());
928 if (pointeeType.isNull())
929 return {};
930
931 if (pointeeType.getAsOpaquePtr()
933 return QualType(T, 0);
934
935 return Ctx.getLValueReferenceType(pointeeType, T->isSpelledAsLValue());
936 }
937
938 QualType VisitRValueReferenceType(const RValueReferenceType *T) {
939 QualType pointeeType = recurse(T->getPointeeTypeAsWritten());
940 if (pointeeType.isNull())
941 return {};
942
943 if (pointeeType.getAsOpaquePtr()
945 return QualType(T, 0);
946
947 return Ctx.getRValueReferenceType(pointeeType);
948 }
949
950 QualType VisitMemberPointerType(const MemberPointerType *T) {
951 QualType pointeeType = recurse(T->getPointeeType());
952 if (pointeeType.isNull())
953 return {};
954
955 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
956 return QualType(T, 0);
957
958 return Ctx.getMemberPointerType(pointeeType, T->getClass());
959 }
960
961 QualType VisitConstantArrayType(const ConstantArrayType *T) {
962 QualType elementType = recurse(T->getElementType());
963 if (elementType.isNull())
964 return {};
965
966 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
967 return QualType(T, 0);
968
969 return Ctx.getConstantArrayType(elementType, T->getSize(), T->getSizeExpr(),
970 T->getSizeModifier(),
972 }
973
974 QualType VisitVariableArrayType(const VariableArrayType *T) {
975 QualType elementType = recurse(T->getElementType());
976 if (elementType.isNull())
977 return {};
978
979 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
980 return QualType(T, 0);
981
982 return Ctx.getVariableArrayType(elementType, T->getSizeExpr(),
983 T->getSizeModifier(),
985 T->getBracketsRange());
986 }
987
988 QualType VisitIncompleteArrayType(const IncompleteArrayType *T) {
989 QualType elementType = recurse(T->getElementType());
990 if (elementType.isNull())
991 return {};
992
993 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
994 return QualType(T, 0);
995
996 return Ctx.getIncompleteArrayType(elementType, T->getSizeModifier(),
998 }
999
1000 QualType VisitVectorType(const VectorType *T) {
1001 QualType elementType = recurse(T->getElementType());
1002 if (elementType.isNull())
1003 return {};
1004
1005 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
1006 return QualType(T, 0);
1007
1008 return Ctx.getVectorType(elementType, T->getNumElements(),
1009 T->getVectorKind());
1010 }
1011
1012 QualType VisitExtVectorType(const ExtVectorType *T) {
1013 QualType elementType = recurse(T->getElementType());
1014 if (elementType.isNull())
1015 return {};
1016
1017 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
1018 return QualType(T, 0);
1019
1020 return Ctx.getExtVectorType(elementType, T->getNumElements());
1021 }
1022
1023 QualType VisitConstantMatrixType(const ConstantMatrixType *T) {
1024 QualType elementType = recurse(T->getElementType());
1025 if (elementType.isNull())
1026 return {};
1027 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
1028 return QualType(T, 0);
1029
1030 return Ctx.getConstantMatrixType(elementType, T->getNumRows(),
1031 T->getNumColumns());
1032 }
1033
1034 QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
1035 QualType returnType = recurse(T->getReturnType());
1036 if (returnType.isNull())
1037 return {};
1038
1039 if (returnType.getAsOpaquePtr() == T->getReturnType().getAsOpaquePtr())
1040 return QualType(T, 0);
1041
1042 return Ctx.getFunctionNoProtoType(returnType, T->getExtInfo());
1043 }
1044
1045 QualType VisitFunctionProtoType(const FunctionProtoType *T) {
1046 QualType returnType = recurse(T->getReturnType());
1047 if (returnType.isNull())
1048 return {};
1049
1050 // Transform parameter types.
1051 SmallVector<QualType, 4> paramTypes;
1052 bool paramChanged = false;
1053 for (auto paramType : T->getParamTypes()) {
1054 QualType newParamType = recurse(paramType);
1055 if (newParamType.isNull())
1056 return {};
1057
1058 if (newParamType.getAsOpaquePtr() != paramType.getAsOpaquePtr())
1059 paramChanged = true;
1060
1061 paramTypes.push_back(newParamType);
1062 }
1063
1064 // Transform extended info.
1066 bool exceptionChanged = false;
1067 if (info.ExceptionSpec.Type == EST_Dynamic) {
1068 SmallVector<QualType, 4> exceptionTypes;
1069 for (auto exceptionType : info.ExceptionSpec.Exceptions) {
1070 QualType newExceptionType = recurse(exceptionType);
1071 if (newExceptionType.isNull())
1072 return {};
1073
1074 if (newExceptionType.getAsOpaquePtr() != exceptionType.getAsOpaquePtr())
1075 exceptionChanged = true;
1076
1077 exceptionTypes.push_back(newExceptionType);
1078 }
1079
1080 if (exceptionChanged) {
1082 llvm::ArrayRef(exceptionTypes).copy(Ctx);
1083 }
1084 }
1085
1086 if (returnType.getAsOpaquePtr() == T->getReturnType().getAsOpaquePtr() &&
1087 !paramChanged && !exceptionChanged)
1088 return QualType(T, 0);
1089
1090 return Ctx.getFunctionType(returnType, paramTypes, info);
1091 }
1092
1093 QualType VisitParenType(const ParenType *T) {
1094 QualType innerType = recurse(T->getInnerType());
1095 if (innerType.isNull())
1096 return {};
1097
1098 if (innerType.getAsOpaquePtr() == T->getInnerType().getAsOpaquePtr())
1099 return QualType(T, 0);
1100
1101 return Ctx.getParenType(innerType);
1102 }
1103
1104 SUGARED_TYPE_CLASS(Typedef)
1105 SUGARED_TYPE_CLASS(ObjCTypeParam)
1106 SUGARED_TYPE_CLASS(MacroQualified)
1107
1108 QualType VisitAdjustedType(const AdjustedType *T) {
1109 QualType originalType = recurse(T->getOriginalType());
1110 if (originalType.isNull())
1111 return {};
1112
1113 QualType adjustedType = recurse(T->getAdjustedType());
1114 if (adjustedType.isNull())
1115 return {};
1116
1117 if (originalType.getAsOpaquePtr()
1118 == T->getOriginalType().getAsOpaquePtr() &&
1119 adjustedType.getAsOpaquePtr() == T->getAdjustedType().getAsOpaquePtr())
1120 return QualType(T, 0);
1121
1122 return Ctx.getAdjustedType(originalType, adjustedType);
1123 }
1124
1125 QualType VisitDecayedType(const DecayedType *T) {
1126 QualType originalType = recurse(T->getOriginalType());
1127 if (originalType.isNull())
1128 return {};
1129
1130 if (originalType.getAsOpaquePtr()
1132 return QualType(T, 0);
1133
1134 return Ctx.getDecayedType(originalType);
1135 }
1136
1137 SUGARED_TYPE_CLASS(TypeOfExpr)
1138 SUGARED_TYPE_CLASS(TypeOf)
1139 SUGARED_TYPE_CLASS(Decltype)
1140 SUGARED_TYPE_CLASS(UnaryTransform)
1141 TRIVIAL_TYPE_CLASS(Record)
1143
1144 // FIXME: Non-trivial to implement, but important for C++
1145 SUGARED_TYPE_CLASS(Elaborated)
1146
1147 QualType VisitAttributedType(const AttributedType *T) {
1148 QualType modifiedType = recurse(T->getModifiedType());
1149 if (modifiedType.isNull())
1150 return {};
1151
1152 QualType equivalentType = recurse(T->getEquivalentType());
1153 if (equivalentType.isNull())
1154 return {};
1155
1156 if (modifiedType.getAsOpaquePtr()
1157 == T->getModifiedType().getAsOpaquePtr() &&
1158 equivalentType.getAsOpaquePtr()
1160 return QualType(T, 0);
1161
1162 return Ctx.getAttributedType(T->getAttrKind(), modifiedType,
1163 equivalentType);
1164 }
1165
1166 QualType VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1167 QualType replacementType = recurse(T->getReplacementType());
1168 if (replacementType.isNull())
1169 return {};
1170
1171 if (replacementType.getAsOpaquePtr()
1173 return QualType(T, 0);
1174
1175 return Ctx.getSubstTemplateTypeParmType(replacementType,
1176 T->getAssociatedDecl(),
1177 T->getIndex(), T->getPackIndex());
1178 }
1179
1180 // FIXME: Non-trivial to implement, but important for C++
1181 SUGARED_TYPE_CLASS(TemplateSpecialization)
1182
1183 QualType VisitAutoType(const AutoType *T) {
1184 if (!T->isDeduced())
1185 return QualType(T, 0);
1186
1187 QualType deducedType = recurse(T->getDeducedType());
1188 if (deducedType.isNull())
1189 return {};
1190
1191 if (deducedType.getAsOpaquePtr()
1193 return QualType(T, 0);
1194
1195 return Ctx.getAutoType(deducedType, T->getKeyword(),
1196 T->isDependentType(), /*IsPack=*/false,
1199 }
1200
1201 QualType VisitObjCObjectType(const ObjCObjectType *T) {
1202 QualType baseType = recurse(T->getBaseType());
1203 if (baseType.isNull())
1204 return {};
1205
1206 // Transform type arguments.
1207 bool typeArgChanged = false;
1208 SmallVector<QualType, 4> typeArgs;
1209 for (auto typeArg : T->getTypeArgsAsWritten()) {
1210 QualType newTypeArg = recurse(typeArg);
1211 if (newTypeArg.isNull())
1212 return {};
1213
1214 if (newTypeArg.getAsOpaquePtr() != typeArg.getAsOpaquePtr())
1215 typeArgChanged = true;
1216
1217 typeArgs.push_back(newTypeArg);
1218 }
1219
1220 if (baseType.getAsOpaquePtr() == T->getBaseType().getAsOpaquePtr() &&
1221 !typeArgChanged)
1222 return QualType(T, 0);
1223
1224 return Ctx.getObjCObjectType(
1225 baseType, typeArgs,
1228 }
1229
1230 TRIVIAL_TYPE_CLASS(ObjCInterface)
1231
1232 QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
1233 QualType pointeeType = recurse(T->getPointeeType());
1234 if (pointeeType.isNull())
1235 return {};
1236
1237 if (pointeeType.getAsOpaquePtr()
1239 return QualType(T, 0);
1240
1241 return Ctx.getObjCObjectPointerType(pointeeType);
1242 }
1243
1244 QualType VisitAtomicType(const AtomicType *T) {
1245 QualType valueType = recurse(T->getValueType());
1246 if (valueType.isNull())
1247 return {};
1248
1249 if (valueType.getAsOpaquePtr()
1250 == T->getValueType().getAsOpaquePtr())
1251 return QualType(T, 0);
1252
1253 return Ctx.getAtomicType(valueType);
1254 }
1255
1256#undef TRIVIAL_TYPE_CLASS
1257#undef SUGARED_TYPE_CLASS
1258};
1259
1260struct SubstObjCTypeArgsVisitor
1261 : public SimpleTransformVisitor<SubstObjCTypeArgsVisitor> {
1262 using BaseType = SimpleTransformVisitor<SubstObjCTypeArgsVisitor>;
1263
1264 ArrayRef<QualType> TypeArgs;
1265 ObjCSubstitutionContext SubstContext;
1266
1267 SubstObjCTypeArgsVisitor(ASTContext &ctx, ArrayRef<QualType> typeArgs,
1269 : BaseType(ctx), TypeArgs(typeArgs), SubstContext(context) {}
1270
1271 QualType VisitObjCTypeParamType(const ObjCTypeParamType *OTPTy) {
1272 // Replace an Objective-C type parameter reference with the corresponding
1273 // type argument.
1274 ObjCTypeParamDecl *typeParam = OTPTy->getDecl();
1275 // If we have type arguments, use them.
1276 if (!TypeArgs.empty()) {
1277 QualType argType = TypeArgs[typeParam->getIndex()];
1278 if (OTPTy->qual_empty())
1279 return argType;
1280
1281 // Apply protocol lists if exists.
1282 bool hasError;
1284 protocolsVec.append(OTPTy->qual_begin(), OTPTy->qual_end());
1285 ArrayRef<ObjCProtocolDecl *> protocolsToApply = protocolsVec;
1286 return Ctx.applyObjCProtocolQualifiers(
1287 argType, protocolsToApply, hasError, true/*allowOnPointerType*/);
1288 }
1289
1290 switch (SubstContext) {
1291 case ObjCSubstitutionContext::Ordinary:
1292 case ObjCSubstitutionContext::Parameter:
1293 case ObjCSubstitutionContext::Superclass:
1294 // Substitute the bound.
1295 return typeParam->getUnderlyingType();
1296
1297 case ObjCSubstitutionContext::Result:
1298 case ObjCSubstitutionContext::Property: {
1299 // Substitute the __kindof form of the underlying type.
1300 const auto *objPtr =
1302
1303 // __kindof types, id, and Class don't need an additional
1304 // __kindof.
1305 if (objPtr->isKindOfType() || objPtr->isObjCIdOrClassType())
1306 return typeParam->getUnderlyingType();
1307
1308 // Add __kindof.
1309 const auto *obj = objPtr->getObjectType();
1310 QualType resultTy = Ctx.getObjCObjectType(
1311 obj->getBaseType(), obj->getTypeArgsAsWritten(), obj->getProtocols(),
1312 /*isKindOf=*/true);
1313
1314 // Rebuild object pointer type.
1315 return Ctx.getObjCObjectPointerType(resultTy);
1316 }
1317 }
1318 llvm_unreachable("Unexpected ObjCSubstitutionContext!");
1319 }
1320
1321 QualType VisitFunctionType(const FunctionType *funcType) {
1322 // If we have a function type, update the substitution context
1323 // appropriately.
1324
1325 //Substitute result type.
1326 QualType returnType = funcType->getReturnType().substObjCTypeArgs(
1327 Ctx, TypeArgs, ObjCSubstitutionContext::Result);
1328 if (returnType.isNull())
1329 return {};
1330
1331 // Handle non-prototyped functions, which only substitute into the result
1332 // type.
1333 if (isa<FunctionNoProtoType>(funcType)) {
1334 // If the return type was unchanged, do nothing.
1335 if (returnType.getAsOpaquePtr() ==
1336 funcType->getReturnType().getAsOpaquePtr())
1337 return BaseType::VisitFunctionType(funcType);
1338
1339 // Otherwise, build a new type.
1340 return Ctx.getFunctionNoProtoType(returnType, funcType->getExtInfo());
1341 }
1342
1343 const auto *funcProtoType = cast<FunctionProtoType>(funcType);
1344
1345 // Transform parameter types.
1346 SmallVector<QualType, 4> paramTypes;
1347 bool paramChanged = false;
1348 for (auto paramType : funcProtoType->getParamTypes()) {
1349 QualType newParamType = paramType.substObjCTypeArgs(
1350 Ctx, TypeArgs, ObjCSubstitutionContext::Parameter);
1351 if (newParamType.isNull())
1352 return {};
1353
1354 if (newParamType.getAsOpaquePtr() != paramType.getAsOpaquePtr())
1355 paramChanged = true;
1356
1357 paramTypes.push_back(newParamType);
1358 }
1359
1360 // Transform extended info.
1361 FunctionProtoType::ExtProtoInfo info = funcProtoType->getExtProtoInfo();
1362 bool exceptionChanged = false;
1363 if (info.ExceptionSpec.Type == EST_Dynamic) {
1364 SmallVector<QualType, 4> exceptionTypes;
1365 for (auto exceptionType : info.ExceptionSpec.Exceptions) {
1366 QualType newExceptionType = exceptionType.substObjCTypeArgs(
1367 Ctx, TypeArgs, ObjCSubstitutionContext::Ordinary);
1368 if (newExceptionType.isNull())
1369 return {};
1370
1371 if (newExceptionType.getAsOpaquePtr() != exceptionType.getAsOpaquePtr())
1372 exceptionChanged = true;
1373
1374 exceptionTypes.push_back(newExceptionType);
1375 }
1376
1377 if (exceptionChanged) {
1379 llvm::ArrayRef(exceptionTypes).copy(Ctx);
1380 }
1381 }
1382
1383 if (returnType.getAsOpaquePtr() ==
1384 funcProtoType->getReturnType().getAsOpaquePtr() &&
1385 !paramChanged && !exceptionChanged)
1386 return BaseType::VisitFunctionType(funcType);
1387
1388 return Ctx.getFunctionType(returnType, paramTypes, info);
1389 }
1390
1391 QualType VisitObjCObjectType(const ObjCObjectType *objcObjectType) {
1392 // Substitute into the type arguments of a specialized Objective-C object
1393 // type.
1394 if (objcObjectType->isSpecializedAsWritten()) {
1395 SmallVector<QualType, 4> newTypeArgs;
1396 bool anyChanged = false;
1397 for (auto typeArg : objcObjectType->getTypeArgsAsWritten()) {
1398 QualType newTypeArg = typeArg.substObjCTypeArgs(
1399 Ctx, TypeArgs, ObjCSubstitutionContext::Ordinary);
1400 if (newTypeArg.isNull())
1401 return {};
1402
1403 if (newTypeArg.getAsOpaquePtr() != typeArg.getAsOpaquePtr()) {
1404 // If we're substituting based on an unspecialized context type,
1405 // produce an unspecialized type.
1407 objcObjectType->qual_begin(), objcObjectType->getNumProtocols());
1408 if (TypeArgs.empty() &&
1409 SubstContext != ObjCSubstitutionContext::Superclass) {
1410 return Ctx.getObjCObjectType(
1411 objcObjectType->getBaseType(), {}, protocols,
1412 objcObjectType->isKindOfTypeAsWritten());
1413 }
1414
1415 anyChanged = true;
1416 }
1417
1418 newTypeArgs.push_back(newTypeArg);
1419 }
1420
1421 if (anyChanged) {
1423 objcObjectType->qual_begin(), objcObjectType->getNumProtocols());
1424 return Ctx.getObjCObjectType(objcObjectType->getBaseType(), newTypeArgs,
1425 protocols,
1426 objcObjectType->isKindOfTypeAsWritten());
1427 }
1428 }
1429
1430 return BaseType::VisitObjCObjectType(objcObjectType);
1431 }
1432
1433 QualType VisitAttributedType(const AttributedType *attrType) {
1434 QualType newType = BaseType::VisitAttributedType(attrType);
1435 if (newType.isNull())
1436 return {};
1437
1438 const auto *newAttrType = dyn_cast<AttributedType>(newType.getTypePtr());
1439 if (!newAttrType || newAttrType->getAttrKind() != attr::ObjCKindOf)
1440 return newType;
1441
1442 // Find out if it's an Objective-C object or object pointer type;
1443 QualType newEquivType = newAttrType->getEquivalentType();
1444 const ObjCObjectPointerType *ptrType =
1445 newEquivType->getAs<ObjCObjectPointerType>();
1446 const ObjCObjectType *objType = ptrType
1447 ? ptrType->getObjectType()
1448 : newEquivType->getAs<ObjCObjectType>();
1449 if (!objType)
1450 return newType;
1451
1452 // Rebuild the "equivalent" type, which pushes __kindof down into
1453 // the object type.
1454 newEquivType = Ctx.getObjCObjectType(
1455 objType->getBaseType(), objType->getTypeArgsAsWritten(),
1456 objType->getProtocols(),
1457 // There is no need to apply kindof on an unqualified id type.
1458 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
1459
1460 // If we started with an object pointer type, rebuild it.
1461 if (ptrType)
1462 newEquivType = Ctx.getObjCObjectPointerType(newEquivType);
1463
1464 // Rebuild the attributed type.
1465 return Ctx.getAttributedType(newAttrType->getAttrKind(),
1466 newAttrType->getModifiedType(), newEquivType);
1467 }
1468};
1469
1470struct StripObjCKindOfTypeVisitor
1471 : public SimpleTransformVisitor<StripObjCKindOfTypeVisitor> {
1472 using BaseType = SimpleTransformVisitor<StripObjCKindOfTypeVisitor>;
1473
1474 explicit StripObjCKindOfTypeVisitor(ASTContext &ctx) : BaseType(ctx) {}
1475
1476 QualType VisitObjCObjectType(const ObjCObjectType *objType) {
1477 if (!objType->isKindOfType())
1478 return BaseType::VisitObjCObjectType(objType);
1479
1480 QualType baseType = objType->getBaseType().stripObjCKindOfType(Ctx);
1481 return Ctx.getObjCObjectType(baseType, objType->getTypeArgsAsWritten(),
1482 objType->getProtocols(),
1483 /*isKindOf=*/false);
1484 }
1485};
1486
1487} // namespace
1488
1490 const BuiltinType *BT = getTypePtr()->getAs<BuiltinType>();
1491 if (!BT) {
1492 const VectorType *VT = getTypePtr()->getAs<VectorType>();
1493 if (VT) {
1494 QualType ElementType = VT->getElementType();
1495 return ElementType.UseExcessPrecision(Ctx);
1496 }
1497 } else {
1498 switch (BT->getKind()) {
1499 case BuiltinType::Kind::Float16: {
1500 const TargetInfo &TI = Ctx.getTargetInfo();
1501 if (TI.hasFloat16Type() && !TI.hasLegalHalfType() &&
1502 Ctx.getLangOpts().getFloat16ExcessPrecision() !=
1503 Ctx.getLangOpts().ExcessPrecisionKind::FPP_None)
1504 return true;
1505 return false;
1506 } break;
1507 case BuiltinType::Kind::BFloat16: {
1508 const TargetInfo &TI = Ctx.getTargetInfo();
1509 if (TI.hasBFloat16Type() && !TI.hasFullBFloat16Type() &&
1510 Ctx.getLangOpts().getBFloat16ExcessPrecision() !=
1511 Ctx.getLangOpts().ExcessPrecisionKind::FPP_None)
1512 return true;
1513 return false;
1514 } break;
1515 default:
1516 return false;
1517 }
1518 }
1519 return false;
1520}
1521
1522/// Substitute the given type arguments for Objective-C type
1523/// parameters within the given type, recursively.
1525 ArrayRef<QualType> typeArgs,
1526 ObjCSubstitutionContext context) const {
1527 SubstObjCTypeArgsVisitor visitor(ctx, typeArgs, context);
1528 return visitor.recurse(*this);
1529}
1530
1532 const DeclContext *dc,
1533 ObjCSubstitutionContext context) const {
1534 if (auto subs = objectType->getObjCSubstitutions(dc))
1535 return substObjCTypeArgs(dc->getParentASTContext(), *subs, context);
1536
1537 return *this;
1538}
1539
1541 // FIXME: Because ASTContext::getAttributedType() is non-const.
1542 auto &ctx = const_cast<ASTContext &>(constCtx);
1543 StripObjCKindOfTypeVisitor visitor(ctx);
1544 return visitor.recurse(*this);
1545}
1546
1548 if (const auto AT = getTypePtr()->getAs<AtomicType>())
1549 return AT->getValueType().getUnqualifiedType();
1550 return getUnqualifiedType();
1551}
1552
1553std::optional<ArrayRef<QualType>>
1555 // Look through method scopes.
1556 if (const auto method = dyn_cast<ObjCMethodDecl>(dc))
1557 dc = method->getDeclContext();
1558
1559 // Find the class or category in which the type we're substituting
1560 // was declared.
1561 const auto *dcClassDecl = dyn_cast<ObjCInterfaceDecl>(dc);
1562 const ObjCCategoryDecl *dcCategoryDecl = nullptr;
1563 ObjCTypeParamList *dcTypeParams = nullptr;
1564 if (dcClassDecl) {
1565 // If the class does not have any type parameters, there's no
1566 // substitution to do.
1567 dcTypeParams = dcClassDecl->getTypeParamList();
1568 if (!dcTypeParams)
1569 return std::nullopt;
1570 } else {
1571 // If we are in neither a class nor a category, there's no
1572 // substitution to perform.
1573 dcCategoryDecl = dyn_cast<ObjCCategoryDecl>(dc);
1574 if (!dcCategoryDecl)
1575 return std::nullopt;
1576
1577 // If the category does not have any type parameters, there's no
1578 // substitution to do.
1579 dcTypeParams = dcCategoryDecl->getTypeParamList();
1580 if (!dcTypeParams)
1581 return std::nullopt;
1582
1583 dcClassDecl = dcCategoryDecl->getClassInterface();
1584 if (!dcClassDecl)
1585 return std::nullopt;
1586 }
1587 assert(dcTypeParams && "No substitutions to perform");
1588 assert(dcClassDecl && "No class context");
1589
1590 // Find the underlying object type.
1591 const ObjCObjectType *objectType;
1592 if (const auto *objectPointerType = getAs<ObjCObjectPointerType>()) {
1593 objectType = objectPointerType->getObjectType();
1594 } else if (getAs<BlockPointerType>()) {
1595 ASTContext &ctx = dc->getParentASTContext();
1596 objectType = ctx.getObjCObjectType(ctx.ObjCBuiltinIdTy, {}, {})
1598 } else {
1599 objectType = getAs<ObjCObjectType>();
1600 }
1601
1602 /// Extract the class from the receiver object type.
1603 ObjCInterfaceDecl *curClassDecl = objectType ? objectType->getInterface()
1604 : nullptr;
1605 if (!curClassDecl) {
1606 // If we don't have a context type (e.g., this is "id" or some
1607 // variant thereof), substitute the bounds.
1608 return llvm::ArrayRef<QualType>();
1609 }
1610
1611 // Follow the superclass chain until we've mapped the receiver type
1612 // to the same class as the context.
1613 while (curClassDecl != dcClassDecl) {
1614 // Map to the superclass type.
1615 QualType superType = objectType->getSuperClassType();
1616 if (superType.isNull()) {
1617 objectType = nullptr;
1618 break;
1619 }
1620
1621 objectType = superType->castAs<ObjCObjectType>();
1622 curClassDecl = objectType->getInterface();
1623 }
1624
1625 // If we don't have a receiver type, or the receiver type does not
1626 // have type arguments, substitute in the defaults.
1627 if (!objectType || objectType->isUnspecialized()) {
1628 return llvm::ArrayRef<QualType>();
1629 }
1630
1631 // The receiver type has the type arguments we want.
1632 return objectType->getTypeArgs();
1633}
1634
1636 if (auto *IfaceT = getAsObjCInterfaceType()) {
1637 if (auto *ID = IfaceT->getInterface()) {
1638 if (ID->getTypeParamList())
1639 return true;
1640 }
1641 }
1642
1643 return false;
1644}
1645
1647 // Retrieve the class declaration for this type. If there isn't one
1648 // (e.g., this is some variant of "id" or "Class"), then there is no
1649 // superclass type.
1650 ObjCInterfaceDecl *classDecl = getInterface();
1651 if (!classDecl) {
1652 CachedSuperClassType.setInt(true);
1653 return;
1654 }
1655
1656 // Extract the superclass type.
1657 const ObjCObjectType *superClassObjTy = classDecl->getSuperClassType();
1658 if (!superClassObjTy) {
1659 CachedSuperClassType.setInt(true);
1660 return;
1661 }
1662
1663 ObjCInterfaceDecl *superClassDecl = superClassObjTy->getInterface();
1664 if (!superClassDecl) {
1665 CachedSuperClassType.setInt(true);
1666 return;
1667 }
1668
1669 // If the superclass doesn't have type parameters, then there is no
1670 // substitution to perform.
1671 QualType superClassType(superClassObjTy, 0);
1672 ObjCTypeParamList *superClassTypeParams = superClassDecl->getTypeParamList();
1673 if (!superClassTypeParams) {
1674 CachedSuperClassType.setPointerAndInt(
1675 superClassType->castAs<ObjCObjectType>(), true);
1676 return;
1677 }
1678
1679 // If the superclass reference is unspecialized, return it.
1680 if (superClassObjTy->isUnspecialized()) {
1681 CachedSuperClassType.setPointerAndInt(superClassObjTy, true);
1682 return;
1683 }
1684
1685 // If the subclass is not parameterized, there aren't any type
1686 // parameters in the superclass reference to substitute.
1687 ObjCTypeParamList *typeParams = classDecl->getTypeParamList();
1688 if (!typeParams) {
1689 CachedSuperClassType.setPointerAndInt(
1690 superClassType->castAs<ObjCObjectType>(), true);
1691 return;
1692 }
1693
1694 // If the subclass type isn't specialized, return the unspecialized
1695 // superclass.
1696 if (isUnspecialized()) {
1697 QualType unspecializedSuper
1698 = classDecl->getASTContext().getObjCInterfaceType(
1699 superClassObjTy->getInterface());
1700 CachedSuperClassType.setPointerAndInt(
1701 unspecializedSuper->castAs<ObjCObjectType>(),
1702 true);
1703 return;
1704 }
1705
1706 // Substitute the provided type arguments into the superclass type.
1707 ArrayRef<QualType> typeArgs = getTypeArgs();
1708 assert(typeArgs.size() == typeParams->size());
1709 CachedSuperClassType.setPointerAndInt(
1710 superClassType.substObjCTypeArgs(classDecl->getASTContext(), typeArgs,
1713 true);
1714}
1715
1717 if (auto interfaceDecl = getObjectType()->getInterface()) {
1718 return interfaceDecl->getASTContext().getObjCInterfaceType(interfaceDecl)
1720 }
1721
1722 return nullptr;
1723}
1724
1726 QualType superObjectType = getObjectType()->getSuperClassType();
1727 if (superObjectType.isNull())
1728 return superObjectType;
1729
1731 return ctx.getObjCObjectPointerType(superObjectType);
1732}
1733
1735 // There is no sugar for ObjCObjectType's, just return the canonical
1736 // type pointer if it is the right class. There is no typedef information to
1737 // return and these cannot be Address-space qualified.
1738 if (const auto *T = getAs<ObjCObjectType>())
1739 if (T->getNumProtocols() && T->getInterface())
1740 return T;
1741 return nullptr;
1742}
1743
1745 return getAsObjCQualifiedInterfaceType() != nullptr;
1746}
1747
1749 // There is no sugar for ObjCQualifiedIdType's, just return the canonical
1750 // type pointer if it is the right class.
1751 if (const auto *OPT = getAs<ObjCObjectPointerType>()) {
1752 if (OPT->isObjCQualifiedIdType())
1753 return OPT;
1754 }
1755 return nullptr;
1756}
1757
1759 // There is no sugar for ObjCQualifiedClassType's, just return the canonical
1760 // type pointer if it is the right class.
1761 if (const auto *OPT = getAs<ObjCObjectPointerType>()) {
1762 if (OPT->isObjCQualifiedClassType())
1763 return OPT;
1764 }
1765 return nullptr;
1766}
1767
1769 if (const auto *OT = getAs<ObjCObjectType>()) {
1770 if (OT->getInterface())
1771 return OT;
1772 }
1773 return nullptr;
1774}
1775
1777 if (const auto *OPT = getAs<ObjCObjectPointerType>()) {
1778 if (OPT->getInterfaceType())
1779 return OPT;
1780 }
1781 return nullptr;
1782}
1783
1785 QualType PointeeType;
1786 if (const auto *PT = getAs<PointerType>())
1787 PointeeType = PT->getPointeeType();
1788 else if (const auto *RT = getAs<ReferenceType>())
1789 PointeeType = RT->getPointeeType();
1790 else
1791 return nullptr;
1792
1793 if (const auto *RT = PointeeType->getAs<RecordType>())
1794 return dyn_cast<CXXRecordDecl>(RT->getDecl());
1795
1796 return nullptr;
1797}
1798
1800 return dyn_cast_or_null<CXXRecordDecl>(getAsTagDecl());
1801}
1802
1804 return dyn_cast_or_null<RecordDecl>(getAsTagDecl());
1805}
1806
1808 if (const auto *TT = getAs<TagType>())
1809 return TT->getDecl();
1810 if (const auto *Injected = getAs<InjectedClassNameType>())
1811 return Injected->getDecl();
1812
1813 return nullptr;
1814}
1815
1817 const Type *Cur = this;
1818 while (const auto *AT = Cur->getAs<AttributedType>()) {
1819 if (AT->getAttrKind() == AK)
1820 return true;
1821 Cur = AT->getEquivalentType().getTypePtr();
1822 }
1823 return false;
1824}
1825
1826namespace {
1827
1828 class GetContainedDeducedTypeVisitor :
1829 public TypeVisitor<GetContainedDeducedTypeVisitor, Type*> {
1830 bool Syntactic;
1831
1832 public:
1833 GetContainedDeducedTypeVisitor(bool Syntactic = false)
1834 : Syntactic(Syntactic) {}
1835
1836 using TypeVisitor<GetContainedDeducedTypeVisitor, Type*>::Visit;
1837
1838 Type *Visit(QualType T) {
1839 if (T.isNull())
1840 return nullptr;
1841 return Visit(T.getTypePtr());
1842 }
1843
1844 // The deduced type itself.
1845 Type *VisitDeducedType(const DeducedType *AT) {
1846 return const_cast<DeducedType*>(AT);
1847 }
1848
1849 // Only these types can contain the desired 'auto' type.
1850 Type *VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1851 return Visit(T->getReplacementType());
1852 }
1853
1854 Type *VisitElaboratedType(const ElaboratedType *T) {
1855 return Visit(T->getNamedType());
1856 }
1857
1858 Type *VisitPointerType(const PointerType *T) {
1859 return Visit(T->getPointeeType());
1860 }
1861
1862 Type *VisitBlockPointerType(const BlockPointerType *T) {
1863 return Visit(T->getPointeeType());
1864 }
1865
1866 Type *VisitReferenceType(const ReferenceType *T) {
1867 return Visit(T->getPointeeTypeAsWritten());
1868 }
1869
1870 Type *VisitMemberPointerType(const MemberPointerType *T) {
1871 return Visit(T->getPointeeType());
1872 }
1873
1874 Type *VisitArrayType(const ArrayType *T) {
1875 return Visit(T->getElementType());
1876 }
1877
1878 Type *VisitDependentSizedExtVectorType(
1879 const DependentSizedExtVectorType *T) {
1880 return Visit(T->getElementType());
1881 }
1882
1883 Type *VisitVectorType(const VectorType *T) {
1884 return Visit(T->getElementType());
1885 }
1886
1887 Type *VisitDependentSizedMatrixType(const DependentSizedMatrixType *T) {
1888 return Visit(T->getElementType());
1889 }
1890
1891 Type *VisitConstantMatrixType(const ConstantMatrixType *T) {
1892 return Visit(T->getElementType());
1893 }
1894
1895 Type *VisitFunctionProtoType(const FunctionProtoType *T) {
1896 if (Syntactic && T->hasTrailingReturn())
1897 return const_cast<FunctionProtoType*>(T);
1898 return VisitFunctionType(T);
1899 }
1900
1901 Type *VisitFunctionType(const FunctionType *T) {
1902 return Visit(T->getReturnType());
1903 }
1904
1905 Type *VisitParenType(const ParenType *T) {
1906 return Visit(T->getInnerType());
1907 }
1908
1909 Type *VisitAttributedType(const AttributedType *T) {
1910 return Visit(T->getModifiedType());
1911 }
1912
1913 Type *VisitMacroQualifiedType(const MacroQualifiedType *T) {
1914 return Visit(T->getUnderlyingType());
1915 }
1916
1917 Type *VisitAdjustedType(const AdjustedType *T) {
1918 return Visit(T->getOriginalType());
1919 }
1920
1921 Type *VisitPackExpansionType(const PackExpansionType *T) {
1922 return Visit(T->getPattern());
1923 }
1924 };
1925
1926} // namespace
1927
1929 return cast_or_null<DeducedType>(
1930 GetContainedDeducedTypeVisitor().Visit(this));
1931}
1932
1934 return isa_and_nonnull<FunctionType>(
1935 GetContainedDeducedTypeVisitor(true).Visit(this));
1936}
1937
1939 if (const auto *VT = dyn_cast<VectorType>(CanonicalType))
1940 return VT->getElementType()->isIntegerType();
1941 if (CanonicalType->isVLSTBuiltinType()) {
1942 const auto *VT = cast<BuiltinType>(CanonicalType);
1943 return VT->getKind() == BuiltinType::SveBool ||
1944 (VT->getKind() >= BuiltinType::SveInt8 &&
1945 VT->getKind() <= BuiltinType::SveUint64);
1946 }
1947 if (CanonicalType->isRVVVLSBuiltinType()) {
1948 const auto *VT = cast<BuiltinType>(CanonicalType);
1949 return (VT->getKind() >= BuiltinType::RvvInt8mf8 &&
1950 VT->getKind() <= BuiltinType::RvvUint64m8);
1951 }
1952
1953 return isIntegerType();
1954}
1955
1956/// Determine whether this type is an integral type.
1957///
1958/// This routine determines whether the given type is an integral type per
1959/// C++ [basic.fundamental]p7. Although the C standard does not define the
1960/// term "integral type", it has a similar term "integer type", and in C++
1961/// the two terms are equivalent. However, C's "integer type" includes
1962/// enumeration types, while C++'s "integer type" does not. The \c ASTContext
1963/// parameter is used to determine whether we should be following the C or
1964/// C++ rules when determining whether this type is an integral/integer type.
1965///
1966/// For cases where C permits "an integer type" and C++ permits "an integral
1967/// type", use this routine.
1968///
1969/// For cases where C permits "an integer type" and C++ permits "an integral
1970/// or enumeration type", use \c isIntegralOrEnumerationType() instead.
1971///
1972/// \param Ctx The context in which this type occurs.
1973///
1974/// \returns true if the type is considered an integral type, false otherwise.
1975bool Type::isIntegralType(const ASTContext &Ctx) const {
1976 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
1977 return BT->getKind() >= BuiltinType::Bool &&
1978 BT->getKind() <= BuiltinType::Int128;
1979
1980 // Complete enum types are integral in C.
1981 if (!Ctx.getLangOpts().CPlusPlus)
1982 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
1983 return ET->getDecl()->isComplete();
1984
1985 return isBitIntType();
1986}
1987
1989 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
1990 return BT->getKind() >= BuiltinType::Bool &&
1991 BT->getKind() <= BuiltinType::Int128;
1992
1993 if (isBitIntType())
1994 return true;
1995
1997}
1998
2000 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
2001 return !ET->getDecl()->isScoped();
2002
2003 return false;
2004}
2005
2006bool Type::isCharType() const {
2007 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2008 return BT->getKind() == BuiltinType::Char_U ||
2009 BT->getKind() == BuiltinType::UChar ||
2010 BT->getKind() == BuiltinType::Char_S ||
2011 BT->getKind() == BuiltinType::SChar;
2012 return false;
2013}
2014
2016 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2017 return BT->getKind() == BuiltinType::WChar_S ||
2018 BT->getKind() == BuiltinType::WChar_U;
2019 return false;
2020}
2021
2022bool Type::isChar8Type() const {
2023 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
2024 return BT->getKind() == BuiltinType::Char8;
2025 return false;
2026}
2027
2029 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2030 return BT->getKind() == BuiltinType::Char16;
2031 return false;
2032}
2033
2035 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2036 return BT->getKind() == BuiltinType::Char32;
2037 return false;
2038}
2039
2040/// Determine whether this type is any of the built-in character
2041/// types.
2043 const auto *BT = dyn_cast<BuiltinType>(CanonicalType);
2044 if (!BT) return false;
2045 switch (BT->getKind()) {
2046 default: return false;
2047 case BuiltinType::Char_U:
2048 case BuiltinType::UChar:
2049 case BuiltinType::WChar_U:
2050 case BuiltinType::Char8:
2051 case BuiltinType::Char16:
2052 case BuiltinType::Char32:
2053 case BuiltinType::Char_S:
2054 case BuiltinType::SChar:
2055 case BuiltinType::WChar_S:
2056 return true;
2057 }
2058}
2059
2060/// isSignedIntegerType - Return true if this is an integer type that is
2061/// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2062/// an enum decl which has a signed representation
2064 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
2065 return BT->getKind() >= BuiltinType::Char_S &&
2066 BT->getKind() <= BuiltinType::Int128;
2067 }
2068
2069 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
2070 // Incomplete enum types are not treated as integer types.
2071 // FIXME: In C++, enum types are never integer types.
2072 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
2073 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
2074 }
2075
2076 if (const auto *IT = dyn_cast<BitIntType>(CanonicalType))
2077 return IT->isSigned();
2078 if (const auto *IT = dyn_cast<DependentBitIntType>(CanonicalType))
2079 return IT->isSigned();
2080
2081 return false;
2082}
2083
2085 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
2086 return BT->getKind() >= BuiltinType::Char_S &&
2087 BT->getKind() <= BuiltinType::Int128;
2088 }
2089
2090 if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) {
2091 if (ET->getDecl()->isComplete())
2092 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
2093 }
2094
2095 if (const auto *IT = dyn_cast<BitIntType>(CanonicalType))
2096 return IT->isSigned();
2097 if (const auto *IT = dyn_cast<DependentBitIntType>(CanonicalType))
2098 return IT->isSigned();
2099
2100 return false;
2101}
2102
2104 if (const auto *VT = dyn_cast<VectorType>(CanonicalType))
2105 return VT->getElementType()->isSignedIntegerOrEnumerationType();
2106 else
2108}
2109
2110/// isUnsignedIntegerType - Return true if this is an integer type that is
2111/// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
2112/// decl which has an unsigned representation
2114 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
2115 return BT->getKind() >= BuiltinType::Bool &&
2116 BT->getKind() <= BuiltinType::UInt128;
2117 }
2118
2119 if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) {
2120 // Incomplete enum types are not treated as integer types.
2121 // FIXME: In C++, enum types are never integer types.
2122 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
2123 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
2124 }
2125
2126 if (const auto *IT = dyn_cast<BitIntType>(CanonicalType))
2127 return IT->isUnsigned();
2128 if (const auto *IT = dyn_cast<DependentBitIntType>(CanonicalType))
2129 return IT->isUnsigned();
2130
2131 return false;
2132}
2133
2135 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
2136 return BT->getKind() >= BuiltinType::Bool &&
2137 BT->getKind() <= BuiltinType::UInt128;
2138 }
2139
2140 if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) {
2141 if (ET->getDecl()->isComplete())
2142 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
2143 }
2144
2145 if (const auto *IT = dyn_cast<BitIntType>(CanonicalType))
2146 return IT->isUnsigned();
2147 if (const auto *IT = dyn_cast<DependentBitIntType>(CanonicalType))
2148 return IT->isUnsigned();
2149
2150 return false;
2151}
2152
2154 if (const auto *VT = dyn_cast<VectorType>(CanonicalType))
2155 return VT->getElementType()->isUnsignedIntegerOrEnumerationType();
2156 if (const auto *VT = dyn_cast<MatrixType>(CanonicalType))
2157 return VT->getElementType()->isUnsignedIntegerOrEnumerationType();
2158 if (CanonicalType->isVLSTBuiltinType()) {
2159 const auto *VT = cast<BuiltinType>(CanonicalType);
2160 return VT->getKind() >= BuiltinType::SveUint8 &&
2161 VT->getKind() <= BuiltinType::SveUint64;
2162 }
2164}
2165
2167 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2168 return BT->getKind() >= BuiltinType::Half &&
2169 BT->getKind() <= BuiltinType::Ibm128;
2170 if (const auto *CT = dyn_cast<ComplexType>(CanonicalType))
2171 return CT->getElementType()->isFloatingType();
2172 return false;
2173}
2174
2176 if (const auto *VT = dyn_cast<VectorType>(CanonicalType))
2177 return VT->getElementType()->isFloatingType();
2178 if (const auto *MT = dyn_cast<MatrixType>(CanonicalType))
2179 return MT->getElementType()->isFloatingType();
2180 return isFloatingType();
2181}
2182
2184 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2185 return BT->isFloatingPoint();
2186 return false;
2187}
2188
2189bool Type::isRealType() const {
2190 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2191 return BT->getKind() >= BuiltinType::Bool &&
2192 BT->getKind() <= BuiltinType::Ibm128;
2193 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
2194 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
2195 return isBitIntType();
2196}
2197
2199 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2200 return BT->getKind() >= BuiltinType::Bool &&
2201 BT->getKind() <= BuiltinType::Ibm128;
2202 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
2203 // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
2204 // If a body isn't seen by the time we get here, return false.
2205 //
2206 // C++0x: Enumerations are not arithmetic types. For now, just return
2207 // false for scoped enumerations since that will disable any
2208 // unwanted implicit conversions.
2209 return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete();
2210 return isa<ComplexType>(CanonicalType) || isBitIntType();
2211}
2212
2214 assert(isScalarType());
2215
2216 const Type *T = CanonicalType.getTypePtr();
2217 if (const auto *BT = dyn_cast<BuiltinType>(T)) {
2218 if (BT->getKind() == BuiltinType::Bool) return STK_Bool;
2219 if (BT->getKind() == BuiltinType::NullPtr) return STK_CPointer;
2220 if (BT->isInteger()) return STK_Integral;
2221 if (BT->isFloatingPoint()) return STK_Floating;
2222 if (BT->isFixedPointType()) return STK_FixedPoint;
2223 llvm_unreachable("unknown scalar builtin type");
2224 } else if (isa<PointerType>(T)) {
2225 return STK_CPointer;
2226 } else if (isa<BlockPointerType>(T)) {
2227 return STK_BlockPointer;
2228 } else if (isa<ObjCObjectPointerType>(T)) {
2229 return STK_ObjCObjectPointer;
2230 } else if (isa<MemberPointerType>(T)) {
2231 return STK_MemberPointer;
2232 } else if (isa<EnumType>(T)) {
2233 assert(cast<EnumType>(T)->getDecl()->isComplete());
2234 return STK_Integral;
2235 } else if (const auto *CT = dyn_cast<ComplexType>(T)) {
2236 if (CT->getElementType()->isRealFloatingType())
2237 return STK_FloatingComplex;
2238 return STK_IntegralComplex;
2239 } else if (isBitIntType()) {
2240 return STK_Integral;
2241 }
2242
2243 llvm_unreachable("unknown scalar type");
2244}
2245
2246/// Determines whether the type is a C++ aggregate type or C
2247/// aggregate or union type.
2248///
2249/// An aggregate type is an array or a class type (struct, union, or
2250/// class) that has no user-declared constructors, no private or
2251/// protected non-static data members, no base classes, and no virtual
2252/// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
2253/// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
2254/// includes union types.
2256 if (const auto *Record = dyn_cast<RecordType>(CanonicalType)) {
2257 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
2258 return ClassDecl->isAggregate();
2259
2260 return true;
2261 }
2262
2263 return isa<ArrayType>(CanonicalType);
2264}
2265
2266/// isConstantSizeType - Return true if this is not a variable sized type,
2267/// according to the rules of C99 6.7.5p3. It is not legal to call this on
2268/// incomplete types or dependent types.
2270 assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
2271 assert(!isDependentType() && "This doesn't make sense for dependent types");
2272 // The VAT must have a size, as it is known to be complete.
2273 return !isa<VariableArrayType>(CanonicalType);
2274}
2275
2276/// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
2277/// - a type that can describe objects, but which lacks information needed to
2278/// determine its size.
2280 if (Def)
2281 *Def = nullptr;
2282
2283 switch (CanonicalType->getTypeClass()) {
2284 default: return false;
2285 case Builtin:
2286 // Void is the only incomplete builtin type. Per C99 6.2.5p19, it can never
2287 // be completed.
2288 return isVoidType();
2289 case Enum: {
2290 EnumDecl *EnumD = cast<EnumType>(CanonicalType)->getDecl();
2291 if (Def)
2292 *Def = EnumD;
2293 return !EnumD->isComplete();
2294 }
2295 case Record: {
2296 // A tagged type (struct/union/enum/class) is incomplete if the decl is a
2297 // forward declaration, but not a full definition (C99 6.2.5p22).
2298 RecordDecl *Rec = cast<RecordType>(CanonicalType)->getDecl();
2299 if (Def)
2300 *Def = Rec;
2301 return !Rec->isCompleteDefinition();
2302 }
2303 case ConstantArray:
2304 case VariableArray:
2305 // An array is incomplete if its element type is incomplete
2306 // (C++ [dcl.array]p1).
2307 // We don't handle dependent-sized arrays (dependent types are never treated
2308 // as incomplete).
2309 return cast<ArrayType>(CanonicalType)->getElementType()
2310 ->isIncompleteType(Def);
2311 case IncompleteArray:
2312 // An array of unknown size is an incomplete type (C99 6.2.5p22).
2313 return true;
2314 case MemberPointer: {
2315 // Member pointers in the MS ABI have special behavior in
2316 // RequireCompleteType: they attach a MSInheritanceAttr to the CXXRecordDecl
2317 // to indicate which inheritance model to use.
2318 auto *MPTy = cast<MemberPointerType>(CanonicalType);
2319 const Type *ClassTy = MPTy->getClass();
2320 // Member pointers with dependent class types don't get special treatment.
2321 if (ClassTy->isDependentType())
2322 return false;
2323 const CXXRecordDecl *RD = ClassTy->getAsCXXRecordDecl();
2324 ASTContext &Context = RD->getASTContext();
2325 // Member pointers not in the MS ABI don't get special treatment.
2326 if (!Context.getTargetInfo().getCXXABI().isMicrosoft())
2327 return false;
2328 // The inheritance attribute might only be present on the most recent
2329 // CXXRecordDecl, use that one.
2331 // Nothing interesting to do if the inheritance attribute is already set.
2332 if (RD->hasAttr<MSInheritanceAttr>())
2333 return false;
2334 return true;
2335 }
2336 case ObjCObject:
2337 return cast<ObjCObjectType>(CanonicalType)->getBaseType()
2338 ->isIncompleteType(Def);
2339 case ObjCInterface: {
2340 // ObjC interfaces are incomplete if they are @class, not @interface.
2341 ObjCInterfaceDecl *Interface
2342 = cast<ObjCInterfaceType>(CanonicalType)->getDecl();
2343 if (Def)
2344 *Def = Interface;
2345 return !Interface->hasDefinition();
2346 }
2347 }
2348}
2349
2351 if (const BuiltinType *BT = getAs<BuiltinType>()) {
2352 switch (BT->getKind()) {
2353 // SVE Types
2354#define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2355#include "clang/Basic/AArch64SVEACLETypes.def"
2356#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2357#include "clang/Basic/RISCVVTypes.def"
2358 return true;
2359 // WebAssembly reference types
2360#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2361#include "clang/Basic/WebAssemblyReferenceTypes.def"
2362 return true;
2363 default:
2364 return false;
2365 }
2366 }
2367 return false;
2368}
2369
2372}
2373
2375 if (const auto *BT = getAs<BuiltinType>())
2376 return BT->getKind() == BuiltinType::WasmExternRef;
2377 return false;
2378}
2379
2381
2383 if (const BuiltinType *BT = getAs<BuiltinType>()) {
2384 switch (BT->getKind()) {
2385 // SVE Types
2386#define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2387#include "clang/Basic/AArch64SVEACLETypes.def"
2388 return true;
2389 default:
2390 return false;
2391 }
2392 }
2393 return false;
2394}
2395
2397 if (const BuiltinType *BT = getAs<BuiltinType>()) {
2398 switch (BT->getKind()) {
2399#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2400#include "clang/Basic/RISCVVTypes.def"
2401 return true;
2402 default:
2403 return false;
2404 }
2405 }
2406 return false;
2407}
2408
2410 if (const BuiltinType *BT = getAs<BuiltinType>()) {
2411 switch (BT->getKind()) {
2412 case BuiltinType::SveInt8:
2413 case BuiltinType::SveInt16:
2414 case BuiltinType::SveInt32:
2415 case BuiltinType::SveInt64:
2416 case BuiltinType::SveUint8:
2417 case BuiltinType::SveUint16:
2418 case BuiltinType::SveUint32:
2419 case BuiltinType::SveUint64:
2420 case BuiltinType::SveFloat16:
2421 case BuiltinType::SveFloat32:
2422 case BuiltinType::SveFloat64:
2423 case BuiltinType::SveBFloat16:
2424 case BuiltinType::SveBool:
2425 case BuiltinType::SveBoolx2:
2426 case BuiltinType::SveBoolx4:
2427 return true;
2428 default:
2429 return false;
2430 }
2431 }
2432 return false;
2433}
2434
2436 assert(isVLSTBuiltinType() && "unsupported type!");
2437
2438 const BuiltinType *BTy = castAs<BuiltinType>();
2439 if (BTy->getKind() == BuiltinType::SveBool)
2440 // Represent predicates as i8 rather than i1 to avoid any layout issues.
2441 // The type is bitcasted to a scalable predicate type when casting between
2442 // scalable and fixed-length vectors.
2443 return Ctx.UnsignedCharTy;
2444 else
2445 return Ctx.getBuiltinVectorTypeInfo(BTy).ElementType;
2446}
2447
2449 if (const BuiltinType *BT = getAs<BuiltinType>()) {
2450 switch (BT->getKind()) {
2451 // FIXME: Support more than LMUL 1.
2452#define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, IsFP) \
2453 case BuiltinType::Id: \
2454 return NF == 1 && (NumEls * ElBits) == llvm::RISCV::RVVBitsPerBlock;
2455#include "clang/Basic/RISCVVTypes.def"
2456 default:
2457 return false;
2458 }
2459 }
2460 return false;
2461}
2462
2464 assert(isRVVVLSBuiltinType() && "unsupported type!");
2465
2466 const BuiltinType *BTy = castAs<BuiltinType>();
2467 return Ctx.getBuiltinVectorTypeInfo(BTy).ElementType;
2468}
2469
2470bool QualType::isPODType(const ASTContext &Context) const {
2471 // C++11 has a more relaxed definition of POD.
2472 if (Context.getLangOpts().CPlusPlus11)
2473 return isCXX11PODType(Context);
2474
2475 return isCXX98PODType(Context);
2476}
2477
2478bool QualType::isCXX98PODType(const ASTContext &Context) const {
2479 // The compiler shouldn't query this for incomplete types, but the user might.
2480 // We return false for that case. Except for incomplete arrays of PODs, which
2481 // are PODs according to the standard.
2482 if (isNull())
2483 return false;
2484
2485 if ((*this)->isIncompleteArrayType())
2486 return Context.getBaseElementType(*this).isCXX98PODType(Context);
2487
2488 if ((*this)->isIncompleteType())
2489 return false;
2490
2492 return false;
2493
2494 QualType CanonicalType = getTypePtr()->CanonicalType;
2495 switch (CanonicalType->getTypeClass()) {
2496 // Everything not explicitly mentioned is not POD.
2497 default: return false;
2498 case Type::VariableArray:
2499 case Type::ConstantArray:
2500 // IncompleteArray is handled above.
2501 return Context.getBaseElementType(*this).isCXX98PODType(Context);
2502
2503 case Type::ObjCObjectPointer:
2504 case Type::BlockPointer:
2505 case Type::Builtin:
2506 case Type::Complex:
2507 case Type::Pointer:
2508 case Type::MemberPointer:
2509 case Type::Vector:
2510 case Type::ExtVector:
2511 case Type::BitInt:
2512 return true;
2513
2514 case Type::Enum:
2515 return true;
2516
2517 case Type::Record:
2518 if (const auto *ClassDecl =
2519 dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
2520 return ClassDecl->isPOD();
2521
2522 // C struct/union is POD.
2523 return true;
2524 }
2525}
2526
2527bool QualType::isTrivialType(const ASTContext &Context) const {
2528 // The compiler shouldn't query this for incomplete types, but the user might.
2529 // We return false for that case. Except for incomplete arrays of PODs, which
2530 // are PODs according to the standard.
2531 if (isNull())
2532 return false;
2533
2534 if ((*this)->isArrayType())
2535 return Context.getBaseElementType(*this).isTrivialType(Context);
2536
2537 if ((*this)->isSizelessBuiltinType())
2538 return true;
2539
2540 // Return false for incomplete types after skipping any incomplete array
2541 // types which are expressly allowed by the standard and thus our API.
2542 if ((*this)->isIncompleteType())
2543 return false;
2544
2546 return false;
2547
2548 QualType CanonicalType = getTypePtr()->CanonicalType;
2549 if (CanonicalType->isDependentType())
2550 return false;
2551
2552 // C++0x [basic.types]p9:
2553 // Scalar types, trivial class types, arrays of such types, and
2554 // cv-qualified versions of these types are collectively called trivial
2555 // types.
2556
2557 // As an extension, Clang treats vector types as Scalar types.
2558 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
2559 return true;
2560 if (const auto *RT = CanonicalType->getAs<RecordType>()) {
2561 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2562 // C++20 [class]p6:
2563 // A trivial class is a class that is trivially copyable, and
2564 // has one or more eligible default constructors such that each is
2565 // trivial.
2566 // FIXME: We should merge this definition of triviality into
2567 // CXXRecordDecl::isTrivial. Currently it computes the wrong thing.
2568 return ClassDecl->hasTrivialDefaultConstructor() &&
2569 !ClassDecl->hasNonTrivialDefaultConstructor() &&
2570 ClassDecl->isTriviallyCopyable();
2571 }
2572
2573 return true;
2574 }
2575
2576 // No other types can match.
2577 return false;
2578}
2579
2581 if ((*this)->isArrayType())
2582 return Context.getBaseElementType(*this).isTriviallyCopyableType(Context);
2583
2585 return false;
2586
2587 // C++11 [basic.types]p9 - See Core 2094
2588 // Scalar types, trivially copyable class types, arrays of such types, and
2589 // cv-qualified versions of these types are collectively
2590 // called trivially copyable types.
2591
2592 QualType CanonicalType = getCanonicalType();
2593 if (CanonicalType->isDependentType())
2594 return false;
2595
2596 if (CanonicalType->isSizelessBuiltinType())
2597 return true;
2598
2599 // Return false for incomplete types after skipping any incomplete array types
2600 // which are expressly allowed by the standard and thus our API.
2601 if (CanonicalType->isIncompleteType())
2602 return false;
2603
2604 // As an extension, Clang treats vector types as Scalar types.
2605 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
2606 return true;
2607
2608 if (const auto *RT = CanonicalType->getAs<RecordType>()) {
2609 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2610 if (!ClassDecl->isTriviallyCopyable()) return false;
2611 }
2612
2613 return true;
2614 }
2615
2616 // No other types can match.
2617 return false;
2618}
2619
2621 QualType BaseElementType = Context.getBaseElementType(*this);
2622
2623 if (BaseElementType->isIncompleteType()) {
2624 return false;
2625 } else if (const auto *RD = BaseElementType->getAsRecordDecl()) {
2626 return RD->canPassInRegisters();
2627 } else {
2629 case PCK_Trivial:
2630 return !isDestructedType();
2631 case PCK_ARCStrong:
2632 return true;
2633 default:
2634 return false;
2635 }
2636 }
2637}
2638
2639static bool
2641 if (Decl->isUnion())
2642 return false;
2643
2644 auto IsDefaultedOperatorEqualEqual = [&](const FunctionDecl *Function) {
2645 return Function->getOverloadedOperator() ==
2646 OverloadedOperatorKind::OO_EqualEqual &&
2647 Function->isDefaulted() && Function->getNumParams() > 0 &&
2648 (Function->getParamDecl(0)->getType()->isReferenceType() ||
2649 Decl->isTriviallyCopyable());
2650 };
2651
2652 if (llvm::none_of(Decl->methods(), IsDefaultedOperatorEqualEqual) &&
2653 llvm::none_of(Decl->friends(), [&](const FriendDecl *Friend) {
2654 if (NamedDecl *ND = Friend->getFriendDecl()) {
2655 return ND->isFunctionOrFunctionTemplate() &&
2656 IsDefaultedOperatorEqualEqual(ND->getAsFunction());
2657 }
2658 return false;
2659 }))
2660 return false;
2661
2662 return llvm::all_of(Decl->bases(),
2663 [](const CXXBaseSpecifier &BS) {
2664 if (const auto *RD = BS.getType()->getAsCXXRecordDecl())
2665 HasNonDeletedDefaultedEqualityComparison(RD);
2666 return true;
2667 }) &&
2668 llvm::all_of(Decl->fields(), [](const FieldDecl *FD) {
2669 auto Type = FD->getType();
2670 if (Type->isReferenceType() || Type->isEnumeralType())
2671 return false;
2672 if (const auto *RD = Type->getAsCXXRecordDecl())
2673 return HasNonDeletedDefaultedEqualityComparison(RD);
2674 return true;
2675 });
2676}
2677
2679 const ASTContext &Context) const {
2680 QualType CanonicalType = getCanonicalType();
2681 if (CanonicalType->isIncompleteType() || CanonicalType->isDependentType() ||
2682 CanonicalType->isEnumeralType())
2683 return false;
2684
2685 if (const auto *RD = CanonicalType->getAsCXXRecordDecl()) {
2687 return false;
2688 }
2689
2690 return Context.hasUniqueObjectRepresentations(
2691 CanonicalType, /*CheckIfTriviallyCopyable=*/false);
2692}
2693
2695 return !Context.getLangOpts().ObjCAutoRefCount &&
2696 Context.getLangOpts().ObjCWeak &&
2698}
2699
2702}
2703
2706}
2707
2710}
2711
2714 if (const auto *RT =
2715 getTypePtr()->getBaseElementTypeUnsafe()->getAs<RecordType>())
2716 if (RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize())
2717 return PDIK_Struct;
2718
2719 switch (getQualifiers().getObjCLifetime()) {
2721 return PDIK_ARCStrong;
2723 return PDIK_ARCWeak;
2724 default:
2725 return PDIK_Trivial;
2726 }
2727}
2728
2730 if (const auto *RT =
2731 getTypePtr()->getBaseElementTypeUnsafe()->getAs<RecordType>())
2732 if (RT->getDecl()->isNonTrivialToPrimitiveCopy())
2733 return PCK_Struct;
2734
2736 switch (Qs.getObjCLifetime()) {
2738 return PCK_ARCStrong;
2740 return PCK_ARCWeak;
2741 default:
2743 }
2744}
2745
2749}
2750
2751bool Type::isLiteralType(const ASTContext &Ctx) const {
2752 if (isDependentType())
2753 return false;
2754
2755 // C++1y [basic.types]p10:
2756 // A type is a literal type if it is:
2757 // -- cv void; or
2758 if (Ctx.getLangOpts().CPlusPlus14 && isVoidType())
2759 return true;
2760
2761 // C++11 [basic.types]p10:
2762 // A type is a literal type if it is:
2763 // [...]
2764 // -- an array of literal type other than an array of runtime bound; or
2765 if (isVariableArrayType())
2766 return false;
2767 const Type *BaseTy = getBaseElementTypeUnsafe();
2768 assert(BaseTy && "NULL element type");
2769
2770 // Return false for incomplete types after skipping any incomplete array
2771 // types; those are expressly allowed by the standard and thus our API.
2772 if (BaseTy->isIncompleteType())
2773 return false;
2774
2775 // C++11 [basic.types]p10:
2776 // A type is a literal type if it is:
2777 // -- a scalar type; or
2778 // As an extension, Clang treats vector types and complex types as
2779 // literal types.
2780 if (BaseTy->isScalarType() || BaseTy->isVectorType() ||
2781 BaseTy->isAnyComplexType())
2782 return true;
2783 // -- a reference type; or
2784 if (BaseTy->isReferenceType())
2785 return true;
2786 // -- a class type that has all of the following properties:
2787 if (const auto *RT = BaseTy->getAs<RecordType>()) {
2788 // -- a trivial destructor,
2789 // -- every constructor call and full-expression in the
2790 // brace-or-equal-initializers for non-static data members (if any)
2791 // is a constant expression,
2792 // -- it is an aggregate type or has at least one constexpr
2793 // constructor or constructor template that is not a copy or move
2794 // constructor, and
2795 // -- all non-static data members and base classes of literal types
2796 //
2797 // We resolve DR1361 by ignoring the second bullet.
2798 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2799 return ClassDecl->isLiteral();
2800
2801 return true;
2802 }
2803
2804 // We treat _Atomic T as a literal type if T is a literal type.
2805 if (const auto *AT = BaseTy->getAs<AtomicType>())
2806 return AT->getValueType()->isLiteralType(Ctx);
2807
2808 // If this type hasn't been deduced yet, then conservatively assume that
2809 // it'll work out to be a literal type.
2810 if (isa<AutoType>(BaseTy->getCanonicalTypeInternal()))
2811 return true;
2812
2813 return false;
2814}
2815
2817 // C++20 [temp.param]p6:
2818 // A structural type is one of the following:
2819 // -- a scalar type; or
2820 // -- a vector type [Clang extension]; or
2821 if (isScalarType() || isVectorType())
2822 return true;
2823 // -- an lvalue reference type; or
2825 return true;
2826 // -- a literal class type [...under some conditions]
2827 if (const CXXRecordDecl *RD = getAsCXXRecordDecl())
2828 return RD->isStructural();
2829 return false;
2830}
2831
2833 if (isDependentType())
2834 return false;
2835
2836 // C++0x [basic.types]p9:
2837 // Scalar types, standard-layout class types, arrays of such types, and
2838 // cv-qualified versions of these types are collectively called
2839 // standard-layout types.
2840 const Type *BaseTy = getBaseElementTypeUnsafe();
2841 assert(BaseTy && "NULL element type");
2842
2843 // Return false for incomplete types after skipping any incomplete array
2844 // types which are expressly allowed by the standard and thus our API.
2845 if (BaseTy->isIncompleteType())
2846 return false;
2847
2848 // As an extension, Clang treats vector types as Scalar types.
2849 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
2850 if (const auto *RT = BaseTy->getAs<RecordType>()) {
2851 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2852 if (!ClassDecl->isStandardLayout())
2853 return false;
2854
2855 // Default to 'true' for non-C++ class types.
2856 // FIXME: This is a bit dubious, but plain C structs should trivially meet
2857 // all the requirements of standard layout classes.
2858 return true;
2859 }
2860
2861 // No other types can match.
2862 return false;
2863}
2864
2865// This is effectively the intersection of isTrivialType and
2866// isStandardLayoutType. We implement it directly to avoid redundant
2867// conversions from a type to a CXXRecordDecl.
2868bool QualType::isCXX11PODType(const ASTContext &Context) const {
2869 const Type *ty = getTypePtr();
2870 if (ty->isDependentType())
2871 return false;
2872
2874 return false;
2875
2876 // C++11 [basic.types]p9:
2877 // Scalar types, POD classes, arrays of such types, and cv-qualified
2878 // versions of these types are collectively called trivial types.
2879 const Type *BaseTy = ty->getBaseElementTypeUnsafe();
2880 assert(BaseTy && "NULL element type");
2881
2882 if (BaseTy->isSizelessBuiltinType())
2883 return true;
2884
2885 // Return false for incomplete types after skipping any incomplete array
2886 // types which are expressly allowed by the standard and thus our API.
2887 if (BaseTy->isIncompleteType())
2888 return false;
2889
2890 // As an extension, Clang treats vector types as Scalar types.
2891 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
2892 if (const auto *RT = BaseTy->getAs<RecordType>()) {
2893 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2894 // C++11 [class]p10:
2895 // A POD struct is a non-union class that is both a trivial class [...]
2896 if (!ClassDecl->isTrivial()) return false;
2897
2898 // C++11 [class]p10:
2899 // A POD struct is a non-union class that is both a trivial class and
2900 // a standard-layout class [...]
2901 if (!ClassDecl->isStandardLayout()) return false;
2902
2903 // C++11 [class]p10:
2904 // A POD struct is a non-union class that is both a trivial class and
2905 // a standard-layout class, and has no non-static data members of type
2906 // non-POD struct, non-POD union (or array of such types). [...]
2907 //
2908 // We don't directly query the recursive aspect as the requirements for
2909 // both standard-layout classes and trivial classes apply recursively
2910 // already.
2911 }
2912
2913 return true;
2914 }
2915
2916 // No other types can match.
2917 return false;
2918}
2919
2920bool Type::isNothrowT() const {
2921 if (const auto *RD = getAsCXXRecordDecl()) {
2922 IdentifierInfo *II = RD->getIdentifier();
2923 if (II && II->isStr("nothrow_t") && RD->isInStdNamespace())
2924 return true;
2925 }
2926 return false;
2927}
2928
2929bool Type::isAlignValT() const {
2930 if (const auto *ET = getAs<EnumType>()) {
2931 IdentifierInfo *II = ET->getDecl()->getIdentifier();
2932 if (II && II->isStr("align_val_t") && ET->getDecl()->isInStdNamespace())
2933 return true;
2934 }
2935 return false;
2936}
2937
2939 if (const auto *ET = getAs<EnumType>()) {
2940 IdentifierInfo *II = ET->getDecl()->getIdentifier();
2941 if (II && II->isStr("byte") && ET->getDecl()->isInStdNamespace())
2942 return true;
2943 }
2944 return false;
2945}
2946
2948 // Note that this intentionally does not use the canonical type.
2949 switch (getTypeClass()) {
2950 case Builtin:
2951 case Record:
2952 case Enum:
2953 case Typedef:
2954 case Complex:
2955 case TypeOfExpr:
2956 case TypeOf:
2957 case TemplateTypeParm:
2958 case SubstTemplateTypeParm:
2959 case TemplateSpecialization:
2960 case Elaborated:
2961 case DependentName:
2962 case DependentTemplateSpecialization:
2963 case ObjCInterface:
2964 case ObjCObject:
2965 return true;
2966 default:
2967 return false;
2968 }
2969}
2970
2973 switch (TypeSpec) {
2974 default: return ETK_None;
2975 case TST_typename: return ETK_Typename;
2976 case TST_class: return ETK_Class;
2977 case TST_struct: return ETK_Struct;
2978 case TST_interface: return ETK_Interface;
2979 case TST_union: return ETK_Union;
2980 case TST_enum: return ETK_Enum;
2981 }
2982}
2983
2986 switch(TypeSpec) {
2987 case TST_class: return TTK_Class;
2988 case TST_struct: return TTK_Struct;
2989 case TST_interface: return TTK_Interface;
2990 case TST_union: return TTK_Union;
2991 case TST_enum: return TTK_Enum;
2992 }
2993
2994 llvm_unreachable("Type specifier is not a tag type kind.");
2995}
2996
2999 switch (Kind) {
3000 case TTK_Class: return ETK_Class;
3001 case TTK_Struct: return ETK_Struct;
3002 case TTK_Interface: return ETK_Interface;
3003 case TTK_Union: return ETK_Union;
3004 case TTK_Enum: return ETK_Enum;
3005 }
3006 llvm_unreachable("Unknown tag type kind.");
3007}
3008
3011 switch (Keyword) {
3012 case ETK_Class: return TTK_Class;
3013 case ETK_Struct: return TTK_Struct;
3014 case ETK_Interface: return TTK_Interface;
3015 case ETK_Union: return TTK_Union;
3016 case ETK_Enum: return TTK_Enum;
3017 case ETK_None: // Fall through.
3018 case ETK_Typename:
3019 llvm_unreachable("Elaborated type keyword is not a tag type kind.");
3020 }
3021 llvm_unreachable("Unknown elaborated type keyword.");
3022}
3023
3024bool
3026 switch (Keyword) {
3027 case ETK_None:
3028 case ETK_Typename:
3029 return false;
3030 case ETK_Class:
3031 case ETK_Struct:
3032 case ETK_Interface:
3033 case ETK_Union:
3034 case ETK_Enum:
3035 return true;
3036 }
3037 llvm_unreachable("Unknown elaborated type keyword.");
3038}
3039
3041 switch (Keyword) {
3042 case ETK_None: return {};
3043 case ETK_Typename: return "typename";
3044 case ETK_Class: return "class";
3045 case ETK_Struct: return "struct";
3046 case ETK_Interface: return "__interface";
3047 case ETK_Union: return "union";
3048 case ETK_Enum: return "enum";
3049 }
3050
3051 llvm_unreachable("Unknown elaborated type keyword.");
3052}
3053
3054DependentTemplateSpecializationType::DependentTemplateSpecializationType(
3056 const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args, QualType Canon)
3057 : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon,
3058 TypeDependence::DependentInstantiation |
3059 (NNS ? toTypeDependence(NNS->getDependence())
3060 : TypeDependence::None)),
3061 NNS(NNS), Name(Name) {
3062 DependentTemplateSpecializationTypeBits.NumArgs = Args.size();
3063 assert((!NNS || NNS->isDependent()) &&
3064 "DependentTemplateSpecializatonType requires dependent qualifier");
3065 auto *ArgBuffer = const_cast<TemplateArgument *>(template_arguments().data());
3066 for (const TemplateArgument &Arg : Args) {
3067 addDependence(toTypeDependence(Arg.getDependence() &
3068 TemplateArgumentDependence::UnexpandedPack));
3069
3070 new (ArgBuffer++) TemplateArgument(Arg);
3071 }
3072}
3073
3074void
3076 const ASTContext &Context,
3077 ElaboratedTypeKeyword Keyword,
3078 NestedNameSpecifier *Qualifier,
3079 const IdentifierInfo *Name,
3081 ID.AddInteger(Keyword);
3082 ID.AddPointer(Qualifier);
3083 ID.AddPointer(Name);
3084 for (const TemplateArgument &Arg : Args)
3085 Arg.Profile(ID, Context);
3086}
3087
3089 ElaboratedTypeKeyword Keyword;
3090 if (const auto *Elab = dyn_cast<ElaboratedType>(this))
3091 Keyword = Elab->getKeyword();
3092 else if (const auto *DepName = dyn_cast<DependentNameType>(this))
3093 Keyword = DepName->getKeyword();
3094 else if (const auto *DepTST =
3095 dyn_cast<DependentTemplateSpecializationType>(this))
3096 Keyword = DepTST->getKeyword();
3097 else
3098 return false;
3099
3101}
3102
3103const char *Type::getTypeClassName() const {
3104 switch (TypeBits.TC) {
3105#define ABSTRACT_TYPE(Derived, Base)
3106#define TYPE(Derived, Base) case Derived: return #Derived;
3107#include "clang/AST/TypeNodes.inc"
3108 }
3109
3110 llvm_unreachable("Invalid type class.");
3111}
3112
3113StringRef BuiltinType::getName(const PrintingPolicy &Policy) const {
3114 switch (getKind()) {
3115 case Void:
3116 return "void";
3117 case Bool:
3118 return Policy.Bool ? "bool" : "_Bool";
3119 case Char_S:
3120 return "char";
3121 case Char_U:
3122 return "char";
3123 case SChar:
3124 return "signed char";
3125 case Short:
3126 return "short";
3127 case Int:
3128 return "int";
3129 case Long:
3130 return "long";
3131 case LongLong:
3132 return "long long";
3133 case Int128:
3134 return "__int128";
3135 case UChar:
3136 return "unsigned char";
3137 case UShort:
3138 return "unsigned short";
3139 case UInt:
3140 return "unsigned int";
3141 case ULong:
3142 return "unsigned long";
3143 case ULongLong:
3144 return "unsigned long long";
3145 case UInt128:
3146 return "unsigned __int128";
3147 case Half:
3148 return Policy.Half ? "half" : "__fp16";
3149 case BFloat16:
3150 return "__bf16";
3151 case Float:
3152 return "float";
3153 case Double:
3154 return "double";
3155 case LongDouble:
3156 return "long double";
3157 case ShortAccum:
3158 return "short _Accum";
3159 case Accum:
3160 return "_Accum";
3161 case LongAccum:
3162 return "long _Accum";
3163 case UShortAccum:
3164 return "unsigned short _Accum";
3165 case UAccum:
3166 return "unsigned _Accum";
3167 case ULongAccum:
3168 return "unsigned long _Accum";
3169 case BuiltinType::ShortFract:
3170 return "short _Fract";
3171 case BuiltinType::Fract:
3172 return "_Fract";
3173 case BuiltinType::LongFract:
3174 return "long _Fract";
3175 case BuiltinType::UShortFract:
3176 return "unsigned short _Fract";
3177 case BuiltinType::UFract:
3178 return "unsigned _Fract";
3179 case BuiltinType::ULongFract:
3180 return "unsigned long _Fract";
3181 case BuiltinType::SatShortAccum:
3182 return "_Sat short _Accum";
3183 case BuiltinType::SatAccum:
3184 return "_Sat _Accum";
3185 case BuiltinType::SatLongAccum:
3186 return "_Sat long _Accum";
3187 case BuiltinType::SatUShortAccum:
3188 return "_Sat unsigned short _Accum";
3189 case BuiltinType::SatUAccum:
3190 return "_Sat unsigned _Accum";
3191 case BuiltinType::SatULongAccum:
3192 return "_Sat unsigned long _Accum";
3193 case BuiltinType::SatShortFract:
3194 return "_Sat short _Fract";
3195 case BuiltinType::SatFract:
3196 return "_Sat _Fract";
3197 case BuiltinType::SatLongFract:
3198 return "_Sat long _Fract";
3199 case BuiltinType::SatUShortFract:
3200 return "_Sat unsigned short _Fract";
3201 case BuiltinType::SatUFract:
3202 return "_Sat unsigned _Fract";
3203 case BuiltinType::SatULongFract:
3204 return "_Sat unsigned long _Fract";
3205 case Float16:
3206 return "_Float16";
3207 case Float128:
3208 return "__float128";
3209 case Ibm128:
3210 return "__ibm128";
3211 case WChar_S:
3212 case WChar_U:
3213 return Policy.MSWChar ? "__wchar_t" : "wchar_t";
3214 case Char8:
3215 return "char8_t";
3216 case Char16:
3217 return "char16_t";
3218 case Char32:
3219 return "char32_t";
3220 case NullPtr:
3221 return Policy.NullptrTypeInNamespace ? "std::nullptr_t" : "nullptr_t";
3222 case Overload:
3223 return "<overloaded function type>";
3224 case BoundMember:
3225 return "<bound member function type>";
3226 case PseudoObject:
3227 return "<pseudo-object type>";
3228 case Dependent:
3229 return "<dependent type>";
3230 case UnknownAny:
3231 return "<unknown type>";
3232 case ARCUnbridgedCast:
3233 return "<ARC unbridged cast type>";
3234 case BuiltinFn:
3235 return "<builtin fn type>";
3236 case ObjCId:
3237 return "id";
3238 case ObjCClass:
3239 return "Class";
3240 case ObjCSel:
3241 return "SEL";
3242#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3243 case Id: \
3244 return "__" #Access " " #ImgType "_t";
3245#include "clang/Basic/OpenCLImageTypes.def"
3246 case OCLSampler:
3247 return "sampler_t";
3248 case OCLEvent:
3249 return "event_t";
3250 case OCLClkEvent:
3251 return "clk_event_t";
3252 case OCLQueue:
3253 return "queue_t";
3254 case OCLReserveID:
3255 return "reserve_id_t";
3256 case IncompleteMatrixIdx:
3257 return "<incomplete matrix index type>";
3258 case OMPArraySection:
3259 return "<OpenMP array section type>";
3260 case OMPArrayShaping:
3261 return "<OpenMP array shaping type>";
3262 case OMPIterator:
3263 return "<OpenMP iterator type>";
3264#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3265 case Id: \
3266 return #ExtType;
3267#include "clang/Basic/OpenCLExtensionTypes.def"
3268#define SVE_TYPE(Name, Id, SingletonId) \
3269 case Id: \
3270 return Name;
3271#include "clang/Basic/AArch64SVEACLETypes.def"
3272#define PPC_VECTOR_TYPE(Name, Id, Size) \
3273 case Id: \
3274 return #Name;
3275#include "clang/Basic/PPCTypes.def"
3276#define RVV_TYPE(Name, Id, SingletonId) \
3277 case Id: \
3278 return Name;
3279#include "clang/Basic/RISCVVTypes.def"
3280#define WASM_TYPE(Name, Id, SingletonId) \
3281 case Id: \
3282 return Name;
3283#include "clang/Basic/WebAssemblyReferenceTypes.def"
3284 }
3285
3286 llvm_unreachable("Invalid builtin type.");
3287}
3288
3290 // We never wrap type sugar around a PackExpansionType.
3291 if (auto *PET = dyn_cast<PackExpansionType>(getTypePtr()))
3292 return PET->getPattern();
3293 return *this;
3294}
3295
3297 if (const auto *RefType = getTypePtr()->getAs<ReferenceType>())
3298 return RefType->getPointeeType();
3299
3300 // C++0x [basic.lval]:
3301 // Class prvalues can have cv-qualified types; non-class prvalues always
3302 // have cv-unqualified types.
3303 //
3304 // See also C99 6.3.2.1p2.
3305 if (!Context.getLangOpts().CPlusPlus ||
3306 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
3307 return getUnqualifiedType();
3308
3309 return *this;
3310}
3311
3313 switch (CC) {
3314 case CC_C: return "cdecl";
3315 case CC_X86StdCall: return "stdcall";
3316 case CC_X86FastCall: return "fastcall";
3317 case CC_X86ThisCall: return "thiscall";
3318 case CC_X86Pascal: return "pascal";
3319 case CC_X86VectorCall: return "vectorcall";
3320 case CC_Win64: return "ms_abi";
3321 case CC_X86_64SysV: return "sysv_abi";
3322 case CC_X86RegCall : return "regcall";
3323 case CC_AAPCS: return "aapcs";
3324 case CC_AAPCS_VFP: return "aapcs-vfp";
3325 case CC_AArch64VectorCall: return "aarch64_vector_pcs";
3326 case CC_AArch64SVEPCS: return "aarch64_sve_pcs";
3327 case CC_AMDGPUKernelCall: return "amdgpu_kernel";
3328 case CC_IntelOclBicc: return "intel_ocl_bicc";
3329 case CC_SpirFunction: return "spir_function";
3330 case CC_OpenCLKernel: return "opencl_kernel";
3331 case CC_Swift: return "swiftcall";
3332 case CC_SwiftAsync: return "swiftasynccall";
3333 case CC_PreserveMost: return "preserve_most";
3334 case CC_PreserveAll: return "preserve_all";
3335 }
3336
3337 llvm_unreachable("Invalid calling convention.");
3338}
3339
3340FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> params,
3341 QualType canonical,
3342 const ExtProtoInfo &epi)
3343 : FunctionType(FunctionProto, result, canonical, result->getDependence(),
3344 epi.ExtInfo) {
3345 FunctionTypeBits.FastTypeQuals = epi.TypeQuals.getFastQualifiers();
3346 FunctionTypeBits.RefQualifier = epi.RefQualifier;
3347 FunctionTypeBits.NumParams = params.size();
3348 assert(getNumParams() == params.size() && "NumParams overflow!");
3349 FunctionTypeBits.ExceptionSpecType = epi.ExceptionSpec.Type;
3350 FunctionTypeBits.HasExtParameterInfos = !!epi.ExtParameterInfos;
3351 FunctionTypeBits.Variadic = epi.Variadic;
3352 FunctionTypeBits.HasTrailingReturn = epi.HasTrailingReturn;
3353
3354 if (epi.requiresFunctionProtoTypeExtraBitfields()) {
3355 FunctionTypeBits.HasExtraBitfields = true;
3356 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
3357 ExtraBits = FunctionTypeExtraBitfields();
3358 } else {
3359 FunctionTypeBits.HasExtraBitfields = false;
3360 }
3361
3362
3363 // Fill in the trailing argument array.
3364 auto *argSlot = getTrailingObjects<QualType>();
3365 for (unsigned i = 0; i != getNumParams(); ++i) {
3366 addDependence(params[i]->getDependence() &
3367 ~TypeDependence::VariablyModified);
3368 argSlot[i] = params[i];
3369 }
3370
3371 // Fill in the exception type array if present.
3372 if (getExceptionSpecType() == EST_Dynamic) {
3373 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
3374 size_t NumExceptions = epi.ExceptionSpec.Exceptions.size();
3375 assert(NumExceptions <= UINT16_MAX &&
3376 "Not enough bits to encode exceptions");
3377 ExtraBits.NumExceptionType = NumExceptions;
3378
3379 assert(hasExtraBitfields() && "missing trailing extra bitfields!");
3380 auto *exnSlot =
3381 reinterpret_cast<QualType *>(getTrailingObjects<ExceptionType>());
3382 unsigned I = 0;
3383 for (QualType ExceptionType : epi.ExceptionSpec.Exceptions) {
3384 // Note that, before C++17, a dependent exception specification does
3385 // *not* make a type dependent; it's not even part of the C++ type
3386 // system.
3388 ExceptionType->getDependence() &
3389 (TypeDependence::Instantiation | TypeDependence::UnexpandedPack));
3390
3391 exnSlot[I++] = ExceptionType;
3392 }
3393 }
3394 // Fill in the Expr * in the exception specification if present.
3395 else if (isComputedNoexcept(getExceptionSpecType())) {
3396 assert(epi.ExceptionSpec.NoexceptExpr && "computed noexcept with no expr");
3397 assert((getExceptionSpecType() == EST_DependentNoexcept) ==
3398 epi.ExceptionSpec.NoexceptExpr->isValueDependent());
3399
3400 // Store the noexcept expression and context.
3401 *getTrailingObjects<Expr *>() = epi.ExceptionSpec.NoexceptExpr;
3402
3404 toTypeDependence(epi.ExceptionSpec.NoexceptExpr->getDependence()) &
3405 (TypeDependence::Instantiation | TypeDependence::UnexpandedPack));
3406 }
3407 // Fill in the FunctionDecl * in the exception specification if present.
3408 else if (getExceptionSpecType() == EST_Uninstantiated) {
3409 // Store the function decl from which we will resolve our
3410 // exception specification.
3411 auto **slot = getTrailingObjects<FunctionDecl *>();
3412 slot[0] = epi.ExceptionSpec.SourceDecl;
3413 slot[1] = epi.ExceptionSpec.SourceTemplate;
3414 // This exception specification doesn't make the type dependent, because
3415 // it's not instantiated as part of instantiating the type.
3416 } else if (getExceptionSpecType() == EST_Unevaluated) {
3417 // Store the function decl from which we will resolve our
3418 // exception specification.
3419 auto **slot = getTrailingObjects<FunctionDecl *>();
3420 slot[0] = epi.ExceptionSpec.SourceDecl;
3421 }
3422
3423 // If this is a canonical type, and its exception specification is dependent,
3424 // then it's a dependent type. This only happens in C++17 onwards.
3425 if (isCanonicalUnqualified()) {
3426 if (getExceptionSpecType() == EST_Dynamic ||
3427 getExceptionSpecType() == EST_DependentNoexcept) {
3428 assert(hasDependentExceptionSpec() && "type should not be canonical");
3429 addDependence(TypeDependence::DependentInstantiation);
3430 }
3431 } else if (getCanonicalTypeInternal()->isDependentType()) {
3432 // Ask our canonical type whether our exception specification was dependent.
3433 addDependence(TypeDependence::DependentInstantiation);
3434 }
3435
3436 // Fill in the extra parameter info if present.
3437 if (epi.ExtParameterInfos) {
3438 auto *extParamInfos = getTrailingObjects<ExtParameterInfo>();
3439 for (unsigned i = 0; i != getNumParams(); ++i)
3440 extParamInfos[i] = epi.ExtParameterInfos[i];
3441 }
3442
3443 if (epi.TypeQuals.hasNonFastQualifiers()) {
3444 FunctionTypeBits.HasExtQuals = 1;
3445 *getTrailingObjects<Qualifiers>() = epi.TypeQuals;
3446 } else {
3447 FunctionTypeBits.HasExtQuals = 0;
3448 }
3449
3450 // Fill in the Ellipsis location info if present.
3451 if (epi.Variadic) {
3452 auto &EllipsisLoc = *getTrailingObjects<SourceLocation>();
3453 EllipsisLoc = epi.EllipsisLoc;
3454 }
3455}
3456
3458 if (Expr *NE = getNoexceptExpr())
3459 return NE->isValueDependent();
3460 for (QualType ET : exceptions())
3461 // A pack expansion with a non-dependent pattern is still dependent,
3462 // because we don't know whether the pattern is in the exception spec
3463 // or not (that depends on whether the pack has 0 expansions).
3464 if (ET->isDependentType() || ET->getAs<PackExpansionType>())
3465 return true;
3466 return false;
3467}
3468
3470 if (Expr *NE = getNoexceptExpr())
3471 return NE->isInstantiationDependent();
3472 for (QualType ET : exceptions())
3473 if (ET->isInstantiationDependentType())
3474 return true;
3475 return false;
3476}
3477
3479 switch (getExceptionSpecType()) {
3480 case EST_Unparsed:
3481 case EST_Unevaluated:
3482 llvm_unreachable("should not call this with unresolved exception specs");
3483
3484 case EST_DynamicNone:
3485 case EST_BasicNoexcept:
3486 case EST_NoexceptTrue:
3487 case EST_NoThrow:
3488 return CT_Cannot;
3489
3490 case EST_None:
3491 case EST_MSAny:
3492 case EST_NoexceptFalse:
3493 return CT_Can;
3494
3495 case EST_Dynamic:
3496 // A dynamic exception specification is throwing unless every exception
3497 // type is an (unexpanded) pack expansion type.
3498 for (unsigned I = 0; I != getNumExceptions(); ++I)
3500 return CT_Can;
3501 return CT_Dependent;
3502
3503 case EST_Uninstantiated:
3505 return CT_Dependent;
3506 }
3507
3508 llvm_unreachable("unexpected exception specification kind");
3509}
3510
3512 for (unsigned ArgIdx = getNumParams(); ArgIdx; --ArgIdx)
3513 if (isa<PackExpansionType>(getParamType(ArgIdx - 1)))
3514 return true;
3515
3516 return false;
3517}
3518
3519void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
3520 const QualType *ArgTys, unsigned NumParams,
3521 const ExtProtoInfo &epi,
3522 const ASTContext &Context, bool Canonical) {
3523 // We have to be careful not to get ambiguous profile encodings.
3524 // Note that valid type pointers are never ambiguous with anything else.
3525 //
3526 // The encoding grammar begins:
3527 // type type* bool int bool
3528 // If that final bool is true, then there is a section for the EH spec:
3529 // bool type*
3530 // This is followed by an optional "consumed argument" section of the
3531 // same length as the first type sequence:
3532 // bool*
3533 // Finally, we have the ext info and trailing return type flag:
3534 // int bool
3535 //
3536 // There is no ambiguity between the consumed arguments and an empty EH
3537 // spec because of the leading 'bool' which unambiguously indicates
3538 // whether the following bool is the EH spec or part of the arguments.
3539
3540 ID.AddPointer(Result.getAsOpaquePtr());
3541 for (unsigned i = 0; i != NumParams; ++i)
3542 ID.AddPointer(ArgTys[i].getAsOpaquePtr());
3543 // This method is relatively performance sensitive, so as a performance
3544 // shortcut, use one AddInteger call instead of four for the next four
3545 // fields.
3546 assert(!(unsigned(epi.Variadic) & ~1) &&
3547 !(unsigned(epi.RefQualifier) & ~3) &&
3548 !(unsigned(epi.ExceptionSpec.Type) & ~15) &&
3549 "Values larger than expected.");
3550 ID.AddInteger(unsigned(epi.Variadic) +
3551 (epi.RefQualifier << 1) +
3552 (epi.ExceptionSpec.Type << 3));
3553 ID.Add(epi.TypeQuals);
3554 if (epi.ExceptionSpec.Type == EST_Dynamic) {
3555 for (QualType Ex : epi.ExceptionSpec.Exceptions)
3556 ID.AddPointer(Ex.getAsOpaquePtr());
3557 } else if (isComputedNoexcept(epi.ExceptionSpec.Type)) {
3558 epi.ExceptionSpec.NoexceptExpr->Profile(ID, Context, Canonical);
3559 } else if (epi.ExceptionSpec.Type == EST_Uninstantiated ||
3560 epi.ExceptionSpec.Type == EST_Unevaluated) {
3561 ID.AddPointer(epi.ExceptionSpec.SourceDecl->getCanonicalDecl());
3562 }
3563 if (epi.ExtParameterInfos) {
3564 for (unsigned i = 0; i != NumParams; ++i)
3565 ID.AddInteger(epi.ExtParameterInfos[i].getOpaqueValue());
3566 }
3567 epi.ExtInfo.Profile(ID);
3568 ID.AddBoolean(epi.HasTrailingReturn);
3569}
3570
3571void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
3572 const ASTContext &Ctx) {
3575}
3576
3577TypedefType::TypedefType(TypeClass tc, const TypedefNameDecl *D,
3578 QualType Underlying, QualType can)
3579 : Type(tc, can, toSemanticDependence(can->getDependence())),
3580 Decl(const_cast<TypedefNameDecl *>(D)) {
3581 assert(!isa<TypedefType>(can) && "Invalid canonical type");
3582 TypedefBits.hasTypeDifferentFromDecl = !Underlying.isNull();
3583 if (!typeMatchesDecl())
3584 *getTrailingObjects<QualType>() = Underlying;
3585}
3586
3588 return typeMatchesDecl() ? Decl->getUnderlyingType()
3589 : *getTrailingObjects<QualType>();
3590}
3591
3592UsingType::UsingType(const UsingShadowDecl *Found, QualType Underlying,
3593 QualType Canon)
3594 : Type(Using, Canon, toSemanticDependence(Canon->getDependence())),
3595 Found(const_cast<UsingShadowDecl *>(Found)) {
3596 UsingBits.hasTypeDifferentFromDecl = !Underlying.isNull();
3597 if (!typeMatchesDecl())
3598 *getTrailingObjects<QualType>() = Underlying;
3599}
3600
3602 return typeMatchesDecl()
3603 ? QualType(
3604 cast<TypeDecl>(Found->getTargetDecl())->getTypeForDecl(), 0)
3605 : *getTrailingObjects<QualType>();
3606}
3607
3609
3611 // Step over MacroQualifiedTypes from the same macro to find the type
3612 // ultimately qualified by the macro qualifier.
3613 QualType Inner = cast<AttributedType>(getUnderlyingType())->getModifiedType();
3614 while (auto *InnerMQT = dyn_cast<MacroQualifiedType>(Inner)) {
3615 if (InnerMQT->getMacroIdentifier() != getMacroIdentifier())
3616 break;
3617 Inner = InnerMQT->getModifiedType();
3618 }
3619 return Inner;
3620}
3621
3623 : Type(TypeOfExpr,
3624 // We have to protect against 'Can' being invalid through its
3625 // default argument.
3626 Kind == TypeOfKind::Unqualified && !Can.isNull()
3627 ? Can.getAtomicUnqualifiedType()
3628 : Can,
3629 toTypeDependence(E->getDependence()) |
3630 (E->getType()->getDependence() &
3631 TypeDependence::VariablyModified)),
3632 TOExpr(E) {
3633 TypeOfBits.IsUnqual = Kind == TypeOfKind::Unqualified;
3634}
3635
3637 return !TOExpr->isTypeDependent();
3638}
3639
3641 if (isSugared()) {
3643 return TypeOfBits.IsUnqual ? QT.getAtomicUnqualifiedType() : QT;
3644 }
3645 return QualType(this, 0);
3646}
3647
3648void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
3649 const ASTContext &Context, Expr *E,
3650 bool IsUnqual) {
3651 E->Profile(ID, Context, true);
3652 ID.AddBoolean(IsUnqual);
3653}
3654
3656 // C++11 [temp.type]p2: "If an expression e involves a template parameter,
3657 // decltype(e) denotes a unique dependent type." Hence a decltype type is
3658 // type-dependent even if its expression is only instantiation-dependent.
3659 : Type(Decltype, can,
3660 toTypeDependence(E->getDependence()) |
3661 (E->isInstantiationDependent() ? TypeDependence::Dependent
3662 : TypeDependence::None) |
3663 (E->getType()->getDependence() &
3664 TypeDependence::VariablyModified)),
3665 E(E), UnderlyingType(underlyingType) {}
3666
3668
3670 if (isSugared())
3671 return getUnderlyingType();
3672
3673 return QualType(this, 0);
3674}
3675
3677 : DecltypeType(E, Context.DependentTy), Context(Context) {}
3678
3679void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
3680 const ASTContext &Context, Expr *E) {
3681 E->Profile(ID, Context, true);
3682}
3683
3685 QualType UnderlyingType, UTTKind UKind,
3686 QualType CanonicalType)
3687 : Type(UnaryTransform, CanonicalType, BaseType->getDependence()),
3688 BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind) {}
3689
3691 QualType BaseType,
3692 UTTKind UKind)
3693 : UnaryTransformType(BaseType, C.DependentTy, UKind, QualType()) {}
3694
3696 : Type(TC, can,
3697 D->isDependentType() ? TypeDependence::DependentInstantiation
3698 : TypeDependence::None),
3699 decl(const_cast<TagDecl *>(D)) {}
3700
3702 for (auto *I : decl->redecls()) {
3703 if (I->isCompleteDefinition() || I->isBeingDefined())
3704 return I;
3705 }
3706 // If there's no definition (not even in progress), return what we have.
3707 return decl;
3708}
3709
3711 return getInterestingTagDecl(decl);
3712}
3713
3715 return getDecl()->isBeingDefined();
3716}
3717
3719 std::vector<const RecordType*> RecordTypeList;
3720 RecordTypeList.push_back(this);
3721 unsigned NextToCheckIndex = 0;
3722
3723 while (RecordTypeList.size() > NextToCheckIndex) {
3724 for (FieldDecl *FD :
3725 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
3726 QualType FieldTy = FD->getType();
3727 if (FieldTy.isConstQualified())
3728 return true;
3729 FieldTy = FieldTy.getCanonicalType();
3730 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
3731 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
3732 RecordTypeList.push_back(FieldRecTy);
3733 }
3734 }
3735 ++NextToCheckIndex;
3736 }
3737 return false;
3738}
3739
3741 // FIXME: Generate this with TableGen.
3742 switch (getAttrKind()) {
3743 // These are type qualifiers in the traditional C sense: they annotate
3744 // something about a specific value/variable of a type. (They aren't
3745 // always part of the canonical type, though.)
3746 case attr::ObjCGC:
3747 case attr::ObjCOwnership:
3748 case attr::ObjCInertUnsafeUnretained:
3749 case attr::TypeNonNull:
3750 case attr::TypeNullable:
3751 case attr::TypeNullableResult:
3752 case attr::TypeNullUnspecified:
3753 case attr::LifetimeBound:
3754 case attr::AddressSpace:
3755 return true;
3756
3757 // All other type attributes aren't qualifiers; they rewrite the modified
3758 // type to be a semantically different type.
3759 default:
3760 return false;
3761 }
3762}
3763
3765 // FIXME: Generate this with TableGen?
3766 switch (getAttrKind()) {
3767 default: return false;
3768 case attr::Ptr32:
3769 case attr::Ptr64:
3770 case attr::SPtr:
3771 case attr::UPtr:
3772 return true;
3773 }
3774 llvm_unreachable("invalid attr kind");
3775}
3776
3778 return getAttrKind() == attr::WebAssemblyFuncref;
3779}
3780
3782 // FIXME: Generate this with TableGen.
3783 switch (getAttrKind()) {
3784 default: return false;
3785 case attr::Pcs:
3786 case attr::CDecl:
3787 case attr::FastCall:
3788 case attr::StdCall:
3789 case attr::ThisCall:
3790 case attr::RegCall:
3791 case attr::SwiftCall:
3792 case attr::SwiftAsyncCall:
3793 case attr::VectorCall:
3794 case attr::AArch64VectorPcs:
3795 case attr::AArch64SVEPcs:
3796 case attr::AMDGPUKernelCall:
3797 case attr::Pascal:
3798 case attr::MSABI:
3799 case attr::SysVABI:
3800 case attr::IntelOclBicc:
3801 case attr::PreserveMost:
3802 case attr::PreserveAll:
3803 return true;
3804 }
3805 llvm_unreachable("invalid attr kind");
3806}
3807
3809 return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
3810}
3811
3813 return isCanonicalUnqualified() ? nullptr : getDecl()->getIdentifier();
3814}
3815
3817 unsigned Index) {
3818 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(D))
3819 return TTP;
3820 return cast<TemplateTypeParmDecl>(
3821 getReplacedTemplateParameterList(D)->getParam(Index));
3822}
3823
3824SubstTemplateTypeParmType::SubstTemplateTypeParmType(
3825 QualType Replacement, Decl *AssociatedDecl, unsigned Index,
3826 std::optional<unsigned> PackIndex)
3827 : Type(SubstTemplateTypeParm, Replacement.getCanonicalType(),
3828 Replacement->getDependence()),
3829 AssociatedDecl(AssociatedDecl) {
3830 SubstTemplateTypeParmTypeBits.HasNonCanonicalUnderlyingType =
3831 Replacement != getCanonicalTypeInternal();
3832 if (SubstTemplateTypeParmTypeBits.HasNonCanonicalUnderlyingType)
3833 *getTrailingObjects<QualType>() = Replacement;
3834
3835 SubstTemplateTypeParmTypeBits.Index = Index;
3836 SubstTemplateTypeParmTypeBits.PackIndex = PackIndex ? *PackIndex + 1 : 0;
3837 assert(AssociatedDecl != nullptr);
3838}
3839
3842 return ::getReplacedParameter(getAssociatedDecl(), getIndex());
3843}
3844
3845SubstTemplateTypeParmPackType::SubstTemplateTypeParmPackType(
3846 QualType Canon, Decl *AssociatedDecl, unsigned Index, bool Final,
3847 const TemplateArgument &ArgPack)
3848 : Type(SubstTemplateTypeParmPack, Canon,
3849 TypeDependence::DependentInstantiation |
3850 TypeDependence::UnexpandedPack),
3851 Arguments(ArgPack.pack_begin()),
3852 AssociatedDeclAndFinal(AssociatedDecl, Final) {
3854 SubstTemplateTypeParmPackTypeBits.NumArgs = ArgPack.pack_size();
3855 assert(AssociatedDecl != nullptr);
3856}
3857
3859 return AssociatedDeclAndFinal.getPointer();
3860}
3861
3863 return AssociatedDeclAndFinal.getInt();
3864}
3865
3868 return ::getReplacedParameter(getAssociatedDecl(), getIndex());
3869}
3870
3873}
3874
3876 return TemplateArgument(llvm::ArrayRef(Arguments, getNumArgs()));
3877}
3878
3879void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
3881}
3882
3883void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
3884 const Decl *AssociatedDecl,
3885 unsigned Index, bool Final,
3886 const TemplateArgument &ArgPack) {
3887 ID.AddPointer(AssociatedDecl);
3888 ID.AddInteger(Index);
3889 ID.AddBoolean(Final);
3890 ID.AddInteger(ArgPack.pack_size());
3891 for (const auto &P : ArgPack.pack_elements())
3892 ID.AddPointer(P.getAsType().getAsOpaquePtr());
3893}
3894
3897 return anyDependentTemplateArguments(Args.arguments(), Converted);
3898}
3899
3902 for (const TemplateArgument &Arg : Converted)
3903 if (Arg.isDependent())
3904 return true;
3905 return false;
3906}
3907
3910 for (const TemplateArgumentLoc &ArgLoc : Args) {
3911 if (ArgLoc.getArgument().isInstantiationDependent())
3912 return true;
3913 }
3914 return false;
3915}
3916
3917TemplateSpecializationType::TemplateSpecializationType(
3919 QualType AliasedType)
3920 : Type(TemplateSpecialization, Canon.isNull() ? QualType(this, 0) : Canon,
3921 (Canon.isNull()
3922 ? TypeDependence::DependentInstantiation
3923 : toSemanticDependence(Canon->getDependence())) |
3924 (toTypeDependence(T.getDependence()) &
3925 TypeDependence::UnexpandedPack)),
3926 Template(T) {
3927 TemplateSpecializationTypeBits.NumArgs = Args.size();
3928 TemplateSpecializationTypeBits.TypeAlias = !AliasedType.isNull();
3929
3930 assert(!T.getAsDependentTemplateName() &&
3931 "Use DependentTemplateSpecializationType for dependent template-name");
3932 assert((T.getKind() == TemplateName::Template ||
3936 "Unexpected template name for TemplateSpecializationType");
3937
3938 auto *TemplateArgs = reinterpret_cast<TemplateArgument *>(this + 1);
3939 for (const TemplateArgument &Arg : Args) {
3940 // Update instantiation-dependent, variably-modified, and error bits.
3941 // If the canonical type exists and is non-dependent, the template
3942 // specialization type can be non-dependent even if one of the type
3943 // arguments is. Given:
3944 // template<typename T> using U = int;
3945 // U<T> is always non-dependent, irrespective of the type T.
3946 // However, U<Ts> contains an unexpanded parameter pack, even though
3947 // its expansion (and thus its desugared type) doesn't.
3948 addDependence(toTypeDependence(Arg.getDependence()) &
3949 ~TypeDependence::Dependent);
3950 if (Arg.getKind() == TemplateArgument::Type)
3951 addDependence(Arg.getAsType()->getDependence() &
3952 TypeDependence::VariablyModified);
3953 new (TemplateArgs++) TemplateArgument(Arg);
3954 }
3955
3956 // Store the aliased type if this is a type alias template specialization.
3957 if (isTypeAlias()) {
3958 auto *Begin = reinterpret_cast<TemplateArgument *>(this + 1);
3959 *reinterpret_cast<QualType *>(Begin + Args.size()) = AliasedType;
3960 }
3961}
3962
3964 assert(isTypeAlias() && "not a type alias template specialization");
3965 return *reinterpret_cast<const QualType *>(template_arguments().end());
3966}
3967
3968void TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
3969 const ASTContext &Ctx) {
3970 Profile(ID, Template, template_arguments(), Ctx);
3971 if (isTypeAlias())
3972 getAliasedType().Profile(ID);
3973}
3974
3975void
3976TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
3977 TemplateName T,
3979 const ASTContext &Context) {
3980 T.Profile(ID);
3981 for (const TemplateArgument &Arg : Args)
3982 Arg.Profile(ID, Context);
3983}
3984
3987 if (!hasNonFastQualifiers())
3989
3990 return Context.getQualifiedType(QT, *this);
3991}
3992
3994QualifierCollector::apply(const ASTContext &Context, const Type *T) const {
3995 if (!hasNonFastQualifiers())
3996 return QualType(T, getFastQualifiers());
3997
3998 return Context.getQualifiedType(T, *this);
3999}
4000
4001void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
4002 QualType BaseType,
4003 ArrayRef<QualType> typeArgs,
4005 bool isKindOf) {
4006 ID.AddPointer(BaseType.getAsOpaquePtr());
4007 ID.AddInteger(typeArgs.size());
4008 for (auto typeArg : typeArgs)
4009 ID.AddPointer(typeArg.getAsOpaquePtr());
4010 ID.AddInteger(protocols.size());
4011 for (auto *proto : protocols)
4012 ID.AddPointer(proto);
4013 ID.AddBoolean(isKindOf);
4014}
4015
4016void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
4020}
4021
4022void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID,
4023 const ObjCTypeParamDecl *OTPDecl,
4024 QualType CanonicalType,
4025 ArrayRef<ObjCProtocolDecl *> protocols) {
4026 ID.AddPointer(OTPDecl);
4027 ID.AddPointer(CanonicalType.getAsOpaquePtr());
4028 ID.AddInteger(protocols.size());
4029 for (auto *proto : protocols)
4030 ID.AddPointer(proto);
4031}
4032
4033void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID) {
4036}
4037
4038namespace {
4039
4040/// The cached properties of a type.
4041class CachedProperties {
4042 Linkage L;
4043 bool local;
4044
4045public:
4046 CachedProperties(Linkage L, bool local) : L(L), local(local) {}
4047
4048 Linkage getLinkage() const { return L; }
4049 bool hasLocalOrUnnamedType() const { return local; }
4050
4051 friend CachedProperties merge(CachedProperties L, CachedProperties R) {
4052 Linkage MergedLinkage = minLinkage(L.L, R.L);
4053 return CachedProperties(MergedLinkage, L.hasLocalOrUnnamedType() ||
4054 R.hasLocalOrUnnamedType());
4055 }
4056};
4057
4058} // namespace
4059
4060static CachedProperties computeCachedProperties(const Type *T);
4061
4062namespace clang {
4063
4064/// The type-property cache. This is templated so as to be
4065/// instantiated at an internal type to prevent unnecessary symbol
4066/// leakage.
4067template <class Private> class TypePropertyCache {
4068public:
4069 static CachedProperties get(QualType T) {
4070 return get(T.getTypePtr());
4071 }
4072
4073 static CachedProperties get(const Type *T) {
4074 ensure(T);
4075 return CachedProperties(T->TypeBits.getLinkage(),
4076 T->TypeBits.hasLocalOrUnnamedType());
4077 }
4078
4079 static void ensure(const Type *T) {
4080 // If the cache is valid, we're okay.
4081 if (T->TypeBits.isCacheValid()) return;
4082
4083 // If this type is non-canonical, ask its canonical type for the
4084 // relevant information.
4085 if (!T->isCanonicalUnqualified()) {
4086 const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
4087 ensure(CT);
4088 T->TypeBits.CacheValid = true;
4089 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
4090 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
4091 return;
4092 }
4093
4094 // Compute the cached properties and then set the cache.
4095 CachedProperties Result = computeCachedProperties(T);
4096 T->TypeBits.CacheValid = true;
4097 T->TypeBits.CachedLinkage = Result.getLinkage();
4098 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
4099 }
4100};
4101
4102} // namespace clang
4103
4104// Instantiate the friend template at a private class. In a
4105// reasonable implementation, these symbols will be internal.
4106// It is terrible that this is the best way to accomplish this.
4107namespace {
4108
4109class Private {};
4110
4111} // namespace
4112
4114
4115static CachedProperties computeCachedProperties(const Type *T) {
4116 switch (T->getTypeClass()) {
4117#define TYPE(Class,Base)
4118#define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
4119#include "clang/AST/TypeNodes.inc"
4120 llvm_unreachable("didn't expect a non-canonical type here");
4121
4122#define TYPE(Class,Base)
4123#define DEPENDENT_TYPE(Class,Base) case Type::Class:
4124#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
4125#include "clang/AST/TypeNodes.inc"
4126 // Treat instantiation-dependent types as external.
4127 if (!T->isInstantiationDependentType()) T->dump();
4128 assert(T->isInstantiationDependentType());
4129 return CachedProperties(ExternalLinkage, false);
4130
4131 case Type::Auto:
4132 case Type::DeducedTemplateSpecialization:
4133 // Give non-deduced 'auto' types external linkage. We should only see them
4134 // here in error recovery.
4135 return CachedProperties(ExternalLinkage, false);
4136
4137 case Type::BitInt:
4138 case Type::Builtin:
4139 // C++ [basic.link]p8:
4140 // A type is said to have linkage if and only if:
4141 // - it is a fundamental type (3.9.1); or
4142 return CachedProperties(ExternalLinkage, false);
4143
4144 case Type::Record:
4145 case Type::Enum: {
4146 const TagDecl *Tag = cast<TagType>(T)->getDecl();
4147
4148 // C++ [basic.link]p8:
4149 // - it is a class or enumeration type that is named (or has a name
4150 // for linkage purposes (7.1.3)) and the name has linkage; or
4151 // - it is a specialization of a class template (14); or
4152 Linkage L = Tag->getLinkageInternal();
4153 bool IsLocalOrUnnamed =
4155 !Tag->hasNameForLinkage();
4156 return CachedProperties(L, IsLocalOrUnnamed);
4157 }
4158
4159 // C++ [basic.link]p8:
4160 // - it is a compound type (3.9.2) other than a class or enumeration,
4161 // compounded exclusively from types that have linkage; or
4162 case Type::Complex:
4163 return Cache::get(cast<ComplexType>(T)->getElementType());
4164 case Type::Pointer:
4165 return Cache::get(cast<PointerType>(T)->getPointeeType());
4166 case Type::BlockPointer:
4167 return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
4168 case Type::LValueReference:
4169 case Type::RValueReference:
4170 return Cache::get(cast<ReferenceType>(T)->getPointeeType());
4171 case Type::MemberPointer: {
4172 const auto *MPT = cast<MemberPointerType>(T);
4173 return merge(Cache::get(MPT->getClass()),
4174 Cache::get(MPT->getPointeeType()));
4175 }
4176 case Type::ConstantArray:
4177 case Type::IncompleteArray:
4178 case Type::VariableArray:
4179 return Cache::get(cast<ArrayType>(T)->getElementType());
4180 case Type::Vector:
4181 case Type::ExtVector:
4182 return Cache::get(cast<VectorType>(T)->getElementType());
4183 case Type::ConstantMatrix:
4184 return Cache::get(cast<ConstantMatrixType>(T)->getElementType());
4185 case Type::FunctionNoProto:
4186 return Cache::get(cast<FunctionType>(T)->getReturnType());
4187 case Type::FunctionProto: {
4188 const auto *FPT = cast<FunctionProtoType>(T);
4189 CachedProperties result = Cache::get(FPT->getReturnType());
4190 for (const auto &ai : FPT->param_types())
4191 result = merge(result, Cache::get(ai));
4192 return result;
4193 }
4194 case Type::ObjCInterface: {
4195 Linkage L = cast<ObjCInterfaceType>(T)->getDecl()->getLinkageInternal();
4196 return CachedProperties(L, false);
4197 }
4198 case Type::ObjCObject:
4199 return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
4200 case Type::ObjCObjectPointer:
4201 return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
4202 case Type::Atomic:
4203 return Cache::get(cast<AtomicType>(T)->getValueType());
4204 case Type::Pipe:
4205 return Cache::get(cast<PipeType>(T)->getElementType());
4206 }
4207
4208 llvm_unreachable("unhandled type class");
4209}
4210
4211/// Determine the linkage of this type.
4213 Cache::ensure(this);
4214 return TypeBits.getLinkage();
4215}
4216
4218 Cache::ensure(this);
4219 return TypeBits.hasLocalOrUnnamedType();
4220}
4221
4223 switch (T->getTypeClass()) {
4224#define TYPE(Class,Base)
4225#define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
4226#include "clang/AST/TypeNodes.inc"
4227 llvm_unreachable("didn't expect a non-canonical type here");
4228
4229#define TYPE(Class,Base)
4230#define DEPENDENT_TYPE(Class,Base) case Type::Class:
4231#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
4232#include "clang/AST/TypeNodes.inc"
4233 // Treat instantiation-dependent types as external.
4234 assert(T->isInstantiationDependentType());
4235 return LinkageInfo::external();
4236
4237 case Type::BitInt:
4238 case Type::Builtin:
4239 return LinkageInfo::external();
4240
4241 case Type::Auto:
4242 case Type::DeducedTemplateSpecialization:
4243 return LinkageInfo::external();
4244
4245 case Type::Record:
4246 case Type::Enum:
4247 return getDeclLinkageAndVisibility(cast<TagType>(T)->getDecl());
4248
4249 case Type::Complex:
4250 return computeTypeLinkageInfo(cast<ComplexType>(T)->getElementType());
4251 case Type::Pointer:
4252 return computeTypeLinkageInfo(cast<PointerType>(T)->getPointeeType());
4253 case Type::BlockPointer:
4254 return computeTypeLinkageInfo(cast<BlockPointerType>(T)->getPointeeType());
4255 case Type::LValueReference:
4256 case Type::RValueReference:
4257 return computeTypeLinkageInfo(cast<ReferenceType>(T)->getPointeeType());
4258 case Type::MemberPointer: {
4259 const auto *MPT = cast<MemberPointerType>(T);
4260 LinkageInfo LV = computeTypeLinkageInfo(MPT->getClass());
4261 LV.merge(computeTypeLinkageInfo(MPT->getPointeeType()));
4262 return LV;
4263 }
4264 case Type::ConstantArray:
4265 case Type::IncompleteArray:
4266 case Type::VariableArray:
4267 return computeTypeLinkageInfo(cast<ArrayType>(T)->getElementType());
4268 case Type::Vector:
4269 case Type::ExtVector:
4270 return computeTypeLinkageInfo(cast<VectorType>(T)->getElementType());
4271 case Type::ConstantMatrix:
4273 cast<ConstantMatrixType>(T)->getElementType());
4274 case Type::FunctionNoProto:
4275 return computeTypeLinkageInfo(cast<FunctionType>(T)->getReturnType());
4276 case Type::FunctionProto: {
4277 const auto *FPT = cast<FunctionProtoType>(T);
4278 LinkageInfo LV = computeTypeLinkageInfo(FPT->getReturnType());
4279 for (const auto &ai : FPT->param_types())
4281 return LV;
4282 }
4283 case Type::ObjCInterface:
4284 return getDeclLinkageAndVisibility(cast<ObjCInterfaceType>(T)->getDecl());
4285 case Type::ObjCObject:
4286 return computeTypeLinkageInfo(cast<ObjCObjectType>(T)->getBaseType());
4287 case Type::ObjCObjectPointer:
4289 cast<ObjCObjectPointerType>(T)->getPointeeType());
4290 case Type::Atomic:
4291 return computeTypeLinkageInfo(cast<AtomicType>(T)->getValueType());
4292 case Type::Pipe:
4293 return computeTypeLinkageInfo(cast<PipeType>(T)->getElementType());
4294 }
4295
4296 llvm_unreachable("unhandled type class");
4297}
4298
4300 if (!TypeBits.isCacheValid())
4301 return true;
4302
4305 .getLinkage();
4306 return L == TypeBits.getLinkage();
4307}
4308
4310 if (!T->isCanonicalUnqualified())
4312
4314 assert(LV.getLinkage() == T->getLinkage());
4315 return LV;
4316}
4317
4320}
4321
4322std::optional<NullabilityKind> Type::getNullability() const {
4323 QualType Type(this, 0);
4324 while (const auto *AT = Type->getAs<AttributedType>()) {
4325 // Check whether this is an attributed type with nullability
4326 // information.
4327 if (auto Nullability = AT->getImmediateNullability())
4328 return Nullability;
4329
4330 Type = AT->getEquivalentType();
4331 }
4332 return std::nullopt;
4333}
4334
4335bool Type::canHaveNullability(bool ResultIfUnknown) const {
4337
4338 switch (type->getTypeClass()) {
4339 // We'll only see canonical types here.
4340#define NON_CANONICAL_TYPE(Class, Parent) \
4341 case Type::Class: \
4342 llvm_unreachable("non-canonical type");
4343#define TYPE(Class, Parent)
4344#include "clang/AST/TypeNodes.inc"
4345
4346 // Pointer types.
4347 case Type::Pointer:
4348 case Type::BlockPointer:
4349 case Type::MemberPointer:
4350 case Type::ObjCObjectPointer:
4351 return true;
4352
4353 // Dependent types that could instantiate to pointer types.
4354 case Type::UnresolvedUsing:
4355 case Type::TypeOfExpr:
4356 case Type::TypeOf:
4357 case Type::Decltype:
4358 case Type::UnaryTransform:
4359 case Type::TemplateTypeParm:
4360 case Type::SubstTemplateTypeParmPack:
4361 case Type::DependentName:
4362 case Type::DependentTemplateSpecialization:
4363 case Type::Auto:
4364 return ResultIfUnknown;
4365
4366 // Dependent template specializations can instantiate to pointer
4367 // types unless they're known to be specializations of a class
4368 // template.
4369 case Type::TemplateSpecialization:
4370 if (TemplateDecl *templateDecl
4371 = cast<TemplateSpecializationType>(type.getTypePtr())
4372 ->getTemplateName().getAsTemplateDecl()) {
4373 if (isa<ClassTemplateDecl>(templateDecl))
4374 return false;
4375 }
4376 return ResultIfUnknown;
4377
4378 case Type::Builtin:
4379 switch (cast<BuiltinType>(type.getTypePtr())->getKind()) {
4380 // Signed, unsigned, and floating-point types cannot have nullability.
4381#define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
4382#define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
4383#define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
4384#define BUILTIN_TYPE(Id, SingletonId)
4385#include "clang/AST/BuiltinTypes.def"
4386 return false;
4387
4388 // Dependent types that could instantiate to a pointer type.
4389 case BuiltinType::Dependent:
4390 case BuiltinType::Overload:
4391 case BuiltinType::BoundMember:
4392 case BuiltinType::PseudoObject:
4393 case BuiltinType::UnknownAny:
4394 case BuiltinType::ARCUnbridgedCast:
4395 return ResultIfUnknown;
4396
4397 case BuiltinType::Void:
4398 case BuiltinType::ObjCId:
4399 case BuiltinType::ObjCClass:
4400 case BuiltinType::ObjCSel:
4401#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
4402 case BuiltinType::Id:
4403#include "clang/Basic/OpenCLImageTypes.def"
4404#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
4405 case BuiltinType::Id:
4406#include "clang/Basic/OpenCLExtensionTypes.def"
4407 case BuiltinType::OCLSampler:
4408 case BuiltinType::OCLEvent:
4409 case BuiltinType::OCLClkEvent:
4410 case BuiltinType::OCLQueue:
4411 case BuiltinType::OCLReserveID:
4412#define SVE_TYPE(Name, Id, SingletonId) \
4413 case BuiltinType::Id:
4414#include "clang/Basic/AArch64SVEACLETypes.def"
4415#define PPC_VECTOR_TYPE(Name, Id, Size) \
4416 case BuiltinType::Id:
4417#include "clang/Basic/PPCTypes.def"
4418#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
4419#include "clang/Basic/RISCVVTypes.def"
4420#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
4421#include "clang/Basic/WebAssemblyReferenceTypes.def"
4422 case BuiltinType::BuiltinFn:
4423 case BuiltinType::NullPtr:
4424 case BuiltinType::IncompleteMatrixIdx:
4425 case BuiltinType::OMPArraySection:
4426 case BuiltinType::OMPArrayShaping:
4427 case BuiltinType::OMPIterator:
4428 return false;
4429 }
4430 llvm_unreachable("unknown builtin type");
4431
4432 // Non-pointer types.
4433 case Type::Complex:
4434 case Type::LValueReference:
4435 case Type::RValueReference:
4436 case Type::ConstantArray:
4437 case Type::IncompleteArray:
4438 case Type::VariableArray:
4439 case Type::DependentSizedArray:
4440 case Type::DependentVector:
4441 case Type::DependentSizedExtVector:
4442 case Type::Vector:
4443 case Type::ExtVector:
4444 case Type::ConstantMatrix:
4445 case Type::DependentSizedMatrix:
4446 case Type::DependentAddressSpace:
4447 case Type::FunctionProto:
4448 case Type::FunctionNoProto:
4449 case Type::Record:
4450 case Type::DeducedTemplateSpecialization:
4451 case Type::Enum:
4452 case Type::InjectedClassName:
4453 case Type::PackExpansion:
4454 case Type::ObjCObject:
4455 case Type::ObjCInterface:
4456 case Type::Atomic:
4457 case Type::Pipe:
4458 case Type::BitInt:
4459 case Type::DependentBitInt:
4460 return false;
4461 }
4462 llvm_unreachable("bad type kind!");
4463}
4464
4465std::optional<NullabilityKind> AttributedType::getImmediateNullability() const {
4466 if (getAttrKind() == attr::TypeNonNull)
4468 if (getAttrKind() == attr::TypeNullable)
4470 if (getAttrKind() == attr::TypeNullUnspecified)
4472 if (getAttrKind() == attr::TypeNullableResult)
4474 return std::nullopt;
4475}
4476
4477std::optional<NullabilityKind>
4479 QualType AttrTy = T;
4480 if (auto MacroTy = dyn_cast<MacroQualifiedType>(T))
4481 AttrTy = MacroTy->getUnderlyingType();
4482
4483 if (auto attributed = dyn_cast<AttributedType>(AttrTy)) {
4484 if (auto nullability = attributed->getImmediateNullability()) {
4485 T = attributed->getModifiedType();
4486 return nullability;
4487 }
4488 }
4489
4490 return std::nullopt;
4491}
4492
4494 const auto *objcPtr = getAs<ObjCObjectPointerType>();
4495 if (!objcPtr)
4496 return false;
4497
4498 if (objcPtr->isObjCIdType()) {
4499 // id is always okay.
4500 return true;
4501 }
4502
4503 // Blocks are NSObjects.
4504 if (ObjCInterfaceDecl *iface = objcPtr->getInterfaceDecl()) {
4505 if (iface->getIdentifier() != ctx.getNSObjectName())
4506 return false;
4507
4508 // Continue to check qualifiers, below.
4509 } else if (objcPtr->isObjCQualifiedIdType()) {
4510 // Continue to check qualifiers, below.
4511 } else {
4512 return false;
4513 }
4514
4515 // Check protocol qualifiers.
4516 for (ObjCProtocolDecl *proto : objcPtr->quals()) {
4517 // Blocks conform to NSObject and NSCopying.
4518 if (proto->getIdentifier() != ctx.getNSObjectName() &&
4519 proto->getIdentifier() != ctx.getNSCopyingName())
4520 return false;
4521 }
4522
4523 return true;
4524}
4525
4530}
4531
4533 assert(isObjCLifetimeType() &&
4534 "cannot query implicit lifetime for non-inferrable type");
4535
4536 const Type *canon = getCanonicalTypeInternal().getTypePtr();
4537
4538 // Walk down to the base type. We don't care about qualifiers for this.
4539 while (const auto *array = dyn_cast<ArrayType>(canon))
4540 canon = array->getElementType().getTypePtr();
4541
4542 if (const auto *opt = dyn_cast<ObjCObjectPointerType>(canon)) {
4543 // Class and Class<Protocol> don't require retention.
4544 if (opt->getObjectType()->isObjCClass())
4545 return true;
4546 }
4547
4548 return false;
4549}
4550
4552 if (const auto *typedefType = getAs<TypedefType>())
4553 return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>();
4554 return false;
4555}
4556
4558 if (const auto *typedefType = getAs<TypedefType>())
4559 return typedefType->getDecl()->hasAttr<ObjCIndependentClassAttr>();
4560 return false;
4561}
4562
4564 return isObjCObjectPointerType() ||
4567}
4568
4570 if (isObjCLifetimeType())
4571 return true;
4572 if (const auto *OPT = getAs<PointerType>())
4573 return OPT->getPointeeType()->isObjCIndirectLifetimeType();
4574 if (const auto *Ref = getAs<ReferenceType>())
4575 return Ref->getPointeeType()->isObjCIndirectLifetimeType();
4576 if (const auto *MemPtr = getAs<MemberPointerType>())
4577 return MemPtr->getPointeeType()->isObjCIndirectLifetimeType();
4578 return false;
4579}
4580
4581/// Returns true if objects of this type have lifetime semantics under
4582/// ARC.
4584 const Type *type = this;
4585 while (const ArrayType *array = type->getAsArrayTypeUnsafe())
4586 type = array->getElementType().getTypePtr();
4587 return type->isObjCRetainableType();
4588}
4589
4590/// Determine whether the given type T is a "bridgable" Objective-C type,
4591/// which is either an Objective-C object pointer type or an
4594}
4595
4596/// Determine whether the given type T is a "bridgeable" C type.
4598 const auto *Pointer = getAs<PointerType>();
4599 if (!Pointer)
4600 return false;
4601
4602 QualType Pointee = Pointer->getPointeeType();
4603 return Pointee->isVoidType() || Pointee->isRecordType();
4604}
4605
4606/// Check if the specified type is the CUDA device builtin surface type.
4608 if (const auto *RT = getAs<RecordType>())
4609 return RT->getDecl()->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>();
4610 return false;
4611}
4612
4613/// Check if the specified type is the CUDA device builtin texture type.
4615 if (const auto *RT = getAs<RecordType>())
4616 return RT->getDecl()->hasAttr<CUDADeviceBuiltinTextureTypeAttr>();
4617 return false;
4618}
4619
4621 if (!isVariablyModifiedType()) return false;
4622
4623 if (const auto *ptr = getAs<PointerType>())
4624 return ptr->getPointeeType()->hasSizedVLAType();
4625 if (const auto *ref = getAs<ReferenceType>())
4626 return ref->getPointeeType()->hasSizedVLAType();
4627 if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
4628 if (isa<VariableArrayType>(arr) &&
4629 cast<VariableArrayType>(arr)->getSizeExpr())
4630 return true;
4631
4632 return arr->getElementType()->hasSizedVLAType();
4633 }
4634
4635 return false;
4636}
4637
4638QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
4639 switch (type.getObjCLifetime()) {
4643 break;
4644
4648 return DK_objc_weak_lifetime;
4649 }
4650
4651 if (const auto *RT =
4652 type->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
4653 const RecordDecl *RD = RT->getDecl();
4654 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4655 /// Check if this is a C++ object with a non-trivial destructor.
4656 if (CXXRD->hasDefinition() && !CXXRD->hasTrivialDestructor())
4657 return DK_cxx_destructor;
4658 } else {
4659 /// Check if this is a C struct that is non-trivial to destroy or an array
4660 /// that contains such a struct.
4663 }
4664 }
4665
4666 return DK_none;
4667}
4668
4671}
4672
4674 llvm::APSInt Val, unsigned Scale) {
4675 llvm::FixedPointSemantics FXSema(Val.getBitWidth(), Scale, Val.isSigned(),
4676 /*IsSaturated=*/false,
4677 /*HasUnsignedPadding=*/false);
4678 llvm::APFixedPoint(Val, FXSema).toString(Str);
4679}
4680
4681AutoType::AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
4682 TypeDependence ExtraDependence, QualType Canon,
4683 ConceptDecl *TypeConstraintConcept,
4684 ArrayRef<TemplateArgument> TypeConstraintArgs)
4685 : DeducedType(Auto, DeducedAsType, ExtraDependence, Canon) {
4686 AutoTypeBits.Keyword = (unsigned)Keyword;
4687 AutoTypeBits.NumArgs = TypeConstraintArgs.size();
4688 this->TypeConstraintConcept = TypeConstraintConcept;
4689 assert(TypeConstraintConcept || AutoTypeBits.NumArgs == 0);
4690 if (TypeConstraintConcept) {
4691 auto *ArgBuffer =
4692 const_cast<TemplateArgument *>(getTypeConstraintArguments().data());
4693 for (const TemplateArgument &Arg : TypeConstraintArgs) {
4694 // If we have a deduced type, our constraints never affect semantic
4695 // dependence. Prior to deduction, however, our canonical type depends
4696 // on the template arguments, so we are a dependent type if any of them
4697 // is dependent.
4698 TypeDependence ArgDependence = toTypeDependence(Arg.getDependence());
4699 if (!DeducedAsType.isNull())
4700 ArgDependence = toSyntacticDependence(ArgDependence);
4701 addDependence(ArgDependence);
4702
4703 new (ArgBuffer++) TemplateArgument(Arg);
4704 }
4705 }
4706}
4707
4708void AutoType::Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4709 QualType Deduced, AutoTypeKeyword Keyword,
4710 bool IsDependent, ConceptDecl *CD,
4711 ArrayRef<TemplateArgument> Arguments) {
4712 ID.AddPointer(Deduced.getAsOpaquePtr());
4713 ID.AddInteger((unsigned)Keyword);
4714 ID.AddBoolean(IsDependent);
4715 ID.AddPointer(CD);
4716 for (const TemplateArgument &Arg : Arguments)
4717 Arg.Profile(ID, Context);
4718}
4719
4720void AutoType::Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
4721 Profile(ID, Context, getDeducedType(), getKeyword(), isDependentType(),
4723}
Defines the clang::ASTContext interface.
StringRef P
Provides definitions for the various language-specific address spaces.
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.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
static bool isRecordType(QualType T)
Defines various enumerations that describe declaration and type specifiers.
Defines the TargetCXXABI class, which abstracts details of the C++ ABI that we're targeting.
static TagDecl * getInterestingTagDecl(TagDecl *decl)
Definition: Type.cpp:3701
#define SUGARED_TYPE_CLASS(Class)
Definition: Type.cpp:879
static bool HasNonDeletedDefaultedEqualityComparison(const CXXRecordDecl *Decl)
Definition: Type.cpp:2640
static const TemplateTypeParmDecl * getReplacedParameter(Decl *D, unsigned Index)
Definition: Type.cpp:3816
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:508
#define TRIVIAL_TYPE_CLASS(Class)
Definition: Type.cpp:877
static CachedProperties computeCachedProperties(const Type *T)
Definition: Type.cpp:4115
C Language Family Type Representation.
SourceLocation Begin
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:182
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 getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType) const
QualType getIncompleteArrayType(QualType EltTy, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a unique reference to the type for an incomplete array of the specified element type.
QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent, bool IsPack=false, ConceptDecl *TypeConstraintConcept=nullptr, ArrayRef< TemplateArgument > TypeConstraintArgs={}) const
C++11 deduced auto 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 getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:761
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.
bool hasUniqueObjectRepresentations(QualType Ty, bool CheckIfTriviallyCopyable=true) const
Return true if the specified type has unique object representations according to (C++17 [meta....
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
CanQualType ObjCBuiltinIdTy
Definition: ASTContext.h:1108
IdentifierInfo * getNSObjectName() const
Retrieve the identifier 'NSObject'.
Definition: ASTContext.h:1868
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType getVariableArrayType(QualType EltTy, Expr *NumElts, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals, SourceRange Brackets) const
Return a non-unique reference to the type for a variable array of the specified element type.
QualType getAdjustedType(QualType Orig, QualType New) const
Return the uniqued reference to a type adjusted from the original type to a new type.
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorType::VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2122
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
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.
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.
Definition: ASTContext.h:2296
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType UnsignedCharTy
Definition: ASTContext.h:1087
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1539
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:743
QualType getSubstTemplateTypeParmType(QualType Replacement, Decl *AssociatedDecl, unsigned Index, std::optional< unsigned > PackIndex) const
Retrieve a substitution-result 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'.
Definition: ASTContext.h:1877
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition: Type.h:2829
QualType getAdjustedType() const
Definition: Type.h:2843
QualType getOriginalType() const
Definition: Type.h:2842
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3043
ArraySizeModifier
Capture whether this is a normal array (e.g.
Definition: Type.h:3049
ArraySizeModifier getSizeModifier() const
Definition: Type.h:3066
QualType getElementType() const
Definition: Type.h:3064
ArrayType(TypeClass tc, QualType et, QualType can, ArraySizeModifier sm, unsigned tq, const Expr *sz=nullptr)
Definition: Type.cpp:120
unsigned getIndexTypeCVRQualifiers() const
Definition: Type.h:3074
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:6493
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:4905
QualType getModifiedType() const
Definition: Type.h:4927
bool isCallingConv() const
Definition: Type.cpp:3781
std::optional< NullabilityKind > getImmediateNullability() const
Definition: Type.cpp:4465
static std::optional< NullabilityKind > stripOuterNullability(QualType &T)
Strip off the top-level nullability annotation on the given type, if it's there.
Definition: Type.cpp:4478
bool isMSTypeSpec() const
Definition: Type.cpp:3764
QualType getEquivalentType() const
Definition: Type.h:4928
Kind getAttrKind() const
Definition: Type.h:4923
bool isWebAssemblyFuncrefSpec() const
Definition: Type.cpp:3777
bool isQualifier() const
Does this attribute behave like a type qualifier?
Definition: Type.cpp:3740
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:5282
ArrayRef< TemplateArgument > getTypeConstraintArguments() const
Definition: Type.h:5292
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.cpp:4720
ConceptDecl * getTypeConstraintConcept() const
Definition: Type.h:5297
AutoTypeKeyword getKeyword() const
Definition: Type.h:5313
BitIntType(bool isUnsigned, unsigned NumBits)
Definition: Type.cpp:343
Pointer to a block type.
Definition: Type.h:2880
QualType getPointeeType() const
Definition: Type.h:2892
This class is used for builtin types like 'int'.
Definition: Type.h:2646
Kind getKind() const
Definition: Type.h:2684
StringRef getName(const PrintingPolicy &Policy) const
Definition: Type.cpp:3113
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
Represents a C++ struct/union/class.
Definition: DeclCXX.h:254
bool mayBeNonDynamicClass() const
Definition: DeclCXX.h:584
CXXRecordDecl * getMostRecentNonInjectedDecl()
Definition: DeclCXX.h:537
bool mayBeDynamicClass() const
Definition: DeclCXX.h:578
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
Complex values, per C99 6.2.5p11.
Definition: Type.h:2747
QualType getElementType() const
Definition: Type.h:2757
Declaration of a C++20 concept.
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3091
const llvm::APInt & getSize() const
Definition: Type.h:3112
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:143
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:178
const Expr * getSizeExpr() const
Definition: Type.h:3113
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.h:3131
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:3618
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: Type.h:3639
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: Type.h:3636
ConstantMatrixType(QualType MatrixElementType, unsigned NRows, unsigned NColumns, QualType CanonElementType)
Definition: Type.cpp:305
Represents a pointer type decayed from an array or function type.
Definition: Type.h:2863
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1402
ASTContext & getParentASTContext() const
Definition: DeclBase.h:1971
bool isFunctionOrMethod() const
Definition: DeclBase.h:1994
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:83
bool isInStdNamespace() const
Definition: DeclBase.cpp:404
bool isFunctionOrFunctionTemplate() const
Whether this declaration is a function or function template.
Definition: DeclBase.h:1087
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:429
DeclContext * getDeclContext()
Definition: DeclBase.h:441
bool hasAttr() const
Definition: DeclBase.h:560
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:946
Represents the type decltype(expr) (C++11).
Definition: Type.h:4724
QualType desugar() const
Remove a single level of sugar.
Definition: Type.cpp:3669
bool isSugared() const
Returns whether this type directly provides sugar.
Definition: Type.cpp:3667
DecltypeType(Expr *E, QualType underlyingType, QualType can=QualType())
Definition: Type.cpp:3655
QualType getUnderlyingType() const
Definition: Type.h:4735
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:5248
QualType getDeducedType() const
Get the type deduced for this placeholder type, or null if it has not been deduced.
Definition: Type.h:5269
bool isDeduced() const
Definition: Type.h:5270
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3331
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:6592
Expr * getNumBitsExpr() const
Definition: Type.cpp:357
bool isUnsigned() const
Definition: Type.cpp:353
DependentBitIntType(const ASTContext &Context, bool IsUnsigned, Expr *NumBits)
Definition: Type.cpp:347
DependentDecltypeType(const ASTContext &Context, Expr *E)
Definition: Type.cpp:3676
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4758
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3286
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3349
QualType getElementType() const
Definition: Type.h:3365
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3375
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition: Type.h:3677
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3699
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context)
Definition: Type.h:5835
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:4677
DependentUnaryTransformType(const ASTContext &C, QualType BaseType, UTTKind UKind)
Definition: Type.cpp:3690
void Profile(llvm::FoldingSetNodeID &ID)
Definition: Type.h:3498
Represents a type that was referred to using an elaborated type keyword, e.g., struct S,...
Definition: Type.h:5674
QualType getNamedType() const
Retrieve the type named by the qualified-id.
Definition: Type.h:5712
Represents an enum.
Definition: Decl.h:3734
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:3953
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:4876
This represents one expression.
Definition: Expr.h:110
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:186
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition: Expr.h:215
QualType getType() const
Definition: Expr.h:142
ExtVectorType - Extended vector type.
Definition: Type.h:3513
Represents a member of a struct/union/class.
Definition: Decl.h:2945
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition: DeclFriend.h:54
Represents a function declaration or definition.
Definition: Decl.h:1917
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition: Type.h:4012
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4056
bool hasDependentExceptionSpec() const
Return whether this function has a dependent exception spec.
Definition: Type.cpp:3457
param_type_iterator param_type_begin() const
Definition: Type.h:4419
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:4286
bool isTemplateVariadic() const
Determines whether this function prototype contains a parameter pack at the end.
Definition: Type.cpp:3511
unsigned getNumParams() const
Definition: Type.h:4261
bool hasTrailingReturn() const
Whether this function prototype has a trailing return type.
Definition: Type.h:4399
QualType getParamType(unsigned i) const
Definition: Type.h:4263
QualType getExceptionType(unsigned i) const
Return the ith exception type, where 0 <= i < getNumExceptions().
Definition: Type.h:4337
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx)
Definition: Type.cpp:3571
unsigned getNumExceptions() const
Return the number of types in the exception specification.
Definition: Type.h:4329
CanThrowResult canThrow() const
Determine whether this function type has a non-throwing exception specification.
Definition: Type.cpp:3478
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4272
Expr * getNoexceptExpr() const
Return the expression inside noexcept(expression), or a null pointer if there is none (because the ex...
Definition: Type.h:4344
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4268
ArrayRef< QualType > exceptions() const
Definition: Type.h:4429
bool hasInstantiationDependentExceptionSpec() const
Return whether this function has an instantiation-dependent exception spec.
Definition: Type.cpp:3469
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3709
ExtInfo getExtInfo() const
Definition: Type.h:3986
static StringRef getNameForCallConv(CallingConv CC)
Definition: Type.cpp:3312
QualType getReturnType() const
Definition: Type.h:3974
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.
Represents a C array with an unspecified size.
Definition: Type.h:3149
CXXRecordDecl * getDecl() const
Definition: Type.cpp:3808
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2955
LinkageInfo computeTypeLinkageInfo(const Type *T)
Definition: Type.cpp:4222
LinkageInfo getTypeLinkageAndVisibility(const Type *T)
Definition: Type.cpp:4309
LinkageInfo getDeclLinkageAndVisibility(const NamedDecl *D)
Definition: Decl.cpp:1577
static LinkageInfo external()
Definition: Visibility.h:67
Linkage getLinkage() const
Definition: Visibility.h:83
void merge(LinkageInfo other)
Merge both linkage and visibility.
Definition: Visibility.h:132
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition: Type.h:4605
QualType desugar() const
Definition: Type.cpp:3608
QualType getModifiedType() const
Return this attributed type's modified type with no qualifiers attached to it.
Definition: Type.cpp:3610
QualType getUnderlyingType() const
Definition: Type.h:4621
const IdentifierInfo * getMacroIdentifier() const
Definition: Type.h:4620
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition: Type.h:3582
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition: Type.h:3596
MatrixType(QualType ElementTy, QualType CanonElementTy)
QualType ElementType
The element type of the matrix.
Definition: Type.h:3587
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2991
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Definition: Type.cpp:4669
QualType getPointeeType() const
Definition: Type.h:3007
const Type * getClass() const
Definition: Type.h:3021
This represents a decl that may have a name.
Definition: Decl.h:247
Linkage getLinkageInternal() const
Determine what kind of linkage this entity has.
Definition: Decl.cpp:1152
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:268
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2312
ObjCInterfaceDecl * getClassInterface()
Definition: DeclObjC.h:2357
ObjCTypeParamList * getTypeParamList() const
Retrieve the type parameter list associated with this category or extension.
Definition: DeclObjC.h:2362
Represents an ObjC class declaration.
Definition: DeclObjC.h:1147
ObjCTypeParamList * getTypeParamList() const
Retrieve the type parameters of this class.
Definition: DeclObjC.cpp:321
bool hasDefinition() const
Determine whether this class has been defined.
Definition: DeclObjC.h:1516
const ObjCObjectType * getSuperClassType() const
Retrieve the superclass type.
Definition: DeclObjC.h:1553
ObjCInterfaceDecl * getDefinition()
Retrieve the definition of this class, or NULL if this class has been forward-declared (with @class) ...
Definition: DeclObjC.h:1530
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:6256
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition: Type.cpp:829
Represents a pointer to an Objective C object.
Definition: Type.h:6312
const ObjCObjectPointerType * stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const
Strip off the Objective-C "kindof" type and (with it) any protocol qualifiers.
Definition: Type.cpp:836
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:6349
QualType getSuperClassType() const
Retrieve the type of the superclass of this object pointer type.
Definition: Type.cpp:1725
bool qual_empty() const
Definition: Type.h:6441