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