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