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