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