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