xref: /llvm-project-15.0.7/clang/lib/AST/Type.cpp (revision bf02bcff)
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   if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
2142     // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
2143     // If a body isn't seen by the time we get here, return false.
2144     //
2145     // C++0x: Enumerations are not arithmetic types. For now, just return
2146     // false for scoped enumerations since that will disable any
2147     // unwanted implicit conversions.
2148     return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete();
2149   return isa<ComplexType>(CanonicalType) || isExtIntType();
2150 }
2151 
2152 Type::ScalarTypeKind Type::getScalarTypeKind() const {
2153   assert(isScalarType());
2154 
2155   const Type *T = CanonicalType.getTypePtr();
2156   if (const auto *BT = dyn_cast<BuiltinType>(T)) {
2157     if (BT->getKind() == BuiltinType::Bool) return STK_Bool;
2158     if (BT->getKind() == BuiltinType::NullPtr) return STK_CPointer;
2159     if (BT->isInteger()) return STK_Integral;
2160     if (BT->isFloatingPoint()) return STK_Floating;
2161     if (BT->isFixedPointType()) return STK_FixedPoint;
2162     llvm_unreachable("unknown scalar builtin type");
2163   } else if (isa<PointerType>(T)) {
2164     return STK_CPointer;
2165   } else if (isa<BlockPointerType>(T)) {
2166     return STK_BlockPointer;
2167   } else if (isa<ObjCObjectPointerType>(T)) {
2168     return STK_ObjCObjectPointer;
2169   } else if (isa<MemberPointerType>(T)) {
2170     return STK_MemberPointer;
2171   } else if (isa<EnumType>(T)) {
2172     assert(cast<EnumType>(T)->getDecl()->isComplete());
2173     return STK_Integral;
2174   } else if (const auto *CT = dyn_cast<ComplexType>(T)) {
2175     if (CT->getElementType()->isRealFloatingType())
2176       return STK_FloatingComplex;
2177     return STK_IntegralComplex;
2178   } else if (isExtIntType()) {
2179     return STK_Integral;
2180   }
2181 
2182   llvm_unreachable("unknown scalar type");
2183 }
2184 
2185 /// Determines whether the type is a C++ aggregate type or C
2186 /// aggregate or union type.
2187 ///
2188 /// An aggregate type is an array or a class type (struct, union, or
2189 /// class) that has no user-declared constructors, no private or
2190 /// protected non-static data members, no base classes, and no virtual
2191 /// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
2192 /// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
2193 /// includes union types.
2194 bool Type::isAggregateType() const {
2195   if (const auto *Record = dyn_cast<RecordType>(CanonicalType)) {
2196     if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
2197       return ClassDecl->isAggregate();
2198 
2199     return true;
2200   }
2201 
2202   return isa<ArrayType>(CanonicalType);
2203 }
2204 
2205 /// isConstantSizeType - Return true if this is not a variable sized type,
2206 /// according to the rules of C99 6.7.5p3.  It is not legal to call this on
2207 /// incomplete types or dependent types.
2208 bool Type::isConstantSizeType() const {
2209   assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
2210   assert(!isDependentType() && "This doesn't make sense for dependent types");
2211   // The VAT must have a size, as it is known to be complete.
2212   return !isa<VariableArrayType>(CanonicalType);
2213 }
2214 
2215 /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
2216 /// - a type that can describe objects, but which lacks information needed to
2217 /// determine its size.
2218 bool Type::isIncompleteType(NamedDecl **Def) const {
2219   if (Def)
2220     *Def = nullptr;
2221 
2222   switch (CanonicalType->getTypeClass()) {
2223   default: return false;
2224   case Builtin:
2225     // Void is the only incomplete builtin type.  Per C99 6.2.5p19, it can never
2226     // be completed.
2227     return isVoidType();
2228   case Enum: {
2229     EnumDecl *EnumD = cast<EnumType>(CanonicalType)->getDecl();
2230     if (Def)
2231       *Def = EnumD;
2232     return !EnumD->isComplete();
2233   }
2234   case Record: {
2235     // A tagged type (struct/union/enum/class) is incomplete if the decl is a
2236     // forward declaration, but not a full definition (C99 6.2.5p22).
2237     RecordDecl *Rec = cast<RecordType>(CanonicalType)->getDecl();
2238     if (Def)
2239       *Def = Rec;
2240     return !Rec->isCompleteDefinition();
2241   }
2242   case ConstantArray:
2243     // An array is incomplete if its element type is incomplete
2244     // (C++ [dcl.array]p1).
2245     // We don't handle variable arrays (they're not allowed in C++) or
2246     // dependent-sized arrays (dependent types are never treated as incomplete).
2247     return cast<ArrayType>(CanonicalType)->getElementType()
2248              ->isIncompleteType(Def);
2249   case IncompleteArray:
2250     // An array of unknown size is an incomplete type (C99 6.2.5p22).
2251     return true;
2252   case MemberPointer: {
2253     // Member pointers in the MS ABI have special behavior in
2254     // RequireCompleteType: they attach a MSInheritanceAttr to the CXXRecordDecl
2255     // to indicate which inheritance model to use.
2256     auto *MPTy = cast<MemberPointerType>(CanonicalType);
2257     const Type *ClassTy = MPTy->getClass();
2258     // Member pointers with dependent class types don't get special treatment.
2259     if (ClassTy->isDependentType())
2260       return false;
2261     const CXXRecordDecl *RD = ClassTy->getAsCXXRecordDecl();
2262     ASTContext &Context = RD->getASTContext();
2263     // Member pointers not in the MS ABI don't get special treatment.
2264     if (!Context.getTargetInfo().getCXXABI().isMicrosoft())
2265       return false;
2266     // The inheritance attribute might only be present on the most recent
2267     // CXXRecordDecl, use that one.
2268     RD = RD->getMostRecentNonInjectedDecl();
2269     // Nothing interesting to do if the inheritance attribute is already set.
2270     if (RD->hasAttr<MSInheritanceAttr>())
2271       return false;
2272     return true;
2273   }
2274   case ObjCObject:
2275     return cast<ObjCObjectType>(CanonicalType)->getBaseType()
2276              ->isIncompleteType(Def);
2277   case ObjCInterface: {
2278     // ObjC interfaces are incomplete if they are @class, not @interface.
2279     ObjCInterfaceDecl *Interface
2280       = cast<ObjCInterfaceType>(CanonicalType)->getDecl();
2281     if (Def)
2282       *Def = Interface;
2283     return !Interface->hasDefinition();
2284   }
2285   }
2286 }
2287 
2288 bool Type::isSizelessBuiltinType() const {
2289   if (const BuiltinType *BT = getAs<BuiltinType>()) {
2290     switch (BT->getKind()) {
2291       // SVE Types
2292 #define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2293 #include "clang/Basic/AArch64SVEACLETypes.def"
2294       return true;
2295     default:
2296       return false;
2297     }
2298   }
2299   return false;
2300 }
2301 
2302 bool Type::isSizelessType() const { return isSizelessBuiltinType(); }
2303 
2304 bool QualType::isPODType(const ASTContext &Context) const {
2305   // C++11 has a more relaxed definition of POD.
2306   if (Context.getLangOpts().CPlusPlus11)
2307     return isCXX11PODType(Context);
2308 
2309   return isCXX98PODType(Context);
2310 }
2311 
2312 bool QualType::isCXX98PODType(const ASTContext &Context) const {
2313   // The compiler shouldn't query this for incomplete types, but the user might.
2314   // We return false for that case. Except for incomplete arrays of PODs, which
2315   // are PODs according to the standard.
2316   if (isNull())
2317     return false;
2318 
2319   if ((*this)->isIncompleteArrayType())
2320     return Context.getBaseElementType(*this).isCXX98PODType(Context);
2321 
2322   if ((*this)->isIncompleteType())
2323     return false;
2324 
2325   if (hasNonTrivialObjCLifetime())
2326     return false;
2327 
2328   QualType CanonicalType = getTypePtr()->CanonicalType;
2329   switch (CanonicalType->getTypeClass()) {
2330     // Everything not explicitly mentioned is not POD.
2331   default: return false;
2332   case Type::VariableArray:
2333   case Type::ConstantArray:
2334     // IncompleteArray is handled above.
2335     return Context.getBaseElementType(*this).isCXX98PODType(Context);
2336 
2337   case Type::ObjCObjectPointer:
2338   case Type::BlockPointer:
2339   case Type::Builtin:
2340   case Type::Complex:
2341   case Type::Pointer:
2342   case Type::MemberPointer:
2343   case Type::Vector:
2344   case Type::ExtVector:
2345   case Type::ExtInt:
2346     return true;
2347 
2348   case Type::Enum:
2349     return true;
2350 
2351   case Type::Record:
2352     if (const auto *ClassDecl =
2353             dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
2354       return ClassDecl->isPOD();
2355 
2356     // C struct/union is POD.
2357     return true;
2358   }
2359 }
2360 
2361 bool QualType::isTrivialType(const ASTContext &Context) const {
2362   // The compiler shouldn't query this for incomplete types, but the user might.
2363   // We return false for that case. Except for incomplete arrays of PODs, which
2364   // are PODs according to the standard.
2365   if (isNull())
2366     return false;
2367 
2368   if ((*this)->isArrayType())
2369     return Context.getBaseElementType(*this).isTrivialType(Context);
2370 
2371   if ((*this)->isSizelessBuiltinType())
2372     return true;
2373 
2374   // Return false for incomplete types after skipping any incomplete array
2375   // types which are expressly allowed by the standard and thus our API.
2376   if ((*this)->isIncompleteType())
2377     return false;
2378 
2379   if (hasNonTrivialObjCLifetime())
2380     return false;
2381 
2382   QualType CanonicalType = getTypePtr()->CanonicalType;
2383   if (CanonicalType->isDependentType())
2384     return false;
2385 
2386   // C++0x [basic.types]p9:
2387   //   Scalar types, trivial class types, arrays of such types, and
2388   //   cv-qualified versions of these types are collectively called trivial
2389   //   types.
2390 
2391   // As an extension, Clang treats vector types as Scalar types.
2392   if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
2393     return true;
2394   if (const auto *RT = CanonicalType->getAs<RecordType>()) {
2395     if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2396       // C++11 [class]p6:
2397       //   A trivial class is a class that has a default constructor,
2398       //   has no non-trivial default constructors, and is trivially
2399       //   copyable.
2400       return ClassDecl->hasDefaultConstructor() &&
2401              !ClassDecl->hasNonTrivialDefaultConstructor() &&
2402              ClassDecl->isTriviallyCopyable();
2403     }
2404 
2405     return true;
2406   }
2407 
2408   // No other types can match.
2409   return false;
2410 }
2411 
2412 bool QualType::isTriviallyCopyableType(const ASTContext &Context) const {
2413   if ((*this)->isArrayType())
2414     return Context.getBaseElementType(*this).isTriviallyCopyableType(Context);
2415 
2416   if (hasNonTrivialObjCLifetime())
2417     return false;
2418 
2419   // C++11 [basic.types]p9 - See Core 2094
2420   //   Scalar types, trivially copyable class types, arrays of such types, and
2421   //   cv-qualified versions of these types are collectively
2422   //   called trivially copyable types.
2423 
2424   QualType CanonicalType = getCanonicalType();
2425   if (CanonicalType->isDependentType())
2426     return false;
2427 
2428   if (CanonicalType->isSizelessBuiltinType())
2429     return true;
2430 
2431   // Return false for incomplete types after skipping any incomplete array types
2432   // which are expressly allowed by the standard and thus our API.
2433   if (CanonicalType->isIncompleteType())
2434     return false;
2435 
2436   // As an extension, Clang treats vector types as Scalar types.
2437   if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
2438     return true;
2439 
2440   if (const auto *RT = CanonicalType->getAs<RecordType>()) {
2441     if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2442       if (!ClassDecl->isTriviallyCopyable()) return false;
2443     }
2444 
2445     return true;
2446   }
2447 
2448   // No other types can match.
2449   return false;
2450 }
2451 
2452 bool QualType::isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const {
2453   return !Context.getLangOpts().ObjCAutoRefCount &&
2454          Context.getLangOpts().ObjCWeak &&
2455          getObjCLifetime() != Qualifiers::OCL_Weak;
2456 }
2457 
2458 bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD) {
2459   return RD->hasNonTrivialToPrimitiveDefaultInitializeCUnion();
2460 }
2461 
2462 bool QualType::hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD) {
2463   return RD->hasNonTrivialToPrimitiveDestructCUnion();
2464 }
2465 
2466 bool QualType::hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD) {
2467   return RD->hasNonTrivialToPrimitiveCopyCUnion();
2468 }
2469 
2470 QualType::PrimitiveDefaultInitializeKind
2471 QualType::isNonTrivialToPrimitiveDefaultInitialize() const {
2472   if (const auto *RT =
2473           getTypePtr()->getBaseElementTypeUnsafe()->getAs<RecordType>())
2474     if (RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize())
2475       return PDIK_Struct;
2476 
2477   switch (getQualifiers().getObjCLifetime()) {
2478   case Qualifiers::OCL_Strong:
2479     return PDIK_ARCStrong;
2480   case Qualifiers::OCL_Weak:
2481     return PDIK_ARCWeak;
2482   default:
2483     return PDIK_Trivial;
2484   }
2485 }
2486 
2487 QualType::PrimitiveCopyKind QualType::isNonTrivialToPrimitiveCopy() const {
2488   if (const auto *RT =
2489           getTypePtr()->getBaseElementTypeUnsafe()->getAs<RecordType>())
2490     if (RT->getDecl()->isNonTrivialToPrimitiveCopy())
2491       return PCK_Struct;
2492 
2493   Qualifiers Qs = getQualifiers();
2494   switch (Qs.getObjCLifetime()) {
2495   case Qualifiers::OCL_Strong:
2496     return PCK_ARCStrong;
2497   case Qualifiers::OCL_Weak:
2498     return PCK_ARCWeak;
2499   default:
2500     return Qs.hasVolatile() ? PCK_VolatileTrivial : PCK_Trivial;
2501   }
2502 }
2503 
2504 QualType::PrimitiveCopyKind
2505 QualType::isNonTrivialToPrimitiveDestructiveMove() const {
2506   return isNonTrivialToPrimitiveCopy();
2507 }
2508 
2509 bool Type::isLiteralType(const ASTContext &Ctx) const {
2510   if (isDependentType())
2511     return false;
2512 
2513   // C++1y [basic.types]p10:
2514   //   A type is a literal type if it is:
2515   //   -- cv void; or
2516   if (Ctx.getLangOpts().CPlusPlus14 && isVoidType())
2517     return true;
2518 
2519   // C++11 [basic.types]p10:
2520   //   A type is a literal type if it is:
2521   //   [...]
2522   //   -- an array of literal type other than an array of runtime bound; or
2523   if (isVariableArrayType())
2524     return false;
2525   const Type *BaseTy = getBaseElementTypeUnsafe();
2526   assert(BaseTy && "NULL element type");
2527 
2528   // Return false for incomplete types after skipping any incomplete array
2529   // types; those are expressly allowed by the standard and thus our API.
2530   if (BaseTy->isIncompleteType())
2531     return false;
2532 
2533   // C++11 [basic.types]p10:
2534   //   A type is a literal type if it is:
2535   //    -- a scalar type; or
2536   // As an extension, Clang treats vector types and complex types as
2537   // literal types.
2538   if (BaseTy->isScalarType() || BaseTy->isVectorType() ||
2539       BaseTy->isAnyComplexType())
2540     return true;
2541   //    -- a reference type; or
2542   if (BaseTy->isReferenceType())
2543     return true;
2544   //    -- a class type that has all of the following properties:
2545   if (const auto *RT = BaseTy->getAs<RecordType>()) {
2546     //    -- a trivial destructor,
2547     //    -- every constructor call and full-expression in the
2548     //       brace-or-equal-initializers for non-static data members (if any)
2549     //       is a constant expression,
2550     //    -- it is an aggregate type or has at least one constexpr
2551     //       constructor or constructor template that is not a copy or move
2552     //       constructor, and
2553     //    -- all non-static data members and base classes of literal types
2554     //
2555     // We resolve DR1361 by ignoring the second bullet.
2556     if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2557       return ClassDecl->isLiteral();
2558 
2559     return true;
2560   }
2561 
2562   // We treat _Atomic T as a literal type if T is a literal type.
2563   if (const auto *AT = BaseTy->getAs<AtomicType>())
2564     return AT->getValueType()->isLiteralType(Ctx);
2565 
2566   // If this type hasn't been deduced yet, then conservatively assume that
2567   // it'll work out to be a literal type.
2568   if (isa<AutoType>(BaseTy->getCanonicalTypeInternal()))
2569     return true;
2570 
2571   return false;
2572 }
2573 
2574 bool Type::isStandardLayoutType() const {
2575   if (isDependentType())
2576     return false;
2577 
2578   // C++0x [basic.types]p9:
2579   //   Scalar types, standard-layout class types, arrays of such types, and
2580   //   cv-qualified versions of these types are collectively called
2581   //   standard-layout types.
2582   const Type *BaseTy = getBaseElementTypeUnsafe();
2583   assert(BaseTy && "NULL element type");
2584 
2585   // Return false for incomplete types after skipping any incomplete array
2586   // types which are expressly allowed by the standard and thus our API.
2587   if (BaseTy->isIncompleteType())
2588     return false;
2589 
2590   // As an extension, Clang treats vector types as Scalar types.
2591   if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
2592   if (const auto *RT = BaseTy->getAs<RecordType>()) {
2593     if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2594       if (!ClassDecl->isStandardLayout())
2595         return false;
2596 
2597     // Default to 'true' for non-C++ class types.
2598     // FIXME: This is a bit dubious, but plain C structs should trivially meet
2599     // all the requirements of standard layout classes.
2600     return true;
2601   }
2602 
2603   // No other types can match.
2604   return false;
2605 }
2606 
2607 // This is effectively the intersection of isTrivialType and
2608 // isStandardLayoutType. We implement it directly to avoid redundant
2609 // conversions from a type to a CXXRecordDecl.
2610 bool QualType::isCXX11PODType(const ASTContext &Context) const {
2611   const Type *ty = getTypePtr();
2612   if (ty->isDependentType())
2613     return false;
2614 
2615   if (hasNonTrivialObjCLifetime())
2616     return false;
2617 
2618   // C++11 [basic.types]p9:
2619   //   Scalar types, POD classes, arrays of such types, and cv-qualified
2620   //   versions of these types are collectively called trivial types.
2621   const Type *BaseTy = ty->getBaseElementTypeUnsafe();
2622   assert(BaseTy && "NULL element type");
2623 
2624   if (BaseTy->isSizelessBuiltinType())
2625     return true;
2626 
2627   // Return false for incomplete types after skipping any incomplete array
2628   // types which are expressly allowed by the standard and thus our API.
2629   if (BaseTy->isIncompleteType())
2630     return false;
2631 
2632   // As an extension, Clang treats vector types as Scalar types.
2633   if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
2634   if (const auto *RT = BaseTy->getAs<RecordType>()) {
2635     if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2636       // C++11 [class]p10:
2637       //   A POD struct is a non-union class that is both a trivial class [...]
2638       if (!ClassDecl->isTrivial()) return false;
2639 
2640       // C++11 [class]p10:
2641       //   A POD struct is a non-union class that is both a trivial class and
2642       //   a standard-layout class [...]
2643       if (!ClassDecl->isStandardLayout()) return false;
2644 
2645       // C++11 [class]p10:
2646       //   A POD struct is a non-union class that is both a trivial class and
2647       //   a standard-layout class, and has no non-static data members of type
2648       //   non-POD struct, non-POD union (or array of such types). [...]
2649       //
2650       // We don't directly query the recursive aspect as the requirements for
2651       // both standard-layout classes and trivial classes apply recursively
2652       // already.
2653     }
2654 
2655     return true;
2656   }
2657 
2658   // No other types can match.
2659   return false;
2660 }
2661 
2662 bool Type::isNothrowT() const {
2663   if (const auto *RD = getAsCXXRecordDecl()) {
2664     IdentifierInfo *II = RD->getIdentifier();
2665     if (II && II->isStr("nothrow_t") && RD->isInStdNamespace())
2666       return true;
2667   }
2668   return false;
2669 }
2670 
2671 bool Type::isAlignValT() const {
2672   if (const auto *ET = getAs<EnumType>()) {
2673     IdentifierInfo *II = ET->getDecl()->getIdentifier();
2674     if (II && II->isStr("align_val_t") && ET->getDecl()->isInStdNamespace())
2675       return true;
2676   }
2677   return false;
2678 }
2679 
2680 bool Type::isStdByteType() const {
2681   if (const auto *ET = getAs<EnumType>()) {
2682     IdentifierInfo *II = ET->getDecl()->getIdentifier();
2683     if (II && II->isStr("byte") && ET->getDecl()->isInStdNamespace())
2684       return true;
2685   }
2686   return false;
2687 }
2688 
2689 bool Type::isPromotableIntegerType() const {
2690   if (const auto *BT = getAs<BuiltinType>())
2691     switch (BT->getKind()) {
2692     case BuiltinType::Bool:
2693     case BuiltinType::Char_S:
2694     case BuiltinType::Char_U:
2695     case BuiltinType::SChar:
2696     case BuiltinType::UChar:
2697     case BuiltinType::Short:
2698     case BuiltinType::UShort:
2699     case BuiltinType::WChar_S:
2700     case BuiltinType::WChar_U:
2701     case BuiltinType::Char8:
2702     case BuiltinType::Char16:
2703     case BuiltinType::Char32:
2704       return true;
2705     default:
2706       return false;
2707     }
2708 
2709   // Enumerated types are promotable to their compatible integer types
2710   // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
2711   if (const auto *ET = getAs<EnumType>()){
2712     if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull()
2713         || ET->getDecl()->isScoped())
2714       return false;
2715 
2716     return true;
2717   }
2718 
2719   return false;
2720 }
2721 
2722 bool Type::isSpecifierType() const {
2723   // Note that this intentionally does not use the canonical type.
2724   switch (getTypeClass()) {
2725   case Builtin:
2726   case Record:
2727   case Enum:
2728   case Typedef:
2729   case Complex:
2730   case TypeOfExpr:
2731   case TypeOf:
2732   case TemplateTypeParm:
2733   case SubstTemplateTypeParm:
2734   case TemplateSpecialization:
2735   case Elaborated:
2736   case DependentName:
2737   case DependentTemplateSpecialization:
2738   case ObjCInterface:
2739   case ObjCObject:
2740   case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers
2741     return true;
2742   default:
2743     return false;
2744   }
2745 }
2746 
2747 ElaboratedTypeKeyword
2748 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) {
2749   switch (TypeSpec) {
2750   default: return ETK_None;
2751   case TST_typename: return ETK_Typename;
2752   case TST_class: return ETK_Class;
2753   case TST_struct: return ETK_Struct;
2754   case TST_interface: return ETK_Interface;
2755   case TST_union: return ETK_Union;
2756   case TST_enum: return ETK_Enum;
2757   }
2758 }
2759 
2760 TagTypeKind
2761 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
2762   switch(TypeSpec) {
2763   case TST_class: return TTK_Class;
2764   case TST_struct: return TTK_Struct;
2765   case TST_interface: return TTK_Interface;
2766   case TST_union: return TTK_Union;
2767   case TST_enum: return TTK_Enum;
2768   }
2769 
2770   llvm_unreachable("Type specifier is not a tag type kind.");
2771 }
2772 
2773 ElaboratedTypeKeyword
2774 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) {
2775   switch (Kind) {
2776   case TTK_Class: return ETK_Class;
2777   case TTK_Struct: return ETK_Struct;
2778   case TTK_Interface: return ETK_Interface;
2779   case TTK_Union: return ETK_Union;
2780   case TTK_Enum: return ETK_Enum;
2781   }
2782   llvm_unreachable("Unknown tag type kind.");
2783 }
2784 
2785 TagTypeKind
2786 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
2787   switch (Keyword) {
2788   case ETK_Class: return TTK_Class;
2789   case ETK_Struct: return TTK_Struct;
2790   case ETK_Interface: return TTK_Interface;
2791   case ETK_Union: return TTK_Union;
2792   case ETK_Enum: return TTK_Enum;
2793   case ETK_None: // Fall through.
2794   case ETK_Typename:
2795     llvm_unreachable("Elaborated type keyword is not a tag type kind.");
2796   }
2797   llvm_unreachable("Unknown elaborated type keyword.");
2798 }
2799 
2800 bool
2801 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
2802   switch (Keyword) {
2803   case ETK_None:
2804   case ETK_Typename:
2805     return false;
2806   case ETK_Class:
2807   case ETK_Struct:
2808   case ETK_Interface:
2809   case ETK_Union:
2810   case ETK_Enum:
2811     return true;
2812   }
2813   llvm_unreachable("Unknown elaborated type keyword.");
2814 }
2815 
2816 StringRef TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) {
2817   switch (Keyword) {
2818   case ETK_None: return {};
2819   case ETK_Typename: return "typename";
2820   case ETK_Class:  return "class";
2821   case ETK_Struct: return "struct";
2822   case ETK_Interface: return "__interface";
2823   case ETK_Union:  return "union";
2824   case ETK_Enum:   return "enum";
2825   }
2826 
2827   llvm_unreachable("Unknown elaborated type keyword.");
2828 }
2829 
2830 DependentTemplateSpecializationType::DependentTemplateSpecializationType(
2831     ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
2832     const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args, QualType Canon)
2833     : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon,
2834                       TypeDependence::DependentInstantiation |
2835                           (NNS ? toTypeDependence(NNS->getDependence())
2836                                : TypeDependence::None)),
2837       NNS(NNS), Name(Name) {
2838   DependentTemplateSpecializationTypeBits.NumArgs = Args.size();
2839   assert((!NNS || NNS->isDependent()) &&
2840          "DependentTemplateSpecializatonType requires dependent qualifier");
2841   TemplateArgument *ArgBuffer = getArgBuffer();
2842   for (const TemplateArgument &Arg : Args) {
2843     addDependence(toTypeDependence(Arg.getDependence() &
2844                                    TemplateArgumentDependence::UnexpandedPack));
2845 
2846     new (ArgBuffer++) TemplateArgument(Arg);
2847   }
2848 }
2849 
2850 void
2851 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
2852                                              const ASTContext &Context,
2853                                              ElaboratedTypeKeyword Keyword,
2854                                              NestedNameSpecifier *Qualifier,
2855                                              const IdentifierInfo *Name,
2856                                              ArrayRef<TemplateArgument> Args) {
2857   ID.AddInteger(Keyword);
2858   ID.AddPointer(Qualifier);
2859   ID.AddPointer(Name);
2860   for (const TemplateArgument &Arg : Args)
2861     Arg.Profile(ID, Context);
2862 }
2863 
2864 bool Type::isElaboratedTypeSpecifier() const {
2865   ElaboratedTypeKeyword Keyword;
2866   if (const auto *Elab = dyn_cast<ElaboratedType>(this))
2867     Keyword = Elab->getKeyword();
2868   else if (const auto *DepName = dyn_cast<DependentNameType>(this))
2869     Keyword = DepName->getKeyword();
2870   else if (const auto *DepTST =
2871                dyn_cast<DependentTemplateSpecializationType>(this))
2872     Keyword = DepTST->getKeyword();
2873   else
2874     return false;
2875 
2876   return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
2877 }
2878 
2879 const char *Type::getTypeClassName() const {
2880   switch (TypeBits.TC) {
2881 #define ABSTRACT_TYPE(Derived, Base)
2882 #define TYPE(Derived, Base) case Derived: return #Derived;
2883 #include "clang/AST/TypeNodes.inc"
2884   }
2885 
2886   llvm_unreachable("Invalid type class.");
2887 }
2888 
2889 StringRef BuiltinType::getName(const PrintingPolicy &Policy) const {
2890   switch (getKind()) {
2891   case Void:
2892     return "void";
2893   case Bool:
2894     return Policy.Bool ? "bool" : "_Bool";
2895   case Char_S:
2896     return "char";
2897   case Char_U:
2898     return "char";
2899   case SChar:
2900     return "signed char";
2901   case Short:
2902     return "short";
2903   case Int:
2904     return "int";
2905   case Long:
2906     return "long";
2907   case LongLong:
2908     return "long long";
2909   case Int128:
2910     return "__int128";
2911   case UChar:
2912     return "unsigned char";
2913   case UShort:
2914     return "unsigned short";
2915   case UInt:
2916     return "unsigned int";
2917   case ULong:
2918     return "unsigned long";
2919   case ULongLong:
2920     return "unsigned long long";
2921   case UInt128:
2922     return "unsigned __int128";
2923   case Half:
2924     return Policy.Half ? "half" : "__fp16";
2925   case Float:
2926     return "float";
2927   case Double:
2928     return "double";
2929   case LongDouble:
2930     return "long double";
2931   case ShortAccum:
2932     return "short _Accum";
2933   case Accum:
2934     return "_Accum";
2935   case LongAccum:
2936     return "long _Accum";
2937   case UShortAccum:
2938     return "unsigned short _Accum";
2939   case UAccum:
2940     return "unsigned _Accum";
2941   case ULongAccum:
2942     return "unsigned long _Accum";
2943   case BuiltinType::ShortFract:
2944     return "short _Fract";
2945   case BuiltinType::Fract:
2946     return "_Fract";
2947   case BuiltinType::LongFract:
2948     return "long _Fract";
2949   case BuiltinType::UShortFract:
2950     return "unsigned short _Fract";
2951   case BuiltinType::UFract:
2952     return "unsigned _Fract";
2953   case BuiltinType::ULongFract:
2954     return "unsigned long _Fract";
2955   case BuiltinType::SatShortAccum:
2956     return "_Sat short _Accum";
2957   case BuiltinType::SatAccum:
2958     return "_Sat _Accum";
2959   case BuiltinType::SatLongAccum:
2960     return "_Sat long _Accum";
2961   case BuiltinType::SatUShortAccum:
2962     return "_Sat unsigned short _Accum";
2963   case BuiltinType::SatUAccum:
2964     return "_Sat unsigned _Accum";
2965   case BuiltinType::SatULongAccum:
2966     return "_Sat unsigned long _Accum";
2967   case BuiltinType::SatShortFract:
2968     return "_Sat short _Fract";
2969   case BuiltinType::SatFract:
2970     return "_Sat _Fract";
2971   case BuiltinType::SatLongFract:
2972     return "_Sat long _Fract";
2973   case BuiltinType::SatUShortFract:
2974     return "_Sat unsigned short _Fract";
2975   case BuiltinType::SatUFract:
2976     return "_Sat unsigned _Fract";
2977   case BuiltinType::SatULongFract:
2978     return "_Sat unsigned long _Fract";
2979   case Float16:
2980     return "_Float16";
2981   case Float128:
2982     return "__float128";
2983   case WChar_S:
2984   case WChar_U:
2985     return Policy.MSWChar ? "__wchar_t" : "wchar_t";
2986   case Char8:
2987     return "char8_t";
2988   case Char16:
2989     return "char16_t";
2990   case Char32:
2991     return "char32_t";
2992   case NullPtr:
2993     return "nullptr_t";
2994   case Overload:
2995     return "<overloaded function type>";
2996   case BoundMember:
2997     return "<bound member function type>";
2998   case PseudoObject:
2999     return "<pseudo-object type>";
3000   case Dependent:
3001     return "<dependent type>";
3002   case UnknownAny:
3003     return "<unknown type>";
3004   case ARCUnbridgedCast:
3005     return "<ARC unbridged cast type>";
3006   case BuiltinFn:
3007     return "<builtin fn type>";
3008   case ObjCId:
3009     return "id";
3010   case ObjCClass:
3011     return "Class";
3012   case ObjCSel:
3013     return "SEL";
3014 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3015   case Id: \
3016     return "__" #Access " " #ImgType "_t";
3017 #include "clang/Basic/OpenCLImageTypes.def"
3018   case OCLSampler:
3019     return "sampler_t";
3020   case OCLEvent:
3021     return "event_t";
3022   case OCLClkEvent:
3023     return "clk_event_t";
3024   case OCLQueue:
3025     return "queue_t";
3026   case OCLReserveID:
3027     return "reserve_id_t";
3028   case OMPArraySection:
3029     return "<OpenMP array section type>";
3030   case OMPArrayShaping:
3031     return "<OpenMP array shaping type>";
3032   case OMPIterator:
3033     return "<OpenMP iterator type>";
3034 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3035   case Id: \
3036     return #ExtType;
3037 #include "clang/Basic/OpenCLExtensionTypes.def"
3038 #define SVE_TYPE(Name, Id, SingletonId) \
3039   case Id: \
3040     return Name;
3041 #include "clang/Basic/AArch64SVEACLETypes.def"
3042   }
3043 
3044   llvm_unreachable("Invalid builtin type.");
3045 }
3046 
3047 QualType QualType::getNonLValueExprType(const ASTContext &Context) const {
3048   if (const auto *RefType = getTypePtr()->getAs<ReferenceType>())
3049     return RefType->getPointeeType();
3050 
3051   // C++0x [basic.lval]:
3052   //   Class prvalues can have cv-qualified types; non-class prvalues always
3053   //   have cv-unqualified types.
3054   //
3055   // See also C99 6.3.2.1p2.
3056   if (!Context.getLangOpts().CPlusPlus ||
3057       (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
3058     return getUnqualifiedType();
3059 
3060   return *this;
3061 }
3062 
3063 StringRef FunctionType::getNameForCallConv(CallingConv CC) {
3064   switch (CC) {
3065   case CC_C: return "cdecl";
3066   case CC_X86StdCall: return "stdcall";
3067   case CC_X86FastCall: return "fastcall";
3068   case CC_X86ThisCall: return "thiscall";
3069   case CC_X86Pascal: return "pascal";
3070   case CC_X86VectorCall: return "vectorcall";
3071   case CC_Win64: return "ms_abi";
3072   case CC_X86_64SysV: return "sysv_abi";
3073   case CC_X86RegCall : return "regcall";
3074   case CC_AAPCS: return "aapcs";
3075   case CC_AAPCS_VFP: return "aapcs-vfp";
3076   case CC_AArch64VectorCall: return "aarch64_vector_pcs";
3077   case CC_IntelOclBicc: return "intel_ocl_bicc";
3078   case CC_SpirFunction: return "spir_function";
3079   case CC_OpenCLKernel: return "opencl_kernel";
3080   case CC_Swift: return "swiftcall";
3081   case CC_PreserveMost: return "preserve_most";
3082   case CC_PreserveAll: return "preserve_all";
3083   }
3084 
3085   llvm_unreachable("Invalid calling convention.");
3086 }
3087 
3088 FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> params,
3089                                      QualType canonical,
3090                                      const ExtProtoInfo &epi)
3091     : FunctionType(FunctionProto, result, canonical, result->getDependence(),
3092                    epi.ExtInfo) {
3093   FunctionTypeBits.FastTypeQuals = epi.TypeQuals.getFastQualifiers();
3094   FunctionTypeBits.RefQualifier = epi.RefQualifier;
3095   FunctionTypeBits.NumParams = params.size();
3096   assert(getNumParams() == params.size() && "NumParams overflow!");
3097   FunctionTypeBits.ExceptionSpecType = epi.ExceptionSpec.Type;
3098   FunctionTypeBits.HasExtParameterInfos = !!epi.ExtParameterInfos;
3099   FunctionTypeBits.Variadic = epi.Variadic;
3100   FunctionTypeBits.HasTrailingReturn = epi.HasTrailingReturn;
3101 
3102   // Fill in the extra trailing bitfields if present.
3103   if (hasExtraBitfields(epi.ExceptionSpec.Type)) {
3104     auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
3105     ExtraBits.NumExceptionType = epi.ExceptionSpec.Exceptions.size();
3106   }
3107 
3108   // Fill in the trailing argument array.
3109   auto *argSlot = getTrailingObjects<QualType>();
3110   for (unsigned i = 0; i != getNumParams(); ++i) {
3111     addDependence(params[i]->getDependence() &
3112                   ~TypeDependence::VariablyModified);
3113     argSlot[i] = params[i];
3114   }
3115 
3116   // Fill in the exception type array if present.
3117   if (getExceptionSpecType() == EST_Dynamic) {
3118     assert(hasExtraBitfields() && "missing trailing extra bitfields!");
3119     auto *exnSlot =
3120         reinterpret_cast<QualType *>(getTrailingObjects<ExceptionType>());
3121     unsigned I = 0;
3122     for (QualType ExceptionType : epi.ExceptionSpec.Exceptions) {
3123       // Note that, before C++17, a dependent exception specification does
3124       // *not* make a type dependent; it's not even part of the C++ type
3125       // system.
3126       addDependence(
3127           ExceptionType->getDependence() &
3128           (TypeDependence::Instantiation | TypeDependence::UnexpandedPack));
3129 
3130       exnSlot[I++] = ExceptionType;
3131     }
3132   }
3133   // Fill in the Expr * in the exception specification if present.
3134   else if (isComputedNoexcept(getExceptionSpecType())) {
3135     assert(epi.ExceptionSpec.NoexceptExpr && "computed noexcept with no expr");
3136     assert((getExceptionSpecType() == EST_DependentNoexcept) ==
3137            epi.ExceptionSpec.NoexceptExpr->isValueDependent());
3138 
3139     // Store the noexcept expression and context.
3140     *getTrailingObjects<Expr *>() = epi.ExceptionSpec.NoexceptExpr;
3141 
3142     addDependence(
3143         toTypeDependence(epi.ExceptionSpec.NoexceptExpr->getDependence()) &
3144         (TypeDependence::Instantiation | TypeDependence::UnexpandedPack));
3145   }
3146   // Fill in the FunctionDecl * in the exception specification if present.
3147   else if (getExceptionSpecType() == EST_Uninstantiated) {
3148     // Store the function decl from which we will resolve our
3149     // exception specification.
3150     auto **slot = getTrailingObjects<FunctionDecl *>();
3151     slot[0] = epi.ExceptionSpec.SourceDecl;
3152     slot[1] = epi.ExceptionSpec.SourceTemplate;
3153     // This exception specification doesn't make the type dependent, because
3154     // it's not instantiated as part of instantiating the type.
3155   } else if (getExceptionSpecType() == EST_Unevaluated) {
3156     // Store the function decl from which we will resolve our
3157     // exception specification.
3158     auto **slot = getTrailingObjects<FunctionDecl *>();
3159     slot[0] = epi.ExceptionSpec.SourceDecl;
3160   }
3161 
3162   // If this is a canonical type, and its exception specification is dependent,
3163   // then it's a dependent type. This only happens in C++17 onwards.
3164   if (isCanonicalUnqualified()) {
3165     if (getExceptionSpecType() == EST_Dynamic ||
3166         getExceptionSpecType() == EST_DependentNoexcept) {
3167       assert(hasDependentExceptionSpec() && "type should not be canonical");
3168       addDependence(TypeDependence::DependentInstantiation);
3169     }
3170   } else if (getCanonicalTypeInternal()->isDependentType()) {
3171     // Ask our canonical type whether our exception specification was dependent.
3172     addDependence(TypeDependence::DependentInstantiation);
3173   }
3174 
3175   // Fill in the extra parameter info if present.
3176   if (epi.ExtParameterInfos) {
3177     auto *extParamInfos = getTrailingObjects<ExtParameterInfo>();
3178     for (unsigned i = 0; i != getNumParams(); ++i)
3179       extParamInfos[i] = epi.ExtParameterInfos[i];
3180   }
3181 
3182   if (epi.TypeQuals.hasNonFastQualifiers()) {
3183     FunctionTypeBits.HasExtQuals = 1;
3184     *getTrailingObjects<Qualifiers>() = epi.TypeQuals;
3185   } else {
3186     FunctionTypeBits.HasExtQuals = 0;
3187   }
3188 
3189   // Fill in the Ellipsis location info if present.
3190   if (epi.Variadic) {
3191     auto &EllipsisLoc = *getTrailingObjects<SourceLocation>();
3192     EllipsisLoc = epi.EllipsisLoc;
3193   }
3194 }
3195 
3196 bool FunctionProtoType::hasDependentExceptionSpec() const {
3197   if (Expr *NE = getNoexceptExpr())
3198     return NE->isValueDependent();
3199   for (QualType ET : exceptions())
3200     // A pack expansion with a non-dependent pattern is still dependent,
3201     // because we don't know whether the pattern is in the exception spec
3202     // or not (that depends on whether the pack has 0 expansions).
3203     if (ET->isDependentType() || ET->getAs<PackExpansionType>())
3204       return true;
3205   return false;
3206 }
3207 
3208 bool FunctionProtoType::hasInstantiationDependentExceptionSpec() const {
3209   if (Expr *NE = getNoexceptExpr())
3210     return NE->isInstantiationDependent();
3211   for (QualType ET : exceptions())
3212     if (ET->isInstantiationDependentType())
3213       return true;
3214   return false;
3215 }
3216 
3217 CanThrowResult FunctionProtoType::canThrow() const {
3218   switch (getExceptionSpecType()) {
3219   case EST_Unparsed:
3220   case EST_Unevaluated:
3221   case EST_Uninstantiated:
3222     llvm_unreachable("should not call this with unresolved exception specs");
3223 
3224   case EST_DynamicNone:
3225   case EST_BasicNoexcept:
3226   case EST_NoexceptTrue:
3227   case EST_NoThrow:
3228     return CT_Cannot;
3229 
3230   case EST_None:
3231   case EST_MSAny:
3232   case EST_NoexceptFalse:
3233     return CT_Can;
3234 
3235   case EST_Dynamic:
3236     // A dynamic exception specification is throwing unless every exception
3237     // type is an (unexpanded) pack expansion type.
3238     for (unsigned I = 0; I != getNumExceptions(); ++I)
3239       if (!getExceptionType(I)->getAs<PackExpansionType>())
3240         return CT_Can;
3241     return CT_Dependent;
3242 
3243   case EST_DependentNoexcept:
3244     return CT_Dependent;
3245   }
3246 
3247   llvm_unreachable("unexpected exception specification kind");
3248 }
3249 
3250 bool FunctionProtoType::isTemplateVariadic() const {
3251   for (unsigned ArgIdx = getNumParams(); ArgIdx; --ArgIdx)
3252     if (isa<PackExpansionType>(getParamType(ArgIdx - 1)))
3253       return true;
3254 
3255   return false;
3256 }
3257 
3258 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
3259                                 const QualType *ArgTys, unsigned NumParams,
3260                                 const ExtProtoInfo &epi,
3261                                 const ASTContext &Context, bool Canonical) {
3262   // We have to be careful not to get ambiguous profile encodings.
3263   // Note that valid type pointers are never ambiguous with anything else.
3264   //
3265   // The encoding grammar begins:
3266   //      type type* bool int bool
3267   // If that final bool is true, then there is a section for the EH spec:
3268   //      bool type*
3269   // This is followed by an optional "consumed argument" section of the
3270   // same length as the first type sequence:
3271   //      bool*
3272   // Finally, we have the ext info and trailing return type flag:
3273   //      int bool
3274   //
3275   // There is no ambiguity between the consumed arguments and an empty EH
3276   // spec because of the leading 'bool' which unambiguously indicates
3277   // whether the following bool is the EH spec or part of the arguments.
3278 
3279   ID.AddPointer(Result.getAsOpaquePtr());
3280   for (unsigned i = 0; i != NumParams; ++i)
3281     ID.AddPointer(ArgTys[i].getAsOpaquePtr());
3282   // This method is relatively performance sensitive, so as a performance
3283   // shortcut, use one AddInteger call instead of four for the next four
3284   // fields.
3285   assert(!(unsigned(epi.Variadic) & ~1) &&
3286          !(unsigned(epi.RefQualifier) & ~3) &&
3287          !(unsigned(epi.ExceptionSpec.Type) & ~15) &&
3288          "Values larger than expected.");
3289   ID.AddInteger(unsigned(epi.Variadic) +
3290                 (epi.RefQualifier << 1) +
3291                 (epi.ExceptionSpec.Type << 3));
3292   ID.Add(epi.TypeQuals);
3293   if (epi.ExceptionSpec.Type == EST_Dynamic) {
3294     for (QualType Ex : epi.ExceptionSpec.Exceptions)
3295       ID.AddPointer(Ex.getAsOpaquePtr());
3296   } else if (isComputedNoexcept(epi.ExceptionSpec.Type)) {
3297     epi.ExceptionSpec.NoexceptExpr->Profile(ID, Context, Canonical);
3298   } else if (epi.ExceptionSpec.Type == EST_Uninstantiated ||
3299              epi.ExceptionSpec.Type == EST_Unevaluated) {
3300     ID.AddPointer(epi.ExceptionSpec.SourceDecl->getCanonicalDecl());
3301   }
3302   if (epi.ExtParameterInfos) {
3303     for (unsigned i = 0; i != NumParams; ++i)
3304       ID.AddInteger(epi.ExtParameterInfos[i].getOpaqueValue());
3305   }
3306   epi.ExtInfo.Profile(ID);
3307   ID.AddBoolean(epi.HasTrailingReturn);
3308 }
3309 
3310 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
3311                                 const ASTContext &Ctx) {
3312   Profile(ID, getReturnType(), param_type_begin(), getNumParams(),
3313           getExtProtoInfo(), Ctx, isCanonicalUnqualified());
3314 }
3315 
3316 QualType TypedefType::desugar() const {
3317   return getDecl()->getUnderlyingType();
3318 }
3319 
3320 QualType MacroQualifiedType::desugar() const { return getUnderlyingType(); }
3321 
3322 QualType MacroQualifiedType::getModifiedType() const {
3323   // Step over MacroQualifiedTypes from the same macro to find the type
3324   // ultimately qualified by the macro qualifier.
3325   QualType Inner = cast<AttributedType>(getUnderlyingType())->getModifiedType();
3326   while (auto *InnerMQT = dyn_cast<MacroQualifiedType>(Inner)) {
3327     if (InnerMQT->getMacroIdentifier() != getMacroIdentifier())
3328       break;
3329     Inner = InnerMQT->getModifiedType();
3330   }
3331   return Inner;
3332 }
3333 
3334 TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
3335     : Type(TypeOfExpr, can,
3336            toTypeDependence(E->getDependence()) |
3337                (E->getType()->getDependence() &
3338                 TypeDependence::VariablyModified)),
3339       TOExpr(E) {}
3340 
3341 bool TypeOfExprType::isSugared() const {
3342   return !TOExpr->isTypeDependent();
3343 }
3344 
3345 QualType TypeOfExprType::desugar() const {
3346   if (isSugared())
3347     return getUnderlyingExpr()->getType();
3348 
3349   return QualType(this, 0);
3350 }
3351 
3352 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
3353                                       const ASTContext &Context, Expr *E) {
3354   E->Profile(ID, Context, true);
3355 }
3356 
3357 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
3358     // C++11 [temp.type]p2: "If an expression e involves a template parameter,
3359     // decltype(e) denotes a unique dependent type." Hence a decltype type is
3360     // type-dependent even if its expression is only instantiation-dependent.
3361     : Type(Decltype, can,
3362            toTypeDependence(E->getDependence()) |
3363                (E->isInstantiationDependent() ? TypeDependence::Dependent
3364                                               : TypeDependence::None) |
3365                (E->getType()->getDependence() &
3366                 TypeDependence::VariablyModified)),
3367       E(E), UnderlyingType(underlyingType) {}
3368 
3369 bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); }
3370 
3371 QualType DecltypeType::desugar() const {
3372   if (isSugared())
3373     return getUnderlyingType();
3374 
3375   return QualType(this, 0);
3376 }
3377 
3378 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E)
3379     : DecltypeType(E, Context.DependentTy), Context(Context) {}
3380 
3381 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
3382                                     const ASTContext &Context, Expr *E) {
3383   E->Profile(ID, Context, true);
3384 }
3385 
3386 UnaryTransformType::UnaryTransformType(QualType BaseType,
3387                                        QualType UnderlyingType, UTTKind UKind,
3388                                        QualType CanonicalType)
3389     : Type(UnaryTransform, CanonicalType, BaseType->getDependence()),
3390       BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind) {}
3391 
3392 DependentUnaryTransformType::DependentUnaryTransformType(const ASTContext &C,
3393                                                          QualType BaseType,
3394                                                          UTTKind UKind)
3395      : UnaryTransformType(BaseType, C.DependentTy, UKind, QualType()) {}
3396 
3397 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
3398     : Type(TC, can,
3399            D->isDependentType() ? TypeDependence::DependentInstantiation
3400                                 : TypeDependence::None),
3401       decl(const_cast<TagDecl *>(D)) {}
3402 
3403 static TagDecl *getInterestingTagDecl(TagDecl *decl) {
3404   for (auto I : decl->redecls()) {
3405     if (I->isCompleteDefinition() || I->isBeingDefined())
3406       return I;
3407   }
3408   // If there's no definition (not even in progress), return what we have.
3409   return decl;
3410 }
3411 
3412 TagDecl *TagType::getDecl() const {
3413   return getInterestingTagDecl(decl);
3414 }
3415 
3416 bool TagType::isBeingDefined() const {
3417   return getDecl()->isBeingDefined();
3418 }
3419 
3420 bool RecordType::hasConstFields() const {
3421   std::vector<const RecordType*> RecordTypeList;
3422   RecordTypeList.push_back(this);
3423   unsigned NextToCheckIndex = 0;
3424 
3425   while (RecordTypeList.size() > NextToCheckIndex) {
3426     for (FieldDecl *FD :
3427          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
3428       QualType FieldTy = FD->getType();
3429       if (FieldTy.isConstQualified())
3430         return true;
3431       FieldTy = FieldTy.getCanonicalType();
3432       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
3433         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
3434           RecordTypeList.push_back(FieldRecTy);
3435       }
3436     }
3437     ++NextToCheckIndex;
3438   }
3439   return false;
3440 }
3441 
3442 bool AttributedType::isQualifier() const {
3443   // FIXME: Generate this with TableGen.
3444   switch (getAttrKind()) {
3445   // These are type qualifiers in the traditional C sense: they annotate
3446   // something about a specific value/variable of a type.  (They aren't
3447   // always part of the canonical type, though.)
3448   case attr::ObjCGC:
3449   case attr::ObjCOwnership:
3450   case attr::ObjCInertUnsafeUnretained:
3451   case attr::TypeNonNull:
3452   case attr::TypeNullable:
3453   case attr::TypeNullUnspecified:
3454   case attr::LifetimeBound:
3455   case attr::AddressSpace:
3456     return true;
3457 
3458   // All other type attributes aren't qualifiers; they rewrite the modified
3459   // type to be a semantically different type.
3460   default:
3461     return false;
3462   }
3463 }
3464 
3465 bool AttributedType::isMSTypeSpec() const {
3466   // FIXME: Generate this with TableGen?
3467   switch (getAttrKind()) {
3468   default: return false;
3469   case attr::Ptr32:
3470   case attr::Ptr64:
3471   case attr::SPtr:
3472   case attr::UPtr:
3473     return true;
3474   }
3475   llvm_unreachable("invalid attr kind");
3476 }
3477 
3478 bool AttributedType::isCallingConv() const {
3479   // FIXME: Generate this with TableGen.
3480   switch (getAttrKind()) {
3481   default: return false;
3482   case attr::Pcs:
3483   case attr::CDecl:
3484   case attr::FastCall:
3485   case attr::StdCall:
3486   case attr::ThisCall:
3487   case attr::RegCall:
3488   case attr::SwiftCall:
3489   case attr::VectorCall:
3490   case attr::AArch64VectorPcs:
3491   case attr::Pascal:
3492   case attr::MSABI:
3493   case attr::SysVABI:
3494   case attr::IntelOclBicc:
3495   case attr::PreserveMost:
3496   case attr::PreserveAll:
3497     return true;
3498   }
3499   llvm_unreachable("invalid attr kind");
3500 }
3501 
3502 CXXRecordDecl *InjectedClassNameType::getDecl() const {
3503   return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
3504 }
3505 
3506 IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
3507   return isCanonicalUnqualified() ? nullptr : getDecl()->getIdentifier();
3508 }
3509 
3510 SubstTemplateTypeParmPackType::SubstTemplateTypeParmPackType(
3511     const TemplateTypeParmType *Param, QualType Canon,
3512     const TemplateArgument &ArgPack)
3513     : Type(SubstTemplateTypeParmPack, Canon,
3514            TypeDependence::DependentInstantiation |
3515                TypeDependence::UnexpandedPack),
3516       Replaced(Param), Arguments(ArgPack.pack_begin()) {
3517   SubstTemplateTypeParmPackTypeBits.NumArgs = ArgPack.pack_size();
3518 }
3519 
3520 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const {
3521   return TemplateArgument(llvm::makeArrayRef(Arguments, getNumArgs()));
3522 }
3523 
3524 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
3525   Profile(ID, getReplacedParameter(), getArgumentPack());
3526 }
3527 
3528 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
3529                                            const TemplateTypeParmType *Replaced,
3530                                             const TemplateArgument &ArgPack) {
3531   ID.AddPointer(Replaced);
3532   ID.AddInteger(ArgPack.pack_size());
3533   for (const auto &P : ArgPack.pack_elements())
3534     ID.AddPointer(P.getAsType().getAsOpaquePtr());
3535 }
3536 
3537 bool TemplateSpecializationType::
3538 anyDependentTemplateArguments(const TemplateArgumentListInfo &Args,
3539                               bool &InstantiationDependent) {
3540   return anyDependentTemplateArguments(Args.arguments(),
3541                                        InstantiationDependent);
3542 }
3543 
3544 bool TemplateSpecializationType::
3545 anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
3546                               bool &InstantiationDependent) {
3547   for (const TemplateArgumentLoc &ArgLoc : Args) {
3548     if (ArgLoc.getArgument().isDependent()) {
3549       InstantiationDependent = true;
3550       return true;
3551     }
3552 
3553     if (ArgLoc.getArgument().isInstantiationDependent())
3554       InstantiationDependent = true;
3555   }
3556   return false;
3557 }
3558 
3559 TemplateSpecializationType::TemplateSpecializationType(
3560     TemplateName T, ArrayRef<TemplateArgument> Args, QualType Canon,
3561     QualType AliasedType)
3562     : Type(TemplateSpecialization, Canon.isNull() ? QualType(this, 0) : Canon,
3563            (Canon.isNull()
3564                 ? TypeDependence::DependentInstantiation
3565                 : Canon->getDependence() & ~(TypeDependence::VariablyModified |
3566                                              TypeDependence::UnexpandedPack)) |
3567                (toTypeDependence(T.getDependence()) &
3568                 TypeDependence::UnexpandedPack)),
3569       Template(T) {
3570   TemplateSpecializationTypeBits.NumArgs = Args.size();
3571   TemplateSpecializationTypeBits.TypeAlias = !AliasedType.isNull();
3572 
3573   assert(!T.getAsDependentTemplateName() &&
3574          "Use DependentTemplateSpecializationType for dependent template-name");
3575   assert((T.getKind() == TemplateName::Template ||
3576           T.getKind() == TemplateName::SubstTemplateTemplateParm ||
3577           T.getKind() == TemplateName::SubstTemplateTemplateParmPack) &&
3578          "Unexpected template name for TemplateSpecializationType");
3579 
3580   auto *TemplateArgs = reinterpret_cast<TemplateArgument *>(this + 1);
3581   for (const TemplateArgument &Arg : Args) {
3582     // Update instantiation-dependent and variably-modified bits.
3583     // If the canonical type exists and is non-dependent, the template
3584     // specialization type can be non-dependent even if one of the type
3585     // arguments is. Given:
3586     //   template<typename T> using U = int;
3587     // U<T> is always non-dependent, irrespective of the type T.
3588     // However, U<Ts> contains an unexpanded parameter pack, even though
3589     // its expansion (and thus its desugared type) doesn't.
3590     addDependence(toTypeDependence(Arg.getDependence()) &
3591                   ~TypeDependence::Dependent);
3592     if (Arg.getKind() == TemplateArgument::Type)
3593       addDependence(Arg.getAsType()->getDependence() &
3594                     TypeDependence::VariablyModified);
3595     new (TemplateArgs++) TemplateArgument(Arg);
3596   }
3597 
3598   // Store the aliased type if this is a type alias template specialization.
3599   if (isTypeAlias()) {
3600     auto *Begin = reinterpret_cast<TemplateArgument *>(this + 1);
3601     *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType;
3602   }
3603 }
3604 
3605 void
3606 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
3607                                     TemplateName T,
3608                                     ArrayRef<TemplateArgument> Args,
3609                                     const ASTContext &Context) {
3610   T.Profile(ID);
3611   for (const TemplateArgument &Arg : Args)
3612     Arg.Profile(ID, Context);
3613 }
3614 
3615 QualType
3616 QualifierCollector::apply(const ASTContext &Context, QualType QT) const {
3617   if (!hasNonFastQualifiers())
3618     return QT.withFastQualifiers(getFastQualifiers());
3619 
3620   return Context.getQualifiedType(QT, *this);
3621 }
3622 
3623 QualType
3624 QualifierCollector::apply(const ASTContext &Context, const Type *T) const {
3625   if (!hasNonFastQualifiers())
3626     return QualType(T, getFastQualifiers());
3627 
3628   return Context.getQualifiedType(T, *this);
3629 }
3630 
3631 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
3632                                  QualType BaseType,
3633                                  ArrayRef<QualType> typeArgs,
3634                                  ArrayRef<ObjCProtocolDecl *> protocols,
3635                                  bool isKindOf) {
3636   ID.AddPointer(BaseType.getAsOpaquePtr());
3637   ID.AddInteger(typeArgs.size());
3638   for (auto typeArg : typeArgs)
3639     ID.AddPointer(typeArg.getAsOpaquePtr());
3640   ID.AddInteger(protocols.size());
3641   for (auto proto : protocols)
3642     ID.AddPointer(proto);
3643   ID.AddBoolean(isKindOf);
3644 }
3645 
3646 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
3647   Profile(ID, getBaseType(), getTypeArgsAsWritten(),
3648           llvm::makeArrayRef(qual_begin(), getNumProtocols()),
3649           isKindOfTypeAsWritten());
3650 }
3651 
3652 void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID,
3653                                 const ObjCTypeParamDecl *OTPDecl,
3654                                 QualType CanonicalType,
3655                                 ArrayRef<ObjCProtocolDecl *> protocols) {
3656   ID.AddPointer(OTPDecl);
3657   ID.AddPointer(CanonicalType.getAsOpaquePtr());
3658   ID.AddInteger(protocols.size());
3659   for (auto proto : protocols)
3660     ID.AddPointer(proto);
3661 }
3662 
3663 void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID) {
3664   Profile(ID, getDecl(), getCanonicalTypeInternal(),
3665           llvm::makeArrayRef(qual_begin(), getNumProtocols()));
3666 }
3667 
3668 namespace {
3669 
3670 /// The cached properties of a type.
3671 class CachedProperties {
3672   Linkage L;
3673   bool local;
3674 
3675 public:
3676   CachedProperties(Linkage L, bool local) : L(L), local(local) {}
3677 
3678   Linkage getLinkage() const { return L; }
3679   bool hasLocalOrUnnamedType() const { return local; }
3680 
3681   friend CachedProperties merge(CachedProperties L, CachedProperties R) {
3682     Linkage MergedLinkage = minLinkage(L.L, R.L);
3683     return CachedProperties(MergedLinkage,
3684                          L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType());
3685   }
3686 };
3687 
3688 } // namespace
3689 
3690 static CachedProperties computeCachedProperties(const Type *T);
3691 
3692 namespace clang {
3693 
3694 /// The type-property cache.  This is templated so as to be
3695 /// instantiated at an internal type to prevent unnecessary symbol
3696 /// leakage.
3697 template <class Private> class TypePropertyCache {
3698 public:
3699   static CachedProperties get(QualType T) {
3700     return get(T.getTypePtr());
3701   }
3702 
3703   static CachedProperties get(const Type *T) {
3704     ensure(T);
3705     return CachedProperties(T->TypeBits.getLinkage(),
3706                             T->TypeBits.hasLocalOrUnnamedType());
3707   }
3708 
3709   static void ensure(const Type *T) {
3710     // If the cache is valid, we're okay.
3711     if (T->TypeBits.isCacheValid()) return;
3712 
3713     // If this type is non-canonical, ask its canonical type for the
3714     // relevant information.
3715     if (!T->isCanonicalUnqualified()) {
3716       const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
3717       ensure(CT);
3718       T->TypeBits.CacheValid = true;
3719       T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
3720       T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
3721       return;
3722     }
3723 
3724     // Compute the cached properties and then set the cache.
3725     CachedProperties Result = computeCachedProperties(T);
3726     T->TypeBits.CacheValid = true;
3727     T->TypeBits.CachedLinkage = Result.getLinkage();
3728     T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
3729   }
3730 };
3731 
3732 } // namespace clang
3733 
3734 // Instantiate the friend template at a private class.  In a
3735 // reasonable implementation, these symbols will be internal.
3736 // It is terrible that this is the best way to accomplish this.
3737 namespace {
3738 
3739 class Private {};
3740 
3741 } // namespace
3742 
3743 using Cache = TypePropertyCache<Private>;
3744 
3745 static CachedProperties computeCachedProperties(const Type *T) {
3746   switch (T->getTypeClass()) {
3747 #define TYPE(Class,Base)
3748 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
3749 #include "clang/AST/TypeNodes.inc"
3750     llvm_unreachable("didn't expect a non-canonical type here");
3751 
3752 #define TYPE(Class,Base)
3753 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
3754 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
3755 #include "clang/AST/TypeNodes.inc"
3756     // Treat instantiation-dependent types as external.
3757     if (!T->isInstantiationDependentType()) T->dump();
3758     assert(T->isInstantiationDependentType());
3759     return CachedProperties(ExternalLinkage, false);
3760 
3761   case Type::Auto:
3762   case Type::DeducedTemplateSpecialization:
3763     // Give non-deduced 'auto' types external linkage. We should only see them
3764     // here in error recovery.
3765     return CachedProperties(ExternalLinkage, false);
3766 
3767   case Type::ExtInt:
3768   case Type::Builtin:
3769     // C++ [basic.link]p8:
3770     //   A type is said to have linkage if and only if:
3771     //     - it is a fundamental type (3.9.1); or
3772     return CachedProperties(ExternalLinkage, false);
3773 
3774   case Type::Record:
3775   case Type::Enum: {
3776     const TagDecl *Tag = cast<TagType>(T)->getDecl();
3777 
3778     // C++ [basic.link]p8:
3779     //     - it is a class or enumeration type that is named (or has a name
3780     //       for linkage purposes (7.1.3)) and the name has linkage; or
3781     //     -  it is a specialization of a class template (14); or
3782     Linkage L = Tag->getLinkageInternal();
3783     bool IsLocalOrUnnamed =
3784       Tag->getDeclContext()->isFunctionOrMethod() ||
3785       !Tag->hasNameForLinkage();
3786     return CachedProperties(L, IsLocalOrUnnamed);
3787   }
3788 
3789     // C++ [basic.link]p8:
3790     //   - it is a compound type (3.9.2) other than a class or enumeration,
3791     //     compounded exclusively from types that have linkage; or
3792   case Type::Complex:
3793     return Cache::get(cast<ComplexType>(T)->getElementType());
3794   case Type::Pointer:
3795     return Cache::get(cast<PointerType>(T)->getPointeeType());
3796   case Type::BlockPointer:
3797     return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
3798   case Type::LValueReference:
3799   case Type::RValueReference:
3800     return Cache::get(cast<ReferenceType>(T)->getPointeeType());
3801   case Type::MemberPointer: {
3802     const auto *MPT = cast<MemberPointerType>(T);
3803     return merge(Cache::get(MPT->getClass()),
3804                  Cache::get(MPT->getPointeeType()));
3805   }
3806   case Type::ConstantArray:
3807   case Type::IncompleteArray:
3808   case Type::VariableArray:
3809     return Cache::get(cast<ArrayType>(T)->getElementType());
3810   case Type::Vector:
3811   case Type::ExtVector:
3812     return Cache::get(cast<VectorType>(T)->getElementType());
3813   case Type::ConstantMatrix:
3814     return Cache::get(cast<ConstantMatrixType>(T)->getElementType());
3815   case Type::FunctionNoProto:
3816     return Cache::get(cast<FunctionType>(T)->getReturnType());
3817   case Type::FunctionProto: {
3818     const auto *FPT = cast<FunctionProtoType>(T);
3819     CachedProperties result = Cache::get(FPT->getReturnType());
3820     for (const auto &ai : FPT->param_types())
3821       result = merge(result, Cache::get(ai));
3822     return result;
3823   }
3824   case Type::ObjCInterface: {
3825     Linkage L = cast<ObjCInterfaceType>(T)->getDecl()->getLinkageInternal();
3826     return CachedProperties(L, false);
3827   }
3828   case Type::ObjCObject:
3829     return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
3830   case Type::ObjCObjectPointer:
3831     return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
3832   case Type::Atomic:
3833     return Cache::get(cast<AtomicType>(T)->getValueType());
3834   case Type::Pipe:
3835     return Cache::get(cast<PipeType>(T)->getElementType());
3836   }
3837 
3838   llvm_unreachable("unhandled type class");
3839 }
3840 
3841 /// Determine the linkage of this type.
3842 Linkage Type::getLinkage() const {
3843   Cache::ensure(this);
3844   return TypeBits.getLinkage();
3845 }
3846 
3847 bool Type::hasUnnamedOrLocalType() const {
3848   Cache::ensure(this);
3849   return TypeBits.hasLocalOrUnnamedType();
3850 }
3851 
3852 LinkageInfo LinkageComputer::computeTypeLinkageInfo(const Type *T) {
3853   switch (T->getTypeClass()) {
3854 #define TYPE(Class,Base)
3855 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
3856 #include "clang/AST/TypeNodes.inc"
3857     llvm_unreachable("didn't expect a non-canonical type here");
3858 
3859 #define TYPE(Class,Base)
3860 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
3861 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
3862 #include "clang/AST/TypeNodes.inc"
3863     // Treat instantiation-dependent types as external.
3864     assert(T->isInstantiationDependentType());
3865     return LinkageInfo::external();
3866 
3867   case Type::ExtInt:
3868   case Type::Builtin:
3869     return LinkageInfo::external();
3870 
3871   case Type::Auto:
3872   case Type::DeducedTemplateSpecialization:
3873     return LinkageInfo::external();
3874 
3875   case Type::Record:
3876   case Type::Enum:
3877     return getDeclLinkageAndVisibility(cast<TagType>(T)->getDecl());
3878 
3879   case Type::Complex:
3880     return computeTypeLinkageInfo(cast<ComplexType>(T)->getElementType());
3881   case Type::Pointer:
3882     return computeTypeLinkageInfo(cast<PointerType>(T)->getPointeeType());
3883   case Type::BlockPointer:
3884     return computeTypeLinkageInfo(cast<BlockPointerType>(T)->getPointeeType());
3885   case Type::LValueReference:
3886   case Type::RValueReference:
3887     return computeTypeLinkageInfo(cast<ReferenceType>(T)->getPointeeType());
3888   case Type::MemberPointer: {
3889     const auto *MPT = cast<MemberPointerType>(T);
3890     LinkageInfo LV = computeTypeLinkageInfo(MPT->getClass());
3891     LV.merge(computeTypeLinkageInfo(MPT->getPointeeType()));
3892     return LV;
3893   }
3894   case Type::ConstantArray:
3895   case Type::IncompleteArray:
3896   case Type::VariableArray:
3897     return computeTypeLinkageInfo(cast<ArrayType>(T)->getElementType());
3898   case Type::Vector:
3899   case Type::ExtVector:
3900     return computeTypeLinkageInfo(cast<VectorType>(T)->getElementType());
3901   case Type::ConstantMatrix:
3902     return computeTypeLinkageInfo(
3903         cast<ConstantMatrixType>(T)->getElementType());
3904   case Type::FunctionNoProto:
3905     return computeTypeLinkageInfo(cast<FunctionType>(T)->getReturnType());
3906   case Type::FunctionProto: {
3907     const auto *FPT = cast<FunctionProtoType>(T);
3908     LinkageInfo LV = computeTypeLinkageInfo(FPT->getReturnType());
3909     for (const auto &ai : FPT->param_types())
3910       LV.merge(computeTypeLinkageInfo(ai));
3911     return LV;
3912   }
3913   case Type::ObjCInterface:
3914     return getDeclLinkageAndVisibility(cast<ObjCInterfaceType>(T)->getDecl());
3915   case Type::ObjCObject:
3916     return computeTypeLinkageInfo(cast<ObjCObjectType>(T)->getBaseType());
3917   case Type::ObjCObjectPointer:
3918     return computeTypeLinkageInfo(
3919         cast<ObjCObjectPointerType>(T)->getPointeeType());
3920   case Type::Atomic:
3921     return computeTypeLinkageInfo(cast<AtomicType>(T)->getValueType());
3922   case Type::Pipe:
3923     return computeTypeLinkageInfo(cast<PipeType>(T)->getElementType());
3924   }
3925 
3926   llvm_unreachable("unhandled type class");
3927 }
3928 
3929 bool Type::isLinkageValid() const {
3930   if (!TypeBits.isCacheValid())
3931     return true;
3932 
3933   Linkage L = LinkageComputer{}
3934                   .computeTypeLinkageInfo(getCanonicalTypeInternal())
3935                   .getLinkage();
3936   return L == TypeBits.getLinkage();
3937 }
3938 
3939 LinkageInfo LinkageComputer::getTypeLinkageAndVisibility(const Type *T) {
3940   if (!T->isCanonicalUnqualified())
3941     return computeTypeLinkageInfo(T->getCanonicalTypeInternal());
3942 
3943   LinkageInfo LV = computeTypeLinkageInfo(T);
3944   assert(LV.getLinkage() == T->getLinkage());
3945   return LV;
3946 }
3947 
3948 LinkageInfo Type::getLinkageAndVisibility() const {
3949   return LinkageComputer{}.getTypeLinkageAndVisibility(this);
3950 }
3951 
3952 Optional<NullabilityKind>
3953 Type::getNullability(const ASTContext &Context) const {
3954   QualType Type(this, 0);
3955   while (const auto *AT = Type->getAs<AttributedType>()) {
3956     // Check whether this is an attributed type with nullability
3957     // information.
3958     if (auto Nullability = AT->getImmediateNullability())
3959       return Nullability;
3960 
3961     Type = AT->getEquivalentType();
3962   }
3963   return None;
3964 }
3965 
3966 bool Type::canHaveNullability(bool ResultIfUnknown) const {
3967   QualType type = getCanonicalTypeInternal();
3968 
3969   switch (type->getTypeClass()) {
3970   // We'll only see canonical types here.
3971 #define NON_CANONICAL_TYPE(Class, Parent)       \
3972   case Type::Class:                             \
3973     llvm_unreachable("non-canonical type");
3974 #define TYPE(Class, Parent)
3975 #include "clang/AST/TypeNodes.inc"
3976 
3977   // Pointer types.
3978   case Type::Pointer:
3979   case Type::BlockPointer:
3980   case Type::MemberPointer:
3981   case Type::ObjCObjectPointer:
3982     return true;
3983 
3984   // Dependent types that could instantiate to pointer types.
3985   case Type::UnresolvedUsing:
3986   case Type::TypeOfExpr:
3987   case Type::TypeOf:
3988   case Type::Decltype:
3989   case Type::UnaryTransform:
3990   case Type::TemplateTypeParm:
3991   case Type::SubstTemplateTypeParmPack:
3992   case Type::DependentName:
3993   case Type::DependentTemplateSpecialization:
3994   case Type::Auto:
3995     return ResultIfUnknown;
3996 
3997   // Dependent template specializations can instantiate to pointer
3998   // types unless they're known to be specializations of a class
3999   // template.
4000   case Type::TemplateSpecialization:
4001     if (TemplateDecl *templateDecl
4002           = cast<TemplateSpecializationType>(type.getTypePtr())
4003               ->getTemplateName().getAsTemplateDecl()) {
4004       if (isa<ClassTemplateDecl>(templateDecl))
4005         return false;
4006     }
4007     return ResultIfUnknown;
4008 
4009   case Type::Builtin:
4010     switch (cast<BuiltinType>(type.getTypePtr())->getKind()) {
4011       // Signed, unsigned, and floating-point types cannot have nullability.
4012 #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
4013 #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
4014 #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
4015 #define BUILTIN_TYPE(Id, SingletonId)
4016 #include "clang/AST/BuiltinTypes.def"
4017       return false;
4018 
4019     // Dependent types that could instantiate to a pointer type.
4020     case BuiltinType::Dependent:
4021     case BuiltinType::Overload:
4022     case BuiltinType::BoundMember:
4023     case BuiltinType::PseudoObject:
4024     case BuiltinType::UnknownAny:
4025     case BuiltinType::ARCUnbridgedCast:
4026       return ResultIfUnknown;
4027 
4028     case BuiltinType::Void:
4029     case BuiltinType::ObjCId:
4030     case BuiltinType::ObjCClass:
4031     case BuiltinType::ObjCSel:
4032 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
4033     case BuiltinType::Id:
4034 #include "clang/Basic/OpenCLImageTypes.def"
4035 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
4036     case BuiltinType::Id:
4037 #include "clang/Basic/OpenCLExtensionTypes.def"
4038     case BuiltinType::OCLSampler:
4039     case BuiltinType::OCLEvent:
4040     case BuiltinType::OCLClkEvent:
4041     case BuiltinType::OCLQueue:
4042     case BuiltinType::OCLReserveID:
4043 #define SVE_TYPE(Name, Id, SingletonId) \
4044     case BuiltinType::Id:
4045 #include "clang/Basic/AArch64SVEACLETypes.def"
4046     case BuiltinType::BuiltinFn:
4047     case BuiltinType::NullPtr:
4048     case BuiltinType::OMPArraySection:
4049     case BuiltinType::OMPArrayShaping:
4050     case BuiltinType::OMPIterator:
4051       return false;
4052     }
4053     llvm_unreachable("unknown builtin type");
4054 
4055   // Non-pointer types.
4056   case Type::Complex:
4057   case Type::LValueReference:
4058   case Type::RValueReference:
4059   case Type::ConstantArray:
4060   case Type::IncompleteArray:
4061   case Type::VariableArray:
4062   case Type::DependentSizedArray:
4063   case Type::DependentVector:
4064   case Type::DependentSizedExtVector:
4065   case Type::Vector:
4066   case Type::ExtVector:
4067   case Type::ConstantMatrix:
4068   case Type::DependentSizedMatrix:
4069   case Type::DependentAddressSpace:
4070   case Type::FunctionProto:
4071   case Type::FunctionNoProto:
4072   case Type::Record:
4073   case Type::DeducedTemplateSpecialization:
4074   case Type::Enum:
4075   case Type::InjectedClassName:
4076   case Type::PackExpansion:
4077   case Type::ObjCObject:
4078   case Type::ObjCInterface:
4079   case Type::Atomic:
4080   case Type::Pipe:
4081   case Type::ExtInt:
4082   case Type::DependentExtInt:
4083     return false;
4084   }
4085   llvm_unreachable("bad type kind!");
4086 }
4087 
4088 llvm::Optional<NullabilityKind>
4089 AttributedType::getImmediateNullability() const {
4090   if (getAttrKind() == attr::TypeNonNull)
4091     return NullabilityKind::NonNull;
4092   if (getAttrKind() == attr::TypeNullable)
4093     return NullabilityKind::Nullable;
4094   if (getAttrKind() == attr::TypeNullUnspecified)
4095     return NullabilityKind::Unspecified;
4096   return None;
4097 }
4098 
4099 Optional<NullabilityKind> AttributedType::stripOuterNullability(QualType &T) {
4100   QualType AttrTy = T;
4101   if (auto MacroTy = dyn_cast<MacroQualifiedType>(T))
4102     AttrTy = MacroTy->getUnderlyingType();
4103 
4104   if (auto attributed = dyn_cast<AttributedType>(AttrTy)) {
4105     if (auto nullability = attributed->getImmediateNullability()) {
4106       T = attributed->getModifiedType();
4107       return nullability;
4108     }
4109   }
4110 
4111   return None;
4112 }
4113 
4114 bool Type::isBlockCompatibleObjCPointerType(ASTContext &ctx) const {
4115   const auto *objcPtr = getAs<ObjCObjectPointerType>();
4116   if (!objcPtr)
4117     return false;
4118 
4119   if (objcPtr->isObjCIdType()) {
4120     // id is always okay.
4121     return true;
4122   }
4123 
4124   // Blocks are NSObjects.
4125   if (ObjCInterfaceDecl *iface = objcPtr->getInterfaceDecl()) {
4126     if (iface->getIdentifier() != ctx.getNSObjectName())
4127       return false;
4128 
4129     // Continue to check qualifiers, below.
4130   } else if (objcPtr->isObjCQualifiedIdType()) {
4131     // Continue to check qualifiers, below.
4132   } else {
4133     return false;
4134   }
4135 
4136   // Check protocol qualifiers.
4137   for (ObjCProtocolDecl *proto : objcPtr->quals()) {
4138     // Blocks conform to NSObject and NSCopying.
4139     if (proto->getIdentifier() != ctx.getNSObjectName() &&
4140         proto->getIdentifier() != ctx.getNSCopyingName())
4141       return false;
4142   }
4143 
4144   return true;
4145 }
4146 
4147 Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const {
4148   if (isObjCARCImplicitlyUnretainedType())
4149     return Qualifiers::OCL_ExplicitNone;
4150   return Qualifiers::OCL_Strong;
4151 }
4152 
4153 bool Type::isObjCARCImplicitlyUnretainedType() const {
4154   assert(isObjCLifetimeType() &&
4155          "cannot query implicit lifetime for non-inferrable type");
4156 
4157   const Type *canon = getCanonicalTypeInternal().getTypePtr();
4158 
4159   // Walk down to the base type.  We don't care about qualifiers for this.
4160   while (const auto *array = dyn_cast<ArrayType>(canon))
4161     canon = array->getElementType().getTypePtr();
4162 
4163   if (const auto *opt = dyn_cast<ObjCObjectPointerType>(canon)) {
4164     // Class and Class<Protocol> don't require retention.
4165     if (opt->getObjectType()->isObjCClass())
4166       return true;
4167   }
4168 
4169   return false;
4170 }
4171 
4172 bool Type::isObjCNSObjectType() const {
4173   const Type *cur = this;
4174   while (true) {
4175     if (const auto *typedefType = dyn_cast<TypedefType>(cur))
4176       return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>();
4177 
4178     // Single-step desugar until we run out of sugar.
4179     QualType next = cur->getLocallyUnqualifiedSingleStepDesugaredType();
4180     if (next.getTypePtr() == cur) return false;
4181     cur = next.getTypePtr();
4182   }
4183 }
4184 
4185 bool Type::isObjCIndependentClassType() const {
4186   if (const auto *typedefType = dyn_cast<TypedefType>(this))
4187     return typedefType->getDecl()->hasAttr<ObjCIndependentClassAttr>();
4188   return false;
4189 }
4190 
4191 bool Type::isObjCRetainableType() const {
4192   return isObjCObjectPointerType() ||
4193          isBlockPointerType() ||
4194          isObjCNSObjectType();
4195 }
4196 
4197 bool Type::isObjCIndirectLifetimeType() const {
4198   if (isObjCLifetimeType())
4199     return true;
4200   if (const auto *OPT = getAs<PointerType>())
4201     return OPT->getPointeeType()->isObjCIndirectLifetimeType();
4202   if (const auto *Ref = getAs<ReferenceType>())
4203     return Ref->getPointeeType()->isObjCIndirectLifetimeType();
4204   if (const auto *MemPtr = getAs<MemberPointerType>())
4205     return MemPtr->getPointeeType()->isObjCIndirectLifetimeType();
4206   return false;
4207 }
4208 
4209 /// Returns true if objects of this type have lifetime semantics under
4210 /// ARC.
4211 bool Type::isObjCLifetimeType() const {
4212   const Type *type = this;
4213   while (const ArrayType *array = type->getAsArrayTypeUnsafe())
4214     type = array->getElementType().getTypePtr();
4215   return type->isObjCRetainableType();
4216 }
4217 
4218 /// Determine whether the given type T is a "bridgable" Objective-C type,
4219 /// which is either an Objective-C object pointer type or an
4220 bool Type::isObjCARCBridgableType() const {
4221   return isObjCObjectPointerType() || isBlockPointerType();
4222 }
4223 
4224 /// Determine whether the given type T is a "bridgeable" C type.
4225 bool Type::isCARCBridgableType() const {
4226   const auto *Pointer = getAs<PointerType>();
4227   if (!Pointer)
4228     return false;
4229 
4230   QualType Pointee = Pointer->getPointeeType();
4231   return Pointee->isVoidType() || Pointee->isRecordType();
4232 }
4233 
4234 /// Check if the specified type is the CUDA device builtin surface type.
4235 bool Type::isCUDADeviceBuiltinSurfaceType() const {
4236   if (const auto *RT = getAs<RecordType>())
4237     return RT->getDecl()->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>();
4238   return false;
4239 }
4240 
4241 /// Check if the specified type is the CUDA device builtin texture type.
4242 bool Type::isCUDADeviceBuiltinTextureType() const {
4243   if (const auto *RT = getAs<RecordType>())
4244     return RT->getDecl()->hasAttr<CUDADeviceBuiltinTextureTypeAttr>();
4245   return false;
4246 }
4247 
4248 bool Type::hasSizedVLAType() const {
4249   if (!isVariablyModifiedType()) return false;
4250 
4251   if (const auto *ptr = getAs<PointerType>())
4252     return ptr->getPointeeType()->hasSizedVLAType();
4253   if (const auto *ref = getAs<ReferenceType>())
4254     return ref->getPointeeType()->hasSizedVLAType();
4255   if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
4256     if (isa<VariableArrayType>(arr) &&
4257         cast<VariableArrayType>(arr)->getSizeExpr())
4258       return true;
4259 
4260     return arr->getElementType()->hasSizedVLAType();
4261   }
4262 
4263   return false;
4264 }
4265 
4266 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
4267   switch (type.getObjCLifetime()) {
4268   case Qualifiers::OCL_None:
4269   case Qualifiers::OCL_ExplicitNone:
4270   case Qualifiers::OCL_Autoreleasing:
4271     break;
4272 
4273   case Qualifiers::OCL_Strong:
4274     return DK_objc_strong_lifetime;
4275   case Qualifiers::OCL_Weak:
4276     return DK_objc_weak_lifetime;
4277   }
4278 
4279   if (const auto *RT =
4280           type->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
4281     const RecordDecl *RD = RT->getDecl();
4282     if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4283       /// Check if this is a C++ object with a non-trivial destructor.
4284       if (CXXRD->hasDefinition() && !CXXRD->hasTrivialDestructor())
4285         return DK_cxx_destructor;
4286     } else {
4287       /// Check if this is a C struct that is non-trivial to destroy or an array
4288       /// that contains such a struct.
4289       if (RD->isNonTrivialToPrimitiveDestroy())
4290         return DK_nontrivial_c_struct;
4291     }
4292   }
4293 
4294   return DK_none;
4295 }
4296 
4297 CXXRecordDecl *MemberPointerType::getMostRecentCXXRecordDecl() const {
4298   return getClass()->getAsCXXRecordDecl()->getMostRecentNonInjectedDecl();
4299 }
4300 
4301 void clang::FixedPointValueToString(SmallVectorImpl<char> &Str,
4302                                     llvm::APSInt Val, unsigned Scale) {
4303   FixedPointSemantics FXSema(Val.getBitWidth(), Scale, Val.isSigned(),
4304                              /*IsSaturated=*/false,
4305                              /*HasUnsignedPadding=*/false);
4306   APFixedPoint(Val, FXSema).toString(Str);
4307 }
4308 
4309 AutoType::AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
4310                    TypeDependence ExtraDependence,
4311                    ConceptDecl *TypeConstraintConcept,
4312                    ArrayRef<TemplateArgument> TypeConstraintArgs)
4313     : DeducedType(Auto, DeducedAsType, ExtraDependence) {
4314   AutoTypeBits.Keyword = (unsigned)Keyword;
4315   AutoTypeBits.NumArgs = TypeConstraintArgs.size();
4316   this->TypeConstraintConcept = TypeConstraintConcept;
4317   if (TypeConstraintConcept) {
4318     TemplateArgument *ArgBuffer = getArgBuffer();
4319     for (const TemplateArgument &Arg : TypeConstraintArgs) {
4320       addDependence(toTypeDependence(
4321           Arg.getDependence() & TemplateArgumentDependence::UnexpandedPack));
4322 
4323       new (ArgBuffer++) TemplateArgument(Arg);
4324     }
4325   }
4326 }
4327 
4328 void AutoType::Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4329                       QualType Deduced, AutoTypeKeyword Keyword,
4330                       bool IsDependent, ConceptDecl *CD,
4331                       ArrayRef<TemplateArgument> Arguments) {
4332   ID.AddPointer(Deduced.getAsOpaquePtr());
4333   ID.AddInteger((unsigned)Keyword);
4334   ID.AddBoolean(IsDependent);
4335   ID.AddPointer(CD);
4336   for (const TemplateArgument &Arg : Arguments)
4337     Arg.Profile(ID, Context);
4338 }
4339