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