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