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