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