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