Type.cpp revision f5c65ffbd7374b6c8d9f1e361041578640cab320
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/StringExtras.h"
25#include "llvm/Support/raw_ostream.h"
26#include <algorithm>
27using namespace clang;
28
29bool QualType::isConstant(QualType T, ASTContext &Ctx) {
30  if (T.isConstQualified())
31    return true;
32
33  if (const ArrayType *AT = Ctx.getAsArrayType(T))
34    return AT->getElementType().isConstant(Ctx);
35
36  return false;
37}
38
39unsigned ConstantArrayType::getNumAddressingBits(ASTContext &Context,
40                                                 QualType ElementType,
41                                               const llvm::APInt &NumElements) {
42  llvm::APSInt SizeExtended(NumElements, true);
43  unsigned SizeTypeBits = Context.getTypeSize(Context.getSizeType());
44  SizeExtended = SizeExtended.extend(std::max(SizeTypeBits,
45                                              SizeExtended.getBitWidth()) * 2);
46
47  uint64_t ElementSize
48    = Context.getTypeSizeInChars(ElementType).getQuantity();
49  llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize));
50  TotalSize *= SizeExtended;
51
52  return TotalSize.getActiveBits();
53}
54
55unsigned ConstantArrayType::getMaxSizeBits(ASTContext &Context) {
56  unsigned Bits = Context.getTypeSize(Context.getSizeType());
57
58  // GCC appears to only allow 63 bits worth of address space when compiling
59  // for 64-bit, so we do the same.
60  if (Bits == 64)
61    --Bits;
62
63  return Bits;
64}
65
66DependentSizedArrayType::DependentSizedArrayType(ASTContext &Context,
67                                                 QualType et, QualType can,
68                                                 Expr *e, ArraySizeModifier sm,
69                                                 unsigned tq,
70                                                 SourceRange brackets)
71    : ArrayType(DependentSizedArray, et, can, sm, tq,
72                (et->containsUnexpandedParameterPack() ||
73                 (e && e->containsUnexpandedParameterPack()))),
74      Context(Context), SizeExpr((Stmt*) e), Brackets(brackets)
75{
76}
77
78void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID,
79                                      ASTContext &Context,
80                                      QualType ET,
81                                      ArraySizeModifier SizeMod,
82                                      unsigned TypeQuals,
83                                      Expr *E) {
84  ID.AddPointer(ET.getAsOpaquePtr());
85  ID.AddInteger(SizeMod);
86  ID.AddInteger(TypeQuals);
87  E->Profile(ID, Context, true);
88}
89
90DependentSizedExtVectorType::DependentSizedExtVectorType(ASTContext &Context,
91                                                         QualType ElementType,
92                                                         QualType can,
93                                                         Expr *SizeExpr,
94                                                         SourceLocation loc)
95    : Type(DependentSizedExtVector, can, /*Dependent=*/true,
96           ElementType->isVariablyModifiedType(),
97           (ElementType->containsUnexpandedParameterPack() ||
98            (SizeExpr && SizeExpr->containsUnexpandedParameterPack()))),
99      Context(Context), SizeExpr(SizeExpr), ElementType(ElementType),
100      loc(loc)
101{
102}
103
104void
105DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID,
106                                     ASTContext &Context,
107                                     QualType ElementType, Expr *SizeExpr) {
108  ID.AddPointer(ElementType.getAsOpaquePtr());
109  SizeExpr->Profile(ID, Context, true);
110}
111
112VectorType::VectorType(QualType vecType, unsigned nElements, QualType canonType,
113                       VectorKind vecKind)
114  : Type(Vector, canonType, vecType->isDependentType(),
115         vecType->isVariablyModifiedType(),
116         vecType->containsUnexpandedParameterPack()),
117    ElementType(vecType)
118{
119  VectorTypeBits.VecKind = vecKind;
120  VectorTypeBits.NumElements = nElements;
121}
122
123VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements,
124                       QualType canonType, VectorKind vecKind)
125  : Type(tc, canonType, vecType->isDependentType(),
126         vecType->isVariablyModifiedType(),
127         vecType->containsUnexpandedParameterPack()),
128    ElementType(vecType)
129{
130  VectorTypeBits.VecKind = vecKind;
131  VectorTypeBits.NumElements = nElements;
132}
133
134/// getArrayElementTypeNoTypeQual - If this is an array type, return the
135/// element type of the array, potentially with type qualifiers missing.
136/// This method should never be used when type qualifiers are meaningful.
137const Type *Type::getArrayElementTypeNoTypeQual() const {
138  // If this is directly an array type, return it.
139  if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
140    return ATy->getElementType().getTypePtr();
141
142  // If the canonical form of this type isn't the right kind, reject it.
143  if (!isa<ArrayType>(CanonicalType))
144    return 0;
145
146  // If this is a typedef for an array type, strip the typedef off without
147  // losing all typedef information.
148  return cast<ArrayType>(getUnqualifiedDesugaredType())
149    ->getElementType().getTypePtr();
150}
151
152/// \brief Retrieve the unqualified variant of the given type, removing as
153/// little sugar as possible.
154///
155/// This routine looks through various kinds of sugar to find the
156/// least-desuraged type that is unqualified. For example, given:
157///
158/// \code
159/// typedef int Integer;
160/// typedef const Integer CInteger;
161/// typedef CInteger DifferenceType;
162/// \endcode
163///
164/// Executing \c getUnqualifiedTypeSlow() on the type \c DifferenceType will
165/// desugar until we hit the type \c Integer, which has no qualifiers on it.
166QualType QualType::getUnqualifiedTypeSlow() const {
167  QualType Cur = *this;
168  while (true) {
169    if (!Cur.hasQualifiers())
170      return Cur;
171
172    const Type *CurTy = Cur.getTypePtr();
173    switch (CurTy->getTypeClass()) {
174#define ABSTRACT_TYPE(Class, Parent)
175#define TYPE(Class, Parent)                                  \
176    case Type::Class: {                                      \
177      const Class##Type *Ty = cast<Class##Type>(CurTy);      \
178      if (!Ty->isSugared())                                  \
179        return Cur.getLocalUnqualifiedType();                \
180      Cur = Ty->desugar();                                   \
181      break;                                                 \
182    }
183#include "clang/AST/TypeNodes.def"
184    }
185  }
186
187  return Cur.getUnqualifiedType();
188}
189
190/// getDesugaredType - Return the specified type with any "sugar" removed from
191/// the type.  This takes off typedefs, typeof's etc.  If the outer level of
192/// the type is already concrete, it returns it unmodified.  This is similar
193/// to getting the canonical type, but it doesn't remove *all* typedefs.  For
194/// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
195/// concrete.
196QualType QualType::getDesugaredType(QualType T, ASTContext &Context) {
197  SplitQualType split = getSplitDesugaredType(T);
198  return Context.getQualifiedType(split.first, split.second);
199}
200
201SplitQualType QualType::getSplitDesugaredType(QualType T) {
202  QualifierCollector Qs;
203
204  QualType Cur = T;
205  while (true) {
206    const Type *CurTy = Qs.strip(Cur);
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 SplitQualType(Ty, Qs); \
214      Cur = Ty->desugar(); \
215      break; \
216    }
217#include "clang/AST/TypeNodes.def"
218    }
219  }
220}
221
222QualType QualType::IgnoreParens(QualType T) {
223  while (const ParenType *PT = T->getAs<ParenType>())
224    T = PT->getInnerType();
225  return T;
226}
227
228/// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
229/// sugar off the given type.  This should produce an object of the
230/// same dynamic type as the canonical type.
231const Type *Type::getUnqualifiedDesugaredType() const {
232  const Type *Cur = this;
233
234  while (true) {
235    switch (Cur->getTypeClass()) {
236#define ABSTRACT_TYPE(Class, Parent)
237#define TYPE(Class, Parent) \
238    case Class: { \
239      const Class##Type *Ty = cast<Class##Type>(Cur); \
240      if (!Ty->isSugared()) return Cur; \
241      Cur = Ty->desugar().getTypePtr(); \
242      break; \
243    }
244#include "clang/AST/TypeNodes.def"
245    }
246  }
247}
248
249/// isVoidType - Helper method to determine if this is the 'void' type.
250bool Type::isVoidType() const {
251  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
252    return BT->getKind() == BuiltinType::Void;
253  return false;
254}
255
256bool Type::isDerivedType() const {
257  switch (CanonicalType->getTypeClass()) {
258  case Pointer:
259  case VariableArray:
260  case ConstantArray:
261  case IncompleteArray:
262  case FunctionProto:
263  case FunctionNoProto:
264  case LValueReference:
265  case RValueReference:
266  case Record:
267    return true;
268  default:
269    return false;
270  }
271}
272
273bool Type::isClassType() const {
274  if (const RecordType *RT = getAs<RecordType>())
275    return RT->getDecl()->isClass();
276  return false;
277}
278bool Type::isStructureType() const {
279  if (const RecordType *RT = getAs<RecordType>())
280    return RT->getDecl()->isStruct();
281  return false;
282}
283bool Type::isStructureOrClassType() const {
284  if (const RecordType *RT = getAs<RecordType>())
285    return RT->getDecl()->isStruct() || RT->getDecl()->isClass();
286  return false;
287}
288bool Type::isVoidPointerType() const {
289  if (const PointerType *PT = getAs<PointerType>())
290    return PT->getPointeeType()->isVoidType();
291  return false;
292}
293
294bool Type::isUnionType() const {
295  if (const RecordType *RT = getAs<RecordType>())
296    return RT->getDecl()->isUnion();
297  return false;
298}
299
300bool Type::isComplexType() const {
301  if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
302    return CT->getElementType()->isFloatingType();
303  return false;
304}
305
306bool Type::isComplexIntegerType() const {
307  // Check for GCC complex integer extension.
308  return getAsComplexIntegerType();
309}
310
311const ComplexType *Type::getAsComplexIntegerType() const {
312  if (const ComplexType *Complex = getAs<ComplexType>())
313    if (Complex->getElementType()->isIntegerType())
314      return Complex;
315  return 0;
316}
317
318QualType Type::getPointeeType() const {
319  if (const PointerType *PT = getAs<PointerType>())
320    return PT->getPointeeType();
321  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
322    return OPT->getPointeeType();
323  if (const BlockPointerType *BPT = getAs<BlockPointerType>())
324    return BPT->getPointeeType();
325  if (const ReferenceType *RT = getAs<ReferenceType>())
326    return RT->getPointeeType();
327  return QualType();
328}
329
330const RecordType *Type::getAsStructureType() const {
331  // If this is directly a structure type, return it.
332  if (const RecordType *RT = dyn_cast<RecordType>(this)) {
333    if (RT->getDecl()->isStruct())
334      return RT;
335  }
336
337  // If the canonical form of this type isn't the right kind, reject it.
338  if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
339    if (!RT->getDecl()->isStruct())
340      return 0;
341
342    // If this is a typedef for a structure type, strip the typedef off without
343    // losing all typedef information.
344    return cast<RecordType>(getUnqualifiedDesugaredType());
345  }
346  return 0;
347}
348
349const RecordType *Type::getAsUnionType() const {
350  // If this is directly a union type, return it.
351  if (const RecordType *RT = dyn_cast<RecordType>(this)) {
352    if (RT->getDecl()->isUnion())
353      return RT;
354  }
355
356  // If the canonical form of this type isn't the right kind, reject it.
357  if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
358    if (!RT->getDecl()->isUnion())
359      return 0;
360
361    // If this is a typedef for a union type, strip the typedef off without
362    // losing all typedef information.
363    return cast<RecordType>(getUnqualifiedDesugaredType());
364  }
365
366  return 0;
367}
368
369ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base,
370                               ObjCProtocolDecl * const *Protocols,
371                               unsigned NumProtocols)
372  : Type(ObjCObject, Canonical, false, false, false),
373    BaseType(Base)
374{
375  ObjCObjectTypeBits.NumProtocols = NumProtocols;
376  assert(getNumProtocols() == NumProtocols &&
377         "bitfield overflow in protocol count");
378  if (NumProtocols)
379    memcpy(getProtocolStorage(), Protocols,
380           NumProtocols * sizeof(ObjCProtocolDecl*));
381}
382
383const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const {
384  // There is no sugar for ObjCObjectType's, just return the canonical
385  // type pointer if it is the right class.  There is no typedef information to
386  // return and these cannot be Address-space qualified.
387  if (const ObjCObjectType *T = getAs<ObjCObjectType>())
388    if (T->getNumProtocols() && T->getInterface())
389      return T;
390  return 0;
391}
392
393bool Type::isObjCQualifiedInterfaceType() const {
394  return getAsObjCQualifiedInterfaceType() != 0;
395}
396
397const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
398  // There is no sugar for ObjCQualifiedIdType's, just return the canonical
399  // type pointer if it is the right class.
400  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
401    if (OPT->isObjCQualifiedIdType())
402      return OPT;
403  }
404  return 0;
405}
406
407const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
408  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
409    if (OPT->getInterfaceType())
410      return OPT;
411  }
412  return 0;
413}
414
415const CXXRecordDecl *Type::getCXXRecordDeclForPointerType() const {
416  if (const PointerType *PT = getAs<PointerType>())
417    if (const RecordType *RT = PT->getPointeeType()->getAs<RecordType>())
418      return dyn_cast<CXXRecordDecl>(RT->getDecl());
419  return 0;
420}
421
422CXXRecordDecl *Type::getAsCXXRecordDecl() const {
423  if (const RecordType *RT = getAs<RecordType>())
424    return dyn_cast<CXXRecordDecl>(RT->getDecl());
425  else if (const InjectedClassNameType *Injected
426                                  = getAs<InjectedClassNameType>())
427    return Injected->getDecl();
428
429  return 0;
430}
431
432bool Type::isIntegerType() const {
433  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
434    return BT->getKind() >= BuiltinType::Bool &&
435           BT->getKind() <= BuiltinType::Int128;
436  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
437    // Incomplete enum types are not treated as integer types.
438    // FIXME: In C++, enum types are never integer types.
439    return ET->getDecl()->isComplete();
440  return false;
441}
442
443bool Type::hasIntegerRepresentation() const {
444  if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
445    return VT->getElementType()->isIntegerType();
446  else
447    return isIntegerType();
448}
449
450/// \brief Determine whether this type is an integral type.
451///
452/// This routine determines whether the given type is an integral type per
453/// C++ [basic.fundamental]p7. Although the C standard does not define the
454/// term "integral type", it has a similar term "integer type", and in C++
455/// the two terms are equivalent. However, C's "integer type" includes
456/// enumeration types, while C++'s "integer type" does not. The \c ASTContext
457/// parameter is used to determine whether we should be following the C or
458/// C++ rules when determining whether this type is an integral/integer type.
459///
460/// For cases where C permits "an integer type" and C++ permits "an integral
461/// type", use this routine.
462///
463/// For cases where C permits "an integer type" and C++ permits "an integral
464/// or enumeration type", use \c isIntegralOrEnumerationType() instead.
465///
466/// \param Ctx The context in which this type occurs.
467///
468/// \returns true if the type is considered an integral type, false otherwise.
469bool Type::isIntegralType(ASTContext &Ctx) const {
470  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
471    return BT->getKind() >= BuiltinType::Bool &&
472    BT->getKind() <= BuiltinType::Int128;
473
474  if (!Ctx.getLangOptions().CPlusPlus)
475    if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
476      return ET->getDecl()->isComplete(); // Complete enum types are integral in C.
477
478  return false;
479}
480
481bool Type::isIntegralOrEnumerationType() const {
482  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
483    return BT->getKind() >= BuiltinType::Bool &&
484           BT->getKind() <= BuiltinType::Int128;
485
486  // Check for a complete enum type; incomplete enum types are not properly an
487  // enumeration type in the sense required here.
488  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
489    return ET->getDecl()->isComplete();
490
491  return false;
492}
493
494bool Type::isIntegralOrUnscopedEnumerationType() const {
495  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
496    return BT->getKind() >= BuiltinType::Bool &&
497           BT->getKind() <= BuiltinType::Int128;
498
499  // Check for a complete enum type; incomplete enum types are not properly an
500  // enumeration type in the sense required here.
501  // C++0x: However, if the underlying type of the enum is fixed, it is
502  // considered complete.
503  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
504    return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
505
506  return false;
507}
508
509
510bool Type::isBooleanType() const {
511  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
512    return BT->getKind() == BuiltinType::Bool;
513  return false;
514}
515
516bool Type::isCharType() const {
517  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
518    return BT->getKind() == BuiltinType::Char_U ||
519           BT->getKind() == BuiltinType::UChar ||
520           BT->getKind() == BuiltinType::Char_S ||
521           BT->getKind() == BuiltinType::SChar;
522  return false;
523}
524
525bool Type::isWideCharType() const {
526  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
527    return BT->getKind() == BuiltinType::WChar_S ||
528           BT->getKind() == BuiltinType::WChar_U;
529  return false;
530}
531
532/// \brief Determine whether this type is any of the built-in character
533/// types.
534bool Type::isAnyCharacterType() const {
535  const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType);
536  if (BT == 0) return false;
537  switch (BT->getKind()) {
538  default: return false;
539  case BuiltinType::Char_U:
540  case BuiltinType::UChar:
541  case BuiltinType::WChar_U:
542  case BuiltinType::Char16:
543  case BuiltinType::Char32:
544  case BuiltinType::Char_S:
545  case BuiltinType::SChar:
546  case BuiltinType::WChar_S:
547    return true;
548  }
549}
550
551/// isSignedIntegerType - Return true if this is an integer type that is
552/// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
553/// an enum decl which has a signed representation
554bool Type::isSignedIntegerType() const {
555  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
556    return BT->getKind() >= BuiltinType::Char_S &&
557           BT->getKind() <= BuiltinType::Int128;
558  }
559
560  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
561    // Incomplete enum types are not treated as integer types.
562    // FIXME: In C++, enum types are never integer types.
563    if (ET->getDecl()->isComplete())
564      return ET->getDecl()->getIntegerType()->isSignedIntegerType();
565  }
566
567  return false;
568}
569
570bool Type::hasSignedIntegerRepresentation() const {
571  if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
572    return VT->getElementType()->isSignedIntegerType();
573  else
574    return isSignedIntegerType();
575}
576
577/// isUnsignedIntegerType - Return true if this is an integer type that is
578/// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
579/// decl which has an unsigned representation
580bool Type::isUnsignedIntegerType() const {
581  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
582    return BT->getKind() >= BuiltinType::Bool &&
583           BT->getKind() <= BuiltinType::UInt128;
584  }
585
586  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
587    // Incomplete enum types are not treated as integer types.
588    // FIXME: In C++, enum types are never integer types.
589    if (ET->getDecl()->isComplete())
590      return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
591  }
592
593  return false;
594}
595
596bool Type::hasUnsignedIntegerRepresentation() const {
597  if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
598    return VT->getElementType()->isUnsignedIntegerType();
599  else
600    return isUnsignedIntegerType();
601}
602
603bool Type::isFloatingType() const {
604  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
605    return BT->getKind() >= BuiltinType::Float &&
606           BT->getKind() <= BuiltinType::LongDouble;
607  if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
608    return CT->getElementType()->isFloatingType();
609  return false;
610}
611
612bool Type::hasFloatingRepresentation() const {
613  if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
614    return VT->getElementType()->isFloatingType();
615  else
616    return isFloatingType();
617}
618
619bool Type::isRealFloatingType() const {
620  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
621    return BT->isFloatingPoint();
622  return false;
623}
624
625bool Type::isRealType() const {
626  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
627    return BT->getKind() >= BuiltinType::Bool &&
628           BT->getKind() <= BuiltinType::LongDouble;
629  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
630      return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
631  return false;
632}
633
634bool Type::isArithmeticType() const {
635  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
636    return BT->getKind() >= BuiltinType::Bool &&
637           BT->getKind() <= BuiltinType::LongDouble;
638  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
639    // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
640    // If a body isn't seen by the time we get here, return false.
641    //
642    // C++0x: Enumerations are not arithmetic types. For now, just return
643    // false for scoped enumerations since that will disable any
644    // unwanted implicit conversions.
645    return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete();
646  return isa<ComplexType>(CanonicalType);
647}
648
649bool Type::isScalarType() const {
650  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
651    return BT->getKind() > BuiltinType::Void &&
652           BT->getKind() <= BuiltinType::NullPtr;
653  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
654    // Enums are scalar types, but only if they are defined.  Incomplete enums
655    // are not treated as scalar types.
656    return ET->getDecl()->isComplete();
657  return isa<PointerType>(CanonicalType) ||
658         isa<BlockPointerType>(CanonicalType) ||
659         isa<MemberPointerType>(CanonicalType) ||
660         isa<ComplexType>(CanonicalType) ||
661         isa<ObjCObjectPointerType>(CanonicalType);
662}
663
664Type::ScalarTypeKind Type::getScalarTypeKind() const {
665  assert(isScalarType());
666
667  const Type *T = CanonicalType.getTypePtr();
668  if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) {
669    if (BT->getKind() == BuiltinType::Bool) return STK_Bool;
670    if (BT->getKind() == BuiltinType::NullPtr) return STK_Pointer;
671    if (BT->isInteger()) return STK_Integral;
672    if (BT->isFloatingPoint()) return STK_Floating;
673    llvm_unreachable("unknown scalar builtin type");
674  } else if (isa<PointerType>(T) ||
675             isa<BlockPointerType>(T) ||
676             isa<ObjCObjectPointerType>(T)) {
677    return STK_Pointer;
678  } else if (isa<MemberPointerType>(T)) {
679    return STK_MemberPointer;
680  } else if (isa<EnumType>(T)) {
681    assert(cast<EnumType>(T)->getDecl()->isComplete());
682    return STK_Integral;
683  } else if (const ComplexType *CT = dyn_cast<ComplexType>(T)) {
684    if (CT->getElementType()->isRealFloatingType())
685      return STK_FloatingComplex;
686    return STK_IntegralComplex;
687  }
688
689  llvm_unreachable("unknown scalar type");
690  return STK_Pointer;
691}
692
693/// \brief Determines whether the type is a C++ aggregate type or C
694/// aggregate or union type.
695///
696/// An aggregate type is an array or a class type (struct, union, or
697/// class) that has no user-declared constructors, no private or
698/// protected non-static data members, no base classes, and no virtual
699/// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
700/// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
701/// includes union types.
702bool Type::isAggregateType() const {
703  if (const RecordType *Record = dyn_cast<RecordType>(CanonicalType)) {
704    if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
705      return ClassDecl->isAggregate();
706
707    return true;
708  }
709
710  return isa<ArrayType>(CanonicalType);
711}
712
713/// isConstantSizeType - Return true if this is not a variable sized type,
714/// according to the rules of C99 6.7.5p3.  It is not legal to call this on
715/// incomplete types or dependent types.
716bool Type::isConstantSizeType() const {
717  assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
718  assert(!isDependentType() && "This doesn't make sense for dependent types");
719  // The VAT must have a size, as it is known to be complete.
720  return !isa<VariableArrayType>(CanonicalType);
721}
722
723/// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
724/// - a type that can describe objects, but which lacks information needed to
725/// determine its size.
726bool Type::isIncompleteType() const {
727  switch (CanonicalType->getTypeClass()) {
728  default: return false;
729  case Builtin:
730    // Void is the only incomplete builtin type.  Per C99 6.2.5p19, it can never
731    // be completed.
732    return isVoidType();
733  case Enum:
734    // An enumeration with fixed underlying type is complete (C++0x 7.2p3).
735    if (cast<EnumType>(CanonicalType)->getDecl()->isFixed())
736        return false;
737    // Fall through.
738  case Record:
739    // A tagged type (struct/union/enum/class) is incomplete if the decl is a
740    // forward declaration, but not a full definition (C99 6.2.5p22).
741    return !cast<TagType>(CanonicalType)->getDecl()->isDefinition();
742  case ConstantArray:
743    // An array is incomplete if its element type is incomplete
744    // (C++ [dcl.array]p1).
745    // We don't handle variable arrays (they're not allowed in C++) or
746    // dependent-sized arrays (dependent types are never treated as incomplete).
747    return cast<ArrayType>(CanonicalType)->getElementType()->isIncompleteType();
748  case IncompleteArray:
749    // An array of unknown size is an incomplete type (C99 6.2.5p22).
750    return true;
751  case ObjCObject:
752    return cast<ObjCObjectType>(CanonicalType)->getBaseType()
753                                                         ->isIncompleteType();
754  case ObjCInterface:
755    // ObjC interfaces are incomplete if they are @class, not @interface.
756    return cast<ObjCInterfaceType>(CanonicalType)->getDecl()->isForwardDecl();
757  }
758}
759
760/// isPODType - Return true if this is a plain-old-data type (C++ 3.9p10)
761bool Type::isPODType() const {
762  // The compiler shouldn't query this for incomplete types, but the user might.
763  // We return false for that case. Except for incomplete arrays of PODs, which
764  // are PODs according to the standard.
765  if (isIncompleteArrayType() &&
766      cast<ArrayType>(CanonicalType)->getElementType()->isPODType())
767    return true;
768  if (isIncompleteType())
769    return false;
770
771  switch (CanonicalType->getTypeClass()) {
772    // Everything not explicitly mentioned is not POD.
773  default: return false;
774  case VariableArray:
775  case ConstantArray:
776    // IncompleteArray is handled above.
777    return cast<ArrayType>(CanonicalType)->getElementType()->isPODType();
778
779  case Builtin:
780  case Complex:
781  case Pointer:
782  case MemberPointer:
783  case Vector:
784  case ExtVector:
785  case ObjCObjectPointer:
786  case BlockPointer:
787    return true;
788
789  case Enum:
790    return true;
791
792  case Record:
793    if (CXXRecordDecl *ClassDecl
794          = dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
795      return ClassDecl->isPOD();
796
797    // C struct/union is POD.
798    return true;
799  }
800}
801
802bool Type::isLiteralType() const {
803  if (isIncompleteType())
804    return false;
805
806  // C++0x [basic.types]p10:
807  //   A type is a literal type if it is:
808  switch (CanonicalType->getTypeClass()) {
809    // We're whitelisting
810  default: return false;
811
812    //   -- a scalar type
813  case Builtin:
814  case Complex:
815  case Pointer:
816  case MemberPointer:
817  case Vector:
818  case ExtVector:
819  case ObjCObjectPointer:
820  case Enum:
821    return true;
822
823    //   -- a class type with ...
824  case Record:
825    // FIXME: Do the tests
826    return false;
827
828    //   -- an array of literal type
829    // Extension: variable arrays cannot be literal types, since they're
830    // runtime-sized.
831  case ConstantArray:
832    return cast<ArrayType>(CanonicalType)->getElementType()->isLiteralType();
833  }
834}
835
836bool Type::isPromotableIntegerType() const {
837  if (const BuiltinType *BT = getAs<BuiltinType>())
838    switch (BT->getKind()) {
839    case BuiltinType::Bool:
840    case BuiltinType::Char_S:
841    case BuiltinType::Char_U:
842    case BuiltinType::SChar:
843    case BuiltinType::UChar:
844    case BuiltinType::Short:
845    case BuiltinType::UShort:
846      return true;
847    default:
848      return false;
849    }
850
851  // Enumerated types are promotable to their compatible integer types
852  // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
853  if (const EnumType *ET = getAs<EnumType>()){
854    if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull()
855        || ET->getDecl()->isScoped())
856      return false;
857
858    const BuiltinType *BT
859      = ET->getDecl()->getPromotionType()->getAs<BuiltinType>();
860    return BT->getKind() == BuiltinType::Int
861           || BT->getKind() == BuiltinType::UInt;
862  }
863
864  return false;
865}
866
867bool Type::isNullPtrType() const {
868  if (const BuiltinType *BT = getAs<BuiltinType>())
869    return BT->getKind() == BuiltinType::NullPtr;
870  return false;
871}
872
873bool Type::isSpecifierType() const {
874  // Note that this intentionally does not use the canonical type.
875  switch (getTypeClass()) {
876  case Builtin:
877  case Record:
878  case Enum:
879  case Typedef:
880  case Complex:
881  case TypeOfExpr:
882  case TypeOf:
883  case TemplateTypeParm:
884  case SubstTemplateTypeParm:
885  case TemplateSpecialization:
886  case Elaborated:
887  case DependentName:
888  case DependentTemplateSpecialization:
889  case ObjCInterface:
890  case ObjCObject:
891  case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers
892    return true;
893  default:
894    return false;
895  }
896}
897
898ElaboratedTypeKeyword
899TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) {
900  switch (TypeSpec) {
901  default: return ETK_None;
902  case TST_typename: return ETK_Typename;
903  case TST_class: return ETK_Class;
904  case TST_struct: return ETK_Struct;
905  case TST_union: return ETK_Union;
906  case TST_enum: return ETK_Enum;
907  }
908}
909
910TagTypeKind
911TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
912  switch(TypeSpec) {
913  case TST_class: return TTK_Class;
914  case TST_struct: return TTK_Struct;
915  case TST_union: return TTK_Union;
916  case TST_enum: return TTK_Enum;
917  }
918
919  llvm_unreachable("Type specifier is not a tag type kind.");
920  return TTK_Union;
921}
922
923ElaboratedTypeKeyword
924TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) {
925  switch (Kind) {
926  case TTK_Class: return ETK_Class;
927  case TTK_Struct: return ETK_Struct;
928  case TTK_Union: return ETK_Union;
929  case TTK_Enum: return ETK_Enum;
930  }
931  llvm_unreachable("Unknown tag type kind.");
932}
933
934TagTypeKind
935TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
936  switch (Keyword) {
937  case ETK_Class: return TTK_Class;
938  case ETK_Struct: return TTK_Struct;
939  case ETK_Union: return TTK_Union;
940  case ETK_Enum: return TTK_Enum;
941  case ETK_None: // Fall through.
942  case ETK_Typename:
943    llvm_unreachable("Elaborated type keyword is not a tag type kind.");
944  }
945  llvm_unreachable("Unknown elaborated type keyword.");
946}
947
948bool
949TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
950  switch (Keyword) {
951  case ETK_None:
952  case ETK_Typename:
953    return false;
954  case ETK_Class:
955  case ETK_Struct:
956  case ETK_Union:
957  case ETK_Enum:
958    return true;
959  }
960  llvm_unreachable("Unknown elaborated type keyword.");
961}
962
963const char*
964TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) {
965  switch (Keyword) {
966  case ETK_None: return "";
967  case ETK_Typename: return "typename";
968  case ETK_Class:  return "class";
969  case ETK_Struct: return "struct";
970  case ETK_Union:  return "union";
971  case ETK_Enum:   return "enum";
972  }
973
974  llvm_unreachable("Unknown elaborated type keyword.");
975  return "";
976}
977
978DependentTemplateSpecializationType::DependentTemplateSpecializationType(
979                         ElaboratedTypeKeyword Keyword,
980                         NestedNameSpecifier *NNS, const IdentifierInfo *Name,
981                         unsigned NumArgs, const TemplateArgument *Args,
982                         QualType Canon)
983  : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true,
984                    /*VariablyModified=*/false,
985                    NNS->containsUnexpandedParameterPack()),
986    NNS(NNS), Name(Name), NumArgs(NumArgs) {
987  assert(NNS && NNS->isDependent() &&
988         "DependentTemplateSpecializatonType requires dependent qualifier");
989  for (unsigned I = 0; I != NumArgs; ++I) {
990    if (Args[I].containsUnexpandedParameterPack())
991      setContainsUnexpandedParameterPack();
992
993    new (&getArgBuffer()[I]) TemplateArgument(Args[I]);
994  }
995}
996
997void
998DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
999                                             ASTContext &Context,
1000                                             ElaboratedTypeKeyword Keyword,
1001                                             NestedNameSpecifier *Qualifier,
1002                                             const IdentifierInfo *Name,
1003                                             unsigned NumArgs,
1004                                             const TemplateArgument *Args) {
1005  ID.AddInteger(Keyword);
1006  ID.AddPointer(Qualifier);
1007  ID.AddPointer(Name);
1008  for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1009    Args[Idx].Profile(ID, Context);
1010}
1011
1012bool Type::isElaboratedTypeSpecifier() const {
1013  ElaboratedTypeKeyword Keyword;
1014  if (const ElaboratedType *Elab = dyn_cast<ElaboratedType>(this))
1015    Keyword = Elab->getKeyword();
1016  else if (const DependentNameType *DepName = dyn_cast<DependentNameType>(this))
1017    Keyword = DepName->getKeyword();
1018  else if (const DependentTemplateSpecializationType *DepTST =
1019             dyn_cast<DependentTemplateSpecializationType>(this))
1020    Keyword = DepTST->getKeyword();
1021  else
1022    return false;
1023
1024  return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
1025}
1026
1027const char *Type::getTypeClassName() const {
1028  switch (TypeBits.TC) {
1029#define ABSTRACT_TYPE(Derived, Base)
1030#define TYPE(Derived, Base) case Derived: return #Derived;
1031#include "clang/AST/TypeNodes.def"
1032  }
1033
1034  llvm_unreachable("Invalid type class.");
1035  return 0;
1036}
1037
1038const char *BuiltinType::getName(const LangOptions &LO) const {
1039  switch (getKind()) {
1040  case Void:              return "void";
1041  case Bool:              return LO.Bool ? "bool" : "_Bool";
1042  case Char_S:            return "char";
1043  case Char_U:            return "char";
1044  case SChar:             return "signed char";
1045  case Short:             return "short";
1046  case Int:               return "int";
1047  case Long:              return "long";
1048  case LongLong:          return "long long";
1049  case Int128:            return "__int128_t";
1050  case UChar:             return "unsigned char";
1051  case UShort:            return "unsigned short";
1052  case UInt:              return "unsigned int";
1053  case ULong:             return "unsigned long";
1054  case ULongLong:         return "unsigned long long";
1055  case UInt128:           return "__uint128_t";
1056  case Float:             return "float";
1057  case Double:            return "double";
1058  case LongDouble:        return "long double";
1059  case WChar_S:
1060  case WChar_U:           return "wchar_t";
1061  case Char16:            return "char16_t";
1062  case Char32:            return "char32_t";
1063  case NullPtr:           return "nullptr_t";
1064  case Overload:          return "<overloaded function type>";
1065  case Dependent:         return "<dependent type>";
1066  case UndeducedAuto:     return "auto";
1067  case ObjCId:            return "id";
1068  case ObjCClass:         return "Class";
1069  case ObjCSel:           return "SEL";
1070  }
1071
1072  llvm_unreachable("Invalid builtin type.");
1073  return 0;
1074}
1075
1076QualType QualType::getNonLValueExprType(ASTContext &Context) const {
1077  if (const ReferenceType *RefType = getTypePtr()->getAs<ReferenceType>())
1078    return RefType->getPointeeType();
1079
1080  // C++0x [basic.lval]:
1081  //   Class prvalues can have cv-qualified types; non-class prvalues always
1082  //   have cv-unqualified types.
1083  //
1084  // See also C99 6.3.2.1p2.
1085  if (!Context.getLangOptions().CPlusPlus ||
1086      (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
1087    return getUnqualifiedType();
1088
1089  return *this;
1090}
1091
1092llvm::StringRef FunctionType::getNameForCallConv(CallingConv CC) {
1093  switch (CC) {
1094  case CC_Default:
1095    llvm_unreachable("no name for default cc");
1096    return "";
1097
1098  case CC_C: return "cdecl";
1099  case CC_X86StdCall: return "stdcall";
1100  case CC_X86FastCall: return "fastcall";
1101  case CC_X86ThisCall: return "thiscall";
1102  case CC_X86Pascal: return "pascal";
1103  }
1104
1105  llvm_unreachable("Invalid calling convention.");
1106  return "";
1107}
1108
1109FunctionProtoType::FunctionProtoType(QualType result, const QualType *args,
1110                                     unsigned numArgs, QualType canonical,
1111                                     const ExtProtoInfo &epi)
1112  : FunctionType(FunctionProto, result, epi.Variadic, epi.TypeQuals, canonical,
1113                 result->isDependentType(),
1114                 result->isVariablyModifiedType(),
1115                 result->containsUnexpandedParameterPack(),
1116                 epi.ExtInfo),
1117    NumArgs(numArgs), NumExceptions(epi.NumExceptions),
1118    HasExceptionSpec(epi.HasExceptionSpec),
1119    HasAnyExceptionSpec(epi.HasAnyExceptionSpec)
1120{
1121  // Fill in the trailing argument array.
1122  QualType *argSlot = reinterpret_cast<QualType*>(this+1);
1123  for (unsigned i = 0; i != numArgs; ++i) {
1124    if (args[i]->isDependentType())
1125      setDependent();
1126
1127    if (args[i]->containsUnexpandedParameterPack())
1128      setContainsUnexpandedParameterPack();
1129
1130    argSlot[i] = args[i];
1131  }
1132
1133  // Fill in the exception array.
1134  QualType *exnSlot = argSlot + numArgs;
1135  for (unsigned i = 0, e = epi.NumExceptions; i != e; ++i) {
1136    if (epi.Exceptions[i]->isDependentType())
1137      setDependent();
1138
1139    if (epi.Exceptions[i]->containsUnexpandedParameterPack())
1140      setContainsUnexpandedParameterPack();
1141
1142    exnSlot[i] = epi.Exceptions[i];
1143  }
1144}
1145
1146bool FunctionProtoType::isTemplateVariadic() const {
1147  return getNumArgs() && isa<PackExpansionType>(getArgType(getNumArgs() - 1));
1148}
1149
1150void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
1151                                const QualType *ArgTys, unsigned NumArgs,
1152                                const ExtProtoInfo &epi) {
1153  ID.AddPointer(Result.getAsOpaquePtr());
1154  for (unsigned i = 0; i != NumArgs; ++i)
1155    ID.AddPointer(ArgTys[i].getAsOpaquePtr());
1156  ID.AddBoolean(epi.Variadic);
1157  ID.AddInteger(epi.TypeQuals);
1158  if (epi.HasExceptionSpec) {
1159    ID.AddBoolean(epi.HasAnyExceptionSpec);
1160    for (unsigned i = 0; i != epi.NumExceptions; ++i)
1161      ID.AddPointer(epi.Exceptions[i].getAsOpaquePtr());
1162  }
1163  epi.ExtInfo.Profile(ID);
1164}
1165
1166void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID) {
1167  Profile(ID, getResultType(), arg_type_begin(), NumArgs, getExtProtoInfo());
1168}
1169
1170QualType TypedefType::desugar() const {
1171  return getDecl()->getUnderlyingType();
1172}
1173
1174TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
1175  : Type(TypeOfExpr, can, E->isTypeDependent(),
1176         E->getType()->isVariablyModifiedType(),
1177         E->containsUnexpandedParameterPack()),
1178    TOExpr(E) {
1179}
1180
1181QualType TypeOfExprType::desugar() const {
1182  return getUnderlyingExpr()->getType();
1183}
1184
1185void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
1186                                      ASTContext &Context, Expr *E) {
1187  E->Profile(ID, Context, true);
1188}
1189
1190DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
1191  : Type(Decltype, can, E->isTypeDependent(),
1192         E->getType()->isVariablyModifiedType(),
1193         E->containsUnexpandedParameterPack()),
1194    E(E),
1195  UnderlyingType(underlyingType) {
1196}
1197
1198DependentDecltypeType::DependentDecltypeType(ASTContext &Context, Expr *E)
1199  : DecltypeType(E, Context.DependentTy), Context(Context) { }
1200
1201void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
1202                                    ASTContext &Context, Expr *E) {
1203  E->Profile(ID, Context, true);
1204}
1205
1206TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
1207  : Type(TC, can, D->isDependentType(), /*VariablyModified=*/false,
1208         /*ContainsUnexpandedParameterPack=*/false),
1209    decl(const_cast<TagDecl*>(D)) {}
1210
1211static TagDecl *getInterestingTagDecl(TagDecl *decl) {
1212  for (TagDecl::redecl_iterator I = decl->redecls_begin(),
1213                                E = decl->redecls_end();
1214       I != E; ++I) {
1215    if (I->isDefinition() || I->isBeingDefined())
1216      return *I;
1217  }
1218  // If there's no definition (not even in progress), return what we have.
1219  return decl;
1220}
1221
1222TagDecl *TagType::getDecl() const {
1223  return getInterestingTagDecl(decl);
1224}
1225
1226bool TagType::isBeingDefined() const {
1227  return getDecl()->isBeingDefined();
1228}
1229
1230CXXRecordDecl *InjectedClassNameType::getDecl() const {
1231  return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
1232}
1233
1234bool RecordType::classof(const TagType *TT) {
1235  return isa<RecordDecl>(TT->getDecl());
1236}
1237
1238bool EnumType::classof(const TagType *TT) {
1239  return isa<EnumDecl>(TT->getDecl());
1240}
1241
1242bool TemplateSpecializationType::
1243anyDependentTemplateArguments(const TemplateArgumentListInfo &Args) {
1244  return anyDependentTemplateArguments(Args.getArgumentArray(), Args.size());
1245}
1246
1247bool TemplateSpecializationType::
1248anyDependentTemplateArguments(const TemplateArgumentLoc *Args, unsigned N) {
1249  for (unsigned i = 0; i != N; ++i)
1250    if (Args[i].getArgument().isDependent())
1251      return true;
1252  return false;
1253}
1254
1255bool TemplateSpecializationType::
1256anyDependentTemplateArguments(const TemplateArgument *Args, unsigned N) {
1257  for (unsigned i = 0; i != N; ++i)
1258    if (Args[i].isDependent())
1259      return true;
1260  return false;
1261}
1262
1263TemplateSpecializationType::
1264TemplateSpecializationType(TemplateName T,
1265                           const TemplateArgument *Args,
1266                           unsigned NumArgs, QualType Canon)
1267  : Type(TemplateSpecialization,
1268         Canon.isNull()? QualType(this, 0) : Canon,
1269         T.isDependent(), false,
1270         T.containsUnexpandedParameterPack()),
1271    Template(T), NumArgs(NumArgs)
1272{
1273  assert((!Canon.isNull() ||
1274          T.isDependent() || anyDependentTemplateArguments(Args, NumArgs)) &&
1275         "No canonical type for non-dependent class template specialization");
1276
1277  TemplateArgument *TemplateArgs
1278    = reinterpret_cast<TemplateArgument *>(this + 1);
1279  for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1280    // Update dependent and variably-modified bits.
1281    if (Args[Arg].isDependent())
1282      setDependent();
1283    if (Args[Arg].getKind() == TemplateArgument::Type &&
1284        Args[Arg].getAsType()->isVariablyModifiedType())
1285      setVariablyModified();
1286    if (Args[Arg].containsUnexpandedParameterPack())
1287      setContainsUnexpandedParameterPack();
1288
1289    new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]);
1290  }
1291}
1292
1293void
1294TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1295                                    TemplateName T,
1296                                    const TemplateArgument *Args,
1297                                    unsigned NumArgs,
1298                                    ASTContext &Context) {
1299  T.Profile(ID);
1300  for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1301    Args[Idx].Profile(ID, Context);
1302}
1303
1304QualType QualifierCollector::apply(ASTContext &Context, QualType QT) const {
1305  if (!hasNonFastQualifiers())
1306    return QT.withFastQualifiers(getFastQualifiers());
1307
1308  return Context.getQualifiedType(QT, *this);
1309}
1310
1311QualType QualifierCollector::apply(ASTContext &Context, const Type *T) const {
1312  if (!hasNonFastQualifiers())
1313    return QualType(T, getFastQualifiers());
1314
1315  return Context.getQualifiedType(T, *this);
1316}
1317
1318void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
1319                                 QualType BaseType,
1320                                 ObjCProtocolDecl * const *Protocols,
1321                                 unsigned NumProtocols) {
1322  ID.AddPointer(BaseType.getAsOpaquePtr());
1323  for (unsigned i = 0; i != NumProtocols; i++)
1324    ID.AddPointer(Protocols[i]);
1325}
1326
1327void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
1328  Profile(ID, getBaseType(), qual_begin(), getNumProtocols());
1329}
1330
1331namespace {
1332
1333/// \brief The cached properties of a type.
1334class CachedProperties {
1335  char linkage;
1336  char visibility;
1337  bool local;
1338
1339public:
1340  CachedProperties(Linkage linkage, Visibility visibility, bool local)
1341    : linkage(linkage), visibility(visibility), local(local) {}
1342
1343  Linkage getLinkage() const { return (Linkage) linkage; }
1344  Visibility getVisibility() const { return (Visibility) visibility; }
1345  bool hasLocalOrUnnamedType() const { return local; }
1346
1347  friend CachedProperties merge(CachedProperties L, CachedProperties R) {
1348    return CachedProperties(minLinkage(L.getLinkage(), R.getLinkage()),
1349                            minVisibility(L.getVisibility(), R.getVisibility()),
1350                         L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType());
1351  }
1352};
1353}
1354
1355static CachedProperties computeCachedProperties(const Type *T);
1356
1357namespace clang {
1358/// The type-property cache.  This is templated so as to be
1359/// instantiated at an internal type to prevent unnecessary symbol
1360/// leakage.
1361template <class Private> class TypePropertyCache {
1362public:
1363  static CachedProperties get(QualType T) {
1364    return get(T.getTypePtr());
1365  }
1366
1367  static CachedProperties get(const Type *T) {
1368    ensure(T);
1369    return CachedProperties(T->TypeBits.getLinkage(),
1370                            T->TypeBits.getVisibility(),
1371                            T->TypeBits.hasLocalOrUnnamedType());
1372  }
1373
1374  static void ensure(const Type *T) {
1375    // If the cache is valid, we're okay.
1376    if (T->TypeBits.isCacheValid()) return;
1377
1378    // If this type is non-canonical, ask its canonical type for the
1379    // relevant information.
1380    if (QualType(T, 0) != T->CanonicalType) {
1381      const Type *CT = T->CanonicalType.getTypePtr();
1382      ensure(CT);
1383      T->TypeBits.CacheValidAndVisibility =
1384        CT->TypeBits.CacheValidAndVisibility;
1385      T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
1386      T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
1387      return;
1388    }
1389
1390    // Compute the cached properties and then set the cache.
1391    CachedProperties Result = computeCachedProperties(T);
1392    T->TypeBits.CacheValidAndVisibility = Result.getVisibility() + 1U;
1393    assert(T->TypeBits.isCacheValid() &&
1394           T->TypeBits.getVisibility() == Result.getVisibility());
1395    T->TypeBits.CachedLinkage = Result.getLinkage();
1396    T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
1397  }
1398};
1399}
1400
1401// Instantiate the friend template at a private class.  In a
1402// reasonable implementation, these symbols will be internal.
1403// It is terrible that this is the best way to accomplish this.
1404namespace { class Private {}; }
1405typedef TypePropertyCache<Private> Cache;
1406
1407static CachedProperties computeCachedProperties(const Type *T) {
1408  switch (T->getTypeClass()) {
1409#define TYPE(Class,Base)
1410#define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
1411#include "clang/AST/TypeNodes.def"
1412    llvm_unreachable("didn't expect a non-canonical type here");
1413
1414#define TYPE(Class,Base)
1415#define DEPENDENT_TYPE(Class,Base) case Type::Class:
1416#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
1417#include "clang/AST/TypeNodes.def"
1418    // Treat dependent types as external.
1419    assert(T->isDependentType());
1420    return CachedProperties(ExternalLinkage, DefaultVisibility, false);
1421
1422  case Type::Builtin:
1423    // C++ [basic.link]p8:
1424    //   A type is said to have linkage if and only if:
1425    //     - it is a fundamental type (3.9.1); or
1426    return CachedProperties(ExternalLinkage, DefaultVisibility, false);
1427
1428  case Type::Record:
1429  case Type::Enum: {
1430    const TagDecl *Tag = cast<TagType>(T)->getDecl();
1431
1432    // C++ [basic.link]p8:
1433    //     - it is a class or enumeration type that is named (or has a name
1434    //       for linkage purposes (7.1.3)) and the name has linkage; or
1435    //     -  it is a specialization of a class template (14); or
1436    NamedDecl::LinkageInfo LV = Tag->getLinkageAndVisibility();
1437    bool IsLocalOrUnnamed =
1438      Tag->getDeclContext()->isFunctionOrMethod() ||
1439      (!Tag->getIdentifier() && !Tag->getTypedefForAnonDecl());
1440    return CachedProperties(LV.linkage(), LV.visibility(), IsLocalOrUnnamed);
1441  }
1442
1443    // C++ [basic.link]p8:
1444    //   - it is a compound type (3.9.2) other than a class or enumeration,
1445    //     compounded exclusively from types that have linkage; or
1446  case Type::Complex:
1447    return Cache::get(cast<ComplexType>(T)->getElementType());
1448  case Type::Pointer:
1449    return Cache::get(cast<PointerType>(T)->getPointeeType());
1450  case Type::BlockPointer:
1451    return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
1452  case Type::LValueReference:
1453  case Type::RValueReference:
1454    return Cache::get(cast<ReferenceType>(T)->getPointeeType());
1455  case Type::MemberPointer: {
1456    const MemberPointerType *MPT = cast<MemberPointerType>(T);
1457    return merge(Cache::get(MPT->getClass()),
1458                 Cache::get(MPT->getPointeeType()));
1459  }
1460  case Type::ConstantArray:
1461  case Type::IncompleteArray:
1462  case Type::VariableArray:
1463    return Cache::get(cast<ArrayType>(T)->getElementType());
1464  case Type::Vector:
1465  case Type::ExtVector:
1466    return Cache::get(cast<VectorType>(T)->getElementType());
1467  case Type::FunctionNoProto:
1468    return Cache::get(cast<FunctionType>(T)->getResultType());
1469  case Type::FunctionProto: {
1470    const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1471    CachedProperties result = Cache::get(FPT->getResultType());
1472    for (FunctionProtoType::arg_type_iterator ai = FPT->arg_type_begin(),
1473           ae = FPT->arg_type_end(); ai != ae; ++ai)
1474      result = merge(result, Cache::get(*ai));
1475    return result;
1476  }
1477  case Type::ObjCInterface: {
1478    NamedDecl::LinkageInfo LV =
1479      cast<ObjCInterfaceType>(T)->getDecl()->getLinkageAndVisibility();
1480    return CachedProperties(LV.linkage(), LV.visibility(), false);
1481  }
1482  case Type::ObjCObject:
1483    return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
1484  case Type::ObjCObjectPointer:
1485    return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
1486  }
1487
1488  llvm_unreachable("unhandled type class");
1489
1490  // C++ [basic.link]p8:
1491  //   Names not covered by these rules have no linkage.
1492  return CachedProperties(NoLinkage, DefaultVisibility, false);
1493}
1494
1495/// \brief Determine the linkage of this type.
1496Linkage Type::getLinkage() const {
1497  Cache::ensure(this);
1498  return TypeBits.getLinkage();
1499}
1500
1501/// \brief Determine the linkage of this type.
1502Visibility Type::getVisibility() const {
1503  Cache::ensure(this);
1504  return TypeBits.getVisibility();
1505}
1506
1507bool Type::hasUnnamedOrLocalType() const {
1508  Cache::ensure(this);
1509  return TypeBits.hasLocalOrUnnamedType();
1510}
1511
1512std::pair<Linkage,Visibility> Type::getLinkageAndVisibility() const {
1513  Cache::ensure(this);
1514  return std::make_pair(TypeBits.getLinkage(), TypeBits.getVisibility());
1515}
1516
1517void Type::ClearLinkageCache() {
1518  TypeBits.CacheValidAndVisibility = 0;
1519  if (QualType(this, 0) != CanonicalType)
1520    CanonicalType->TypeBits.CacheValidAndVisibility = 0;
1521}
1522