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