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