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