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