Type.h revision 8e02635c9c276720a1e6f926b33303a53cebe9c7
1//===--- Type.h - C Language Family Type Representation ---------*- C++ -*-===//
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 defines the Type interface and subclasses.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_TYPE_H
15#define LLVM_CLANG_AST_TYPE_H
16
17#include "clang/Basic/Diagnostic.h"
18#include "clang/Basic/ExceptionSpecificationType.h"
19#include "clang/Basic/IdentifierTable.h"
20#include "clang/Basic/Linkage.h"
21#include "clang/Basic/PartialDiagnostic.h"
22#include "clang/Basic/Visibility.h"
23#include "clang/AST/NestedNameSpecifier.h"
24#include "clang/AST/TemplateName.h"
25#include "llvm/Support/Casting.h"
26#include "llvm/Support/type_traits.h"
27#include "llvm/ADT/APSInt.h"
28#include "llvm/ADT/FoldingSet.h"
29#include "llvm/ADT/Optional.h"
30#include "llvm/ADT/PointerIntPair.h"
31#include "llvm/ADT/PointerUnion.h"
32
33using llvm::isa;
34using llvm::cast;
35using llvm::cast_or_null;
36using llvm::dyn_cast;
37using llvm::dyn_cast_or_null;
38namespace clang {
39  enum {
40    TypeAlignmentInBits = 4,
41    TypeAlignment = 1 << TypeAlignmentInBits
42  };
43  class Type;
44  class ExtQuals;
45  class QualType;
46}
47
48namespace llvm {
49  template <typename T>
50  class PointerLikeTypeTraits;
51  template<>
52  class PointerLikeTypeTraits< ::clang::Type*> {
53  public:
54    static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
55    static inline ::clang::Type *getFromVoidPointer(void *P) {
56      return static_cast< ::clang::Type*>(P);
57    }
58    enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
59  };
60  template<>
61  class PointerLikeTypeTraits< ::clang::ExtQuals*> {
62  public:
63    static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
64    static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
65      return static_cast< ::clang::ExtQuals*>(P);
66    }
67    enum { NumLowBitsAvailable = clang::TypeAlignmentInBits };
68  };
69
70  template <>
71  struct isPodLike<clang::QualType> { static const bool value = true; };
72}
73
74namespace clang {
75  class ASTContext;
76  class TypedefDecl;
77  class TemplateDecl;
78  class TemplateTypeParmDecl;
79  class NonTypeTemplateParmDecl;
80  class TemplateTemplateParmDecl;
81  class TagDecl;
82  class RecordDecl;
83  class CXXRecordDecl;
84  class EnumDecl;
85  class FieldDecl;
86  class ObjCInterfaceDecl;
87  class ObjCProtocolDecl;
88  class ObjCMethodDecl;
89  class UnresolvedUsingTypenameDecl;
90  class Expr;
91  class Stmt;
92  class SourceLocation;
93  class StmtIteratorBase;
94  class TemplateArgument;
95  class TemplateArgumentLoc;
96  class TemplateArgumentListInfo;
97  class ElaboratedType;
98  class ExtQuals;
99  class ExtQualsTypeCommonBase;
100  struct PrintingPolicy;
101
102  template <typename> class CanQual;
103  typedef CanQual<Type> CanQualType;
104
105  // Provide forward declarations for all of the *Type classes
106#define TYPE(Class, Base) class Class##Type;
107#include "clang/AST/TypeNodes.def"
108
109/// Qualifiers - The collection of all-type qualifiers we support.
110/// Clang supports five independent qualifiers:
111/// * C99: const, volatile, and restrict
112/// * Embedded C (TR18037): address spaces
113/// * Objective C: the GC attributes (none, weak, or strong)
114class Qualifiers {
115public:
116  enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
117    Const    = 0x1,
118    Restrict = 0x2,
119    Volatile = 0x4,
120    CVRMask = Const | Volatile | Restrict
121  };
122
123  enum GC {
124    GCNone = 0,
125    Weak,
126    Strong
127  };
128
129  enum {
130    /// The maximum supported address space number.
131    /// 24 bits should be enough for anyone.
132    MaxAddressSpace = 0xffffffu,
133
134    /// The width of the "fast" qualifier mask.
135    FastWidth = 3,
136
137    /// The fast qualifier mask.
138    FastMask = (1 << FastWidth) - 1
139  };
140
141  Qualifiers() : Mask(0) {}
142
143  static Qualifiers fromFastMask(unsigned Mask) {
144    Qualifiers Qs;
145    Qs.addFastQualifiers(Mask);
146    return Qs;
147  }
148
149  static Qualifiers fromCVRMask(unsigned CVR) {
150    Qualifiers Qs;
151    Qs.addCVRQualifiers(CVR);
152    return Qs;
153  }
154
155  // Deserialize qualifiers from an opaque representation.
156  static Qualifiers fromOpaqueValue(unsigned opaque) {
157    Qualifiers Qs;
158    Qs.Mask = opaque;
159    return Qs;
160  }
161
162  // Serialize these qualifiers into an opaque representation.
163  unsigned getAsOpaqueValue() const {
164    return Mask;
165  }
166
167  bool hasConst() const { return Mask & Const; }
168  void setConst(bool flag) {
169    Mask = (Mask & ~Const) | (flag ? Const : 0);
170  }
171  void removeConst() { Mask &= ~Const; }
172  void addConst() { Mask |= Const; }
173
174  bool hasVolatile() const { return Mask & Volatile; }
175  void setVolatile(bool flag) {
176    Mask = (Mask & ~Volatile) | (flag ? Volatile : 0);
177  }
178  void removeVolatile() { Mask &= ~Volatile; }
179  void addVolatile() { Mask |= Volatile; }
180
181  bool hasRestrict() const { return Mask & Restrict; }
182  void setRestrict(bool flag) {
183    Mask = (Mask & ~Restrict) | (flag ? Restrict : 0);
184  }
185  void removeRestrict() { Mask &= ~Restrict; }
186  void addRestrict() { Mask |= Restrict; }
187
188  bool hasCVRQualifiers() const { return getCVRQualifiers(); }
189  unsigned getCVRQualifiers() const { return Mask & CVRMask; }
190  void setCVRQualifiers(unsigned mask) {
191    assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
192    Mask = (Mask & ~CVRMask) | mask;
193  }
194  void removeCVRQualifiers(unsigned mask) {
195    assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
196    Mask &= ~mask;
197  }
198  void removeCVRQualifiers() {
199    removeCVRQualifiers(CVRMask);
200  }
201  void addCVRQualifiers(unsigned mask) {
202    assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
203    Mask |= mask;
204  }
205
206  bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
207  GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
208  void setObjCGCAttr(GC type) {
209    Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
210  }
211  void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
212  void addObjCGCAttr(GC type) {
213    assert(type);
214    setObjCGCAttr(type);
215  }
216
217  bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
218  unsigned getAddressSpace() const { return Mask >> AddressSpaceShift; }
219  void setAddressSpace(unsigned space) {
220    assert(space <= MaxAddressSpace);
221    Mask = (Mask & ~AddressSpaceMask)
222         | (((uint32_t) space) << AddressSpaceShift);
223  }
224  void removeAddressSpace() { setAddressSpace(0); }
225  void addAddressSpace(unsigned space) {
226    assert(space);
227    setAddressSpace(space);
228  }
229
230  // Fast qualifiers are those that can be allocated directly
231  // on a QualType object.
232  bool hasFastQualifiers() const { return getFastQualifiers(); }
233  unsigned getFastQualifiers() const { return Mask & FastMask; }
234  void setFastQualifiers(unsigned mask) {
235    assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
236    Mask = (Mask & ~FastMask) | mask;
237  }
238  void removeFastQualifiers(unsigned mask) {
239    assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
240    Mask &= ~mask;
241  }
242  void removeFastQualifiers() {
243    removeFastQualifiers(FastMask);
244  }
245  void addFastQualifiers(unsigned mask) {
246    assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
247    Mask |= mask;
248  }
249
250  /// hasNonFastQualifiers - Return true if the set contains any
251  /// qualifiers which require an ExtQuals node to be allocated.
252  bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
253  Qualifiers getNonFastQualifiers() const {
254    Qualifiers Quals = *this;
255    Quals.setFastQualifiers(0);
256    return Quals;
257  }
258
259  /// hasQualifiers - Return true if the set contains any qualifiers.
260  bool hasQualifiers() const { return Mask; }
261  bool empty() const { return !Mask; }
262
263  /// \brief Add the qualifiers from the given set to this set.
264  void addQualifiers(Qualifiers Q) {
265    // If the other set doesn't have any non-boolean qualifiers, just
266    // bit-or it in.
267    if (!(Q.Mask & ~CVRMask))
268      Mask |= Q.Mask;
269    else {
270      Mask |= (Q.Mask & CVRMask);
271      if (Q.hasAddressSpace())
272        addAddressSpace(Q.getAddressSpace());
273      if (Q.hasObjCGCAttr())
274        addObjCGCAttr(Q.getObjCGCAttr());
275    }
276  }
277
278  /// \brief Add the qualifiers from the given set to this set, given that
279  /// they don't conflict.
280  void addConsistentQualifiers(Qualifiers qs) {
281    assert(getAddressSpace() == qs.getAddressSpace() ||
282           !hasAddressSpace() || !qs.hasAddressSpace());
283    assert(getObjCGCAttr() == qs.getObjCGCAttr() ||
284           !hasObjCGCAttr() || !qs.hasObjCGCAttr());
285    Mask |= qs.Mask;
286  }
287
288  /// \brief Determines if these qualifiers compatibly include another set.
289  /// Generally this answers the question of whether an object with the other
290  /// qualifiers can be safely used as an object with these qualifiers.
291  bool compatiblyIncludes(Qualifiers other) const {
292    // Non-CVR qualifiers must match exactly.  CVR qualifiers may subset.
293    return ((Mask & ~CVRMask) == (other.Mask & ~CVRMask)) &&
294           (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask));
295  }
296
297  bool isSupersetOf(Qualifiers Other) const;
298
299  bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
300  bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
301
302  operator bool() const { return hasQualifiers(); }
303
304  Qualifiers &operator+=(Qualifiers R) {
305    addQualifiers(R);
306    return *this;
307  }
308
309  // Union two qualifier sets.  If an enumerated qualifier appears
310  // in both sets, use the one from the right.
311  friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
312    L += R;
313    return L;
314  }
315
316  Qualifiers &operator-=(Qualifiers R) {
317    Mask = Mask & ~(R.Mask);
318    return *this;
319  }
320
321  /// \brief Compute the difference between two qualifier sets.
322  friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
323    L -= R;
324    return L;
325  }
326
327  std::string getAsString() const;
328  std::string getAsString(const PrintingPolicy &Policy) const {
329    std::string Buffer;
330    getAsStringInternal(Buffer, Policy);
331    return Buffer;
332  }
333  void getAsStringInternal(std::string &S, const PrintingPolicy &Policy) const;
334
335  void Profile(llvm::FoldingSetNodeID &ID) const {
336    ID.AddInteger(Mask);
337  }
338
339private:
340
341  // bits:     |0 1 2|3 .. 4|5  ..  31|
342  //           |C R V|GCAttr|AddrSpace|
343  uint32_t Mask;
344
345  static const uint32_t GCAttrMask = 0x18;
346  static const uint32_t GCAttrShift = 3;
347  static const uint32_t AddressSpaceMask = ~(CVRMask | GCAttrMask);
348  static const uint32_t AddressSpaceShift = 5;
349};
350
351/// CallingConv - Specifies the calling convention that a function uses.
352enum CallingConv {
353  CC_Default,
354  CC_C,           // __attribute__((cdecl))
355  CC_X86StdCall,  // __attribute__((stdcall))
356  CC_X86FastCall, // __attribute__((fastcall))
357  CC_X86ThisCall, // __attribute__((thiscall))
358  CC_X86Pascal    // __attribute__((pascal))
359};
360
361typedef std::pair<const Type*, Qualifiers> SplitQualType;
362
363/// QualType - For efficiency, we don't store CV-qualified types as nodes on
364/// their own: instead each reference to a type stores the qualifiers.  This
365/// greatly reduces the number of nodes we need to allocate for types (for
366/// example we only need one for 'int', 'const int', 'volatile int',
367/// 'const volatile int', etc).
368///
369/// As an added efficiency bonus, instead of making this a pair, we
370/// just store the two bits we care about in the low bits of the
371/// pointer.  To handle the packing/unpacking, we make QualType be a
372/// simple wrapper class that acts like a smart pointer.  A third bit
373/// indicates whether there are extended qualifiers present, in which
374/// case the pointer points to a special structure.
375class QualType {
376  // Thankfully, these are efficiently composable.
377  llvm::PointerIntPair<llvm::PointerUnion<const Type*,const ExtQuals*>,
378                       Qualifiers::FastWidth> Value;
379
380  const ExtQuals *getExtQualsUnsafe() const {
381    return Value.getPointer().get<const ExtQuals*>();
382  }
383
384  const Type *getTypePtrUnsafe() const {
385    return Value.getPointer().get<const Type*>();
386  }
387
388  const ExtQualsTypeCommonBase *getCommonPtr() const {
389    assert(!isNull() && "Cannot retrieve a NULL type pointer");
390    uintptr_t CommonPtrVal
391      = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
392    CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
393    return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
394  }
395
396  friend class QualifierCollector;
397public:
398  QualType() {}
399
400  QualType(const Type *Ptr, unsigned Quals)
401    : Value(Ptr, Quals) {}
402  QualType(const ExtQuals *Ptr, unsigned Quals)
403    : Value(Ptr, Quals) {}
404
405  unsigned getLocalFastQualifiers() const { return Value.getInt(); }
406  void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
407
408  /// Retrieves a pointer to the underlying (unqualified) type.
409  /// This should really return a const Type, but it's not worth
410  /// changing all the users right now.
411  ///
412  /// This function requires that the type not be NULL. If the type might be
413  /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
414  const Type *getTypePtr() const;
415
416  const Type *getTypePtrOrNull() const;
417
418  /// Divides a QualType into its unqualified type and a set of local
419  /// qualifiers.
420  SplitQualType split() const;
421
422  void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
423  static QualType getFromOpaquePtr(const void *Ptr) {
424    QualType T;
425    T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
426    return T;
427  }
428
429  const Type &operator*() const {
430    return *getTypePtr();
431  }
432
433  const Type *operator->() const {
434    return getTypePtr();
435  }
436
437  bool isCanonical() const;
438  bool isCanonicalAsParam() const;
439
440  /// isNull - Return true if this QualType doesn't point to a type yet.
441  bool isNull() const {
442    return Value.getPointer().isNull();
443  }
444
445  /// \brief Determine whether this particular QualType instance has the
446  /// "const" qualifier set, without looking through typedefs that may have
447  /// added "const" at a different level.
448  bool isLocalConstQualified() const {
449    return (getLocalFastQualifiers() & Qualifiers::Const);
450  }
451
452  /// \brief Determine whether this type is const-qualified.
453  bool isConstQualified() const;
454
455  /// \brief Determine whether this particular QualType instance has the
456  /// "restrict" qualifier set, without looking through typedefs that may have
457  /// added "restrict" at a different level.
458  bool isLocalRestrictQualified() const {
459    return (getLocalFastQualifiers() & Qualifiers::Restrict);
460  }
461
462  /// \brief Determine whether this type is restrict-qualified.
463  bool isRestrictQualified() const;
464
465  /// \brief Determine whether this particular QualType instance has the
466  /// "volatile" qualifier set, without looking through typedefs that may have
467  /// added "volatile" at a different level.
468  bool isLocalVolatileQualified() const {
469    return (getLocalFastQualifiers() & Qualifiers::Volatile);
470  }
471
472  /// \brief Determine whether this type is volatile-qualified.
473  bool isVolatileQualified() const;
474
475  /// \brief Determine whether this particular QualType instance has any
476  /// qualifiers, without looking through any typedefs that might add
477  /// qualifiers at a different level.
478  bool hasLocalQualifiers() const {
479    return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
480  }
481
482  /// \brief Determine whether this type has any qualifiers.
483  bool hasQualifiers() const;
484
485  /// \brief Determine whether this particular QualType instance has any
486  /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
487  /// instance.
488  bool hasLocalNonFastQualifiers() const {
489    return Value.getPointer().is<const ExtQuals*>();
490  }
491
492  /// \brief Retrieve the set of qualifiers local to this particular QualType
493  /// instance, not including any qualifiers acquired through typedefs or
494  /// other sugar.
495  Qualifiers getLocalQualifiers() const;
496
497  /// \brief Retrieve the set of qualifiers applied to this type.
498  Qualifiers getQualifiers() const;
499
500  /// \brief Retrieve the set of CVR (const-volatile-restrict) qualifiers
501  /// local to this particular QualType instance, not including any qualifiers
502  /// acquired through typedefs or other sugar.
503  unsigned getLocalCVRQualifiers() const {
504    return getLocalFastQualifiers();
505  }
506
507  /// \brief Retrieve the set of CVR (const-volatile-restrict) qualifiers
508  /// applied to this type.
509  unsigned getCVRQualifiers() const;
510
511  bool isConstant(ASTContext& Ctx) const {
512    return QualType::isConstant(*this, Ctx);
513  }
514
515  // Don't promise in the API that anything besides 'const' can be
516  // easily added.
517
518  /// addConst - add the specified type qualifier to this QualType.
519  void addConst() {
520    addFastQualifiers(Qualifiers::Const);
521  }
522  QualType withConst() const {
523    return withFastQualifiers(Qualifiers::Const);
524  }
525
526  void addFastQualifiers(unsigned TQs) {
527    assert(!(TQs & ~Qualifiers::FastMask)
528           && "non-fast qualifier bits set in mask!");
529    Value.setInt(Value.getInt() | TQs);
530  }
531
532  void removeLocalConst();
533  void removeLocalVolatile();
534  void removeLocalRestrict();
535  void removeLocalCVRQualifiers(unsigned Mask);
536
537  void removeLocalFastQualifiers() { Value.setInt(0); }
538  void removeLocalFastQualifiers(unsigned Mask) {
539    assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers");
540    Value.setInt(Value.getInt() & ~Mask);
541  }
542
543  // Creates a type with the given qualifiers in addition to any
544  // qualifiers already on this type.
545  QualType withFastQualifiers(unsigned TQs) const {
546    QualType T = *this;
547    T.addFastQualifiers(TQs);
548    return T;
549  }
550
551  // Creates a type with exactly the given fast qualifiers, removing
552  // any existing fast qualifiers.
553  QualType withExactLocalFastQualifiers(unsigned TQs) const {
554    return withoutLocalFastQualifiers().withFastQualifiers(TQs);
555  }
556
557  // Removes fast qualifiers, but leaves any extended qualifiers in place.
558  QualType withoutLocalFastQualifiers() const {
559    QualType T = *this;
560    T.removeLocalFastQualifiers();
561    return T;
562  }
563
564  QualType getCanonicalType() const;
565
566  /// \brief Return this type with all of the instance-specific qualifiers
567  /// removed, but without removing any qualifiers that may have been applied
568  /// through typedefs.
569  QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
570
571  /// \brief Retrieve the unqualified variant of the given type,
572  /// removing as little sugar as possible.
573  ///
574  /// This routine looks through various kinds of sugar to find the
575  /// least-desugared type that is unqualified. For example, given:
576  ///
577  /// \code
578  /// typedef int Integer;
579  /// typedef const Integer CInteger;
580  /// typedef CInteger DifferenceType;
581  /// \endcode
582  ///
583  /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
584  /// desugar until we hit the type \c Integer, which has no qualifiers on it.
585  ///
586  /// The resulting type might still be qualified if it's an array
587  /// type.  To strip qualifiers even from within an array type, use
588  /// ASTContext::getUnqualifiedArrayType.
589  inline QualType getUnqualifiedType() const;
590
591  /// getSplitUnqualifiedType - Retrieve the unqualified variant of the
592  /// given type, removing as little sugar as possible.
593  ///
594  /// Like getUnqualifiedType(), but also returns the set of
595  /// qualifiers that were built up.
596  ///
597  /// The resulting type might still be qualified if it's an array
598  /// type.  To strip qualifiers even from within an array type, use
599  /// ASTContext::getUnqualifiedArrayType.
600  inline SplitQualType getSplitUnqualifiedType() const;
601
602  bool isMoreQualifiedThan(QualType Other) const;
603  bool isAtLeastAsQualifiedAs(QualType Other) const;
604  QualType getNonReferenceType() const;
605
606  /// \brief Determine the type of a (typically non-lvalue) expression with the
607  /// specified result type.
608  ///
609  /// This routine should be used for expressions for which the return type is
610  /// explicitly specified (e.g., in a cast or call) and isn't necessarily
611  /// an lvalue. It removes a top-level reference (since there are no
612  /// expressions of reference type) and deletes top-level cvr-qualifiers
613  /// from non-class types (in C++) or all types (in C).
614  QualType getNonLValueExprType(ASTContext &Context) const;
615
616  /// getDesugaredType - Return the specified type with any "sugar" removed from
617  /// the type.  This takes off typedefs, typeof's etc.  If the outer level of
618  /// the type is already concrete, it returns it unmodified.  This is similar
619  /// to getting the canonical type, but it doesn't remove *all* typedefs.  For
620  /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
621  /// concrete.
622  ///
623  /// Qualifiers are left in place.
624  QualType getDesugaredType(const ASTContext &Context) const {
625    return getDesugaredType(*this, Context);
626  }
627
628  SplitQualType getSplitDesugaredType() const {
629    return getSplitDesugaredType(*this);
630  }
631
632  /// IgnoreParens - Returns the specified type after dropping any
633  /// outer-level parentheses.
634  QualType IgnoreParens() const {
635    if (isa<ParenType>(*this))
636      return QualType::IgnoreParens(*this);
637    return *this;
638  }
639
640  /// operator==/!= - Indicate whether the specified types and qualifiers are
641  /// identical.
642  friend bool operator==(const QualType &LHS, const QualType &RHS) {
643    return LHS.Value == RHS.Value;
644  }
645  friend bool operator!=(const QualType &LHS, const QualType &RHS) {
646    return LHS.Value != RHS.Value;
647  }
648  std::string getAsString() const {
649    return getAsString(split());
650  }
651  static std::string getAsString(SplitQualType split) {
652    return getAsString(split.first, split.second);
653  }
654  static std::string getAsString(const Type *ty, Qualifiers qs);
655
656  std::string getAsString(const PrintingPolicy &Policy) const {
657    std::string S;
658    getAsStringInternal(S, Policy);
659    return S;
660  }
661  void getAsStringInternal(std::string &Str,
662                           const PrintingPolicy &Policy) const {
663    return getAsStringInternal(split(), Str, Policy);
664  }
665  static void getAsStringInternal(SplitQualType split, std::string &out,
666                                  const PrintingPolicy &policy) {
667    return getAsStringInternal(split.first, split.second, out, policy);
668  }
669  static void getAsStringInternal(const Type *ty, Qualifiers qs,
670                                  std::string &out,
671                                  const PrintingPolicy &policy);
672
673  void dump(const char *s) const;
674  void dump() const;
675
676  void Profile(llvm::FoldingSetNodeID &ID) const {
677    ID.AddPointer(getAsOpaquePtr());
678  }
679
680  /// getAddressSpace - Return the address space of this type.
681  inline unsigned getAddressSpace() const;
682
683  /// GCAttrTypesAttr - Returns gc attribute of this type.
684  inline Qualifiers::GC getObjCGCAttr() const;
685
686  /// isObjCGCWeak true when Type is objc's weak.
687  bool isObjCGCWeak() const {
688    return getObjCGCAttr() == Qualifiers::Weak;
689  }
690
691  /// isObjCGCStrong true when Type is objc's strong.
692  bool isObjCGCStrong() const {
693    return getObjCGCAttr() == Qualifiers::Strong;
694  }
695
696  enum DestructionKind {
697    DK_none,
698    DK_cxx_destructor
699  };
700
701  /// isDestructedType - nonzero if objects of this type require
702  /// non-trivial work to clean up after.  Non-zero because it's
703  /// conceivable that qualifiers (objc_gc(weak)?) could make
704  /// something require destruction.
705  DestructionKind isDestructedType() const {
706    return isDestructedTypeImpl(*this);
707  }
708
709private:
710  // These methods are implemented in a separate translation unit;
711  // "static"-ize them to avoid creating temporary QualTypes in the
712  // caller.
713  static bool isConstant(QualType T, ASTContext& Ctx);
714  static QualType getDesugaredType(QualType T, const ASTContext &Context);
715  static SplitQualType getSplitDesugaredType(QualType T);
716  static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
717  static QualType IgnoreParens(QualType T);
718  static DestructionKind isDestructedTypeImpl(QualType type);
719};
720
721} // end clang.
722
723namespace llvm {
724/// Implement simplify_type for QualType, so that we can dyn_cast from QualType
725/// to a specific Type class.
726template<> struct simplify_type<const ::clang::QualType> {
727  typedef const ::clang::Type *SimpleType;
728  static SimpleType getSimplifiedValue(const ::clang::QualType &Val) {
729    return Val.getTypePtr();
730  }
731};
732template<> struct simplify_type< ::clang::QualType>
733  : public simplify_type<const ::clang::QualType> {};
734
735// Teach SmallPtrSet that QualType is "basically a pointer".
736template<>
737class PointerLikeTypeTraits<clang::QualType> {
738public:
739  static inline void *getAsVoidPointer(clang::QualType P) {
740    return P.getAsOpaquePtr();
741  }
742  static inline clang::QualType getFromVoidPointer(void *P) {
743    return clang::QualType::getFromOpaquePtr(P);
744  }
745  // Various qualifiers go in low bits.
746  enum { NumLowBitsAvailable = 0 };
747};
748
749} // end namespace llvm
750
751namespace clang {
752
753/// \brief Base class that is common to both the \c ExtQuals and \c Type
754/// classes, which allows \c QualType to access the common fields between the
755/// two.
756///
757class ExtQualsTypeCommonBase {
758  ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
759    : BaseType(baseType), CanonicalType(canon) {}
760
761  /// \brief The "base" type of an extended qualifiers type (\c ExtQuals) or
762  /// a self-referential pointer (for \c Type).
763  ///
764  /// This pointer allows an efficient mapping from a QualType to its
765  /// underlying type pointer.
766  const Type *const BaseType;
767
768  /// \brief The canonical type of this type.  A QualType.
769  QualType CanonicalType;
770
771  friend class QualType;
772  friend class Type;
773  friend class ExtQuals;
774};
775
776/// ExtQuals - We can encode up to four bits in the low bits of a
777/// type pointer, but there are many more type qualifiers that we want
778/// to be able to apply to an arbitrary type.  Therefore we have this
779/// struct, intended to be heap-allocated and used by QualType to
780/// store qualifiers.
781///
782/// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
783/// in three low bits on the QualType pointer; a fourth bit records whether
784/// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
785/// Objective-C GC attributes) are much more rare.
786class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
787  // NOTE: changing the fast qualifiers should be straightforward as
788  // long as you don't make 'const' non-fast.
789  // 1. Qualifiers:
790  //    a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
791  //       Fast qualifiers must occupy the low-order bits.
792  //    b) Update Qualifiers::FastWidth and FastMask.
793  // 2. QualType:
794  //    a) Update is{Volatile,Restrict}Qualified(), defined inline.
795  //    b) Update remove{Volatile,Restrict}, defined near the end of
796  //       this header.
797  // 3. ASTContext:
798  //    a) Update get{Volatile,Restrict}Type.
799
800  /// Quals - the immutable set of qualifiers applied by this
801  /// node;  always contains extended qualifiers.
802  Qualifiers Quals;
803
804  ExtQuals *this_() { return this; }
805
806public:
807  ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
808    : ExtQualsTypeCommonBase(baseType,
809                             canon.isNull() ? QualType(this_(), 0) : canon),
810      Quals(quals)
811  {
812    assert(Quals.hasNonFastQualifiers()
813           && "ExtQuals created with no fast qualifiers");
814    assert(!Quals.hasFastQualifiers()
815           && "ExtQuals created with fast qualifiers");
816  }
817
818  Qualifiers getQualifiers() const { return Quals; }
819
820  bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
821  Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
822
823  bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
824  unsigned getAddressSpace() const { return Quals.getAddressSpace(); }
825
826  const Type *getBaseType() const { return BaseType; }
827
828public:
829  void Profile(llvm::FoldingSetNodeID &ID) const {
830    Profile(ID, getBaseType(), Quals);
831  }
832  static void Profile(llvm::FoldingSetNodeID &ID,
833                      const Type *BaseType,
834                      Qualifiers Quals) {
835    assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!");
836    ID.AddPointer(BaseType);
837    Quals.Profile(ID);
838  }
839};
840
841/// \brief The kind of C++0x ref-qualifier associated with a function type,
842/// which determines whether a member function's "this" object can be an
843/// lvalue, rvalue, or neither.
844enum RefQualifierKind {
845  /// \brief No ref-qualifier was provided.
846  RQ_None = 0,
847  /// \brief An lvalue ref-qualifier was provided (\c &).
848  RQ_LValue,
849  /// \brief An rvalue ref-qualifier was provided (\c &&).
850  RQ_RValue
851};
852
853/// Type - This is the base class of the type hierarchy.  A central concept
854/// with types is that each type always has a canonical type.  A canonical type
855/// is the type with any typedef names stripped out of it or the types it
856/// references.  For example, consider:
857///
858///  typedef int  foo;
859///  typedef foo* bar;
860///    'int *'    'foo *'    'bar'
861///
862/// There will be a Type object created for 'int'.  Since int is canonical, its
863/// canonicaltype pointer points to itself.  There is also a Type for 'foo' (a
864/// TypedefType).  Its CanonicalType pointer points to the 'int' Type.  Next
865/// there is a PointerType that represents 'int*', which, like 'int', is
866/// canonical.  Finally, there is a PointerType type for 'foo*' whose canonical
867/// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
868/// is also 'int*'.
869///
870/// Non-canonical types are useful for emitting diagnostics, without losing
871/// information about typedefs being used.  Canonical types are useful for type
872/// comparisons (they allow by-pointer equality tests) and useful for reasoning
873/// about whether something has a particular form (e.g. is a function type),
874/// because they implicitly, recursively, strip all typedefs out of a type.
875///
876/// Types, once created, are immutable.
877///
878class Type : public ExtQualsTypeCommonBase {
879public:
880  enum TypeClass {
881#define TYPE(Class, Base) Class,
882#define LAST_TYPE(Class) TypeLast = Class,
883#define ABSTRACT_TYPE(Class, Base)
884#include "clang/AST/TypeNodes.def"
885    TagFirst = Record, TagLast = Enum
886  };
887
888private:
889  Type(const Type&);           // DO NOT IMPLEMENT.
890  void operator=(const Type&); // DO NOT IMPLEMENT.
891
892  /// Bitfields required by the Type class.
893  class TypeBitfields {
894    friend class Type;
895    template <class T> friend class TypePropertyCache;
896
897    /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
898    unsigned TC : 8;
899
900    /// Dependent - Whether this type is a dependent type (C++ [temp.dep.type]).
901    /// Note that this should stay at the end of the ivars for Type so that
902    /// subclasses can pack their bitfields into the same word.
903    unsigned Dependent : 1;
904
905    /// \brief Whether this type is a variably-modified type (C99 6.7.5).
906    unsigned VariablyModified : 1;
907
908    /// \brief Whether this type contains an unexpanded parameter pack
909    /// (for C++0x variadic templates).
910    unsigned ContainsUnexpandedParameterPack : 1;
911
912    /// \brief Nonzero if the cache (i.e. the bitfields here starting
913    /// with 'Cache') is valid.  If so, then this is a
914    /// LangOptions::VisibilityMode+1.
915    mutable unsigned CacheValidAndVisibility : 2;
916
917    /// \brief Linkage of this type.
918    mutable unsigned CachedLinkage : 2;
919
920    /// \brief Whether this type involves and local or unnamed types.
921    mutable unsigned CachedLocalOrUnnamed : 1;
922
923    /// \brief FromAST - Whether this type comes from an AST file.
924    mutable unsigned FromAST : 1;
925
926    bool isCacheValid() const {
927      return (CacheValidAndVisibility != 0);
928    }
929    Visibility getVisibility() const {
930      assert(isCacheValid() && "getting linkage from invalid cache");
931      return static_cast<Visibility>(CacheValidAndVisibility-1);
932    }
933    Linkage getLinkage() const {
934      assert(isCacheValid() && "getting linkage from invalid cache");
935      return static_cast<Linkage>(CachedLinkage);
936    }
937    bool hasLocalOrUnnamedType() const {
938      assert(isCacheValid() && "getting linkage from invalid cache");
939      return CachedLocalOrUnnamed;
940    }
941  };
942  enum { NumTypeBits = 17 };
943
944protected:
945  // These classes allow subclasses to somewhat cleanly pack bitfields
946  // into Type.
947
948  class ArrayTypeBitfields {
949    friend class ArrayType;
950
951    unsigned : NumTypeBits;
952
953    /// IndexTypeQuals - CVR qualifiers from declarations like
954    /// 'int X[static restrict 4]'. For function parameters only.
955    unsigned IndexTypeQuals : 3;
956
957    /// SizeModifier - storage class qualifiers from declarations like
958    /// 'int X[static restrict 4]'. For function parameters only.
959    /// Actually an ArrayType::ArraySizeModifier.
960    unsigned SizeModifier : 3;
961  };
962
963  class BuiltinTypeBitfields {
964    friend class BuiltinType;
965
966    unsigned : NumTypeBits;
967
968    /// The kind (BuiltinType::Kind) of builtin type this is.
969    unsigned Kind : 8;
970  };
971
972  class FunctionTypeBitfields {
973    friend class FunctionType;
974
975    unsigned : NumTypeBits;
976
977    /// Extra information which affects how the function is called, like
978    /// regparm and the calling convention.
979    unsigned ExtInfo : 8;
980
981    /// Whether the function is variadic.  Only used by FunctionProtoType.
982    unsigned Variadic : 1;
983
984    /// TypeQuals - Used only by FunctionProtoType, put here to pack with the
985    /// other bitfields.
986    /// The qualifiers are part of FunctionProtoType because...
987    ///
988    /// C++ 8.3.5p4: The return type, the parameter type list and the
989    /// cv-qualifier-seq, [...], are part of the function type.
990    unsigned TypeQuals : 3;
991
992    /// \brief The ref-qualifier associated with a \c FunctionProtoType.
993    ///
994    /// This is a value of type \c RefQualifierKind.
995    unsigned RefQualifier : 2;
996  };
997
998  class ObjCObjectTypeBitfields {
999    friend class ObjCObjectType;
1000
1001    unsigned : NumTypeBits;
1002
1003    /// NumProtocols - The number of protocols stored directly on this
1004    /// object type.
1005    unsigned NumProtocols : 32 - NumTypeBits;
1006  };
1007
1008  class ReferenceTypeBitfields {
1009    friend class ReferenceType;
1010
1011    unsigned : NumTypeBits;
1012
1013    /// True if the type was originally spelled with an lvalue sigil.
1014    /// This is never true of rvalue references but can also be false
1015    /// on lvalue references because of C++0x [dcl.typedef]p9,
1016    /// as follows:
1017    ///
1018    ///   typedef int &ref;    // lvalue, spelled lvalue
1019    ///   typedef int &&rvref; // rvalue
1020    ///   ref &a;              // lvalue, inner ref, spelled lvalue
1021    ///   ref &&a;             // lvalue, inner ref
1022    ///   rvref &a;            // lvalue, inner ref, spelled lvalue
1023    ///   rvref &&a;           // rvalue, inner ref
1024    unsigned SpelledAsLValue : 1;
1025
1026    /// True if the inner type is a reference type.  This only happens
1027    /// in non-canonical forms.
1028    unsigned InnerRef : 1;
1029  };
1030
1031  class TypeWithKeywordBitfields {
1032    friend class TypeWithKeyword;
1033
1034    unsigned : NumTypeBits;
1035
1036    /// An ElaboratedTypeKeyword.  8 bits for efficient access.
1037    unsigned Keyword : 8;
1038  };
1039
1040  class VectorTypeBitfields {
1041    friend class VectorType;
1042
1043    unsigned : NumTypeBits;
1044
1045    /// VecKind - The kind of vector, either a generic vector type or some
1046    /// target-specific vector type such as for AltiVec or Neon.
1047    unsigned VecKind : 3;
1048
1049    /// NumElements - The number of elements in the vector.
1050    unsigned NumElements : 29 - NumTypeBits;
1051  };
1052
1053  class AttributedTypeBitfields {
1054    friend class AttributedType;
1055
1056    unsigned : NumTypeBits;
1057
1058    /// AttrKind - an AttributedType::Kind
1059    unsigned AttrKind : 32 - NumTypeBits;
1060  };
1061
1062  union {
1063    TypeBitfields TypeBits;
1064    ArrayTypeBitfields ArrayTypeBits;
1065    AttributedTypeBitfields AttributedTypeBits;
1066    BuiltinTypeBitfields BuiltinTypeBits;
1067    FunctionTypeBitfields FunctionTypeBits;
1068    ObjCObjectTypeBitfields ObjCObjectTypeBits;
1069    ReferenceTypeBitfields ReferenceTypeBits;
1070    TypeWithKeywordBitfields TypeWithKeywordBits;
1071    VectorTypeBitfields VectorTypeBits;
1072  };
1073
1074private:
1075  /// \brief Set whether this type comes from an AST file.
1076  void setFromAST(bool V = true) const {
1077    TypeBits.FromAST = V;
1078  }
1079
1080  template <class T> friend class TypePropertyCache;
1081
1082protected:
1083  // silence VC++ warning C4355: 'this' : used in base member initializer list
1084  Type *this_() { return this; }
1085  Type(TypeClass tc, QualType canon, bool Dependent, bool VariablyModified,
1086       bool ContainsUnexpandedParameterPack)
1087    : ExtQualsTypeCommonBase(this,
1088                             canon.isNull() ? QualType(this_(), 0) : canon) {
1089    TypeBits.TC = tc;
1090    TypeBits.Dependent = Dependent;
1091    TypeBits.VariablyModified = VariablyModified;
1092    TypeBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1093    TypeBits.CacheValidAndVisibility = 0;
1094    TypeBits.CachedLocalOrUnnamed = false;
1095    TypeBits.CachedLinkage = NoLinkage;
1096    TypeBits.FromAST = false;
1097  }
1098  friend class ASTContext;
1099
1100  void setDependent(bool D = true) { TypeBits.Dependent = D; }
1101  void setVariablyModified(bool VM = true) { TypeBits.VariablyModified = VM; }
1102  void setContainsUnexpandedParameterPack(bool PP = true) {
1103    TypeBits.ContainsUnexpandedParameterPack = PP;
1104  }
1105
1106public:
1107  TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1108
1109  /// \brief Whether this type comes from an AST file.
1110  bool isFromAST() const { return TypeBits.FromAST; }
1111
1112  /// \brief Whether this type is or contains an unexpanded parameter
1113  /// pack, used to support C++0x variadic templates.
1114  ///
1115  /// A type that contains a parameter pack shall be expanded by the
1116  /// ellipsis operator at some point. For example, the typedef in the
1117  /// following example contains an unexpanded parameter pack 'T':
1118  ///
1119  /// \code
1120  /// template<typename ...T>
1121  /// struct X {
1122  ///   typedef T* pointer_types; // ill-formed; T is a parameter pack.
1123  /// };
1124  /// \endcode
1125  ///
1126  /// Note that this routine does not specify which
1127  bool containsUnexpandedParameterPack() const {
1128    return TypeBits.ContainsUnexpandedParameterPack;
1129  }
1130
1131  /// Determines if this type would be canonical if it had no further
1132  /// qualification.
1133  bool isCanonicalUnqualified() const {
1134    return CanonicalType == QualType(this, 0);
1135  }
1136
1137  /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1138  /// object types, function types, and incomplete types.
1139
1140  /// isIncompleteType - Return true if this is an incomplete type.
1141  /// A type that can describe objects, but which lacks information needed to
1142  /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1143  /// routine will need to determine if the size is actually required.
1144  bool isIncompleteType() const;
1145
1146  /// isIncompleteOrObjectType - Return true if this is an incomplete or object
1147  /// type, in other words, not a function type.
1148  bool isIncompleteOrObjectType() const {
1149    return !isFunctionType();
1150  }
1151
1152  /// \brief Determine whether this type is an object type.
1153  bool isObjectType() const {
1154    // C++ [basic.types]p8:
1155    //   An object type is a (possibly cv-qualified) type that is not a
1156    //   function type, not a reference type, and not a void type.
1157    return !isReferenceType() && !isFunctionType() && !isVoidType();
1158  }
1159
1160  /// isPODType - Return true if this is a plain-old-data type (C++ 3.9p10).
1161  bool isPODType() const;
1162
1163  /// isLiteralType - Return true if this is a literal type
1164  /// (C++0x [basic.types]p10)
1165  bool isLiteralType() const;
1166
1167  /// Helper methods to distinguish type categories. All type predicates
1168  /// operate on the canonical type, ignoring typedefs and qualifiers.
1169
1170  /// isBuiltinType - returns true if the type is a builtin type.
1171  bool isBuiltinType() const;
1172
1173  /// isSpecificBuiltinType - Test for a particular builtin type.
1174  bool isSpecificBuiltinType(unsigned K) const;
1175
1176  /// isPlaceholderType - Test for a type which does not represent an
1177  /// actual type-system type but is instead used as a placeholder for
1178  /// various convenient purposes within Clang.  All such types are
1179  /// BuiltinTypes.
1180  bool isPlaceholderType() const;
1181
1182  /// isIntegerType() does *not* include complex integers (a GCC extension).
1183  /// isComplexIntegerType() can be used to test for complex integers.
1184  bool isIntegerType() const;     // C99 6.2.5p17 (int, char, bool, enum)
1185  bool isEnumeralType() const;
1186  bool isBooleanType() const;
1187  bool isCharType() const;
1188  bool isWideCharType() const;
1189  bool isAnyCharacterType() const;
1190  bool isIntegralType(ASTContext &Ctx) const;
1191
1192  /// \brief Determine whether this type is an integral or enumeration type.
1193  bool isIntegralOrEnumerationType() const;
1194  /// \brief Determine whether this type is an integral or unscoped enumeration
1195  /// type.
1196  bool isIntegralOrUnscopedEnumerationType() const;
1197
1198  /// Floating point categories.
1199  bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1200  /// isComplexType() does *not* include complex integers (a GCC extension).
1201  /// isComplexIntegerType() can be used to test for complex integers.
1202  bool isComplexType() const;      // C99 6.2.5p11 (complex)
1203  bool isAnyComplexType() const;   // C99 6.2.5p11 (complex) + Complex Int.
1204  bool isFloatingType() const;     // C99 6.2.5p11 (real floating + complex)
1205  bool isRealType() const;         // C99 6.2.5p17 (real floating + integer)
1206  bool isArithmeticType() const;   // C99 6.2.5p18 (integer + floating)
1207  bool isVoidType() const;         // C99 6.2.5p19
1208  bool isDerivedType() const;      // C99 6.2.5p20
1209  bool isScalarType() const;       // C99 6.2.5p21 (arithmetic + pointers)
1210  bool isAggregateType() const;
1211
1212  // Type Predicates: Check to see if this type is structurally the specified
1213  // type, ignoring typedefs and qualifiers.
1214  bool isFunctionType() const;
1215  bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
1216  bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
1217  bool isPointerType() const;
1218  bool isAnyPointerType() const;   // Any C pointer or ObjC object pointer
1219  bool isBlockPointerType() const;
1220  bool isVoidPointerType() const;
1221  bool isReferenceType() const;
1222  bool isLValueReferenceType() const;
1223  bool isRValueReferenceType() const;
1224  bool isFunctionPointerType() const;
1225  bool isMemberPointerType() const;
1226  bool isMemberFunctionPointerType() const;
1227  bool isMemberDataPointerType() const;
1228  bool isArrayType() const;
1229  bool isConstantArrayType() const;
1230  bool isIncompleteArrayType() const;
1231  bool isVariableArrayType() const;
1232  bool isDependentSizedArrayType() const;
1233  bool isRecordType() const;
1234  bool isClassType() const;
1235  bool isStructureType() const;
1236  bool isStructureOrClassType() const;
1237  bool isUnionType() const;
1238  bool isComplexIntegerType() const;            // GCC _Complex integer type.
1239  bool isVectorType() const;                    // GCC vector type.
1240  bool isExtVectorType() const;                 // Extended vector type.
1241  bool isObjCObjectPointerType() const;         // Pointer to *any* ObjC object.
1242  // FIXME: change this to 'raw' interface type, so we can used 'interface' type
1243  // for the common case.
1244  bool isObjCObjectType() const;                // NSString or typeof(*(id)0)
1245  bool isObjCQualifiedInterfaceType() const;    // NSString<foo>
1246  bool isObjCQualifiedIdType() const;           // id<foo>
1247  bool isObjCQualifiedClassType() const;        // Class<foo>
1248  bool isObjCObjectOrInterfaceType() const;
1249  bool isObjCIdType() const;                    // id
1250  bool isObjCClassType() const;                 // Class
1251  bool isObjCSelType() const;                 // Class
1252  bool isObjCBuiltinType() const;               // 'id' or 'Class'
1253  bool isTemplateTypeParmType() const;          // C++ template type parameter
1254  bool isNullPtrType() const;                   // C++0x nullptr_t
1255
1256  enum ScalarTypeKind {
1257    STK_Pointer,
1258    STK_MemberPointer,
1259    STK_Bool,
1260    STK_Integral,
1261    STK_Floating,
1262    STK_IntegralComplex,
1263    STK_FloatingComplex
1264  };
1265  /// getScalarTypeKind - Given that this is a scalar type, classify it.
1266  ScalarTypeKind getScalarTypeKind() const;
1267
1268  /// isDependentType - Whether this type is a dependent type, meaning
1269  /// that its definition somehow depends on a template parameter
1270  /// (C++ [temp.dep.type]).
1271  bool isDependentType() const { return TypeBits.Dependent; }
1272
1273  /// \brief Whether this type is a variably-modified type (C99 6.7.5).
1274  bool isVariablyModifiedType() const { return TypeBits.VariablyModified; }
1275
1276  /// \brief Whether this type involves a variable-length array type
1277  /// with a definite size.
1278  bool hasSizedVLAType() const;
1279
1280  /// \brief Whether this type is or contains a local or unnamed type.
1281  bool hasUnnamedOrLocalType() const;
1282
1283  bool isOverloadableType() const;
1284
1285  /// \brief Determine wither this type is a C++ elaborated-type-specifier.
1286  bool isElaboratedTypeSpecifier() const;
1287
1288  /// hasPointerRepresentation - Whether this type is represented
1289  /// natively as a pointer; this includes pointers, references, block
1290  /// pointers, and Objective-C interface, qualified id, and qualified
1291  /// interface types, as well as nullptr_t.
1292  bool hasPointerRepresentation() const;
1293
1294  /// hasObjCPointerRepresentation - Whether this type can represent
1295  /// an objective pointer type for the purpose of GC'ability
1296  bool hasObjCPointerRepresentation() const;
1297
1298  /// \brief Determine whether this type has an integer representation
1299  /// of some sort, e.g., it is an integer type or a vector.
1300  bool hasIntegerRepresentation() const;
1301
1302  /// \brief Determine whether this type has an signed integer representation
1303  /// of some sort, e.g., it is an signed integer type or a vector.
1304  bool hasSignedIntegerRepresentation() const;
1305
1306  /// \brief Determine whether this type has an unsigned integer representation
1307  /// of some sort, e.g., it is an unsigned integer type or a vector.
1308  bool hasUnsignedIntegerRepresentation() const;
1309
1310  /// \brief Determine whether this type has a floating-point representation
1311  /// of some sort, e.g., it is a floating-point type or a vector thereof.
1312  bool hasFloatingRepresentation() const;
1313
1314  // Type Checking Functions: Check to see if this type is structurally the
1315  // specified type, ignoring typedefs and qualifiers, and return a pointer to
1316  // the best type we can.
1317  const RecordType *getAsStructureType() const;
1318  /// NOTE: getAs*ArrayType are methods on ASTContext.
1319  const RecordType *getAsUnionType() const;
1320  const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
1321  // The following is a convenience method that returns an ObjCObjectPointerType
1322  // for object declared using an interface.
1323  const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
1324  const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
1325  const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
1326  const CXXRecordDecl *getCXXRecordDeclForPointerType() const;
1327
1328  /// \brief Retrieves the CXXRecordDecl that this type refers to, either
1329  /// because the type is a RecordType or because it is the injected-class-name
1330  /// type of a class template or class template partial specialization.
1331  CXXRecordDecl *getAsCXXRecordDecl() const;
1332
1333  /// \brief Get the AutoType whose type will be deduced for a variable with
1334  /// an initializer of this type. This looks through declarators like pointer
1335  /// types, but not through decltype or typedefs.
1336  AutoType *getContainedAutoType() const;
1337
1338  /// Member-template getAs<specific type>'.  Look through sugar for
1339  /// an instance of <specific type>.   This scheme will eventually
1340  /// replace the specific getAsXXXX methods above.
1341  ///
1342  /// There are some specializations of this member template listed
1343  /// immediately following this class.
1344  template <typename T> const T *getAs() const;
1345
1346  /// A variant of getAs<> for array types which silently discards
1347  /// qualifiers from the outermost type.
1348  const ArrayType *getAsArrayTypeUnsafe() const;
1349
1350  /// Member-template castAs<specific type>.  Look through sugar for
1351  /// the underlying instance of <specific type>.
1352  ///
1353  /// This method has the same relationship to getAs<T> as cast<T> has
1354  /// to dyn_cast<T>; which is to say, the underlying type *must*
1355  /// have the intended type, and this method will never return null.
1356  template <typename T> const T *castAs() const;
1357
1358  /// A variant of castAs<> for array type which silently discards
1359  /// qualifiers from the outermost type.
1360  const ArrayType *castAsArrayTypeUnsafe() const;
1361
1362  /// getBaseElementTypeUnsafe - Get the base element type of this
1363  /// type, potentially discarding type qualifiers.  This method
1364  /// should never be used when type qualifiers are meaningful.
1365  const Type *getBaseElementTypeUnsafe() const;
1366
1367  /// getArrayElementTypeNoTypeQual - If this is an array type, return the
1368  /// element type of the array, potentially with type qualifiers missing.
1369  /// This method should never be used when type qualifiers are meaningful.
1370  const Type *getArrayElementTypeNoTypeQual() const;
1371
1372  /// getPointeeType - If this is a pointer, ObjC object pointer, or block
1373  /// pointer, this returns the respective pointee.
1374  QualType getPointeeType() const;
1375
1376  /// getUnqualifiedDesugaredType() - Return the specified type with
1377  /// any "sugar" removed from the type, removing any typedefs,
1378  /// typeofs, etc., as well as any qualifiers.
1379  const Type *getUnqualifiedDesugaredType() const;
1380
1381  /// More type predicates useful for type checking/promotion
1382  bool isPromotableIntegerType() const; // C99 6.3.1.1p2
1383
1384  /// isSignedIntegerType - Return true if this is an integer type that is
1385  /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
1386  /// an enum decl which has a signed representation, or a vector of signed
1387  /// integer element type.
1388  bool isSignedIntegerType() const;
1389
1390  /// isUnsignedIntegerType - Return true if this is an integer type that is
1391  /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
1392  /// decl which has an unsigned representation, or a vector of unsigned integer
1393  /// element type.
1394  bool isUnsignedIntegerType() const;
1395
1396  /// isConstantSizeType - Return true if this is not a variable sized type,
1397  /// according to the rules of C99 6.7.5p3.  It is not legal to call this on
1398  /// incomplete types.
1399  bool isConstantSizeType() const;
1400
1401  /// isSpecifierType - Returns true if this type can be represented by some
1402  /// set of type specifiers.
1403  bool isSpecifierType() const;
1404
1405  /// \brief Determine the linkage of this type.
1406  Linkage getLinkage() const;
1407
1408  /// \brief Determine the visibility of this type.
1409  Visibility getVisibility() const;
1410
1411  /// \brief Determine the linkage and visibility of this type.
1412  std::pair<Linkage,Visibility> getLinkageAndVisibility() const;
1413
1414  /// \brief Note that the linkage is no longer known.
1415  void ClearLinkageCache();
1416
1417  const char *getTypeClassName() const;
1418
1419  QualType getCanonicalTypeInternal() const {
1420    return CanonicalType;
1421  }
1422  CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
1423  void dump() const;
1424  static bool classof(const Type *) { return true; }
1425
1426  friend class ASTReader;
1427  friend class ASTWriter;
1428};
1429
1430template <> inline const TypedefType *Type::getAs() const {
1431  return dyn_cast<TypedefType>(this);
1432}
1433
1434// We can do canonical leaf types faster, because we don't have to
1435// worry about preserving child type decoration.
1436#define TYPE(Class, Base)
1437#define LEAF_TYPE(Class) \
1438template <> inline const Class##Type *Type::getAs() const { \
1439  return dyn_cast<Class##Type>(CanonicalType); \
1440} \
1441template <> inline const Class##Type *Type::castAs() const { \
1442  return cast<Class##Type>(CanonicalType); \
1443}
1444#include "clang/AST/TypeNodes.def"
1445
1446
1447/// BuiltinType - This class is used for builtin types like 'int'.  Builtin
1448/// types are always canonical and have a literal name field.
1449class BuiltinType : public Type {
1450public:
1451  enum Kind {
1452    Void,
1453
1454    Bool,     // This is bool and/or _Bool.
1455    Char_U,   // This is 'char' for targets where char is unsigned.
1456    UChar,    // This is explicitly qualified unsigned char.
1457    WChar_U,  // This is 'wchar_t' for C++, when unsigned.
1458    Char16,   // This is 'char16_t' for C++.
1459    Char32,   // This is 'char32_t' for C++.
1460    UShort,
1461    UInt,
1462    ULong,
1463    ULongLong,
1464    UInt128,  // __uint128_t
1465
1466    Char_S,   // This is 'char' for targets where char is signed.
1467    SChar,    // This is explicitly qualified signed char.
1468    WChar_S,  // This is 'wchar_t' for C++, when signed.
1469    Short,
1470    Int,
1471    Long,
1472    LongLong,
1473    Int128,   // __int128_t
1474
1475    Float, Double, LongDouble,
1476
1477    NullPtr,  // This is the type of C++0x 'nullptr'.
1478
1479    /// This represents the type of an expression whose type is
1480    /// totally unknown, e.g. 'T::foo'.  It is permitted for this to
1481    /// appear in situations where the structure of the type is
1482    /// theoretically deducible.
1483    Dependent,
1484
1485    Overload,  // This represents the type of an overloaded function declaration.
1486
1487    /// The primitive Objective C 'id' type.  The type pointed to by the
1488    /// user-visible 'id' type.  Only ever shows up in an AST as the base
1489    /// type of an ObjCObjectType.
1490    ObjCId,
1491
1492    /// The primitive Objective C 'Class' type.  The type pointed to by the
1493    /// user-visible 'Class' type.  Only ever shows up in an AST as the
1494    /// base type of an ObjCObjectType.
1495    ObjCClass,
1496
1497    ObjCSel    // This represents the ObjC 'SEL' type.
1498  };
1499
1500public:
1501  BuiltinType(Kind K)
1502    : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
1503           /*VariablyModified=*/false,
1504           /*Unexpanded paramter pack=*/false) {
1505    BuiltinTypeBits.Kind = K;
1506  }
1507
1508  Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
1509  const char *getName(const LangOptions &LO) const;
1510
1511  bool isSugared() const { return false; }
1512  QualType desugar() const { return QualType(this, 0); }
1513
1514  bool isInteger() const {
1515    return getKind() >= Bool && getKind() <= Int128;
1516  }
1517
1518  bool isSignedInteger() const {
1519    return getKind() >= Char_S && getKind() <= Int128;
1520  }
1521
1522  bool isUnsignedInteger() const {
1523    return getKind() >= Bool && getKind() <= UInt128;
1524  }
1525
1526  bool isFloatingPoint() const {
1527    return getKind() >= Float && getKind() <= LongDouble;
1528  }
1529
1530  /// Determines whether this type is a "forbidden" placeholder type,
1531  /// i.e. a type which cannot appear in arbitrary positions in a
1532  /// fully-formed expression.
1533  bool isPlaceholderType() const {
1534    return getKind() == Overload;
1535  }
1536
1537  static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
1538  static bool classof(const BuiltinType *) { return true; }
1539};
1540
1541/// ComplexType - C99 6.2.5p11 - Complex values.  This supports the C99 complex
1542/// types (_Complex float etc) as well as the GCC integer complex extensions.
1543///
1544class ComplexType : public Type, public llvm::FoldingSetNode {
1545  QualType ElementType;
1546  ComplexType(QualType Element, QualType CanonicalPtr) :
1547    Type(Complex, CanonicalPtr, Element->isDependentType(),
1548         Element->isVariablyModifiedType(),
1549         Element->containsUnexpandedParameterPack()),
1550    ElementType(Element) {
1551  }
1552  friend class ASTContext;  // ASTContext creates these.
1553
1554public:
1555  QualType getElementType() const { return ElementType; }
1556
1557  bool isSugared() const { return false; }
1558  QualType desugar() const { return QualType(this, 0); }
1559
1560  void Profile(llvm::FoldingSetNodeID &ID) {
1561    Profile(ID, getElementType());
1562  }
1563  static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
1564    ID.AddPointer(Element.getAsOpaquePtr());
1565  }
1566
1567  static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
1568  static bool classof(const ComplexType *) { return true; }
1569};
1570
1571/// ParenType - Sugar for parentheses used when specifying types.
1572///
1573class ParenType : public Type, public llvm::FoldingSetNode {
1574  QualType Inner;
1575
1576  ParenType(QualType InnerType, QualType CanonType) :
1577    Type(Paren, CanonType, InnerType->isDependentType(),
1578         InnerType->isVariablyModifiedType(),
1579         InnerType->containsUnexpandedParameterPack()),
1580    Inner(InnerType) {
1581  }
1582  friend class ASTContext;  // ASTContext creates these.
1583
1584public:
1585
1586  QualType getInnerType() const { return Inner; }
1587
1588  bool isSugared() const { return true; }
1589  QualType desugar() const { return getInnerType(); }
1590
1591  void Profile(llvm::FoldingSetNodeID &ID) {
1592    Profile(ID, getInnerType());
1593  }
1594  static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
1595    Inner.Profile(ID);
1596  }
1597
1598  static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
1599  static bool classof(const ParenType *) { return true; }
1600};
1601
1602/// PointerType - C99 6.7.5.1 - Pointer Declarators.
1603///
1604class PointerType : public Type, public llvm::FoldingSetNode {
1605  QualType PointeeType;
1606
1607  PointerType(QualType Pointee, QualType CanonicalPtr) :
1608    Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
1609         Pointee->isVariablyModifiedType(),
1610         Pointee->containsUnexpandedParameterPack()),
1611    PointeeType(Pointee) {
1612  }
1613  friend class ASTContext;  // ASTContext creates these.
1614
1615public:
1616
1617  QualType getPointeeType() const { return PointeeType; }
1618
1619  bool isSugared() const { return false; }
1620  QualType desugar() const { return QualType(this, 0); }
1621
1622  void Profile(llvm::FoldingSetNodeID &ID) {
1623    Profile(ID, getPointeeType());
1624  }
1625  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
1626    ID.AddPointer(Pointee.getAsOpaquePtr());
1627  }
1628
1629  static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
1630  static bool classof(const PointerType *) { return true; }
1631};
1632
1633/// BlockPointerType - pointer to a block type.
1634/// This type is to represent types syntactically represented as
1635/// "void (^)(int)", etc. Pointee is required to always be a function type.
1636///
1637class BlockPointerType : public Type, public llvm::FoldingSetNode {
1638  QualType PointeeType;  // Block is some kind of pointer type
1639  BlockPointerType(QualType Pointee, QualType CanonicalCls) :
1640    Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
1641         Pointee->isVariablyModifiedType(),
1642         Pointee->containsUnexpandedParameterPack()),
1643    PointeeType(Pointee) {
1644  }
1645  friend class ASTContext;  // ASTContext creates these.
1646
1647public:
1648
1649  // Get the pointee type. Pointee is required to always be a function type.
1650  QualType getPointeeType() const { return PointeeType; }
1651
1652  bool isSugared() const { return false; }
1653  QualType desugar() const { return QualType(this, 0); }
1654
1655  void Profile(llvm::FoldingSetNodeID &ID) {
1656      Profile(ID, getPointeeType());
1657  }
1658  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
1659      ID.AddPointer(Pointee.getAsOpaquePtr());
1660  }
1661
1662  static bool classof(const Type *T) {
1663    return T->getTypeClass() == BlockPointer;
1664  }
1665  static bool classof(const BlockPointerType *) { return true; }
1666};
1667
1668/// ReferenceType - Base for LValueReferenceType and RValueReferenceType
1669///
1670class ReferenceType : public Type, public llvm::FoldingSetNode {
1671  QualType PointeeType;
1672
1673protected:
1674  ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
1675                bool SpelledAsLValue) :
1676    Type(tc, CanonicalRef, Referencee->isDependentType(),
1677         Referencee->isVariablyModifiedType(),
1678         Referencee->containsUnexpandedParameterPack()),
1679    PointeeType(Referencee)
1680  {
1681    ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
1682    ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
1683  }
1684
1685public:
1686  bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
1687  bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
1688
1689  QualType getPointeeTypeAsWritten() const { return PointeeType; }
1690  QualType getPointeeType() const {
1691    // FIXME: this might strip inner qualifiers; okay?
1692    const ReferenceType *T = this;
1693    while (T->isInnerRef())
1694      T = T->PointeeType->castAs<ReferenceType>();
1695    return T->PointeeType;
1696  }
1697
1698  void Profile(llvm::FoldingSetNodeID &ID) {
1699    Profile(ID, PointeeType, isSpelledAsLValue());
1700  }
1701  static void Profile(llvm::FoldingSetNodeID &ID,
1702                      QualType Referencee,
1703                      bool SpelledAsLValue) {
1704    ID.AddPointer(Referencee.getAsOpaquePtr());
1705    ID.AddBoolean(SpelledAsLValue);
1706  }
1707
1708  static bool classof(const Type *T) {
1709    return T->getTypeClass() == LValueReference ||
1710           T->getTypeClass() == RValueReference;
1711  }
1712  static bool classof(const ReferenceType *) { return true; }
1713};
1714
1715/// LValueReferenceType - C++ [dcl.ref] - Lvalue reference
1716///
1717class LValueReferenceType : public ReferenceType {
1718  LValueReferenceType(QualType Referencee, QualType CanonicalRef,
1719                      bool SpelledAsLValue) :
1720    ReferenceType(LValueReference, Referencee, CanonicalRef, SpelledAsLValue)
1721  {}
1722  friend class ASTContext; // ASTContext creates these
1723public:
1724  bool isSugared() const { return false; }
1725  QualType desugar() const { return QualType(this, 0); }
1726
1727  static bool classof(const Type *T) {
1728    return T->getTypeClass() == LValueReference;
1729  }
1730  static bool classof(const LValueReferenceType *) { return true; }
1731};
1732
1733/// RValueReferenceType - C++0x [dcl.ref] - Rvalue reference
1734///
1735class RValueReferenceType : public ReferenceType {
1736  RValueReferenceType(QualType Referencee, QualType CanonicalRef) :
1737    ReferenceType(RValueReference, Referencee, CanonicalRef, false) {
1738  }
1739  friend class ASTContext; // ASTContext creates these
1740public:
1741  bool isSugared() const { return false; }
1742  QualType desugar() const { return QualType(this, 0); }
1743
1744  static bool classof(const Type *T) {
1745    return T->getTypeClass() == RValueReference;
1746  }
1747  static bool classof(const RValueReferenceType *) { return true; }
1748};
1749
1750/// MemberPointerType - C++ 8.3.3 - Pointers to members
1751///
1752class MemberPointerType : public Type, public llvm::FoldingSetNode {
1753  QualType PointeeType;
1754  /// The class of which the pointee is a member. Must ultimately be a
1755  /// RecordType, but could be a typedef or a template parameter too.
1756  const Type *Class;
1757
1758  MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) :
1759    Type(MemberPointer, CanonicalPtr,
1760         Cls->isDependentType() || Pointee->isDependentType(),
1761         Pointee->isVariablyModifiedType(),
1762         (Cls->containsUnexpandedParameterPack() ||
1763          Pointee->containsUnexpandedParameterPack())),
1764    PointeeType(Pointee), Class(Cls) {
1765  }
1766  friend class ASTContext; // ASTContext creates these.
1767
1768public:
1769  QualType getPointeeType() const { return PointeeType; }
1770
1771  /// Returns true if the member type (i.e. the pointee type) is a
1772  /// function type rather than a data-member type.
1773  bool isMemberFunctionPointer() const {
1774    return PointeeType->isFunctionProtoType();
1775  }
1776
1777  /// Returns true if the member type (i.e. the pointee type) is a
1778  /// data type rather than a function type.
1779  bool isMemberDataPointer() const {
1780    return !PointeeType->isFunctionProtoType();
1781  }
1782
1783  const Type *getClass() const { return Class; }
1784
1785  bool isSugared() const { return false; }
1786  QualType desugar() const { return QualType(this, 0); }
1787
1788  void Profile(llvm::FoldingSetNodeID &ID) {
1789    Profile(ID, getPointeeType(), getClass());
1790  }
1791  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
1792                      const Type *Class) {
1793    ID.AddPointer(Pointee.getAsOpaquePtr());
1794    ID.AddPointer(Class);
1795  }
1796
1797  static bool classof(const Type *T) {
1798    return T->getTypeClass() == MemberPointer;
1799  }
1800  static bool classof(const MemberPointerType *) { return true; }
1801};
1802
1803/// ArrayType - C99 6.7.5.2 - Array Declarators.
1804///
1805class ArrayType : public Type, public llvm::FoldingSetNode {
1806public:
1807  /// ArraySizeModifier - Capture whether this is a normal array (e.g. int X[4])
1808  /// an array with a static size (e.g. int X[static 4]), or an array
1809  /// with a star size (e.g. int X[*]).
1810  /// 'static' is only allowed on function parameters.
1811  enum ArraySizeModifier {
1812    Normal, Static, Star
1813  };
1814private:
1815  /// ElementType - The element type of the array.
1816  QualType ElementType;
1817
1818protected:
1819  // C++ [temp.dep.type]p1:
1820  //   A type is dependent if it is...
1821  //     - an array type constructed from any dependent type or whose
1822  //       size is specified by a constant expression that is
1823  //       value-dependent,
1824  ArrayType(TypeClass tc, QualType et, QualType can,
1825            ArraySizeModifier sm, unsigned tq,
1826            bool ContainsUnexpandedParameterPack)
1827    : Type(tc, can, et->isDependentType() || tc == DependentSizedArray,
1828           (tc == VariableArray || et->isVariablyModifiedType()),
1829           ContainsUnexpandedParameterPack),
1830      ElementType(et) {
1831    ArrayTypeBits.IndexTypeQuals = tq;
1832    ArrayTypeBits.SizeModifier = sm;
1833  }
1834
1835  friend class ASTContext;  // ASTContext creates these.
1836
1837public:
1838  QualType getElementType() const { return ElementType; }
1839  ArraySizeModifier getSizeModifier() const {
1840    return ArraySizeModifier(ArrayTypeBits.SizeModifier);
1841  }
1842  Qualifiers getIndexTypeQualifiers() const {
1843    return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
1844  }
1845  unsigned getIndexTypeCVRQualifiers() const {
1846    return ArrayTypeBits.IndexTypeQuals;
1847  }
1848
1849  static bool classof(const Type *T) {
1850    return T->getTypeClass() == ConstantArray ||
1851           T->getTypeClass() == VariableArray ||
1852           T->getTypeClass() == IncompleteArray ||
1853           T->getTypeClass() == DependentSizedArray;
1854  }
1855  static bool classof(const ArrayType *) { return true; }
1856};
1857
1858/// ConstantArrayType - This class represents the canonical version of
1859/// C arrays with a specified constant size.  For example, the canonical
1860/// type for 'int A[4 + 4*100]' is a ConstantArrayType where the element
1861/// type is 'int' and the size is 404.
1862class ConstantArrayType : public ArrayType {
1863  llvm::APInt Size; // Allows us to unique the type.
1864
1865  ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
1866                    ArraySizeModifier sm, unsigned tq)
1867    : ArrayType(ConstantArray, et, can, sm, tq,
1868                et->containsUnexpandedParameterPack()),
1869      Size(size) {}
1870protected:
1871  ConstantArrayType(TypeClass tc, QualType et, QualType can,
1872                    const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
1873    : ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()),
1874      Size(size) {}
1875  friend class ASTContext;  // ASTContext creates these.
1876public:
1877  const llvm::APInt &getSize() const { return Size; }
1878  bool isSugared() const { return false; }
1879  QualType desugar() const { return QualType(this, 0); }
1880
1881
1882  /// \brief Determine the number of bits required to address a member of
1883  // an array with the given element type and number of elements.
1884  static unsigned getNumAddressingBits(ASTContext &Context,
1885                                       QualType ElementType,
1886                                       const llvm::APInt &NumElements);
1887
1888  /// \brief Determine the maximum number of active bits that an array's size
1889  /// can require, which limits the maximum size of the array.
1890  static unsigned getMaxSizeBits(ASTContext &Context);
1891
1892  void Profile(llvm::FoldingSetNodeID &ID) {
1893    Profile(ID, getElementType(), getSize(),
1894            getSizeModifier(), getIndexTypeCVRQualifiers());
1895  }
1896  static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
1897                      const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
1898                      unsigned TypeQuals) {
1899    ID.AddPointer(ET.getAsOpaquePtr());
1900    ID.AddInteger(ArraySize.getZExtValue());
1901    ID.AddInteger(SizeMod);
1902    ID.AddInteger(TypeQuals);
1903  }
1904  static bool classof(const Type *T) {
1905    return T->getTypeClass() == ConstantArray;
1906  }
1907  static bool classof(const ConstantArrayType *) { return true; }
1908};
1909
1910/// IncompleteArrayType - This class represents C arrays with an unspecified
1911/// size.  For example 'int A[]' has an IncompleteArrayType where the element
1912/// type is 'int' and the size is unspecified.
1913class IncompleteArrayType : public ArrayType {
1914
1915  IncompleteArrayType(QualType et, QualType can,
1916                      ArraySizeModifier sm, unsigned tq)
1917    : ArrayType(IncompleteArray, et, can, sm, tq,
1918                et->containsUnexpandedParameterPack()) {}
1919  friend class ASTContext;  // ASTContext creates these.
1920public:
1921  bool isSugared() const { return false; }
1922  QualType desugar() const { return QualType(this, 0); }
1923
1924  static bool classof(const Type *T) {
1925    return T->getTypeClass() == IncompleteArray;
1926  }
1927  static bool classof(const IncompleteArrayType *) { return true; }
1928
1929  friend class StmtIteratorBase;
1930
1931  void Profile(llvm::FoldingSetNodeID &ID) {
1932    Profile(ID, getElementType(), getSizeModifier(),
1933            getIndexTypeCVRQualifiers());
1934  }
1935
1936  static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
1937                      ArraySizeModifier SizeMod, unsigned TypeQuals) {
1938    ID.AddPointer(ET.getAsOpaquePtr());
1939    ID.AddInteger(SizeMod);
1940    ID.AddInteger(TypeQuals);
1941  }
1942};
1943
1944/// VariableArrayType - This class represents C arrays with a specified size
1945/// which is not an integer-constant-expression.  For example, 'int s[x+foo()]'.
1946/// Since the size expression is an arbitrary expression, we store it as such.
1947///
1948/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
1949/// should not be: two lexically equivalent variable array types could mean
1950/// different things, for example, these variables do not have the same type
1951/// dynamically:
1952///
1953/// void foo(int x) {
1954///   int Y[x];
1955///   ++x;
1956///   int Z[x];
1957/// }
1958///
1959class VariableArrayType : public ArrayType {
1960  /// SizeExpr - An assignment expression. VLA's are only permitted within
1961  /// a function block.
1962  Stmt *SizeExpr;
1963  /// Brackets - The left and right array brackets.
1964  SourceRange Brackets;
1965
1966  VariableArrayType(QualType et, QualType can, Expr *e,
1967                    ArraySizeModifier sm, unsigned tq,
1968                    SourceRange brackets)
1969    : ArrayType(VariableArray, et, can, sm, tq,
1970                et->containsUnexpandedParameterPack()),
1971      SizeExpr((Stmt*) e), Brackets(brackets) {}
1972  friend class ASTContext;  // ASTContext creates these.
1973
1974public:
1975  Expr *getSizeExpr() const {
1976    // We use C-style casts instead of cast<> here because we do not wish
1977    // to have a dependency of Type.h on Stmt.h/Expr.h.
1978    return (Expr*) SizeExpr;
1979  }
1980  SourceRange getBracketsRange() const { return Brackets; }
1981  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
1982  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
1983
1984  bool isSugared() const { return false; }
1985  QualType desugar() const { return QualType(this, 0); }
1986
1987  static bool classof(const Type *T) {
1988    return T->getTypeClass() == VariableArray;
1989  }
1990  static bool classof(const VariableArrayType *) { return true; }
1991
1992  friend class StmtIteratorBase;
1993
1994  void Profile(llvm::FoldingSetNodeID &ID) {
1995    assert(0 && "Cannnot unique VariableArrayTypes.");
1996  }
1997};
1998
1999/// DependentSizedArrayType - This type represents an array type in
2000/// C++ whose size is a value-dependent expression. For example:
2001///
2002/// \code
2003/// template<typename T, int Size>
2004/// class array {
2005///   T data[Size];
2006/// };
2007/// \endcode
2008///
2009/// For these types, we won't actually know what the array bound is
2010/// until template instantiation occurs, at which point this will
2011/// become either a ConstantArrayType or a VariableArrayType.
2012class DependentSizedArrayType : public ArrayType {
2013  const ASTContext &Context;
2014
2015  /// \brief An assignment expression that will instantiate to the
2016  /// size of the array.
2017  ///
2018  /// The expression itself might be NULL, in which case the array
2019  /// type will have its size deduced from an initializer.
2020  Stmt *SizeExpr;
2021
2022  /// Brackets - The left and right array brackets.
2023  SourceRange Brackets;
2024
2025  DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
2026                          Expr *e, ArraySizeModifier sm, unsigned tq,
2027                          SourceRange brackets);
2028
2029  friend class ASTContext;  // ASTContext creates these.
2030
2031public:
2032  Expr *getSizeExpr() const {
2033    // We use C-style casts instead of cast<> here because we do not wish
2034    // to have a dependency of Type.h on Stmt.h/Expr.h.
2035    return (Expr*) SizeExpr;
2036  }
2037  SourceRange getBracketsRange() const { return Brackets; }
2038  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2039  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2040
2041  bool isSugared() const { return false; }
2042  QualType desugar() const { return QualType(this, 0); }
2043
2044  static bool classof(const Type *T) {
2045    return T->getTypeClass() == DependentSizedArray;
2046  }
2047  static bool classof(const DependentSizedArrayType *) { return true; }
2048
2049  friend class StmtIteratorBase;
2050
2051
2052  void Profile(llvm::FoldingSetNodeID &ID) {
2053    Profile(ID, Context, getElementType(),
2054            getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
2055  }
2056
2057  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2058                      QualType ET, ArraySizeModifier SizeMod,
2059                      unsigned TypeQuals, Expr *E);
2060};
2061
2062/// DependentSizedExtVectorType - This type represent an extended vector type
2063/// where either the type or size is dependent. For example:
2064/// @code
2065/// template<typename T, int Size>
2066/// class vector {
2067///   typedef T __attribute__((ext_vector_type(Size))) type;
2068/// }
2069/// @endcode
2070class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
2071  const ASTContext &Context;
2072  Expr *SizeExpr;
2073  /// ElementType - The element type of the array.
2074  QualType ElementType;
2075  SourceLocation loc;
2076
2077  DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
2078                              QualType can, Expr *SizeExpr, SourceLocation loc);
2079
2080  friend class ASTContext;
2081
2082public:
2083  Expr *getSizeExpr() const { return SizeExpr; }
2084  QualType getElementType() const { return ElementType; }
2085  SourceLocation getAttributeLoc() const { return loc; }
2086
2087  bool isSugared() const { return false; }
2088  QualType desugar() const { return QualType(this, 0); }
2089
2090  static bool classof(const Type *T) {
2091    return T->getTypeClass() == DependentSizedExtVector;
2092  }
2093  static bool classof(const DependentSizedExtVectorType *) { return true; }
2094
2095  void Profile(llvm::FoldingSetNodeID &ID) {
2096    Profile(ID, Context, getElementType(), getSizeExpr());
2097  }
2098
2099  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2100                      QualType ElementType, Expr *SizeExpr);
2101};
2102
2103
2104/// VectorType - GCC generic vector type. This type is created using
2105/// __attribute__((vector_size(n)), where "n" specifies the vector size in
2106/// bytes; or from an Altivec __vector or vector declaration.
2107/// Since the constructor takes the number of vector elements, the
2108/// client is responsible for converting the size into the number of elements.
2109class VectorType : public Type, public llvm::FoldingSetNode {
2110public:
2111  enum VectorKind {
2112    GenericVector,  // not a target-specific vector type
2113    AltiVecVector,  // is AltiVec vector
2114    AltiVecPixel,   // is AltiVec 'vector Pixel'
2115    AltiVecBool,    // is AltiVec 'vector bool ...'
2116    NeonVector,     // is ARM Neon vector
2117    NeonPolyVector  // is ARM Neon polynomial vector
2118  };
2119protected:
2120  /// ElementType - The element type of the vector.
2121  QualType ElementType;
2122
2123  VectorType(QualType vecType, unsigned nElements, QualType canonType,
2124             VectorKind vecKind);
2125
2126  VectorType(TypeClass tc, QualType vecType, unsigned nElements,
2127             QualType canonType, VectorKind vecKind);
2128
2129  friend class ASTContext;  // ASTContext creates these.
2130
2131public:
2132
2133  QualType getElementType() const { return ElementType; }
2134  unsigned getNumElements() const { return VectorTypeBits.NumElements; }
2135
2136  bool isSugared() const { return false; }
2137  QualType desugar() const { return QualType(this, 0); }
2138
2139  VectorKind getVectorKind() const {
2140    return VectorKind(VectorTypeBits.VecKind);
2141  }
2142
2143  void Profile(llvm::FoldingSetNodeID &ID) {
2144    Profile(ID, getElementType(), getNumElements(),
2145            getTypeClass(), getVectorKind());
2146  }
2147  static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
2148                      unsigned NumElements, TypeClass TypeClass,
2149                      VectorKind VecKind) {
2150    ID.AddPointer(ElementType.getAsOpaquePtr());
2151    ID.AddInteger(NumElements);
2152    ID.AddInteger(TypeClass);
2153    ID.AddInteger(VecKind);
2154  }
2155
2156  static bool classof(const Type *T) {
2157    return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
2158  }
2159  static bool classof(const VectorType *) { return true; }
2160};
2161
2162/// ExtVectorType - Extended vector type. This type is created using
2163/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
2164/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
2165/// class enables syntactic extensions, like Vector Components for accessing
2166/// points, colors, and textures (modeled after OpenGL Shading Language).
2167class ExtVectorType : public VectorType {
2168  ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) :
2169    VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
2170  friend class ASTContext;  // ASTContext creates these.
2171public:
2172  static int getPointAccessorIdx(char c) {
2173    switch (c) {
2174    default: return -1;
2175    case 'x': case 'r': return 0;
2176    case 'y': case 'g': return 1;
2177    case 'z': case 'b': return 2;
2178    case 'w': case 'a': return 3;
2179    }
2180  }
2181  static int getNumericAccessorIdx(char c) {
2182    switch (c) {
2183      default: return -1;
2184      case '0': return 0;
2185      case '1': return 1;
2186      case '2': return 2;
2187      case '3': return 3;
2188      case '4': return 4;
2189      case '5': return 5;
2190      case '6': return 6;
2191      case '7': return 7;
2192      case '8': return 8;
2193      case '9': return 9;
2194      case 'A':
2195      case 'a': return 10;
2196      case 'B':
2197      case 'b': return 11;
2198      case 'C':
2199      case 'c': return 12;
2200      case 'D':
2201      case 'd': return 13;
2202      case 'E':
2203      case 'e': return 14;
2204      case 'F':
2205      case 'f': return 15;
2206    }
2207  }
2208
2209  static int getAccessorIdx(char c) {
2210    if (int idx = getPointAccessorIdx(c)+1) return idx-1;
2211    return getNumericAccessorIdx(c);
2212  }
2213
2214  bool isAccessorWithinNumElements(char c) const {
2215    if (int idx = getAccessorIdx(c)+1)
2216      return unsigned(idx-1) < getNumElements();
2217    return false;
2218  }
2219  bool isSugared() const { return false; }
2220  QualType desugar() const { return QualType(this, 0); }
2221
2222  static bool classof(const Type *T) {
2223    return T->getTypeClass() == ExtVector;
2224  }
2225  static bool classof(const ExtVectorType *) { return true; }
2226};
2227
2228/// FunctionType - C99 6.7.5.3 - Function Declarators.  This is the common base
2229/// class of FunctionNoProtoType and FunctionProtoType.
2230///
2231class FunctionType : public Type {
2232  // The type returned by the function.
2233  QualType ResultType;
2234
2235 public:
2236  /// ExtInfo - A class which abstracts out some details necessary for
2237  /// making a call.
2238  ///
2239  /// It is not actually used directly for storing this information in
2240  /// a FunctionType, although FunctionType does currently use the
2241  /// same bit-pattern.
2242  ///
2243  // If you add a field (say Foo), other than the obvious places (both,
2244  // constructors, compile failures), what you need to update is
2245  // * Operator==
2246  // * getFoo
2247  // * withFoo
2248  // * functionType. Add Foo, getFoo.
2249  // * ASTContext::getFooType
2250  // * ASTContext::mergeFunctionTypes
2251  // * FunctionNoProtoType::Profile
2252  // * FunctionProtoType::Profile
2253  // * TypePrinter::PrintFunctionProto
2254  // * AST read and write
2255  // * Codegen
2256  class ExtInfo {
2257    // Feel free to rearrange or add bits, but if you go over 8,
2258    // you'll need to adjust both the Bits field below and
2259    // Type::FunctionTypeBitfields.
2260
2261    //   |  CC  |noreturn|regparm
2262    //   |0 .. 2|   3    |4 ..  6
2263    enum { CallConvMask = 0x7 };
2264    enum { NoReturnMask = 0x8 };
2265    enum { RegParmMask = ~(CallConvMask | NoReturnMask),
2266           RegParmOffset = 4 };
2267
2268    unsigned char Bits;
2269
2270    ExtInfo(unsigned Bits) : Bits(static_cast<unsigned char>(Bits)) {}
2271
2272    friend class FunctionType;
2273
2274   public:
2275    // Constructor with no defaults. Use this when you know that you
2276    // have all the elements (when reading an AST file for example).
2277    ExtInfo(bool noReturn, unsigned regParm, CallingConv cc) {
2278      Bits = ((unsigned) cc) |
2279             (noReturn ? NoReturnMask : 0) |
2280             (regParm << RegParmOffset);
2281    }
2282
2283    // Constructor with all defaults. Use when for example creating a
2284    // function know to use defaults.
2285    ExtInfo() : Bits(0) {}
2286
2287    bool getNoReturn() const { return Bits & NoReturnMask; }
2288    unsigned getRegParm() const { return Bits >> RegParmOffset; }
2289    CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
2290
2291    bool operator==(ExtInfo Other) const {
2292      return Bits == Other.Bits;
2293    }
2294    bool operator!=(ExtInfo Other) const {
2295      return Bits != Other.Bits;
2296    }
2297
2298    // Note that we don't have setters. That is by design, use
2299    // the following with methods instead of mutating these objects.
2300
2301    ExtInfo withNoReturn(bool noReturn) const {
2302      if (noReturn)
2303        return ExtInfo(Bits | NoReturnMask);
2304      else
2305        return ExtInfo(Bits & ~NoReturnMask);
2306    }
2307
2308    ExtInfo withRegParm(unsigned RegParm) const {
2309      return ExtInfo((Bits & ~RegParmMask) | (RegParm << RegParmOffset));
2310    }
2311
2312    ExtInfo withCallingConv(CallingConv cc) const {
2313      return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
2314    }
2315
2316    void Profile(llvm::FoldingSetNodeID &ID) const {
2317      ID.AddInteger(Bits);
2318    }
2319  };
2320
2321protected:
2322  FunctionType(TypeClass tc, QualType res, bool variadic,
2323               unsigned typeQuals, RefQualifierKind RefQualifier,
2324               QualType Canonical, bool Dependent,
2325               bool VariablyModified, bool ContainsUnexpandedParameterPack,
2326               ExtInfo Info)
2327    : Type(tc, Canonical, Dependent, VariablyModified,
2328           ContainsUnexpandedParameterPack),
2329      ResultType(res) {
2330    FunctionTypeBits.ExtInfo = Info.Bits;
2331    FunctionTypeBits.Variadic = variadic;
2332    FunctionTypeBits.TypeQuals = typeQuals;
2333    FunctionTypeBits.RefQualifier = static_cast<unsigned>(RefQualifier);
2334  }
2335  bool isVariadic() const { return FunctionTypeBits.Variadic; }
2336  unsigned getTypeQuals() const { return FunctionTypeBits.TypeQuals; }
2337
2338  RefQualifierKind getRefQualifier() const {
2339    return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
2340  }
2341
2342public:
2343
2344  QualType getResultType() const { return ResultType; }
2345
2346  unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
2347  bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
2348  CallingConv getCallConv() const { return getExtInfo().getCC(); }
2349  ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
2350
2351  /// \brief Determine the type of an expression that calls a function of
2352  /// this type.
2353  QualType getCallResultType(ASTContext &Context) const {
2354    return getResultType().getNonLValueExprType(Context);
2355  }
2356
2357  static llvm::StringRef getNameForCallConv(CallingConv CC);
2358
2359  static bool classof(const Type *T) {
2360    return T->getTypeClass() == FunctionNoProto ||
2361           T->getTypeClass() == FunctionProto;
2362  }
2363  static bool classof(const FunctionType *) { return true; }
2364};
2365
2366/// FunctionNoProtoType - Represents a K&R-style 'int foo()' function, which has
2367/// no information available about its arguments.
2368class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
2369  FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
2370    : FunctionType(FunctionNoProto, Result, false, 0, RQ_None, Canonical,
2371                   /*Dependent=*/false, Result->isVariablyModifiedType(),
2372                   /*ContainsUnexpandedParameterPack=*/false, Info) {}
2373
2374  friend class ASTContext;  // ASTContext creates these.
2375
2376public:
2377  // No additional state past what FunctionType provides.
2378
2379  bool isSugared() const { return false; }
2380  QualType desugar() const { return QualType(this, 0); }
2381
2382  void Profile(llvm::FoldingSetNodeID &ID) {
2383    Profile(ID, getResultType(), getExtInfo());
2384  }
2385  static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
2386                      ExtInfo Info) {
2387    Info.Profile(ID);
2388    ID.AddPointer(ResultType.getAsOpaquePtr());
2389  }
2390
2391  static bool classof(const Type *T) {
2392    return T->getTypeClass() == FunctionNoProto;
2393  }
2394  static bool classof(const FunctionNoProtoType *) { return true; }
2395};
2396
2397/// FunctionProtoType - Represents a prototype with argument type info, e.g.
2398/// 'int foo(int)' or 'int foo(void)'.  'void' is represented as having no
2399/// arguments, not as having a single void argument. Such a type can have an
2400/// exception specification, but this specification is not part of the canonical
2401/// type.
2402class FunctionProtoType : public FunctionType, public llvm::FoldingSetNode {
2403public:
2404  /// ExtProtoInfo - Extra information about a function prototype.
2405  struct ExtProtoInfo {
2406    ExtProtoInfo() :
2407      Variadic(false), ExceptionSpecType(EST_None), TypeQuals(0),
2408      RefQualifier(RQ_None), NumExceptions(0), Exceptions(0), NoexceptExpr(0) {}
2409
2410    FunctionType::ExtInfo ExtInfo;
2411    bool Variadic;
2412    ExceptionSpecificationType ExceptionSpecType;
2413    unsigned char TypeQuals;
2414    RefQualifierKind RefQualifier;
2415    unsigned NumExceptions;
2416    const QualType *Exceptions;
2417    Expr *NoexceptExpr;
2418  };
2419
2420private:
2421  /// \brief Determine whether there are any argument types that
2422  /// contain an unexpanded parameter pack.
2423  static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
2424                                                 unsigned numArgs) {
2425    for (unsigned Idx = 0; Idx < numArgs; ++Idx)
2426      if (ArgArray[Idx]->containsUnexpandedParameterPack())
2427        return true;
2428
2429    return false;
2430  }
2431
2432  FunctionProtoType(QualType result, const QualType *args, unsigned numArgs,
2433                    QualType canonical, const ExtProtoInfo &epi);
2434
2435  /// NumArgs - The number of arguments this function has, not counting '...'.
2436  unsigned NumArgs : 20;
2437
2438  /// NumExceptions - The number of types in the exception spec, if any.
2439  unsigned NumExceptions : 9;
2440
2441  /// ExceptionSpecType - The type of exception specification this function has.
2442  unsigned ExceptionSpecType : 3;
2443
2444  /// ArgInfo - There is an variable size array after the class in memory that
2445  /// holds the argument types.
2446
2447  /// Exceptions - There is another variable size array after ArgInfo that
2448  /// holds the exception types.
2449
2450  /// NoexceptExpr - Instead of Exceptions, there may be a single Expr* pointing
2451  /// to the expression in the noexcept() specifier.
2452
2453  friend class ASTContext;  // ASTContext creates these.
2454
2455public:
2456  unsigned getNumArgs() const { return NumArgs; }
2457  QualType getArgType(unsigned i) const {
2458    assert(i < NumArgs && "Invalid argument number!");
2459    return arg_type_begin()[i];
2460  }
2461
2462  ExtProtoInfo getExtProtoInfo() const {
2463    ExtProtoInfo EPI;
2464    EPI.ExtInfo = getExtInfo();
2465    EPI.Variadic = isVariadic();
2466    EPI.ExceptionSpecType = getExceptionSpecType();
2467    EPI.TypeQuals = static_cast<unsigned char>(getTypeQuals());
2468    EPI.RefQualifier = getRefQualifier();
2469    if (EPI.ExceptionSpecType == EST_Dynamic) {
2470      EPI.NumExceptions = NumExceptions;
2471      EPI.Exceptions = exception_begin();
2472    } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
2473      EPI.NoexceptExpr = getNoexceptExpr();
2474    }
2475    return EPI;
2476  }
2477
2478  /// \brief Get the kind of exception specification on this function.
2479  ExceptionSpecificationType getExceptionSpecType() const {
2480    return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
2481  }
2482  /// \brief Return whether this function has any kind of exception spec.
2483  bool hasExceptionSpec() const {
2484    return getExceptionSpecType() != EST_None;
2485  }
2486  /// \brief Return whether this function has a dynamic (throw) exception spec.
2487  bool hasDynamicExceptionSpec() const {
2488    return isDynamicExceptionSpec(getExceptionSpecType());
2489  }
2490  /// \brief Return whther this function has a noexcept exception spec.
2491  bool hasNoexceptExceptionSpec() const {
2492    return isNoexceptExceptionSpec(getExceptionSpecType());
2493  }
2494  /// \brief Result type of getNoexceptSpec().
2495  enum NoexceptResult {
2496    NR_NoNoexcept,  ///< There is no noexcept specifier.
2497    NR_BadNoexcept, ///< The noexcept specifier has a bad expression.
2498    NR_Dependent,   ///< The noexcept specifier is dependent.
2499    NR_Throw,       ///< The noexcept specifier evaluates to false.
2500    NR_Nothrow      ///< The noexcept specifier evaluates to true.
2501  };
2502  /// \brief Get the meaning of the noexcept spec on this function, if any.
2503  NoexceptResult getNoexceptSpec(ASTContext &Ctx) const;
2504  unsigned getNumExceptions() const { return NumExceptions; }
2505  QualType getExceptionType(unsigned i) const {
2506    assert(i < NumExceptions && "Invalid exception number!");
2507    return exception_begin()[i];
2508  }
2509  Expr *getNoexceptExpr() const {
2510    if (getExceptionSpecType() != EST_ComputedNoexcept)
2511      return 0;
2512    // NoexceptExpr sits where the arguments end.
2513    return *reinterpret_cast<Expr *const *>(arg_type_end());
2514  }
2515  bool isNothrow(ASTContext &Ctx) const {
2516    ExceptionSpecificationType EST = getExceptionSpecType();
2517    if (EST == EST_DynamicNone || EST == EST_BasicNoexcept)
2518      return true;
2519    if (EST != EST_ComputedNoexcept)
2520      return false;
2521    return getNoexceptSpec(Ctx) == NR_Nothrow;
2522  }
2523
2524  using FunctionType::isVariadic;
2525
2526  /// \brief Determines whether this function prototype contains a
2527  /// parameter pack at the end.
2528  ///
2529  /// A function template whose last parameter is a parameter pack can be
2530  /// called with an arbitrary number of arguments, much like a variadic
2531  /// function. However,
2532  bool isTemplateVariadic() const;
2533
2534  unsigned getTypeQuals() const { return FunctionType::getTypeQuals(); }
2535
2536
2537  /// \brief Retrieve the ref-qualifier associated with this function type.
2538  RefQualifierKind getRefQualifier() const {
2539    return FunctionType::getRefQualifier();
2540  }
2541
2542  typedef const QualType *arg_type_iterator;
2543  arg_type_iterator arg_type_begin() const {
2544    return reinterpret_cast<const QualType *>(this+1);
2545  }
2546  arg_type_iterator arg_type_end() const { return arg_type_begin()+NumArgs; }
2547
2548  typedef const QualType *exception_iterator;
2549  exception_iterator exception_begin() const {
2550    // exceptions begin where arguments end
2551    return arg_type_end();
2552  }
2553  exception_iterator exception_end() const {
2554    if (getExceptionSpecType() != EST_Dynamic)
2555      return exception_begin();
2556    return exception_begin() + NumExceptions;
2557  }
2558
2559  bool isSugared() const { return false; }
2560  QualType desugar() const { return QualType(this, 0); }
2561
2562  static bool classof(const Type *T) {
2563    return T->getTypeClass() == FunctionProto;
2564  }
2565  static bool classof(const FunctionProtoType *) { return true; }
2566
2567  void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
2568  static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
2569                      arg_type_iterator ArgTys, unsigned NumArgs,
2570                      const ExtProtoInfo &EPI, const ASTContext &Context);
2571};
2572
2573
2574/// \brief Represents the dependent type named by a dependently-scoped
2575/// typename using declaration, e.g.
2576///   using typename Base<T>::foo;
2577/// Template instantiation turns these into the underlying type.
2578class UnresolvedUsingType : public Type {
2579  UnresolvedUsingTypenameDecl *Decl;
2580
2581  UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
2582    : Type(UnresolvedUsing, QualType(), true, false,
2583           /*ContainsUnexpandedParameterPack=*/false),
2584      Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
2585  friend class ASTContext; // ASTContext creates these.
2586public:
2587
2588  UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
2589
2590  bool isSugared() const { return false; }
2591  QualType desugar() const { return QualType(this, 0); }
2592
2593  static bool classof(const Type *T) {
2594    return T->getTypeClass() == UnresolvedUsing;
2595  }
2596  static bool classof(const UnresolvedUsingType *) { return true; }
2597
2598  void Profile(llvm::FoldingSetNodeID &ID) {
2599    return Profile(ID, Decl);
2600  }
2601  static void Profile(llvm::FoldingSetNodeID &ID,
2602                      UnresolvedUsingTypenameDecl *D) {
2603    ID.AddPointer(D);
2604  }
2605};
2606
2607
2608class TypedefType : public Type {
2609  TypedefDecl *Decl;
2610protected:
2611  TypedefType(TypeClass tc, const TypedefDecl *D, QualType can)
2612    : Type(tc, can, can->isDependentType(), can->isVariablyModifiedType(),
2613           /*ContainsUnexpandedParameterPack=*/false),
2614      Decl(const_cast<TypedefDecl*>(D)) {
2615    assert(!isa<TypedefType>(can) && "Invalid canonical type");
2616  }
2617  friend class ASTContext;  // ASTContext creates these.
2618public:
2619
2620  TypedefDecl *getDecl() const { return Decl; }
2621
2622  bool isSugared() const { return true; }
2623  QualType desugar() const;
2624
2625  static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
2626  static bool classof(const TypedefType *) { return true; }
2627};
2628
2629/// TypeOfExprType (GCC extension).
2630class TypeOfExprType : public Type {
2631  Expr *TOExpr;
2632
2633protected:
2634  TypeOfExprType(Expr *E, QualType can = QualType());
2635  friend class ASTContext;  // ASTContext creates these.
2636public:
2637  Expr *getUnderlyingExpr() const { return TOExpr; }
2638
2639  /// \brief Remove a single level of sugar.
2640  QualType desugar() const;
2641
2642  /// \brief Returns whether this type directly provides sugar.
2643  bool isSugared() const { return true; }
2644
2645  static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
2646  static bool classof(const TypeOfExprType *) { return true; }
2647};
2648
2649/// \brief Internal representation of canonical, dependent
2650/// typeof(expr) types.
2651///
2652/// This class is used internally by the ASTContext to manage
2653/// canonical, dependent types, only. Clients will only see instances
2654/// of this class via TypeOfExprType nodes.
2655class DependentTypeOfExprType
2656  : public TypeOfExprType, public llvm::FoldingSetNode {
2657  const ASTContext &Context;
2658
2659public:
2660  DependentTypeOfExprType(const ASTContext &Context, Expr *E)
2661    : TypeOfExprType(E), Context(Context) { }
2662
2663  bool isSugared() const { return false; }
2664  QualType desugar() const { return QualType(this, 0); }
2665
2666  void Profile(llvm::FoldingSetNodeID &ID) {
2667    Profile(ID, Context, getUnderlyingExpr());
2668  }
2669
2670  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2671                      Expr *E);
2672};
2673
2674/// TypeOfType (GCC extension).
2675class TypeOfType : public Type {
2676  QualType TOType;
2677  TypeOfType(QualType T, QualType can)
2678    : Type(TypeOf, can, T->isDependentType(), T->isVariablyModifiedType(),
2679           T->containsUnexpandedParameterPack()),
2680      TOType(T) {
2681    assert(!isa<TypedefType>(can) && "Invalid canonical type");
2682  }
2683  friend class ASTContext;  // ASTContext creates these.
2684public:
2685  QualType getUnderlyingType() const { return TOType; }
2686
2687  /// \brief Remove a single level of sugar.
2688  QualType desugar() const { return getUnderlyingType(); }
2689
2690  /// \brief Returns whether this type directly provides sugar.
2691  bool isSugared() const { return true; }
2692
2693  static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
2694  static bool classof(const TypeOfType *) { return true; }
2695};
2696
2697/// DecltypeType (C++0x)
2698class DecltypeType : public Type {
2699  Expr *E;
2700
2701  // FIXME: We could get rid of UnderlyingType if we wanted to: We would have to
2702  // Move getDesugaredType to ASTContext so that it can call getDecltypeForExpr
2703  // from it.
2704  QualType UnderlyingType;
2705
2706protected:
2707  DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
2708  friend class ASTContext;  // ASTContext creates these.
2709public:
2710  Expr *getUnderlyingExpr() const { return E; }
2711  QualType getUnderlyingType() const { return UnderlyingType; }
2712
2713  /// \brief Remove a single level of sugar.
2714  QualType desugar() const { return getUnderlyingType(); }
2715
2716  /// \brief Returns whether this type directly provides sugar.
2717  bool isSugared() const { return !isDependentType(); }
2718
2719  static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
2720  static bool classof(const DecltypeType *) { return true; }
2721};
2722
2723/// \brief Internal representation of canonical, dependent
2724/// decltype(expr) types.
2725///
2726/// This class is used internally by the ASTContext to manage
2727/// canonical, dependent types, only. Clients will only see instances
2728/// of this class via DecltypeType nodes.
2729class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
2730  const ASTContext &Context;
2731
2732public:
2733  DependentDecltypeType(const ASTContext &Context, Expr *E);
2734
2735  bool isSugared() const { return false; }
2736  QualType desugar() const { return QualType(this, 0); }
2737
2738  void Profile(llvm::FoldingSetNodeID &ID) {
2739    Profile(ID, Context, getUnderlyingExpr());
2740  }
2741
2742  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2743                      Expr *E);
2744};
2745
2746class TagType : public Type {
2747  /// Stores the TagDecl associated with this type. The decl may point to any
2748  /// TagDecl that declares the entity.
2749  TagDecl * decl;
2750
2751protected:
2752  TagType(TypeClass TC, const TagDecl *D, QualType can);
2753
2754public:
2755  TagDecl *getDecl() const;
2756
2757  /// @brief Determines whether this type is in the process of being
2758  /// defined.
2759  bool isBeingDefined() const;
2760
2761  static bool classof(const Type *T) {
2762    return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast;
2763  }
2764  static bool classof(const TagType *) { return true; }
2765  static bool classof(const RecordType *) { return true; }
2766  static bool classof(const EnumType *) { return true; }
2767};
2768
2769/// RecordType - This is a helper class that allows the use of isa/cast/dyncast
2770/// to detect TagType objects of structs/unions/classes.
2771class RecordType : public TagType {
2772protected:
2773  explicit RecordType(const RecordDecl *D)
2774    : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) { }
2775  explicit RecordType(TypeClass TC, RecordDecl *D)
2776    : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) { }
2777  friend class ASTContext;   // ASTContext creates these.
2778public:
2779
2780  RecordDecl *getDecl() const {
2781    return reinterpret_cast<RecordDecl*>(TagType::getDecl());
2782  }
2783
2784  // FIXME: This predicate is a helper to QualType/Type. It needs to
2785  // recursively check all fields for const-ness. If any field is declared
2786  // const, it needs to return false.
2787  bool hasConstFields() const { return false; }
2788
2789  bool isSugared() const { return false; }
2790  QualType desugar() const { return QualType(this, 0); }
2791
2792  static bool classof(const TagType *T);
2793  static bool classof(const Type *T) {
2794    return isa<TagType>(T) && classof(cast<TagType>(T));
2795  }
2796  static bool classof(const RecordType *) { return true; }
2797};
2798
2799/// EnumType - This is a helper class that allows the use of isa/cast/dyncast
2800/// to detect TagType objects of enums.
2801class EnumType : public TagType {
2802  explicit EnumType(const EnumDecl *D)
2803    : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) { }
2804  friend class ASTContext;   // ASTContext creates these.
2805public:
2806
2807  EnumDecl *getDecl() const {
2808    return reinterpret_cast<EnumDecl*>(TagType::getDecl());
2809  }
2810
2811  bool isSugared() const { return false; }
2812  QualType desugar() const { return QualType(this, 0); }
2813
2814  static bool classof(const TagType *T);
2815  static bool classof(const Type *T) {
2816    return isa<TagType>(T) && classof(cast<TagType>(T));
2817  }
2818  static bool classof(const EnumType *) { return true; }
2819};
2820
2821/// AttributedType - An attributed type is a type to which a type
2822/// attribute has been applied.  The "modified type" is the
2823/// fully-sugared type to which the attributed type was applied;
2824/// generally it is not canonically equivalent to the attributed type.
2825/// The "equivalent type" is the minimally-desugared type which the
2826/// type is canonically equivalent to.
2827///
2828/// For example, in the following attributed type:
2829///     int32_t __attribute__((vector_size(16)))
2830///   - the modified type is the TypedefType for int32_t
2831///   - the equivalent type is VectorType(16, int32_t)
2832///   - the canonical type is VectorType(16, int)
2833class AttributedType : public Type, public llvm::FoldingSetNode {
2834public:
2835  // It is really silly to have yet another attribute-kind enum, but
2836  // clang::attr::Kind doesn't currently cover the pure type attrs.
2837  enum Kind {
2838    // Expression operand.
2839    attr_address_space,
2840    attr_regparm,
2841    attr_vector_size,
2842    attr_neon_vector_type,
2843    attr_neon_polyvector_type,
2844
2845    FirstExprOperandKind = attr_address_space,
2846    LastExprOperandKind = attr_neon_polyvector_type,
2847
2848    // Enumerated operand (string or keyword).
2849    attr_objc_gc,
2850
2851    FirstEnumOperandKind = attr_objc_gc,
2852    LastEnumOperandKind = attr_objc_gc,
2853
2854    // No operand.
2855    attr_noreturn,
2856    attr_cdecl,
2857    attr_fastcall,
2858    attr_stdcall,
2859    attr_thiscall,
2860    attr_pascal
2861  };
2862
2863private:
2864  QualType ModifiedType;
2865  QualType EquivalentType;
2866
2867  friend class ASTContext; // creates these
2868
2869  AttributedType(QualType canon, Kind attrKind,
2870                 QualType modified, QualType equivalent)
2871    : Type(Attributed, canon, canon->isDependentType(),
2872           canon->isVariablyModifiedType(),
2873           canon->containsUnexpandedParameterPack()),
2874      ModifiedType(modified), EquivalentType(equivalent) {
2875    AttributedTypeBits.AttrKind = attrKind;
2876  }
2877
2878public:
2879  Kind getAttrKind() const {
2880    return static_cast<Kind>(AttributedTypeBits.AttrKind);
2881  }
2882
2883  QualType getModifiedType() const { return ModifiedType; }
2884  QualType getEquivalentType() const { return EquivalentType; }
2885
2886  bool isSugared() const { return true; }
2887  QualType desugar() const { return getEquivalentType(); }
2888
2889  void Profile(llvm::FoldingSetNodeID &ID) {
2890    Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
2891  }
2892
2893  static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
2894                      QualType modified, QualType equivalent) {
2895    ID.AddInteger(attrKind);
2896    ID.AddPointer(modified.getAsOpaquePtr());
2897    ID.AddPointer(equivalent.getAsOpaquePtr());
2898  }
2899
2900  static bool classof(const Type *T) {
2901    return T->getTypeClass() == Attributed;
2902  }
2903  static bool classof(const AttributedType *T) { return true; }
2904};
2905
2906class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
2907  unsigned Depth : 15;
2908  unsigned ParameterPack : 1;
2909  unsigned Index : 16;
2910  IdentifierInfo *Name;
2911
2912  TemplateTypeParmType(unsigned D, unsigned I, bool PP, IdentifierInfo *N,
2913                       QualType Canon)
2914    : Type(TemplateTypeParm, Canon, /*Dependent=*/true,
2915           /*VariablyModified=*/false, PP),
2916      Depth(D), ParameterPack(PP), Index(I), Name(N) { }
2917
2918  TemplateTypeParmType(unsigned D, unsigned I, bool PP)
2919    : Type(TemplateTypeParm, QualType(this, 0), /*Dependent=*/true,
2920           /*VariablyModified=*/false, PP),
2921      Depth(D), ParameterPack(PP), Index(I), Name(0) { }
2922
2923  friend class ASTContext;  // ASTContext creates these
2924
2925public:
2926  unsigned getDepth() const { return Depth; }
2927  unsigned getIndex() const { return Index; }
2928  bool isParameterPack() const { return ParameterPack; }
2929  IdentifierInfo *getName() const { return Name; }
2930
2931  bool isSugared() const { return false; }
2932  QualType desugar() const { return QualType(this, 0); }
2933
2934  void Profile(llvm::FoldingSetNodeID &ID) {
2935    Profile(ID, Depth, Index, ParameterPack, Name);
2936  }
2937
2938  static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
2939                      unsigned Index, bool ParameterPack,
2940                      IdentifierInfo *Name) {
2941    ID.AddInteger(Depth);
2942    ID.AddInteger(Index);
2943    ID.AddBoolean(ParameterPack);
2944    ID.AddPointer(Name);
2945  }
2946
2947  static bool classof(const Type *T) {
2948    return T->getTypeClass() == TemplateTypeParm;
2949  }
2950  static bool classof(const TemplateTypeParmType *T) { return true; }
2951};
2952
2953/// \brief Represents the result of substituting a type for a template
2954/// type parameter.
2955///
2956/// Within an instantiated template, all template type parameters have
2957/// been replaced with these.  They are used solely to record that a
2958/// type was originally written as a template type parameter;
2959/// therefore they are never canonical.
2960class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
2961  // The original type parameter.
2962  const TemplateTypeParmType *Replaced;
2963
2964  SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
2965    : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(),
2966           Canon->isVariablyModifiedType(),
2967           Canon->containsUnexpandedParameterPack()),
2968      Replaced(Param) { }
2969
2970  friend class ASTContext;
2971
2972public:
2973  IdentifierInfo *getName() const { return Replaced->getName(); }
2974
2975  /// Gets the template parameter that was substituted for.
2976  const TemplateTypeParmType *getReplacedParameter() const {
2977    return Replaced;
2978  }
2979
2980  /// Gets the type that was substituted for the template
2981  /// parameter.
2982  QualType getReplacementType() const {
2983    return getCanonicalTypeInternal();
2984  }
2985
2986  bool isSugared() const { return true; }
2987  QualType desugar() const { return getReplacementType(); }
2988
2989  void Profile(llvm::FoldingSetNodeID &ID) {
2990    Profile(ID, getReplacedParameter(), getReplacementType());
2991  }
2992  static void Profile(llvm::FoldingSetNodeID &ID,
2993                      const TemplateTypeParmType *Replaced,
2994                      QualType Replacement) {
2995    ID.AddPointer(Replaced);
2996    ID.AddPointer(Replacement.getAsOpaquePtr());
2997  }
2998
2999  static bool classof(const Type *T) {
3000    return T->getTypeClass() == SubstTemplateTypeParm;
3001  }
3002  static bool classof(const SubstTemplateTypeParmType *T) { return true; }
3003};
3004
3005/// \brief Represents the result of substituting a set of types for a template
3006/// type parameter pack.
3007///
3008/// When a pack expansion in the source code contains multiple parameter packs
3009/// and those parameter packs correspond to different levels of template
3010/// parameter lists, this type node is used to represent a template type
3011/// parameter pack from an outer level, which has already had its argument pack
3012/// substituted but that still lives within a pack expansion that itself
3013/// could not be instantiated. When actually performing a substitution into
3014/// that pack expansion (e.g., when all template parameters have corresponding
3015/// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
3016/// at the current pack substitution index.
3017class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
3018  /// \brief The original type parameter.
3019  const TemplateTypeParmType *Replaced;
3020
3021  /// \brief A pointer to the set of template arguments that this
3022  /// parameter pack is instantiated with.
3023  const TemplateArgument *Arguments;
3024
3025  /// \brief The number of template arguments in \c Arguments.
3026  unsigned NumArguments;
3027
3028  SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
3029                                QualType Canon,
3030                                const TemplateArgument &ArgPack);
3031
3032  friend class ASTContext;
3033
3034public:
3035  IdentifierInfo *getName() const { return Replaced->getName(); }
3036
3037  /// Gets the template parameter that was substituted for.
3038  const TemplateTypeParmType *getReplacedParameter() const {
3039    return Replaced;
3040  }
3041
3042  bool isSugared() const { return false; }
3043  QualType desugar() const { return QualType(this, 0); }
3044
3045  TemplateArgument getArgumentPack() const;
3046
3047  void Profile(llvm::FoldingSetNodeID &ID);
3048  static void Profile(llvm::FoldingSetNodeID &ID,
3049                      const TemplateTypeParmType *Replaced,
3050                      const TemplateArgument &ArgPack);
3051
3052  static bool classof(const Type *T) {
3053    return T->getTypeClass() == SubstTemplateTypeParmPack;
3054  }
3055  static bool classof(const SubstTemplateTypeParmPackType *T) { return true; }
3056};
3057
3058/// \brief Represents a C++0x auto type.
3059///
3060/// These types are usually a placeholder for a deduced type. However, within
3061/// templates and before the initializer is attached, there is no deduced type
3062/// and an auto type is type-dependent and canonical.
3063class AutoType : public Type, public llvm::FoldingSetNode {
3064  AutoType(QualType DeducedType)
3065    : Type(Auto, DeducedType.isNull() ? QualType(this, 0) : DeducedType,
3066           /*Dependent=*/DeducedType.isNull(),
3067           /*VariablyModified=*/false, /*ContainsParameterPack=*/false) {
3068    assert((DeducedType.isNull() || !DeducedType->isDependentType()) &&
3069           "deduced a dependent type for auto");
3070  }
3071
3072  friend class ASTContext;  // ASTContext creates these
3073
3074public:
3075  bool isSugared() const { return isDeduced(); }
3076  QualType desugar() const { return getCanonicalTypeInternal(); }
3077
3078  QualType getDeducedType() const {
3079    return isDeduced() ? getCanonicalTypeInternal() : QualType();
3080  }
3081  bool isDeduced() const {
3082    return !isDependentType();
3083  }
3084
3085  void Profile(llvm::FoldingSetNodeID &ID) {
3086    Profile(ID, getDeducedType());
3087  }
3088
3089  static void Profile(llvm::FoldingSetNodeID &ID,
3090                      QualType Deduced) {
3091    ID.AddPointer(Deduced.getAsOpaquePtr());
3092  }
3093
3094  static bool classof(const Type *T) {
3095    return T->getTypeClass() == Auto;
3096  }
3097  static bool classof(const AutoType *T) { return true; }
3098};
3099
3100/// \brief Represents the type of a template specialization as written
3101/// in the source code.
3102///
3103/// Template specialization types represent the syntactic form of a
3104/// template-id that refers to a type, e.g., @c vector<int>. Some
3105/// template specialization types are syntactic sugar, whose canonical
3106/// type will point to some other type node that represents the
3107/// instantiation or class template specialization. For example, a
3108/// class template specialization type of @c vector<int> will refer to
3109/// a tag type for the instantiation
3110/// @c std::vector<int, std::allocator<int>>.
3111///
3112/// Other template specialization types, for which the template name
3113/// is dependent, may be canonical types. These types are always
3114/// dependent.
3115class TemplateSpecializationType
3116  : public Type, public llvm::FoldingSetNode {
3117  /// \brief The name of the template being specialized.
3118  TemplateName Template;
3119
3120  /// \brief - The number of template arguments named in this class
3121  /// template specialization.
3122  unsigned NumArgs;
3123
3124  TemplateSpecializationType(TemplateName T,
3125                             const TemplateArgument *Args,
3126                             unsigned NumArgs, QualType Canon);
3127
3128  friend class ASTContext;  // ASTContext creates these
3129
3130public:
3131  /// \brief Determine whether any of the given template arguments are
3132  /// dependent.
3133  static bool anyDependentTemplateArguments(const TemplateArgument *Args,
3134                                            unsigned NumArgs);
3135
3136  static bool anyDependentTemplateArguments(const TemplateArgumentLoc *Args,
3137                                            unsigned NumArgs);
3138
3139  static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &);
3140
3141  /// \brief Print a template argument list, including the '<' and '>'
3142  /// enclosing the template arguments.
3143  static std::string PrintTemplateArgumentList(const TemplateArgument *Args,
3144                                               unsigned NumArgs,
3145                                               const PrintingPolicy &Policy,
3146                                               bool SkipBrackets = false);
3147
3148  static std::string PrintTemplateArgumentList(const TemplateArgumentLoc *Args,
3149                                               unsigned NumArgs,
3150                                               const PrintingPolicy &Policy);
3151
3152  static std::string PrintTemplateArgumentList(const TemplateArgumentListInfo &,
3153                                               const PrintingPolicy &Policy);
3154
3155  /// True if this template specialization type matches a current
3156  /// instantiation in the context in which it is found.
3157  bool isCurrentInstantiation() const {
3158    return isa<InjectedClassNameType>(getCanonicalTypeInternal());
3159  }
3160
3161  typedef const TemplateArgument * iterator;
3162
3163  iterator begin() const { return getArgs(); }
3164  iterator end() const; // defined inline in TemplateBase.h
3165
3166  /// \brief Retrieve the name of the template that we are specializing.
3167  TemplateName getTemplateName() const { return Template; }
3168
3169  /// \brief Retrieve the template arguments.
3170  const TemplateArgument *getArgs() const {
3171    return reinterpret_cast<const TemplateArgument *>(this + 1);
3172  }
3173
3174  /// \brief Retrieve the number of template arguments.
3175  unsigned getNumArgs() const { return NumArgs; }
3176
3177  /// \brief Retrieve a specific template argument as a type.
3178  /// \precondition @c isArgType(Arg)
3179  const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
3180
3181  bool isSugared() const {
3182    return !isDependentType() || isCurrentInstantiation();
3183  }
3184  QualType desugar() const { return getCanonicalTypeInternal(); }
3185
3186  void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
3187    Profile(ID, Template, getArgs(), NumArgs, Ctx);
3188  }
3189
3190  static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
3191                      const TemplateArgument *Args,
3192                      unsigned NumArgs,
3193                      const ASTContext &Context);
3194
3195  static bool classof(const Type *T) {
3196    return T->getTypeClass() == TemplateSpecialization;
3197  }
3198  static bool classof(const TemplateSpecializationType *T) { return true; }
3199};
3200
3201/// \brief The injected class name of a C++ class template or class
3202/// template partial specialization.  Used to record that a type was
3203/// spelled with a bare identifier rather than as a template-id; the
3204/// equivalent for non-templated classes is just RecordType.
3205///
3206/// Injected class name types are always dependent.  Template
3207/// instantiation turns these into RecordTypes.
3208///
3209/// Injected class name types are always canonical.  This works
3210/// because it is impossible to compare an injected class name type
3211/// with the corresponding non-injected template type, for the same
3212/// reason that it is impossible to directly compare template
3213/// parameters from different dependent contexts: injected class name
3214/// types can only occur within the scope of a particular templated
3215/// declaration, and within that scope every template specialization
3216/// will canonicalize to the injected class name (when appropriate
3217/// according to the rules of the language).
3218class InjectedClassNameType : public Type {
3219  CXXRecordDecl *Decl;
3220
3221  /// The template specialization which this type represents.
3222  /// For example, in
3223  ///   template <class T> class A { ... };
3224  /// this is A<T>, whereas in
3225  ///   template <class X, class Y> class A<B<X,Y> > { ... };
3226  /// this is A<B<X,Y> >.
3227  ///
3228  /// It is always unqualified, always a template specialization type,
3229  /// and always dependent.
3230  QualType InjectedType;
3231
3232  friend class ASTContext; // ASTContext creates these.
3233  friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
3234                          // currently suitable for AST reading, too much
3235                          // interdependencies.
3236  InjectedClassNameType(CXXRecordDecl *D, QualType TST)
3237    : Type(InjectedClassName, QualType(), /*Dependent=*/true,
3238           /*VariablyModified=*/false,
3239           /*ContainsUnexpandedParameterPack=*/false),
3240      Decl(D), InjectedType(TST) {
3241    assert(isa<TemplateSpecializationType>(TST));
3242    assert(!TST.hasQualifiers());
3243    assert(TST->isDependentType());
3244  }
3245
3246public:
3247  QualType getInjectedSpecializationType() const { return InjectedType; }
3248  const TemplateSpecializationType *getInjectedTST() const {
3249    return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
3250  }
3251
3252  CXXRecordDecl *getDecl() const;
3253
3254  bool isSugared() const { return false; }
3255  QualType desugar() const { return QualType(this, 0); }
3256
3257  static bool classof(const Type *T) {
3258    return T->getTypeClass() == InjectedClassName;
3259  }
3260  static bool classof(const InjectedClassNameType *T) { return true; }
3261};
3262
3263/// \brief The kind of a tag type.
3264enum TagTypeKind {
3265  /// \brief The "struct" keyword.
3266  TTK_Struct,
3267  /// \brief The "union" keyword.
3268  TTK_Union,
3269  /// \brief The "class" keyword.
3270  TTK_Class,
3271  /// \brief The "enum" keyword.
3272  TTK_Enum
3273};
3274
3275/// \brief The elaboration keyword that precedes a qualified type name or
3276/// introduces an elaborated-type-specifier.
3277enum ElaboratedTypeKeyword {
3278  /// \brief The "struct" keyword introduces the elaborated-type-specifier.
3279  ETK_Struct,
3280  /// \brief The "union" keyword introduces the elaborated-type-specifier.
3281  ETK_Union,
3282  /// \brief The "class" keyword introduces the elaborated-type-specifier.
3283  ETK_Class,
3284  /// \brief The "enum" keyword introduces the elaborated-type-specifier.
3285  ETK_Enum,
3286  /// \brief The "typename" keyword precedes the qualified type name, e.g.,
3287  /// \c typename T::type.
3288  ETK_Typename,
3289  /// \brief No keyword precedes the qualified type name.
3290  ETK_None
3291};
3292
3293/// A helper class for Type nodes having an ElaboratedTypeKeyword.
3294/// The keyword in stored in the free bits of the base class.
3295/// Also provides a few static helpers for converting and printing
3296/// elaborated type keyword and tag type kind enumerations.
3297class TypeWithKeyword : public Type {
3298protected:
3299  TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
3300                  QualType Canonical, bool Dependent, bool VariablyModified,
3301                  bool ContainsUnexpandedParameterPack)
3302  : Type(tc, Canonical, Dependent, VariablyModified,
3303         ContainsUnexpandedParameterPack) {
3304    TypeWithKeywordBits.Keyword = Keyword;
3305  }
3306
3307public:
3308  ElaboratedTypeKeyword getKeyword() const {
3309    return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
3310  }
3311
3312  /// getKeywordForTypeSpec - Converts a type specifier (DeclSpec::TST)
3313  /// into an elaborated type keyword.
3314  static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
3315
3316  /// getTagTypeKindForTypeSpec - Converts a type specifier (DeclSpec::TST)
3317  /// into a tag type kind.  It is an error to provide a type specifier
3318  /// which *isn't* a tag kind here.
3319  static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
3320
3321  /// getKeywordForTagDeclKind - Converts a TagTypeKind into an
3322  /// elaborated type keyword.
3323  static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
3324
3325  /// getTagTypeKindForKeyword - Converts an elaborated type keyword into
3326  // a TagTypeKind. It is an error to provide an elaborated type keyword
3327  /// which *isn't* a tag kind here.
3328  static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
3329
3330  static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
3331
3332  static const char *getKeywordName(ElaboratedTypeKeyword Keyword);
3333
3334  static const char *getTagTypeKindName(TagTypeKind Kind) {
3335    return getKeywordName(getKeywordForTagTypeKind(Kind));
3336  }
3337
3338  class CannotCastToThisType {};
3339  static CannotCastToThisType classof(const Type *);
3340};
3341
3342/// \brief Represents a type that was referred to using an elaborated type
3343/// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
3344/// or both.
3345///
3346/// This type is used to keep track of a type name as written in the
3347/// source code, including tag keywords and any nested-name-specifiers.
3348/// The type itself is always "sugar", used to express what was written
3349/// in the source code but containing no additional semantic information.
3350class ElaboratedType : public TypeWithKeyword, public llvm::FoldingSetNode {
3351
3352  /// \brief The nested name specifier containing the qualifier.
3353  NestedNameSpecifier *NNS;
3354
3355  /// \brief The type that this qualified name refers to.
3356  QualType NamedType;
3357
3358  ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
3359                 QualType NamedType, QualType CanonType)
3360    : TypeWithKeyword(Keyword, Elaborated, CanonType,
3361                      NamedType->isDependentType(),
3362                      NamedType->isVariablyModifiedType(),
3363                      NamedType->containsUnexpandedParameterPack()),
3364      NNS(NNS), NamedType(NamedType) {
3365    assert(!(Keyword == ETK_None && NNS == 0) &&
3366           "ElaboratedType cannot have elaborated type keyword "
3367           "and name qualifier both null.");
3368  }
3369
3370  friend class ASTContext;  // ASTContext creates these
3371
3372public:
3373  ~ElaboratedType();
3374
3375  /// \brief Retrieve the qualification on this type.
3376  NestedNameSpecifier *getQualifier() const { return NNS; }
3377
3378  /// \brief Retrieve the type named by the qualified-id.
3379  QualType getNamedType() const { return NamedType; }
3380
3381  /// \brief Remove a single level of sugar.
3382  QualType desugar() const { return getNamedType(); }
3383
3384  /// \brief Returns whether this type directly provides sugar.
3385  bool isSugared() const { return true; }
3386
3387  void Profile(llvm::FoldingSetNodeID &ID) {
3388    Profile(ID, getKeyword(), NNS, NamedType);
3389  }
3390
3391  static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
3392                      NestedNameSpecifier *NNS, QualType NamedType) {
3393    ID.AddInteger(Keyword);
3394    ID.AddPointer(NNS);
3395    NamedType.Profile(ID);
3396  }
3397
3398  static bool classof(const Type *T) {
3399    return T->getTypeClass() == Elaborated;
3400  }
3401  static bool classof(const ElaboratedType *T) { return true; }
3402};
3403
3404/// \brief Represents a qualified type name for which the type name is
3405/// dependent.
3406///
3407/// DependentNameType represents a class of dependent types that involve a
3408/// dependent nested-name-specifier (e.g., "T::") followed by a (dependent)
3409/// name of a type. The DependentNameType may start with a "typename" (for a
3410/// typename-specifier), "class", "struct", "union", or "enum" (for a
3411/// dependent elaborated-type-specifier), or nothing (in contexts where we
3412/// know that we must be referring to a type, e.g., in a base class specifier).
3413class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
3414
3415  /// \brief The nested name specifier containing the qualifier.
3416  NestedNameSpecifier *NNS;
3417
3418  /// \brief The type that this typename specifier refers to.
3419  const IdentifierInfo *Name;
3420
3421  DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
3422                    const IdentifierInfo *Name, QualType CanonType)
3423    : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true,
3424                      /*VariablyModified=*/false,
3425                      NNS->containsUnexpandedParameterPack()),
3426      NNS(NNS), Name(Name) {
3427    assert(NNS->isDependent() &&
3428           "DependentNameType requires a dependent nested-name-specifier");
3429  }
3430
3431  friend class ASTContext;  // ASTContext creates these
3432
3433public:
3434  /// \brief Retrieve the qualification on this type.
3435  NestedNameSpecifier *getQualifier() const { return NNS; }
3436
3437  /// \brief Retrieve the type named by the typename specifier as an
3438  /// identifier.
3439  ///
3440  /// This routine will return a non-NULL identifier pointer when the
3441  /// form of the original typename was terminated by an identifier,
3442  /// e.g., "typename T::type".
3443  const IdentifierInfo *getIdentifier() const {
3444    return Name;
3445  }
3446
3447  bool isSugared() const { return false; }
3448  QualType desugar() const { return QualType(this, 0); }
3449
3450  void Profile(llvm::FoldingSetNodeID &ID) {
3451    Profile(ID, getKeyword(), NNS, Name);
3452  }
3453
3454  static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
3455                      NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
3456    ID.AddInteger(Keyword);
3457    ID.AddPointer(NNS);
3458    ID.AddPointer(Name);
3459  }
3460
3461  static bool classof(const Type *T) {
3462    return T->getTypeClass() == DependentName;
3463  }
3464  static bool classof(const DependentNameType *T) { return true; }
3465};
3466
3467/// DependentTemplateSpecializationType - Represents a template
3468/// specialization type whose template cannot be resolved, e.g.
3469///   A<T>::template B<T>
3470class DependentTemplateSpecializationType :
3471  public TypeWithKeyword, public llvm::FoldingSetNode {
3472
3473  /// \brief The nested name specifier containing the qualifier.
3474  NestedNameSpecifier *NNS;
3475
3476  /// \brief The identifier of the template.
3477  const IdentifierInfo *Name;
3478
3479  /// \brief - The number of template arguments named in this class
3480  /// template specialization.
3481  unsigned NumArgs;
3482
3483  const TemplateArgument *getArgBuffer() const {
3484    return reinterpret_cast<const TemplateArgument*>(this+1);
3485  }
3486  TemplateArgument *getArgBuffer() {
3487    return reinterpret_cast<TemplateArgument*>(this+1);
3488  }
3489
3490  DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
3491                                      NestedNameSpecifier *NNS,
3492                                      const IdentifierInfo *Name,
3493                                      unsigned NumArgs,
3494                                      const TemplateArgument *Args,
3495                                      QualType Canon);
3496
3497  friend class ASTContext;  // ASTContext creates these
3498
3499public:
3500  NestedNameSpecifier *getQualifier() const { return NNS; }
3501  const IdentifierInfo *getIdentifier() const { return Name; }
3502
3503  /// \brief Retrieve the template arguments.
3504  const TemplateArgument *getArgs() const {
3505    return getArgBuffer();
3506  }
3507
3508  /// \brief Retrieve the number of template arguments.
3509  unsigned getNumArgs() const { return NumArgs; }
3510
3511  const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
3512
3513  typedef const TemplateArgument * iterator;
3514  iterator begin() const { return getArgs(); }
3515  iterator end() const; // inline in TemplateBase.h
3516
3517  bool isSugared() const { return false; }
3518  QualType desugar() const { return QualType(this, 0); }
3519
3520  void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
3521    Profile(ID, Context, getKeyword(), NNS, Name, NumArgs, getArgs());
3522  }
3523
3524  static void Profile(llvm::FoldingSetNodeID &ID,
3525                      const ASTContext &Context,
3526                      ElaboratedTypeKeyword Keyword,
3527                      NestedNameSpecifier *Qualifier,
3528                      const IdentifierInfo *Name,
3529                      unsigned NumArgs,
3530                      const TemplateArgument *Args);
3531
3532  static bool classof(const Type *T) {
3533    return T->getTypeClass() == DependentTemplateSpecialization;
3534  }
3535  static bool classof(const DependentTemplateSpecializationType *T) {
3536    return true;
3537  }
3538};
3539
3540/// \brief Represents a pack expansion of types.
3541///
3542/// Pack expansions are part of C++0x variadic templates. A pack
3543/// expansion contains a pattern, which itself contains one or more
3544/// "unexpanded" parameter packs. When instantiated, a pack expansion
3545/// produces a series of types, each instantiated from the pattern of
3546/// the expansion, where the Ith instantiation of the pattern uses the
3547/// Ith arguments bound to each of the unexpanded parameter packs. The
3548/// pack expansion is considered to "expand" these unexpanded
3549/// parameter packs.
3550///
3551/// \code
3552/// template<typename ...Types> struct tuple;
3553///
3554/// template<typename ...Types>
3555/// struct tuple_of_references {
3556///   typedef tuple<Types&...> type;
3557/// };
3558/// \endcode
3559///
3560/// Here, the pack expansion \c Types&... is represented via a
3561/// PackExpansionType whose pattern is Types&.
3562class PackExpansionType : public Type, public llvm::FoldingSetNode {
3563  /// \brief The pattern of the pack expansion.
3564  QualType Pattern;
3565
3566  /// \brief The number of expansions that this pack expansion will
3567  /// generate when substituted (+1), or indicates that
3568  ///
3569  /// This field will only have a non-zero value when some of the parameter
3570  /// packs that occur within the pattern have been substituted but others have
3571  /// not.
3572  unsigned NumExpansions;
3573
3574  PackExpansionType(QualType Pattern, QualType Canon,
3575                    llvm::Optional<unsigned> NumExpansions)
3576    : Type(PackExpansion, Canon, /*Dependent=*/true,
3577           /*VariableModified=*/Pattern->isVariablyModifiedType(),
3578           /*ContainsUnexpandedParameterPack=*/false),
3579      Pattern(Pattern),
3580      NumExpansions(NumExpansions? *NumExpansions + 1: 0) { }
3581
3582  friend class ASTContext;  // ASTContext creates these
3583
3584public:
3585  /// \brief Retrieve the pattern of this pack expansion, which is the
3586  /// type that will be repeatedly instantiated when instantiating the
3587  /// pack expansion itself.
3588  QualType getPattern() const { return Pattern; }
3589
3590  /// \brief Retrieve the number of expansions that this pack expansion will
3591  /// generate, if known.
3592  llvm::Optional<unsigned> getNumExpansions() const {
3593    if (NumExpansions)
3594      return NumExpansions - 1;
3595
3596    return llvm::Optional<unsigned>();
3597  }
3598
3599  bool isSugared() const { return false; }
3600  QualType desugar() const { return QualType(this, 0); }
3601
3602  void Profile(llvm::FoldingSetNodeID &ID) {
3603    Profile(ID, getPattern(), getNumExpansions());
3604  }
3605
3606  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
3607                      llvm::Optional<unsigned> NumExpansions) {
3608    ID.AddPointer(Pattern.getAsOpaquePtr());
3609    ID.AddBoolean(NumExpansions);
3610    if (NumExpansions)
3611      ID.AddInteger(*NumExpansions);
3612  }
3613
3614  static bool classof(const Type *T) {
3615    return T->getTypeClass() == PackExpansion;
3616  }
3617  static bool classof(const PackExpansionType *T) {
3618    return true;
3619  }
3620};
3621
3622/// ObjCObjectType - Represents a class type in Objective C.
3623/// Every Objective C type is a combination of a base type and a
3624/// list of protocols.
3625///
3626/// Given the following declarations:
3627///   @class C;
3628///   @protocol P;
3629///
3630/// 'C' is an ObjCInterfaceType C.  It is sugar for an ObjCObjectType
3631/// with base C and no protocols.
3632///
3633/// 'C<P>' is an ObjCObjectType with base C and protocol list [P].
3634///
3635/// 'id' is a TypedefType which is sugar for an ObjCPointerType whose
3636/// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
3637/// and no protocols.
3638///
3639/// 'id<P>' is an ObjCPointerType whose pointee is an ObjCObjecType
3640/// with base BuiltinType::ObjCIdType and protocol list [P].  Eventually
3641/// this should get its own sugar class to better represent the source.
3642class ObjCObjectType : public Type {
3643  // ObjCObjectType.NumProtocols - the number of protocols stored
3644  // after the ObjCObjectPointerType node.
3645  //
3646  // These protocols are those written directly on the type.  If
3647  // protocol qualifiers ever become additive, the iterators will need
3648  // to get kindof complicated.
3649  //
3650  // In the canonical object type, these are sorted alphabetically
3651  // and uniqued.
3652
3653  /// Either a BuiltinType or an InterfaceType or sugar for either.
3654  QualType BaseType;
3655
3656  ObjCProtocolDecl * const *getProtocolStorage() const {
3657    return const_cast<ObjCObjectType*>(this)->getProtocolStorage();
3658  }
3659
3660  ObjCProtocolDecl **getProtocolStorage();
3661
3662protected:
3663  ObjCObjectType(QualType Canonical, QualType Base,
3664                 ObjCProtocolDecl * const *Protocols, unsigned NumProtocols);
3665
3666  enum Nonce_ObjCInterface { Nonce_ObjCInterface };
3667  ObjCObjectType(enum Nonce_ObjCInterface)
3668        : Type(ObjCInterface, QualType(), false, false, false),
3669      BaseType(QualType(this_(), 0)) {
3670    ObjCObjectTypeBits.NumProtocols = 0;
3671  }
3672
3673public:
3674  /// getBaseType - Gets the base type of this object type.  This is
3675  /// always (possibly sugar for) one of:
3676  ///  - the 'id' builtin type (as opposed to the 'id' type visible to the
3677  ///    user, which is a typedef for an ObjCPointerType)
3678  ///  - the 'Class' builtin type (same caveat)
3679  ///  - an ObjCObjectType (currently always an ObjCInterfaceType)
3680  QualType getBaseType() const { return BaseType; }
3681
3682  bool isObjCId() const {
3683    return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
3684  }
3685  bool isObjCClass() const {
3686    return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
3687  }
3688  bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
3689  bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
3690  bool isObjCUnqualifiedIdOrClass() const {
3691    if (!qual_empty()) return false;
3692    if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
3693      return T->getKind() == BuiltinType::ObjCId ||
3694             T->getKind() == BuiltinType::ObjCClass;
3695    return false;
3696  }
3697  bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
3698  bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
3699
3700  /// Gets the interface declaration for this object type, if the base type
3701  /// really is an interface.
3702  ObjCInterfaceDecl *getInterface() const;
3703
3704  typedef ObjCProtocolDecl * const *qual_iterator;
3705
3706  qual_iterator qual_begin() const { return getProtocolStorage(); }
3707  qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
3708
3709  bool qual_empty() const { return getNumProtocols() == 0; }
3710
3711  /// getNumProtocols - Return the number of qualifying protocols in this
3712  /// interface type, or 0 if there are none.
3713  unsigned getNumProtocols() const { return ObjCObjectTypeBits.NumProtocols; }
3714
3715  /// \brief Fetch a protocol by index.
3716  ObjCProtocolDecl *getProtocol(unsigned I) const {
3717    assert(I < getNumProtocols() && "Out-of-range protocol access");
3718    return qual_begin()[I];
3719  }
3720
3721  bool isSugared() const { return false; }
3722  QualType desugar() const { return QualType(this, 0); }
3723
3724  static bool classof(const Type *T) {
3725    return T->getTypeClass() == ObjCObject ||
3726           T->getTypeClass() == ObjCInterface;
3727  }
3728  static bool classof(const ObjCObjectType *) { return true; }
3729};
3730
3731/// ObjCObjectTypeImpl - A class providing a concrete implementation
3732/// of ObjCObjectType, so as to not increase the footprint of
3733/// ObjCInterfaceType.  Code outside of ASTContext and the core type
3734/// system should not reference this type.
3735class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
3736  friend class ASTContext;
3737
3738  // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
3739  // will need to be modified.
3740
3741  ObjCObjectTypeImpl(QualType Canonical, QualType Base,
3742                     ObjCProtocolDecl * const *Protocols,
3743                     unsigned NumProtocols)
3744    : ObjCObjectType(Canonical, Base, Protocols, NumProtocols) {}
3745
3746public:
3747  void Profile(llvm::FoldingSetNodeID &ID);
3748  static void Profile(llvm::FoldingSetNodeID &ID,
3749                      QualType Base,
3750                      ObjCProtocolDecl *const *protocols,
3751                      unsigned NumProtocols);
3752};
3753
3754inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorage() {
3755  return reinterpret_cast<ObjCProtocolDecl**>(
3756            static_cast<ObjCObjectTypeImpl*>(this) + 1);
3757}
3758
3759/// ObjCInterfaceType - Interfaces are the core concept in Objective-C for
3760/// object oriented design.  They basically correspond to C++ classes.  There
3761/// are two kinds of interface types, normal interfaces like "NSString" and
3762/// qualified interfaces, which are qualified with a protocol list like
3763/// "NSString<NSCopyable, NSAmazing>".
3764///
3765/// ObjCInterfaceType guarantees the following properties when considered
3766/// as a subtype of its superclass, ObjCObjectType:
3767///   - There are no protocol qualifiers.  To reinforce this, code which
3768///     tries to invoke the protocol methods via an ObjCInterfaceType will
3769///     fail to compile.
3770///   - It is its own base type.  That is, if T is an ObjCInterfaceType*,
3771///     T->getBaseType() == QualType(T, 0).
3772class ObjCInterfaceType : public ObjCObjectType {
3773  ObjCInterfaceDecl *Decl;
3774
3775  ObjCInterfaceType(const ObjCInterfaceDecl *D)
3776    : ObjCObjectType(Nonce_ObjCInterface),
3777      Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
3778  friend class ASTContext;  // ASTContext creates these.
3779
3780public:
3781  /// getDecl - Get the declaration of this interface.
3782  ObjCInterfaceDecl *getDecl() const { return Decl; }
3783
3784  bool isSugared() const { return false; }
3785  QualType desugar() const { return QualType(this, 0); }
3786
3787  static bool classof(const Type *T) {
3788    return T->getTypeClass() == ObjCInterface;
3789  }
3790  static bool classof(const ObjCInterfaceType *) { return true; }
3791
3792  // Nonsense to "hide" certain members of ObjCObjectType within this
3793  // class.  People asking for protocols on an ObjCInterfaceType are
3794  // not going to get what they want: ObjCInterfaceTypes are
3795  // guaranteed to have no protocols.
3796  enum {
3797    qual_iterator,
3798    qual_begin,
3799    qual_end,
3800    getNumProtocols,
3801    getProtocol
3802  };
3803};
3804
3805inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
3806  if (const ObjCInterfaceType *T =
3807        getBaseType()->getAs<ObjCInterfaceType>())
3808    return T->getDecl();
3809  return 0;
3810}
3811
3812/// ObjCObjectPointerType - Used to represent a pointer to an
3813/// Objective C object.  These are constructed from pointer
3814/// declarators when the pointee type is an ObjCObjectType (or sugar
3815/// for one).  In addition, the 'id' and 'Class' types are typedefs
3816/// for these, and the protocol-qualified types 'id<P>' and 'Class<P>'
3817/// are translated into these.
3818///
3819/// Pointers to pointers to Objective C objects are still PointerTypes;
3820/// only the first level of pointer gets it own type implementation.
3821class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
3822  QualType PointeeType;
3823
3824  ObjCObjectPointerType(QualType Canonical, QualType Pointee)
3825    : Type(ObjCObjectPointer, Canonical, false, false, false),
3826      PointeeType(Pointee) {}
3827  friend class ASTContext;  // ASTContext creates these.
3828
3829public:
3830  /// getPointeeType - Gets the type pointed to by this ObjC pointer.
3831  /// The result will always be an ObjCObjectType or sugar thereof.
3832  QualType getPointeeType() const { return PointeeType; }
3833
3834  /// getObjCObjectType - Gets the type pointed to by this ObjC
3835  /// pointer.  This method always returns non-null.
3836  ///
3837  /// This method is equivalent to getPointeeType() except that
3838  /// it discards any typedefs (or other sugar) between this
3839  /// type and the "outermost" object type.  So for:
3840  ///   @class A; @protocol P; @protocol Q;
3841  ///   typedef A<P> AP;
3842  ///   typedef A A1;
3843  ///   typedef A1<P> A1P;
3844  ///   typedef A1P<Q> A1PQ;
3845  /// For 'A*', getObjectType() will return 'A'.
3846  /// For 'A<P>*', getObjectType() will return 'A<P>'.
3847  /// For 'AP*', getObjectType() will return 'A<P>'.
3848  /// For 'A1*', getObjectType() will return 'A'.
3849  /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
3850  /// For 'A1P*', getObjectType() will return 'A1<P>'.
3851  /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
3852  ///   adding protocols to a protocol-qualified base discards the
3853  ///   old qualifiers (for now).  But if it didn't, getObjectType()
3854  ///   would return 'A1P<Q>' (and we'd have to make iterating over
3855  ///   qualifiers more complicated).
3856  const ObjCObjectType *getObjectType() const {
3857    return PointeeType->castAs<ObjCObjectType>();
3858  }
3859
3860  /// getInterfaceType - If this pointer points to an Objective C
3861  /// @interface type, gets the type for that interface.  Any protocol
3862  /// qualifiers on the interface are ignored.
3863  ///
3864  /// \return null if the base type for this pointer is 'id' or 'Class'
3865  const ObjCInterfaceType *getInterfaceType() const {
3866    return getObjectType()->getBaseType()->getAs<ObjCInterfaceType>();
3867  }
3868
3869  /// getInterfaceDecl - If this pointer points to an Objective @interface
3870  /// type, gets the declaration for that interface.
3871  ///
3872  /// \return null if the base type for this pointer is 'id' or 'Class'
3873  ObjCInterfaceDecl *getInterfaceDecl() const {
3874    return getObjectType()->getInterface();
3875  }
3876
3877  /// isObjCIdType - True if this is equivalent to the 'id' type, i.e. if
3878  /// its object type is the primitive 'id' type with no protocols.
3879  bool isObjCIdType() const {
3880    return getObjectType()->isObjCUnqualifiedId();
3881  }
3882
3883  /// isObjCClassType - True if this is equivalent to the 'Class' type,
3884  /// i.e. if its object tive is the primitive 'Class' type with no protocols.
3885  bool isObjCClassType() const {
3886    return getObjectType()->isObjCUnqualifiedClass();
3887  }
3888
3889  /// isObjCQualifiedIdType - True if this is equivalent to 'id<P>' for some
3890  /// non-empty set of protocols.
3891  bool isObjCQualifiedIdType() const {
3892    return getObjectType()->isObjCQualifiedId();
3893  }
3894
3895  /// isObjCQualifiedClassType - True if this is equivalent to 'Class<P>' for
3896  /// some non-empty set of protocols.
3897  bool isObjCQualifiedClassType() const {
3898    return getObjectType()->isObjCQualifiedClass();
3899  }
3900
3901  /// An iterator over the qualifiers on the object type.  Provided
3902  /// for convenience.  This will always iterate over the full set of
3903  /// protocols on a type, not just those provided directly.
3904  typedef ObjCObjectType::qual_iterator qual_iterator;
3905
3906  qual_iterator qual_begin() const {
3907    return getObjectType()->qual_begin();
3908  }
3909  qual_iterator qual_end() const {
3910    return getObjectType()->qual_end();
3911  }
3912  bool qual_empty() const { return getObjectType()->qual_empty(); }
3913
3914  /// getNumProtocols - Return the number of qualifying protocols on
3915  /// the object type.
3916  unsigned getNumProtocols() const {
3917    return getObjectType()->getNumProtocols();
3918  }
3919
3920  /// \brief Retrieve a qualifying protocol by index on the object
3921  /// type.
3922  ObjCProtocolDecl *getProtocol(unsigned I) const {
3923    return getObjectType()->getProtocol(I);
3924  }
3925
3926  bool isSugared() const { return false; }
3927  QualType desugar() const { return QualType(this, 0); }
3928
3929  void Profile(llvm::FoldingSetNodeID &ID) {
3930    Profile(ID, getPointeeType());
3931  }
3932  static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
3933    ID.AddPointer(T.getAsOpaquePtr());
3934  }
3935  static bool classof(const Type *T) {
3936    return T->getTypeClass() == ObjCObjectPointer;
3937  }
3938  static bool classof(const ObjCObjectPointerType *) { return true; }
3939};
3940
3941/// A qualifier set is used to build a set of qualifiers.
3942class QualifierCollector : public Qualifiers {
3943public:
3944  QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
3945
3946  /// Collect any qualifiers on the given type and return an
3947  /// unqualified type.  The qualifiers are assumed to be consistent
3948  /// with those already in the type.
3949  const Type *strip(QualType type) {
3950    addFastQualifiers(type.getLocalFastQualifiers());
3951    if (!type.hasLocalNonFastQualifiers())
3952      return type.getTypePtrUnsafe();
3953
3954    const ExtQuals *extQuals = type.getExtQualsUnsafe();
3955    addConsistentQualifiers(extQuals->getQualifiers());
3956    return extQuals->getBaseType();
3957  }
3958
3959  /// Apply the collected qualifiers to the given type.
3960  QualType apply(const ASTContext &Context, QualType QT) const;
3961
3962  /// Apply the collected qualifiers to the given type.
3963  QualType apply(const ASTContext &Context, const Type* T) const;
3964};
3965
3966
3967// Inline function definitions.
3968
3969inline const Type *QualType::getTypePtr() const {
3970  return getCommonPtr()->BaseType;
3971}
3972
3973inline const Type *QualType::getTypePtrOrNull() const {
3974  return (isNull() ? 0 : getCommonPtr()->BaseType);
3975}
3976
3977inline SplitQualType QualType::split() const {
3978  if (!hasLocalNonFastQualifiers())
3979    return SplitQualType(getTypePtrUnsafe(),
3980                         Qualifiers::fromFastMask(getLocalFastQualifiers()));
3981
3982  const ExtQuals *eq = getExtQualsUnsafe();
3983  Qualifiers qs = eq->getQualifiers();
3984  qs.addFastQualifiers(getLocalFastQualifiers());
3985  return SplitQualType(eq->getBaseType(), qs);
3986}
3987
3988inline Qualifiers QualType::getLocalQualifiers() const {
3989  Qualifiers Quals;
3990  if (hasLocalNonFastQualifiers())
3991    Quals = getExtQualsUnsafe()->getQualifiers();
3992  Quals.addFastQualifiers(getLocalFastQualifiers());
3993  return Quals;
3994}
3995
3996inline Qualifiers QualType::getQualifiers() const {
3997  Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
3998  quals.addFastQualifiers(getLocalFastQualifiers());
3999  return quals;
4000}
4001
4002inline unsigned QualType::getCVRQualifiers() const {
4003  unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
4004  cvr |= getLocalCVRQualifiers();
4005  return cvr;
4006}
4007
4008inline QualType QualType::getCanonicalType() const {
4009  QualType canon = getCommonPtr()->CanonicalType;
4010  return canon.withFastQualifiers(getLocalFastQualifiers());
4011}
4012
4013inline bool QualType::isCanonical() const {
4014  return getTypePtr()->isCanonicalUnqualified();
4015}
4016
4017inline bool QualType::isCanonicalAsParam() const {
4018  if (!isCanonical()) return false;
4019  if (hasLocalQualifiers()) return false;
4020
4021  const Type *T = getTypePtr();
4022  if (T->isVariablyModifiedType() && T->hasSizedVLAType())
4023    return false;
4024
4025  return !isa<FunctionType>(T) && !isa<ArrayType>(T);
4026}
4027
4028inline bool QualType::isConstQualified() const {
4029  return isLocalConstQualified() ||
4030         getCommonPtr()->CanonicalType.isLocalConstQualified();
4031}
4032
4033inline bool QualType::isRestrictQualified() const {
4034  return isLocalRestrictQualified() ||
4035         getCommonPtr()->CanonicalType.isLocalRestrictQualified();
4036}
4037
4038
4039inline bool QualType::isVolatileQualified() const {
4040  return isLocalVolatileQualified() ||
4041         getCommonPtr()->CanonicalType.isLocalVolatileQualified();
4042}
4043
4044inline bool QualType::hasQualifiers() const {
4045  return hasLocalQualifiers() ||
4046         getCommonPtr()->CanonicalType.hasLocalQualifiers();
4047}
4048
4049inline QualType QualType::getUnqualifiedType() const {
4050  if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
4051    return QualType(getTypePtr(), 0);
4052
4053  return QualType(getSplitUnqualifiedTypeImpl(*this).first, 0);
4054}
4055
4056inline SplitQualType QualType::getSplitUnqualifiedType() const {
4057  if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
4058    return split();
4059
4060  return getSplitUnqualifiedTypeImpl(*this);
4061}
4062
4063inline void QualType::removeLocalConst() {
4064  removeLocalFastQualifiers(Qualifiers::Const);
4065}
4066
4067inline void QualType::removeLocalRestrict() {
4068  removeLocalFastQualifiers(Qualifiers::Restrict);
4069}
4070
4071inline void QualType::removeLocalVolatile() {
4072  removeLocalFastQualifiers(Qualifiers::Volatile);
4073}
4074
4075inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
4076  assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits");
4077  assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask);
4078
4079  // Fast path: we don't need to touch the slow qualifiers.
4080  removeLocalFastQualifiers(Mask);
4081}
4082
4083/// getAddressSpace - Return the address space of this type.
4084inline unsigned QualType::getAddressSpace() const {
4085  return getQualifiers().getAddressSpace();
4086}
4087
4088/// getObjCGCAttr - Return the gc attribute of this type.
4089inline Qualifiers::GC QualType::getObjCGCAttr() const {
4090  return getQualifiers().getObjCGCAttr();
4091}
4092
4093inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
4094  if (const PointerType *PT = t.getAs<PointerType>()) {
4095    if (const FunctionType *FT = PT->getPointeeType()->getAs<FunctionType>())
4096      return FT->getExtInfo();
4097  } else if (const FunctionType *FT = t.getAs<FunctionType>())
4098    return FT->getExtInfo();
4099
4100  return FunctionType::ExtInfo();
4101}
4102
4103inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
4104  return getFunctionExtInfo(*t);
4105}
4106
4107/// \brief Determine whether this set of qualifiers is a superset of the given
4108/// set of qualifiers.
4109inline bool Qualifiers::isSupersetOf(Qualifiers Other) const {
4110  return Mask != Other.Mask && (Mask | Other.Mask) == Mask;
4111}
4112
4113/// isMoreQualifiedThan - Determine whether this type is more
4114/// qualified than the Other type. For example, "const volatile int"
4115/// is more qualified than "const int", "volatile int", and
4116/// "int". However, it is not more qualified than "const volatile
4117/// int".
4118inline bool QualType::isMoreQualifiedThan(QualType other) const {
4119  Qualifiers myQuals = getQualifiers();
4120  Qualifiers otherQuals = other.getQualifiers();
4121  return (myQuals != otherQuals && myQuals.compatiblyIncludes(otherQuals));
4122}
4123
4124/// isAtLeastAsQualifiedAs - Determine whether this type is at last
4125/// as qualified as the Other type. For example, "const volatile
4126/// int" is at least as qualified as "const int", "volatile int",
4127/// "int", and "const volatile int".
4128inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
4129  return getQualifiers().compatiblyIncludes(other.getQualifiers());
4130}
4131
4132/// getNonReferenceType - If Type is a reference type (e.g., const
4133/// int&), returns the type that the reference refers to ("const
4134/// int"). Otherwise, returns the type itself. This routine is used
4135/// throughout Sema to implement C++ 5p6:
4136///
4137///   If an expression initially has the type "reference to T" (8.3.2,
4138///   8.5.3), the type is adjusted to "T" prior to any further
4139///   analysis, the expression designates the object or function
4140///   denoted by the reference, and the expression is an lvalue.
4141inline QualType QualType::getNonReferenceType() const {
4142  if (const ReferenceType *RefType = (*this)->getAs<ReferenceType>())
4143    return RefType->getPointeeType();
4144  else
4145    return *this;
4146}
4147
4148inline bool Type::isFunctionType() const {
4149  return isa<FunctionType>(CanonicalType);
4150}
4151inline bool Type::isPointerType() const {
4152  return isa<PointerType>(CanonicalType);
4153}
4154inline bool Type::isAnyPointerType() const {
4155  return isPointerType() || isObjCObjectPointerType();
4156}
4157inline bool Type::isBlockPointerType() const {
4158  return isa<BlockPointerType>(CanonicalType);
4159}
4160inline bool Type::isReferenceType() const {
4161  return isa<ReferenceType>(CanonicalType);
4162}
4163inline bool Type::isLValueReferenceType() const {
4164  return isa<LValueReferenceType>(CanonicalType);
4165}
4166inline bool Type::isRValueReferenceType() const {
4167  return isa<RValueReferenceType>(CanonicalType);
4168}
4169inline bool Type::isFunctionPointerType() const {
4170  if (const PointerType *T = getAs<PointerType>())
4171    return T->getPointeeType()->isFunctionType();
4172  else
4173    return false;
4174}
4175inline bool Type::isMemberPointerType() const {
4176  return isa<MemberPointerType>(CanonicalType);
4177}
4178inline bool Type::isMemberFunctionPointerType() const {
4179  if (const MemberPointerType* T = getAs<MemberPointerType>())
4180    return T->isMemberFunctionPointer();
4181  else
4182    return false;
4183}
4184inline bool Type::isMemberDataPointerType() const {
4185  if (const MemberPointerType* T = getAs<MemberPointerType>())
4186    return T->isMemberDataPointer();
4187  else
4188    return false;
4189}
4190inline bool Type::isArrayType() const {
4191  return isa<ArrayType>(CanonicalType);
4192}
4193inline bool Type::isConstantArrayType() const {
4194  return isa<ConstantArrayType>(CanonicalType);
4195}
4196inline bool Type::isIncompleteArrayType() const {
4197  return isa<IncompleteArrayType>(CanonicalType);
4198}
4199inline bool Type::isVariableArrayType() const {
4200  return isa<VariableArrayType>(CanonicalType);
4201}
4202inline bool Type::isDependentSizedArrayType() const {
4203  return isa<DependentSizedArrayType>(CanonicalType);
4204}
4205inline bool Type::isBuiltinType() const {
4206  return isa<BuiltinType>(CanonicalType);
4207}
4208inline bool Type::isRecordType() const {
4209  return isa<RecordType>(CanonicalType);
4210}
4211inline bool Type::isEnumeralType() const {
4212  return isa<EnumType>(CanonicalType);
4213}
4214inline bool Type::isAnyComplexType() const {
4215  return isa<ComplexType>(CanonicalType);
4216}
4217inline bool Type::isVectorType() const {
4218  return isa<VectorType>(CanonicalType);
4219}
4220inline bool Type::isExtVectorType() const {
4221  return isa<ExtVectorType>(CanonicalType);
4222}
4223inline bool Type::isObjCObjectPointerType() const {
4224  return isa<ObjCObjectPointerType>(CanonicalType);
4225}
4226inline bool Type::isObjCObjectType() const {
4227  return isa<ObjCObjectType>(CanonicalType);
4228}
4229inline bool Type::isObjCObjectOrInterfaceType() const {
4230  return isa<ObjCInterfaceType>(CanonicalType) ||
4231    isa<ObjCObjectType>(CanonicalType);
4232}
4233
4234inline bool Type::isObjCQualifiedIdType() const {
4235  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4236    return OPT->isObjCQualifiedIdType();
4237  return false;
4238}
4239inline bool Type::isObjCQualifiedClassType() const {
4240  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4241    return OPT->isObjCQualifiedClassType();
4242  return false;
4243}
4244inline bool Type::isObjCIdType() const {
4245  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4246    return OPT->isObjCIdType();
4247  return false;
4248}
4249inline bool Type::isObjCClassType() const {
4250  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4251    return OPT->isObjCClassType();
4252  return false;
4253}
4254inline bool Type::isObjCSelType() const {
4255  if (const PointerType *OPT = getAs<PointerType>())
4256    return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
4257  return false;
4258}
4259inline bool Type::isObjCBuiltinType() const {
4260  return isObjCIdType() || isObjCClassType() || isObjCSelType();
4261}
4262inline bool Type::isTemplateTypeParmType() const {
4263  return isa<TemplateTypeParmType>(CanonicalType);
4264}
4265
4266inline bool Type::isSpecificBuiltinType(unsigned K) const {
4267  if (const BuiltinType *BT = getAs<BuiltinType>())
4268    if (BT->getKind() == (BuiltinType::Kind) K)
4269      return true;
4270  return false;
4271}
4272
4273inline bool Type::isPlaceholderType() const {
4274  if (const BuiltinType *BT = getAs<BuiltinType>())
4275    return BT->isPlaceholderType();
4276  return false;
4277}
4278
4279/// \brief Determines whether this is a type for which one can define
4280/// an overloaded operator.
4281inline bool Type::isOverloadableType() const {
4282  return isDependentType() || isRecordType() || isEnumeralType();
4283}
4284
4285inline bool Type::hasPointerRepresentation() const {
4286  return (isPointerType() || isReferenceType() || isBlockPointerType() ||
4287          isObjCObjectPointerType() || isNullPtrType());
4288}
4289
4290inline bool Type::hasObjCPointerRepresentation() const {
4291  return isObjCObjectPointerType();
4292}
4293
4294inline const Type *Type::getBaseElementTypeUnsafe() const {
4295  const Type *type = this;
4296  while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
4297    type = arrayType->getElementType().getTypePtr();
4298  return type;
4299}
4300
4301/// Insertion operator for diagnostics.  This allows sending QualType's into a
4302/// diagnostic with <<.
4303inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
4304                                           QualType T) {
4305  DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
4306                  Diagnostic::ak_qualtype);
4307  return DB;
4308}
4309
4310/// Insertion operator for partial diagnostics.  This allows sending QualType's
4311/// into a diagnostic with <<.
4312inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
4313                                           QualType T) {
4314  PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
4315                  Diagnostic::ak_qualtype);
4316  return PD;
4317}
4318
4319// Helper class template that is used by Type::getAs to ensure that one does
4320// not try to look through a qualified type to get to an array type.
4321template<typename T,
4322         bool isArrayType = (llvm::is_same<T, ArrayType>::value ||
4323                             llvm::is_base_of<ArrayType, T>::value)>
4324struct ArrayType_cannot_be_used_with_getAs { };
4325
4326template<typename T>
4327struct ArrayType_cannot_be_used_with_getAs<T, true>;
4328
4329/// Member-template getAs<specific type>'.
4330template <typename T> const T *Type::getAs() const {
4331  ArrayType_cannot_be_used_with_getAs<T> at;
4332  (void)at;
4333
4334  // If this is directly a T type, return it.
4335  if (const T *Ty = dyn_cast<T>(this))
4336    return Ty;
4337
4338  // If the canonical form of this type isn't the right kind, reject it.
4339  if (!isa<T>(CanonicalType))
4340    return 0;
4341
4342  // If this is a typedef for the type, strip the typedef off without
4343  // losing all typedef information.
4344  return cast<T>(getUnqualifiedDesugaredType());
4345}
4346
4347inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
4348  // If this is directly an array type, return it.
4349  if (const ArrayType *arr = dyn_cast<ArrayType>(this))
4350    return arr;
4351
4352  // If the canonical form of this type isn't the right kind, reject it.
4353  if (!isa<ArrayType>(CanonicalType))
4354    return 0;
4355
4356  // If this is a typedef for the type, strip the typedef off without
4357  // losing all typedef information.
4358  return cast<ArrayType>(getUnqualifiedDesugaredType());
4359}
4360
4361template <typename T> const T *Type::castAs() const {
4362  ArrayType_cannot_be_used_with_getAs<T> at;
4363  (void) at;
4364
4365  assert(isa<T>(CanonicalType));
4366  if (const T *ty = dyn_cast<T>(this)) return ty;
4367  return cast<T>(getUnqualifiedDesugaredType());
4368}
4369
4370inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
4371  assert(isa<ArrayType>(CanonicalType));
4372  if (const ArrayType *arr = dyn_cast<ArrayType>(this)) return arr;
4373  return cast<ArrayType>(getUnqualifiedDesugaredType());
4374}
4375
4376}  // end namespace clang
4377
4378#endif
4379