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