Type.h revision 8b5b4099c61a136e9a1714c4d8a593febe942268
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': return 0;
2176    case 'y': return 1;
2177    case 'z': return 2;
2178    case 'w': 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 : 10;
2440
2441  /// HasExceptionSpec - Whether this function has an exception spec at all.
2442  unsigned HasExceptionSpec : 1;
2443
2444  /// HasAnyExceptionSpec - Whether this function has a throw(...) spec.
2445  unsigned HasAnyExceptionSpec : 1;
2446
2447  /// ArgInfo - There is an variable size array after the class in memory that
2448  /// holds the argument types.
2449
2450  /// Exceptions - There is another variable size array after ArgInfo that
2451  /// holds the exception types.
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 = hasExceptionSpec() ?
2467        (hasAnyExceptionSpec() ? EST_DynamicAny : EST_Dynamic) : EST_None;
2468    EPI.TypeQuals = static_cast<unsigned char>(getTypeQuals());
2469    EPI.RefQualifier = getRefQualifier();
2470    EPI.NumExceptions = NumExceptions;
2471    EPI.Exceptions = exception_begin();
2472    return EPI;
2473  }
2474
2475  bool hasExceptionSpec() const { return HasExceptionSpec; }
2476  bool hasAnyExceptionSpec() const { return HasAnyExceptionSpec; }
2477  unsigned getNumExceptions() const { return NumExceptions; }
2478  QualType getExceptionType(unsigned i) const {
2479    assert(i < NumExceptions && "Invalid exception number!");
2480    return exception_begin()[i];
2481  }
2482  bool hasEmptyExceptionSpec() const {
2483    return hasExceptionSpec() && !hasAnyExceptionSpec() &&
2484      getNumExceptions() == 0;
2485  }
2486
2487  using FunctionType::isVariadic;
2488
2489  /// \brief Determines whether this function prototype contains a
2490  /// parameter pack at the end.
2491  ///
2492  /// A function template whose last parameter is a parameter pack can be
2493  /// called with an arbitrary number of arguments, much like a variadic
2494  /// function. However,
2495  bool isTemplateVariadic() const;
2496
2497  unsigned getTypeQuals() const { return FunctionType::getTypeQuals(); }
2498
2499
2500  /// \brief Retrieve the ref-qualifier associated with this function type.
2501  RefQualifierKind getRefQualifier() const {
2502    return FunctionType::getRefQualifier();
2503  }
2504
2505  typedef const QualType *arg_type_iterator;
2506  arg_type_iterator arg_type_begin() const {
2507    return reinterpret_cast<const QualType *>(this+1);
2508  }
2509  arg_type_iterator arg_type_end() const { return arg_type_begin()+NumArgs; }
2510
2511  typedef const QualType *exception_iterator;
2512  exception_iterator exception_begin() const {
2513    // exceptions begin where arguments end
2514    return arg_type_end();
2515  }
2516  exception_iterator exception_end() const {
2517    return exception_begin() + NumExceptions;
2518  }
2519
2520  bool isSugared() const { return false; }
2521  QualType desugar() const { return QualType(this, 0); }
2522
2523  static bool classof(const Type *T) {
2524    return T->getTypeClass() == FunctionProto;
2525  }
2526  static bool classof(const FunctionProtoType *) { return true; }
2527
2528  void Profile(llvm::FoldingSetNodeID &ID);
2529  static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
2530                      arg_type_iterator ArgTys, unsigned NumArgs,
2531                      const ExtProtoInfo &EPI);
2532};
2533
2534
2535/// \brief Represents the dependent type named by a dependently-scoped
2536/// typename using declaration, e.g.
2537///   using typename Base<T>::foo;
2538/// Template instantiation turns these into the underlying type.
2539class UnresolvedUsingType : public Type {
2540  UnresolvedUsingTypenameDecl *Decl;
2541
2542  UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
2543    : Type(UnresolvedUsing, QualType(), true, false,
2544           /*ContainsUnexpandedParameterPack=*/false),
2545      Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
2546  friend class ASTContext; // ASTContext creates these.
2547public:
2548
2549  UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
2550
2551  bool isSugared() const { return false; }
2552  QualType desugar() const { return QualType(this, 0); }
2553
2554  static bool classof(const Type *T) {
2555    return T->getTypeClass() == UnresolvedUsing;
2556  }
2557  static bool classof(const UnresolvedUsingType *) { return true; }
2558
2559  void Profile(llvm::FoldingSetNodeID &ID) {
2560    return Profile(ID, Decl);
2561  }
2562  static void Profile(llvm::FoldingSetNodeID &ID,
2563                      UnresolvedUsingTypenameDecl *D) {
2564    ID.AddPointer(D);
2565  }
2566};
2567
2568
2569class TypedefType : public Type {
2570  TypedefDecl *Decl;
2571protected:
2572  TypedefType(TypeClass tc, const TypedefDecl *D, QualType can)
2573    : Type(tc, can, can->isDependentType(), can->isVariablyModifiedType(),
2574           /*ContainsUnexpandedParameterPack=*/false),
2575      Decl(const_cast<TypedefDecl*>(D)) {
2576    assert(!isa<TypedefType>(can) && "Invalid canonical type");
2577  }
2578  friend class ASTContext;  // ASTContext creates these.
2579public:
2580
2581  TypedefDecl *getDecl() const { return Decl; }
2582
2583  bool isSugared() const { return true; }
2584  QualType desugar() const;
2585
2586  static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
2587  static bool classof(const TypedefType *) { return true; }
2588};
2589
2590/// TypeOfExprType (GCC extension).
2591class TypeOfExprType : public Type {
2592  Expr *TOExpr;
2593
2594protected:
2595  TypeOfExprType(Expr *E, QualType can = QualType());
2596  friend class ASTContext;  // ASTContext creates these.
2597public:
2598  Expr *getUnderlyingExpr() const { return TOExpr; }
2599
2600  /// \brief Remove a single level of sugar.
2601  QualType desugar() const;
2602
2603  /// \brief Returns whether this type directly provides sugar.
2604  bool isSugared() const { return true; }
2605
2606  static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
2607  static bool classof(const TypeOfExprType *) { return true; }
2608};
2609
2610/// \brief Internal representation of canonical, dependent
2611/// typeof(expr) types.
2612///
2613/// This class is used internally by the ASTContext to manage
2614/// canonical, dependent types, only. Clients will only see instances
2615/// of this class via TypeOfExprType nodes.
2616class DependentTypeOfExprType
2617  : public TypeOfExprType, public llvm::FoldingSetNode {
2618  const ASTContext &Context;
2619
2620public:
2621  DependentTypeOfExprType(const ASTContext &Context, Expr *E)
2622    : TypeOfExprType(E), Context(Context) { }
2623
2624  bool isSugared() const { return false; }
2625  QualType desugar() const { return QualType(this, 0); }
2626
2627  void Profile(llvm::FoldingSetNodeID &ID) {
2628    Profile(ID, Context, getUnderlyingExpr());
2629  }
2630
2631  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2632                      Expr *E);
2633};
2634
2635/// TypeOfType (GCC extension).
2636class TypeOfType : public Type {
2637  QualType TOType;
2638  TypeOfType(QualType T, QualType can)
2639    : Type(TypeOf, can, T->isDependentType(), T->isVariablyModifiedType(),
2640           T->containsUnexpandedParameterPack()),
2641      TOType(T) {
2642    assert(!isa<TypedefType>(can) && "Invalid canonical type");
2643  }
2644  friend class ASTContext;  // ASTContext creates these.
2645public:
2646  QualType getUnderlyingType() const { return TOType; }
2647
2648  /// \brief Remove a single level of sugar.
2649  QualType desugar() const { return getUnderlyingType(); }
2650
2651  /// \brief Returns whether this type directly provides sugar.
2652  bool isSugared() const { return true; }
2653
2654  static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
2655  static bool classof(const TypeOfType *) { return true; }
2656};
2657
2658/// DecltypeType (C++0x)
2659class DecltypeType : public Type {
2660  Expr *E;
2661
2662  // FIXME: We could get rid of UnderlyingType if we wanted to: We would have to
2663  // Move getDesugaredType to ASTContext so that it can call getDecltypeForExpr
2664  // from it.
2665  QualType UnderlyingType;
2666
2667protected:
2668  DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
2669  friend class ASTContext;  // ASTContext creates these.
2670public:
2671  Expr *getUnderlyingExpr() const { return E; }
2672  QualType getUnderlyingType() const { return UnderlyingType; }
2673
2674  /// \brief Remove a single level of sugar.
2675  QualType desugar() const { return getUnderlyingType(); }
2676
2677  /// \brief Returns whether this type directly provides sugar.
2678  bool isSugared() const { return !isDependentType(); }
2679
2680  static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
2681  static bool classof(const DecltypeType *) { return true; }
2682};
2683
2684/// \brief Internal representation of canonical, dependent
2685/// decltype(expr) types.
2686///
2687/// This class is used internally by the ASTContext to manage
2688/// canonical, dependent types, only. Clients will only see instances
2689/// of this class via DecltypeType nodes.
2690class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
2691  const ASTContext &Context;
2692
2693public:
2694  DependentDecltypeType(const ASTContext &Context, Expr *E);
2695
2696  bool isSugared() const { return false; }
2697  QualType desugar() const { return QualType(this, 0); }
2698
2699  void Profile(llvm::FoldingSetNodeID &ID) {
2700    Profile(ID, Context, getUnderlyingExpr());
2701  }
2702
2703  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2704                      Expr *E);
2705};
2706
2707class TagType : public Type {
2708  /// Stores the TagDecl associated with this type. The decl may point to any
2709  /// TagDecl that declares the entity.
2710  TagDecl * decl;
2711
2712protected:
2713  TagType(TypeClass TC, const TagDecl *D, QualType can);
2714
2715public:
2716  TagDecl *getDecl() const;
2717
2718  /// @brief Determines whether this type is in the process of being
2719  /// defined.
2720  bool isBeingDefined() const;
2721
2722  static bool classof(const Type *T) {
2723    return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast;
2724  }
2725  static bool classof(const TagType *) { return true; }
2726  static bool classof(const RecordType *) { return true; }
2727  static bool classof(const EnumType *) { return true; }
2728};
2729
2730/// RecordType - This is a helper class that allows the use of isa/cast/dyncast
2731/// to detect TagType objects of structs/unions/classes.
2732class RecordType : public TagType {
2733protected:
2734  explicit RecordType(const RecordDecl *D)
2735    : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) { }
2736  explicit RecordType(TypeClass TC, RecordDecl *D)
2737    : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) { }
2738  friend class ASTContext;   // ASTContext creates these.
2739public:
2740
2741  RecordDecl *getDecl() const {
2742    return reinterpret_cast<RecordDecl*>(TagType::getDecl());
2743  }
2744
2745  // FIXME: This predicate is a helper to QualType/Type. It needs to
2746  // recursively check all fields for const-ness. If any field is declared
2747  // const, it needs to return false.
2748  bool hasConstFields() const { return false; }
2749
2750  bool isSugared() const { return false; }
2751  QualType desugar() const { return QualType(this, 0); }
2752
2753  static bool classof(const TagType *T);
2754  static bool classof(const Type *T) {
2755    return isa<TagType>(T) && classof(cast<TagType>(T));
2756  }
2757  static bool classof(const RecordType *) { return true; }
2758};
2759
2760/// EnumType - This is a helper class that allows the use of isa/cast/dyncast
2761/// to detect TagType objects of enums.
2762class EnumType : public TagType {
2763  explicit EnumType(const EnumDecl *D)
2764    : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) { }
2765  friend class ASTContext;   // ASTContext creates these.
2766public:
2767
2768  EnumDecl *getDecl() const {
2769    return reinterpret_cast<EnumDecl*>(TagType::getDecl());
2770  }
2771
2772  bool isSugared() const { return false; }
2773  QualType desugar() const { return QualType(this, 0); }
2774
2775  static bool classof(const TagType *T);
2776  static bool classof(const Type *T) {
2777    return isa<TagType>(T) && classof(cast<TagType>(T));
2778  }
2779  static bool classof(const EnumType *) { return true; }
2780};
2781
2782/// AttributedType - An attributed type is a type to which a type
2783/// attribute has been applied.  The "modified type" is the
2784/// fully-sugared type to which the attributed type was applied;
2785/// generally it is not canonically equivalent to the attributed type.
2786/// The "equivalent type" is the minimally-desugared type which the
2787/// type is canonically equivalent to.
2788///
2789/// For example, in the following attributed type:
2790///     int32_t __attribute__((vector_size(16)))
2791///   - the modified type is the TypedefType for int32_t
2792///   - the equivalent type is VectorType(16, int32_t)
2793///   - the canonical type is VectorType(16, int)
2794class AttributedType : public Type, public llvm::FoldingSetNode {
2795public:
2796  // It is really silly to have yet another attribute-kind enum, but
2797  // clang::attr::Kind doesn't currently cover the pure type attrs.
2798  enum Kind {
2799    // Expression operand.
2800    attr_address_space,
2801    attr_regparm,
2802    attr_vector_size,
2803    attr_neon_vector_type,
2804    attr_neon_polyvector_type,
2805
2806    FirstExprOperandKind = attr_address_space,
2807    LastExprOperandKind = attr_neon_polyvector_type,
2808
2809    // Enumerated operand (string or keyword).
2810    attr_objc_gc,
2811
2812    FirstEnumOperandKind = attr_objc_gc,
2813    LastEnumOperandKind = attr_objc_gc,
2814
2815    // No operand.
2816    attr_noreturn,
2817    attr_cdecl,
2818    attr_fastcall,
2819    attr_stdcall,
2820    attr_thiscall,
2821    attr_pascal
2822  };
2823
2824private:
2825  QualType ModifiedType;
2826  QualType EquivalentType;
2827
2828  friend class ASTContext; // creates these
2829
2830  AttributedType(QualType canon, Kind attrKind,
2831                 QualType modified, QualType equivalent)
2832    : Type(Attributed, canon, canon->isDependentType(),
2833           canon->isVariablyModifiedType(),
2834           canon->containsUnexpandedParameterPack()),
2835      ModifiedType(modified), EquivalentType(equivalent) {
2836    AttributedTypeBits.AttrKind = attrKind;
2837  }
2838
2839public:
2840  Kind getAttrKind() const {
2841    return static_cast<Kind>(AttributedTypeBits.AttrKind);
2842  }
2843
2844  QualType getModifiedType() const { return ModifiedType; }
2845  QualType getEquivalentType() const { return EquivalentType; }
2846
2847  bool isSugared() const { return true; }
2848  QualType desugar() const { return getEquivalentType(); }
2849
2850  void Profile(llvm::FoldingSetNodeID &ID) {
2851    Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
2852  }
2853
2854  static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
2855                      QualType modified, QualType equivalent) {
2856    ID.AddInteger(attrKind);
2857    ID.AddPointer(modified.getAsOpaquePtr());
2858    ID.AddPointer(equivalent.getAsOpaquePtr());
2859  }
2860
2861  static bool classof(const Type *T) {
2862    return T->getTypeClass() == Attributed;
2863  }
2864  static bool classof(const AttributedType *T) { return true; }
2865};
2866
2867class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
2868  unsigned Depth : 15;
2869  unsigned ParameterPack : 1;
2870  unsigned Index : 16;
2871  IdentifierInfo *Name;
2872
2873  TemplateTypeParmType(unsigned D, unsigned I, bool PP, IdentifierInfo *N,
2874                       QualType Canon)
2875    : Type(TemplateTypeParm, Canon, /*Dependent=*/true,
2876           /*VariablyModified=*/false, PP),
2877      Depth(D), ParameterPack(PP), Index(I), Name(N) { }
2878
2879  TemplateTypeParmType(unsigned D, unsigned I, bool PP)
2880    : Type(TemplateTypeParm, QualType(this, 0), /*Dependent=*/true,
2881           /*VariablyModified=*/false, PP),
2882      Depth(D), ParameterPack(PP), Index(I), Name(0) { }
2883
2884  friend class ASTContext;  // ASTContext creates these
2885
2886public:
2887  unsigned getDepth() const { return Depth; }
2888  unsigned getIndex() const { return Index; }
2889  bool isParameterPack() const { return ParameterPack; }
2890  IdentifierInfo *getName() const { return Name; }
2891
2892  bool isSugared() const { return false; }
2893  QualType desugar() const { return QualType(this, 0); }
2894
2895  void Profile(llvm::FoldingSetNodeID &ID) {
2896    Profile(ID, Depth, Index, ParameterPack, Name);
2897  }
2898
2899  static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
2900                      unsigned Index, bool ParameterPack,
2901                      IdentifierInfo *Name) {
2902    ID.AddInteger(Depth);
2903    ID.AddInteger(Index);
2904    ID.AddBoolean(ParameterPack);
2905    ID.AddPointer(Name);
2906  }
2907
2908  static bool classof(const Type *T) {
2909    return T->getTypeClass() == TemplateTypeParm;
2910  }
2911  static bool classof(const TemplateTypeParmType *T) { return true; }
2912};
2913
2914/// \brief Represents the result of substituting a type for a template
2915/// type parameter.
2916///
2917/// Within an instantiated template, all template type parameters have
2918/// been replaced with these.  They are used solely to record that a
2919/// type was originally written as a template type parameter;
2920/// therefore they are never canonical.
2921class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
2922  // The original type parameter.
2923  const TemplateTypeParmType *Replaced;
2924
2925  SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
2926    : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(),
2927           Canon->isVariablyModifiedType(),
2928           Canon->containsUnexpandedParameterPack()),
2929      Replaced(Param) { }
2930
2931  friend class ASTContext;
2932
2933public:
2934  IdentifierInfo *getName() const { return Replaced->getName(); }
2935
2936  /// Gets the template parameter that was substituted for.
2937  const TemplateTypeParmType *getReplacedParameter() const {
2938    return Replaced;
2939  }
2940
2941  /// Gets the type that was substituted for the template
2942  /// parameter.
2943  QualType getReplacementType() const {
2944    return getCanonicalTypeInternal();
2945  }
2946
2947  bool isSugared() const { return true; }
2948  QualType desugar() const { return getReplacementType(); }
2949
2950  void Profile(llvm::FoldingSetNodeID &ID) {
2951    Profile(ID, getReplacedParameter(), getReplacementType());
2952  }
2953  static void Profile(llvm::FoldingSetNodeID &ID,
2954                      const TemplateTypeParmType *Replaced,
2955                      QualType Replacement) {
2956    ID.AddPointer(Replaced);
2957    ID.AddPointer(Replacement.getAsOpaquePtr());
2958  }
2959
2960  static bool classof(const Type *T) {
2961    return T->getTypeClass() == SubstTemplateTypeParm;
2962  }
2963  static bool classof(const SubstTemplateTypeParmType *T) { return true; }
2964};
2965
2966/// \brief Represents the result of substituting a set of types for a template
2967/// type parameter pack.
2968///
2969/// When a pack expansion in the source code contains multiple parameter packs
2970/// and those parameter packs correspond to different levels of template
2971/// parameter lists, this type node is used to represent a template type
2972/// parameter pack from an outer level, which has already had its argument pack
2973/// substituted but that still lives within a pack expansion that itself
2974/// could not be instantiated. When actually performing a substitution into
2975/// that pack expansion (e.g., when all template parameters have corresponding
2976/// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
2977/// at the current pack substitution index.
2978class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
2979  /// \brief The original type parameter.
2980  const TemplateTypeParmType *Replaced;
2981
2982  /// \brief A pointer to the set of template arguments that this
2983  /// parameter pack is instantiated with.
2984  const TemplateArgument *Arguments;
2985
2986  /// \brief The number of template arguments in \c Arguments.
2987  unsigned NumArguments;
2988
2989  SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
2990                                QualType Canon,
2991                                const TemplateArgument &ArgPack);
2992
2993  friend class ASTContext;
2994
2995public:
2996  IdentifierInfo *getName() const { return Replaced->getName(); }
2997
2998  /// Gets the template parameter that was substituted for.
2999  const TemplateTypeParmType *getReplacedParameter() const {
3000    return Replaced;
3001  }
3002
3003  bool isSugared() const { return false; }
3004  QualType desugar() const { return QualType(this, 0); }
3005
3006  TemplateArgument getArgumentPack() const;
3007
3008  void Profile(llvm::FoldingSetNodeID &ID);
3009  static void Profile(llvm::FoldingSetNodeID &ID,
3010                      const TemplateTypeParmType *Replaced,
3011                      const TemplateArgument &ArgPack);
3012
3013  static bool classof(const Type *T) {
3014    return T->getTypeClass() == SubstTemplateTypeParmPack;
3015  }
3016  static bool classof(const SubstTemplateTypeParmPackType *T) { return true; }
3017};
3018
3019/// \brief Represents a C++0x auto type.
3020///
3021/// These types are usually a placeholder for a deduced type. However, within
3022/// templates and before the initializer is attached, there is no deduced type
3023/// and an auto type is type-dependent and canonical.
3024class AutoType : public Type, public llvm::FoldingSetNode {
3025  AutoType(QualType DeducedType)
3026    : Type(Auto, DeducedType.isNull() ? QualType(this, 0) : DeducedType,
3027           /*Dependent=*/DeducedType.isNull(),
3028           /*VariablyModified=*/false, /*ContainsParameterPack=*/false) {
3029    assert((DeducedType.isNull() || !DeducedType->isDependentType()) &&
3030           "deduced a dependent type for auto");
3031  }
3032
3033  friend class ASTContext;  // ASTContext creates these
3034
3035public:
3036  bool isSugared() const { return isDeduced(); }
3037  QualType desugar() const { return getCanonicalTypeInternal(); }
3038
3039  QualType getDeducedType() const {
3040    return isDeduced() ? getCanonicalTypeInternal() : QualType();
3041  }
3042  bool isDeduced() const {
3043    return !isDependentType();
3044  }
3045
3046  void Profile(llvm::FoldingSetNodeID &ID) {
3047    Profile(ID, getDeducedType());
3048  }
3049
3050  static void Profile(llvm::FoldingSetNodeID &ID,
3051                      QualType Deduced) {
3052    ID.AddPointer(Deduced.getAsOpaquePtr());
3053  }
3054
3055  static bool classof(const Type *T) {
3056    return T->getTypeClass() == Auto;
3057  }
3058  static bool classof(const AutoType *T) { return true; }
3059};
3060
3061/// \brief Represents the type of a template specialization as written
3062/// in the source code.
3063///
3064/// Template specialization types represent the syntactic form of a
3065/// template-id that refers to a type, e.g., @c vector<int>. Some
3066/// template specialization types are syntactic sugar, whose canonical
3067/// type will point to some other type node that represents the
3068/// instantiation or class template specialization. For example, a
3069/// class template specialization type of @c vector<int> will refer to
3070/// a tag type for the instantiation
3071/// @c std::vector<int, std::allocator<int>>.
3072///
3073/// Other template specialization types, for which the template name
3074/// is dependent, may be canonical types. These types are always
3075/// dependent.
3076class TemplateSpecializationType
3077  : public Type, public llvm::FoldingSetNode {
3078  /// \brief The name of the template being specialized.
3079  TemplateName Template;
3080
3081  /// \brief - The number of template arguments named in this class
3082  /// template specialization.
3083  unsigned NumArgs;
3084
3085  TemplateSpecializationType(TemplateName T,
3086                             const TemplateArgument *Args,
3087                             unsigned NumArgs, QualType Canon);
3088
3089  friend class ASTContext;  // ASTContext creates these
3090
3091public:
3092  /// \brief Determine whether any of the given template arguments are
3093  /// dependent.
3094  static bool anyDependentTemplateArguments(const TemplateArgument *Args,
3095                                            unsigned NumArgs);
3096
3097  static bool anyDependentTemplateArguments(const TemplateArgumentLoc *Args,
3098                                            unsigned NumArgs);
3099
3100  static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &);
3101
3102  /// \brief Print a template argument list, including the '<' and '>'
3103  /// enclosing the template arguments.
3104  static std::string PrintTemplateArgumentList(const TemplateArgument *Args,
3105                                               unsigned NumArgs,
3106                                               const PrintingPolicy &Policy,
3107                                               bool SkipBrackets = false);
3108
3109  static std::string PrintTemplateArgumentList(const TemplateArgumentLoc *Args,
3110                                               unsigned NumArgs,
3111                                               const PrintingPolicy &Policy);
3112
3113  static std::string PrintTemplateArgumentList(const TemplateArgumentListInfo &,
3114                                               const PrintingPolicy &Policy);
3115
3116  /// True if this template specialization type matches a current
3117  /// instantiation in the context in which it is found.
3118  bool isCurrentInstantiation() const {
3119    return isa<InjectedClassNameType>(getCanonicalTypeInternal());
3120  }
3121
3122  typedef const TemplateArgument * iterator;
3123
3124  iterator begin() const { return getArgs(); }
3125  iterator end() const; // defined inline in TemplateBase.h
3126
3127  /// \brief Retrieve the name of the template that we are specializing.
3128  TemplateName getTemplateName() const { return Template; }
3129
3130  /// \brief Retrieve the template arguments.
3131  const TemplateArgument *getArgs() const {
3132    return reinterpret_cast<const TemplateArgument *>(this + 1);
3133  }
3134
3135  /// \brief Retrieve the number of template arguments.
3136  unsigned getNumArgs() const { return NumArgs; }
3137
3138  /// \brief Retrieve a specific template argument as a type.
3139  /// \precondition @c isArgType(Arg)
3140  const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
3141
3142  bool isSugared() const {
3143    return !isDependentType() || isCurrentInstantiation();
3144  }
3145  QualType desugar() const { return getCanonicalTypeInternal(); }
3146
3147  void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
3148    Profile(ID, Template, getArgs(), NumArgs, Ctx);
3149  }
3150
3151  static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
3152                      const TemplateArgument *Args,
3153                      unsigned NumArgs,
3154                      const ASTContext &Context);
3155
3156  static bool classof(const Type *T) {
3157    return T->getTypeClass() == TemplateSpecialization;
3158  }
3159  static bool classof(const TemplateSpecializationType *T) { return true; }
3160};
3161
3162/// \brief The injected class name of a C++ class template or class
3163/// template partial specialization.  Used to record that a type was
3164/// spelled with a bare identifier rather than as a template-id; the
3165/// equivalent for non-templated classes is just RecordType.
3166///
3167/// Injected class name types are always dependent.  Template
3168/// instantiation turns these into RecordTypes.
3169///
3170/// Injected class name types are always canonical.  This works
3171/// because it is impossible to compare an injected class name type
3172/// with the corresponding non-injected template type, for the same
3173/// reason that it is impossible to directly compare template
3174/// parameters from different dependent contexts: injected class name
3175/// types can only occur within the scope of a particular templated
3176/// declaration, and within that scope every template specialization
3177/// will canonicalize to the injected class name (when appropriate
3178/// according to the rules of the language).
3179class InjectedClassNameType : public Type {
3180  CXXRecordDecl *Decl;
3181
3182  /// The template specialization which this type represents.
3183  /// For example, in
3184  ///   template <class T> class A { ... };
3185  /// this is A<T>, whereas in
3186  ///   template <class X, class Y> class A<B<X,Y> > { ... };
3187  /// this is A<B<X,Y> >.
3188  ///
3189  /// It is always unqualified, always a template specialization type,
3190  /// and always dependent.
3191  QualType InjectedType;
3192
3193  friend class ASTContext; // ASTContext creates these.
3194  friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
3195                          // currently suitable for AST reading, too much
3196                          // interdependencies.
3197  InjectedClassNameType(CXXRecordDecl *D, QualType TST)
3198    : Type(InjectedClassName, QualType(), /*Dependent=*/true,
3199           /*VariablyModified=*/false,
3200           /*ContainsUnexpandedParameterPack=*/false),
3201      Decl(D), InjectedType(TST) {
3202    assert(isa<TemplateSpecializationType>(TST));
3203    assert(!TST.hasQualifiers());
3204    assert(TST->isDependentType());
3205  }
3206
3207public:
3208  QualType getInjectedSpecializationType() const { return InjectedType; }
3209  const TemplateSpecializationType *getInjectedTST() const {
3210    return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
3211  }
3212
3213  CXXRecordDecl *getDecl() const;
3214
3215  bool isSugared() const { return false; }
3216  QualType desugar() const { return QualType(this, 0); }
3217
3218  static bool classof(const Type *T) {
3219    return T->getTypeClass() == InjectedClassName;
3220  }
3221  static bool classof(const InjectedClassNameType *T) { return true; }
3222};
3223
3224/// \brief The kind of a tag type.
3225enum TagTypeKind {
3226  /// \brief The "struct" keyword.
3227  TTK_Struct,
3228  /// \brief The "union" keyword.
3229  TTK_Union,
3230  /// \brief The "class" keyword.
3231  TTK_Class,
3232  /// \brief The "enum" keyword.
3233  TTK_Enum
3234};
3235
3236/// \brief The elaboration keyword that precedes a qualified type name or
3237/// introduces an elaborated-type-specifier.
3238enum ElaboratedTypeKeyword {
3239  /// \brief The "struct" keyword introduces the elaborated-type-specifier.
3240  ETK_Struct,
3241  /// \brief The "union" keyword introduces the elaborated-type-specifier.
3242  ETK_Union,
3243  /// \brief The "class" keyword introduces the elaborated-type-specifier.
3244  ETK_Class,
3245  /// \brief The "enum" keyword introduces the elaborated-type-specifier.
3246  ETK_Enum,
3247  /// \brief The "typename" keyword precedes the qualified type name, e.g.,
3248  /// \c typename T::type.
3249  ETK_Typename,
3250  /// \brief No keyword precedes the qualified type name.
3251  ETK_None
3252};
3253
3254/// A helper class for Type nodes having an ElaboratedTypeKeyword.
3255/// The keyword in stored in the free bits of the base class.
3256/// Also provides a few static helpers for converting and printing
3257/// elaborated type keyword and tag type kind enumerations.
3258class TypeWithKeyword : public Type {
3259protected:
3260  TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
3261                  QualType Canonical, bool Dependent, bool VariablyModified,
3262                  bool ContainsUnexpandedParameterPack)
3263  : Type(tc, Canonical, Dependent, VariablyModified,
3264         ContainsUnexpandedParameterPack) {
3265    TypeWithKeywordBits.Keyword = Keyword;
3266  }
3267
3268public:
3269  ElaboratedTypeKeyword getKeyword() const {
3270    return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
3271  }
3272
3273  /// getKeywordForTypeSpec - Converts a type specifier (DeclSpec::TST)
3274  /// into an elaborated type keyword.
3275  static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
3276
3277  /// getTagTypeKindForTypeSpec - Converts a type specifier (DeclSpec::TST)
3278  /// into a tag type kind.  It is an error to provide a type specifier
3279  /// which *isn't* a tag kind here.
3280  static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
3281
3282  /// getKeywordForTagDeclKind - Converts a TagTypeKind into an
3283  /// elaborated type keyword.
3284  static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
3285
3286  /// getTagTypeKindForKeyword - Converts an elaborated type keyword into
3287  // a TagTypeKind. It is an error to provide an elaborated type keyword
3288  /// which *isn't* a tag kind here.
3289  static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
3290
3291  static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
3292
3293  static const char *getKeywordName(ElaboratedTypeKeyword Keyword);
3294
3295  static const char *getTagTypeKindName(TagTypeKind Kind) {
3296    return getKeywordName(getKeywordForTagTypeKind(Kind));
3297  }
3298
3299  class CannotCastToThisType {};
3300  static CannotCastToThisType classof(const Type *);
3301};
3302
3303/// \brief Represents a type that was referred to using an elaborated type
3304/// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
3305/// or both.
3306///
3307/// This type is used to keep track of a type name as written in the
3308/// source code, including tag keywords and any nested-name-specifiers.
3309/// The type itself is always "sugar", used to express what was written
3310/// in the source code but containing no additional semantic information.
3311class ElaboratedType : public TypeWithKeyword, public llvm::FoldingSetNode {
3312
3313  /// \brief The nested name specifier containing the qualifier.
3314  NestedNameSpecifier *NNS;
3315
3316  /// \brief The type that this qualified name refers to.
3317  QualType NamedType;
3318
3319  ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
3320                 QualType NamedType, QualType CanonType)
3321    : TypeWithKeyword(Keyword, Elaborated, CanonType,
3322                      NamedType->isDependentType(),
3323                      NamedType->isVariablyModifiedType(),
3324                      NamedType->containsUnexpandedParameterPack()),
3325      NNS(NNS), NamedType(NamedType) {
3326    assert(!(Keyword == ETK_None && NNS == 0) &&
3327           "ElaboratedType cannot have elaborated type keyword "
3328           "and name qualifier both null.");
3329  }
3330
3331  friend class ASTContext;  // ASTContext creates these
3332
3333public:
3334  ~ElaboratedType();
3335
3336  /// \brief Retrieve the qualification on this type.
3337  NestedNameSpecifier *getQualifier() const { return NNS; }
3338
3339  /// \brief Retrieve the type named by the qualified-id.
3340  QualType getNamedType() const { return NamedType; }
3341
3342  /// \brief Remove a single level of sugar.
3343  QualType desugar() const { return getNamedType(); }
3344
3345  /// \brief Returns whether this type directly provides sugar.
3346  bool isSugared() const { return true; }
3347
3348  void Profile(llvm::FoldingSetNodeID &ID) {
3349    Profile(ID, getKeyword(), NNS, NamedType);
3350  }
3351
3352  static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
3353                      NestedNameSpecifier *NNS, QualType NamedType) {
3354    ID.AddInteger(Keyword);
3355    ID.AddPointer(NNS);
3356    NamedType.Profile(ID);
3357  }
3358
3359  static bool classof(const Type *T) {
3360    return T->getTypeClass() == Elaborated;
3361  }
3362  static bool classof(const ElaboratedType *T) { return true; }
3363};
3364
3365/// \brief Represents a qualified type name for which the type name is
3366/// dependent.
3367///
3368/// DependentNameType represents a class of dependent types that involve a
3369/// dependent nested-name-specifier (e.g., "T::") followed by a (dependent)
3370/// name of a type. The DependentNameType may start with a "typename" (for a
3371/// typename-specifier), "class", "struct", "union", or "enum" (for a
3372/// dependent elaborated-type-specifier), or nothing (in contexts where we
3373/// know that we must be referring to a type, e.g., in a base class specifier).
3374class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
3375
3376  /// \brief The nested name specifier containing the qualifier.
3377  NestedNameSpecifier *NNS;
3378
3379  /// \brief The type that this typename specifier refers to.
3380  const IdentifierInfo *Name;
3381
3382  DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
3383                    const IdentifierInfo *Name, QualType CanonType)
3384    : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true,
3385                      /*VariablyModified=*/false,
3386                      NNS->containsUnexpandedParameterPack()),
3387      NNS(NNS), Name(Name) {
3388    assert(NNS->isDependent() &&
3389           "DependentNameType requires a dependent nested-name-specifier");
3390  }
3391
3392  friend class ASTContext;  // ASTContext creates these
3393
3394public:
3395  /// \brief Retrieve the qualification on this type.
3396  NestedNameSpecifier *getQualifier() const { return NNS; }
3397
3398  /// \brief Retrieve the type named by the typename specifier as an
3399  /// identifier.
3400  ///
3401  /// This routine will return a non-NULL identifier pointer when the
3402  /// form of the original typename was terminated by an identifier,
3403  /// e.g., "typename T::type".
3404  const IdentifierInfo *getIdentifier() const {
3405    return Name;
3406  }
3407
3408  bool isSugared() const { return false; }
3409  QualType desugar() const { return QualType(this, 0); }
3410
3411  void Profile(llvm::FoldingSetNodeID &ID) {
3412    Profile(ID, getKeyword(), NNS, Name);
3413  }
3414
3415  static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
3416                      NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
3417    ID.AddInteger(Keyword);
3418    ID.AddPointer(NNS);
3419    ID.AddPointer(Name);
3420  }
3421
3422  static bool classof(const Type *T) {
3423    return T->getTypeClass() == DependentName;
3424  }
3425  static bool classof(const DependentNameType *T) { return true; }
3426};
3427
3428/// DependentTemplateSpecializationType - Represents a template
3429/// specialization type whose template cannot be resolved, e.g.
3430///   A<T>::template B<T>
3431class DependentTemplateSpecializationType :
3432  public TypeWithKeyword, public llvm::FoldingSetNode {
3433
3434  /// \brief The nested name specifier containing the qualifier.
3435  NestedNameSpecifier *NNS;
3436
3437  /// \brief The identifier of the template.
3438  const IdentifierInfo *Name;
3439
3440  /// \brief - The number of template arguments named in this class
3441  /// template specialization.
3442  unsigned NumArgs;
3443
3444  const TemplateArgument *getArgBuffer() const {
3445    return reinterpret_cast<const TemplateArgument*>(this+1);
3446  }
3447  TemplateArgument *getArgBuffer() {
3448    return reinterpret_cast<TemplateArgument*>(this+1);
3449  }
3450
3451  DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
3452                                      NestedNameSpecifier *NNS,
3453                                      const IdentifierInfo *Name,
3454                                      unsigned NumArgs,
3455                                      const TemplateArgument *Args,
3456                                      QualType Canon);
3457
3458  friend class ASTContext;  // ASTContext creates these
3459
3460public:
3461  NestedNameSpecifier *getQualifier() const { return NNS; }
3462  const IdentifierInfo *getIdentifier() const { return Name; }
3463
3464  /// \brief Retrieve the template arguments.
3465  const TemplateArgument *getArgs() const {
3466    return getArgBuffer();
3467  }
3468
3469  /// \brief Retrieve the number of template arguments.
3470  unsigned getNumArgs() const { return NumArgs; }
3471
3472  const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
3473
3474  typedef const TemplateArgument * iterator;
3475  iterator begin() const { return getArgs(); }
3476  iterator end() const; // inline in TemplateBase.h
3477
3478  bool isSugared() const { return false; }
3479  QualType desugar() const { return QualType(this, 0); }
3480
3481  void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
3482    Profile(ID, Context, getKeyword(), NNS, Name, NumArgs, getArgs());
3483  }
3484
3485  static void Profile(llvm::FoldingSetNodeID &ID,
3486                      const ASTContext &Context,
3487                      ElaboratedTypeKeyword Keyword,
3488                      NestedNameSpecifier *Qualifier,
3489                      const IdentifierInfo *Name,
3490                      unsigned NumArgs,
3491                      const TemplateArgument *Args);
3492
3493  static bool classof(const Type *T) {
3494    return T->getTypeClass() == DependentTemplateSpecialization;
3495  }
3496  static bool classof(const DependentTemplateSpecializationType *T) {
3497    return true;
3498  }
3499};
3500
3501/// \brief Represents a pack expansion of types.
3502///
3503/// Pack expansions are part of C++0x variadic templates. A pack
3504/// expansion contains a pattern, which itself contains one or more
3505/// "unexpanded" parameter packs. When instantiated, a pack expansion
3506/// produces a series of types, each instantiated from the pattern of
3507/// the expansion, where the Ith instantiation of the pattern uses the
3508/// Ith arguments bound to each of the unexpanded parameter packs. The
3509/// pack expansion is considered to "expand" these unexpanded
3510/// parameter packs.
3511///
3512/// \code
3513/// template<typename ...Types> struct tuple;
3514///
3515/// template<typename ...Types>
3516/// struct tuple_of_references {
3517///   typedef tuple<Types&...> type;
3518/// };
3519/// \endcode
3520///
3521/// Here, the pack expansion \c Types&... is represented via a
3522/// PackExpansionType whose pattern is Types&.
3523class PackExpansionType : public Type, public llvm::FoldingSetNode {
3524  /// \brief The pattern of the pack expansion.
3525  QualType Pattern;
3526
3527  /// \brief The number of expansions that this pack expansion will
3528  /// generate when substituted (+1), or indicates that
3529  ///
3530  /// This field will only have a non-zero value when some of the parameter
3531  /// packs that occur within the pattern have been substituted but others have
3532  /// not.
3533  unsigned NumExpansions;
3534
3535  PackExpansionType(QualType Pattern, QualType Canon,
3536                    llvm::Optional<unsigned> NumExpansions)
3537    : Type(PackExpansion, Canon, /*Dependent=*/true,
3538           /*VariableModified=*/Pattern->isVariablyModifiedType(),
3539           /*ContainsUnexpandedParameterPack=*/false),
3540      Pattern(Pattern),
3541      NumExpansions(NumExpansions? *NumExpansions + 1: 0) { }
3542
3543  friend class ASTContext;  // ASTContext creates these
3544
3545public:
3546  /// \brief Retrieve the pattern of this pack expansion, which is the
3547  /// type that will be repeatedly instantiated when instantiating the
3548  /// pack expansion itself.
3549  QualType getPattern() const { return Pattern; }
3550
3551  /// \brief Retrieve the number of expansions that this pack expansion will
3552  /// generate, if known.
3553  llvm::Optional<unsigned> getNumExpansions() const {
3554    if (NumExpansions)
3555      return NumExpansions - 1;
3556
3557    return llvm::Optional<unsigned>();
3558  }
3559
3560  bool isSugared() const { return false; }
3561  QualType desugar() const { return QualType(this, 0); }
3562
3563  void Profile(llvm::FoldingSetNodeID &ID) {
3564    Profile(ID, getPattern(), getNumExpansions());
3565  }
3566
3567  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
3568                      llvm::Optional<unsigned> NumExpansions) {
3569    ID.AddPointer(Pattern.getAsOpaquePtr());
3570    ID.AddBoolean(NumExpansions);
3571    if (NumExpansions)
3572      ID.AddInteger(*NumExpansions);
3573  }
3574
3575  static bool classof(const Type *T) {
3576    return T->getTypeClass() == PackExpansion;
3577  }
3578  static bool classof(const PackExpansionType *T) {
3579    return true;
3580  }
3581};
3582
3583/// ObjCObjectType - Represents a class type in Objective C.
3584/// Every Objective C type is a combination of a base type and a
3585/// list of protocols.
3586///
3587/// Given the following declarations:
3588///   @class C;
3589///   @protocol P;
3590///
3591/// 'C' is an ObjCInterfaceType C.  It is sugar for an ObjCObjectType
3592/// with base C and no protocols.
3593///
3594/// 'C<P>' is an ObjCObjectType with base C and protocol list [P].
3595///
3596/// 'id' is a TypedefType which is sugar for an ObjCPointerType whose
3597/// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
3598/// and no protocols.
3599///
3600/// 'id<P>' is an ObjCPointerType whose pointee is an ObjCObjecType
3601/// with base BuiltinType::ObjCIdType and protocol list [P].  Eventually
3602/// this should get its own sugar class to better represent the source.
3603class ObjCObjectType : public Type {
3604  // ObjCObjectType.NumProtocols - the number of protocols stored
3605  // after the ObjCObjectPointerType node.
3606  //
3607  // These protocols are those written directly on the type.  If
3608  // protocol qualifiers ever become additive, the iterators will need
3609  // to get kindof complicated.
3610  //
3611  // In the canonical object type, these are sorted alphabetically
3612  // and uniqued.
3613
3614  /// Either a BuiltinType or an InterfaceType or sugar for either.
3615  QualType BaseType;
3616
3617  ObjCProtocolDecl * const *getProtocolStorage() const {
3618    return const_cast<ObjCObjectType*>(this)->getProtocolStorage();
3619  }
3620
3621  ObjCProtocolDecl **getProtocolStorage();
3622
3623protected:
3624  ObjCObjectType(QualType Canonical, QualType Base,
3625                 ObjCProtocolDecl * const *Protocols, unsigned NumProtocols);
3626
3627  enum Nonce_ObjCInterface { Nonce_ObjCInterface };
3628  ObjCObjectType(enum Nonce_ObjCInterface)
3629        : Type(ObjCInterface, QualType(), false, false, false),
3630      BaseType(QualType(this_(), 0)) {
3631    ObjCObjectTypeBits.NumProtocols = 0;
3632  }
3633
3634public:
3635  /// getBaseType - Gets the base type of this object type.  This is
3636  /// always (possibly sugar for) one of:
3637  ///  - the 'id' builtin type (as opposed to the 'id' type visible to the
3638  ///    user, which is a typedef for an ObjCPointerType)
3639  ///  - the 'Class' builtin type (same caveat)
3640  ///  - an ObjCObjectType (currently always an ObjCInterfaceType)
3641  QualType getBaseType() const { return BaseType; }
3642
3643  bool isObjCId() const {
3644    return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
3645  }
3646  bool isObjCClass() const {
3647    return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
3648  }
3649  bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
3650  bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
3651  bool isObjCUnqualifiedIdOrClass() const {
3652    if (!qual_empty()) return false;
3653    if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
3654      return T->getKind() == BuiltinType::ObjCId ||
3655             T->getKind() == BuiltinType::ObjCClass;
3656    return false;
3657  }
3658  bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
3659  bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
3660
3661  /// Gets the interface declaration for this object type, if the base type
3662  /// really is an interface.
3663  ObjCInterfaceDecl *getInterface() const;
3664
3665  typedef ObjCProtocolDecl * const *qual_iterator;
3666
3667  qual_iterator qual_begin() const { return getProtocolStorage(); }
3668  qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
3669
3670  bool qual_empty() const { return getNumProtocols() == 0; }
3671
3672  /// getNumProtocols - Return the number of qualifying protocols in this
3673  /// interface type, or 0 if there are none.
3674  unsigned getNumProtocols() const { return ObjCObjectTypeBits.NumProtocols; }
3675
3676  /// \brief Fetch a protocol by index.
3677  ObjCProtocolDecl *getProtocol(unsigned I) const {
3678    assert(I < getNumProtocols() && "Out-of-range protocol access");
3679    return qual_begin()[I];
3680  }
3681
3682  bool isSugared() const { return false; }
3683  QualType desugar() const { return QualType(this, 0); }
3684
3685  static bool classof(const Type *T) {
3686    return T->getTypeClass() == ObjCObject ||
3687           T->getTypeClass() == ObjCInterface;
3688  }
3689  static bool classof(const ObjCObjectType *) { return true; }
3690};
3691
3692/// ObjCObjectTypeImpl - A class providing a concrete implementation
3693/// of ObjCObjectType, so as to not increase the footprint of
3694/// ObjCInterfaceType.  Code outside of ASTContext and the core type
3695/// system should not reference this type.
3696class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
3697  friend class ASTContext;
3698
3699  // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
3700  // will need to be modified.
3701
3702  ObjCObjectTypeImpl(QualType Canonical, QualType Base,
3703                     ObjCProtocolDecl * const *Protocols,
3704                     unsigned NumProtocols)
3705    : ObjCObjectType(Canonical, Base, Protocols, NumProtocols) {}
3706
3707public:
3708  void Profile(llvm::FoldingSetNodeID &ID);
3709  static void Profile(llvm::FoldingSetNodeID &ID,
3710                      QualType Base,
3711                      ObjCProtocolDecl *const *protocols,
3712                      unsigned NumProtocols);
3713};
3714
3715inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorage() {
3716  return reinterpret_cast<ObjCProtocolDecl**>(
3717            static_cast<ObjCObjectTypeImpl*>(this) + 1);
3718}
3719
3720/// ObjCInterfaceType - Interfaces are the core concept in Objective-C for
3721/// object oriented design.  They basically correspond to C++ classes.  There
3722/// are two kinds of interface types, normal interfaces like "NSString" and
3723/// qualified interfaces, which are qualified with a protocol list like
3724/// "NSString<NSCopyable, NSAmazing>".
3725///
3726/// ObjCInterfaceType guarantees the following properties when considered
3727/// as a subtype of its superclass, ObjCObjectType:
3728///   - There are no protocol qualifiers.  To reinforce this, code which
3729///     tries to invoke the protocol methods via an ObjCInterfaceType will
3730///     fail to compile.
3731///   - It is its own base type.  That is, if T is an ObjCInterfaceType*,
3732///     T->getBaseType() == QualType(T, 0).
3733class ObjCInterfaceType : public ObjCObjectType {
3734  ObjCInterfaceDecl *Decl;
3735
3736  ObjCInterfaceType(const ObjCInterfaceDecl *D)
3737    : ObjCObjectType(Nonce_ObjCInterface),
3738      Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
3739  friend class ASTContext;  // ASTContext creates these.
3740
3741public:
3742  /// getDecl - Get the declaration of this interface.
3743  ObjCInterfaceDecl *getDecl() const { return Decl; }
3744
3745  bool isSugared() const { return false; }
3746  QualType desugar() const { return QualType(this, 0); }
3747
3748  static bool classof(const Type *T) {
3749    return T->getTypeClass() == ObjCInterface;
3750  }
3751  static bool classof(const ObjCInterfaceType *) { return true; }
3752
3753  // Nonsense to "hide" certain members of ObjCObjectType within this
3754  // class.  People asking for protocols on an ObjCInterfaceType are
3755  // not going to get what they want: ObjCInterfaceTypes are
3756  // guaranteed to have no protocols.
3757  enum {
3758    qual_iterator,
3759    qual_begin,
3760    qual_end,
3761    getNumProtocols,
3762    getProtocol
3763  };
3764};
3765
3766inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
3767  if (const ObjCInterfaceType *T =
3768        getBaseType()->getAs<ObjCInterfaceType>())
3769    return T->getDecl();
3770  return 0;
3771}
3772
3773/// ObjCObjectPointerType - Used to represent a pointer to an
3774/// Objective C object.  These are constructed from pointer
3775/// declarators when the pointee type is an ObjCObjectType (or sugar
3776/// for one).  In addition, the 'id' and 'Class' types are typedefs
3777/// for these, and the protocol-qualified types 'id<P>' and 'Class<P>'
3778/// are translated into these.
3779///
3780/// Pointers to pointers to Objective C objects are still PointerTypes;
3781/// only the first level of pointer gets it own type implementation.
3782class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
3783  QualType PointeeType;
3784
3785  ObjCObjectPointerType(QualType Canonical, QualType Pointee)
3786    : Type(ObjCObjectPointer, Canonical, false, false, false),
3787      PointeeType(Pointee) {}
3788  friend class ASTContext;  // ASTContext creates these.
3789
3790public:
3791  /// getPointeeType - Gets the type pointed to by this ObjC pointer.
3792  /// The result will always be an ObjCObjectType or sugar thereof.
3793  QualType getPointeeType() const { return PointeeType; }
3794
3795  /// getObjCObjectType - Gets the type pointed to by this ObjC
3796  /// pointer.  This method always returns non-null.
3797  ///
3798  /// This method is equivalent to getPointeeType() except that
3799  /// it discards any typedefs (or other sugar) between this
3800  /// type and the "outermost" object type.  So for:
3801  ///   @class A; @protocol P; @protocol Q;
3802  ///   typedef A<P> AP;
3803  ///   typedef A A1;
3804  ///   typedef A1<P> A1P;
3805  ///   typedef A1P<Q> A1PQ;
3806  /// For 'A*', getObjectType() will return 'A'.
3807  /// For 'A<P>*', getObjectType() will return 'A<P>'.
3808  /// For 'AP*', getObjectType() will return 'A<P>'.
3809  /// For 'A1*', getObjectType() will return 'A'.
3810  /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
3811  /// For 'A1P*', getObjectType() will return 'A1<P>'.
3812  /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
3813  ///   adding protocols to a protocol-qualified base discards the
3814  ///   old qualifiers (for now).  But if it didn't, getObjectType()
3815  ///   would return 'A1P<Q>' (and we'd have to make iterating over
3816  ///   qualifiers more complicated).
3817  const ObjCObjectType *getObjectType() const {
3818    return PointeeType->castAs<ObjCObjectType>();
3819  }
3820
3821  /// getInterfaceType - If this pointer points to an Objective C
3822  /// @interface type, gets the type for that interface.  Any protocol
3823  /// qualifiers on the interface are ignored.
3824  ///
3825  /// \return null if the base type for this pointer is 'id' or 'Class'
3826  const ObjCInterfaceType *getInterfaceType() const {
3827    return getObjectType()->getBaseType()->getAs<ObjCInterfaceType>();
3828  }
3829
3830  /// getInterfaceDecl - If this pointer points to an Objective @interface
3831  /// type, gets the declaration for that interface.
3832  ///
3833  /// \return null if the base type for this pointer is 'id' or 'Class'
3834  ObjCInterfaceDecl *getInterfaceDecl() const {
3835    return getObjectType()->getInterface();
3836  }
3837
3838  /// isObjCIdType - True if this is equivalent to the 'id' type, i.e. if
3839  /// its object type is the primitive 'id' type with no protocols.
3840  bool isObjCIdType() const {
3841    return getObjectType()->isObjCUnqualifiedId();
3842  }
3843
3844  /// isObjCClassType - True if this is equivalent to the 'Class' type,
3845  /// i.e. if its object tive is the primitive 'Class' type with no protocols.
3846  bool isObjCClassType() const {
3847    return getObjectType()->isObjCUnqualifiedClass();
3848  }
3849
3850  /// isObjCQualifiedIdType - True if this is equivalent to 'id<P>' for some
3851  /// non-empty set of protocols.
3852  bool isObjCQualifiedIdType() const {
3853    return getObjectType()->isObjCQualifiedId();
3854  }
3855
3856  /// isObjCQualifiedClassType - True if this is equivalent to 'Class<P>' for
3857  /// some non-empty set of protocols.
3858  bool isObjCQualifiedClassType() const {
3859    return getObjectType()->isObjCQualifiedClass();
3860  }
3861
3862  /// An iterator over the qualifiers on the object type.  Provided
3863  /// for convenience.  This will always iterate over the full set of
3864  /// protocols on a type, not just those provided directly.
3865  typedef ObjCObjectType::qual_iterator qual_iterator;
3866
3867  qual_iterator qual_begin() const {
3868    return getObjectType()->qual_begin();
3869  }
3870  qual_iterator qual_end() const {
3871    return getObjectType()->qual_end();
3872  }
3873  bool qual_empty() const { return getObjectType()->qual_empty(); }
3874
3875  /// getNumProtocols - Return the number of qualifying protocols on
3876  /// the object type.
3877  unsigned getNumProtocols() const {
3878    return getObjectType()->getNumProtocols();
3879  }
3880
3881  /// \brief Retrieve a qualifying protocol by index on the object
3882  /// type.
3883  ObjCProtocolDecl *getProtocol(unsigned I) const {
3884    return getObjectType()->getProtocol(I);
3885  }
3886
3887  bool isSugared() const { return false; }
3888  QualType desugar() const { return QualType(this, 0); }
3889
3890  void Profile(llvm::FoldingSetNodeID &ID) {
3891    Profile(ID, getPointeeType());
3892  }
3893  static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
3894    ID.AddPointer(T.getAsOpaquePtr());
3895  }
3896  static bool classof(const Type *T) {
3897    return T->getTypeClass() == ObjCObjectPointer;
3898  }
3899  static bool classof(const ObjCObjectPointerType *) { return true; }
3900};
3901
3902/// A qualifier set is used to build a set of qualifiers.
3903class QualifierCollector : public Qualifiers {
3904public:
3905  QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
3906
3907  /// Collect any qualifiers on the given type and return an
3908  /// unqualified type.  The qualifiers are assumed to be consistent
3909  /// with those already in the type.
3910  const Type *strip(QualType type) {
3911    addFastQualifiers(type.getLocalFastQualifiers());
3912    if (!type.hasLocalNonFastQualifiers())
3913      return type.getTypePtrUnsafe();
3914
3915    const ExtQuals *extQuals = type.getExtQualsUnsafe();
3916    addConsistentQualifiers(extQuals->getQualifiers());
3917    return extQuals->getBaseType();
3918  }
3919
3920  /// Apply the collected qualifiers to the given type.
3921  QualType apply(const ASTContext &Context, QualType QT) const;
3922
3923  /// Apply the collected qualifiers to the given type.
3924  QualType apply(const ASTContext &Context, const Type* T) const;
3925};
3926
3927
3928// Inline function definitions.
3929
3930inline const Type *QualType::getTypePtr() const {
3931  return getCommonPtr()->BaseType;
3932}
3933
3934inline const Type *QualType::getTypePtrOrNull() const {
3935  return (isNull() ? 0 : getCommonPtr()->BaseType);
3936}
3937
3938inline SplitQualType QualType::split() const {
3939  if (!hasLocalNonFastQualifiers())
3940    return SplitQualType(getTypePtrUnsafe(),
3941                         Qualifiers::fromFastMask(getLocalFastQualifiers()));
3942
3943  const ExtQuals *eq = getExtQualsUnsafe();
3944  Qualifiers qs = eq->getQualifiers();
3945  qs.addFastQualifiers(getLocalFastQualifiers());
3946  return SplitQualType(eq->getBaseType(), qs);
3947}
3948
3949inline Qualifiers QualType::getLocalQualifiers() const {
3950  Qualifiers Quals;
3951  if (hasLocalNonFastQualifiers())
3952    Quals = getExtQualsUnsafe()->getQualifiers();
3953  Quals.addFastQualifiers(getLocalFastQualifiers());
3954  return Quals;
3955}
3956
3957inline Qualifiers QualType::getQualifiers() const {
3958  Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
3959  quals.addFastQualifiers(getLocalFastQualifiers());
3960  return quals;
3961}
3962
3963inline unsigned QualType::getCVRQualifiers() const {
3964  unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
3965  cvr |= getLocalCVRQualifiers();
3966  return cvr;
3967}
3968
3969inline QualType QualType::getCanonicalType() const {
3970  QualType canon = getCommonPtr()->CanonicalType;
3971  return canon.withFastQualifiers(getLocalFastQualifiers());
3972}
3973
3974inline bool QualType::isCanonical() const {
3975  return getTypePtr()->isCanonicalUnqualified();
3976}
3977
3978inline bool QualType::isCanonicalAsParam() const {
3979  if (!isCanonical()) return false;
3980  if (hasLocalQualifiers()) return false;
3981
3982  const Type *T = getTypePtr();
3983  if (T->isVariablyModifiedType() && T->hasSizedVLAType())
3984    return false;
3985
3986  return !isa<FunctionType>(T) && !isa<ArrayType>(T);
3987}
3988
3989inline bool QualType::isConstQualified() const {
3990  return isLocalConstQualified() ||
3991         getCommonPtr()->CanonicalType.isLocalConstQualified();
3992}
3993
3994inline bool QualType::isRestrictQualified() const {
3995  return isLocalRestrictQualified() ||
3996         getCommonPtr()->CanonicalType.isLocalRestrictQualified();
3997}
3998
3999
4000inline bool QualType::isVolatileQualified() const {
4001  return isLocalVolatileQualified() ||
4002         getCommonPtr()->CanonicalType.isLocalVolatileQualified();
4003}
4004
4005inline bool QualType::hasQualifiers() const {
4006  return hasLocalQualifiers() ||
4007         getCommonPtr()->CanonicalType.hasLocalQualifiers();
4008}
4009
4010inline QualType QualType::getUnqualifiedType() const {
4011  if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
4012    return QualType(getTypePtr(), 0);
4013
4014  return QualType(getSplitUnqualifiedTypeImpl(*this).first, 0);
4015}
4016
4017inline SplitQualType QualType::getSplitUnqualifiedType() const {
4018  if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
4019    return split();
4020
4021  return getSplitUnqualifiedTypeImpl(*this);
4022}
4023
4024inline void QualType::removeLocalConst() {
4025  removeLocalFastQualifiers(Qualifiers::Const);
4026}
4027
4028inline void QualType::removeLocalRestrict() {
4029  removeLocalFastQualifiers(Qualifiers::Restrict);
4030}
4031
4032inline void QualType::removeLocalVolatile() {
4033  removeLocalFastQualifiers(Qualifiers::Volatile);
4034}
4035
4036inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
4037  assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits");
4038  assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask);
4039
4040  // Fast path: we don't need to touch the slow qualifiers.
4041  removeLocalFastQualifiers(Mask);
4042}
4043
4044/// getAddressSpace - Return the address space of this type.
4045inline unsigned QualType::getAddressSpace() const {
4046  return getQualifiers().getAddressSpace();
4047}
4048
4049/// getObjCGCAttr - Return the gc attribute of this type.
4050inline Qualifiers::GC QualType::getObjCGCAttr() const {
4051  return getQualifiers().getObjCGCAttr();
4052}
4053
4054inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
4055  if (const PointerType *PT = t.getAs<PointerType>()) {
4056    if (const FunctionType *FT = PT->getPointeeType()->getAs<FunctionType>())
4057      return FT->getExtInfo();
4058  } else if (const FunctionType *FT = t.getAs<FunctionType>())
4059    return FT->getExtInfo();
4060
4061  return FunctionType::ExtInfo();
4062}
4063
4064inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
4065  return getFunctionExtInfo(*t);
4066}
4067
4068/// \brief Determine whether this set of qualifiers is a superset of the given
4069/// set of qualifiers.
4070inline bool Qualifiers::isSupersetOf(Qualifiers Other) const {
4071  return Mask != Other.Mask && (Mask | Other.Mask) == Mask;
4072}
4073
4074/// isMoreQualifiedThan - Determine whether this type is more
4075/// qualified than the Other type. For example, "const volatile int"
4076/// is more qualified than "const int", "volatile int", and
4077/// "int". However, it is not more qualified than "const volatile
4078/// int".
4079inline bool QualType::isMoreQualifiedThan(QualType other) const {
4080  Qualifiers myQuals = getQualifiers();
4081  Qualifiers otherQuals = other.getQualifiers();
4082  return (myQuals != otherQuals && myQuals.compatiblyIncludes(otherQuals));
4083}
4084
4085/// isAtLeastAsQualifiedAs - Determine whether this type is at last
4086/// as qualified as the Other type. For example, "const volatile
4087/// int" is at least as qualified as "const int", "volatile int",
4088/// "int", and "const volatile int".
4089inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
4090  return getQualifiers().compatiblyIncludes(other.getQualifiers());
4091}
4092
4093/// getNonReferenceType - If Type is a reference type (e.g., const
4094/// int&), returns the type that the reference refers to ("const
4095/// int"). Otherwise, returns the type itself. This routine is used
4096/// throughout Sema to implement C++ 5p6:
4097///
4098///   If an expression initially has the type "reference to T" (8.3.2,
4099///   8.5.3), the type is adjusted to "T" prior to any further
4100///   analysis, the expression designates the object or function
4101///   denoted by the reference, and the expression is an lvalue.
4102inline QualType QualType::getNonReferenceType() const {
4103  if (const ReferenceType *RefType = (*this)->getAs<ReferenceType>())
4104    return RefType->getPointeeType();
4105  else
4106    return *this;
4107}
4108
4109inline bool Type::isFunctionType() const {
4110  return isa<FunctionType>(CanonicalType);
4111}
4112inline bool Type::isPointerType() const {
4113  return isa<PointerType>(CanonicalType);
4114}
4115inline bool Type::isAnyPointerType() const {
4116  return isPointerType() || isObjCObjectPointerType();
4117}
4118inline bool Type::isBlockPointerType() const {
4119  return isa<BlockPointerType>(CanonicalType);
4120}
4121inline bool Type::isReferenceType() const {
4122  return isa<ReferenceType>(CanonicalType);
4123}
4124inline bool Type::isLValueReferenceType() const {
4125  return isa<LValueReferenceType>(CanonicalType);
4126}
4127inline bool Type::isRValueReferenceType() const {
4128  return isa<RValueReferenceType>(CanonicalType);
4129}
4130inline bool Type::isFunctionPointerType() const {
4131  if (const PointerType *T = getAs<PointerType>())
4132    return T->getPointeeType()->isFunctionType();
4133  else
4134    return false;
4135}
4136inline bool Type::isMemberPointerType() const {
4137  return isa<MemberPointerType>(CanonicalType);
4138}
4139inline bool Type::isMemberFunctionPointerType() const {
4140  if (const MemberPointerType* T = getAs<MemberPointerType>())
4141    return T->isMemberFunctionPointer();
4142  else
4143    return false;
4144}
4145inline bool Type::isMemberDataPointerType() const {
4146  if (const MemberPointerType* T = getAs<MemberPointerType>())
4147    return T->isMemberDataPointer();
4148  else
4149    return false;
4150}
4151inline bool Type::isArrayType() const {
4152  return isa<ArrayType>(CanonicalType);
4153}
4154inline bool Type::isConstantArrayType() const {
4155  return isa<ConstantArrayType>(CanonicalType);
4156}
4157inline bool Type::isIncompleteArrayType() const {
4158  return isa<IncompleteArrayType>(CanonicalType);
4159}
4160inline bool Type::isVariableArrayType() const {
4161  return isa<VariableArrayType>(CanonicalType);
4162}
4163inline bool Type::isDependentSizedArrayType() const {
4164  return isa<DependentSizedArrayType>(CanonicalType);
4165}
4166inline bool Type::isBuiltinType() const {
4167  return isa<BuiltinType>(CanonicalType);
4168}
4169inline bool Type::isRecordType() const {
4170  return isa<RecordType>(CanonicalType);
4171}
4172inline bool Type::isEnumeralType() const {
4173  return isa<EnumType>(CanonicalType);
4174}
4175inline bool Type::isAnyComplexType() const {
4176  return isa<ComplexType>(CanonicalType);
4177}
4178inline bool Type::isVectorType() const {
4179  return isa<VectorType>(CanonicalType);
4180}
4181inline bool Type::isExtVectorType() const {
4182  return isa<ExtVectorType>(CanonicalType);
4183}
4184inline bool Type::isObjCObjectPointerType() const {
4185  return isa<ObjCObjectPointerType>(CanonicalType);
4186}
4187inline bool Type::isObjCObjectType() const {
4188  return isa<ObjCObjectType>(CanonicalType);
4189}
4190inline bool Type::isObjCObjectOrInterfaceType() const {
4191  return isa<ObjCInterfaceType>(CanonicalType) ||
4192    isa<ObjCObjectType>(CanonicalType);
4193}
4194
4195inline bool Type::isObjCQualifiedIdType() const {
4196  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4197    return OPT->isObjCQualifiedIdType();
4198  return false;
4199}
4200inline bool Type::isObjCQualifiedClassType() const {
4201  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4202    return OPT->isObjCQualifiedClassType();
4203  return false;
4204}
4205inline bool Type::isObjCIdType() const {
4206  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4207    return OPT->isObjCIdType();
4208  return false;
4209}
4210inline bool Type::isObjCClassType() const {
4211  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4212    return OPT->isObjCClassType();
4213  return false;
4214}
4215inline bool Type::isObjCSelType() const {
4216  if (const PointerType *OPT = getAs<PointerType>())
4217    return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
4218  return false;
4219}
4220inline bool Type::isObjCBuiltinType() const {
4221  return isObjCIdType() || isObjCClassType() || isObjCSelType();
4222}
4223inline bool Type::isTemplateTypeParmType() const {
4224  return isa<TemplateTypeParmType>(CanonicalType);
4225}
4226
4227inline bool Type::isSpecificBuiltinType(unsigned K) const {
4228  if (const BuiltinType *BT = getAs<BuiltinType>())
4229    if (BT->getKind() == (BuiltinType::Kind) K)
4230      return true;
4231  return false;
4232}
4233
4234inline bool Type::isPlaceholderType() const {
4235  if (const BuiltinType *BT = getAs<BuiltinType>())
4236    return BT->isPlaceholderType();
4237  return false;
4238}
4239
4240/// \brief Determines whether this is a type for which one can define
4241/// an overloaded operator.
4242inline bool Type::isOverloadableType() const {
4243  return isDependentType() || isRecordType() || isEnumeralType();
4244}
4245
4246inline bool Type::hasPointerRepresentation() const {
4247  return (isPointerType() || isReferenceType() || isBlockPointerType() ||
4248          isObjCObjectPointerType() || isNullPtrType());
4249}
4250
4251inline bool Type::hasObjCPointerRepresentation() const {
4252  return isObjCObjectPointerType();
4253}
4254
4255inline const Type *Type::getBaseElementTypeUnsafe() const {
4256  const Type *type = this;
4257  while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
4258    type = arrayType->getElementType().getTypePtr();
4259  return type;
4260}
4261
4262/// Insertion operator for diagnostics.  This allows sending QualType's into a
4263/// diagnostic with <<.
4264inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
4265                                           QualType T) {
4266  DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
4267                  Diagnostic::ak_qualtype);
4268  return DB;
4269}
4270
4271/// Insertion operator for partial diagnostics.  This allows sending QualType's
4272/// into a diagnostic with <<.
4273inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
4274                                           QualType T) {
4275  PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
4276                  Diagnostic::ak_qualtype);
4277  return PD;
4278}
4279
4280// Helper class template that is used by Type::getAs to ensure that one does
4281// not try to look through a qualified type to get to an array type.
4282template<typename T,
4283         bool isArrayType = (llvm::is_same<T, ArrayType>::value ||
4284                             llvm::is_base_of<ArrayType, T>::value)>
4285struct ArrayType_cannot_be_used_with_getAs { };
4286
4287template<typename T>
4288struct ArrayType_cannot_be_used_with_getAs<T, true>;
4289
4290/// Member-template getAs<specific type>'.
4291template <typename T> const T *Type::getAs() const {
4292  ArrayType_cannot_be_used_with_getAs<T> at;
4293  (void)at;
4294
4295  // If this is directly a T type, return it.
4296  if (const T *Ty = dyn_cast<T>(this))
4297    return Ty;
4298
4299  // If the canonical form of this type isn't the right kind, reject it.
4300  if (!isa<T>(CanonicalType))
4301    return 0;
4302
4303  // If this is a typedef for the type, strip the typedef off without
4304  // losing all typedef information.
4305  return cast<T>(getUnqualifiedDesugaredType());
4306}
4307
4308inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
4309  // If this is directly an array type, return it.
4310  if (const ArrayType *arr = dyn_cast<ArrayType>(this))
4311    return arr;
4312
4313  // If the canonical form of this type isn't the right kind, reject it.
4314  if (!isa<ArrayType>(CanonicalType))
4315    return 0;
4316
4317  // If this is a typedef for the type, strip the typedef off without
4318  // losing all typedef information.
4319  return cast<ArrayType>(getUnqualifiedDesugaredType());
4320}
4321
4322template <typename T> const T *Type::castAs() const {
4323  ArrayType_cannot_be_used_with_getAs<T> at;
4324  (void) at;
4325
4326  assert(isa<T>(CanonicalType));
4327  if (const T *ty = dyn_cast<T>(this)) return ty;
4328  return cast<T>(getUnqualifiedDesugaredType());
4329}
4330
4331inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
4332  assert(isa<ArrayType>(CanonicalType));
4333  if (const ArrayType *arr = dyn_cast<ArrayType>(this)) return arr;
4334  return cast<ArrayType>(getUnqualifiedDesugaredType());
4335}
4336
4337}  // end namespace clang
4338
4339#endif
4340