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