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