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