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