Type.cpp revision 223017
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}
41
42bool QualType::isConstant(QualType T, ASTContext &Ctx) {
43  if (T.isConstQualified())
44    return true;
45
46  if (const ArrayType *AT = Ctx.getAsArrayType(T))
47    return AT->getElementType().isConstant(Ctx);
48
49  return false;
50}
51
52unsigned ConstantArrayType::getNumAddressingBits(ASTContext &Context,
53                                                 QualType ElementType,
54                                               const llvm::APInt &NumElements) {
55  llvm::APSInt SizeExtended(NumElements, true);
56  unsigned SizeTypeBits = Context.getTypeSize(Context.getSizeType());
57  SizeExtended = SizeExtended.extend(std::max(SizeTypeBits,
58                                              SizeExtended.getBitWidth()) * 2);
59
60  uint64_t ElementSize
61    = Context.getTypeSizeInChars(ElementType).getQuantity();
62  llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize));
63  TotalSize *= SizeExtended;
64
65  return TotalSize.getActiveBits();
66}
67
68unsigned ConstantArrayType::getMaxSizeBits(ASTContext &Context) {
69  unsigned Bits = Context.getTypeSize(Context.getSizeType());
70
71  // GCC appears to only allow 63 bits worth of address space when compiling
72  // for 64-bit, so we do the same.
73  if (Bits == 64)
74    --Bits;
75
76  return Bits;
77}
78
79DependentSizedArrayType::DependentSizedArrayType(const ASTContext &Context,
80                                                 QualType et, QualType can,
81                                                 Expr *e, ArraySizeModifier sm,
82                                                 unsigned tq,
83                                                 SourceRange brackets)
84    : ArrayType(DependentSizedArray, et, can, sm, tq,
85                (et->containsUnexpandedParameterPack() ||
86                 (e && e->containsUnexpandedParameterPack()))),
87      Context(Context), SizeExpr((Stmt*) e), Brackets(brackets)
88{
89}
90
91void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID,
92                                      const ASTContext &Context,
93                                      QualType ET,
94                                      ArraySizeModifier SizeMod,
95                                      unsigned TypeQuals,
96                                      Expr *E) {
97  ID.AddPointer(ET.getAsOpaquePtr());
98  ID.AddInteger(SizeMod);
99  ID.AddInteger(TypeQuals);
100  E->Profile(ID, Context, true);
101}
102
103DependentSizedExtVectorType::DependentSizedExtVectorType(const
104                                                         ASTContext &Context,
105                                                         QualType ElementType,
106                                                         QualType can,
107                                                         Expr *SizeExpr,
108                                                         SourceLocation loc)
109    : Type(DependentSizedExtVector, can, /*Dependent=*/true,
110           ElementType->isVariablyModifiedType(),
111           (ElementType->containsUnexpandedParameterPack() ||
112            (SizeExpr && SizeExpr->containsUnexpandedParameterPack()))),
113      Context(Context), SizeExpr(SizeExpr), ElementType(ElementType),
114      loc(loc)
115{
116}
117
118void
119DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID,
120                                     const ASTContext &Context,
121                                     QualType ElementType, Expr *SizeExpr) {
122  ID.AddPointer(ElementType.getAsOpaquePtr());
123  SizeExpr->Profile(ID, Context, true);
124}
125
126VectorType::VectorType(QualType vecType, unsigned nElements, QualType canonType,
127                       VectorKind vecKind)
128  : Type(Vector, canonType, vecType->isDependentType(),
129         vecType->isVariablyModifiedType(),
130         vecType->containsUnexpandedParameterPack()),
131    ElementType(vecType)
132{
133  VectorTypeBits.VecKind = vecKind;
134  VectorTypeBits.NumElements = nElements;
135}
136
137VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements,
138                       QualType canonType, VectorKind vecKind)
139  : Type(tc, canonType, vecType->isDependentType(),
140         vecType->isVariablyModifiedType(),
141         vecType->containsUnexpandedParameterPack()),
142    ElementType(vecType)
143{
144  VectorTypeBits.VecKind = vecKind;
145  VectorTypeBits.NumElements = nElements;
146}
147
148/// getArrayElementTypeNoTypeQual - If this is an array type, return the
149/// element type of the array, potentially with type qualifiers missing.
150/// This method should never be used when type qualifiers are meaningful.
151const Type *Type::getArrayElementTypeNoTypeQual() const {
152  // If this is directly an array type, return it.
153  if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
154    return ATy->getElementType().getTypePtr();
155
156  // If the canonical form of this type isn't the right kind, reject it.
157  if (!isa<ArrayType>(CanonicalType))
158    return 0;
159
160  // If this is a typedef for an array type, strip the typedef off without
161  // losing all typedef information.
162  return cast<ArrayType>(getUnqualifiedDesugaredType())
163    ->getElementType().getTypePtr();
164}
165
166/// getDesugaredType - Return the specified type with any "sugar" removed from
167/// the type.  This takes off typedefs, typeof's etc.  If the outer level of
168/// the type is already concrete, it returns it unmodified.  This is similar
169/// to getting the canonical type, but it doesn't remove *all* typedefs.  For
170/// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
171/// concrete.
172QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) {
173  SplitQualType split = getSplitDesugaredType(T);
174  return Context.getQualifiedType(split.first, split.second);
175}
176
177SplitQualType QualType::getSplitDesugaredType(QualType T) {
178  QualifierCollector Qs;
179
180  QualType Cur = T;
181  while (true) {
182    const Type *CurTy = Qs.strip(Cur);
183    switch (CurTy->getTypeClass()) {
184#define ABSTRACT_TYPE(Class, Parent)
185#define TYPE(Class, Parent) \
186    case Type::Class: { \
187      const Class##Type *Ty = cast<Class##Type>(CurTy); \
188      if (!Ty->isSugared()) \
189        return SplitQualType(Ty, Qs); \
190      Cur = Ty->desugar(); \
191      break; \
192    }
193#include "clang/AST/TypeNodes.def"
194    }
195  }
196}
197
198SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) {
199  SplitQualType split = type.split();
200
201  // All the qualifiers we've seen so far.
202  Qualifiers quals = split.second;
203
204  // The last type node we saw with any nodes inside it.
205  const Type *lastTypeWithQuals = split.first;
206
207  while (true) {
208    QualType next;
209
210    // Do a single-step desugar, aborting the loop if the type isn't
211    // sugared.
212    switch (split.first->getTypeClass()) {
213#define ABSTRACT_TYPE(Class, Parent)
214#define TYPE(Class, Parent) \
215    case Type::Class: { \
216      const Class##Type *ty = cast<Class##Type>(split.first); \
217      if (!ty->isSugared()) goto done; \
218      next = ty->desugar(); \
219      break; \
220    }
221#include "clang/AST/TypeNodes.def"
222    }
223
224    // Otherwise, split the underlying type.  If that yields qualifiers,
225    // update the information.
226    split = next.split();
227    if (!split.second.empty()) {
228      lastTypeWithQuals = split.first;
229      quals.addConsistentQualifiers(split.second);
230    }
231  }
232
233 done:
234  return SplitQualType(lastTypeWithQuals, quals);
235}
236
237QualType QualType::IgnoreParens(QualType T) {
238  // FIXME: this seems inherently un-qualifiers-safe.
239  while (const ParenType *PT = T->getAs<ParenType>())
240    T = PT->getInnerType();
241  return T;
242}
243
244/// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
245/// sugar off the given type.  This should produce an object of the
246/// same dynamic type as the canonical type.
247const Type *Type::getUnqualifiedDesugaredType() const {
248  const Type *Cur = this;
249
250  while (true) {
251    switch (Cur->getTypeClass()) {
252#define ABSTRACT_TYPE(Class, Parent)
253#define TYPE(Class, Parent) \
254    case Class: { \
255      const Class##Type *Ty = cast<Class##Type>(Cur); \
256      if (!Ty->isSugared()) return Cur; \
257      Cur = Ty->desugar().getTypePtr(); \
258      break; \
259    }
260#include "clang/AST/TypeNodes.def"
261    }
262  }
263}
264
265/// isVoidType - Helper method to determine if this is the 'void' type.
266bool Type::isVoidType() const {
267  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
268    return BT->getKind() == BuiltinType::Void;
269  return false;
270}
271
272bool Type::isDerivedType() const {
273  switch (CanonicalType->getTypeClass()) {
274  case Pointer:
275  case VariableArray:
276  case ConstantArray:
277  case IncompleteArray:
278  case FunctionProto:
279  case FunctionNoProto:
280  case LValueReference:
281  case RValueReference:
282  case Record:
283    return true;
284  default:
285    return false;
286  }
287}
288
289bool Type::isClassType() const {
290  if (const RecordType *RT = getAs<RecordType>())
291    return RT->getDecl()->isClass();
292  return false;
293}
294bool Type::isStructureType() const {
295  if (const RecordType *RT = getAs<RecordType>())
296    return RT->getDecl()->isStruct();
297  return false;
298}
299bool Type::isStructureOrClassType() const {
300  if (const RecordType *RT = getAs<RecordType>())
301    return RT->getDecl()->isStruct() || RT->getDecl()->isClass();
302  return false;
303}
304bool Type::isVoidPointerType() const {
305  if (const PointerType *PT = getAs<PointerType>())
306    return PT->getPointeeType()->isVoidType();
307  return false;
308}
309
310bool Type::isUnionType() const {
311  if (const RecordType *RT = getAs<RecordType>())
312    return RT->getDecl()->isUnion();
313  return false;
314}
315
316bool Type::isComplexType() const {
317  if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
318    return CT->getElementType()->isFloatingType();
319  return false;
320}
321
322bool Type::isComplexIntegerType() const {
323  // Check for GCC complex integer extension.
324  return getAsComplexIntegerType();
325}
326
327const ComplexType *Type::getAsComplexIntegerType() const {
328  if (const ComplexType *Complex = getAs<ComplexType>())
329    if (Complex->getElementType()->isIntegerType())
330      return Complex;
331  return 0;
332}
333
334QualType Type::getPointeeType() const {
335  if (const PointerType *PT = getAs<PointerType>())
336    return PT->getPointeeType();
337  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
338    return OPT->getPointeeType();
339  if (const BlockPointerType *BPT = getAs<BlockPointerType>())
340    return BPT->getPointeeType();
341  if (const ReferenceType *RT = getAs<ReferenceType>())
342    return RT->getPointeeType();
343  return QualType();
344}
345
346const RecordType *Type::getAsStructureType() const {
347  // If this is directly a structure type, return it.
348  if (const RecordType *RT = dyn_cast<RecordType>(this)) {
349    if (RT->getDecl()->isStruct())
350      return RT;
351  }
352
353  // If the canonical form of this type isn't the right kind, reject it.
354  if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
355    if (!RT->getDecl()->isStruct())
356      return 0;
357
358    // If this is a typedef for a structure type, strip the typedef off without
359    // losing all typedef information.
360    return cast<RecordType>(getUnqualifiedDesugaredType());
361  }
362  return 0;
363}
364
365const RecordType *Type::getAsUnionType() const {
366  // If this is directly a union type, return it.
367  if (const RecordType *RT = dyn_cast<RecordType>(this)) {
368    if (RT->getDecl()->isUnion())
369      return RT;
370  }
371
372  // If the canonical form of this type isn't the right kind, reject it.
373  if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
374    if (!RT->getDecl()->isUnion())
375      return 0;
376
377    // If this is a typedef for a union type, strip the typedef off without
378    // losing all typedef information.
379    return cast<RecordType>(getUnqualifiedDesugaredType());
380  }
381
382  return 0;
383}
384
385ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base,
386                               ObjCProtocolDecl * const *Protocols,
387                               unsigned NumProtocols)
388  : Type(ObjCObject, Canonical, false, false, false),
389    BaseType(Base)
390{
391  ObjCObjectTypeBits.NumProtocols = NumProtocols;
392  assert(getNumProtocols() == NumProtocols &&
393         "bitfield overflow in protocol count");
394  if (NumProtocols)
395    memcpy(getProtocolStorage(), Protocols,
396           NumProtocols * sizeof(ObjCProtocolDecl*));
397}
398
399const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const {
400  // There is no sugar for ObjCObjectType's, just return the canonical
401  // type pointer if it is the right class.  There is no typedef information to
402  // return and these cannot be Address-space qualified.
403  if (const ObjCObjectType *T = getAs<ObjCObjectType>())
404    if (T->getNumProtocols() && T->getInterface())
405      return T;
406  return 0;
407}
408
409bool Type::isObjCQualifiedInterfaceType() const {
410  return getAsObjCQualifiedInterfaceType() != 0;
411}
412
413const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
414  // There is no sugar for ObjCQualifiedIdType's, just return the canonical
415  // type pointer if it is the right class.
416  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
417    if (OPT->isObjCQualifiedIdType())
418      return OPT;
419  }
420  return 0;
421}
422
423const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const {
424  // There is no sugar for ObjCQualifiedClassType's, just return the canonical
425  // type pointer if it is the right class.
426  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
427    if (OPT->isObjCQualifiedClassType())
428      return OPT;
429  }
430  return 0;
431}
432
433const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
434  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
435    if (OPT->getInterfaceType())
436      return OPT;
437  }
438  return 0;
439}
440
441const CXXRecordDecl *Type::getCXXRecordDeclForPointerType() const {
442  if (const PointerType *PT = getAs<PointerType>())
443    if (const RecordType *RT = PT->getPointeeType()->getAs<RecordType>())
444      return dyn_cast<CXXRecordDecl>(RT->getDecl());
445  return 0;
446}
447
448CXXRecordDecl *Type::getAsCXXRecordDecl() const {
449  if (const RecordType *RT = getAs<RecordType>())
450    return dyn_cast<CXXRecordDecl>(RT->getDecl());
451  else if (const InjectedClassNameType *Injected
452                                  = getAs<InjectedClassNameType>())
453    return Injected->getDecl();
454
455  return 0;
456}
457
458namespace {
459  class GetContainedAutoVisitor :
460    public TypeVisitor<GetContainedAutoVisitor, AutoType*> {
461  public:
462    using TypeVisitor<GetContainedAutoVisitor, AutoType*>::Visit;
463    AutoType *Visit(QualType T) {
464      if (T.isNull())
465        return 0;
466      return Visit(T.getTypePtr());
467    }
468
469    // The 'auto' type itself.
470    AutoType *VisitAutoType(const AutoType *AT) {
471      return const_cast<AutoType*>(AT);
472    }
473
474    // Only these types can contain the desired 'auto' type.
475    AutoType *VisitPointerType(const PointerType *T) {
476      return Visit(T->getPointeeType());
477    }
478    AutoType *VisitBlockPointerType(const BlockPointerType *T) {
479      return Visit(T->getPointeeType());
480    }
481    AutoType *VisitReferenceType(const ReferenceType *T) {
482      return Visit(T->getPointeeTypeAsWritten());
483    }
484    AutoType *VisitMemberPointerType(const MemberPointerType *T) {
485      return Visit(T->getPointeeType());
486    }
487    AutoType *VisitArrayType(const ArrayType *T) {
488      return Visit(T->getElementType());
489    }
490    AutoType *VisitDependentSizedExtVectorType(
491      const DependentSizedExtVectorType *T) {
492      return Visit(T->getElementType());
493    }
494    AutoType *VisitVectorType(const VectorType *T) {
495      return Visit(T->getElementType());
496    }
497    AutoType *VisitFunctionType(const FunctionType *T) {
498      return Visit(T->getResultType());
499    }
500    AutoType *VisitParenType(const ParenType *T) {
501      return Visit(T->getInnerType());
502    }
503    AutoType *VisitAttributedType(const AttributedType *T) {
504      return Visit(T->getModifiedType());
505    }
506  };
507}
508
509AutoType *Type::getContainedAutoType() const {
510  return GetContainedAutoVisitor().Visit(this);
511}
512
513bool Type::isIntegerType() const {
514  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
515    return BT->getKind() >= BuiltinType::Bool &&
516           BT->getKind() <= BuiltinType::Int128;
517  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
518    // Incomplete enum types are not treated as integer types.
519    // FIXME: In C++, enum types are never integer types.
520    return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
521  return false;
522}
523
524bool Type::hasIntegerRepresentation() const {
525  if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
526    return VT->getElementType()->isIntegerType();
527  else
528    return isIntegerType();
529}
530
531/// \brief Determine whether this type is an integral type.
532///
533/// This routine determines whether the given type is an integral type per
534/// C++ [basic.fundamental]p7. Although the C standard does not define the
535/// term "integral type", it has a similar term "integer type", and in C++
536/// the two terms are equivalent. However, C's "integer type" includes
537/// enumeration types, while C++'s "integer type" does not. The \c ASTContext
538/// parameter is used to determine whether we should be following the C or
539/// C++ rules when determining whether this type is an integral/integer type.
540///
541/// For cases where C permits "an integer type" and C++ permits "an integral
542/// type", use this routine.
543///
544/// For cases where C permits "an integer type" and C++ permits "an integral
545/// or enumeration type", use \c isIntegralOrEnumerationType() instead.
546///
547/// \param Ctx The context in which this type occurs.
548///
549/// \returns true if the type is considered an integral type, false otherwise.
550bool Type::isIntegralType(ASTContext &Ctx) const {
551  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
552    return BT->getKind() >= BuiltinType::Bool &&
553    BT->getKind() <= BuiltinType::Int128;
554
555  if (!Ctx.getLangOptions().CPlusPlus)
556    if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
557      return ET->getDecl()->isComplete(); // Complete enum types are integral in C.
558
559  return false;
560}
561
562bool Type::isIntegralOrEnumerationType() const {
563  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
564    return BT->getKind() >= BuiltinType::Bool &&
565           BT->getKind() <= BuiltinType::Int128;
566
567  // Check for a complete enum type; incomplete enum types are not properly an
568  // enumeration type in the sense required here.
569  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
570    return ET->getDecl()->isComplete();
571
572  return false;
573}
574
575bool Type::isIntegralOrUnscopedEnumerationType() const {
576  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
577    return BT->getKind() >= BuiltinType::Bool &&
578           BT->getKind() <= BuiltinType::Int128;
579
580  // Check for a complete enum type; incomplete enum types are not properly an
581  // enumeration type in the sense required here.
582  // C++0x: However, if the underlying type of the enum is fixed, it is
583  // considered complete.
584  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
585    return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
586
587  return false;
588}
589
590
591bool Type::isBooleanType() const {
592  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
593    return BT->getKind() == BuiltinType::Bool;
594  return false;
595}
596
597bool Type::isCharType() const {
598  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
599    return BT->getKind() == BuiltinType::Char_U ||
600           BT->getKind() == BuiltinType::UChar ||
601           BT->getKind() == BuiltinType::Char_S ||
602           BT->getKind() == BuiltinType::SChar;
603  return false;
604}
605
606bool Type::isWideCharType() const {
607  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
608    return BT->getKind() == BuiltinType::WChar_S ||
609           BT->getKind() == BuiltinType::WChar_U;
610  return false;
611}
612
613/// \brief Determine whether this type is any of the built-in character
614/// types.
615bool Type::isAnyCharacterType() const {
616  const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType);
617  if (BT == 0) return false;
618  switch (BT->getKind()) {
619  default: return false;
620  case BuiltinType::Char_U:
621  case BuiltinType::UChar:
622  case BuiltinType::WChar_U:
623  case BuiltinType::Char16:
624  case BuiltinType::Char32:
625  case BuiltinType::Char_S:
626  case BuiltinType::SChar:
627  case BuiltinType::WChar_S:
628    return true;
629  }
630}
631
632/// isSignedIntegerType - Return true if this is an integer type that is
633/// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
634/// an enum decl which has a signed representation
635bool Type::isSignedIntegerType() const {
636  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
637    return BT->getKind() >= BuiltinType::Char_S &&
638           BT->getKind() <= BuiltinType::Int128;
639  }
640
641  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
642    // Incomplete enum types are not treated as integer types.
643    // FIXME: In C++, enum types are never integer types.
644    if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
645      return ET->getDecl()->getIntegerType()->isSignedIntegerType();
646  }
647
648  return false;
649}
650
651bool Type::isSignedIntegerOrEnumerationType() const {
652  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
653    return BT->getKind() >= BuiltinType::Char_S &&
654    BT->getKind() <= BuiltinType::Int128;
655  }
656
657  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
658    if (ET->getDecl()->isComplete())
659      return ET->getDecl()->getIntegerType()->isSignedIntegerType();
660  }
661
662  return false;
663}
664
665bool Type::hasSignedIntegerRepresentation() const {
666  if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
667    return VT->getElementType()->isSignedIntegerType();
668  else
669    return isSignedIntegerType();
670}
671
672/// isUnsignedIntegerType - Return true if this is an integer type that is
673/// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
674/// decl which has an unsigned representation
675bool Type::isUnsignedIntegerType() const {
676  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
677    return BT->getKind() >= BuiltinType::Bool &&
678           BT->getKind() <= BuiltinType::UInt128;
679  }
680
681  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
682    // Incomplete enum types are not treated as integer types.
683    // FIXME: In C++, enum types are never integer types.
684    if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
685      return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
686  }
687
688  return false;
689}
690
691bool Type::isUnsignedIntegerOrEnumerationType() const {
692  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
693    return BT->getKind() >= BuiltinType::Bool &&
694    BT->getKind() <= BuiltinType::UInt128;
695  }
696
697  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
698    if (ET->getDecl()->isComplete())
699      return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
700  }
701
702  return false;
703}
704
705bool Type::hasUnsignedIntegerRepresentation() const {
706  if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
707    return VT->getElementType()->isUnsignedIntegerType();
708  else
709    return isUnsignedIntegerType();
710}
711
712bool Type::isFloatingType() const {
713  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
714    return BT->getKind() >= BuiltinType::Float &&
715           BT->getKind() <= BuiltinType::LongDouble;
716  if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
717    return CT->getElementType()->isFloatingType();
718  return false;
719}
720
721bool Type::hasFloatingRepresentation() const {
722  if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
723    return VT->getElementType()->isFloatingType();
724  else
725    return isFloatingType();
726}
727
728bool Type::isRealFloatingType() const {
729  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
730    return BT->isFloatingPoint();
731  return false;
732}
733
734bool Type::isRealType() const {
735  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
736    return BT->getKind() >= BuiltinType::Bool &&
737           BT->getKind() <= BuiltinType::LongDouble;
738  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
739      return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
740  return false;
741}
742
743bool Type::isArithmeticType() const {
744  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
745    return BT->getKind() >= BuiltinType::Bool &&
746           BT->getKind() <= BuiltinType::LongDouble;
747  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
748    // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
749    // If a body isn't seen by the time we get here, return false.
750    //
751    // C++0x: Enumerations are not arithmetic types. For now, just return
752    // false for scoped enumerations since that will disable any
753    // unwanted implicit conversions.
754    return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete();
755  return isa<ComplexType>(CanonicalType);
756}
757
758bool Type::isScalarType() const {
759  if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
760    return BT->getKind() > BuiltinType::Void &&
761           BT->getKind() <= BuiltinType::NullPtr;
762  if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
763    // Enums are scalar types, but only if they are defined.  Incomplete enums
764    // are not treated as scalar types.
765    return ET->getDecl()->isComplete();
766  return isa<PointerType>(CanonicalType) ||
767         isa<BlockPointerType>(CanonicalType) ||
768         isa<MemberPointerType>(CanonicalType) ||
769         isa<ComplexType>(CanonicalType) ||
770         isa<ObjCObjectPointerType>(CanonicalType);
771}
772
773Type::ScalarTypeKind Type::getScalarTypeKind() const {
774  assert(isScalarType());
775
776  const Type *T = CanonicalType.getTypePtr();
777  if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) {
778    if (BT->getKind() == BuiltinType::Bool) return STK_Bool;
779    if (BT->getKind() == BuiltinType::NullPtr) return STK_Pointer;
780    if (BT->isInteger()) return STK_Integral;
781    if (BT->isFloatingPoint()) return STK_Floating;
782    llvm_unreachable("unknown scalar builtin type");
783  } else if (isa<PointerType>(T) ||
784             isa<BlockPointerType>(T) ||
785             isa<ObjCObjectPointerType>(T)) {
786    return STK_Pointer;
787  } else if (isa<MemberPointerType>(T)) {
788    return STK_MemberPointer;
789  } else if (isa<EnumType>(T)) {
790    assert(cast<EnumType>(T)->getDecl()->isComplete());
791    return STK_Integral;
792  } else if (const ComplexType *CT = dyn_cast<ComplexType>(T)) {
793    if (CT->getElementType()->isRealFloatingType())
794      return STK_FloatingComplex;
795    return STK_IntegralComplex;
796  }
797
798  llvm_unreachable("unknown scalar type");
799  return STK_Pointer;
800}
801
802/// \brief Determines whether the type is a C++ aggregate type or C
803/// aggregate or union type.
804///
805/// An aggregate type is an array or a class type (struct, union, or
806/// class) that has no user-declared constructors, no private or
807/// protected non-static data members, no base classes, and no virtual
808/// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
809/// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
810/// includes union types.
811bool Type::isAggregateType() const {
812  if (const RecordType *Record = dyn_cast<RecordType>(CanonicalType)) {
813    if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
814      return ClassDecl->isAggregate();
815
816    return true;
817  }
818
819  return isa<ArrayType>(CanonicalType);
820}
821
822/// isConstantSizeType - Return true if this is not a variable sized type,
823/// according to the rules of C99 6.7.5p3.  It is not legal to call this on
824/// incomplete types or dependent types.
825bool Type::isConstantSizeType() const {
826  assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
827  assert(!isDependentType() && "This doesn't make sense for dependent types");
828  // The VAT must have a size, as it is known to be complete.
829  return !isa<VariableArrayType>(CanonicalType);
830}
831
832/// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
833/// - a type that can describe objects, but which lacks information needed to
834/// determine its size.
835bool Type::isIncompleteType() const {
836  switch (CanonicalType->getTypeClass()) {
837  default: return false;
838  case Builtin:
839    // Void is the only incomplete builtin type.  Per C99 6.2.5p19, it can never
840    // be completed.
841    return isVoidType();
842  case Enum:
843    // An enumeration with fixed underlying type is complete (C++0x 7.2p3).
844    if (cast<EnumType>(CanonicalType)->getDecl()->isFixed())
845        return false;
846    // Fall through.
847  case Record:
848    // A tagged type (struct/union/enum/class) is incomplete if the decl is a
849    // forward declaration, but not a full definition (C99 6.2.5p22).
850    return !cast<TagType>(CanonicalType)->getDecl()->isDefinition();
851  case ConstantArray:
852    // An array is incomplete if its element type is incomplete
853    // (C++ [dcl.array]p1).
854    // We don't handle variable arrays (they're not allowed in C++) or
855    // dependent-sized arrays (dependent types are never treated as incomplete).
856    return cast<ArrayType>(CanonicalType)->getElementType()->isIncompleteType();
857  case IncompleteArray:
858    // An array of unknown size is an incomplete type (C99 6.2.5p22).
859    return true;
860  case ObjCObject:
861    return cast<ObjCObjectType>(CanonicalType)->getBaseType()
862                                                         ->isIncompleteType();
863  case ObjCInterface:
864    // ObjC interfaces are incomplete if they are @class, not @interface.
865    return cast<ObjCInterfaceType>(CanonicalType)->getDecl()->isForwardDecl();
866  }
867}
868
869/// isPODType - Return true if this is a plain-old-data type (C++ 3.9p10)
870bool Type::isPODType() const {
871  // The compiler shouldn't query this for incomplete types, but the user might.
872  // We return false for that case. Except for incomplete arrays of PODs, which
873  // are PODs according to the standard.
874  if (isIncompleteArrayType() &&
875      cast<ArrayType>(CanonicalType)->getElementType()->isPODType())
876    return true;
877  if (isIncompleteType())
878    return false;
879
880  switch (CanonicalType->getTypeClass()) {
881    // Everything not explicitly mentioned is not POD.
882  default: return false;
883  case VariableArray:
884  case ConstantArray:
885    // IncompleteArray is handled above.
886    return cast<ArrayType>(CanonicalType)->getElementType()->isPODType();
887
888  case Builtin:
889  case Complex:
890  case Pointer:
891  case MemberPointer:
892  case Vector:
893  case ExtVector:
894  case ObjCObjectPointer:
895  case BlockPointer:
896    return true;
897
898  case Enum:
899    return true;
900
901  case Record:
902    if (CXXRecordDecl *ClassDecl
903          = dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
904      return ClassDecl->isPOD();
905
906    // C struct/union is POD.
907    return true;
908  }
909}
910
911bool Type::isLiteralType() const {
912  if (isDependentType())
913    return false;
914
915  // C++0x [basic.types]p10:
916  //   A type is a literal type if it is:
917  //   [...]
918  //   -- an array of literal type
919  // Extension: variable arrays cannot be literal types, since they're
920  // runtime-sized.
921  if (isVariableArrayType())
922    return false;
923  const Type *BaseTy = getBaseElementTypeUnsafe();
924  assert(BaseTy && "NULL element type");
925
926  // Return false for incomplete types after skipping any incomplete array
927  // types; those are expressly allowed by the standard and thus our API.
928  if (BaseTy->isIncompleteType())
929    return false;
930
931  // C++0x [basic.types]p10:
932  //   A type is a literal type if it is:
933  //    -- a scalar type; or
934  // As an extension, Clang treats vector types as Scalar types.
935  if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
936  //    -- a reference type; or
937  if (BaseTy->isReferenceType()) return true;
938  //    -- a class type that has all of the following properties:
939  if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
940    if (const CXXRecordDecl *ClassDecl =
941        dyn_cast<CXXRecordDecl>(RT->getDecl())) {
942      //    -- a trivial destructor,
943      if (!ClassDecl->hasTrivialDestructor()) return false;
944      //    -- every constructor call and full-expression in the
945      //       brace-or-equal-initializers for non-static data members (if any)
946      //       is a constant expression,
947      // FIXME: C++0x: Clang doesn't yet support non-static data member
948      // declarations with initializers, or constexprs.
949      //    -- it is an aggregate type or has at least one constexpr
950      //       constructor or constructor template that is not a copy or move
951      //       constructor, and
952      if (!ClassDecl->isAggregate() &&
953          !ClassDecl->hasConstExprNonCopyMoveConstructor())
954        return false;
955      //    -- all non-static data members and base classes of literal types
956      if (ClassDecl->hasNonLiteralTypeFieldsOrBases()) return false;
957    }
958
959    return true;
960  }
961  return false;
962}
963
964bool Type::isTrivialType() const {
965  if (isDependentType())
966    return false;
967
968  // C++0x [basic.types]p9:
969  //   Scalar types, trivial class types, arrays of such types, and
970  //   cv-qualified versions of these types are collectively called trivial
971  //   types.
972  const Type *BaseTy = getBaseElementTypeUnsafe();
973  assert(BaseTy && "NULL element type");
974
975  // Return false for incomplete types after skipping any incomplete array
976  // types which are expressly allowed by the standard and thus our API.
977  if (BaseTy->isIncompleteType())
978    return false;
979
980  // As an extension, Clang treats vector types as Scalar types.
981  if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
982  if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
983    if (const CXXRecordDecl *ClassDecl =
984        dyn_cast<CXXRecordDecl>(RT->getDecl())) {
985      if (!ClassDecl->isTrivial()) return false;
986    }
987
988    return true;
989  }
990
991  // No other types can match.
992  return false;
993}
994
995bool Type::isTriviallyCopyableType() const {
996  if (isDependentType())
997    return false;
998
999  // C++0x [basic.types]p9
1000  //   Scalar types, trivially copyable class types, arrays of such types, and
1001  //   cv-qualified versions of these types are collectively called trivial
1002  //   types.
1003  const Type *BaseTy = getBaseElementTypeUnsafe();
1004  assert(BaseTy && "NULL element type");
1005
1006  // Return false for incomplete types after skipping any incomplete array types
1007  // which are expressly allowed by the standard and thus our API.
1008  if (BaseTy->isIncompleteType())
1009    return false;
1010
1011  // As an extension, Clang treats vector types as Scalar types.
1012  if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
1013  if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1014    if (const CXXRecordDecl *ClassDecl =
1015        dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1016      if (!ClassDecl->isTriviallyCopyable()) return false;
1017    }
1018
1019    return true;
1020  }
1021
1022  // No other types can match.
1023  return false;
1024}
1025
1026bool Type::isStandardLayoutType() const {
1027  if (isDependentType())
1028    return false;
1029
1030  // C++0x [basic.types]p9:
1031  //   Scalar types, standard-layout class types, arrays of such types, and
1032  //   cv-qualified versions of these types are collectively called
1033  //   standard-layout types.
1034  const Type *BaseTy = getBaseElementTypeUnsafe();
1035  assert(BaseTy && "NULL element type");
1036
1037  // Return false for incomplete types after skipping any incomplete array
1038  // types which are expressly allowed by the standard and thus our API.
1039  if (BaseTy->isIncompleteType())
1040    return false;
1041
1042  // As an extension, Clang treats vector types as Scalar types.
1043  if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
1044  if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1045    if (const CXXRecordDecl *ClassDecl =
1046        dyn_cast<CXXRecordDecl>(RT->getDecl()))
1047      if (!ClassDecl->isStandardLayout())
1048        return false;
1049
1050    // Default to 'true' for non-C++ class types.
1051    // FIXME: This is a bit dubious, but plain C structs should trivially meet
1052    // all the requirements of standard layout classes.
1053    return true;
1054  }
1055
1056  // No other types can match.
1057  return false;
1058}
1059
1060// This is effectively the intersection of isTrivialType and
1061// isStandardLayoutType. We implement it dircetly to avoid redundant
1062// conversions from a type to a CXXRecordDecl.
1063bool Type::isCXX11PODType() const {
1064  if (isDependentType())
1065    return false;
1066
1067  // C++11 [basic.types]p9:
1068  //   Scalar types, POD classes, arrays of such types, and cv-qualified
1069  //   versions of these types are collectively called trivial types.
1070  const Type *BaseTy = getBaseElementTypeUnsafe();
1071  assert(BaseTy && "NULL element type");
1072
1073  // Return false for incomplete types after skipping any incomplete array
1074  // types which are expressly allowed by the standard and thus our API.
1075  if (BaseTy->isIncompleteType())
1076    return false;
1077
1078  // As an extension, Clang treats vector types as Scalar types.
1079  if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
1080  if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
1081    if (const CXXRecordDecl *ClassDecl =
1082        dyn_cast<CXXRecordDecl>(RT->getDecl())) {
1083      // C++11 [class]p10:
1084      //   A POD struct is a non-union class that is both a trivial class [...]
1085      if (!ClassDecl->isTrivial()) return false;
1086
1087      // C++11 [class]p10:
1088      //   A POD struct is a non-union class that is both a trivial class and
1089      //   a standard-layout class [...]
1090      if (!ClassDecl->isStandardLayout()) return false;
1091
1092      // C++11 [class]p10:
1093      //   A POD struct is a non-union class that is both a trivial class and
1094      //   a standard-layout class, and has no non-static data members of type
1095      //   non-POD struct, non-POD union (or array of such types). [...]
1096      //
1097      // We don't directly query the recursive aspect as the requiremets for
1098      // both standard-layout classes and trivial classes apply recursively
1099      // already.
1100    }
1101
1102    return true;
1103  }
1104
1105  // No other types can match.
1106  return false;
1107}
1108
1109bool Type::isPromotableIntegerType() const {
1110  if (const BuiltinType *BT = getAs<BuiltinType>())
1111    switch (BT->getKind()) {
1112    case BuiltinType::Bool:
1113    case BuiltinType::Char_S:
1114    case BuiltinType::Char_U:
1115    case BuiltinType::SChar:
1116    case BuiltinType::UChar:
1117    case BuiltinType::Short:
1118    case BuiltinType::UShort:
1119      return true;
1120    default:
1121      return false;
1122    }
1123
1124  // Enumerated types are promotable to their compatible integer types
1125  // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
1126  if (const EnumType *ET = getAs<EnumType>()){
1127    if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull()
1128        || ET->getDecl()->isScoped())
1129      return false;
1130
1131    const BuiltinType *BT
1132      = ET->getDecl()->getPromotionType()->getAs<BuiltinType>();
1133    return BT->getKind() == BuiltinType::Int
1134           || BT->getKind() == BuiltinType::UInt;
1135  }
1136
1137  return false;
1138}
1139
1140bool Type::isNullPtrType() const {
1141  if (const BuiltinType *BT = getAs<BuiltinType>())
1142    return BT->getKind() == BuiltinType::NullPtr;
1143  return false;
1144}
1145
1146bool Type::isSpecifierType() const {
1147  // Note that this intentionally does not use the canonical type.
1148  switch (getTypeClass()) {
1149  case Builtin:
1150  case Record:
1151  case Enum:
1152  case Typedef:
1153  case Complex:
1154  case TypeOfExpr:
1155  case TypeOf:
1156  case TemplateTypeParm:
1157  case SubstTemplateTypeParm:
1158  case TemplateSpecialization:
1159  case Elaborated:
1160  case DependentName:
1161  case DependentTemplateSpecialization:
1162  case ObjCInterface:
1163  case ObjCObject:
1164  case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers
1165    return true;
1166  default:
1167    return false;
1168  }
1169}
1170
1171ElaboratedTypeKeyword
1172TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) {
1173  switch (TypeSpec) {
1174  default: return ETK_None;
1175  case TST_typename: return ETK_Typename;
1176  case TST_class: return ETK_Class;
1177  case TST_struct: return ETK_Struct;
1178  case TST_union: return ETK_Union;
1179  case TST_enum: return ETK_Enum;
1180  }
1181}
1182
1183TagTypeKind
1184TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
1185  switch(TypeSpec) {
1186  case TST_class: return TTK_Class;
1187  case TST_struct: return TTK_Struct;
1188  case TST_union: return TTK_Union;
1189  case TST_enum: return TTK_Enum;
1190  }
1191
1192  llvm_unreachable("Type specifier is not a tag type kind.");
1193  return TTK_Union;
1194}
1195
1196ElaboratedTypeKeyword
1197TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) {
1198  switch (Kind) {
1199  case TTK_Class: return ETK_Class;
1200  case TTK_Struct: return ETK_Struct;
1201  case TTK_Union: return ETK_Union;
1202  case TTK_Enum: return ETK_Enum;
1203  }
1204  llvm_unreachable("Unknown tag type kind.");
1205}
1206
1207TagTypeKind
1208TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
1209  switch (Keyword) {
1210  case ETK_Class: return TTK_Class;
1211  case ETK_Struct: return TTK_Struct;
1212  case ETK_Union: return TTK_Union;
1213  case ETK_Enum: return TTK_Enum;
1214  case ETK_None: // Fall through.
1215  case ETK_Typename:
1216    llvm_unreachable("Elaborated type keyword is not a tag type kind.");
1217  }
1218  llvm_unreachable("Unknown elaborated type keyword.");
1219}
1220
1221bool
1222TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
1223  switch (Keyword) {
1224  case ETK_None:
1225  case ETK_Typename:
1226    return false;
1227  case ETK_Class:
1228  case ETK_Struct:
1229  case ETK_Union:
1230  case ETK_Enum:
1231    return true;
1232  }
1233  llvm_unreachable("Unknown elaborated type keyword.");
1234}
1235
1236const char*
1237TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) {
1238  switch (Keyword) {
1239  case ETK_None: return "";
1240  case ETK_Typename: return "typename";
1241  case ETK_Class:  return "class";
1242  case ETK_Struct: return "struct";
1243  case ETK_Union:  return "union";
1244  case ETK_Enum:   return "enum";
1245  }
1246
1247  llvm_unreachable("Unknown elaborated type keyword.");
1248  return "";
1249}
1250
1251DependentTemplateSpecializationType::DependentTemplateSpecializationType(
1252                         ElaboratedTypeKeyword Keyword,
1253                         NestedNameSpecifier *NNS, const IdentifierInfo *Name,
1254                         unsigned NumArgs, const TemplateArgument *Args,
1255                         QualType Canon)
1256  : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true,
1257                    /*VariablyModified=*/false,
1258                    NNS && NNS->containsUnexpandedParameterPack()),
1259    NNS(NNS), Name(Name), NumArgs(NumArgs) {
1260  assert((!NNS || NNS->isDependent()) &&
1261         "DependentTemplateSpecializatonType requires dependent qualifier");
1262  for (unsigned I = 0; I != NumArgs; ++I) {
1263    if (Args[I].containsUnexpandedParameterPack())
1264      setContainsUnexpandedParameterPack();
1265
1266    new (&getArgBuffer()[I]) TemplateArgument(Args[I]);
1267  }
1268}
1269
1270void
1271DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1272                                             const ASTContext &Context,
1273                                             ElaboratedTypeKeyword Keyword,
1274                                             NestedNameSpecifier *Qualifier,
1275                                             const IdentifierInfo *Name,
1276                                             unsigned NumArgs,
1277                                             const TemplateArgument *Args) {
1278  ID.AddInteger(Keyword);
1279  ID.AddPointer(Qualifier);
1280  ID.AddPointer(Name);
1281  for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1282    Args[Idx].Profile(ID, Context);
1283}
1284
1285bool Type::isElaboratedTypeSpecifier() const {
1286  ElaboratedTypeKeyword Keyword;
1287  if (const ElaboratedType *Elab = dyn_cast<ElaboratedType>(this))
1288    Keyword = Elab->getKeyword();
1289  else if (const DependentNameType *DepName = dyn_cast<DependentNameType>(this))
1290    Keyword = DepName->getKeyword();
1291  else if (const DependentTemplateSpecializationType *DepTST =
1292             dyn_cast<DependentTemplateSpecializationType>(this))
1293    Keyword = DepTST->getKeyword();
1294  else
1295    return false;
1296
1297  return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
1298}
1299
1300const char *Type::getTypeClassName() const {
1301  switch (TypeBits.TC) {
1302#define ABSTRACT_TYPE(Derived, Base)
1303#define TYPE(Derived, Base) case Derived: return #Derived;
1304#include "clang/AST/TypeNodes.def"
1305  }
1306
1307  llvm_unreachable("Invalid type class.");
1308  return 0;
1309}
1310
1311const char *BuiltinType::getName(const LangOptions &LO) const {
1312  switch (getKind()) {
1313  case Void:              return "void";
1314  case Bool:              return LO.Bool ? "bool" : "_Bool";
1315  case Char_S:            return "char";
1316  case Char_U:            return "char";
1317  case SChar:             return "signed char";
1318  case Short:             return "short";
1319  case Int:               return "int";
1320  case Long:              return "long";
1321  case LongLong:          return "long long";
1322  case Int128:            return "__int128_t";
1323  case UChar:             return "unsigned char";
1324  case UShort:            return "unsigned short";
1325  case UInt:              return "unsigned int";
1326  case ULong:             return "unsigned long";
1327  case ULongLong:         return "unsigned long long";
1328  case UInt128:           return "__uint128_t";
1329  case Float:             return "float";
1330  case Double:            return "double";
1331  case LongDouble:        return "long double";
1332  case WChar_S:
1333  case WChar_U:           return "wchar_t";
1334  case Char16:            return "char16_t";
1335  case Char32:            return "char32_t";
1336  case NullPtr:           return "nullptr_t";
1337  case Overload:          return "<overloaded function type>";
1338  case BoundMember:       return "<bound member function type>";
1339  case Dependent:         return "<dependent type>";
1340  case UnknownAny:        return "<unknown type>";
1341  case ObjCId:            return "id";
1342  case ObjCClass:         return "Class";
1343  case ObjCSel:           return "SEL";
1344  }
1345
1346  llvm_unreachable("Invalid builtin type.");
1347  return 0;
1348}
1349
1350QualType QualType::getNonLValueExprType(ASTContext &Context) const {
1351  if (const ReferenceType *RefType = getTypePtr()->getAs<ReferenceType>())
1352    return RefType->getPointeeType();
1353
1354  // C++0x [basic.lval]:
1355  //   Class prvalues can have cv-qualified types; non-class prvalues always
1356  //   have cv-unqualified types.
1357  //
1358  // See also C99 6.3.2.1p2.
1359  if (!Context.getLangOptions().CPlusPlus ||
1360      (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
1361    return getUnqualifiedType();
1362
1363  return *this;
1364}
1365
1366llvm::StringRef FunctionType::getNameForCallConv(CallingConv CC) {
1367  switch (CC) {
1368  case CC_Default:
1369    llvm_unreachable("no name for default cc");
1370    return "";
1371
1372  case CC_C: return "cdecl";
1373  case CC_X86StdCall: return "stdcall";
1374  case CC_X86FastCall: return "fastcall";
1375  case CC_X86ThisCall: return "thiscall";
1376  case CC_X86Pascal: return "pascal";
1377  case CC_AAPCS: return "aapcs";
1378  case CC_AAPCS_VFP: return "aapcs-vfp";
1379  }
1380
1381  llvm_unreachable("Invalid calling convention.");
1382  return "";
1383}
1384
1385FunctionProtoType::FunctionProtoType(QualType result, const QualType *args,
1386                                     unsigned numArgs, QualType canonical,
1387                                     const ExtProtoInfo &epi)
1388  : FunctionType(FunctionProto, result, epi.Variadic, epi.TypeQuals,
1389                 epi.RefQualifier, canonical,
1390                 result->isDependentType(),
1391                 result->isVariablyModifiedType(),
1392                 result->containsUnexpandedParameterPack(),
1393                 epi.ExtInfo),
1394    NumArgs(numArgs), NumExceptions(epi.NumExceptions),
1395    ExceptionSpecType(epi.ExceptionSpecType)
1396{
1397  // Fill in the trailing argument array.
1398  QualType *argSlot = reinterpret_cast<QualType*>(this+1);
1399  for (unsigned i = 0; i != numArgs; ++i) {
1400    if (args[i]->isDependentType())
1401      setDependent();
1402
1403    if (args[i]->containsUnexpandedParameterPack())
1404      setContainsUnexpandedParameterPack();
1405
1406    argSlot[i] = args[i];
1407  }
1408
1409  if (getExceptionSpecType() == EST_Dynamic) {
1410    // Fill in the exception array.
1411    QualType *exnSlot = argSlot + numArgs;
1412    for (unsigned i = 0, e = epi.NumExceptions; i != e; ++i) {
1413      if (epi.Exceptions[i]->isDependentType())
1414        setDependent();
1415
1416      if (epi.Exceptions[i]->containsUnexpandedParameterPack())
1417        setContainsUnexpandedParameterPack();
1418
1419      exnSlot[i] = epi.Exceptions[i];
1420    }
1421  } else if (getExceptionSpecType() == EST_ComputedNoexcept) {
1422    // Store the noexcept expression and context.
1423    Expr **noexSlot = reinterpret_cast<Expr**>(argSlot + numArgs);
1424    *noexSlot = epi.NoexceptExpr;
1425  }
1426}
1427
1428FunctionProtoType::NoexceptResult
1429FunctionProtoType::getNoexceptSpec(ASTContext &ctx) const {
1430  ExceptionSpecificationType est = getExceptionSpecType();
1431  if (est == EST_BasicNoexcept)
1432    return NR_Nothrow;
1433
1434  if (est != EST_ComputedNoexcept)
1435    return NR_NoNoexcept;
1436
1437  Expr *noexceptExpr = getNoexceptExpr();
1438  if (!noexceptExpr)
1439    return NR_BadNoexcept;
1440  if (noexceptExpr->isValueDependent())
1441    return NR_Dependent;
1442
1443  llvm::APSInt value;
1444  bool isICE = noexceptExpr->isIntegerConstantExpr(value, ctx, 0,
1445                                                   /*evaluated*/false);
1446  (void)isICE;
1447  assert(isICE && "AST should not contain bad noexcept expressions.");
1448
1449  return value.getBoolValue() ? NR_Nothrow : NR_Throw;
1450}
1451
1452bool FunctionProtoType::isTemplateVariadic() const {
1453  for (unsigned ArgIdx = getNumArgs(); ArgIdx; --ArgIdx)
1454    if (isa<PackExpansionType>(getArgType(ArgIdx - 1)))
1455      return true;
1456
1457  return false;
1458}
1459
1460void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
1461                                const QualType *ArgTys, unsigned NumArgs,
1462                                const ExtProtoInfo &epi,
1463                                const ASTContext &Context) {
1464  ID.AddPointer(Result.getAsOpaquePtr());
1465  for (unsigned i = 0; i != NumArgs; ++i)
1466    ID.AddPointer(ArgTys[i].getAsOpaquePtr());
1467  ID.AddBoolean(epi.Variadic);
1468  ID.AddInteger(epi.TypeQuals);
1469  ID.AddInteger(epi.RefQualifier);
1470  ID.AddInteger(epi.ExceptionSpecType);
1471  if (epi.ExceptionSpecType == EST_Dynamic) {
1472    for (unsigned i = 0; i != epi.NumExceptions; ++i)
1473      ID.AddPointer(epi.Exceptions[i].getAsOpaquePtr());
1474  } else if (epi.ExceptionSpecType == EST_ComputedNoexcept && epi.NoexceptExpr){
1475    epi.NoexceptExpr->Profile(ID, Context, true);
1476  }
1477  epi.ExtInfo.Profile(ID);
1478}
1479
1480void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
1481                                const ASTContext &Ctx) {
1482  Profile(ID, getResultType(), arg_type_begin(), NumArgs, getExtProtoInfo(),
1483          Ctx);
1484}
1485
1486QualType TypedefType::desugar() const {
1487  return getDecl()->getUnderlyingType();
1488}
1489
1490TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
1491  : Type(TypeOfExpr, can, E->isTypeDependent(),
1492         E->getType()->isVariablyModifiedType(),
1493         E->containsUnexpandedParameterPack()),
1494    TOExpr(E) {
1495}
1496
1497QualType TypeOfExprType::desugar() const {
1498  return getUnderlyingExpr()->getType();
1499}
1500
1501void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
1502                                      const ASTContext &Context, Expr *E) {
1503  E->Profile(ID, Context, true);
1504}
1505
1506DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
1507  : Type(Decltype, can, E->isTypeDependent(),
1508         E->getType()->isVariablyModifiedType(),
1509         E->containsUnexpandedParameterPack()),
1510    E(E),
1511  UnderlyingType(underlyingType) {
1512}
1513
1514DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E)
1515  : DecltypeType(E, Context.DependentTy), Context(Context) { }
1516
1517void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
1518                                    const ASTContext &Context, Expr *E) {
1519  E->Profile(ID, Context, true);
1520}
1521
1522TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
1523  : Type(TC, can, D->isDependentType(), /*VariablyModified=*/false,
1524         /*ContainsUnexpandedParameterPack=*/false),
1525    decl(const_cast<TagDecl*>(D)) {}
1526
1527static TagDecl *getInterestingTagDecl(TagDecl *decl) {
1528  for (TagDecl::redecl_iterator I = decl->redecls_begin(),
1529                                E = decl->redecls_end();
1530       I != E; ++I) {
1531    if (I->isDefinition() || I->isBeingDefined())
1532      return *I;
1533  }
1534  // If there's no definition (not even in progress), return what we have.
1535  return decl;
1536}
1537
1538UnaryTransformType::UnaryTransformType(QualType BaseType,
1539                                       QualType UnderlyingType,
1540                                       UTTKind UKind,
1541                                       QualType CanonicalType)
1542  : Type(UnaryTransform, CanonicalType, UnderlyingType->isDependentType(),
1543         UnderlyingType->isVariablyModifiedType(),
1544         BaseType->containsUnexpandedParameterPack())
1545  , BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind)
1546{}
1547
1548TagDecl *TagType::getDecl() const {
1549  return getInterestingTagDecl(decl);
1550}
1551
1552bool TagType::isBeingDefined() const {
1553  return getDecl()->isBeingDefined();
1554}
1555
1556CXXRecordDecl *InjectedClassNameType::getDecl() const {
1557  return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
1558}
1559
1560bool RecordType::classof(const TagType *TT) {
1561  return isa<RecordDecl>(TT->getDecl());
1562}
1563
1564bool EnumType::classof(const TagType *TT) {
1565  return isa<EnumDecl>(TT->getDecl());
1566}
1567
1568IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
1569  return isCanonicalUnqualified() ? 0 : getDecl()->getIdentifier();
1570}
1571
1572SubstTemplateTypeParmPackType::
1573SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
1574                              QualType Canon,
1575                              const TemplateArgument &ArgPack)
1576  : Type(SubstTemplateTypeParmPack, Canon, true, false, true), Replaced(Param),
1577    Arguments(ArgPack.pack_begin()), NumArguments(ArgPack.pack_size())
1578{
1579}
1580
1581TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const {
1582  return TemplateArgument(Arguments, NumArguments);
1583}
1584
1585void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
1586  Profile(ID, getReplacedParameter(), getArgumentPack());
1587}
1588
1589void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
1590                                           const TemplateTypeParmType *Replaced,
1591                                            const TemplateArgument &ArgPack) {
1592  ID.AddPointer(Replaced);
1593  ID.AddInteger(ArgPack.pack_size());
1594  for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
1595                                    PEnd = ArgPack.pack_end();
1596       P != PEnd; ++P)
1597    ID.AddPointer(P->getAsType().getAsOpaquePtr());
1598}
1599
1600bool TemplateSpecializationType::
1601anyDependentTemplateArguments(const TemplateArgumentListInfo &Args) {
1602  return anyDependentTemplateArguments(Args.getArgumentArray(), Args.size());
1603}
1604
1605bool TemplateSpecializationType::
1606anyDependentTemplateArguments(const TemplateArgumentLoc *Args, unsigned N) {
1607  for (unsigned i = 0; i != N; ++i)
1608    if (Args[i].getArgument().isDependent())
1609      return true;
1610  return false;
1611}
1612
1613bool TemplateSpecializationType::
1614anyDependentTemplateArguments(const TemplateArgument *Args, unsigned N) {
1615  for (unsigned i = 0; i != N; ++i)
1616    if (Args[i].isDependent())
1617      return true;
1618  return false;
1619}
1620
1621TemplateSpecializationType::
1622TemplateSpecializationType(TemplateName T,
1623                           const TemplateArgument *Args, unsigned NumArgs,
1624                           QualType Canon, QualType AliasedType)
1625  : Type(TemplateSpecialization,
1626         Canon.isNull()? QualType(this, 0) : Canon,
1627         Canon.isNull()? T.isDependent() : Canon->isDependentType(),
1628         false, T.containsUnexpandedParameterPack()),
1629    Template(T), NumArgs(NumArgs) {
1630  assert(!T.getAsDependentTemplateName() &&
1631         "Use DependentTemplateSpecializationType for dependent template-name");
1632  assert((!Canon.isNull() ||
1633          T.isDependent() || anyDependentTemplateArguments(Args, NumArgs)) &&
1634         "No canonical type for non-dependent class template specialization");
1635
1636  TemplateArgument *TemplateArgs
1637    = reinterpret_cast<TemplateArgument *>(this + 1);
1638  for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
1639    // Update dependent and variably-modified bits.
1640    // If the canonical type exists and is non-dependent, the template
1641    // specialization type can be non-dependent even if one of the type
1642    // arguments is. Given:
1643    //   template<typename T> using U = int;
1644    // U<T> is always non-dependent, irrespective of the type T.
1645    if (Canon.isNull() && Args[Arg].isDependent())
1646      setDependent();
1647    if (Args[Arg].getKind() == TemplateArgument::Type &&
1648        Args[Arg].getAsType()->isVariablyModifiedType())
1649      setVariablyModified();
1650    if (Args[Arg].containsUnexpandedParameterPack())
1651      setContainsUnexpandedParameterPack();
1652
1653    new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]);
1654  }
1655
1656  // Store the aliased type if this is a type alias template specialization.
1657  bool IsTypeAlias = !AliasedType.isNull();
1658  assert(IsTypeAlias == isTypeAlias() &&
1659         "allocated wrong size for type alias");
1660  if (IsTypeAlias) {
1661    TemplateArgument *Begin = reinterpret_cast<TemplateArgument *>(this + 1);
1662    *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType;
1663  }
1664}
1665
1666void
1667TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
1668                                    TemplateName T,
1669                                    const TemplateArgument *Args,
1670                                    unsigned NumArgs,
1671                                    const ASTContext &Context) {
1672  T.Profile(ID);
1673  for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
1674    Args[Idx].Profile(ID, Context);
1675}
1676
1677bool TemplateSpecializationType::isTypeAlias() const {
1678  TemplateDecl *D = Template.getAsTemplateDecl();
1679  return D && isa<TypeAliasTemplateDecl>(D);
1680}
1681
1682QualType
1683QualifierCollector::apply(const ASTContext &Context, QualType QT) const {
1684  if (!hasNonFastQualifiers())
1685    return QT.withFastQualifiers(getFastQualifiers());
1686
1687  return Context.getQualifiedType(QT, *this);
1688}
1689
1690QualType
1691QualifierCollector::apply(const ASTContext &Context, const Type *T) const {
1692  if (!hasNonFastQualifiers())
1693    return QualType(T, getFastQualifiers());
1694
1695  return Context.getQualifiedType(T, *this);
1696}
1697
1698void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
1699                                 QualType BaseType,
1700                                 ObjCProtocolDecl * const *Protocols,
1701                                 unsigned NumProtocols) {
1702  ID.AddPointer(BaseType.getAsOpaquePtr());
1703  for (unsigned i = 0; i != NumProtocols; i++)
1704    ID.AddPointer(Protocols[i]);
1705}
1706
1707void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
1708  Profile(ID, getBaseType(), qual_begin(), getNumProtocols());
1709}
1710
1711namespace {
1712
1713/// \brief The cached properties of a type.
1714class CachedProperties {
1715  char linkage;
1716  char visibility;
1717  bool local;
1718
1719public:
1720  CachedProperties(Linkage linkage, Visibility visibility, bool local)
1721    : linkage(linkage), visibility(visibility), local(local) {}
1722
1723  Linkage getLinkage() const { return (Linkage) linkage; }
1724  Visibility getVisibility() const { return (Visibility) visibility; }
1725  bool hasLocalOrUnnamedType() const { return local; }
1726
1727  friend CachedProperties merge(CachedProperties L, CachedProperties R) {
1728    return CachedProperties(minLinkage(L.getLinkage(), R.getLinkage()),
1729                            minVisibility(L.getVisibility(), R.getVisibility()),
1730                         L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType());
1731  }
1732};
1733}
1734
1735static CachedProperties computeCachedProperties(const Type *T);
1736
1737namespace clang {
1738/// The type-property cache.  This is templated so as to be
1739/// instantiated at an internal type to prevent unnecessary symbol
1740/// leakage.
1741template <class Private> class TypePropertyCache {
1742public:
1743  static CachedProperties get(QualType T) {
1744    return get(T.getTypePtr());
1745  }
1746
1747  static CachedProperties get(const Type *T) {
1748    ensure(T);
1749    return CachedProperties(T->TypeBits.getLinkage(),
1750                            T->TypeBits.getVisibility(),
1751                            T->TypeBits.hasLocalOrUnnamedType());
1752  }
1753
1754  static void ensure(const Type *T) {
1755    // If the cache is valid, we're okay.
1756    if (T->TypeBits.isCacheValid()) return;
1757
1758    // If this type is non-canonical, ask its canonical type for the
1759    // relevant information.
1760    if (!T->isCanonicalUnqualified()) {
1761      const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
1762      ensure(CT);
1763      T->TypeBits.CacheValidAndVisibility =
1764        CT->TypeBits.CacheValidAndVisibility;
1765      T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
1766      T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
1767      return;
1768    }
1769
1770    // Compute the cached properties and then set the cache.
1771    CachedProperties Result = computeCachedProperties(T);
1772    T->TypeBits.CacheValidAndVisibility = Result.getVisibility() + 1U;
1773    assert(T->TypeBits.isCacheValid() &&
1774           T->TypeBits.getVisibility() == Result.getVisibility());
1775    T->TypeBits.CachedLinkage = Result.getLinkage();
1776    T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
1777  }
1778};
1779}
1780
1781// Instantiate the friend template at a private class.  In a
1782// reasonable implementation, these symbols will be internal.
1783// It is terrible that this is the best way to accomplish this.
1784namespace { class Private {}; }
1785typedef TypePropertyCache<Private> Cache;
1786
1787static CachedProperties computeCachedProperties(const Type *T) {
1788  switch (T->getTypeClass()) {
1789#define TYPE(Class,Base)
1790#define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
1791#include "clang/AST/TypeNodes.def"
1792    llvm_unreachable("didn't expect a non-canonical type here");
1793
1794#define TYPE(Class,Base)
1795#define DEPENDENT_TYPE(Class,Base) case Type::Class:
1796#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
1797#include "clang/AST/TypeNodes.def"
1798    // Treat dependent types as external.
1799    assert(T->isDependentType());
1800    return CachedProperties(ExternalLinkage, DefaultVisibility, false);
1801
1802  case Type::Builtin:
1803    // C++ [basic.link]p8:
1804    //   A type is said to have linkage if and only if:
1805    //     - it is a fundamental type (3.9.1); or
1806    return CachedProperties(ExternalLinkage, DefaultVisibility, false);
1807
1808  case Type::Record:
1809  case Type::Enum: {
1810    const TagDecl *Tag = cast<TagType>(T)->getDecl();
1811
1812    // C++ [basic.link]p8:
1813    //     - it is a class or enumeration type that is named (or has a name
1814    //       for linkage purposes (7.1.3)) and the name has linkage; or
1815    //     -  it is a specialization of a class template (14); or
1816    NamedDecl::LinkageInfo LV = Tag->getLinkageAndVisibility();
1817    bool IsLocalOrUnnamed =
1818      Tag->getDeclContext()->isFunctionOrMethod() ||
1819      (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl());
1820    return CachedProperties(LV.linkage(), LV.visibility(), IsLocalOrUnnamed);
1821  }
1822
1823    // C++ [basic.link]p8:
1824    //   - it is a compound type (3.9.2) other than a class or enumeration,
1825    //     compounded exclusively from types that have linkage; or
1826  case Type::Complex:
1827    return Cache::get(cast<ComplexType>(T)->getElementType());
1828  case Type::Pointer:
1829    return Cache::get(cast<PointerType>(T)->getPointeeType());
1830  case Type::BlockPointer:
1831    return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
1832  case Type::LValueReference:
1833  case Type::RValueReference:
1834    return Cache::get(cast<ReferenceType>(T)->getPointeeType());
1835  case Type::MemberPointer: {
1836    const MemberPointerType *MPT = cast<MemberPointerType>(T);
1837    return merge(Cache::get(MPT->getClass()),
1838                 Cache::get(MPT->getPointeeType()));
1839  }
1840  case Type::ConstantArray:
1841  case Type::IncompleteArray:
1842  case Type::VariableArray:
1843    return Cache::get(cast<ArrayType>(T)->getElementType());
1844  case Type::Vector:
1845  case Type::ExtVector:
1846    return Cache::get(cast<VectorType>(T)->getElementType());
1847  case Type::FunctionNoProto:
1848    return Cache::get(cast<FunctionType>(T)->getResultType());
1849  case Type::FunctionProto: {
1850    const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1851    CachedProperties result = Cache::get(FPT->getResultType());
1852    for (FunctionProtoType::arg_type_iterator ai = FPT->arg_type_begin(),
1853           ae = FPT->arg_type_end(); ai != ae; ++ai)
1854      result = merge(result, Cache::get(*ai));
1855    return result;
1856  }
1857  case Type::ObjCInterface: {
1858    NamedDecl::LinkageInfo LV =
1859      cast<ObjCInterfaceType>(T)->getDecl()->getLinkageAndVisibility();
1860    return CachedProperties(LV.linkage(), LV.visibility(), false);
1861  }
1862  case Type::ObjCObject:
1863    return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
1864  case Type::ObjCObjectPointer:
1865    return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
1866  }
1867
1868  llvm_unreachable("unhandled type class");
1869
1870  // C++ [basic.link]p8:
1871  //   Names not covered by these rules have no linkage.
1872  return CachedProperties(NoLinkage, DefaultVisibility, false);
1873}
1874
1875/// \brief Determine the linkage of this type.
1876Linkage Type::getLinkage() const {
1877  Cache::ensure(this);
1878  return TypeBits.getLinkage();
1879}
1880
1881/// \brief Determine the linkage of this type.
1882Visibility Type::getVisibility() const {
1883  Cache::ensure(this);
1884  return TypeBits.getVisibility();
1885}
1886
1887bool Type::hasUnnamedOrLocalType() const {
1888  Cache::ensure(this);
1889  return TypeBits.hasLocalOrUnnamedType();
1890}
1891
1892std::pair<Linkage,Visibility> Type::getLinkageAndVisibility() const {
1893  Cache::ensure(this);
1894  return std::make_pair(TypeBits.getLinkage(), TypeBits.getVisibility());
1895}
1896
1897void Type::ClearLinkageCache() {
1898  TypeBits.CacheValidAndVisibility = 0;
1899  if (QualType(this, 0) != CanonicalType)
1900    CanonicalType->TypeBits.CacheValidAndVisibility = 0;
1901}
1902
1903bool Type::hasSizedVLAType() const {
1904  if (!isVariablyModifiedType()) return false;
1905
1906  if (const PointerType *ptr = getAs<PointerType>())
1907    return ptr->getPointeeType()->hasSizedVLAType();
1908  if (const ReferenceType *ref = getAs<ReferenceType>())
1909    return ref->getPointeeType()->hasSizedVLAType();
1910  if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
1911    if (isa<VariableArrayType>(arr) &&
1912        cast<VariableArrayType>(arr)->getSizeExpr())
1913      return true;
1914
1915    return arr->getElementType()->hasSizedVLAType();
1916  }
1917
1918  return false;
1919}
1920
1921QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
1922  /// Currently, the only destruction kind we recognize is C++ objects
1923  /// with non-trivial destructors.
1924  const CXXRecordDecl *record =
1925    type->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1926  if (record && !record->hasTrivialDestructor())
1927    return DK_cxx_destructor;
1928
1929  return DK_none;
1930}
1931