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