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