]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/AST/Type.cpp
Merge bmake-20130123
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / AST / Type.cpp
1 //===--- Type.cpp - Type representation and manipulation ------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements type-related functionality.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/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   case CC_PnaclCall: return "pnaclcall";
1546   }
1547
1548   llvm_unreachable("Invalid calling convention.");
1549 }
1550
1551 FunctionProtoType::FunctionProtoType(QualType result, const QualType *args,
1552                                      unsigned numArgs, QualType canonical,
1553                                      const ExtProtoInfo &epi)
1554   : FunctionType(FunctionProto, result, epi.TypeQuals, epi.RefQualifier,
1555                  canonical,
1556                  result->isDependentType(),
1557                  result->isInstantiationDependentType(),
1558                  result->isVariablyModifiedType(),
1559                  result->containsUnexpandedParameterPack(),
1560                  epi.ExtInfo),
1561     NumArgs(numArgs), NumExceptions(epi.NumExceptions),
1562     ExceptionSpecType(epi.ExceptionSpecType),
1563     HasAnyConsumedArgs(epi.ConsumedArguments != 0),
1564     Variadic(epi.Variadic), HasTrailingReturn(epi.HasTrailingReturn)
1565 {
1566   // Fill in the trailing argument array.
1567   QualType *argSlot = reinterpret_cast<QualType*>(this+1);
1568   for (unsigned i = 0; i != numArgs; ++i) {
1569     if (args[i]->isDependentType())
1570       setDependent();
1571     else if (args[i]->isInstantiationDependentType())
1572       setInstantiationDependent();
1573     
1574     if (args[i]->containsUnexpandedParameterPack())
1575       setContainsUnexpandedParameterPack();
1576
1577     argSlot[i] = args[i];
1578   }
1579
1580   if (getExceptionSpecType() == EST_Dynamic) {
1581     // Fill in the exception array.
1582     QualType *exnSlot = argSlot + numArgs;
1583     for (unsigned i = 0, e = epi.NumExceptions; i != e; ++i) {
1584       if (epi.Exceptions[i]->isDependentType())
1585         setDependent();
1586       else if (epi.Exceptions[i]->isInstantiationDependentType())
1587         setInstantiationDependent();
1588       
1589       if (epi.Exceptions[i]->containsUnexpandedParameterPack())
1590         setContainsUnexpandedParameterPack();
1591
1592       exnSlot[i] = epi.Exceptions[i];
1593     }
1594   } else if (getExceptionSpecType() == EST_ComputedNoexcept) {
1595     // Store the noexcept expression and context.
1596     Expr **noexSlot = reinterpret_cast<Expr**>(argSlot + numArgs);
1597     *noexSlot = epi.NoexceptExpr;
1598     
1599     if (epi.NoexceptExpr) {
1600       if (epi.NoexceptExpr->isValueDependent() 
1601           || epi.NoexceptExpr->isTypeDependent())
1602         setDependent();
1603       else if (epi.NoexceptExpr->isInstantiationDependent())
1604         setInstantiationDependent();
1605     }
1606   } else if (getExceptionSpecType() == EST_Uninstantiated) {
1607     // Store the function decl from which we will resolve our
1608     // exception specification.
1609     FunctionDecl **slot = reinterpret_cast<FunctionDecl**>(argSlot + numArgs);
1610     slot[0] = epi.ExceptionSpecDecl;
1611     slot[1] = epi.ExceptionSpecTemplate;
1612     // This exception specification doesn't make the type dependent, because
1613     // it's not instantiated as part of instantiating the type.
1614   } else if (getExceptionSpecType() == EST_Unevaluated) {
1615     // Store the function decl from which we will resolve our
1616     // exception specification.
1617     FunctionDecl **slot = reinterpret_cast<FunctionDecl**>(argSlot + numArgs);
1618     slot[0] = epi.ExceptionSpecDecl;
1619   }
1620
1621   if (epi.ConsumedArguments) {
1622     bool *consumedArgs = const_cast<bool*>(getConsumedArgsBuffer());
1623     for (unsigned i = 0; i != numArgs; ++i)
1624       consumedArgs[i] = epi.ConsumedArguments[i];
1625   }
1626 }
1627
1628 FunctionProtoType::NoexceptResult
1629 FunctionProtoType::getNoexceptSpec(ASTContext &ctx) const {
1630   ExceptionSpecificationType est = getExceptionSpecType();
1631   if (est == EST_BasicNoexcept)
1632     return NR_Nothrow;
1633
1634   if (est != EST_ComputedNoexcept)
1635     return NR_NoNoexcept;
1636
1637   Expr *noexceptExpr = getNoexceptExpr();
1638   if (!noexceptExpr)
1639     return NR_BadNoexcept;
1640   if (noexceptExpr->isValueDependent())
1641     return NR_Dependent;
1642
1643   llvm::APSInt value;
1644   bool isICE = noexceptExpr->isIntegerConstantExpr(value, ctx, 0,
1645                                                    /*evaluated*/false);
1646   (void)isICE;
1647   assert(isICE && "AST should not contain bad noexcept expressions.");
1648
1649   return value.getBoolValue() ? NR_Nothrow : NR_Throw;
1650 }
1651
1652 bool FunctionProtoType::isTemplateVariadic() const {
1653   for (unsigned ArgIdx = getNumArgs(); ArgIdx; --ArgIdx)
1654     if (isa<PackExpansionType>(getArgType(ArgIdx - 1)))
1655       return true;
1656   
1657   return false;
1658 }
1659
1660 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
1661                                 const QualType *ArgTys, unsigned NumArgs,
1662                                 const ExtProtoInfo &epi,
1663                                 const ASTContext &Context) {
1664
1665   // We have to be careful not to get ambiguous profile encodings.
1666   // Note that valid type pointers are never ambiguous with anything else.
1667   //
1668   // The encoding grammar begins:
1669   //      type type* bool int bool 
1670   // If that final bool is true, then there is a section for the EH spec:
1671   //      bool type*
1672   // This is followed by an optional "consumed argument" section of the
1673   // same length as the first type sequence:
1674   //      bool*
1675   // Finally, we have the ext info and trailing return type flag:
1676   //      int bool
1677   // 
1678   // There is no ambiguity between the consumed arguments and an empty EH
1679   // spec because of the leading 'bool' which unambiguously indicates
1680   // whether the following bool is the EH spec or part of the arguments.
1681
1682   ID.AddPointer(Result.getAsOpaquePtr());
1683   for (unsigned i = 0; i != NumArgs; ++i)
1684     ID.AddPointer(ArgTys[i].getAsOpaquePtr());
1685   // This method is relatively performance sensitive, so as a performance
1686   // shortcut, use one AddInteger call instead of four for the next four
1687   // fields.
1688   assert(!(unsigned(epi.Variadic) & ~1) &&
1689          !(unsigned(epi.TypeQuals) & ~255) &&
1690          !(unsigned(epi.RefQualifier) & ~3) &&
1691          !(unsigned(epi.ExceptionSpecType) & ~7) &&
1692          "Values larger than expected.");
1693   ID.AddInteger(unsigned(epi.Variadic) +
1694                 (epi.TypeQuals << 1) +
1695                 (epi.RefQualifier << 9) +
1696                 (epi.ExceptionSpecType << 11));
1697   if (epi.ExceptionSpecType == EST_Dynamic) {
1698     for (unsigned i = 0; i != epi.NumExceptions; ++i)
1699       ID.AddPointer(epi.Exceptions[i].getAsOpaquePtr());
1700   } else if (epi.ExceptionSpecType == EST_ComputedNoexcept && epi.NoexceptExpr){
1701     epi.NoexceptExpr->Profile(ID, Context, false);
1702   } else if (epi.ExceptionSpecType == EST_Uninstantiated ||
1703              epi.ExceptionSpecType == EST_Unevaluated) {
1704     ID.AddPointer(epi.ExceptionSpecDecl->getCanonicalDecl());
1705   }
1706   if (epi.ConsumedArguments) {
1707     for (unsigned i = 0; i != NumArgs; ++i)
1708       ID.AddBoolean(epi.ConsumedArguments[i]);
1709   }
1710   epi.ExtInfo.Profile(ID);
1711   ID.AddBoolean(epi.HasTrailingReturn);
1712 }
1713
1714 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
1715                                 const ASTContext &Ctx) {
1716   Profile(ID, getResultType(), arg_type_begin(), NumArgs, getExtProtoInfo(),
1717           Ctx);
1718 }
1719
1720 QualType TypedefType::desugar() const {
1721   return getDecl()->getUnderlyingType();
1722 }
1723
1724 TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
1725   : Type(TypeOfExpr, can, E->isTypeDependent(), 
1726          E->isInstantiationDependent(),
1727          E->getType()->isVariablyModifiedType(),
1728          E->containsUnexpandedParameterPack()), 
1729     TOExpr(E) {
1730 }
1731
1732 bool TypeOfExprType::isSugared() const {
1733   return !TOExpr->isTypeDependent();
1734 }
1735
1736 QualType TypeOfExprType::desugar() const {
1737   if (isSugared())
1738     return getUnderlyingExpr()->getType();
1739   
1740   return QualType(this, 0);
1741 }
1742
1743 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
1744                                       const ASTContext &Context, Expr *E) {
1745   E->Profile(ID, Context, true);
1746 }
1747
1748 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
1749   // C++11 [temp.type]p2: "If an expression e involves a template parameter,
1750   // decltype(e) denotes a unique dependent type." Hence a decltype type is
1751   // type-dependent even if its expression is only instantiation-dependent.
1752   : Type(Decltype, can, E->isInstantiationDependent(),
1753          E->isInstantiationDependent(),
1754          E->getType()->isVariablyModifiedType(), 
1755          E->containsUnexpandedParameterPack()), 
1756     E(E),
1757   UnderlyingType(underlyingType) {
1758 }
1759
1760 bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); }
1761
1762 QualType DecltypeType::desugar() const {
1763   if (isSugared())
1764     return getUnderlyingType();
1765   
1766   return QualType(this, 0);
1767 }
1768
1769 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E)
1770   : DecltypeType(E, Context.DependentTy), Context(Context) { }
1771
1772 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
1773                                     const ASTContext &Context, Expr *E) {
1774   E->Profile(ID, Context, true);
1775 }
1776
1777 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
1778   : Type(TC, can, D->isDependentType(), 
1779          /*InstantiationDependent=*/D->isDependentType(),
1780          /*VariablyModified=*/false, 
1781          /*ContainsUnexpandedParameterPack=*/false),
1782     decl(const_cast<TagDecl*>(D)) {}
1783
1784 static TagDecl *getInterestingTagDecl(TagDecl *decl) {
1785   for (TagDecl::redecl_iterator I = decl->redecls_begin(),
1786                                 E = decl->redecls_end();
1787        I != E; ++I) {
1788     if (I->isCompleteDefinition() || I->isBeingDefined())
1789       return *I;
1790   }
1791   // If there's no definition (not even in progress), return what we have.
1792   return decl;
1793 }
1794
1795 UnaryTransformType::UnaryTransformType(QualType BaseType,
1796                                        QualType UnderlyingType,
1797                                        UTTKind UKind,
1798                                        QualType CanonicalType)
1799   : Type(UnaryTransform, CanonicalType, UnderlyingType->isDependentType(),
1800          UnderlyingType->isInstantiationDependentType(),
1801          UnderlyingType->isVariablyModifiedType(),
1802          BaseType->containsUnexpandedParameterPack())
1803   , BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind)
1804 {}
1805
1806 TagDecl *TagType::getDecl() const {
1807   return getInterestingTagDecl(decl);
1808 }
1809
1810 bool TagType::isBeingDefined() const {
1811   return getDecl()->isBeingDefined();
1812 }
1813
1814 CXXRecordDecl *InjectedClassNameType::getDecl() const {
1815   return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
1816 }
1817
1818 IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
1819   return isCanonicalUnqualified() ? 0 : getDecl()->getIdentifier();
1820 }
1821
1822 SubstTemplateTypeParmPackType::
1823 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param, 
1824                               QualType Canon,
1825                               const TemplateArgument &ArgPack)
1826   : Type(SubstTemplateTypeParmPack, Canon, true, true, false, true), 
1827     Replaced(Param), 
1828     Arguments(ArgPack.pack_begin()), NumArguments(ArgPack.pack_size()) 
1829
1830 }
1831
1832 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const {
1833   return TemplateArgument(Arguments, NumArguments);
1834 }
1835
1836 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
1837   Profile(ID, getReplacedParameter(), getArgumentPack());
1838 }
1839
1840 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
1841                                            const TemplateTypeParmType *Replaced,
1842                                             const TemplateArgument &ArgPack) {
1843   ID.AddPointer(Replaced);
1844   ID.AddInteger(ArgPack.pack_size());
1845   for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(), 
1846                                     PEnd = ArgPack.pack_end();
1847        P != PEnd; ++P)
1848     ID.AddPointer(P->getAsType().getAsOpaquePtr());
1849 }
1850
1851 bool TemplateSpecializationType::
1852 anyDependentTemplateArguments(const TemplateArgumentListInfo &Args,
1853                               bool &InstantiationDependent) {
1854   return anyDependentTemplateArguments(Args.getArgumentArray(), Args.size(),
1855                                        InstantiationDependent);
1856 }
1857
1858 bool TemplateSpecializationType::
1859 anyDependentTemplateArguments(const TemplateArgumentLoc *Args, unsigned N,
1860                               bool &InstantiationDependent) {
1861   for (unsigned i = 0; i != N; ++i) {
1862     if (Args[i].getArgument().isDependent()) {
1863       InstantiationDependent = true;
1864       return true;
1865     }
1866     
1867     if (Args[i].getArgument().isInstantiationDependent())
1868       InstantiationDependent = true;
1869   }
1870   return false;
1871 }
1872
1873 bool TemplateSpecializationType::
1874 anyDependentTemplateArguments(const TemplateArgument *Args, unsigned N,
1875                               bool &InstantiationDependent) {
1876   for (unsigned i = 0; i != N; ++i) {
1877     if (Args[i].isDependent()) {
1878       InstantiationDependent = true;
1879       return true;
1880     }
1881     
1882     if (Args[i].isInstantiationDependent())
1883       InstantiationDependent = true;
1884   }
1885   return false;
1886 }
1887
1888 TemplateSpecializationType::
1889 TemplateSpecializationType(TemplateName T,
1890                            const TemplateArgument *Args, unsigned NumArgs,
1891                            QualType Canon, QualType AliasedType)
1892   : Type(TemplateSpecialization,
1893          Canon.isNull()? QualType(this, 0) : Canon,
1894          Canon.isNull()? T.isDependent() : Canon->isDependentType(),
1895          Canon.isNull()? T.isDependent() 
1896                        : Canon->isInstantiationDependentType(),
1897          false,
1898          T.containsUnexpandedParameterPack()),
1899     Template(T), NumArgs(NumArgs), TypeAlias(!AliasedType.isNull()) {
1900   assert(!T.getAsDependentTemplateName() && 
1901          "Use DependentTemplateSpecializationType for dependent template-name");
1902   assert((T.getKind() == TemplateName::Template ||
1903           T.getKind() == TemplateName::SubstTemplateTemplateParm ||
1904           T.getKind() == TemplateName::SubstTemplateTemplateParmPack) &&
1905          "Unexpected template name for TemplateSpecializationType");
1906   bool InstantiationDependent;
1907   (void)InstantiationDependent;
1908   assert((!Canon.isNull() ||
1909           T.isDependent() || 
1910           anyDependentTemplateArguments(Args, NumArgs, 
1911                                         InstantiationDependent)) &&
1912          "No canonical type for non-dependent class template specialization");
1913
1914   TemplateArgument *TemplateArgs
1915     = reinterpret_cast<TemplateArgument *>(this + 1);
1916   for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1917     // Update dependent and variably-modified bits.
1918     // If the canonical type exists and is non-dependent, the template
1919     // specialization type can be non-dependent even if one of the type
1920     // arguments is. Given:
1921     //   template<typename T> using U = int;
1922     // U<T> is always non-dependent, irrespective of the type T.
1923     // However, U<Ts> contains an unexpanded parameter pack, even though
1924     // its expansion (and thus its desugared type) doesn't.
1925     if (Canon.isNull() && Args[Arg].isDependent())
1926       setDependent();
1927     else if (Args[Arg].isInstantiationDependent())
1928       setInstantiationDependent();
1929     
1930     if (Args[Arg].getKind() == TemplateArgument::Type &&
1931         Args[Arg].getAsType()->isVariablyModifiedType())
1932       setVariablyModified();
1933     if (Args[Arg].containsUnexpandedParameterPack())
1934       setContainsUnexpandedParameterPack();
1935
1936     new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]);
1937   }
1938
1939   // Store the aliased type if this is a type alias template specialization.
1940   if (TypeAlias) {
1941     TemplateArgument *Begin = reinterpret_cast<TemplateArgument *>(this + 1);
1942     *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType;
1943   }
1944 }
1945
1946 void
1947 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1948                                     TemplateName T,
1949                                     const TemplateArgument *Args,
1950                                     unsigned NumArgs,
1951                                     const ASTContext &Context) {
1952   T.Profile(ID);
1953   for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1954     Args[Idx].Profile(ID, Context);
1955 }
1956
1957 QualType
1958 QualifierCollector::apply(const ASTContext &Context, QualType QT) const {
1959   if (!hasNonFastQualifiers())
1960     return QT.withFastQualifiers(getFastQualifiers());
1961
1962   return Context.getQualifiedType(QT, *this);
1963 }
1964
1965 QualType
1966 QualifierCollector::apply(const ASTContext &Context, const Type *T) const {
1967   if (!hasNonFastQualifiers())
1968     return QualType(T, getFastQualifiers());
1969
1970   return Context.getQualifiedType(T, *this);
1971 }
1972
1973 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
1974                                  QualType BaseType,
1975                                  ObjCProtocolDecl * const *Protocols,
1976                                  unsigned NumProtocols) {
1977   ID.AddPointer(BaseType.getAsOpaquePtr());
1978   for (unsigned i = 0; i != NumProtocols; i++)
1979     ID.AddPointer(Protocols[i]);
1980 }
1981
1982 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
1983   Profile(ID, getBaseType(), qual_begin(), getNumProtocols());
1984 }
1985
1986 namespace {
1987
1988 /// \brief The cached properties of a type.
1989 class CachedProperties {
1990   NamedDecl::LinkageInfo LV;
1991   bool local;
1992   
1993 public:
1994   CachedProperties(NamedDecl::LinkageInfo LV, bool local)
1995     : LV(LV), local(local) {}
1996   
1997   Linkage getLinkage() const { return LV.linkage(); }
1998   Visibility getVisibility() const { return LV.visibility(); }
1999   bool isVisibilityExplicit() const { return LV.visibilityExplicit(); }
2000   bool hasLocalOrUnnamedType() const { return local; }
2001   
2002   friend CachedProperties merge(CachedProperties L, CachedProperties R) {
2003     NamedDecl::LinkageInfo MergedLV = L.LV;
2004     MergedLV.merge(R.LV);
2005     return CachedProperties(MergedLV,
2006                          L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType());
2007   }
2008 };
2009 }
2010
2011 static CachedProperties computeCachedProperties(const Type *T);
2012
2013 namespace clang {
2014 /// The type-property cache.  This is templated so as to be
2015 /// instantiated at an internal type to prevent unnecessary symbol
2016 /// leakage.
2017 template <class Private> class TypePropertyCache {
2018 public:
2019   static CachedProperties get(QualType T) {
2020     return get(T.getTypePtr());
2021   }
2022
2023   static CachedProperties get(const Type *T) {
2024     ensure(T);
2025     NamedDecl::LinkageInfo LV(T->TypeBits.getLinkage(),
2026                               T->TypeBits.getVisibility(),
2027                               T->TypeBits.isVisibilityExplicit());
2028     return CachedProperties(LV, T->TypeBits.hasLocalOrUnnamedType());
2029   }
2030
2031   static void ensure(const Type *T) {
2032     // If the cache is valid, we're okay.
2033     if (T->TypeBits.isCacheValid()) return;
2034
2035     // If this type is non-canonical, ask its canonical type for the
2036     // relevant information.
2037     if (!T->isCanonicalUnqualified()) {
2038       const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
2039       ensure(CT);
2040       T->TypeBits.CacheValidAndVisibility =
2041         CT->TypeBits.CacheValidAndVisibility;
2042       T->TypeBits.CachedExplicitVisibility =
2043         CT->TypeBits.CachedExplicitVisibility;
2044       T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
2045       T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
2046       return;
2047     }
2048
2049     // Compute the cached properties and then set the cache.
2050     CachedProperties Result = computeCachedProperties(T);
2051     T->TypeBits.CacheValidAndVisibility = Result.getVisibility() + 1U;
2052     T->TypeBits.CachedExplicitVisibility = Result.isVisibilityExplicit();
2053     assert(T->TypeBits.isCacheValid() &&
2054            T->TypeBits.getVisibility() == Result.getVisibility());
2055     T->TypeBits.CachedLinkage = Result.getLinkage();
2056     T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
2057   }
2058 };
2059 }
2060
2061 // Instantiate the friend template at a private class.  In a
2062 // reasonable implementation, these symbols will be internal.
2063 // It is terrible that this is the best way to accomplish this.
2064 namespace { class Private {}; }
2065 typedef TypePropertyCache<Private> Cache;
2066
2067 static CachedProperties computeCachedProperties(const Type *T) {
2068   switch (T->getTypeClass()) {
2069 #define TYPE(Class,Base)
2070 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
2071 #include "clang/AST/TypeNodes.def"
2072     llvm_unreachable("didn't expect a non-canonical type here");
2073
2074 #define TYPE(Class,Base)
2075 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
2076 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
2077 #include "clang/AST/TypeNodes.def"
2078     // Treat instantiation-dependent types as external.
2079     assert(T->isInstantiationDependentType());
2080     return CachedProperties(NamedDecl::LinkageInfo(), false);
2081
2082   case Type::Builtin:
2083     // C++ [basic.link]p8:
2084     //   A type is said to have linkage if and only if:
2085     //     - it is a fundamental type (3.9.1); or
2086     return CachedProperties(NamedDecl::LinkageInfo(), false);
2087
2088   case Type::Record:
2089   case Type::Enum: {
2090     const TagDecl *Tag = cast<TagType>(T)->getDecl();
2091
2092     // C++ [basic.link]p8:
2093     //     - it is a class or enumeration type that is named (or has a name
2094     //       for linkage purposes (7.1.3)) and the name has linkage; or
2095     //     -  it is a specialization of a class template (14); or
2096     NamedDecl::LinkageInfo LV = Tag->getLinkageAndVisibility();
2097     bool IsLocalOrUnnamed =
2098       Tag->getDeclContext()->isFunctionOrMethod() ||
2099       (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl());
2100     return CachedProperties(LV, IsLocalOrUnnamed);
2101   }
2102
2103     // C++ [basic.link]p8:
2104     //   - it is a compound type (3.9.2) other than a class or enumeration, 
2105     //     compounded exclusively from types that have linkage; or
2106   case Type::Complex:
2107     return Cache::get(cast<ComplexType>(T)->getElementType());
2108   case Type::Pointer:
2109     return Cache::get(cast<PointerType>(T)->getPointeeType());
2110   case Type::BlockPointer:
2111     return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
2112   case Type::LValueReference:
2113   case Type::RValueReference:
2114     return Cache::get(cast<ReferenceType>(T)->getPointeeType());
2115   case Type::MemberPointer: {
2116     const MemberPointerType *MPT = cast<MemberPointerType>(T);
2117     return merge(Cache::get(MPT->getClass()),
2118                  Cache::get(MPT->getPointeeType()));
2119   }
2120   case Type::ConstantArray:
2121   case Type::IncompleteArray:
2122   case Type::VariableArray:
2123     return Cache::get(cast<ArrayType>(T)->getElementType());
2124   case Type::Vector:
2125   case Type::ExtVector:
2126     return Cache::get(cast<VectorType>(T)->getElementType());
2127   case Type::FunctionNoProto:
2128     return Cache::get(cast<FunctionType>(T)->getResultType());
2129   case Type::FunctionProto: {
2130     const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2131     CachedProperties result = Cache::get(FPT->getResultType());
2132     for (FunctionProtoType::arg_type_iterator ai = FPT->arg_type_begin(),
2133            ae = FPT->arg_type_end(); ai != ae; ++ai)
2134       result = merge(result, Cache::get(*ai));
2135     return result;
2136   }
2137   case Type::ObjCInterface: {
2138     NamedDecl::LinkageInfo LV =
2139       cast<ObjCInterfaceType>(T)->getDecl()->getLinkageAndVisibility();
2140     return CachedProperties(LV, false);
2141   }
2142   case Type::ObjCObject:
2143     return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
2144   case Type::ObjCObjectPointer:
2145     return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
2146   case Type::Atomic:
2147     return Cache::get(cast<AtomicType>(T)->getValueType());
2148   }
2149
2150   llvm_unreachable("unhandled type class");
2151 }
2152
2153 /// \brief Determine the linkage of this type.
2154 Linkage Type::getLinkage() const {
2155   Cache::ensure(this);
2156   return TypeBits.getLinkage();
2157 }
2158
2159 /// \brief Determine the linkage of this type.
2160 Visibility Type::getVisibility() const {
2161   Cache::ensure(this);
2162   return TypeBits.getVisibility();
2163 }
2164
2165 bool Type::isVisibilityExplicit() const {
2166   Cache::ensure(this);
2167   return TypeBits.isVisibilityExplicit();
2168 }
2169
2170 bool Type::hasUnnamedOrLocalType() const {
2171   Cache::ensure(this);
2172   return TypeBits.hasLocalOrUnnamedType();
2173 }
2174
2175 std::pair<Linkage,Visibility> Type::getLinkageAndVisibility() const {
2176   Cache::ensure(this);
2177   return std::make_pair(TypeBits.getLinkage(), TypeBits.getVisibility());
2178 }
2179
2180 void Type::ClearLinkageCache() {
2181   TypeBits.CacheValidAndVisibility = 0;
2182   if (QualType(this, 0) != CanonicalType)
2183     CanonicalType->TypeBits.CacheValidAndVisibility = 0;
2184 }
2185
2186 Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const {
2187   if (isObjCARCImplicitlyUnretainedType())
2188     return Qualifiers::OCL_ExplicitNone;
2189   return Qualifiers::OCL_Strong;
2190 }
2191
2192 bool Type::isObjCARCImplicitlyUnretainedType() const {
2193   assert(isObjCLifetimeType() &&
2194          "cannot query implicit lifetime for non-inferrable type");
2195
2196   const Type *canon = getCanonicalTypeInternal().getTypePtr();
2197
2198   // Walk down to the base type.  We don't care about qualifiers for this.
2199   while (const ArrayType *array = dyn_cast<ArrayType>(canon))
2200     canon = array->getElementType().getTypePtr();
2201
2202   if (const ObjCObjectPointerType *opt
2203         = dyn_cast<ObjCObjectPointerType>(canon)) {
2204     // Class and Class<Protocol> don't require retension.
2205     if (opt->getObjectType()->isObjCClass())
2206       return true;
2207   }
2208
2209   return false;
2210 }
2211
2212 bool Type::isObjCNSObjectType() const {
2213   if (const TypedefType *typedefType = dyn_cast<TypedefType>(this))
2214     return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>();
2215   return false;
2216 }
2217 bool Type::isObjCRetainableType() const {
2218   return isObjCObjectPointerType() ||
2219          isBlockPointerType() ||
2220          isObjCNSObjectType();
2221 }
2222 bool Type::isObjCIndirectLifetimeType() const {
2223   if (isObjCLifetimeType())
2224     return true;
2225   if (const PointerType *OPT = getAs<PointerType>())
2226     return OPT->getPointeeType()->isObjCIndirectLifetimeType();
2227   if (const ReferenceType *Ref = getAs<ReferenceType>())
2228     return Ref->getPointeeType()->isObjCIndirectLifetimeType();
2229   if (const MemberPointerType *MemPtr = getAs<MemberPointerType>())
2230     return MemPtr->getPointeeType()->isObjCIndirectLifetimeType();
2231   return false;
2232 }
2233
2234 /// Returns true if objects of this type have lifetime semantics under
2235 /// ARC.
2236 bool Type::isObjCLifetimeType() const {
2237   const Type *type = this;
2238   while (const ArrayType *array = type->getAsArrayTypeUnsafe())
2239     type = array->getElementType().getTypePtr();
2240   return type->isObjCRetainableType();
2241 }
2242
2243 /// \brief Determine whether the given type T is a "bridgable" Objective-C type,
2244 /// which is either an Objective-C object pointer type or an 
2245 bool Type::isObjCARCBridgableType() const {
2246   return isObjCObjectPointerType() || isBlockPointerType();
2247 }
2248
2249 /// \brief Determine whether the given type T is a "bridgeable" C type.
2250 bool Type::isCARCBridgableType() const {
2251   const PointerType *Pointer = getAs<PointerType>();
2252   if (!Pointer)
2253     return false;
2254   
2255   QualType Pointee = Pointer->getPointeeType();
2256   return Pointee->isVoidType() || Pointee->isRecordType();
2257 }
2258
2259 bool Type::hasSizedVLAType() const {
2260   if (!isVariablyModifiedType()) return false;
2261
2262   if (const PointerType *ptr = getAs<PointerType>())
2263     return ptr->getPointeeType()->hasSizedVLAType();
2264   if (const ReferenceType *ref = getAs<ReferenceType>())
2265     return ref->getPointeeType()->hasSizedVLAType();
2266   if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
2267     if (isa<VariableArrayType>(arr) && 
2268         cast<VariableArrayType>(arr)->getSizeExpr())
2269       return true;
2270
2271     return arr->getElementType()->hasSizedVLAType();
2272   }
2273
2274   return false;
2275 }
2276
2277 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
2278   switch (type.getObjCLifetime()) {
2279   case Qualifiers::OCL_None:
2280   case Qualifiers::OCL_ExplicitNone:
2281   case Qualifiers::OCL_Autoreleasing:
2282     break;
2283
2284   case Qualifiers::OCL_Strong:
2285     return DK_objc_strong_lifetime;
2286   case Qualifiers::OCL_Weak:
2287     return DK_objc_weak_lifetime;
2288   }
2289
2290   /// Currently, the only destruction kind we recognize is C++ objects
2291   /// with non-trivial destructors.
2292   const CXXRecordDecl *record =
2293     type->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2294   if (record && record->hasDefinition() && !record->hasTrivialDestructor())
2295     return DK_cxx_destructor;
2296
2297   return DK_none;
2298 }
2299
2300 bool QualType::hasTrivialAssignment(ASTContext &Context, bool Copying) const {
2301   switch (getObjCLifetime()) {
2302   case Qualifiers::OCL_None:
2303     break;
2304       
2305   case Qualifiers::OCL_ExplicitNone:
2306     return true;
2307       
2308   case Qualifiers::OCL_Autoreleasing:
2309   case Qualifiers::OCL_Strong:
2310   case Qualifiers::OCL_Weak:
2311     return !Context.getLangOpts().ObjCAutoRefCount;
2312   }
2313   
2314   if (const CXXRecordDecl *Record 
2315             = getTypePtr()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl())
2316     return Copying ? Record->hasTrivialCopyAssignment() :
2317                      Record->hasTrivialMoveAssignment();
2318   
2319   return true;
2320 }