1 //===- Type.cpp - Type representation and manipulation --------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements type-related functionality.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/Type.h"
14 #include "Linkage.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/CharUnits.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclBase.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclFriend.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/DependenceFlags.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/NestedNameSpecifier.h"
27 #include "clang/AST/NonTrivialTypeVisitor.h"
28 #include "clang/AST/PrettyPrinter.h"
29 #include "clang/AST/TemplateBase.h"
30 #include "clang/AST/TemplateName.h"
31 #include "clang/AST/TypeVisitor.h"
32 #include "clang/Basic/AddressSpaces.h"
33 #include "clang/Basic/ExceptionSpecificationType.h"
34 #include "clang/Basic/IdentifierTable.h"
35 #include "clang/Basic/LLVM.h"
36 #include "clang/Basic/LangOptions.h"
37 #include "clang/Basic/Linkage.h"
38 #include "clang/Basic/Specifiers.h"
39 #include "clang/Basic/TargetCXXABI.h"
40 #include "clang/Basic/TargetInfo.h"
41 #include "clang/Basic/Visibility.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 
58 using namespace clang;
59 
60 bool Qualifiers::isStrictSupersetOf(Qualifiers Other) const {
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 
75 const IdentifierInfo* QualType::getBaseTypeIdentifier() const {
76   const Type* ty = getTypePtr();
77   NamedDecl *ND = nullptr;
78   if (ty->isPointerType() || ty->isReferenceType())
79     return ty->getPointeeType().getBaseTypeIdentifier();
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 
95 bool QualType::mayBeDynamicClass() const {
96   const auto *ClassDecl = getTypePtr()->getPointeeCXXRecordDecl();
97   return ClassDecl && ClassDecl->mayBeDynamicClass();
98 }
99 
100 bool QualType::mayBeNotDynamicClass() const {
101   const auto *ClassDecl = getTypePtr()->getPointeeCXXRecordDecl();
102   return !ClassDecl || ClassDecl->mayBeNonDynamicClass();
103 }
104 
105 bool 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 
112   return T.getAddressSpace() == LangAS::opencl_constant;
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,
120 ArrayType::ArrayType(TypeClass tc, QualType et, QualType can,
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 
143 unsigned ConstantArrayType::getNumAddressingBits(const ASTContext &Context,
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 
178 unsigned ConstantArrayType::getMaxSizeBits(const ASTContext &Context) {
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 
190 void 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 
204 DependentSizedArrayType::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 
212 void 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 
224 DependentVectorType::DependentVectorType(const ASTContext &Context,
225                                          QualType ElementType,
226                                          QualType CanonType, Expr *SizeExpr,
227                                          SourceLocation Loc,
228                                          VectorType::VectorKind VecKind)
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 
238 void 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 
247 DependentSizedExtVectorType::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 
258 void
259 DependentSizedExtVectorType::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 
266 DependentAddressSpaceType::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 
279 void 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 
287 MatrixType::MatrixType(TypeClass tc, QualType matrixType, QualType canonType,
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
301                             : TypeDependence::None))
302                     : matrixType->getDependence())),
303       ElementType(matrixType) {}
304 
305 ConstantMatrixType::ConstantMatrixType(QualType matrixType, unsigned nRows,
306                                        unsigned nColumns, QualType canonType)
307     : ConstantMatrixType(ConstantMatrix, matrixType, nRows, nColumns,
308                          canonType) {}
309 
310 ConstantMatrixType::ConstantMatrixType(TypeClass tc, QualType matrixType,
311                                        unsigned nRows, unsigned nColumns,
312                                        QualType canonType)
313     : MatrixType(tc, matrixType, canonType), NumRows(nRows),
314       NumColumns(nColumns) {}
315 
316 DependentSizedMatrixType::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 
323 void 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 
332 VectorType::VectorType(QualType vecType, unsigned nElements, QualType canonType,
333                        VectorKind vecKind)
334     : VectorType(Vector, vecType, nElements, canonType, vecKind) {}
335 
336 VectorType::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 
343 BitIntType::BitIntType(bool IsUnsigned, unsigned NumBits)
344     : Type(BitInt, QualType{}, TypeDependence::None), IsUnsigned(IsUnsigned),
345       NumBits(NumBits) {}
346 
347 DependentBitIntType::DependentBitIntType(const ASTContext &Context,
348                                          bool IsUnsigned, Expr *NumBitsExpr)
349     : Type(DependentBitInt, QualType{},
350            toTypeDependence(NumBitsExpr->getDependence())),
351       Context(Context), ExprAndUnsigned(NumBitsExpr, IsUnsigned) {}
352 
353 bool DependentBitIntType::isUnsigned() const {
354   return ExprAndUnsigned.getInt();
355 }
356 
357 clang::Expr *DependentBitIntType::getNumBitsExpr() const {
358   return ExprAndUnsigned.getPointer();
359 }
360 
361 void 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.
371 const Type *Type::getArrayElementTypeNoTypeQual() const {
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.
392 QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) {
393   SplitQualType split = getSplitDesugaredType(T);
394   return Context.getQualifiedType(split.Ty, split.Quals);
395 }
396 
397 QualType QualType::getSingleStepDesugaredTypeImpl(QualType type,
398                                                   const ASTContext &Context) {
399   SplitQualType split = type.split();
400   QualType desugar = split.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
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 
424 QualType Type::getLocallyUnqualifiedSingleStepDesugaredType() const {
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 
438 SplitQualType QualType::getSplitDesugaredType(QualType T) {
439   QualifierCollector Qs;
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 
459 SplitQualType 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;
490       quals.addConsistentQualifiers(split.Quals);
491     }
492   }
493 
494  done:
495   return SplitQualType(lastTypeWithQuals, quals);
496 }
497 
498 QualType QualType::IgnoreParens(QualType T) {
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.
508 template<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 
526 template <> const TypedefType *Type::getAs() const {
527   return getAsSugar<TypedefType>(this);
528 }
529 
530 template <> const UsingType *Type::getAs() const {
531   return getAsSugar<UsingType>(this);
532 }
533 
534 template <> const TemplateSpecializationType *Type::getAs() const {
535   return getAsSugar<TemplateSpecializationType>(this);
536 }
537 
538 template <> 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.
545 const Type *Type::getUnqualifiedDesugaredType() const {
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 
563 bool Type::isClassType() const {
564   if (const auto *RT = getAs<RecordType>())
565     return RT->getDecl()->isClass();
566   return false;
567 }
568 
569 bool Type::isStructureType() const {
570   if (const auto *RT = getAs<RecordType>())
571     return RT->getDecl()->isStruct();
572   return false;
573 }
574 
575 bool Type::isObjCBoxableRecordType() const {
576   if (const auto *RT = getAs<RecordType>())
577     return RT->getDecl()->hasAttr<ObjCBoxableAttr>();
578   return false;
579 }
580 
581 bool Type::isInterfaceType() const {
582   if (const auto *RT = getAs<RecordType>())
583     return RT->getDecl()->isInterface();
584   return false;
585 }
586 
587 bool Type::isStructureOrClassType() const {
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 
595 bool Type::isVoidPointerType() const {
596   if (const auto *PT = getAs<PointerType>())
597     return PT->getPointeeType()->isVoidType();
598   return false;
599 }
600 
601 bool Type::isUnionType() const {
602   if (const auto *RT = getAs<RecordType>())
603     return RT->getDecl()->isUnion();
604   return false;
605 }
606 
607 bool Type::isComplexType() const {
608   if (const auto *CT = dyn_cast<ComplexType>(CanonicalType))
609     return CT->getElementType()->isFloatingType();
610   return false;
611 }
612 
613 bool Type::isComplexIntegerType() const {
614   // Check for GCC complex integer extension.
615   return getAsComplexIntegerType();
616 }
617 
618 bool Type::isScopedEnumeralType() const {
619   if (const auto *ET = getAs<EnumType>())
620     return ET->getDecl()->isScoped();
621   return false;
622 }
623 
624 const ComplexType *Type::getAsComplexIntegerType() const {
625   if (const auto *Complex = getAs<ComplexType>())
626     if (Complex->getElementType()->isIntegerType())
627       return Complex;
628   return nullptr;
629 }
630 
631 QualType Type::getPointeeType() const {
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 
647 const RecordType *Type::getAsStructureType() const {
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 
666 const RecordType *Type::getAsUnionType() const {
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 
686 bool Type::isObjCIdOrObjectKindOfType(const ASTContext &ctx,
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)
708             ->getAs<ObjCObjectType>();
709   return true;
710 }
711 
712 bool Type::isObjCClassOrClassKindOfType() const {
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 
729 ObjCTypeParamType::ObjCTypeParamType(const ObjCTypeParamDecl *D, QualType can,
730                                      ArrayRef<ObjCProtocolDecl *> protocols)
731     : Type(ObjCTypeParam, can, toSemanticDependence(can->getDependence())),
732       OTPDecl(const_cast<ObjCTypeParamDecl *>(D)) {
733   initialize(protocols);
734 }
735 
736 ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base,
737                                ArrayRef<QualType> typeArgs,
738                                ArrayRef<ObjCProtocolDecl *> protocols,
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 
758 bool ObjCObjectType::isSpecialized() const {
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 
776 ArrayRef<QualType> ObjCObjectType::getTypeArgs() const {
777   // We have type arguments written on this type.
778   if (isSpecializedAsWritten())
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 
794 bool ObjCObjectType::isKindOfType() const {
795   if (isKindOfTypeAsWritten())
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 
811 QualType ObjCObjectType::stripObjCKindOfTypeAndQuals(
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),
824                                getTypeArgsAsWritten(),
825                                /*protocols=*/{},
826                                /*isKindOf=*/false);
827 }
828 
829 ObjCInterfaceDecl *ObjCInterfaceType::getDecl() const {
830   ObjCInterfaceDecl *Canon = Decl->getCanonicalDecl();
831   if (ObjCInterfaceDecl *Def = Canon->getDefinition())
832     return Def;
833   return Canon;
834 }
835 
836 const ObjCObjectPointerType *ObjCObjectPointerType::stripObjCKindOfTypeAndQuals(
837                                const ASTContext &ctx) const {
838   if (!isKindOfType() && qual_empty())
839     return this;
840 
841   QualType obj = getObjectType()->stripObjCKindOfTypeAndQuals(ctx);
842   return ctx.getObjCObjectPointerType(obj)->castAs<ObjCObjectPointerType>();
843 }
844 
845 namespace {
846 
847 /// Visitor used to perform a simple type transformation that does not change
848 /// the semantics of the type.
849 template <typename Derived>
850 struct 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 
867 public:
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()
932           == T->getPointeeTypeAsWritten().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()
944           == T->getPointeeTypeAsWritten().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(),
971                                     T->getIndexTypeCVRQualifiers());
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(),
984                                     T->getIndexTypeCVRQualifiers(),
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(),
997                                       T->getIndexTypeCVRQualifiers());
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.
1065     FunctionProtoType::ExtProtoInfo info = T->getExtProtoInfo();
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) {
1081         info.ExceptionSpec.Exceptions =
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()
1131           == T->getOriginalType().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)
1142   TRIVIAL_TYPE_CLASS(Enum)
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()
1159           == T->getEquivalentType().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()
1172           == T->getReplacementType().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()
1192           == T->getDeducedType().getAsOpaquePtr())
1193       return QualType(T, 0);
1194 
1195     return Ctx.getAutoType(deducedType, T->getKeyword(),
1196                            T->isDependentType(), /*IsPack=*/false,
1197                            T->getTypeConstraintConcept(),
1198                            T->getTypeConstraintArguments());
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,
1226         llvm::ArrayRef(T->qual_begin(), T->getNumProtocols()),
1227         T->isKindOfTypeAsWritten());
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()
1238           == T->getPointeeType().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 
1260 struct 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,
1268                            ObjCSubstitutionContext context)
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;
1283       SmallVector<ObjCProtocolDecl *, 8> protocolsVec;
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 =
1301           typeParam->getUnderlyingType()->castAs<ObjCObjectPointerType>();
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) {
1378         info.ExceptionSpec.Exceptions =
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.
1406           ArrayRef<ObjCProtocolDecl *> protocols(
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) {
1422         ArrayRef<ObjCProtocolDecl *> protocols(
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 
1470 struct 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 
1489 bool QualType::UseExcessPrecision(const ASTContext &Ctx) {
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.
1524 QualType QualType::substObjCTypeArgs(ASTContext &ctx,
1525                                      ArrayRef<QualType> typeArgs,
1526                                      ObjCSubstitutionContext context) const {
1527   SubstObjCTypeArgsVisitor visitor(ctx, typeArgs, context);
1528   return visitor.recurse(*this);
1529 }
1530 
1531 QualType QualType::substObjCMemberType(QualType objectType,
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 
1540 QualType QualType::stripObjCKindOfType(const ASTContext &constCtx) const {
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 
1547 QualType QualType::getAtomicUnqualifiedType() const {
1548   if (const auto AT = getTypePtr()->getAs<AtomicType>())
1549     return AT->getValueType().getUnqualifiedType();
1550   return getUnqualifiedType();
1551 }
1552 
1553 std::optional<ArrayRef<QualType>>
1554 Type::getObjCSubstitutions(const DeclContext *dc) const {
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, {}, {})
1597                    ->castAs<ObjCObjectType>();
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 
1635 bool Type::acceptsObjCTypeParams() const {
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 
1646 void ObjCObjectType::computeSuperClassTypeSlow() const {
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,
1711                                      ObjCSubstitutionContext::Superclass)
1712       ->castAs<ObjCObjectType>(),
1713     true);
1714 }
1715 
1716 const ObjCInterfaceType *ObjCObjectPointerType::getInterfaceType() const {
1717   if (auto interfaceDecl = getObjectType()->getInterface()) {
1718     return interfaceDecl->getASTContext().getObjCInterfaceType(interfaceDecl)
1719              ->castAs<ObjCInterfaceType>();
1720   }
1721 
1722   return nullptr;
1723 }
1724 
1725 QualType ObjCObjectPointerType::getSuperClassType() const {
1726   QualType superObjectType = getObjectType()->getSuperClassType();
1727   if (superObjectType.isNull())
1728     return superObjectType;
1729 
1730   ASTContext &ctx = getInterfaceDecl()->getASTContext();
1731   return ctx.getObjCObjectPointerType(superObjectType);
1732 }
1733 
1734 const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const {
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 
1744 bool Type::isObjCQualifiedInterfaceType() const {
1745   return getAsObjCQualifiedInterfaceType() != nullptr;
1746 }
1747 
1748 const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
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 
1758 const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const {
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 
1768 const ObjCObjectType *Type::getAsObjCInterfaceType() const {
1769   if (const auto *OT = getAs<ObjCObjectType>()) {
1770     if (OT->getInterface())
1771       return OT;
1772   }
1773   return nullptr;
1774 }
1775 
1776 const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
1777   if (const auto *OPT = getAs<ObjCObjectPointerType>()) {
1778     if (OPT->getInterfaceType())
1779       return OPT;
1780   }
1781   return nullptr;
1782 }
1783 
1784 const CXXRecordDecl *Type::getPointeeCXXRecordDecl() const {
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 
1799 CXXRecordDecl *Type::getAsCXXRecordDecl() const {
1800   return dyn_cast_or_null<CXXRecordDecl>(getAsTagDecl());
1801 }
1802 
1803 RecordDecl *Type::getAsRecordDecl() const {
1804   return dyn_cast_or_null<RecordDecl>(getAsTagDecl());
1805 }
1806 
1807 TagDecl *Type::getAsTagDecl() const {
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 
1816 bool Type::hasAttr(attr::Kind AK) const {
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 
1826 namespace {
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 
1928 DeducedType *Type::getContainedDeducedType() const {
1929   return cast_or_null<DeducedType>(
1930       GetContainedDeducedTypeVisitor().Visit(this));
1931 }
1932 
1933 bool Type::hasAutoForTrailingReturnType() const {
1934   return isa_and_nonnull<FunctionType>(
1935       GetContainedDeducedTypeVisitor(true).Visit(this));
1936 }
1937 
1938 bool Type::hasIntegerRepresentation() const {
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.
1975 bool 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 
1988 bool Type::isIntegralOrUnscopedEnumerationType() const {
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 
1996   return isUnscopedEnumerationType();
1997 }
1998 
1999 bool Type::isUnscopedEnumerationType() const {
2000   if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
2001     return !ET->getDecl()->isScoped();
2002 
2003   return false;
2004 }
2005 
2006 bool 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 
2015 bool Type::isWideCharType() const {
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 
2022 bool Type::isChar8Type() const {
2023   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
2024     return BT->getKind() == BuiltinType::Char8;
2025   return false;
2026 }
2027 
2028 bool Type::isChar16Type() const {
2029   if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2030     return BT->getKind() == BuiltinType::Char16;
2031   return false;
2032 }
2033 
2034 bool Type::isChar32Type() const {
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.
2042 bool Type::isAnyCharacterType() const {
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
2063 bool Type::isSignedIntegerType() const {
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 
2084 bool Type::isSignedIntegerOrEnumerationType() const {
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 
2103 bool Type::hasSignedIntegerRepresentation() const {
2104   if (const auto *VT = dyn_cast<VectorType>(CanonicalType))
2105     return VT->getElementType()->isSignedIntegerOrEnumerationType();
2106   else
2107     return isSignedIntegerOrEnumerationType();
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
2113 bool Type::isUnsignedIntegerType() const {
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 
2134 bool Type::isUnsignedIntegerOrEnumerationType() const {
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 
2153 bool Type::hasUnsignedIntegerRepresentation() const {
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   }
2163   return isUnsignedIntegerOrEnumerationType();
2164 }
2165 
2166 bool Type::isFloatingType() const {
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 
2175 bool Type::hasFloatingRepresentation() const {
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 
2183 bool Type::isRealFloatingType() const {
2184   if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2185     return BT->isFloatingPoint();
2186   return false;
2187 }
2188 
2189 bool 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 
2198 bool Type::isArithmeticType() const {
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 
2213 Type::ScalarTypeKind Type::getScalarTypeKind() const {
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.
2255 bool Type::isAggregateType() const {
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.
2269 bool Type::isConstantSizeType() const {
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.
2279 bool Type::isIncompleteType(NamedDecl **Def) const {
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.
2330     RD = RD->getMostRecentNonInjectedDecl();
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 
2350 bool Type::isSizelessBuiltinType() const {
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 
2370 bool Type::isWebAssemblyExternrefType() const {
2371   if (const auto *BT = getAs<BuiltinType>())
2372     return BT->getKind() == BuiltinType::WasmExternRef;
2373   return false;
2374 }
2375 
2376 bool Type::isWebAssemblyTableType() const {
2377   if (const auto *ATy = dyn_cast<ArrayType>(this))
2378     return ATy->getElementType().isWebAssemblyReferenceType();
2379 
2380   if (const auto *PTy = dyn_cast<PointerType>(this))
2381     return PTy->getPointeeType().isWebAssemblyReferenceType();
2382 
2383   return false;
2384 }
2385 
2386 bool Type::isSizelessType() const { return isSizelessBuiltinType(); }
2387 
2388 bool Type::isSVESizelessBuiltinType() const {
2389   if (const BuiltinType *BT = getAs<BuiltinType>()) {
2390     switch (BT->getKind()) {
2391       // SVE Types
2392 #define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2393 #include "clang/Basic/AArch64SVEACLETypes.def"
2394       return true;
2395     default:
2396       return false;
2397     }
2398   }
2399   return false;
2400 }
2401 
2402 bool Type::isRVVSizelessBuiltinType() const {
2403   if (const BuiltinType *BT = getAs<BuiltinType>()) {
2404     switch (BT->getKind()) {
2405 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2406 #include "clang/Basic/RISCVVTypes.def"
2407       return true;
2408     default:
2409       return false;
2410     }
2411   }
2412   return false;
2413 }
2414 
2415 bool Type::isVLSTBuiltinType() const {
2416   if (const BuiltinType *BT = getAs<BuiltinType>()) {
2417     switch (BT->getKind()) {
2418     case BuiltinType::SveInt8:
2419     case BuiltinType::SveInt16:
2420     case BuiltinType::SveInt32:
2421     case BuiltinType::SveInt64:
2422     case BuiltinType::SveUint8:
2423     case BuiltinType::SveUint16:
2424     case BuiltinType::SveUint32:
2425     case BuiltinType::SveUint64:
2426     case BuiltinType::SveFloat16:
2427     case BuiltinType::SveFloat32:
2428     case BuiltinType::SveFloat64:
2429     case BuiltinType::SveBFloat16:
2430     case BuiltinType::SveBool:
2431     case BuiltinType::SveBoolx2:
2432     case BuiltinType::SveBoolx4:
2433       return true;
2434     default:
2435       return false;
2436     }
2437   }
2438   return false;
2439 }
2440 
2441 QualType Type::getSveEltType(const ASTContext &Ctx) const {
2442   assert(isVLSTBuiltinType() && "unsupported type!");
2443 
2444   const BuiltinType *BTy = castAs<BuiltinType>();
2445   if (BTy->getKind() == BuiltinType::SveBool)
2446     // Represent predicates as i8 rather than i1 to avoid any layout issues.
2447     // The type is bitcasted to a scalable predicate type when casting between
2448     // scalable and fixed-length vectors.
2449     return Ctx.UnsignedCharTy;
2450   else
2451     return Ctx.getBuiltinVectorTypeInfo(BTy).ElementType;
2452 }
2453 
2454 bool Type::isRVVVLSBuiltinType() const {
2455   if (const BuiltinType *BT = getAs<BuiltinType>()) {
2456     switch (BT->getKind()) {
2457 #define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, IsFP) \
2458     case BuiltinType::Id: \
2459       return NF == 1;
2460 #include "clang/Basic/RISCVVTypes.def"
2461     default:
2462       return false;
2463     }
2464   }
2465   return false;
2466 }
2467 
2468 QualType Type::getRVVEltType(const ASTContext &Ctx) const {
2469   assert(isRVVVLSBuiltinType() && "unsupported type!");
2470 
2471   const BuiltinType *BTy = castAs<BuiltinType>();
2472   return Ctx.getBuiltinVectorTypeInfo(BTy).ElementType;
2473 }
2474 
2475 bool QualType::isPODType(const ASTContext &Context) const {
2476   // C++11 has a more relaxed definition of POD.
2477   if (Context.getLangOpts().CPlusPlus11)
2478     return isCXX11PODType(Context);
2479 
2480   return isCXX98PODType(Context);
2481 }
2482 
2483 bool QualType::isCXX98PODType(const ASTContext &Context) const {
2484   // The compiler shouldn't query this for incomplete types, but the user might.
2485   // We return false for that case. Except for incomplete arrays of PODs, which
2486   // are PODs according to the standard.
2487   if (isNull())
2488     return false;
2489 
2490   if ((*this)->isIncompleteArrayType())
2491     return Context.getBaseElementType(*this).isCXX98PODType(Context);
2492 
2493   if ((*this)->isIncompleteType())
2494     return false;
2495 
2496   if (hasNonTrivialObjCLifetime())
2497     return false;
2498 
2499   QualType CanonicalType = getTypePtr()->CanonicalType;
2500   switch (CanonicalType->getTypeClass()) {
2501     // Everything not explicitly mentioned is not POD.
2502   default: return false;
2503   case Type::VariableArray:
2504   case Type::ConstantArray:
2505     // IncompleteArray is handled above.
2506     return Context.getBaseElementType(*this).isCXX98PODType(Context);
2507 
2508   case Type::ObjCObjectPointer:
2509   case Type::BlockPointer:
2510   case Type::Builtin:
2511   case Type::Complex:
2512   case Type::Pointer:
2513   case Type::MemberPointer:
2514   case Type::Vector:
2515   case Type::ExtVector:
2516   case Type::BitInt:
2517     return true;
2518 
2519   case Type::Enum:
2520     return true;
2521 
2522   case Type::Record:
2523     if (const auto *ClassDecl =
2524             dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
2525       return ClassDecl->isPOD();
2526 
2527     // C struct/union is POD.
2528     return true;
2529   }
2530 }
2531 
2532 bool QualType::isTrivialType(const ASTContext &Context) const {
2533   // The compiler shouldn't query this for incomplete types, but the user might.
2534   // We return false for that case. Except for incomplete arrays of PODs, which
2535   // are PODs according to the standard.
2536   if (isNull())
2537     return false;
2538 
2539   if ((*this)->isArrayType())
2540     return Context.getBaseElementType(*this).isTrivialType(Context);
2541 
2542   if ((*this)->isSizelessBuiltinType())
2543     return true;
2544 
2545   // Return false for incomplete types after skipping any incomplete array
2546   // types which are expressly allowed by the standard and thus our API.
2547   if ((*this)->isIncompleteType())
2548     return false;
2549 
2550   if (hasNonTrivialObjCLifetime())
2551     return false;
2552 
2553   QualType CanonicalType = getTypePtr()->CanonicalType;
2554   if (CanonicalType->isDependentType())
2555     return false;
2556 
2557   // C++0x [basic.types]p9:
2558   //   Scalar types, trivial class types, arrays of such types, and
2559   //   cv-qualified versions of these types are collectively called trivial
2560   //   types.
2561 
2562   // As an extension, Clang treats vector types as Scalar types.
2563   if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
2564     return true;
2565   if (const auto *RT = CanonicalType->getAs<RecordType>()) {
2566     if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2567       // C++20 [class]p6:
2568       //   A trivial class is a class that is trivially copyable, and
2569       //     has one or more eligible default constructors such that each is
2570       //     trivial.
2571       // FIXME: We should merge this definition of triviality into
2572       // CXXRecordDecl::isTrivial. Currently it computes the wrong thing.
2573       return ClassDecl->hasTrivialDefaultConstructor() &&
2574              !ClassDecl->hasNonTrivialDefaultConstructor() &&
2575              ClassDecl->isTriviallyCopyable();
2576     }
2577 
2578     return true;
2579   }
2580 
2581   // No other types can match.
2582   return false;
2583 }
2584 
2585 bool QualType::isTriviallyCopyableType(const ASTContext &Context) const {
2586   if ((*this)->isArrayType())
2587     return Context.getBaseElementType(*this).isTriviallyCopyableType(Context);
2588 
2589   if (hasNonTrivialObjCLifetime())
2590     return false;
2591 
2592   // C++11 [basic.types]p9 - See Core 2094
2593   //   Scalar types, trivially copyable class types, arrays of such types, and
2594   //   cv-qualified versions of these types are collectively
2595   //   called trivially copyable types.
2596 
2597   QualType CanonicalType = getCanonicalType();
2598   if (CanonicalType->isDependentType())
2599     return false;
2600 
2601   if (CanonicalType->isSizelessBuiltinType())
2602     return true;
2603 
2604   // Return false for incomplete types after skipping any incomplete array types
2605   // which are expressly allowed by the standard and thus our API.
2606   if (CanonicalType->isIncompleteType())
2607     return false;
2608 
2609   // As an extension, Clang treats vector types as Scalar types.
2610   if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
2611     return true;
2612 
2613   if (const auto *RT = CanonicalType->getAs<RecordType>()) {
2614     if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2615       if (!ClassDecl->isTriviallyCopyable()) return false;
2616     }
2617 
2618     return true;
2619   }
2620 
2621   // No other types can match.
2622   return false;
2623 }
2624 
2625 bool QualType::isTriviallyRelocatableType(const ASTContext &Context) const {
2626   QualType BaseElementType = Context.getBaseElementType(*this);
2627 
2628   if (BaseElementType->isIncompleteType()) {
2629     return false;
2630   } else if (const auto *RD = BaseElementType->getAsRecordDecl()) {
2631     return RD->canPassInRegisters();
2632   } else {
2633     switch (isNonTrivialToPrimitiveDestructiveMove()) {
2634     case PCK_Trivial:
2635       return !isDestructedType();
2636     case PCK_ARCStrong:
2637       return true;
2638     default:
2639       return false;
2640     }
2641   }
2642 }
2643 
2644 static bool
2645 HasNonDeletedDefaultedEqualityComparison(const CXXRecordDecl *Decl) {
2646   if (Decl->isUnion())
2647     return false;
2648 
2649   auto IsDefaultedOperatorEqualEqual = [&](const FunctionDecl *Function) {
2650     return Function->getOverloadedOperator() ==
2651                OverloadedOperatorKind::OO_EqualEqual &&
2652            Function->isDefaulted() && Function->getNumParams() > 0 &&
2653            (Function->getParamDecl(0)->getType()->isReferenceType() ||
2654             Decl->isTriviallyCopyable());
2655   };
2656 
2657   if (llvm::none_of(Decl->methods(), IsDefaultedOperatorEqualEqual) &&
2658       llvm::none_of(Decl->friends(), [&](const FriendDecl *Friend) {
2659         if (NamedDecl *ND = Friend->getFriendDecl()) {
2660           return ND->isFunctionOrFunctionTemplate() &&
2661                  IsDefaultedOperatorEqualEqual(ND->getAsFunction());
2662         }
2663         return false;
2664       }))
2665     return false;
2666 
2667   return llvm::all_of(Decl->bases(),
2668                       [](const CXXBaseSpecifier &BS) {
2669                         if (const auto *RD = BS.getType()->getAsCXXRecordDecl())
2670                           return HasNonDeletedDefaultedEqualityComparison(RD);
2671                         return true;
2672                       }) &&
2673          llvm::all_of(Decl->fields(), [](const FieldDecl *FD) {
2674            auto Type = FD->getType();
2675            if (Type->isArrayType())
2676              Type = Type->getBaseElementTypeUnsafe()->getCanonicalTypeUnqualified();
2677 
2678            if (Type->isReferenceType() || Type->isEnumeralType())
2679              return false;
2680            if (const auto *RD = Type->getAsCXXRecordDecl())
2681              return HasNonDeletedDefaultedEqualityComparison(RD);
2682            return true;
2683          });
2684 }
2685 
2686 bool QualType::isTriviallyEqualityComparableType(
2687     const ASTContext &Context) const {
2688   QualType CanonicalType = getCanonicalType();
2689   if (CanonicalType->isIncompleteType() || CanonicalType->isDependentType() ||
2690       CanonicalType->isEnumeralType() || CanonicalType->isArrayType())
2691     return false;
2692 
2693   if (const auto *RD = CanonicalType->getAsCXXRecordDecl()) {
2694     if (!HasNonDeletedDefaultedEqualityComparison(RD))
2695       return false;
2696   }
2697 
2698   return Context.hasUniqueObjectRepresentations(
2699       CanonicalType, /*CheckIfTriviallyCopyable=*/false);
2700 }
2701 
2702 bool QualType::isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const {
2703   return !Context.getLangOpts().ObjCAutoRefCount &&
2704          Context.getLangOpts().ObjCWeak &&
2705          getObjCLifetime() != Qualifiers::OCL_Weak;
2706 }
2707 
2708 bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD) {
2709   return RD->hasNonTrivialToPrimitiveDefaultInitializeCUnion();
2710 }
2711 
2712 bool QualType::hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD) {
2713   return RD->hasNonTrivialToPrimitiveDestructCUnion();
2714 }
2715 
2716 bool QualType::hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD) {
2717   return RD->hasNonTrivialToPrimitiveCopyCUnion();
2718 }
2719 
2720 bool QualType::isWebAssemblyReferenceType() const {
2721   return isWebAssemblyExternrefType() || isWebAssemblyFuncrefType();
2722 }
2723 
2724 bool QualType::isWebAssemblyExternrefType() const {
2725   return getTypePtr()->isWebAssemblyExternrefType();
2726 }
2727 
2728 bool QualType::isWebAssemblyFuncrefType() const {
2729   return getTypePtr()->isFunctionPointerType() &&
2730          getAddressSpace() == LangAS::wasm_funcref;
2731 }
2732 
2733 QualType::PrimitiveDefaultInitializeKind
2734 QualType::isNonTrivialToPrimitiveDefaultInitialize() const {
2735   if (const auto *RT =
2736           getTypePtr()->getBaseElementTypeUnsafe()->getAs<RecordType>())
2737     if (RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize())
2738       return PDIK_Struct;
2739 
2740   switch (getQualifiers().getObjCLifetime()) {
2741   case Qualifiers::OCL_Strong:
2742     return PDIK_ARCStrong;
2743   case Qualifiers::OCL_Weak:
2744     return PDIK_ARCWeak;
2745   default:
2746     return PDIK_Trivial;
2747   }
2748 }
2749 
2750 QualType::PrimitiveCopyKind QualType::isNonTrivialToPrimitiveCopy() const {
2751   if (const auto *RT =
2752           getTypePtr()->getBaseElementTypeUnsafe()->getAs<RecordType>())
2753     if (RT->getDecl()->isNonTrivialToPrimitiveCopy())
2754       return PCK_Struct;
2755 
2756   Qualifiers Qs = getQualifiers();
2757   switch (Qs.getObjCLifetime()) {
2758   case Qualifiers::OCL_Strong:
2759     return PCK_ARCStrong;
2760   case Qualifiers::OCL_Weak:
2761     return PCK_ARCWeak;
2762   default:
2763     return Qs.hasVolatile() ? PCK_VolatileTrivial : PCK_Trivial;
2764   }
2765 }
2766 
2767 QualType::PrimitiveCopyKind
2768 QualType::isNonTrivialToPrimitiveDestructiveMove() const {
2769   return isNonTrivialToPrimitiveCopy();
2770 }
2771 
2772 bool Type::isLiteralType(const ASTContext &Ctx) const {
2773   if (isDependentType())
2774     return false;
2775 
2776   // C++1y [basic.types]p10:
2777   //   A type is a literal type if it is:
2778   //   -- cv void; or
2779   if (Ctx.getLangOpts().CPlusPlus14 && isVoidType())
2780     return true;
2781 
2782   // C++11 [basic.types]p10:
2783   //   A type is a literal type if it is:
2784   //   [...]
2785   //   -- an array of literal type other than an array of runtime bound; or
2786   if (isVariableArrayType())
2787     return false;
2788   const Type *BaseTy = getBaseElementTypeUnsafe();
2789   assert(BaseTy && "NULL element type");
2790 
2791   // Return false for incomplete types after skipping any incomplete array
2792   // types; those are expressly allowed by the standard and thus our API.
2793   if (BaseTy->isIncompleteType())
2794     return false;
2795 
2796   // C++11 [basic.types]p10:
2797   //   A type is a literal type if it is:
2798   //    -- a scalar type; or
2799   // As an extension, Clang treats vector types and complex types as
2800   // literal types.
2801   if (BaseTy->isScalarType() || BaseTy->isVectorType() ||
2802       BaseTy->isAnyComplexType())
2803     return true;
2804   //    -- a reference type; or
2805   if (BaseTy->isReferenceType())
2806     return true;
2807   //    -- a class type that has all of the following properties:
2808   if (const auto *RT = BaseTy->getAs<RecordType>()) {
2809     //    -- a trivial destructor,
2810     //    -- every constructor call and full-expression in the
2811     //       brace-or-equal-initializers for non-static data members (if any)
2812     //       is a constant expression,
2813     //    -- it is an aggregate type or has at least one constexpr
2814     //       constructor or constructor template that is not a copy or move
2815     //       constructor, and
2816     //    -- all non-static data members and base classes of literal types
2817     //
2818     // We resolve DR1361 by ignoring the second bullet.
2819     if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2820       return ClassDecl->isLiteral();
2821 
2822     return true;
2823   }
2824 
2825   // We treat _Atomic T as a literal type if T is a literal type.
2826   if (const auto *AT = BaseTy->getAs<AtomicType>())
2827     return AT->getValueType()->isLiteralType(Ctx);
2828 
2829   // If this type hasn't been deduced yet, then conservatively assume that
2830   // it'll work out to be a literal type.
2831   if (isa<AutoType>(BaseTy->getCanonicalTypeInternal()))
2832     return true;
2833 
2834   return false;
2835 }
2836 
2837 bool Type::isStructuralType() const {
2838   // C++20 [temp.param]p6:
2839   //   A structural type is one of the following:
2840   //   -- a scalar type; or
2841   //   -- a vector type [Clang extension]; or
2842   if (isScalarType() || isVectorType())
2843     return true;
2844   //   -- an lvalue reference type; or
2845   if (isLValueReferenceType())
2846     return true;
2847   //  -- a literal class type [...under some conditions]
2848   if (const CXXRecordDecl *RD = getAsCXXRecordDecl())
2849     return RD->isStructural();
2850   return false;
2851 }
2852 
2853 bool Type::isStandardLayoutType() const {
2854   if (isDependentType())
2855     return false;
2856 
2857   // C++0x [basic.types]p9:
2858   //   Scalar types, standard-layout class types, arrays of such types, and
2859   //   cv-qualified versions of these types are collectively called
2860   //   standard-layout types.
2861   const Type *BaseTy = getBaseElementTypeUnsafe();
2862   assert(BaseTy && "NULL element type");
2863 
2864   // Return false for incomplete types after skipping any incomplete array
2865   // types which are expressly allowed by the standard and thus our API.
2866   if (BaseTy->isIncompleteType())
2867     return false;
2868 
2869   // As an extension, Clang treats vector types as Scalar types.
2870   if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
2871   if (const auto *RT = BaseTy->getAs<RecordType>()) {
2872     if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2873       if (!ClassDecl->isStandardLayout())
2874         return false;
2875 
2876     // Default to 'true' for non-C++ class types.
2877     // FIXME: This is a bit dubious, but plain C structs should trivially meet
2878     // all the requirements of standard layout classes.
2879     return true;
2880   }
2881 
2882   // No other types can match.
2883   return false;
2884 }
2885 
2886 // This is effectively the intersection of isTrivialType and
2887 // isStandardLayoutType. We implement it directly to avoid redundant
2888 // conversions from a type to a CXXRecordDecl.
2889 bool QualType::isCXX11PODType(const ASTContext &Context) const {
2890   const Type *ty = getTypePtr();
2891   if (ty->isDependentType())
2892     return false;
2893 
2894   if (hasNonTrivialObjCLifetime())
2895     return false;
2896 
2897   // C++11 [basic.types]p9:
2898   //   Scalar types, POD classes, arrays of such types, and cv-qualified
2899   //   versions of these types are collectively called trivial types.
2900   const Type *BaseTy = ty->getBaseElementTypeUnsafe();
2901   assert(BaseTy && "NULL element type");
2902 
2903   if (BaseTy->isSizelessBuiltinType())
2904     return true;
2905 
2906   // Return false for incomplete types after skipping any incomplete array
2907   // types which are expressly allowed by the standard and thus our API.
2908   if (BaseTy->isIncompleteType())
2909     return false;
2910 
2911   // As an extension, Clang treats vector types as Scalar types.
2912   if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
2913   if (const auto *RT = BaseTy->getAs<RecordType>()) {
2914     if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2915       // C++11 [class]p10:
2916       //   A POD struct is a non-union class that is both a trivial class [...]
2917       if (!ClassDecl->isTrivial()) return false;
2918 
2919       // C++11 [class]p10:
2920       //   A POD struct is a non-union class that is both a trivial class and
2921       //   a standard-layout class [...]
2922       if (!ClassDecl->isStandardLayout()) return false;
2923 
2924       // C++11 [class]p10:
2925       //   A POD struct is a non-union class that is both a trivial class and
2926       //   a standard-layout class, and has no non-static data members of type
2927       //   non-POD struct, non-POD union (or array of such types). [...]
2928       //
2929       // We don't directly query the recursive aspect as the requirements for
2930       // both standard-layout classes and trivial classes apply recursively
2931       // already.
2932     }
2933 
2934     return true;
2935   }
2936 
2937   // No other types can match.
2938   return false;
2939 }
2940 
2941 bool Type::isNothrowT() const {
2942   if (const auto *RD = getAsCXXRecordDecl()) {
2943     IdentifierInfo *II = RD->getIdentifier();
2944     if (II && II->isStr("nothrow_t") && RD->isInStdNamespace())
2945       return true;
2946   }
2947   return false;
2948 }
2949 
2950 bool Type::isAlignValT() const {
2951   if (const auto *ET = getAs<EnumType>()) {
2952     IdentifierInfo *II = ET->getDecl()->getIdentifier();
2953     if (II && II->isStr("align_val_t") && ET->getDecl()->isInStdNamespace())
2954       return true;
2955   }
2956   return false;
2957 }
2958 
2959 bool Type::isStdByteType() const {
2960   if (const auto *ET = getAs<EnumType>()) {
2961     IdentifierInfo *II = ET->getDecl()->getIdentifier();
2962     if (II && II->isStr("byte") && ET->getDecl()->isInStdNamespace())
2963       return true;
2964   }
2965   return false;
2966 }
2967 
2968 bool Type::isSpecifierType() const {
2969   // Note that this intentionally does not use the canonical type.
2970   switch (getTypeClass()) {
2971   case Builtin:
2972   case Record:
2973   case Enum:
2974   case Typedef:
2975   case Complex:
2976   case TypeOfExpr:
2977   case TypeOf:
2978   case TemplateTypeParm:
2979   case SubstTemplateTypeParm:
2980   case TemplateSpecialization:
2981   case Elaborated:
2982   case DependentName:
2983   case DependentTemplateSpecialization:
2984   case ObjCInterface:
2985   case ObjCObject:
2986     return true;
2987   default:
2988     return false;
2989   }
2990 }
2991 
2992 ElaboratedTypeKeyword
2993 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) {
2994   switch (TypeSpec) {
2995   default: return ETK_None;
2996   case TST_typename: return ETK_Typename;
2997   case TST_class: return ETK_Class;
2998   case TST_struct: return ETK_Struct;
2999   case TST_interface: return ETK_Interface;
3000   case TST_union: return ETK_Union;
3001   case TST_enum: return ETK_Enum;
3002   }
3003 }
3004 
3005 TagTypeKind
3006 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
3007   switch(TypeSpec) {
3008   case TST_class: return TTK_Class;
3009   case TST_struct: return TTK_Struct;
3010   case TST_interface: return TTK_Interface;
3011   case TST_union: return TTK_Union;
3012   case TST_enum: return TTK_Enum;
3013   }
3014 
3015   llvm_unreachable("Type specifier is not a tag type kind.");
3016 }
3017 
3018 ElaboratedTypeKeyword
3019 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) {
3020   switch (Kind) {
3021   case TTK_Class: return ETK_Class;
3022   case TTK_Struct: return ETK_Struct;
3023   case TTK_Interface: return ETK_Interface;
3024   case TTK_Union: return ETK_Union;
3025   case TTK_Enum: return ETK_Enum;
3026   }
3027   llvm_unreachable("Unknown tag type kind.");
3028 }
3029 
3030 TagTypeKind
3031 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
3032   switch (Keyword) {
3033   case ETK_Class: return TTK_Class;
3034   case ETK_Struct: return TTK_Struct;
3035   case ETK_Interface: return TTK_Interface;
3036   case ETK_Union: return TTK_Union;
3037   case ETK_Enum: return TTK_Enum;
3038   case ETK_None: // Fall through.
3039   case ETK_Typename:
3040     llvm_unreachable("Elaborated type keyword is not a tag type kind.");
3041   }
3042   llvm_unreachable("Unknown elaborated type keyword.");
3043 }
3044 
3045 bool
3046 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
3047   switch (Keyword) {
3048   case ETK_None:
3049   case ETK_Typename:
3050     return false;
3051   case ETK_Class:
3052   case ETK_Struct:
3053   case ETK_Interface:
3054   case ETK_Union:
3055   case ETK_Enum:
3056     return true;
3057   }
3058   llvm_unreachable("Unknown elaborated type keyword.");
3059 }
3060 
3061 StringRef TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) {
3062   switch (Keyword) {
3063   case ETK_None: return {};
3064   case ETK_Typename: return "typename";
3065   case ETK_Class:  return "class";
3066   case ETK_Struct: return "struct";
3067   case ETK_Interface: return "__interface";
3068   case ETK_Union:  return "union";
3069   case ETK_Enum:   return "enum";
3070   }
3071 
3072   llvm_unreachable("Unknown elaborated type keyword.");
3073 }
3074 
3075 DependentTemplateSpecializationType::DependentTemplateSpecializationType(
3076     ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
3077     const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args, QualType Canon)
3078     : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon,
3079                       TypeDependence::DependentInstantiation |
3080                           (NNS ? toTypeDependence(NNS->getDependence())
3081                                : TypeDependence::None)),
3082       NNS(NNS), Name(Name) {
3083   DependentTemplateSpecializationTypeBits.NumArgs = Args.size();
3084   assert((!NNS || NNS->isDependent()) &&
3085          "DependentTemplateSpecializatonType requires dependent qualifier");
3086   auto *ArgBuffer = const_cast<TemplateArgument *>(template_arguments().data());
3087   for (const TemplateArgument &Arg : Args) {
3088     addDependence(toTypeDependence(Arg.getDependence() &
3089                                    TemplateArgumentDependence::UnexpandedPack));
3090 
3091     new (ArgBuffer++) TemplateArgument(Arg);
3092   }
3093 }
3094 
3095 void
3096 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
3097                                              const ASTContext &Context,
3098                                              ElaboratedTypeKeyword Keyword,
3099                                              NestedNameSpecifier *Qualifier,
3100                                              const IdentifierInfo *Name,
3101                                              ArrayRef<TemplateArgument> Args) {
3102   ID.AddInteger(Keyword);
3103   ID.AddPointer(Qualifier);
3104   ID.AddPointer(Name);
3105   for (const TemplateArgument &Arg : Args)
3106     Arg.Profile(ID, Context);
3107 }
3108 
3109 bool Type::isElaboratedTypeSpecifier() const {
3110   ElaboratedTypeKeyword Keyword;
3111   if (const auto *Elab = dyn_cast<ElaboratedType>(this))
3112     Keyword = Elab->getKeyword();
3113   else if (const auto *DepName = dyn_cast<DependentNameType>(this))
3114     Keyword = DepName->getKeyword();
3115   else if (const auto *DepTST =
3116                dyn_cast<DependentTemplateSpecializationType>(this))
3117     Keyword = DepTST->getKeyword();
3118   else
3119     return false;
3120 
3121   return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
3122 }
3123 
3124 const char *Type::getTypeClassName() const {
3125   switch (TypeBits.TC) {
3126 #define ABSTRACT_TYPE(Derived, Base)
3127 #define TYPE(Derived, Base) case Derived: return #Derived;
3128 #include "clang/AST/TypeNodes.inc"
3129   }
3130 
3131   llvm_unreachable("Invalid type class.");
3132 }
3133 
3134 StringRef BuiltinType::getName(const PrintingPolicy &Policy) const {
3135   switch (getKind()) {
3136   case Void:
3137     return "void";
3138   case Bool:
3139     return Policy.Bool ? "bool" : "_Bool";
3140   case Char_S:
3141     return "char";
3142   case Char_U:
3143     return "char";
3144   case SChar:
3145     return "signed char";
3146   case Short:
3147     return "short";
3148   case Int:
3149     return "int";
3150   case Long:
3151     return "long";
3152   case LongLong:
3153     return "long long";
3154   case Int128:
3155     return "__int128";
3156   case UChar:
3157     return "unsigned char";
3158   case UShort:
3159     return "unsigned short";
3160   case UInt:
3161     return "unsigned int";
3162   case ULong:
3163     return "unsigned long";
3164   case ULongLong:
3165     return "unsigned long long";
3166   case UInt128:
3167     return "unsigned __int128";
3168   case Half:
3169     return Policy.Half ? "half" : "__fp16";
3170   case BFloat16:
3171     return "__bf16";
3172   case Float:
3173     return "float";
3174   case Double:
3175     return "double";
3176   case LongDouble:
3177     return "long double";
3178   case ShortAccum:
3179     return "short _Accum";
3180   case Accum:
3181     return "_Accum";
3182   case LongAccum:
3183     return "long _Accum";
3184   case UShortAccum:
3185     return "unsigned short _Accum";
3186   case UAccum:
3187     return "unsigned _Accum";
3188   case ULongAccum:
3189     return "unsigned long _Accum";
3190   case BuiltinType::ShortFract:
3191     return "short _Fract";
3192   case BuiltinType::Fract:
3193     return "_Fract";
3194   case BuiltinType::LongFract:
3195     return "long _Fract";
3196   case BuiltinType::UShortFract:
3197     return "unsigned short _Fract";
3198   case BuiltinType::UFract:
3199     return "unsigned _Fract";
3200   case BuiltinType::ULongFract:
3201     return "unsigned long _Fract";
3202   case BuiltinType::SatShortAccum:
3203     return "_Sat short _Accum";
3204   case BuiltinType::SatAccum:
3205     return "_Sat _Accum";
3206   case BuiltinType::SatLongAccum:
3207     return "_Sat long _Accum";
3208   case BuiltinType::SatUShortAccum:
3209     return "_Sat unsigned short _Accum";
3210   case BuiltinType::SatUAccum:
3211     return "_Sat unsigned _Accum";
3212   case BuiltinType::SatULongAccum:
3213     return "_Sat unsigned long _Accum";
3214   case BuiltinType::SatShortFract:
3215     return "_Sat short _Fract";
3216   case BuiltinType::SatFract:
3217     return "_Sat _Fract";
3218   case BuiltinType::SatLongFract:
3219     return "_Sat long _Fract";
3220   case BuiltinType::SatUShortFract:
3221     return "_Sat unsigned short _Fract";
3222   case BuiltinType::SatUFract:
3223     return "_Sat unsigned _Fract";
3224   case BuiltinType::SatULongFract:
3225     return "_Sat unsigned long _Fract";
3226   case Float16:
3227     return "_Float16";
3228   case Float128:
3229     return "__float128";
3230   case Ibm128:
3231     return "__ibm128";
3232   case WChar_S:
3233   case WChar_U:
3234     return Policy.MSWChar ? "__wchar_t" : "wchar_t";
3235   case Char8:
3236     return "char8_t";
3237   case Char16:
3238     return "char16_t";
3239   case Char32:
3240     return "char32_t";
3241   case NullPtr:
3242     return Policy.NullptrTypeInNamespace ? "std::nullptr_t" : "nullptr_t";
3243   case Overload:
3244     return "<overloaded function type>";
3245   case BoundMember:
3246     return "<bound member function type>";
3247   case PseudoObject:
3248     return "<pseudo-object type>";
3249   case Dependent:
3250     return "<dependent type>";
3251   case UnknownAny:
3252     return "<unknown type>";
3253   case ARCUnbridgedCast:
3254     return "<ARC unbridged cast type>";
3255   case BuiltinFn:
3256     return "<builtin fn type>";
3257   case ObjCId:
3258     return "id";
3259   case ObjCClass:
3260     return "Class";
3261   case ObjCSel:
3262     return "SEL";
3263 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3264   case Id: \
3265     return "__" #Access " " #ImgType "_t";
3266 #include "clang/Basic/OpenCLImageTypes.def"
3267   case OCLSampler:
3268     return "sampler_t";
3269   case OCLEvent:
3270     return "event_t";
3271   case OCLClkEvent:
3272     return "clk_event_t";
3273   case OCLQueue:
3274     return "queue_t";
3275   case OCLReserveID:
3276     return "reserve_id_t";
3277   case IncompleteMatrixIdx:
3278     return "<incomplete matrix index type>";
3279   case OMPArraySection:
3280     return "<OpenMP array section type>";
3281   case OMPArrayShaping:
3282     return "<OpenMP array shaping type>";
3283   case OMPIterator:
3284     return "<OpenMP iterator type>";
3285 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3286   case Id: \
3287     return #ExtType;
3288 #include "clang/Basic/OpenCLExtensionTypes.def"
3289 #define SVE_TYPE(Name, Id, SingletonId) \
3290   case Id: \
3291     return Name;
3292 #include "clang/Basic/AArch64SVEACLETypes.def"
3293 #define PPC_VECTOR_TYPE(Name, Id, Size) \
3294   case Id: \
3295     return #Name;
3296 #include "clang/Basic/PPCTypes.def"
3297 #define RVV_TYPE(Name, Id, SingletonId)                                        \
3298   case Id:                                                                     \
3299     return Name;
3300 #include "clang/Basic/RISCVVTypes.def"
3301 #define WASM_TYPE(Name, Id, SingletonId)                                       \
3302   case Id:                                                                     \
3303     return Name;
3304 #include "clang/Basic/WebAssemblyReferenceTypes.def"
3305   }
3306 
3307   llvm_unreachable("Invalid builtin type.");
3308 }
3309 
3310 QualType QualType::getNonPackExpansionType() const {
3311   // We never wrap type sugar around a PackExpansionType.
3312   if (auto *PET = dyn_cast<PackExpansionType>(getTypePtr()))
3313     return PET->getPattern();
3314   return *this;
3315 }
3316 
3317 QualType QualType::getNonLValueExprType(const ASTContext &Context) const {
3318   if (const auto *RefType = getTypePtr()->getAs<ReferenceType>())
3319     return RefType->getPointeeType();
3320 
3321   // C++0x [basic.lval]:
3322   //   Class prvalues can have cv-qualified types; non-class prvalues always
3323   //   have cv-unqualified types.
3324   //
3325   // See also C99 6.3.2.1p2.
3326   if (!Context.getLangOpts().CPlusPlus ||
3327       (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
3328     return getUnqualifiedType();
3329 
3330   return *this;
3331 }
3332 
3333 StringRef FunctionType::getNameForCallConv(CallingConv CC) {
3334   switch (CC) {
3335   case CC_C: return "cdecl";
3336   case CC_X86StdCall: return "stdcall";
3337   case CC_X86FastCall: return "fastcall";
3338   case CC_X86ThisCall: return "thiscall";
3339   case CC_X86Pascal: return "pascal";
3340   case CC_X86VectorCall: return "vectorcall";
3341   case CC_Win64: return "ms_abi";
3342   case CC_X86_64SysV: return "sysv_abi";
3343   case CC_X86RegCall : return "regcall";
3344   case CC_AAPCS: return "aapcs";
3345   case CC_AAPCS_VFP: return "aapcs-vfp";
3346   case CC_AArch64VectorCall: return "aarch64_vector_pcs";
3347   case CC_AArch64SVEPCS: return "aarch64_sve_pcs";
3348   case CC_AMDGPUKernelCall: return "amdgpu_kernel";
3349   case CC_IntelOclBicc: return "intel_ocl_bicc";
3350   case CC_SpirFunction: return "spir_function";
3351   case CC_OpenCLKernel: return "opencl_kernel";
3352   case CC_Swift: return "swiftcall";
3353   case CC_SwiftAsync: return "swiftasynccall";
3354   case CC_PreserveMost: return "preserve_most";
3355   case CC_PreserveAll: return "preserve_all";
3356   }
3357 
3358   llvm_unreachable("Invalid calling convention.");
3359 }
3360 
3361 FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> params,
3362                                      QualType canonical,
3363                                      const ExtProtoInfo &epi)
3364     : FunctionType(FunctionProto, result, canonical, result->getDependence(),
3365                    epi.ExtInfo) {
3366   FunctionTypeBits.FastTypeQuals = epi.TypeQuals.getFastQualifiers();
3367   FunctionTypeBits.RefQualifier = epi.RefQualifier;
3368   FunctionTypeBits.NumParams = params.size();
3369   assert(getNumParams() == params.size() && "NumParams overflow!");
3370   FunctionTypeBits.ExceptionSpecType = epi.ExceptionSpec.Type;
3371   FunctionTypeBits.HasExtParameterInfos = !!epi.ExtParameterInfos;
3372   FunctionTypeBits.Variadic = epi.Variadic;
3373   FunctionTypeBits.HasTrailingReturn = epi.HasTrailingReturn;
3374 
3375   if (epi.requiresFunctionProtoTypeExtraBitfields()) {
3376     FunctionTypeBits.HasExtraBitfields = true;
3377     auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
3378     ExtraBits = FunctionTypeExtraBitfields();
3379   } else {
3380     FunctionTypeBits.HasExtraBitfields = false;
3381   }
3382 
3383 
3384   // Fill in the trailing argument array.
3385   auto *argSlot = getTrailingObjects<QualType>();
3386   for (unsigned i = 0; i != getNumParams(); ++i) {
3387     addDependence(params[i]->getDependence() &
3388                   ~TypeDependence::VariablyModified);
3389     argSlot[i] = params[i];
3390   }
3391 
3392   // Fill in the exception type array if present.
3393   if (getExceptionSpecType() == EST_Dynamic) {
3394     auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
3395     size_t NumExceptions = epi.ExceptionSpec.Exceptions.size();
3396     assert(NumExceptions <= UINT16_MAX &&
3397            "Not enough bits to encode exceptions");
3398     ExtraBits.NumExceptionType = NumExceptions;
3399 
3400     assert(hasExtraBitfields() && "missing trailing extra bitfields!");
3401     auto *exnSlot =
3402         reinterpret_cast<QualType *>(getTrailingObjects<ExceptionType>());
3403     unsigned I = 0;
3404     for (QualType ExceptionType : epi.ExceptionSpec.Exceptions) {
3405       // Note that, before C++17, a dependent exception specification does
3406       // *not* make a type dependent; it's not even part of the C++ type
3407       // system.
3408       addDependence(
3409           ExceptionType->getDependence() &
3410           (TypeDependence::Instantiation | TypeDependence::UnexpandedPack));
3411 
3412       exnSlot[I++] = ExceptionType;
3413     }
3414   }
3415   // Fill in the Expr * in the exception specification if present.
3416   else if (isComputedNoexcept(getExceptionSpecType())) {
3417     assert(epi.ExceptionSpec.NoexceptExpr && "computed noexcept with no expr");
3418     assert((getExceptionSpecType() == EST_DependentNoexcept) ==
3419            epi.ExceptionSpec.NoexceptExpr->isValueDependent());
3420 
3421     // Store the noexcept expression and context.
3422     *getTrailingObjects<Expr *>() = epi.ExceptionSpec.NoexceptExpr;
3423 
3424     addDependence(
3425         toTypeDependence(epi.ExceptionSpec.NoexceptExpr->getDependence()) &
3426         (TypeDependence::Instantiation | TypeDependence::UnexpandedPack));
3427   }
3428   // Fill in the FunctionDecl * in the exception specification if present.
3429   else if (getExceptionSpecType() == EST_Uninstantiated) {
3430     // Store the function decl from which we will resolve our
3431     // exception specification.
3432     auto **slot = getTrailingObjects<FunctionDecl *>();
3433     slot[0] = epi.ExceptionSpec.SourceDecl;
3434     slot[1] = epi.ExceptionSpec.SourceTemplate;
3435     // This exception specification doesn't make the type dependent, because
3436     // it's not instantiated as part of instantiating the type.
3437   } else if (getExceptionSpecType() == EST_Unevaluated) {
3438     // Store the function decl from which we will resolve our
3439     // exception specification.
3440     auto **slot = getTrailingObjects<FunctionDecl *>();
3441     slot[0] = epi.ExceptionSpec.SourceDecl;
3442   }
3443 
3444   // If this is a canonical type, and its exception specification is dependent,
3445   // then it's a dependent type. This only happens in C++17 onwards.
3446   if (isCanonicalUnqualified()) {
3447     if (getExceptionSpecType() == EST_Dynamic ||
3448         getExceptionSpecType() == EST_DependentNoexcept) {
3449       assert(hasDependentExceptionSpec() && "type should not be canonical");
3450       addDependence(TypeDependence::DependentInstantiation);
3451     }
3452   } else if (getCanonicalTypeInternal()->isDependentType()) {
3453     // Ask our canonical type whether our exception specification was dependent.
3454     addDependence(TypeDependence::DependentInstantiation);
3455   }
3456 
3457   // Fill in the extra parameter info if present.
3458   if (epi.ExtParameterInfos) {
3459     auto *extParamInfos = getTrailingObjects<ExtParameterInfo>();
3460     for (unsigned i = 0; i != getNumParams(); ++i)
3461       extParamInfos[i] = epi.ExtParameterInfos[i];
3462   }
3463 
3464   if (epi.TypeQuals.hasNonFastQualifiers()) {
3465     FunctionTypeBits.HasExtQuals = 1;
3466     *getTrailingObjects<Qualifiers>() = epi.TypeQuals;
3467   } else {
3468     FunctionTypeBits.HasExtQuals = 0;
3469   }
3470 
3471   // Fill in the Ellipsis location info if present.
3472   if (epi.Variadic) {
3473     auto &EllipsisLoc = *getTrailingObjects<SourceLocation>();
3474     EllipsisLoc = epi.EllipsisLoc;
3475   }
3476 }
3477 
3478 bool FunctionProtoType::hasDependentExceptionSpec() const {
3479   if (Expr *NE = getNoexceptExpr())
3480     return NE->isValueDependent();
3481   for (QualType ET : exceptions())
3482     // A pack expansion with a non-dependent pattern is still dependent,
3483     // because we don't know whether the pattern is in the exception spec
3484     // or not (that depends on whether the pack has 0 expansions).
3485     if (ET->isDependentType() || ET->getAs<PackExpansionType>())
3486       return true;
3487   return false;
3488 }
3489 
3490 bool FunctionProtoType::hasInstantiationDependentExceptionSpec() const {
3491   if (Expr *NE = getNoexceptExpr())
3492     return NE->isInstantiationDependent();
3493   for (QualType ET : exceptions())
3494     if (ET->isInstantiationDependentType())
3495       return true;
3496   return false;
3497 }
3498 
3499 CanThrowResult FunctionProtoType::canThrow() const {
3500   switch (getExceptionSpecType()) {
3501   case EST_Unparsed:
3502   case EST_Unevaluated:
3503     llvm_unreachable("should not call this with unresolved exception specs");
3504 
3505   case EST_DynamicNone:
3506   case EST_BasicNoexcept:
3507   case EST_NoexceptTrue:
3508   case EST_NoThrow:
3509     return CT_Cannot;
3510 
3511   case EST_None:
3512   case EST_MSAny:
3513   case EST_NoexceptFalse:
3514     return CT_Can;
3515 
3516   case EST_Dynamic:
3517     // A dynamic exception specification is throwing unless every exception
3518     // type is an (unexpanded) pack expansion type.
3519     for (unsigned I = 0; I != getNumExceptions(); ++I)
3520       if (!getExceptionType(I)->getAs<PackExpansionType>())
3521         return CT_Can;
3522     return CT_Dependent;
3523 
3524   case EST_Uninstantiated:
3525   case EST_DependentNoexcept:
3526     return CT_Dependent;
3527   }
3528 
3529   llvm_unreachable("unexpected exception specification kind");
3530 }
3531 
3532 bool FunctionProtoType::isTemplateVariadic() const {
3533   for (unsigned ArgIdx = getNumParams(); ArgIdx; --ArgIdx)
3534     if (isa<PackExpansionType>(getParamType(ArgIdx - 1)))
3535       return true;
3536 
3537   return false;
3538 }
3539 
3540 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
3541                                 const QualType *ArgTys, unsigned NumParams,
3542                                 const ExtProtoInfo &epi,
3543                                 const ASTContext &Context, bool Canonical) {
3544   // We have to be careful not to get ambiguous profile encodings.
3545   // Note that valid type pointers are never ambiguous with anything else.
3546   //
3547   // The encoding grammar begins:
3548   //      type type* bool int bool
3549   // If that final bool is true, then there is a section for the EH spec:
3550   //      bool type*
3551   // This is followed by an optional "consumed argument" section of the
3552   // same length as the first type sequence:
3553   //      bool*
3554   // Finally, we have the ext info and trailing return type flag:
3555   //      int bool
3556   //
3557   // There is no ambiguity between the consumed arguments and an empty EH
3558   // spec because of the leading 'bool' which unambiguously indicates
3559   // whether the following bool is the EH spec or part of the arguments.
3560 
3561   ID.AddPointer(Result.getAsOpaquePtr());
3562   for (unsigned i = 0; i != NumParams; ++i)
3563     ID.AddPointer(ArgTys[i].getAsOpaquePtr());
3564   // This method is relatively performance sensitive, so as a performance
3565   // shortcut, use one AddInteger call instead of four for the next four
3566   // fields.
3567   assert(!(unsigned(epi.Variadic) & ~1) &&
3568          !(unsigned(epi.RefQualifier) & ~3) &&
3569          !(unsigned(epi.ExceptionSpec.Type) & ~15) &&
3570          "Values larger than expected.");
3571   ID.AddInteger(unsigned(epi.Variadic) +
3572                 (epi.RefQualifier << 1) +
3573                 (epi.ExceptionSpec.Type << 3));
3574   ID.Add(epi.TypeQuals);
3575   if (epi.ExceptionSpec.Type == EST_Dynamic) {
3576     for (QualType Ex : epi.ExceptionSpec.Exceptions)
3577       ID.AddPointer(Ex.getAsOpaquePtr());
3578   } else if (isComputedNoexcept(epi.ExceptionSpec.Type)) {
3579     epi.ExceptionSpec.NoexceptExpr->Profile(ID, Context, Canonical);
3580   } else if (epi.ExceptionSpec.Type == EST_Uninstantiated ||
3581              epi.ExceptionSpec.Type == EST_Unevaluated) {
3582     ID.AddPointer(epi.ExceptionSpec.SourceDecl->getCanonicalDecl());
3583   }
3584   if (epi.ExtParameterInfos) {
3585     for (unsigned i = 0; i != NumParams; ++i)
3586       ID.AddInteger(epi.ExtParameterInfos[i].getOpaqueValue());
3587   }
3588   epi.ExtInfo.Profile(ID);
3589   ID.AddBoolean(epi.HasTrailingReturn);
3590 }
3591 
3592 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
3593                                 const ASTContext &Ctx) {
3594   Profile(ID, getReturnType(), param_type_begin(), getNumParams(),
3595           getExtProtoInfo(), Ctx, isCanonicalUnqualified());
3596 }
3597 
3598 TypedefType::TypedefType(TypeClass tc, const TypedefNameDecl *D,
3599                          QualType Underlying, QualType can)
3600     : Type(tc, can, toSemanticDependence(can->getDependence())),
3601       Decl(const_cast<TypedefNameDecl *>(D)) {
3602   assert(!isa<TypedefType>(can) && "Invalid canonical type");
3603   TypedefBits.hasTypeDifferentFromDecl = !Underlying.isNull();
3604   if (!typeMatchesDecl())
3605     *getTrailingObjects<QualType>() = Underlying;
3606 }
3607 
3608 QualType TypedefType::desugar() const {
3609   return typeMatchesDecl() ? Decl->getUnderlyingType()
3610                            : *getTrailingObjects<QualType>();
3611 }
3612 
3613 UsingType::UsingType(const UsingShadowDecl *Found, QualType Underlying,
3614                      QualType Canon)
3615     : Type(Using, Canon, toSemanticDependence(Canon->getDependence())),
3616       Found(const_cast<UsingShadowDecl *>(Found)) {
3617   UsingBits.hasTypeDifferentFromDecl = !Underlying.isNull();
3618   if (!typeMatchesDecl())
3619     *getTrailingObjects<QualType>() = Underlying;
3620 }
3621 
3622 QualType UsingType::getUnderlyingType() const {
3623   return typeMatchesDecl()
3624              ? QualType(
3625                    cast<TypeDecl>(Found->getTargetDecl())->getTypeForDecl(), 0)
3626              : *getTrailingObjects<QualType>();
3627 }
3628 
3629 QualType MacroQualifiedType::desugar() const { return getUnderlyingType(); }
3630 
3631 QualType MacroQualifiedType::getModifiedType() const {
3632   // Step over MacroQualifiedTypes from the same macro to find the type
3633   // ultimately qualified by the macro qualifier.
3634   QualType Inner = cast<AttributedType>(getUnderlyingType())->getModifiedType();
3635   while (auto *InnerMQT = dyn_cast<MacroQualifiedType>(Inner)) {
3636     if (InnerMQT->getMacroIdentifier() != getMacroIdentifier())
3637       break;
3638     Inner = InnerMQT->getModifiedType();
3639   }
3640   return Inner;
3641 }
3642 
3643 TypeOfExprType::TypeOfExprType(Expr *E, TypeOfKind Kind, QualType Can)
3644     : Type(TypeOfExpr,
3645            // We have to protect against 'Can' being invalid through its
3646            // default argument.
3647            Kind == TypeOfKind::Unqualified && !Can.isNull()
3648                ? Can.getAtomicUnqualifiedType()
3649                : Can,
3650            toTypeDependence(E->getDependence()) |
3651                (E->getType()->getDependence() &
3652                 TypeDependence::VariablyModified)),
3653       TOExpr(E) {
3654   TypeOfBits.IsUnqual = Kind == TypeOfKind::Unqualified;
3655 }
3656 
3657 bool TypeOfExprType::isSugared() const {
3658   return !TOExpr->isTypeDependent();
3659 }
3660 
3661 QualType TypeOfExprType::desugar() const {
3662   if (isSugared()) {
3663     QualType QT = getUnderlyingExpr()->getType();
3664     return TypeOfBits.IsUnqual ? QT.getAtomicUnqualifiedType() : QT;
3665   }
3666   return QualType(this, 0);
3667 }
3668 
3669 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
3670                                       const ASTContext &Context, Expr *E,
3671                                       bool IsUnqual) {
3672   E->Profile(ID, Context, true);
3673   ID.AddBoolean(IsUnqual);
3674 }
3675 
3676 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
3677     // C++11 [temp.type]p2: "If an expression e involves a template parameter,
3678     // decltype(e) denotes a unique dependent type." Hence a decltype type is
3679     // type-dependent even if its expression is only instantiation-dependent.
3680     : Type(Decltype, can,
3681            toTypeDependence(E->getDependence()) |
3682                (E->isInstantiationDependent() ? TypeDependence::Dependent
3683                                               : TypeDependence::None) |
3684                (E->getType()->getDependence() &
3685                 TypeDependence::VariablyModified)),
3686       E(E), UnderlyingType(underlyingType) {}
3687 
3688 bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); }
3689 
3690 QualType DecltypeType::desugar() const {
3691   if (isSugared())
3692     return getUnderlyingType();
3693 
3694   return QualType(this, 0);
3695 }
3696 
3697 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E)
3698     : DecltypeType(E, Context.DependentTy), Context(Context) {}
3699 
3700 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
3701                                     const ASTContext &Context, Expr *E) {
3702   E->Profile(ID, Context, true);
3703 }
3704 
3705 UnaryTransformType::UnaryTransformType(QualType BaseType,
3706                                        QualType UnderlyingType, UTTKind UKind,
3707                                        QualType CanonicalType)
3708     : Type(UnaryTransform, CanonicalType, BaseType->getDependence()),
3709       BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind) {}
3710 
3711 DependentUnaryTransformType::DependentUnaryTransformType(const ASTContext &C,
3712                                                          QualType BaseType,
3713                                                          UTTKind UKind)
3714      : UnaryTransformType(BaseType, C.DependentTy, UKind, QualType()) {}
3715 
3716 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
3717     : Type(TC, can,
3718            D->isDependentType() ? TypeDependence::DependentInstantiation
3719                                 : TypeDependence::None),
3720       decl(const_cast<TagDecl *>(D)) {}
3721 
3722 static TagDecl *getInterestingTagDecl(TagDecl *decl) {
3723   for (auto *I : decl->redecls()) {
3724     if (I->isCompleteDefinition() || I->isBeingDefined())
3725       return I;
3726   }
3727   // If there's no definition (not even in progress), return what we have.
3728   return decl;
3729 }
3730 
3731 TagDecl *TagType::getDecl() const {
3732   return getInterestingTagDecl(decl);
3733 }
3734 
3735 bool TagType::isBeingDefined() const {
3736   return getDecl()->isBeingDefined();
3737 }
3738 
3739 bool RecordType::hasConstFields() const {
3740   std::vector<const RecordType*> RecordTypeList;
3741   RecordTypeList.push_back(this);
3742   unsigned NextToCheckIndex = 0;
3743 
3744   while (RecordTypeList.size() > NextToCheckIndex) {
3745     for (FieldDecl *FD :
3746          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
3747       QualType FieldTy = FD->getType();
3748       if (FieldTy.isConstQualified())
3749         return true;
3750       FieldTy = FieldTy.getCanonicalType();
3751       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
3752         if (!llvm::is_contained(RecordTypeList, FieldRecTy))
3753           RecordTypeList.push_back(FieldRecTy);
3754       }
3755     }
3756     ++NextToCheckIndex;
3757   }
3758   return false;
3759 }
3760 
3761 bool AttributedType::isQualifier() const {
3762   // FIXME: Generate this with TableGen.
3763   switch (getAttrKind()) {
3764   // These are type qualifiers in the traditional C sense: they annotate
3765   // something about a specific value/variable of a type.  (They aren't
3766   // always part of the canonical type, though.)
3767   case attr::ObjCGC:
3768   case attr::ObjCOwnership:
3769   case attr::ObjCInertUnsafeUnretained:
3770   case attr::TypeNonNull:
3771   case attr::TypeNullable:
3772   case attr::TypeNullableResult:
3773   case attr::TypeNullUnspecified:
3774   case attr::LifetimeBound:
3775   case attr::AddressSpace:
3776     return true;
3777 
3778   // All other type attributes aren't qualifiers; they rewrite the modified
3779   // type to be a semantically different type.
3780   default:
3781     return false;
3782   }
3783 }
3784 
3785 bool AttributedType::isMSTypeSpec() const {
3786   // FIXME: Generate this with TableGen?
3787   switch (getAttrKind()) {
3788   default: return false;
3789   case attr::Ptr32:
3790   case attr::Ptr64:
3791   case attr::SPtr:
3792   case attr::UPtr:
3793     return true;
3794   }
3795   llvm_unreachable("invalid attr kind");
3796 }
3797 
3798 bool AttributedType::isWebAssemblyFuncrefSpec() const {
3799   return getAttrKind() == attr::WebAssemblyFuncref;
3800 }
3801 
3802 bool AttributedType::isCallingConv() const {
3803   // FIXME: Generate this with TableGen.
3804   switch (getAttrKind()) {
3805   default: return false;
3806   case attr::Pcs:
3807   case attr::CDecl:
3808   case attr::FastCall:
3809   case attr::StdCall:
3810   case attr::ThisCall:
3811   case attr::RegCall:
3812   case attr::SwiftCall:
3813   case attr::SwiftAsyncCall:
3814   case attr::VectorCall:
3815   case attr::AArch64VectorPcs:
3816   case attr::AArch64SVEPcs:
3817   case attr::AMDGPUKernelCall:
3818   case attr::Pascal:
3819   case attr::MSABI:
3820   case attr::SysVABI:
3821   case attr::IntelOclBicc:
3822   case attr::PreserveMost:
3823   case attr::PreserveAll:
3824     return true;
3825   }
3826   llvm_unreachable("invalid attr kind");
3827 }
3828 
3829 CXXRecordDecl *InjectedClassNameType::getDecl() const {
3830   return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
3831 }
3832 
3833 IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
3834   return isCanonicalUnqualified() ? nullptr : getDecl()->getIdentifier();
3835 }
3836 
3837 static const TemplateTypeParmDecl *getReplacedParameter(Decl *D,
3838                                                         unsigned Index) {
3839   if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(D))
3840     return TTP;
3841   return cast<TemplateTypeParmDecl>(
3842       getReplacedTemplateParameterList(D)->getParam(Index));
3843 }
3844 
3845 SubstTemplateTypeParmType::SubstTemplateTypeParmType(
3846     QualType Replacement, Decl *AssociatedDecl, unsigned Index,
3847     std::optional<unsigned> PackIndex)
3848     : Type(SubstTemplateTypeParm, Replacement.getCanonicalType(),
3849            Replacement->getDependence()),
3850       AssociatedDecl(AssociatedDecl) {
3851   SubstTemplateTypeParmTypeBits.HasNonCanonicalUnderlyingType =
3852       Replacement != getCanonicalTypeInternal();
3853   if (SubstTemplateTypeParmTypeBits.HasNonCanonicalUnderlyingType)
3854     *getTrailingObjects<QualType>() = Replacement;
3855 
3856   SubstTemplateTypeParmTypeBits.Index = Index;
3857   SubstTemplateTypeParmTypeBits.PackIndex = PackIndex ? *PackIndex + 1 : 0;
3858   assert(AssociatedDecl != nullptr);
3859 }
3860 
3861 const TemplateTypeParmDecl *
3862 SubstTemplateTypeParmType::getReplacedParameter() const {
3863   return ::getReplacedParameter(getAssociatedDecl(), getIndex());
3864 }
3865 
3866 SubstTemplateTypeParmPackType::SubstTemplateTypeParmPackType(
3867     QualType Canon, Decl *AssociatedDecl, unsigned Index, bool Final,
3868     const TemplateArgument &ArgPack)
3869     : Type(SubstTemplateTypeParmPack, Canon,
3870            TypeDependence::DependentInstantiation |
3871                TypeDependence::UnexpandedPack),
3872       Arguments(ArgPack.pack_begin()),
3873       AssociatedDeclAndFinal(AssociatedDecl, Final) {
3874   SubstTemplateTypeParmPackTypeBits.Index = Index;
3875   SubstTemplateTypeParmPackTypeBits.NumArgs = ArgPack.pack_size();
3876   assert(AssociatedDecl != nullptr);
3877 }
3878 
3879 Decl *SubstTemplateTypeParmPackType::getAssociatedDecl() const {
3880   return AssociatedDeclAndFinal.getPointer();
3881 }
3882 
3883 bool SubstTemplateTypeParmPackType::getFinal() const {
3884   return AssociatedDeclAndFinal.getInt();
3885 }
3886 
3887 const TemplateTypeParmDecl *
3888 SubstTemplateTypeParmPackType::getReplacedParameter() const {
3889   return ::getReplacedParameter(getAssociatedDecl(), getIndex());
3890 }
3891 
3892 IdentifierInfo *SubstTemplateTypeParmPackType::getIdentifier() const {
3893   return getReplacedParameter()->getIdentifier();
3894 }
3895 
3896 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const {
3897   return TemplateArgument(llvm::ArrayRef(Arguments, getNumArgs()));
3898 }
3899 
3900 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
3901   Profile(ID, getAssociatedDecl(), getIndex(), getFinal(), getArgumentPack());
3902 }
3903 
3904 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
3905                                             const Decl *AssociatedDecl,
3906                                             unsigned Index, bool Final,
3907                                             const TemplateArgument &ArgPack) {
3908   ID.AddPointer(AssociatedDecl);
3909   ID.AddInteger(Index);
3910   ID.AddBoolean(Final);
3911   ID.AddInteger(ArgPack.pack_size());
3912   for (const auto &P : ArgPack.pack_elements())
3913     ID.AddPointer(P.getAsType().getAsOpaquePtr());
3914 }
3915 
3916 bool TemplateSpecializationType::anyDependentTemplateArguments(
3917     const TemplateArgumentListInfo &Args, ArrayRef<TemplateArgument> Converted) {
3918   return anyDependentTemplateArguments(Args.arguments(), Converted);
3919 }
3920 
3921 bool TemplateSpecializationType::anyDependentTemplateArguments(
3922     ArrayRef<TemplateArgumentLoc> Args, ArrayRef<TemplateArgument> Converted) {
3923   for (const TemplateArgument &Arg : Converted)
3924     if (Arg.isDependent())
3925       return true;
3926   return false;
3927 }
3928 
3929 bool TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
3930       ArrayRef<TemplateArgumentLoc> Args) {
3931   for (const TemplateArgumentLoc &ArgLoc : Args) {
3932     if (ArgLoc.getArgument().isInstantiationDependent())
3933       return true;
3934   }
3935   return false;
3936 }
3937 
3938 TemplateSpecializationType::TemplateSpecializationType(
3939     TemplateName T, ArrayRef<TemplateArgument> Args, QualType Canon,
3940     QualType AliasedType)
3941     : Type(TemplateSpecialization, Canon.isNull() ? QualType(this, 0) : Canon,
3942            (Canon.isNull()
3943                 ? TypeDependence::DependentInstantiation
3944                 : toSemanticDependence(Canon->getDependence())) |
3945                (toTypeDependence(T.getDependence()) &
3946                 TypeDependence::UnexpandedPack)),
3947       Template(T) {
3948   TemplateSpecializationTypeBits.NumArgs = Args.size();
3949   TemplateSpecializationTypeBits.TypeAlias = !AliasedType.isNull();
3950 
3951   assert(!T.getAsDependentTemplateName() &&
3952          "Use DependentTemplateSpecializationType for dependent template-name");
3953   assert((T.getKind() == TemplateName::Template ||
3954           T.getKind() == TemplateName::SubstTemplateTemplateParm ||
3955           T.getKind() == TemplateName::SubstTemplateTemplateParmPack ||
3956           T.getKind() == TemplateName::UsingTemplate) &&
3957          "Unexpected template name for TemplateSpecializationType");
3958 
3959   auto *TemplateArgs = reinterpret_cast<TemplateArgument *>(this + 1);
3960   for (const TemplateArgument &Arg : Args) {
3961     // Update instantiation-dependent, variably-modified, and error bits.
3962     // If the canonical type exists and is non-dependent, the template
3963     // specialization type can be non-dependent even if one of the type
3964     // arguments is. Given:
3965     //   template<typename T> using U = int;
3966     // U<T> is always non-dependent, irrespective of the type T.
3967     // However, U<Ts> contains an unexpanded parameter pack, even though
3968     // its expansion (and thus its desugared type) doesn't.
3969     addDependence(toTypeDependence(Arg.getDependence()) &
3970                   ~TypeDependence::Dependent);
3971     if (Arg.getKind() == TemplateArgument::Type)
3972       addDependence(Arg.getAsType()->getDependence() &
3973                     TypeDependence::VariablyModified);
3974     new (TemplateArgs++) TemplateArgument(Arg);
3975   }
3976 
3977   // Store the aliased type if this is a type alias template specialization.
3978   if (isTypeAlias()) {
3979     auto *Begin = reinterpret_cast<TemplateArgument *>(this + 1);
3980     *reinterpret_cast<QualType *>(Begin + Args.size()) = AliasedType;
3981   }
3982 }
3983 
3984 QualType TemplateSpecializationType::getAliasedType() const {
3985   assert(isTypeAlias() && "not a type alias template specialization");
3986   return *reinterpret_cast<const QualType *>(template_arguments().end());
3987 }
3988 
3989 void TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
3990                                          const ASTContext &Ctx) {
3991   Profile(ID, Template, template_arguments(), Ctx);
3992   if (isTypeAlias())
3993     getAliasedType().Profile(ID);
3994 }
3995 
3996 void
3997 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
3998                                     TemplateName T,
3999                                     ArrayRef<TemplateArgument> Args,
4000                                     const ASTContext &Context) {
4001   T.Profile(ID);
4002   for (const TemplateArgument &Arg : Args)
4003     Arg.Profile(ID, Context);
4004 }
4005 
4006 QualType
4007 QualifierCollector::apply(const ASTContext &Context, QualType QT) const {
4008   if (!hasNonFastQualifiers())
4009     return QT.withFastQualifiers(getFastQualifiers());
4010 
4011   return Context.getQualifiedType(QT, *this);
4012 }
4013 
4014 QualType
4015 QualifierCollector::apply(const ASTContext &Context, const Type *T) const {
4016   if (!hasNonFastQualifiers())
4017     return QualType(T, getFastQualifiers());
4018 
4019   return Context.getQualifiedType(T, *this);
4020 }
4021 
4022 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
4023                                  QualType BaseType,
4024                                  ArrayRef<QualType> typeArgs,
4025                                  ArrayRef<ObjCProtocolDecl *> protocols,
4026                                  bool isKindOf) {
4027   ID.AddPointer(BaseType.getAsOpaquePtr());
4028   ID.AddInteger(typeArgs.size());
4029   for (auto typeArg : typeArgs)
4030     ID.AddPointer(typeArg.getAsOpaquePtr());
4031   ID.AddInteger(protocols.size());
4032   for (auto *proto : protocols)
4033     ID.AddPointer(proto);
4034   ID.AddBoolean(isKindOf);
4035 }
4036 
4037 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
4038   Profile(ID, getBaseType(), getTypeArgsAsWritten(),
4039           llvm::ArrayRef(qual_begin(), getNumProtocols()),
4040           isKindOfTypeAsWritten());
4041 }
4042 
4043 void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID,
4044                                 const ObjCTypeParamDecl *OTPDecl,
4045                                 QualType CanonicalType,
4046                                 ArrayRef<ObjCProtocolDecl *> protocols) {
4047   ID.AddPointer(OTPDecl);
4048   ID.AddPointer(CanonicalType.getAsOpaquePtr());
4049   ID.AddInteger(protocols.size());
4050   for (auto *proto : protocols)
4051     ID.AddPointer(proto);
4052 }
4053 
4054 void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID) {
4055   Profile(ID, getDecl(), getCanonicalTypeInternal(),
4056           llvm::ArrayRef(qual_begin(), getNumProtocols()));
4057 }
4058 
4059 namespace {
4060 
4061 /// The cached properties of a type.
4062 class CachedProperties {
4063   Linkage L;
4064   bool local;
4065 
4066 public:
4067   CachedProperties(Linkage L, bool local) : L(L), local(local) {}
4068 
4069   Linkage getLinkage() const { return L; }
4070   bool hasLocalOrUnnamedType() const { return local; }
4071 
4072   friend CachedProperties merge(CachedProperties L, CachedProperties R) {
4073     Linkage MergedLinkage = minLinkage(L.L, R.L);
4074     return CachedProperties(MergedLinkage, L.hasLocalOrUnnamedType() ||
4075                                                R.hasLocalOrUnnamedType());
4076   }
4077 };
4078 
4079 } // namespace
4080 
4081 static CachedProperties computeCachedProperties(const Type *T);
4082 
4083 namespace clang {
4084 
4085 /// The type-property cache.  This is templated so as to be
4086 /// instantiated at an internal type to prevent unnecessary symbol
4087 /// leakage.
4088 template <class Private> class TypePropertyCache {
4089 public:
4090   static CachedProperties get(QualType T) {
4091     return get(T.getTypePtr());
4092   }
4093 
4094   static CachedProperties get(const Type *T) {
4095     ensure(T);
4096     return CachedProperties(T->TypeBits.getLinkage(),
4097                             T->TypeBits.hasLocalOrUnnamedType());
4098   }
4099 
4100   static void ensure(const Type *T) {
4101     // If the cache is valid, we're okay.
4102     if (T->TypeBits.isCacheValid()) return;
4103 
4104     // If this type is non-canonical, ask its canonical type for the
4105     // relevant information.
4106     if (!T->isCanonicalUnqualified()) {
4107       const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
4108       ensure(CT);
4109       T->TypeBits.CacheValid = true;
4110       T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
4111       T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
4112       return;
4113     }
4114 
4115     // Compute the cached properties and then set the cache.
4116     CachedProperties Result = computeCachedProperties(T);
4117     T->TypeBits.CacheValid = true;
4118     T->TypeBits.CachedLinkage = Result.getLinkage();
4119     T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
4120   }
4121 };
4122 
4123 } // namespace clang
4124 
4125 // Instantiate the friend template at a private class.  In a
4126 // reasonable implementation, these symbols will be internal.
4127 // It is terrible that this is the best way to accomplish this.
4128 namespace {
4129 
4130 class Private {};
4131 
4132 } // namespace
4133 
4134 using Cache = TypePropertyCache<Private>;
4135 
4136 static CachedProperties computeCachedProperties(const Type *T) {
4137   switch (T->getTypeClass()) {
4138 #define TYPE(Class,Base)
4139 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
4140 #include "clang/AST/TypeNodes.inc"
4141     llvm_unreachable("didn't expect a non-canonical type here");
4142 
4143 #define TYPE(Class,Base)
4144 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
4145 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
4146 #include "clang/AST/TypeNodes.inc"
4147     // Treat instantiation-dependent types as external.
4148     if (!T->isInstantiationDependentType()) T->dump();
4149     assert(T->isInstantiationDependentType());
4150     return CachedProperties(ExternalLinkage, false);
4151 
4152   case Type::Auto:
4153   case Type::DeducedTemplateSpecialization:
4154     // Give non-deduced 'auto' types external linkage. We should only see them
4155     // here in error recovery.
4156     return CachedProperties(ExternalLinkage, false);
4157 
4158   case Type::BitInt:
4159   case Type::Builtin:
4160     // C++ [basic.link]p8:
4161     //   A type is said to have linkage if and only if:
4162     //     - it is a fundamental type (3.9.1); or
4163     return CachedProperties(ExternalLinkage, false);
4164 
4165   case Type::Record:
4166   case Type::Enum: {
4167     const TagDecl *Tag = cast<TagType>(T)->getDecl();
4168 
4169     // C++ [basic.link]p8:
4170     //     - it is a class or enumeration type that is named (or has a name
4171     //       for linkage purposes (7.1.3)) and the name has linkage; or
4172     //     -  it is a specialization of a class template (14); or
4173     Linkage L = Tag->getLinkageInternal();
4174     bool IsLocalOrUnnamed =
4175       Tag->getDeclContext()->isFunctionOrMethod() ||
4176       !Tag->hasNameForLinkage();
4177     return CachedProperties(L, IsLocalOrUnnamed);
4178   }
4179 
4180     // C++ [basic.link]p8:
4181     //   - it is a compound type (3.9.2) other than a class or enumeration,
4182     //     compounded exclusively from types that have linkage; or
4183   case Type::Complex:
4184     return Cache::get(cast<ComplexType>(T)->getElementType());
4185   case Type::Pointer:
4186     return Cache::get(cast<PointerType>(T)->getPointeeType());
4187   case Type::BlockPointer:
4188     return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
4189   case Type::LValueReference:
4190   case Type::RValueReference:
4191     return Cache::get(cast<ReferenceType>(T)->getPointeeType());
4192   case Type::MemberPointer: {
4193     const auto *MPT = cast<MemberPointerType>(T);
4194     return merge(Cache::get(MPT->getClass()),
4195                  Cache::get(MPT->getPointeeType()));
4196   }
4197   case Type::ConstantArray:
4198   case Type::IncompleteArray:
4199   case Type::VariableArray:
4200     return Cache::get(cast<ArrayType>(T)->getElementType());
4201   case Type::Vector:
4202   case Type::ExtVector:
4203     return Cache::get(cast<VectorType>(T)->getElementType());
4204   case Type::ConstantMatrix:
4205     return Cache::get(cast<ConstantMatrixType>(T)->getElementType());
4206   case Type::FunctionNoProto:
4207     return Cache::get(cast<FunctionType>(T)->getReturnType());
4208   case Type::FunctionProto: {
4209     const auto *FPT = cast<FunctionProtoType>(T);
4210     CachedProperties result = Cache::get(FPT->getReturnType());
4211     for (const auto &ai : FPT->param_types())
4212       result = merge(result, Cache::get(ai));
4213     return result;
4214   }
4215   case Type::ObjCInterface: {
4216     Linkage L = cast<ObjCInterfaceType>(T)->getDecl()->getLinkageInternal();
4217     return CachedProperties(L, false);
4218   }
4219   case Type::ObjCObject:
4220     return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
4221   case Type::ObjCObjectPointer:
4222     return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
4223   case Type::Atomic:
4224     return Cache::get(cast<AtomicType>(T)->getValueType());
4225   case Type::Pipe:
4226     return Cache::get(cast<PipeType>(T)->getElementType());
4227   }
4228 
4229   llvm_unreachable("unhandled type class");
4230 }
4231 
4232 /// Determine the linkage of this type.
4233 Linkage Type::getLinkage() const {
4234   Cache::ensure(this);
4235   return TypeBits.getLinkage();
4236 }
4237 
4238 bool Type::hasUnnamedOrLocalType() const {
4239   Cache::ensure(this);
4240   return TypeBits.hasLocalOrUnnamedType();
4241 }
4242 
4243 LinkageInfo LinkageComputer::computeTypeLinkageInfo(const Type *T) {
4244   switch (T->getTypeClass()) {
4245 #define TYPE(Class,Base)
4246 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
4247 #include "clang/AST/TypeNodes.inc"
4248     llvm_unreachable("didn't expect a non-canonical type here");
4249 
4250 #define TYPE(Class,Base)
4251 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
4252 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
4253 #include "clang/AST/TypeNodes.inc"
4254     // Treat instantiation-dependent types as external.
4255     assert(T->isInstantiationDependentType());
4256     return LinkageInfo::external();
4257 
4258   case Type::BitInt:
4259   case Type::Builtin:
4260     return LinkageInfo::external();
4261 
4262   case Type::Auto:
4263   case Type::DeducedTemplateSpecialization:
4264     return LinkageInfo::external();
4265 
4266   case Type::Record:
4267   case Type::Enum:
4268     return getDeclLinkageAndVisibility(cast<TagType>(T)->getDecl());
4269 
4270   case Type::Complex:
4271     return computeTypeLinkageInfo(cast<ComplexType>(T)->getElementType());
4272   case Type::Pointer:
4273     return computeTypeLinkageInfo(cast<PointerType>(T)->getPointeeType());
4274   case Type::BlockPointer:
4275     return computeTypeLinkageInfo(cast<BlockPointerType>(T)->getPointeeType());
4276   case Type::LValueReference:
4277   case Type::RValueReference:
4278     return computeTypeLinkageInfo(cast<ReferenceType>(T)->getPointeeType());
4279   case Type::MemberPointer: {
4280     const auto *MPT = cast<MemberPointerType>(T);
4281     LinkageInfo LV = computeTypeLinkageInfo(MPT->getClass());
4282     LV.merge(computeTypeLinkageInfo(MPT->getPointeeType()));
4283     return LV;
4284   }
4285   case Type::ConstantArray:
4286   case Type::IncompleteArray:
4287   case Type::VariableArray:
4288     return computeTypeLinkageInfo(cast<ArrayType>(T)->getElementType());
4289   case Type::Vector:
4290   case Type::ExtVector:
4291     return computeTypeLinkageInfo(cast<VectorType>(T)->getElementType());
4292   case Type::ConstantMatrix:
4293     return computeTypeLinkageInfo(
4294         cast<ConstantMatrixType>(T)->getElementType());
4295   case Type::FunctionNoProto:
4296     return computeTypeLinkageInfo(cast<FunctionType>(T)->getReturnType());
4297   case Type::FunctionProto: {
4298     const auto *FPT = cast<FunctionProtoType>(T);
4299     LinkageInfo LV = computeTypeLinkageInfo(FPT->getReturnType());
4300     for (const auto &ai : FPT->param_types())
4301       LV.merge(computeTypeLinkageInfo(ai));
4302     return LV;
4303   }
4304   case Type::ObjCInterface:
4305     return getDeclLinkageAndVisibility(cast<ObjCInterfaceType>(T)->getDecl());
4306   case Type::ObjCObject:
4307     return computeTypeLinkageInfo(cast<ObjCObjectType>(T)->getBaseType());
4308   case Type::ObjCObjectPointer:
4309     return computeTypeLinkageInfo(
4310         cast<ObjCObjectPointerType>(T)->getPointeeType());
4311   case Type::Atomic:
4312     return computeTypeLinkageInfo(cast<AtomicType>(T)->getValueType());
4313   case Type::Pipe:
4314     return computeTypeLinkageInfo(cast<PipeType>(T)->getElementType());
4315   }
4316 
4317   llvm_unreachable("unhandled type class");
4318 }
4319 
4320 bool Type::isLinkageValid() const {
4321   if (!TypeBits.isCacheValid())
4322     return true;
4323 
4324   Linkage L = LinkageComputer{}
4325                   .computeTypeLinkageInfo(getCanonicalTypeInternal())
4326                   .getLinkage();
4327   return L == TypeBits.getLinkage();
4328 }
4329 
4330 LinkageInfo LinkageComputer::getTypeLinkageAndVisibility(const Type *T) {
4331   if (!T->isCanonicalUnqualified())
4332     return computeTypeLinkageInfo(T->getCanonicalTypeInternal());
4333 
4334   LinkageInfo LV = computeTypeLinkageInfo(T);
4335   assert(LV.getLinkage() == T->getLinkage());
4336   return LV;
4337 }
4338 
4339 LinkageInfo Type::getLinkageAndVisibility() const {
4340   return LinkageComputer{}.getTypeLinkageAndVisibility(this);
4341 }
4342 
4343 std::optional<NullabilityKind> Type::getNullability() const {
4344   QualType Type(this, 0);
4345   while (const auto *AT = Type->getAs<AttributedType>()) {
4346     // Check whether this is an attributed type with nullability
4347     // information.
4348     if (auto Nullability = AT->getImmediateNullability())
4349       return Nullability;
4350 
4351     Type = AT->getEquivalentType();
4352   }
4353   return std::nullopt;
4354 }
4355 
4356 bool Type::canHaveNullability(bool ResultIfUnknown) const {
4357   QualType type = getCanonicalTypeInternal();
4358 
4359   switch (type->getTypeClass()) {
4360   // We'll only see canonical types here.
4361 #define NON_CANONICAL_TYPE(Class, Parent)       \
4362   case Type::Class:                             \
4363     llvm_unreachable("non-canonical type");
4364 #define TYPE(Class, Parent)
4365 #include "clang/AST/TypeNodes.inc"
4366 
4367   // Pointer types.
4368   case Type::Pointer:
4369   case Type::BlockPointer:
4370   case Type::MemberPointer:
4371   case Type::ObjCObjectPointer:
4372     return true;
4373 
4374   // Dependent types that could instantiate to pointer types.
4375   case Type::UnresolvedUsing:
4376   case Type::TypeOfExpr:
4377   case Type::TypeOf:
4378   case Type::Decltype:
4379   case Type::UnaryTransform:
4380   case Type::TemplateTypeParm:
4381   case Type::SubstTemplateTypeParmPack:
4382   case Type::DependentName:
4383   case Type::DependentTemplateSpecialization:
4384   case Type::Auto:
4385     return ResultIfUnknown;
4386 
4387   // Dependent template specializations can instantiate to pointer
4388   // types unless they're known to be specializations of a class
4389   // template.
4390   case Type::TemplateSpecialization:
4391     if (TemplateDecl *templateDecl
4392           = cast<TemplateSpecializationType>(type.getTypePtr())
4393               ->getTemplateName().getAsTemplateDecl()) {
4394       if (isa<ClassTemplateDecl>(templateDecl))
4395         return false;
4396     }
4397     return ResultIfUnknown;
4398 
4399   case Type::Builtin:
4400     switch (cast<BuiltinType>(type.getTypePtr())->getKind()) {
4401       // Signed, unsigned, and floating-point types cannot have nullability.
4402 #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
4403 #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
4404 #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
4405 #define BUILTIN_TYPE(Id, SingletonId)
4406 #include "clang/AST/BuiltinTypes.def"
4407       return false;
4408 
4409     // Dependent types that could instantiate to a pointer type.
4410     case BuiltinType::Dependent:
4411     case BuiltinType::Overload:
4412     case BuiltinType::BoundMember:
4413     case BuiltinType::PseudoObject:
4414     case BuiltinType::UnknownAny:
4415     case BuiltinType::ARCUnbridgedCast:
4416       return ResultIfUnknown;
4417 
4418     case BuiltinType::Void:
4419     case BuiltinType::ObjCId:
4420     case BuiltinType::ObjCClass:
4421     case BuiltinType::ObjCSel:
4422 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
4423     case BuiltinType::Id:
4424 #include "clang/Basic/OpenCLImageTypes.def"
4425 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
4426     case BuiltinType::Id:
4427 #include "clang/Basic/OpenCLExtensionTypes.def"
4428     case BuiltinType::OCLSampler:
4429     case BuiltinType::OCLEvent:
4430     case BuiltinType::OCLClkEvent:
4431     case BuiltinType::OCLQueue:
4432     case BuiltinType::OCLReserveID:
4433 #define SVE_TYPE(Name, Id, SingletonId) \
4434     case BuiltinType::Id:
4435 #include "clang/Basic/AArch64SVEACLETypes.def"
4436 #define PPC_VECTOR_TYPE(Name, Id, Size) \
4437     case BuiltinType::Id:
4438 #include "clang/Basic/PPCTypes.def"
4439 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
4440 #include "clang/Basic/RISCVVTypes.def"
4441 #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
4442 #include "clang/Basic/WebAssemblyReferenceTypes.def"
4443     case BuiltinType::BuiltinFn:
4444     case BuiltinType::NullPtr:
4445     case BuiltinType::IncompleteMatrixIdx:
4446     case BuiltinType::OMPArraySection:
4447     case BuiltinType::OMPArrayShaping:
4448     case BuiltinType::OMPIterator:
4449       return false;
4450     }
4451     llvm_unreachable("unknown builtin type");
4452 
4453   // Non-pointer types.
4454   case Type::Complex:
4455   case Type::LValueReference:
4456   case Type::RValueReference:
4457   case Type::ConstantArray:
4458   case Type::IncompleteArray:
4459   case Type::VariableArray:
4460   case Type::DependentSizedArray:
4461   case Type::DependentVector:
4462   case Type::DependentSizedExtVector:
4463   case Type::Vector:
4464   case Type::ExtVector:
4465   case Type::ConstantMatrix:
4466   case Type::DependentSizedMatrix:
4467   case Type::DependentAddressSpace:
4468   case Type::FunctionProto:
4469   case Type::FunctionNoProto:
4470   case Type::Record:
4471   case Type::DeducedTemplateSpecialization:
4472   case Type::Enum:
4473   case Type::InjectedClassName:
4474   case Type::PackExpansion:
4475   case Type::ObjCObject:
4476   case Type::ObjCInterface:
4477   case Type::Atomic:
4478   case Type::Pipe:
4479   case Type::BitInt:
4480   case Type::DependentBitInt:
4481     return false;
4482   }
4483   llvm_unreachable("bad type kind!");
4484 }
4485 
4486 std::optional<NullabilityKind> AttributedType::getImmediateNullability() const {
4487   if (getAttrKind() == attr::TypeNonNull)
4488     return NullabilityKind::NonNull;
4489   if (getAttrKind() == attr::TypeNullable)
4490     return NullabilityKind::Nullable;
4491   if (getAttrKind() == attr::TypeNullUnspecified)
4492     return NullabilityKind::Unspecified;
4493   if (getAttrKind() == attr::TypeNullableResult)
4494     return NullabilityKind::NullableResult;
4495   return std::nullopt;
4496 }
4497 
4498 std::optional<NullabilityKind>
4499 AttributedType::stripOuterNullability(QualType &T) {
4500   QualType AttrTy = T;
4501   if (auto MacroTy = dyn_cast<MacroQualifiedType>(T))
4502     AttrTy = MacroTy->getUnderlyingType();
4503 
4504   if (auto attributed = dyn_cast<AttributedType>(AttrTy)) {
4505     if (auto nullability = attributed->getImmediateNullability()) {
4506       T = attributed->getModifiedType();
4507       return nullability;
4508     }
4509   }
4510 
4511   return std::nullopt;
4512 }
4513 
4514 bool Type::isBlockCompatibleObjCPointerType(ASTContext &ctx) const {
4515   const auto *objcPtr = getAs<ObjCObjectPointerType>();
4516   if (!objcPtr)
4517     return false;
4518 
4519   if (objcPtr->isObjCIdType()) {
4520     // id is always okay.
4521     return true;
4522   }
4523 
4524   // Blocks are NSObjects.
4525   if (ObjCInterfaceDecl *iface = objcPtr->getInterfaceDecl()) {
4526     if (iface->getIdentifier() != ctx.getNSObjectName())
4527       return false;
4528 
4529     // Continue to check qualifiers, below.
4530   } else if (objcPtr->isObjCQualifiedIdType()) {
4531     // Continue to check qualifiers, below.
4532   } else {
4533     return false;
4534   }
4535 
4536   // Check protocol qualifiers.
4537   for (ObjCProtocolDecl *proto : objcPtr->quals()) {
4538     // Blocks conform to NSObject and NSCopying.
4539     if (proto->getIdentifier() != ctx.getNSObjectName() &&
4540         proto->getIdentifier() != ctx.getNSCopyingName())
4541       return false;
4542   }
4543 
4544   return true;
4545 }
4546 
4547 Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const {
4548   if (isObjCARCImplicitlyUnretainedType())
4549     return Qualifiers::OCL_ExplicitNone;
4550   return Qualifiers::OCL_Strong;
4551 }
4552 
4553 bool Type::isObjCARCImplicitlyUnretainedType() const {
4554   assert(isObjCLifetimeType() &&
4555          "cannot query implicit lifetime for non-inferrable type");
4556 
4557   const Type *canon = getCanonicalTypeInternal().getTypePtr();
4558 
4559   // Walk down to the base type.  We don't care about qualifiers for this.
4560   while (const auto *array = dyn_cast<ArrayType>(canon))
4561     canon = array->getElementType().getTypePtr();
4562 
4563   if (const auto *opt = dyn_cast<ObjCObjectPointerType>(canon)) {
4564     // Class and Class<Protocol> don't require retention.
4565     if (opt->getObjectType()->isObjCClass())
4566       return true;
4567   }
4568 
4569   return false;
4570 }
4571 
4572 bool Type::isObjCNSObjectType() const {
4573   if (const auto *typedefType = getAs<TypedefType>())
4574     return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>();
4575   return false;
4576 }
4577 
4578 bool Type::isObjCIndependentClassType() const {
4579   if (const auto *typedefType = getAs<TypedefType>())
4580     return typedefType->getDecl()->hasAttr<ObjCIndependentClassAttr>();
4581   return false;
4582 }
4583 
4584 bool Type::isObjCRetainableType() const {
4585   return isObjCObjectPointerType() ||
4586          isBlockPointerType() ||
4587          isObjCNSObjectType();
4588 }
4589 
4590 bool Type::isObjCIndirectLifetimeType() const {
4591   if (isObjCLifetimeType())
4592     return true;
4593   if (const auto *OPT = getAs<PointerType>())
4594     return OPT->getPointeeType()->isObjCIndirectLifetimeType();
4595   if (const auto *Ref = getAs<ReferenceType>())
4596     return Ref->getPointeeType()->isObjCIndirectLifetimeType();
4597   if (const auto *MemPtr = getAs<MemberPointerType>())
4598     return MemPtr->getPointeeType()->isObjCIndirectLifetimeType();
4599   return false;
4600 }
4601 
4602 /// Returns true if objects of this type have lifetime semantics under
4603 /// ARC.
4604 bool Type::isObjCLifetimeType() const {
4605   const Type *type = this;
4606   while (const ArrayType *array = type->getAsArrayTypeUnsafe())
4607     type = array->getElementType().getTypePtr();
4608   return type->isObjCRetainableType();
4609 }
4610 
4611 /// Determine whether the given type T is a "bridgable" Objective-C type,
4612 /// which is either an Objective-C object pointer type or an
4613 bool Type::isObjCARCBridgableType() const {
4614   return isObjCObjectPointerType() || isBlockPointerType();
4615 }
4616 
4617 /// Determine whether the given type T is a "bridgeable" C type.
4618 bool Type::isCARCBridgableType() const {
4619   const auto *Pointer = getAs<PointerType>();
4620   if (!Pointer)
4621     return false;
4622 
4623   QualType Pointee = Pointer->getPointeeType();
4624   return Pointee->isVoidType() || Pointee->isRecordType();
4625 }
4626 
4627 /// Check if the specified type is the CUDA device builtin surface type.
4628 bool Type::isCUDADeviceBuiltinSurfaceType() const {
4629   if (const auto *RT = getAs<RecordType>())
4630     return RT->getDecl()->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>();
4631   return false;
4632 }
4633 
4634 /// Check if the specified type is the CUDA device builtin texture type.
4635 bool Type::isCUDADeviceBuiltinTextureType() const {
4636   if (const auto *RT = getAs<RecordType>())
4637     return RT->getDecl()->hasAttr<CUDADeviceBuiltinTextureTypeAttr>();
4638   return false;
4639 }
4640 
4641 bool Type::hasSizedVLAType() const {
4642   if (!isVariablyModifiedType()) return false;
4643 
4644   if (const auto *ptr = getAs<PointerType>())
4645     return ptr->getPointeeType()->hasSizedVLAType();
4646   if (const auto *ref = getAs<ReferenceType>())
4647     return ref->getPointeeType()->hasSizedVLAType();
4648   if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
4649     if (isa<VariableArrayType>(arr) &&
4650         cast<VariableArrayType>(arr)->getSizeExpr())
4651       return true;
4652 
4653     return arr->getElementType()->hasSizedVLAType();
4654   }
4655 
4656   return false;
4657 }
4658 
4659 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
4660   switch (type.getObjCLifetime()) {
4661   case Qualifiers::OCL_None:
4662   case Qualifiers::OCL_ExplicitNone:
4663   case Qualifiers::OCL_Autoreleasing:
4664     break;
4665 
4666   case Qualifiers::OCL_Strong:
4667     return DK_objc_strong_lifetime;
4668   case Qualifiers::OCL_Weak:
4669     return DK_objc_weak_lifetime;
4670   }
4671 
4672   if (const auto *RT =
4673           type->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
4674     const RecordDecl *RD = RT->getDecl();
4675     if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4676       /// Check if this is a C++ object with a non-trivial destructor.
4677       if (CXXRD->hasDefinition() && !CXXRD->hasTrivialDestructor())
4678         return DK_cxx_destructor;
4679     } else {
4680       /// Check if this is a C struct that is non-trivial to destroy or an array
4681       /// that contains such a struct.
4682       if (RD->isNonTrivialToPrimitiveDestroy())
4683         return DK_nontrivial_c_struct;
4684     }
4685   }
4686 
4687   return DK_none;
4688 }
4689 
4690 CXXRecordDecl *MemberPointerType::getMostRecentCXXRecordDecl() const {
4691   return getClass()->getAsCXXRecordDecl()->getMostRecentNonInjectedDecl();
4692 }
4693 
4694 void clang::FixedPointValueToString(SmallVectorImpl<char> &Str,
4695                                     llvm::APSInt Val, unsigned Scale) {
4696   llvm::FixedPointSemantics FXSema(Val.getBitWidth(), Scale, Val.isSigned(),
4697                                    /*IsSaturated=*/false,
4698                                    /*HasUnsignedPadding=*/false);
4699   llvm::APFixedPoint(Val, FXSema).toString(Str);
4700 }
4701 
4702 AutoType::AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
4703                    TypeDependence ExtraDependence, QualType Canon,
4704                    ConceptDecl *TypeConstraintConcept,
4705                    ArrayRef<TemplateArgument> TypeConstraintArgs)
4706     : DeducedType(Auto, DeducedAsType, ExtraDependence, Canon) {
4707   AutoTypeBits.Keyword = (unsigned)Keyword;
4708   AutoTypeBits.NumArgs = TypeConstraintArgs.size();
4709   this->TypeConstraintConcept = TypeConstraintConcept;
4710   assert(TypeConstraintConcept || AutoTypeBits.NumArgs == 0);
4711   if (TypeConstraintConcept) {
4712     auto *ArgBuffer =
4713         const_cast<TemplateArgument *>(getTypeConstraintArguments().data());
4714     for (const TemplateArgument &Arg : TypeConstraintArgs) {
4715       // We only syntactically depend on the constraint arguments. They don't
4716       // affect the deduced type, only its validity.
4717       addDependence(
4718           toSyntacticDependence(toTypeDependence(Arg.getDependence())));
4719 
4720       new (ArgBuffer++) TemplateArgument(Arg);
4721     }
4722   }
4723 }
4724 
4725 void AutoType::Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4726                       QualType Deduced, AutoTypeKeyword Keyword,
4727                       bool IsDependent, ConceptDecl *CD,
4728                       ArrayRef<TemplateArgument> Arguments) {
4729   ID.AddPointer(Deduced.getAsOpaquePtr());
4730   ID.AddInteger((unsigned)Keyword);
4731   ID.AddBoolean(IsDependent);
4732   ID.AddPointer(CD);
4733   for (const TemplateArgument &Arg : Arguments)
4734     Arg.Profile(ID, Context);
4735 }
4736 
4737 void AutoType::Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
4738   Profile(ID, Context, getDeducedType(), getKeyword(), isDependentType(),
4739           getTypeConstraintConcept(), getTypeConstraintArguments());
4740 }
4741