xref: /llvm-project-15.0.7/clang/lib/AST/Type.cpp (revision 999500a2)
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/ASTContext.h"
15 #include "clang/AST/Attr.h"
16 #include "clang/AST/CharUnits.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/PrettyPrinter.h"
22 #include "clang/AST/Type.h"
23 #include "clang/AST/TypeVisitor.h"
24 #include "clang/Basic/Specifiers.h"
25 #include "llvm/ADT/APSInt.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include <algorithm>
29 using namespace clang;
30 
31 bool Qualifiers::isStrictSupersetOf(Qualifiers Other) const {
32   return (*this != Other) &&
33     // CVR qualifiers superset
34     (((Mask & CVRMask) | (Other.Mask & CVRMask)) == (Mask & CVRMask)) &&
35     // ObjC GC qualifiers superset
36     ((getObjCGCAttr() == Other.getObjCGCAttr()) ||
37      (hasObjCGCAttr() && !Other.hasObjCGCAttr())) &&
38     // Address space superset.
39     ((getAddressSpace() == Other.getAddressSpace()) ||
40      (hasAddressSpace()&& !Other.hasAddressSpace())) &&
41     // Lifetime qualifier superset.
42     ((getObjCLifetime() == Other.getObjCLifetime()) ||
43      (hasObjCLifetime() && !Other.hasObjCLifetime()));
44 }
45 
46 const IdentifierInfo* QualType::getBaseTypeIdentifier() const {
47   const Type* ty = getTypePtr();
48   NamedDecl *ND = nullptr;
49   if (ty->isPointerType() || ty->isReferenceType())
50     return ty->getPointeeType().getBaseTypeIdentifier();
51   else if (ty->isRecordType())
52     ND = ty->getAs<RecordType>()->getDecl();
53   else if (ty->isEnumeralType())
54     ND = ty->getAs<EnumType>()->getDecl();
55   else if (ty->getTypeClass() == Type::Typedef)
56     ND = ty->getAs<TypedefType>()->getDecl();
57   else if (ty->isArrayType())
58     return ty->castAsArrayTypeUnsafe()->
59         getElementType().getBaseTypeIdentifier();
60 
61   if (ND)
62     return ND->getIdentifier();
63   return nullptr;
64 }
65 
66 bool QualType::isConstant(QualType T, ASTContext &Ctx) {
67   if (T.isConstQualified())
68     return true;
69 
70   if (const ArrayType *AT = Ctx.getAsArrayType(T))
71     return AT->getElementType().isConstant(Ctx);
72 
73   return T.getAddressSpace() == LangAS::opencl_constant;
74 }
75 
76 unsigned ConstantArrayType::getNumAddressingBits(ASTContext &Context,
77                                                  QualType ElementType,
78                                                const llvm::APInt &NumElements) {
79   uint64_t ElementSize = Context.getTypeSizeInChars(ElementType).getQuantity();
80 
81   // Fast path the common cases so we can avoid the conservative computation
82   // below, which in common cases allocates "large" APSInt values, which are
83   // slow.
84 
85   // If the element size is a power of 2, we can directly compute the additional
86   // number of addressing bits beyond those required for the element count.
87   if (llvm::isPowerOf2_64(ElementSize)) {
88     return NumElements.getActiveBits() + llvm::Log2_64(ElementSize);
89   }
90 
91   // If both the element count and element size fit in 32-bits, we can do the
92   // computation directly in 64-bits.
93   if ((ElementSize >> 32) == 0 && NumElements.getBitWidth() <= 64 &&
94       (NumElements.getZExtValue() >> 32) == 0) {
95     uint64_t TotalSize = NumElements.getZExtValue() * ElementSize;
96     return 64 - llvm::countLeadingZeros(TotalSize);
97   }
98 
99   // Otherwise, use APSInt to handle arbitrary sized values.
100   llvm::APSInt SizeExtended(NumElements, true);
101   unsigned SizeTypeBits = Context.getTypeSize(Context.getSizeType());
102   SizeExtended = SizeExtended.extend(std::max(SizeTypeBits,
103                                               SizeExtended.getBitWidth()) * 2);
104 
105   llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize));
106   TotalSize *= SizeExtended;
107 
108   return TotalSize.getActiveBits();
109 }
110 
111 unsigned ConstantArrayType::getMaxSizeBits(ASTContext &Context) {
112   unsigned Bits = Context.getTypeSize(Context.getSizeType());
113 
114   // Limit the number of bits in size_t so that maximal bit size fits 64 bit
115   // integer (see PR8256).  We can do this as currently there is no hardware
116   // that supports full 64-bit virtual space.
117   if (Bits > 61)
118     Bits = 61;
119 
120   return Bits;
121 }
122 
123 DependentSizedArrayType::DependentSizedArrayType(const ASTContext &Context,
124                                                  QualType et, QualType can,
125                                                  Expr *e, ArraySizeModifier sm,
126                                                  unsigned tq,
127                                                  SourceRange brackets)
128     : ArrayType(DependentSizedArray, et, can, sm, tq,
129                 (et->containsUnexpandedParameterPack() ||
130                  (e && e->containsUnexpandedParameterPack()))),
131       Context(Context), SizeExpr((Stmt*) e), Brackets(brackets)
132 {
133 }
134 
135 void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID,
136                                       const ASTContext &Context,
137                                       QualType ET,
138                                       ArraySizeModifier SizeMod,
139                                       unsigned TypeQuals,
140                                       Expr *E) {
141   ID.AddPointer(ET.getAsOpaquePtr());
142   ID.AddInteger(SizeMod);
143   ID.AddInteger(TypeQuals);
144   E->Profile(ID, Context, true);
145 }
146 
147 DependentSizedExtVectorType::DependentSizedExtVectorType(const
148                                                          ASTContext &Context,
149                                                          QualType ElementType,
150                                                          QualType can,
151                                                          Expr *SizeExpr,
152                                                          SourceLocation loc)
153     : Type(DependentSizedExtVector, can, /*Dependent=*/true,
154            /*InstantiationDependent=*/true,
155            ElementType->isVariablyModifiedType(),
156            (ElementType->containsUnexpandedParameterPack() ||
157             (SizeExpr && SizeExpr->containsUnexpandedParameterPack()))),
158       Context(Context), SizeExpr(SizeExpr), ElementType(ElementType),
159       loc(loc)
160 {
161 }
162 
163 void
164 DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID,
165                                      const ASTContext &Context,
166                                      QualType ElementType, Expr *SizeExpr) {
167   ID.AddPointer(ElementType.getAsOpaquePtr());
168   SizeExpr->Profile(ID, Context, true);
169 }
170 
171 VectorType::VectorType(QualType vecType, unsigned nElements, QualType canonType,
172                        VectorKind vecKind)
173   : Type(Vector, canonType, vecType->isDependentType(),
174          vecType->isInstantiationDependentType(),
175          vecType->isVariablyModifiedType(),
176          vecType->containsUnexpandedParameterPack()),
177     ElementType(vecType)
178 {
179   VectorTypeBits.VecKind = vecKind;
180   VectorTypeBits.NumElements = nElements;
181 }
182 
183 VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements,
184                        QualType canonType, VectorKind vecKind)
185   : Type(tc, canonType, vecType->isDependentType(),
186          vecType->isInstantiationDependentType(),
187          vecType->isVariablyModifiedType(),
188          vecType->containsUnexpandedParameterPack()),
189     ElementType(vecType)
190 {
191   VectorTypeBits.VecKind = vecKind;
192   VectorTypeBits.NumElements = nElements;
193 }
194 
195 /// getArrayElementTypeNoTypeQual - If this is an array type, return the
196 /// element type of the array, potentially with type qualifiers missing.
197 /// This method should never be used when type qualifiers are meaningful.
198 const Type *Type::getArrayElementTypeNoTypeQual() const {
199   // If this is directly an array type, return it.
200   if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
201     return ATy->getElementType().getTypePtr();
202 
203   // If the canonical form of this type isn't the right kind, reject it.
204   if (!isa<ArrayType>(CanonicalType))
205     return nullptr;
206 
207   // If this is a typedef for an array type, strip the typedef off without
208   // losing all typedef information.
209   return cast<ArrayType>(getUnqualifiedDesugaredType())
210     ->getElementType().getTypePtr();
211 }
212 
213 /// getDesugaredType - Return the specified type with any "sugar" removed from
214 /// the type.  This takes off typedefs, typeof's etc.  If the outer level of
215 /// the type is already concrete, it returns it unmodified.  This is similar
216 /// to getting the canonical type, but it doesn't remove *all* typedefs.  For
217 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
218 /// concrete.
219 QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) {
220   SplitQualType split = getSplitDesugaredType(T);
221   return Context.getQualifiedType(split.Ty, split.Quals);
222 }
223 
224 QualType QualType::getSingleStepDesugaredTypeImpl(QualType type,
225                                                   const ASTContext &Context) {
226   SplitQualType split = type.split();
227   QualType desugar = split.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
228   return Context.getQualifiedType(desugar, split.Quals);
229 }
230 
231 QualType Type::getLocallyUnqualifiedSingleStepDesugaredType() const {
232   switch (getTypeClass()) {
233 #define ABSTRACT_TYPE(Class, Parent)
234 #define TYPE(Class, Parent) \
235   case Type::Class: { \
236     const Class##Type *ty = cast<Class##Type>(this); \
237     if (!ty->isSugared()) return QualType(ty, 0); \
238     return ty->desugar(); \
239   }
240 #include "clang/AST/TypeNodes.def"
241   }
242   llvm_unreachable("bad type kind!");
243 }
244 
245 SplitQualType QualType::getSplitDesugaredType(QualType T) {
246   QualifierCollector Qs;
247 
248   QualType Cur = T;
249   while (true) {
250     const Type *CurTy = Qs.strip(Cur);
251     switch (CurTy->getTypeClass()) {
252 #define ABSTRACT_TYPE(Class, Parent)
253 #define TYPE(Class, Parent) \
254     case Type::Class: { \
255       const Class##Type *Ty = cast<Class##Type>(CurTy); \
256       if (!Ty->isSugared()) \
257         return SplitQualType(Ty, Qs); \
258       Cur = Ty->desugar(); \
259       break; \
260     }
261 #include "clang/AST/TypeNodes.def"
262     }
263   }
264 }
265 
266 SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) {
267   SplitQualType split = type.split();
268 
269   // All the qualifiers we've seen so far.
270   Qualifiers quals = split.Quals;
271 
272   // The last type node we saw with any nodes inside it.
273   const Type *lastTypeWithQuals = split.Ty;
274 
275   while (true) {
276     QualType next;
277 
278     // Do a single-step desugar, aborting the loop if the type isn't
279     // sugared.
280     switch (split.Ty->getTypeClass()) {
281 #define ABSTRACT_TYPE(Class, Parent)
282 #define TYPE(Class, Parent) \
283     case Type::Class: { \
284       const Class##Type *ty = cast<Class##Type>(split.Ty); \
285       if (!ty->isSugared()) goto done; \
286       next = ty->desugar(); \
287       break; \
288     }
289 #include "clang/AST/TypeNodes.def"
290     }
291 
292     // Otherwise, split the underlying type.  If that yields qualifiers,
293     // update the information.
294     split = next.split();
295     if (!split.Quals.empty()) {
296       lastTypeWithQuals = split.Ty;
297       quals.addConsistentQualifiers(split.Quals);
298     }
299   }
300 
301  done:
302   return SplitQualType(lastTypeWithQuals, quals);
303 }
304 
305 QualType QualType::IgnoreParens(QualType T) {
306   // FIXME: this seems inherently un-qualifiers-safe.
307   while (const ParenType *PT = T->getAs<ParenType>())
308     T = PT->getInnerType();
309   return T;
310 }
311 
312 /// \brief This will check for a T (which should be a Type which can act as
313 /// sugar, such as a TypedefType) by removing any existing sugar until it
314 /// reaches a T or a non-sugared type.
315 template<typename T> static const T *getAsSugar(const Type *Cur) {
316   while (true) {
317     if (const T *Sugar = dyn_cast<T>(Cur))
318       return Sugar;
319     switch (Cur->getTypeClass()) {
320 #define ABSTRACT_TYPE(Class, Parent)
321 #define TYPE(Class, Parent) \
322     case Type::Class: { \
323       const Class##Type *Ty = cast<Class##Type>(Cur); \
324       if (!Ty->isSugared()) return 0; \
325       Cur = Ty->desugar().getTypePtr(); \
326       break; \
327     }
328 #include "clang/AST/TypeNodes.def"
329     }
330   }
331 }
332 
333 template <> const TypedefType *Type::getAs() const {
334   return getAsSugar<TypedefType>(this);
335 }
336 
337 template <> const TemplateSpecializationType *Type::getAs() const {
338   return getAsSugar<TemplateSpecializationType>(this);
339 }
340 
341 template <> const AttributedType *Type::getAs() const {
342   return getAsSugar<AttributedType>(this);
343 }
344 
345 /// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
346 /// sugar off the given type.  This should produce an object of the
347 /// same dynamic type as the canonical type.
348 const Type *Type::getUnqualifiedDesugaredType() const {
349   const Type *Cur = this;
350 
351   while (true) {
352     switch (Cur->getTypeClass()) {
353 #define ABSTRACT_TYPE(Class, Parent)
354 #define TYPE(Class, Parent) \
355     case Class: { \
356       const Class##Type *Ty = cast<Class##Type>(Cur); \
357       if (!Ty->isSugared()) return Cur; \
358       Cur = Ty->desugar().getTypePtr(); \
359       break; \
360     }
361 #include "clang/AST/TypeNodes.def"
362     }
363   }
364 }
365 bool Type::isClassType() const {
366   if (const RecordType *RT = getAs<RecordType>())
367     return RT->getDecl()->isClass();
368   return false;
369 }
370 bool Type::isStructureType() const {
371   if (const RecordType *RT = getAs<RecordType>())
372     return RT->getDecl()->isStruct();
373   return false;
374 }
375 bool Type::isInterfaceType() const {
376   if (const RecordType *RT = getAs<RecordType>())
377     return RT->getDecl()->isInterface();
378   return false;
379 }
380 bool Type::isStructureOrClassType() const {
381   if (const RecordType *RT = getAs<RecordType>()) {
382     RecordDecl *RD = RT->getDecl();
383     return RD->isStruct() || RD->isClass() || RD->isInterface();
384   }
385   return false;
386 }
387 bool Type::isVoidPointerType() const {
388   if (const PointerType *PT = getAs<PointerType>())
389     return PT->getPointeeType()->isVoidType();
390   return false;
391 }
392 
393 bool Type::isUnionType() const {
394   if (const RecordType *RT = getAs<RecordType>())
395     return RT->getDecl()->isUnion();
396   return false;
397 }
398 
399 bool Type::isComplexType() const {
400   if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
401     return CT->getElementType()->isFloatingType();
402   return false;
403 }
404 
405 bool Type::isComplexIntegerType() const {
406   // Check for GCC complex integer extension.
407   return getAsComplexIntegerType();
408 }
409 
410 const ComplexType *Type::getAsComplexIntegerType() const {
411   if (const ComplexType *Complex = getAs<ComplexType>())
412     if (Complex->getElementType()->isIntegerType())
413       return Complex;
414   return nullptr;
415 }
416 
417 QualType Type::getPointeeType() const {
418   if (const PointerType *PT = getAs<PointerType>())
419     return PT->getPointeeType();
420   if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
421     return OPT->getPointeeType();
422   if (const BlockPointerType *BPT = getAs<BlockPointerType>())
423     return BPT->getPointeeType();
424   if (const ReferenceType *RT = getAs<ReferenceType>())
425     return RT->getPointeeType();
426   if (const MemberPointerType *MPT = getAs<MemberPointerType>())
427     return MPT->getPointeeType();
428   if (const DecayedType *DT = getAs<DecayedType>())
429     return DT->getPointeeType();
430   return QualType();
431 }
432 
433 const RecordType *Type::getAsStructureType() const {
434   // If this is directly a structure type, return it.
435   if (const RecordType *RT = dyn_cast<RecordType>(this)) {
436     if (RT->getDecl()->isStruct())
437       return RT;
438   }
439 
440   // If the canonical form of this type isn't the right kind, reject it.
441   if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
442     if (!RT->getDecl()->isStruct())
443       return nullptr;
444 
445     // If this is a typedef for a structure type, strip the typedef off without
446     // losing all typedef information.
447     return cast<RecordType>(getUnqualifiedDesugaredType());
448   }
449   return nullptr;
450 }
451 
452 const RecordType *Type::getAsUnionType() const {
453   // If this is directly a union type, return it.
454   if (const RecordType *RT = dyn_cast<RecordType>(this)) {
455     if (RT->getDecl()->isUnion())
456       return RT;
457   }
458 
459   // If the canonical form of this type isn't the right kind, reject it.
460   if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
461     if (!RT->getDecl()->isUnion())
462       return nullptr;
463 
464     // If this is a typedef for a union type, strip the typedef off without
465     // losing all typedef information.
466     return cast<RecordType>(getUnqualifiedDesugaredType());
467   }
468 
469   return nullptr;
470 }
471 
472 ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base,
473                                ObjCProtocolDecl * const *Protocols,
474                                unsigned NumProtocols)
475   : Type(ObjCObject, Canonical, false, false, false, false),
476     BaseType(Base)
477 {
478   ObjCObjectTypeBits.NumProtocols = NumProtocols;
479   assert(getNumProtocols() == NumProtocols &&
480          "bitfield overflow in protocol count");
481   if (NumProtocols)
482     memcpy(getProtocolStorage(), Protocols,
483            NumProtocols * sizeof(ObjCProtocolDecl*));
484 }
485 
486 const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const {
487   // There is no sugar for ObjCObjectType's, just return the canonical
488   // type pointer if it is the right class.  There is no typedef information to
489   // return and these cannot be Address-space qualified.
490   if (const ObjCObjectType *T = getAs<ObjCObjectType>())
491     if (T->getNumProtocols() && T->getInterface())
492       return T;
493   return nullptr;
494 }
495 
496 bool Type::isObjCQualifiedInterfaceType() const {
497   return getAsObjCQualifiedInterfaceType() != nullptr;
498 }
499 
500 const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
501   // There is no sugar for ObjCQualifiedIdType's, just return the canonical
502   // type pointer if it is the right class.
503   if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
504     if (OPT->isObjCQualifiedIdType())
505       return OPT;
506   }
507   return nullptr;
508 }
509 
510 const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const {
511   // There is no sugar for ObjCQualifiedClassType's, just return the canonical
512   // type pointer if it is the right class.
513   if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
514     if (OPT->isObjCQualifiedClassType())
515       return OPT;
516   }
517   return nullptr;
518 }
519 
520 const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
521   if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
522     if (OPT->getInterfaceType())
523       return OPT;
524   }
525   return nullptr;
526 }
527 
528 const CXXRecordDecl *Type::getPointeeCXXRecordDecl() const {
529   QualType PointeeType;
530   if (const PointerType *PT = getAs<PointerType>())
531     PointeeType = PT->getPointeeType();
532   else if (const ReferenceType *RT = getAs<ReferenceType>())
533     PointeeType = RT->getPointeeType();
534   else
535     return nullptr;
536 
537   if (const RecordType *RT = PointeeType->getAs<RecordType>())
538     return dyn_cast<CXXRecordDecl>(RT->getDecl());
539 
540   return nullptr;
541 }
542 
543 CXXRecordDecl *Type::getAsCXXRecordDecl() const {
544   return dyn_cast_or_null<CXXRecordDecl>(getAsTagDecl());
545 }
546 
547 TagDecl *Type::getAsTagDecl() const {
548   if (const auto *TT = getAs<TagType>())
549     return cast<TagDecl>(TT->getDecl());
550   if (const auto *Injected = getAs<InjectedClassNameType>())
551     return Injected->getDecl();
552 
553   return nullptr;
554 }
555 
556 namespace {
557   class GetContainedAutoVisitor :
558     public TypeVisitor<GetContainedAutoVisitor, AutoType*> {
559   public:
560     using TypeVisitor<GetContainedAutoVisitor, AutoType*>::Visit;
561     AutoType *Visit(QualType T) {
562       if (T.isNull())
563         return nullptr;
564       return Visit(T.getTypePtr());
565     }
566 
567     // The 'auto' type itself.
568     AutoType *VisitAutoType(const AutoType *AT) {
569       return const_cast<AutoType*>(AT);
570     }
571 
572     // Only these types can contain the desired 'auto' type.
573     AutoType *VisitPointerType(const PointerType *T) {
574       return Visit(T->getPointeeType());
575     }
576     AutoType *VisitBlockPointerType(const BlockPointerType *T) {
577       return Visit(T->getPointeeType());
578     }
579     AutoType *VisitReferenceType(const ReferenceType *T) {
580       return Visit(T->getPointeeTypeAsWritten());
581     }
582     AutoType *VisitMemberPointerType(const MemberPointerType *T) {
583       return Visit(T->getPointeeType());
584     }
585     AutoType *VisitArrayType(const ArrayType *T) {
586       return Visit(T->getElementType());
587     }
588     AutoType *VisitDependentSizedExtVectorType(
589       const DependentSizedExtVectorType *T) {
590       return Visit(T->getElementType());
591     }
592     AutoType *VisitVectorType(const VectorType *T) {
593       return Visit(T->getElementType());
594     }
595     AutoType *VisitFunctionType(const FunctionType *T) {
596       return Visit(T->getReturnType());
597     }
598     AutoType *VisitParenType(const ParenType *T) {
599       return Visit(T->getInnerType());
600     }
601     AutoType *VisitAttributedType(const AttributedType *T) {
602       return Visit(T->getModifiedType());
603     }
604     AutoType *VisitAdjustedType(const AdjustedType *T) {
605       return Visit(T->getOriginalType());
606     }
607   };
608 }
609 
610 AutoType *Type::getContainedAutoType() const {
611   return GetContainedAutoVisitor().Visit(this);
612 }
613 
614 bool Type::hasIntegerRepresentation() const {
615   if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
616     return VT->getElementType()->isIntegerType();
617   else
618     return isIntegerType();
619 }
620 
621 /// \brief Determine whether this type is an integral type.
622 ///
623 /// This routine determines whether the given type is an integral type per
624 /// C++ [basic.fundamental]p7. Although the C standard does not define the
625 /// term "integral type", it has a similar term "integer type", and in C++
626 /// the two terms are equivalent. However, C's "integer type" includes
627 /// enumeration types, while C++'s "integer type" does not. The \c ASTContext
628 /// parameter is used to determine whether we should be following the C or
629 /// C++ rules when determining whether this type is an integral/integer type.
630 ///
631 /// For cases where C permits "an integer type" and C++ permits "an integral
632 /// type", use this routine.
633 ///
634 /// For cases where C permits "an integer type" and C++ permits "an integral
635 /// or enumeration type", use \c isIntegralOrEnumerationType() instead.
636 ///
637 /// \param Ctx The context in which this type occurs.
638 ///
639 /// \returns true if the type is considered an integral type, false otherwise.
640 bool Type::isIntegralType(ASTContext &Ctx) const {
641   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
642     return BT->getKind() >= BuiltinType::Bool &&
643     BT->getKind() <= BuiltinType::Int128;
644 
645   if (!Ctx.getLangOpts().CPlusPlus)
646     if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
647       return ET->getDecl()->isComplete(); // Complete enum types are integral in C.
648 
649   return false;
650 }
651 
652 
653 bool Type::isIntegralOrUnscopedEnumerationType() const {
654   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
655     return BT->getKind() >= BuiltinType::Bool &&
656            BT->getKind() <= BuiltinType::Int128;
657 
658   // Check for a complete enum type; incomplete enum types are not properly an
659   // enumeration type in the sense required here.
660   // C++0x: However, if the underlying type of the enum is fixed, it is
661   // considered complete.
662   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
663     return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
664 
665   return false;
666 }
667 
668 
669 
670 bool Type::isCharType() const {
671   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
672     return BT->getKind() == BuiltinType::Char_U ||
673            BT->getKind() == BuiltinType::UChar ||
674            BT->getKind() == BuiltinType::Char_S ||
675            BT->getKind() == BuiltinType::SChar;
676   return false;
677 }
678 
679 bool Type::isWideCharType() const {
680   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
681     return BT->getKind() == BuiltinType::WChar_S ||
682            BT->getKind() == BuiltinType::WChar_U;
683   return false;
684 }
685 
686 bool Type::isChar16Type() const {
687   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
688     return BT->getKind() == BuiltinType::Char16;
689   return false;
690 }
691 
692 bool Type::isChar32Type() const {
693   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
694     return BT->getKind() == BuiltinType::Char32;
695   return false;
696 }
697 
698 /// \brief Determine whether this type is any of the built-in character
699 /// types.
700 bool Type::isAnyCharacterType() const {
701   const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType);
702   if (!BT) return false;
703   switch (BT->getKind()) {
704   default: return false;
705   case BuiltinType::Char_U:
706   case BuiltinType::UChar:
707   case BuiltinType::WChar_U:
708   case BuiltinType::Char16:
709   case BuiltinType::Char32:
710   case BuiltinType::Char_S:
711   case BuiltinType::SChar:
712   case BuiltinType::WChar_S:
713     return true;
714   }
715 }
716 
717 /// isSignedIntegerType - Return true if this is an integer type that is
718 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
719 /// an enum decl which has a signed representation
720 bool Type::isSignedIntegerType() const {
721   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
722     return BT->getKind() >= BuiltinType::Char_S &&
723            BT->getKind() <= BuiltinType::Int128;
724   }
725 
726   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
727     // Incomplete enum types are not treated as integer types.
728     // FIXME: In C++, enum types are never integer types.
729     if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
730       return ET->getDecl()->getIntegerType()->isSignedIntegerType();
731   }
732 
733   return false;
734 }
735 
736 bool Type::isSignedIntegerOrEnumerationType() const {
737   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
738     return BT->getKind() >= BuiltinType::Char_S &&
739     BT->getKind() <= BuiltinType::Int128;
740   }
741 
742   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
743     if (ET->getDecl()->isComplete())
744       return ET->getDecl()->getIntegerType()->isSignedIntegerType();
745   }
746 
747   return false;
748 }
749 
750 bool Type::hasSignedIntegerRepresentation() const {
751   if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
752     return VT->getElementType()->isSignedIntegerOrEnumerationType();
753   else
754     return isSignedIntegerOrEnumerationType();
755 }
756 
757 /// isUnsignedIntegerType - Return true if this is an integer type that is
758 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
759 /// decl which has an unsigned representation
760 bool Type::isUnsignedIntegerType() const {
761   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
762     return BT->getKind() >= BuiltinType::Bool &&
763            BT->getKind() <= BuiltinType::UInt128;
764   }
765 
766   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
767     // Incomplete enum types are not treated as integer types.
768     // FIXME: In C++, enum types are never integer types.
769     if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
770       return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
771   }
772 
773   return false;
774 }
775 
776 bool Type::isUnsignedIntegerOrEnumerationType() const {
777   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
778     return BT->getKind() >= BuiltinType::Bool &&
779     BT->getKind() <= BuiltinType::UInt128;
780   }
781 
782   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
783     if (ET->getDecl()->isComplete())
784       return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
785   }
786 
787   return false;
788 }
789 
790 bool Type::hasUnsignedIntegerRepresentation() const {
791   if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
792     return VT->getElementType()->isUnsignedIntegerOrEnumerationType();
793   else
794     return isUnsignedIntegerOrEnumerationType();
795 }
796 
797 bool Type::isFloatingType() const {
798   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
799     return BT->getKind() >= BuiltinType::Half &&
800            BT->getKind() <= BuiltinType::LongDouble;
801   if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
802     return CT->getElementType()->isFloatingType();
803   return false;
804 }
805 
806 bool Type::hasFloatingRepresentation() const {
807   if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
808     return VT->getElementType()->isFloatingType();
809   else
810     return isFloatingType();
811 }
812 
813 bool Type::isRealFloatingType() const {
814   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
815     return BT->isFloatingPoint();
816   return false;
817 }
818 
819 bool Type::isRealType() const {
820   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
821     return BT->getKind() >= BuiltinType::Bool &&
822            BT->getKind() <= BuiltinType::LongDouble;
823   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
824       return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
825   return false;
826 }
827 
828 bool Type::isArithmeticType() const {
829   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
830     return BT->getKind() >= BuiltinType::Bool &&
831            BT->getKind() <= BuiltinType::LongDouble;
832   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
833     // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
834     // If a body isn't seen by the time we get here, return false.
835     //
836     // C++0x: Enumerations are not arithmetic types. For now, just return
837     // false for scoped enumerations since that will disable any
838     // unwanted implicit conversions.
839     return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete();
840   return isa<ComplexType>(CanonicalType);
841 }
842 
843 Type::ScalarTypeKind Type::getScalarTypeKind() const {
844   assert(isScalarType());
845 
846   const Type *T = CanonicalType.getTypePtr();
847   if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) {
848     if (BT->getKind() == BuiltinType::Bool) return STK_Bool;
849     if (BT->getKind() == BuiltinType::NullPtr) return STK_CPointer;
850     if (BT->isInteger()) return STK_Integral;
851     if (BT->isFloatingPoint()) return STK_Floating;
852     llvm_unreachable("unknown scalar builtin type");
853   } else if (isa<PointerType>(T)) {
854     return STK_CPointer;
855   } else if (isa<BlockPointerType>(T)) {
856     return STK_BlockPointer;
857   } else if (isa<ObjCObjectPointerType>(T)) {
858     return STK_ObjCObjectPointer;
859   } else if (isa<MemberPointerType>(T)) {
860     return STK_MemberPointer;
861   } else if (isa<EnumType>(T)) {
862     assert(cast<EnumType>(T)->getDecl()->isComplete());
863     return STK_Integral;
864   } else if (const ComplexType *CT = dyn_cast<ComplexType>(T)) {
865     if (CT->getElementType()->isRealFloatingType())
866       return STK_FloatingComplex;
867     return STK_IntegralComplex;
868   }
869 
870   llvm_unreachable("unknown scalar type");
871 }
872 
873 /// \brief Determines whether the type is a C++ aggregate type or C
874 /// aggregate or union type.
875 ///
876 /// An aggregate type is an array or a class type (struct, union, or
877 /// class) that has no user-declared constructors, no private or
878 /// protected non-static data members, no base classes, and no virtual
879 /// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
880 /// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
881 /// includes union types.
882 bool Type::isAggregateType() const {
883   if (const RecordType *Record = dyn_cast<RecordType>(CanonicalType)) {
884     if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
885       return ClassDecl->isAggregate();
886 
887     return true;
888   }
889 
890   return isa<ArrayType>(CanonicalType);
891 }
892 
893 /// isConstantSizeType - Return true if this is not a variable sized type,
894 /// according to the rules of C99 6.7.5p3.  It is not legal to call this on
895 /// incomplete types or dependent types.
896 bool Type::isConstantSizeType() const {
897   assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
898   assert(!isDependentType() && "This doesn't make sense for dependent types");
899   // The VAT must have a size, as it is known to be complete.
900   return !isa<VariableArrayType>(CanonicalType);
901 }
902 
903 /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
904 /// - a type that can describe objects, but which lacks information needed to
905 /// determine its size.
906 bool Type::isIncompleteType(NamedDecl **Def) const {
907   if (Def)
908     *Def = nullptr;
909 
910   switch (CanonicalType->getTypeClass()) {
911   default: return false;
912   case Builtin:
913     // Void is the only incomplete builtin type.  Per C99 6.2.5p19, it can never
914     // be completed.
915     return isVoidType();
916   case Enum: {
917     EnumDecl *EnumD = cast<EnumType>(CanonicalType)->getDecl();
918     if (Def)
919       *Def = EnumD;
920 
921     // An enumeration with fixed underlying type is complete (C++0x 7.2p3).
922     if (EnumD->isFixed())
923       return false;
924 
925     return !EnumD->isCompleteDefinition();
926   }
927   case Record: {
928     // A tagged type (struct/union/enum/class) is incomplete if the decl is a
929     // forward declaration, but not a full definition (C99 6.2.5p22).
930     RecordDecl *Rec = cast<RecordType>(CanonicalType)->getDecl();
931     if (Def)
932       *Def = Rec;
933     return !Rec->isCompleteDefinition();
934   }
935   case ConstantArray:
936     // An array is incomplete if its element type is incomplete
937     // (C++ [dcl.array]p1).
938     // We don't handle variable arrays (they're not allowed in C++) or
939     // dependent-sized arrays (dependent types are never treated as incomplete).
940     return cast<ArrayType>(CanonicalType)->getElementType()
941              ->isIncompleteType(Def);
942   case IncompleteArray:
943     // An array of unknown size is an incomplete type (C99 6.2.5p22).
944     return true;
945   case ObjCObject:
946     return cast<ObjCObjectType>(CanonicalType)->getBaseType()
947              ->isIncompleteType(Def);
948   case ObjCInterface: {
949     // ObjC interfaces are incomplete if they are @class, not @interface.
950     ObjCInterfaceDecl *Interface
951       = cast<ObjCInterfaceType>(CanonicalType)->getDecl();
952     if (Def)
953       *Def = Interface;
954     return !Interface->hasDefinition();
955   }
956   }
957 }
958 
959 bool QualType::isPODType(ASTContext &Context) const {
960   // C++11 has a more relaxed definition of POD.
961   if (Context.getLangOpts().CPlusPlus11)
962     return isCXX11PODType(Context);
963 
964   return isCXX98PODType(Context);
965 }
966 
967 bool QualType::isCXX98PODType(ASTContext &Context) const {
968   // The compiler shouldn't query this for incomplete types, but the user might.
969   // We return false for that case. Except for incomplete arrays of PODs, which
970   // are PODs according to the standard.
971   if (isNull())
972     return 0;
973 
974   if ((*this)->isIncompleteArrayType())
975     return Context.getBaseElementType(*this).isCXX98PODType(Context);
976 
977   if ((*this)->isIncompleteType())
978     return false;
979 
980   if (Context.getLangOpts().ObjCAutoRefCount) {
981     switch (getObjCLifetime()) {
982     case Qualifiers::OCL_ExplicitNone:
983       return true;
984 
985     case Qualifiers::OCL_Strong:
986     case Qualifiers::OCL_Weak:
987     case Qualifiers::OCL_Autoreleasing:
988       return false;
989 
990     case Qualifiers::OCL_None:
991       break;
992     }
993   }
994 
995   QualType CanonicalType = getTypePtr()->CanonicalType;
996   switch (CanonicalType->getTypeClass()) {
997     // Everything not explicitly mentioned is not POD.
998   default: return false;
999   case Type::VariableArray:
1000   case Type::ConstantArray:
1001     // IncompleteArray is handled above.
1002     return Context.getBaseElementType(*this).isCXX98PODType(Context);
1003 
1004   case Type::ObjCObjectPointer:
1005   case Type::BlockPointer:
1006   case Type::Builtin:
1007   case Type::Complex:
1008   case Type::Pointer:
1009   case Type::MemberPointer:
1010   case Type::Vector:
1011   case Type::ExtVector:
1012     return true;
1013 
1014   case Type::Enum:
1015     return true;
1016 
1017   case Type::Record:
1018     if (CXXRecordDecl *ClassDecl
1019           = dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
1020       return ClassDecl->isPOD();
1021 
1022     // C struct/union is POD.
1023     return true;
1024   }
1025 }
1026 
1027 bool QualType::isTrivialType(ASTContext &Context) const {
1028   // The compiler shouldn't query this for incomplete types, but the user might.
1029   // We return false for that case. Except for incomplete arrays of PODs, which
1030   // are PODs according to the standard.
1031   if (isNull())
1032     return 0;
1033 
1034   if ((*this)->isArrayType())
1035     return Context.getBaseElementType(*this).isTrivialType(Context);
1036 
1037   // Return false for incomplete types after skipping any incomplete array
1038   // types which are expressly allowed by the standard and thus our API.
1039   if ((*this)->isIncompleteType())
1040     return false;
1041 
1042   if (Context.getLangOpts().ObjCAutoRefCount) {
1043     switch (getObjCLifetime()) {
1044     case Qualifiers::OCL_ExplicitNone:
1045       return true;
1046 
1047     case Qualifiers::OCL_Strong:
1048     case Qualifiers::OCL_Weak:
1049     case Qualifiers::OCL_Autoreleasing:
1050       return false;
1051 
1052     case Qualifiers::OCL_None:
1053       if ((*this)->isObjCLifetimeType())
1054         return false;
1055       break;
1056     }
1057   }
1058 
1059   QualType CanonicalType = getTypePtr()->CanonicalType;
1060   if (CanonicalType->isDependentType())
1061     return false;
1062 
1063   // C++0x [basic.types]p9:
1064   //   Scalar types, trivial class types, arrays of such types, and
1065   //   cv-qualified versions of these types are collectively called trivial
1066   //   types.
1067 
1068   // As an extension, Clang treats vector types as Scalar types.
1069   if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
1070     return true;
1071   if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
1072     if (const CXXRecordDecl *ClassDecl =
1073         dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1074       // C++11 [class]p6:
1075       //   A trivial class is a class that has a default constructor,
1076       //   has no non-trivial default constructors, and is trivially
1077       //   copyable.
1078       return ClassDecl->hasDefaultConstructor() &&
1079              !ClassDecl->hasNonTrivialDefaultConstructor() &&
1080              ClassDecl->isTriviallyCopyable();
1081     }
1082 
1083     return true;
1084   }
1085 
1086   // No other types can match.
1087   return false;
1088 }
1089 
1090 bool QualType::isTriviallyCopyableType(ASTContext &Context) const {
1091   if ((*this)->isArrayType())
1092     return Context.getBaseElementType(*this).isTriviallyCopyableType(Context);
1093 
1094   if (Context.getLangOpts().ObjCAutoRefCount) {
1095     switch (getObjCLifetime()) {
1096     case Qualifiers::OCL_ExplicitNone:
1097       return true;
1098 
1099     case Qualifiers::OCL_Strong:
1100     case Qualifiers::OCL_Weak:
1101     case Qualifiers::OCL_Autoreleasing:
1102       return false;
1103 
1104     case Qualifiers::OCL_None:
1105       if ((*this)->isObjCLifetimeType())
1106         return false;
1107       break;
1108     }
1109   }
1110 
1111   // C++11 [basic.types]p9
1112   //   Scalar types, trivially copyable class types, arrays of such types, and
1113   //   non-volatile const-qualified versions of these types are collectively
1114   //   called trivially copyable types.
1115 
1116   QualType CanonicalType = getCanonicalType();
1117   if (CanonicalType->isDependentType())
1118     return false;
1119 
1120   if (CanonicalType.isVolatileQualified())
1121     return false;
1122 
1123   // Return false for incomplete types after skipping any incomplete array types
1124   // which are expressly allowed by the standard and thus our API.
1125   if (CanonicalType->isIncompleteType())
1126     return false;
1127 
1128   // As an extension, Clang treats vector types as Scalar types.
1129   if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
1130     return true;
1131 
1132   if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
1133     if (const CXXRecordDecl *ClassDecl =
1134           dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1135       if (!ClassDecl->isTriviallyCopyable()) return false;
1136     }
1137 
1138     return true;
1139   }
1140 
1141   // No other types can match.
1142   return false;
1143 }
1144 
1145 
1146 
1147 bool Type::isLiteralType(const ASTContext &Ctx) const {
1148   if (isDependentType())
1149     return false;
1150 
1151   // C++1y [basic.types]p10:
1152   //   A type is a literal type if it is:
1153   //   -- cv void; or
1154   if (Ctx.getLangOpts().CPlusPlus14 && isVoidType())
1155     return true;
1156 
1157   // C++11 [basic.types]p10:
1158   //   A type is a literal type if it is:
1159   //   [...]
1160   //   -- an array of literal type other than an array of runtime bound; or
1161   if (isVariableArrayType())
1162     return false;
1163   const Type *BaseTy = getBaseElementTypeUnsafe();
1164   assert(BaseTy && "NULL element type");
1165 
1166   // Return false for incomplete types after skipping any incomplete array
1167   // types; those are expressly allowed by the standard and thus our API.
1168   if (BaseTy->isIncompleteType())
1169     return false;
1170 
1171   // C++11 [basic.types]p10:
1172   //   A type is a literal type if it is:
1173   //    -- a scalar type; or
1174   // As an extension, Clang treats vector types and complex types as
1175   // literal types.
1176   if (BaseTy->isScalarType() || BaseTy->isVectorType() ||
1177       BaseTy->isAnyComplexType())
1178     return true;
1179   //    -- a reference type; or
1180   if (BaseTy->isReferenceType())
1181     return true;
1182   //    -- a class type that has all of the following properties:
1183   if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1184     //    -- a trivial destructor,
1185     //    -- every constructor call and full-expression in the
1186     //       brace-or-equal-initializers for non-static data members (if any)
1187     //       is a constant expression,
1188     //    -- it is an aggregate type or has at least one constexpr
1189     //       constructor or constructor template that is not a copy or move
1190     //       constructor, and
1191     //    -- all non-static data members and base classes of literal types
1192     //
1193     // We resolve DR1361 by ignoring the second bullet.
1194     if (const CXXRecordDecl *ClassDecl =
1195         dyn_cast<CXXRecordDecl>(RT->getDecl()))
1196       return ClassDecl->isLiteral();
1197 
1198     return true;
1199   }
1200 
1201   // We treat _Atomic T as a literal type if T is a literal type.
1202   if (const AtomicType *AT = BaseTy->getAs<AtomicType>())
1203     return AT->getValueType()->isLiteralType(Ctx);
1204 
1205   // If this type hasn't been deduced yet, then conservatively assume that
1206   // it'll work out to be a literal type.
1207   if (isa<AutoType>(BaseTy->getCanonicalTypeInternal()))
1208     return true;
1209 
1210   return false;
1211 }
1212 
1213 bool Type::isStandardLayoutType() const {
1214   if (isDependentType())
1215     return false;
1216 
1217   // C++0x [basic.types]p9:
1218   //   Scalar types, standard-layout class types, arrays of such types, and
1219   //   cv-qualified versions of these types are collectively called
1220   //   standard-layout types.
1221   const Type *BaseTy = getBaseElementTypeUnsafe();
1222   assert(BaseTy && "NULL element type");
1223 
1224   // Return false for incomplete types after skipping any incomplete array
1225   // types which are expressly allowed by the standard and thus our API.
1226   if (BaseTy->isIncompleteType())
1227     return false;
1228 
1229   // As an extension, Clang treats vector types as Scalar types.
1230   if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
1231   if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1232     if (const CXXRecordDecl *ClassDecl =
1233         dyn_cast<CXXRecordDecl>(RT->getDecl()))
1234       if (!ClassDecl->isStandardLayout())
1235         return false;
1236 
1237     // Default to 'true' for non-C++ class types.
1238     // FIXME: This is a bit dubious, but plain C structs should trivially meet
1239     // all the requirements of standard layout classes.
1240     return true;
1241   }
1242 
1243   // No other types can match.
1244   return false;
1245 }
1246 
1247 // This is effectively the intersection of isTrivialType and
1248 // isStandardLayoutType. We implement it directly to avoid redundant
1249 // conversions from a type to a CXXRecordDecl.
1250 bool QualType::isCXX11PODType(ASTContext &Context) const {
1251   const Type *ty = getTypePtr();
1252   if (ty->isDependentType())
1253     return false;
1254 
1255   if (Context.getLangOpts().ObjCAutoRefCount) {
1256     switch (getObjCLifetime()) {
1257     case Qualifiers::OCL_ExplicitNone:
1258       return true;
1259 
1260     case Qualifiers::OCL_Strong:
1261     case Qualifiers::OCL_Weak:
1262     case Qualifiers::OCL_Autoreleasing:
1263       return false;
1264 
1265     case Qualifiers::OCL_None:
1266       break;
1267     }
1268   }
1269 
1270   // C++11 [basic.types]p9:
1271   //   Scalar types, POD classes, arrays of such types, and cv-qualified
1272   //   versions of these types are collectively called trivial types.
1273   const Type *BaseTy = ty->getBaseElementTypeUnsafe();
1274   assert(BaseTy && "NULL element type");
1275 
1276   // Return false for incomplete types after skipping any incomplete array
1277   // types which are expressly allowed by the standard and thus our API.
1278   if (BaseTy->isIncompleteType())
1279     return false;
1280 
1281   // As an extension, Clang treats vector types as Scalar types.
1282   if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
1283   if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1284     if (const CXXRecordDecl *ClassDecl =
1285         dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1286       // C++11 [class]p10:
1287       //   A POD struct is a non-union class that is both a trivial class [...]
1288       if (!ClassDecl->isTrivial()) return false;
1289 
1290       // C++11 [class]p10:
1291       //   A POD struct is a non-union class that is both a trivial class and
1292       //   a standard-layout class [...]
1293       if (!ClassDecl->isStandardLayout()) return false;
1294 
1295       // C++11 [class]p10:
1296       //   A POD struct is a non-union class that is both a trivial class and
1297       //   a standard-layout class, and has no non-static data members of type
1298       //   non-POD struct, non-POD union (or array of such types). [...]
1299       //
1300       // We don't directly query the recursive aspect as the requiremets for
1301       // both standard-layout classes and trivial classes apply recursively
1302       // already.
1303     }
1304 
1305     return true;
1306   }
1307 
1308   // No other types can match.
1309   return false;
1310 }
1311 
1312 bool Type::isPromotableIntegerType() const {
1313   if (const BuiltinType *BT = getAs<BuiltinType>())
1314     switch (BT->getKind()) {
1315     case BuiltinType::Bool:
1316     case BuiltinType::Char_S:
1317     case BuiltinType::Char_U:
1318     case BuiltinType::SChar:
1319     case BuiltinType::UChar:
1320     case BuiltinType::Short:
1321     case BuiltinType::UShort:
1322     case BuiltinType::WChar_S:
1323     case BuiltinType::WChar_U:
1324     case BuiltinType::Char16:
1325     case BuiltinType::Char32:
1326       return true;
1327     default:
1328       return false;
1329     }
1330 
1331   // Enumerated types are promotable to their compatible integer types
1332   // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1333   if (const EnumType *ET = getAs<EnumType>()){
1334     if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull()
1335         || ET->getDecl()->isScoped())
1336       return false;
1337 
1338     return true;
1339   }
1340 
1341   return false;
1342 }
1343 
1344 bool Type::isSpecifierType() const {
1345   // Note that this intentionally does not use the canonical type.
1346   switch (getTypeClass()) {
1347   case Builtin:
1348   case Record:
1349   case Enum:
1350   case Typedef:
1351   case Complex:
1352   case TypeOfExpr:
1353   case TypeOf:
1354   case TemplateTypeParm:
1355   case SubstTemplateTypeParm:
1356   case TemplateSpecialization:
1357   case Elaborated:
1358   case DependentName:
1359   case DependentTemplateSpecialization:
1360   case ObjCInterface:
1361   case ObjCObject:
1362   case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers
1363     return true;
1364   default:
1365     return false;
1366   }
1367 }
1368 
1369 ElaboratedTypeKeyword
1370 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) {
1371   switch (TypeSpec) {
1372   default: return ETK_None;
1373   case TST_typename: return ETK_Typename;
1374   case TST_class: return ETK_Class;
1375   case TST_struct: return ETK_Struct;
1376   case TST_interface: return ETK_Interface;
1377   case TST_union: return ETK_Union;
1378   case TST_enum: return ETK_Enum;
1379   }
1380 }
1381 
1382 TagTypeKind
1383 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
1384   switch(TypeSpec) {
1385   case TST_class: return TTK_Class;
1386   case TST_struct: return TTK_Struct;
1387   case TST_interface: return TTK_Interface;
1388   case TST_union: return TTK_Union;
1389   case TST_enum: return TTK_Enum;
1390   }
1391 
1392   llvm_unreachable("Type specifier is not a tag type kind.");
1393 }
1394 
1395 ElaboratedTypeKeyword
1396 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) {
1397   switch (Kind) {
1398   case TTK_Class: return ETK_Class;
1399   case TTK_Struct: return ETK_Struct;
1400   case TTK_Interface: return ETK_Interface;
1401   case TTK_Union: return ETK_Union;
1402   case TTK_Enum: return ETK_Enum;
1403   }
1404   llvm_unreachable("Unknown tag type kind.");
1405 }
1406 
1407 TagTypeKind
1408 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
1409   switch (Keyword) {
1410   case ETK_Class: return TTK_Class;
1411   case ETK_Struct: return TTK_Struct;
1412   case ETK_Interface: return TTK_Interface;
1413   case ETK_Union: return TTK_Union;
1414   case ETK_Enum: return TTK_Enum;
1415   case ETK_None: // Fall through.
1416   case ETK_Typename:
1417     llvm_unreachable("Elaborated type keyword is not a tag type kind.");
1418   }
1419   llvm_unreachable("Unknown elaborated type keyword.");
1420 }
1421 
1422 bool
1423 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
1424   switch (Keyword) {
1425   case ETK_None:
1426   case ETK_Typename:
1427     return false;
1428   case ETK_Class:
1429   case ETK_Struct:
1430   case ETK_Interface:
1431   case ETK_Union:
1432   case ETK_Enum:
1433     return true;
1434   }
1435   llvm_unreachable("Unknown elaborated type keyword.");
1436 }
1437 
1438 StringRef TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) {
1439   switch (Keyword) {
1440   case ETK_None: return "";
1441   case ETK_Typename: return "typename";
1442   case ETK_Class:  return "class";
1443   case ETK_Struct: return "struct";
1444   case ETK_Interface: return "__interface";
1445   case ETK_Union:  return "union";
1446   case ETK_Enum:   return "enum";
1447   }
1448 
1449   llvm_unreachable("Unknown elaborated type keyword.");
1450 }
1451 
1452 DependentTemplateSpecializationType::DependentTemplateSpecializationType(
1453                          ElaboratedTypeKeyword Keyword,
1454                          NestedNameSpecifier *NNS, const IdentifierInfo *Name,
1455                          unsigned NumArgs, const TemplateArgument *Args,
1456                          QualType Canon)
1457   : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true, true,
1458                     /*VariablyModified=*/false,
1459                     NNS && NNS->containsUnexpandedParameterPack()),
1460     NNS(NNS), Name(Name), NumArgs(NumArgs) {
1461   assert((!NNS || NNS->isDependent()) &&
1462          "DependentTemplateSpecializatonType requires dependent qualifier");
1463   for (unsigned I = 0; I != NumArgs; ++I) {
1464     if (Args[I].containsUnexpandedParameterPack())
1465       setContainsUnexpandedParameterPack();
1466 
1467     new (&getArgBuffer()[I]) TemplateArgument(Args[I]);
1468   }
1469 }
1470 
1471 void
1472 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1473                                              const ASTContext &Context,
1474                                              ElaboratedTypeKeyword Keyword,
1475                                              NestedNameSpecifier *Qualifier,
1476                                              const IdentifierInfo *Name,
1477                                              unsigned NumArgs,
1478                                              const TemplateArgument *Args) {
1479   ID.AddInteger(Keyword);
1480   ID.AddPointer(Qualifier);
1481   ID.AddPointer(Name);
1482   for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1483     Args[Idx].Profile(ID, Context);
1484 }
1485 
1486 bool Type::isElaboratedTypeSpecifier() const {
1487   ElaboratedTypeKeyword Keyword;
1488   if (const ElaboratedType *Elab = dyn_cast<ElaboratedType>(this))
1489     Keyword = Elab->getKeyword();
1490   else if (const DependentNameType *DepName = dyn_cast<DependentNameType>(this))
1491     Keyword = DepName->getKeyword();
1492   else if (const DependentTemplateSpecializationType *DepTST =
1493              dyn_cast<DependentTemplateSpecializationType>(this))
1494     Keyword = DepTST->getKeyword();
1495   else
1496     return false;
1497 
1498   return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
1499 }
1500 
1501 const char *Type::getTypeClassName() const {
1502   switch (TypeBits.TC) {
1503 #define ABSTRACT_TYPE(Derived, Base)
1504 #define TYPE(Derived, Base) case Derived: return #Derived;
1505 #include "clang/AST/TypeNodes.def"
1506   }
1507 
1508   llvm_unreachable("Invalid type class.");
1509 }
1510 
1511 StringRef BuiltinType::getName(const PrintingPolicy &Policy) const {
1512   switch (getKind()) {
1513   case Void:              return "void";
1514   case Bool:              return Policy.Bool ? "bool" : "_Bool";
1515   case Char_S:            return "char";
1516   case Char_U:            return "char";
1517   case SChar:             return "signed char";
1518   case Short:             return "short";
1519   case Int:               return "int";
1520   case Long:              return "long";
1521   case LongLong:          return "long long";
1522   case Int128:            return "__int128";
1523   case UChar:             return "unsigned char";
1524   case UShort:            return "unsigned short";
1525   case UInt:              return "unsigned int";
1526   case ULong:             return "unsigned long";
1527   case ULongLong:         return "unsigned long long";
1528   case UInt128:           return "unsigned __int128";
1529   case Half:              return Policy.Half ? "half" : "__fp16";
1530   case Float:             return "float";
1531   case Double:            return "double";
1532   case LongDouble:        return "long double";
1533   case WChar_S:
1534   case WChar_U:           return Policy.MSWChar ? "__wchar_t" : "wchar_t";
1535   case Char16:            return "char16_t";
1536   case Char32:            return "char32_t";
1537   case NullPtr:           return "nullptr_t";
1538   case Overload:          return "<overloaded function type>";
1539   case BoundMember:       return "<bound member function type>";
1540   case PseudoObject:      return "<pseudo-object type>";
1541   case Dependent:         return "<dependent type>";
1542   case UnknownAny:        return "<unknown type>";
1543   case ARCUnbridgedCast:  return "<ARC unbridged cast type>";
1544   case BuiltinFn:         return "<builtin fn type>";
1545   case ObjCId:            return "id";
1546   case ObjCClass:         return "Class";
1547   case ObjCSel:           return "SEL";
1548   case OCLImage1d:        return "image1d_t";
1549   case OCLImage1dArray:   return "image1d_array_t";
1550   case OCLImage1dBuffer:  return "image1d_buffer_t";
1551   case OCLImage2d:        return "image2d_t";
1552   case OCLImage2dArray:   return "image2d_array_t";
1553   case OCLImage3d:        return "image3d_t";
1554   case OCLSampler:        return "sampler_t";
1555   case OCLEvent:          return "event_t";
1556   }
1557 
1558   llvm_unreachable("Invalid builtin type.");
1559 }
1560 
1561 QualType QualType::getNonLValueExprType(const ASTContext &Context) const {
1562   if (const ReferenceType *RefType = getTypePtr()->getAs<ReferenceType>())
1563     return RefType->getPointeeType();
1564 
1565   // C++0x [basic.lval]:
1566   //   Class prvalues can have cv-qualified types; non-class prvalues always
1567   //   have cv-unqualified types.
1568   //
1569   // See also C99 6.3.2.1p2.
1570   if (!Context.getLangOpts().CPlusPlus ||
1571       (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
1572     return getUnqualifiedType();
1573 
1574   return *this;
1575 }
1576 
1577 StringRef FunctionType::getNameForCallConv(CallingConv CC) {
1578   switch (CC) {
1579   case CC_C: return "cdecl";
1580   case CC_X86StdCall: return "stdcall";
1581   case CC_X86FastCall: return "fastcall";
1582   case CC_X86ThisCall: return "thiscall";
1583   case CC_X86Pascal: return "pascal";
1584   case CC_X86VectorCall: return "vectorcall";
1585   case CC_X86_64Win64: return "ms_abi";
1586   case CC_X86_64SysV: return "sysv_abi";
1587   case CC_AAPCS: return "aapcs";
1588   case CC_AAPCS_VFP: return "aapcs-vfp";
1589   case CC_PnaclCall: return "pnaclcall";
1590   case CC_IntelOclBicc: return "intel_ocl_bicc";
1591   case CC_SpirFunction: return "spir_function";
1592   case CC_SpirKernel: return "spir_kernel";
1593   }
1594 
1595   llvm_unreachable("Invalid calling convention.");
1596 }
1597 
1598 FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> params,
1599                                      QualType canonical,
1600                                      const ExtProtoInfo &epi)
1601     : FunctionType(FunctionProto, result, canonical,
1602                    result->isDependentType(),
1603                    result->isInstantiationDependentType(),
1604                    result->isVariablyModifiedType(),
1605                    result->containsUnexpandedParameterPack(), epi.ExtInfo),
1606       NumParams(params.size()),
1607       NumExceptions(epi.ExceptionSpec.Exceptions.size()),
1608       ExceptionSpecType(epi.ExceptionSpec.Type),
1609       HasAnyConsumedParams(epi.ConsumedParameters != nullptr),
1610       Variadic(epi.Variadic), HasTrailingReturn(epi.HasTrailingReturn) {
1611   assert(NumParams == params.size() && "function has too many parameters");
1612 
1613   FunctionTypeBits.TypeQuals = epi.TypeQuals;
1614   FunctionTypeBits.RefQualifier = epi.RefQualifier;
1615 
1616   // Fill in the trailing argument array.
1617   QualType *argSlot = reinterpret_cast<QualType*>(this+1);
1618   for (unsigned i = 0; i != NumParams; ++i) {
1619     if (params[i]->isDependentType())
1620       setDependent();
1621     else if (params[i]->isInstantiationDependentType())
1622       setInstantiationDependent();
1623 
1624     if (params[i]->containsUnexpandedParameterPack())
1625       setContainsUnexpandedParameterPack();
1626 
1627     argSlot[i] = params[i];
1628   }
1629 
1630   if (getExceptionSpecType() == EST_Dynamic) {
1631     // Fill in the exception array.
1632     QualType *exnSlot = argSlot + NumParams;
1633     unsigned I = 0;
1634     for (QualType ExceptionType : epi.ExceptionSpec.Exceptions) {
1635       // Note that a dependent exception specification does *not* make
1636       // a type dependent; it's not even part of the C++ type system.
1637       if (ExceptionType->isInstantiationDependentType())
1638         setInstantiationDependent();
1639 
1640       if (ExceptionType->containsUnexpandedParameterPack())
1641         setContainsUnexpandedParameterPack();
1642 
1643       exnSlot[I++] = ExceptionType;
1644     }
1645   } else if (getExceptionSpecType() == EST_ComputedNoexcept) {
1646     // Store the noexcept expression and context.
1647     Expr **noexSlot = reinterpret_cast<Expr **>(argSlot + NumParams);
1648     *noexSlot = epi.ExceptionSpec.NoexceptExpr;
1649 
1650     if (epi.ExceptionSpec.NoexceptExpr) {
1651       if (epi.ExceptionSpec.NoexceptExpr->isValueDependent() ||
1652           epi.ExceptionSpec.NoexceptExpr->isInstantiationDependent())
1653         setInstantiationDependent();
1654 
1655       if (epi.ExceptionSpec.NoexceptExpr->containsUnexpandedParameterPack())
1656         setContainsUnexpandedParameterPack();
1657     }
1658   } else if (getExceptionSpecType() == EST_Uninstantiated) {
1659     // Store the function decl from which we will resolve our
1660     // exception specification.
1661     FunctionDecl **slot =
1662         reinterpret_cast<FunctionDecl **>(argSlot + NumParams);
1663     slot[0] = epi.ExceptionSpec.SourceDecl;
1664     slot[1] = epi.ExceptionSpec.SourceTemplate;
1665     // This exception specification doesn't make the type dependent, because
1666     // it's not instantiated as part of instantiating the type.
1667   } else if (getExceptionSpecType() == EST_Unevaluated) {
1668     // Store the function decl from which we will resolve our
1669     // exception specification.
1670     FunctionDecl **slot =
1671         reinterpret_cast<FunctionDecl **>(argSlot + NumParams);
1672     slot[0] = epi.ExceptionSpec.SourceDecl;
1673   }
1674 
1675   if (epi.ConsumedParameters) {
1676     bool *consumedParams = const_cast<bool *>(getConsumedParamsBuffer());
1677     for (unsigned i = 0; i != NumParams; ++i)
1678       consumedParams[i] = epi.ConsumedParameters[i];
1679   }
1680 }
1681 
1682 bool FunctionProtoType::hasDependentExceptionSpec() const {
1683   if (Expr *NE = getNoexceptExpr())
1684     return NE->isValueDependent();
1685   for (QualType ET : exceptions())
1686     // A pack expansion with a non-dependent pattern is still dependent,
1687     // because we don't know whether the pattern is in the exception spec
1688     // or not (that depends on whether the pack has 0 expansions).
1689     if (ET->isDependentType() || ET->getAs<PackExpansionType>())
1690       return true;
1691   return false;
1692 }
1693 
1694 FunctionProtoType::NoexceptResult
1695 FunctionProtoType::getNoexceptSpec(const ASTContext &ctx) const {
1696   ExceptionSpecificationType est = getExceptionSpecType();
1697   if (est == EST_BasicNoexcept)
1698     return NR_Nothrow;
1699 
1700   if (est != EST_ComputedNoexcept)
1701     return NR_NoNoexcept;
1702 
1703   Expr *noexceptExpr = getNoexceptExpr();
1704   if (!noexceptExpr)
1705     return NR_BadNoexcept;
1706   if (noexceptExpr->isValueDependent())
1707     return NR_Dependent;
1708 
1709   llvm::APSInt value;
1710   bool isICE = noexceptExpr->isIntegerConstantExpr(value, ctx, nullptr,
1711                                                    /*evaluated*/false);
1712   (void)isICE;
1713   assert(isICE && "AST should not contain bad noexcept expressions.");
1714 
1715   return value.getBoolValue() ? NR_Nothrow : NR_Throw;
1716 }
1717 
1718 bool FunctionProtoType::isNothrow(const ASTContext &Ctx,
1719                                   bool ResultIfDependent) const {
1720   ExceptionSpecificationType EST = getExceptionSpecType();
1721   assert(EST != EST_Unevaluated && EST != EST_Uninstantiated);
1722   if (EST == EST_DynamicNone || EST == EST_BasicNoexcept)
1723     return true;
1724 
1725   if (EST == EST_Dynamic && ResultIfDependent == true) {
1726     // A dynamic exception specification is throwing unless every exception
1727     // type is an (unexpanded) pack expansion type.
1728     for (unsigned I = 0, N = NumExceptions; I != N; ++I)
1729       if (!getExceptionType(I)->getAs<PackExpansionType>())
1730         return false;
1731     return ResultIfDependent;
1732   }
1733 
1734   if (EST != EST_ComputedNoexcept)
1735     return false;
1736 
1737   NoexceptResult NR = getNoexceptSpec(Ctx);
1738   if (NR == NR_Dependent)
1739     return ResultIfDependent;
1740   return NR == NR_Nothrow;
1741 }
1742 
1743 bool FunctionProtoType::isTemplateVariadic() const {
1744   for (unsigned ArgIdx = getNumParams(); ArgIdx; --ArgIdx)
1745     if (isa<PackExpansionType>(getParamType(ArgIdx - 1)))
1746       return true;
1747 
1748   return false;
1749 }
1750 
1751 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
1752                                 const QualType *ArgTys, unsigned NumParams,
1753                                 const ExtProtoInfo &epi,
1754                                 const ASTContext &Context) {
1755 
1756   // We have to be careful not to get ambiguous profile encodings.
1757   // Note that valid type pointers are never ambiguous with anything else.
1758   //
1759   // The encoding grammar begins:
1760   //      type type* bool int bool
1761   // If that final bool is true, then there is a section for the EH spec:
1762   //      bool type*
1763   // This is followed by an optional "consumed argument" section of the
1764   // same length as the first type sequence:
1765   //      bool*
1766   // Finally, we have the ext info and trailing return type flag:
1767   //      int bool
1768   //
1769   // There is no ambiguity between the consumed arguments and an empty EH
1770   // spec because of the leading 'bool' which unambiguously indicates
1771   // whether the following bool is the EH spec or part of the arguments.
1772 
1773   ID.AddPointer(Result.getAsOpaquePtr());
1774   for (unsigned i = 0; i != NumParams; ++i)
1775     ID.AddPointer(ArgTys[i].getAsOpaquePtr());
1776   // This method is relatively performance sensitive, so as a performance
1777   // shortcut, use one AddInteger call instead of four for the next four
1778   // fields.
1779   assert(!(unsigned(epi.Variadic) & ~1) &&
1780          !(unsigned(epi.TypeQuals) & ~255) &&
1781          !(unsigned(epi.RefQualifier) & ~3) &&
1782          !(unsigned(epi.ExceptionSpec.Type) & ~15) &&
1783          "Values larger than expected.");
1784   ID.AddInteger(unsigned(epi.Variadic) +
1785                 (epi.TypeQuals << 1) +
1786                 (epi.RefQualifier << 9) +
1787                 (epi.ExceptionSpec.Type << 11));
1788   if (epi.ExceptionSpec.Type == EST_Dynamic) {
1789     for (QualType Ex : epi.ExceptionSpec.Exceptions)
1790       ID.AddPointer(Ex.getAsOpaquePtr());
1791   } else if (epi.ExceptionSpec.Type == EST_ComputedNoexcept &&
1792              epi.ExceptionSpec.NoexceptExpr) {
1793     epi.ExceptionSpec.NoexceptExpr->Profile(ID, Context, false);
1794   } else if (epi.ExceptionSpec.Type == EST_Uninstantiated ||
1795              epi.ExceptionSpec.Type == EST_Unevaluated) {
1796     ID.AddPointer(epi.ExceptionSpec.SourceDecl->getCanonicalDecl());
1797   }
1798   if (epi.ConsumedParameters) {
1799     for (unsigned i = 0; i != NumParams; ++i)
1800       ID.AddBoolean(epi.ConsumedParameters[i]);
1801   }
1802   epi.ExtInfo.Profile(ID);
1803   ID.AddBoolean(epi.HasTrailingReturn);
1804 }
1805 
1806 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
1807                                 const ASTContext &Ctx) {
1808   Profile(ID, getReturnType(), param_type_begin(), NumParams, getExtProtoInfo(),
1809           Ctx);
1810 }
1811 
1812 QualType TypedefType::desugar() const {
1813   return getDecl()->getUnderlyingType();
1814 }
1815 
1816 TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
1817   : Type(TypeOfExpr, can, E->isTypeDependent(),
1818          E->isInstantiationDependent(),
1819          E->getType()->isVariablyModifiedType(),
1820          E->containsUnexpandedParameterPack()),
1821     TOExpr(E) {
1822 }
1823 
1824 bool TypeOfExprType::isSugared() const {
1825   return !TOExpr->isTypeDependent();
1826 }
1827 
1828 QualType TypeOfExprType::desugar() const {
1829   if (isSugared())
1830     return getUnderlyingExpr()->getType();
1831 
1832   return QualType(this, 0);
1833 }
1834 
1835 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
1836                                       const ASTContext &Context, Expr *E) {
1837   E->Profile(ID, Context, true);
1838 }
1839 
1840 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
1841   // C++11 [temp.type]p2: "If an expression e involves a template parameter,
1842   // decltype(e) denotes a unique dependent type." Hence a decltype type is
1843   // type-dependent even if its expression is only instantiation-dependent.
1844   : Type(Decltype, can, E->isInstantiationDependent(),
1845          E->isInstantiationDependent(),
1846          E->getType()->isVariablyModifiedType(),
1847          E->containsUnexpandedParameterPack()),
1848     E(E),
1849   UnderlyingType(underlyingType) {
1850 }
1851 
1852 bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); }
1853 
1854 QualType DecltypeType::desugar() const {
1855   if (isSugared())
1856     return getUnderlyingType();
1857 
1858   return QualType(this, 0);
1859 }
1860 
1861 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E)
1862   : DecltypeType(E, Context.DependentTy), Context(Context) { }
1863 
1864 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
1865                                     const ASTContext &Context, Expr *E) {
1866   E->Profile(ID, Context, true);
1867 }
1868 
1869 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
1870   : Type(TC, can, D->isDependentType(),
1871          /*InstantiationDependent=*/D->isDependentType(),
1872          /*VariablyModified=*/false,
1873          /*ContainsUnexpandedParameterPack=*/false),
1874     decl(const_cast<TagDecl*>(D)) {}
1875 
1876 static TagDecl *getInterestingTagDecl(TagDecl *decl) {
1877   for (auto I : decl->redecls()) {
1878     if (I->isCompleteDefinition() || I->isBeingDefined())
1879       return I;
1880   }
1881   // If there's no definition (not even in progress), return what we have.
1882   return decl;
1883 }
1884 
1885 UnaryTransformType::UnaryTransformType(QualType BaseType,
1886                                        QualType UnderlyingType,
1887                                        UTTKind UKind,
1888                                        QualType CanonicalType)
1889   : Type(UnaryTransform, CanonicalType, UnderlyingType->isDependentType(),
1890          UnderlyingType->isInstantiationDependentType(),
1891          UnderlyingType->isVariablyModifiedType(),
1892          BaseType->containsUnexpandedParameterPack())
1893   , BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind)
1894 {}
1895 
1896 TagDecl *TagType::getDecl() const {
1897   return getInterestingTagDecl(decl);
1898 }
1899 
1900 bool TagType::isBeingDefined() const {
1901   return getDecl()->isBeingDefined();
1902 }
1903 
1904 bool AttributedType::isMSTypeSpec() const {
1905   switch (getAttrKind()) {
1906   default:  return false;
1907   case attr_ptr32:
1908   case attr_ptr64:
1909   case attr_sptr:
1910   case attr_uptr:
1911     return true;
1912   }
1913   llvm_unreachable("invalid attr kind");
1914 }
1915 
1916 bool AttributedType::isCallingConv() const {
1917   switch (getAttrKind()) {
1918   case attr_ptr32:
1919   case attr_ptr64:
1920   case attr_sptr:
1921   case attr_uptr:
1922   case attr_address_space:
1923   case attr_regparm:
1924   case attr_vector_size:
1925   case attr_neon_vector_type:
1926   case attr_neon_polyvector_type:
1927   case attr_objc_gc:
1928   case attr_objc_ownership:
1929   case attr_noreturn:
1930       return false;
1931   case attr_pcs:
1932   case attr_pcs_vfp:
1933   case attr_cdecl:
1934   case attr_fastcall:
1935   case attr_stdcall:
1936   case attr_thiscall:
1937   case attr_vectorcall:
1938   case attr_pascal:
1939   case attr_ms_abi:
1940   case attr_sysv_abi:
1941   case attr_pnaclcall:
1942   case attr_inteloclbicc:
1943     return true;
1944   }
1945   llvm_unreachable("invalid attr kind");
1946 }
1947 
1948 CXXRecordDecl *InjectedClassNameType::getDecl() const {
1949   return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
1950 }
1951 
1952 IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
1953   return isCanonicalUnqualified() ? nullptr : getDecl()->getIdentifier();
1954 }
1955 
1956 SubstTemplateTypeParmPackType::
1957 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
1958                               QualType Canon,
1959                               const TemplateArgument &ArgPack)
1960   : Type(SubstTemplateTypeParmPack, Canon, true, true, false, true),
1961     Replaced(Param),
1962     Arguments(ArgPack.pack_begin()), NumArguments(ArgPack.pack_size())
1963 {
1964 }
1965 
1966 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const {
1967   return TemplateArgument(Arguments, NumArguments);
1968 }
1969 
1970 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
1971   Profile(ID, getReplacedParameter(), getArgumentPack());
1972 }
1973 
1974 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
1975                                            const TemplateTypeParmType *Replaced,
1976                                             const TemplateArgument &ArgPack) {
1977   ID.AddPointer(Replaced);
1978   ID.AddInteger(ArgPack.pack_size());
1979   for (const auto &P : ArgPack.pack_elements())
1980     ID.AddPointer(P.getAsType().getAsOpaquePtr());
1981 }
1982 
1983 bool TemplateSpecializationType::
1984 anyDependentTemplateArguments(const TemplateArgumentListInfo &Args,
1985                               bool &InstantiationDependent) {
1986   return anyDependentTemplateArguments(Args.getArgumentArray(), Args.size(),
1987                                        InstantiationDependent);
1988 }
1989 
1990 bool TemplateSpecializationType::
1991 anyDependentTemplateArguments(const TemplateArgumentLoc *Args, unsigned N,
1992                               bool &InstantiationDependent) {
1993   for (unsigned i = 0; i != N; ++i) {
1994     if (Args[i].getArgument().isDependent()) {
1995       InstantiationDependent = true;
1996       return true;
1997     }
1998 
1999     if (Args[i].getArgument().isInstantiationDependent())
2000       InstantiationDependent = true;
2001   }
2002   return false;
2003 }
2004 
2005 TemplateSpecializationType::
2006 TemplateSpecializationType(TemplateName T,
2007                            const TemplateArgument *Args, unsigned NumArgs,
2008                            QualType Canon, QualType AliasedType)
2009   : Type(TemplateSpecialization,
2010          Canon.isNull()? QualType(this, 0) : Canon,
2011          Canon.isNull()? true : Canon->isDependentType(),
2012          Canon.isNull()? true : Canon->isInstantiationDependentType(),
2013          false,
2014          T.containsUnexpandedParameterPack()),
2015     Template(T), NumArgs(NumArgs), TypeAlias(!AliasedType.isNull()) {
2016   assert(!T.getAsDependentTemplateName() &&
2017          "Use DependentTemplateSpecializationType for dependent template-name");
2018   assert((T.getKind() == TemplateName::Template ||
2019           T.getKind() == TemplateName::SubstTemplateTemplateParm ||
2020           T.getKind() == TemplateName::SubstTemplateTemplateParmPack) &&
2021          "Unexpected template name for TemplateSpecializationType");
2022 
2023   TemplateArgument *TemplateArgs
2024     = reinterpret_cast<TemplateArgument *>(this + 1);
2025   for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
2026     // Update instantiation-dependent and variably-modified bits.
2027     // If the canonical type exists and is non-dependent, the template
2028     // specialization type can be non-dependent even if one of the type
2029     // arguments is. Given:
2030     //   template<typename T> using U = int;
2031     // U<T> is always non-dependent, irrespective of the type T.
2032     // However, U<Ts> contains an unexpanded parameter pack, even though
2033     // its expansion (and thus its desugared type) doesn't.
2034     if (Args[Arg].isInstantiationDependent())
2035       setInstantiationDependent();
2036     if (Args[Arg].getKind() == TemplateArgument::Type &&
2037         Args[Arg].getAsType()->isVariablyModifiedType())
2038       setVariablyModified();
2039     if (Args[Arg].containsUnexpandedParameterPack())
2040       setContainsUnexpandedParameterPack();
2041     new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]);
2042   }
2043 
2044   // Store the aliased type if this is a type alias template specialization.
2045   if (TypeAlias) {
2046     TemplateArgument *Begin = reinterpret_cast<TemplateArgument *>(this + 1);
2047     *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType;
2048   }
2049 }
2050 
2051 void
2052 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
2053                                     TemplateName T,
2054                                     const TemplateArgument *Args,
2055                                     unsigned NumArgs,
2056                                     const ASTContext &Context) {
2057   T.Profile(ID);
2058   for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
2059     Args[Idx].Profile(ID, Context);
2060 }
2061 
2062 QualType
2063 QualifierCollector::apply(const ASTContext &Context, QualType QT) const {
2064   if (!hasNonFastQualifiers())
2065     return QT.withFastQualifiers(getFastQualifiers());
2066 
2067   return Context.getQualifiedType(QT, *this);
2068 }
2069 
2070 QualType
2071 QualifierCollector::apply(const ASTContext &Context, const Type *T) const {
2072   if (!hasNonFastQualifiers())
2073     return QualType(T, getFastQualifiers());
2074 
2075   return Context.getQualifiedType(T, *this);
2076 }
2077 
2078 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
2079                                  QualType BaseType,
2080                                  ObjCProtocolDecl * const *Protocols,
2081                                  unsigned NumProtocols) {
2082   ID.AddPointer(BaseType.getAsOpaquePtr());
2083   for (unsigned i = 0; i != NumProtocols; i++)
2084     ID.AddPointer(Protocols[i]);
2085 }
2086 
2087 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
2088   Profile(ID, getBaseType(), qual_begin(), getNumProtocols());
2089 }
2090 
2091 namespace {
2092 
2093 /// \brief The cached properties of a type.
2094 class CachedProperties {
2095   Linkage L;
2096   bool local;
2097 
2098 public:
2099   CachedProperties(Linkage L, bool local) : L(L), local(local) {}
2100 
2101   Linkage getLinkage() const { return L; }
2102   bool hasLocalOrUnnamedType() const { return local; }
2103 
2104   friend CachedProperties merge(CachedProperties L, CachedProperties R) {
2105     Linkage MergedLinkage = minLinkage(L.L, R.L);
2106     return CachedProperties(MergedLinkage,
2107                          L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType());
2108   }
2109 };
2110 }
2111 
2112 static CachedProperties computeCachedProperties(const Type *T);
2113 
2114 namespace clang {
2115 /// The type-property cache.  This is templated so as to be
2116 /// instantiated at an internal type to prevent unnecessary symbol
2117 /// leakage.
2118 template <class Private> class TypePropertyCache {
2119 public:
2120   static CachedProperties get(QualType T) {
2121     return get(T.getTypePtr());
2122   }
2123 
2124   static CachedProperties get(const Type *T) {
2125     ensure(T);
2126     return CachedProperties(T->TypeBits.getLinkage(),
2127                             T->TypeBits.hasLocalOrUnnamedType());
2128   }
2129 
2130   static void ensure(const Type *T) {
2131     // If the cache is valid, we're okay.
2132     if (T->TypeBits.isCacheValid()) return;
2133 
2134     // If this type is non-canonical, ask its canonical type for the
2135     // relevant information.
2136     if (!T->isCanonicalUnqualified()) {
2137       const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
2138       ensure(CT);
2139       T->TypeBits.CacheValid = true;
2140       T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
2141       T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
2142       return;
2143     }
2144 
2145     // Compute the cached properties and then set the cache.
2146     CachedProperties Result = computeCachedProperties(T);
2147     T->TypeBits.CacheValid = true;
2148     T->TypeBits.CachedLinkage = Result.getLinkage();
2149     T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
2150   }
2151 };
2152 }
2153 
2154 // Instantiate the friend template at a private class.  In a
2155 // reasonable implementation, these symbols will be internal.
2156 // It is terrible that this is the best way to accomplish this.
2157 namespace { class Private {}; }
2158 typedef TypePropertyCache<Private> Cache;
2159 
2160 static CachedProperties computeCachedProperties(const Type *T) {
2161   switch (T->getTypeClass()) {
2162 #define TYPE(Class,Base)
2163 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
2164 #include "clang/AST/TypeNodes.def"
2165     llvm_unreachable("didn't expect a non-canonical type here");
2166 
2167 #define TYPE(Class,Base)
2168 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
2169 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
2170 #include "clang/AST/TypeNodes.def"
2171     // Treat instantiation-dependent types as external.
2172     assert(T->isInstantiationDependentType());
2173     return CachedProperties(ExternalLinkage, false);
2174 
2175   case Type::Auto:
2176     // Give non-deduced 'auto' types external linkage. We should only see them
2177     // here in error recovery.
2178     return CachedProperties(ExternalLinkage, false);
2179 
2180   case Type::Builtin:
2181     // C++ [basic.link]p8:
2182     //   A type is said to have linkage if and only if:
2183     //     - it is a fundamental type (3.9.1); or
2184     return CachedProperties(ExternalLinkage, false);
2185 
2186   case Type::Record:
2187   case Type::Enum: {
2188     const TagDecl *Tag = cast<TagType>(T)->getDecl();
2189 
2190     // C++ [basic.link]p8:
2191     //     - it is a class or enumeration type that is named (or has a name
2192     //       for linkage purposes (7.1.3)) and the name has linkage; or
2193     //     -  it is a specialization of a class template (14); or
2194     Linkage L = Tag->getLinkageInternal();
2195     bool IsLocalOrUnnamed =
2196       Tag->getDeclContext()->isFunctionOrMethod() ||
2197       !Tag->hasNameForLinkage();
2198     return CachedProperties(L, IsLocalOrUnnamed);
2199   }
2200 
2201     // C++ [basic.link]p8:
2202     //   - it is a compound type (3.9.2) other than a class or enumeration,
2203     //     compounded exclusively from types that have linkage; or
2204   case Type::Complex:
2205     return Cache::get(cast<ComplexType>(T)->getElementType());
2206   case Type::Pointer:
2207     return Cache::get(cast<PointerType>(T)->getPointeeType());
2208   case Type::BlockPointer:
2209     return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
2210   case Type::LValueReference:
2211   case Type::RValueReference:
2212     return Cache::get(cast<ReferenceType>(T)->getPointeeType());
2213   case Type::MemberPointer: {
2214     const MemberPointerType *MPT = cast<MemberPointerType>(T);
2215     return merge(Cache::get(MPT->getClass()),
2216                  Cache::get(MPT->getPointeeType()));
2217   }
2218   case Type::ConstantArray:
2219   case Type::IncompleteArray:
2220   case Type::VariableArray:
2221     return Cache::get(cast<ArrayType>(T)->getElementType());
2222   case Type::Vector:
2223   case Type::ExtVector:
2224     return Cache::get(cast<VectorType>(T)->getElementType());
2225   case Type::FunctionNoProto:
2226     return Cache::get(cast<FunctionType>(T)->getReturnType());
2227   case Type::FunctionProto: {
2228     const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2229     CachedProperties result = Cache::get(FPT->getReturnType());
2230     for (const auto &ai : FPT->param_types())
2231       result = merge(result, Cache::get(ai));
2232     return result;
2233   }
2234   case Type::ObjCInterface: {
2235     Linkage L = cast<ObjCInterfaceType>(T)->getDecl()->getLinkageInternal();
2236     return CachedProperties(L, false);
2237   }
2238   case Type::ObjCObject:
2239     return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
2240   case Type::ObjCObjectPointer:
2241     return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
2242   case Type::Atomic:
2243     return Cache::get(cast<AtomicType>(T)->getValueType());
2244   }
2245 
2246   llvm_unreachable("unhandled type class");
2247 }
2248 
2249 /// \brief Determine the linkage of this type.
2250 Linkage Type::getLinkage() const {
2251   Cache::ensure(this);
2252   return TypeBits.getLinkage();
2253 }
2254 
2255 bool Type::hasUnnamedOrLocalType() const {
2256   Cache::ensure(this);
2257   return TypeBits.hasLocalOrUnnamedType();
2258 }
2259 
2260 static LinkageInfo computeLinkageInfo(QualType T);
2261 
2262 static LinkageInfo computeLinkageInfo(const Type *T) {
2263   switch (T->getTypeClass()) {
2264 #define TYPE(Class,Base)
2265 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
2266 #include "clang/AST/TypeNodes.def"
2267     llvm_unreachable("didn't expect a non-canonical type here");
2268 
2269 #define TYPE(Class,Base)
2270 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
2271 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
2272 #include "clang/AST/TypeNodes.def"
2273     // Treat instantiation-dependent types as external.
2274     assert(T->isInstantiationDependentType());
2275     return LinkageInfo::external();
2276 
2277   case Type::Builtin:
2278     return LinkageInfo::external();
2279 
2280   case Type::Auto:
2281     return LinkageInfo::external();
2282 
2283   case Type::Record:
2284   case Type::Enum:
2285     return cast<TagType>(T)->getDecl()->getLinkageAndVisibility();
2286 
2287   case Type::Complex:
2288     return computeLinkageInfo(cast<ComplexType>(T)->getElementType());
2289   case Type::Pointer:
2290     return computeLinkageInfo(cast<PointerType>(T)->getPointeeType());
2291   case Type::BlockPointer:
2292     return computeLinkageInfo(cast<BlockPointerType>(T)->getPointeeType());
2293   case Type::LValueReference:
2294   case Type::RValueReference:
2295     return computeLinkageInfo(cast<ReferenceType>(T)->getPointeeType());
2296   case Type::MemberPointer: {
2297     const MemberPointerType *MPT = cast<MemberPointerType>(T);
2298     LinkageInfo LV = computeLinkageInfo(MPT->getClass());
2299     LV.merge(computeLinkageInfo(MPT->getPointeeType()));
2300     return LV;
2301   }
2302   case Type::ConstantArray:
2303   case Type::IncompleteArray:
2304   case Type::VariableArray:
2305     return computeLinkageInfo(cast<ArrayType>(T)->getElementType());
2306   case Type::Vector:
2307   case Type::ExtVector:
2308     return computeLinkageInfo(cast<VectorType>(T)->getElementType());
2309   case Type::FunctionNoProto:
2310     return computeLinkageInfo(cast<FunctionType>(T)->getReturnType());
2311   case Type::FunctionProto: {
2312     const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2313     LinkageInfo LV = computeLinkageInfo(FPT->getReturnType());
2314     for (const auto &ai : FPT->param_types())
2315       LV.merge(computeLinkageInfo(ai));
2316     return LV;
2317   }
2318   case Type::ObjCInterface:
2319     return cast<ObjCInterfaceType>(T)->getDecl()->getLinkageAndVisibility();
2320   case Type::ObjCObject:
2321     return computeLinkageInfo(cast<ObjCObjectType>(T)->getBaseType());
2322   case Type::ObjCObjectPointer:
2323     return computeLinkageInfo(cast<ObjCObjectPointerType>(T)->getPointeeType());
2324   case Type::Atomic:
2325     return computeLinkageInfo(cast<AtomicType>(T)->getValueType());
2326   }
2327 
2328   llvm_unreachable("unhandled type class");
2329 }
2330 
2331 static LinkageInfo computeLinkageInfo(QualType T) {
2332   return computeLinkageInfo(T.getTypePtr());
2333 }
2334 
2335 bool Type::isLinkageValid() const {
2336   if (!TypeBits.isCacheValid())
2337     return true;
2338 
2339   return computeLinkageInfo(getCanonicalTypeInternal()).getLinkage() ==
2340     TypeBits.getLinkage();
2341 }
2342 
2343 LinkageInfo Type::getLinkageAndVisibility() const {
2344   if (!isCanonicalUnqualified())
2345     return computeLinkageInfo(getCanonicalTypeInternal());
2346 
2347   LinkageInfo LV = computeLinkageInfo(this);
2348   assert(LV.getLinkage() == getLinkage());
2349   return LV;
2350 }
2351 
2352 Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const {
2353   if (isObjCARCImplicitlyUnretainedType())
2354     return Qualifiers::OCL_ExplicitNone;
2355   return Qualifiers::OCL_Strong;
2356 }
2357 
2358 bool Type::isObjCARCImplicitlyUnretainedType() const {
2359   assert(isObjCLifetimeType() &&
2360          "cannot query implicit lifetime for non-inferrable type");
2361 
2362   const Type *canon = getCanonicalTypeInternal().getTypePtr();
2363 
2364   // Walk down to the base type.  We don't care about qualifiers for this.
2365   while (const ArrayType *array = dyn_cast<ArrayType>(canon))
2366     canon = array->getElementType().getTypePtr();
2367 
2368   if (const ObjCObjectPointerType *opt
2369         = dyn_cast<ObjCObjectPointerType>(canon)) {
2370     // Class and Class<Protocol> don't require retension.
2371     if (opt->getObjectType()->isObjCClass())
2372       return true;
2373   }
2374 
2375   return false;
2376 }
2377 
2378 bool Type::isObjCNSObjectType() const {
2379   if (const TypedefType *typedefType = dyn_cast<TypedefType>(this))
2380     return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>();
2381   return false;
2382 }
2383 bool Type::isObjCRetainableType() const {
2384   return isObjCObjectPointerType() ||
2385          isBlockPointerType() ||
2386          isObjCNSObjectType();
2387 }
2388 bool Type::isObjCIndirectLifetimeType() const {
2389   if (isObjCLifetimeType())
2390     return true;
2391   if (const PointerType *OPT = getAs<PointerType>())
2392     return OPT->getPointeeType()->isObjCIndirectLifetimeType();
2393   if (const ReferenceType *Ref = getAs<ReferenceType>())
2394     return Ref->getPointeeType()->isObjCIndirectLifetimeType();
2395   if (const MemberPointerType *MemPtr = getAs<MemberPointerType>())
2396     return MemPtr->getPointeeType()->isObjCIndirectLifetimeType();
2397   return false;
2398 }
2399 
2400 /// Returns true if objects of this type have lifetime semantics under
2401 /// ARC.
2402 bool Type::isObjCLifetimeType() const {
2403   const Type *type = this;
2404   while (const ArrayType *array = type->getAsArrayTypeUnsafe())
2405     type = array->getElementType().getTypePtr();
2406   return type->isObjCRetainableType();
2407 }
2408 
2409 /// \brief Determine whether the given type T is a "bridgable" Objective-C type,
2410 /// which is either an Objective-C object pointer type or an
2411 bool Type::isObjCARCBridgableType() const {
2412   return isObjCObjectPointerType() || isBlockPointerType();
2413 }
2414 
2415 /// \brief Determine whether the given type T is a "bridgeable" C type.
2416 bool Type::isCARCBridgableType() const {
2417   const PointerType *Pointer = getAs<PointerType>();
2418   if (!Pointer)
2419     return false;
2420 
2421   QualType Pointee = Pointer->getPointeeType();
2422   return Pointee->isVoidType() || Pointee->isRecordType();
2423 }
2424 
2425 bool Type::hasSizedVLAType() const {
2426   if (!isVariablyModifiedType()) return false;
2427 
2428   if (const PointerType *ptr = getAs<PointerType>())
2429     return ptr->getPointeeType()->hasSizedVLAType();
2430   if (const ReferenceType *ref = getAs<ReferenceType>())
2431     return ref->getPointeeType()->hasSizedVLAType();
2432   if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
2433     if (isa<VariableArrayType>(arr) &&
2434         cast<VariableArrayType>(arr)->getSizeExpr())
2435       return true;
2436 
2437     return arr->getElementType()->hasSizedVLAType();
2438   }
2439 
2440   return false;
2441 }
2442 
2443 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
2444   switch (type.getObjCLifetime()) {
2445   case Qualifiers::OCL_None:
2446   case Qualifiers::OCL_ExplicitNone:
2447   case Qualifiers::OCL_Autoreleasing:
2448     break;
2449 
2450   case Qualifiers::OCL_Strong:
2451     return DK_objc_strong_lifetime;
2452   case Qualifiers::OCL_Weak:
2453     return DK_objc_weak_lifetime;
2454   }
2455 
2456   /// Currently, the only destruction kind we recognize is C++ objects
2457   /// with non-trivial destructors.
2458   const CXXRecordDecl *record =
2459     type->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2460   if (record && record->hasDefinition() && !record->hasTrivialDestructor())
2461     return DK_cxx_destructor;
2462 
2463   return DK_none;
2464 }
2465 
2466 CXXRecordDecl *MemberPointerType::getMostRecentCXXRecordDecl() const {
2467   return getClass()->getAsCXXRecordDecl()->getMostRecentDecl();
2468 }
2469