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