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