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