Type.h revision ca63c200346c0ca9e00194ec6e34a5a7b0ed9321
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  /// Determines whether this is an integer type that is signed or an
1440  /// enumeration types whose underlying type is a signed integer type.
1441  bool isSignedIntegerOrEnumerationType() const;
1442
1443  /// Determines whether this is an integer type that is unsigned or an
1444  /// enumeration types whose underlying type is a unsigned integer type.
1445  bool isUnsignedIntegerOrEnumerationType() const;
1446
1447  /// isConstantSizeType - Return true if this is not a variable sized type,
1448  /// according to the rules of C99 6.7.5p3.  It is not legal to call this on
1449  /// incomplete types.
1450  bool isConstantSizeType() const;
1451
1452  /// isSpecifierType - Returns true if this type can be represented by some
1453  /// set of type specifiers.
1454  bool isSpecifierType() const;
1455
1456  /// \brief Determine the linkage of this type.
1457  Linkage getLinkage() const;
1458
1459  /// \brief Determine the visibility of this type.
1460  Visibility getVisibility() const;
1461
1462  /// \brief Determine the linkage and visibility of this type.
1463  std::pair<Linkage,Visibility> getLinkageAndVisibility() const;
1464
1465  /// \brief Note that the linkage is no longer known.
1466  void ClearLinkageCache();
1467
1468  const char *getTypeClassName() const;
1469
1470  QualType getCanonicalTypeInternal() const {
1471    return CanonicalType;
1472  }
1473  CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
1474  void dump() const;
1475  static bool classof(const Type *) { return true; }
1476
1477  friend class ASTReader;
1478  friend class ASTWriter;
1479};
1480
1481template <> inline const TypedefType *Type::getAs() const {
1482  return dyn_cast<TypedefType>(this);
1483}
1484
1485// We can do canonical leaf types faster, because we don't have to
1486// worry about preserving child type decoration.
1487#define TYPE(Class, Base)
1488#define LEAF_TYPE(Class) \
1489template <> inline const Class##Type *Type::getAs() const { \
1490  return dyn_cast<Class##Type>(CanonicalType); \
1491} \
1492template <> inline const Class##Type *Type::castAs() const { \
1493  return cast<Class##Type>(CanonicalType); \
1494}
1495#include "clang/AST/TypeNodes.def"
1496
1497
1498/// BuiltinType - This class is used for builtin types like 'int'.  Builtin
1499/// types are always canonical and have a literal name field.
1500class BuiltinType : public Type {
1501public:
1502  enum Kind {
1503    Void,
1504
1505    Bool,     // This is bool and/or _Bool.
1506    Char_U,   // This is 'char' for targets where char is unsigned.
1507    UChar,    // This is explicitly qualified unsigned char.
1508    WChar_U,  // This is 'wchar_t' for C++, when unsigned.
1509    Char16,   // This is 'char16_t' for C++.
1510    Char32,   // This is 'char32_t' for C++.
1511    UShort,
1512    UInt,
1513    ULong,
1514    ULongLong,
1515    UInt128,  // __uint128_t
1516
1517    Char_S,   // This is 'char' for targets where char is signed.
1518    SChar,    // This is explicitly qualified signed char.
1519    WChar_S,  // This is 'wchar_t' for C++, when signed.
1520    Short,
1521    Int,
1522    Long,
1523    LongLong,
1524    Int128,   // __int128_t
1525
1526    Float, Double, LongDouble,
1527
1528    NullPtr,  // This is the type of C++0x 'nullptr'.
1529
1530    /// The primitive Objective C 'id' type.  The user-visible 'id'
1531    /// type is a typedef of an ObjCObjectPointerType to an
1532    /// ObjCObjectType with this as its base.  In fact, this only ever
1533    /// shows up in an AST as the base type of an ObjCObjectType.
1534    ObjCId,
1535
1536    /// The primitive Objective C 'Class' type.  The user-visible
1537    /// 'Class' type is a typedef of an ObjCObjectPointerType to an
1538    /// ObjCObjectType with this as its base.  In fact, this only ever
1539    /// shows up in an AST as the base type of an ObjCObjectType.
1540    ObjCClass,
1541
1542    /// The primitive Objective C 'SEL' type.  The user-visible 'SEL'
1543    /// type is a typedef of a PointerType to this.
1544    ObjCSel,
1545
1546    /// This represents the type of an expression whose type is
1547    /// totally unknown, e.g. 'T::foo'.  It is permitted for this to
1548    /// appear in situations where the structure of the type is
1549    /// theoretically deducible.
1550    Dependent,
1551
1552    /// The type of an unresolved overload set.  A placeholder type.
1553    /// Expressions with this type have one of the following basic
1554    /// forms, with parentheses generally permitted:
1555    ///   foo          # possibly qualified, not if an implicit access
1556    ///   foo          # possibly qualified, not if an implicit access
1557    ///   &foo         # possibly qualified, not if an implicit access
1558    ///   x->foo       # only if might be a static member function
1559    ///   &x->foo      # only if might be a static member function
1560    ///   &Class::foo  # when a pointer-to-member; sub-expr also has this type
1561    /// OverloadExpr::find can be used to analyze the expression.
1562    Overload,
1563
1564    /// The type of a bound C++ non-static member function.
1565    /// A placeholder type.  Expressions with this type have one of the
1566    /// following basic forms:
1567    ///   foo          # if an implicit access
1568    ///   x->foo       # if only contains non-static members
1569    BoundMember,
1570
1571    /// __builtin_any_type.  A placeholder type.  Useful for clients
1572    /// like debuggers that don't know what type to give something.
1573    /// Only a small number of operations are valid on expressions of
1574    /// unknown type, most notably explicit casts.
1575    UnknownAny
1576  };
1577
1578public:
1579  BuiltinType(Kind K)
1580    : Type(Builtin, QualType(), /*Dependent=*/(K == Dependent),
1581           /*VariablyModified=*/false,
1582           /*Unexpanded paramter pack=*/false) {
1583    BuiltinTypeBits.Kind = K;
1584  }
1585
1586  Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
1587  const char *getName(const LangOptions &LO) const;
1588
1589  bool isSugared() const { return false; }
1590  QualType desugar() const { return QualType(this, 0); }
1591
1592  bool isInteger() const {
1593    return getKind() >= Bool && getKind() <= Int128;
1594  }
1595
1596  bool isSignedInteger() const {
1597    return getKind() >= Char_S && getKind() <= Int128;
1598  }
1599
1600  bool isUnsignedInteger() const {
1601    return getKind() >= Bool && getKind() <= UInt128;
1602  }
1603
1604  bool isFloatingPoint() const {
1605    return getKind() >= Float && getKind() <= LongDouble;
1606  }
1607
1608  /// Determines whether this type is a placeholder type, i.e. a type
1609  /// which cannot appear in arbitrary positions in a fully-formed
1610  /// expression.
1611  bool isPlaceholderType() const {
1612    return getKind() >= Overload;
1613  }
1614
1615  static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
1616  static bool classof(const BuiltinType *) { return true; }
1617};
1618
1619/// ComplexType - C99 6.2.5p11 - Complex values.  This supports the C99 complex
1620/// types (_Complex float etc) as well as the GCC integer complex extensions.
1621///
1622class ComplexType : public Type, public llvm::FoldingSetNode {
1623  QualType ElementType;
1624  ComplexType(QualType Element, QualType CanonicalPtr) :
1625    Type(Complex, CanonicalPtr, Element->isDependentType(),
1626         Element->isVariablyModifiedType(),
1627         Element->containsUnexpandedParameterPack()),
1628    ElementType(Element) {
1629  }
1630  friend class ASTContext;  // ASTContext creates these.
1631
1632public:
1633  QualType getElementType() const { return ElementType; }
1634
1635  bool isSugared() const { return false; }
1636  QualType desugar() const { return QualType(this, 0); }
1637
1638  void Profile(llvm::FoldingSetNodeID &ID) {
1639    Profile(ID, getElementType());
1640  }
1641  static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
1642    ID.AddPointer(Element.getAsOpaquePtr());
1643  }
1644
1645  static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
1646  static bool classof(const ComplexType *) { return true; }
1647};
1648
1649/// ParenType - Sugar for parentheses used when specifying types.
1650///
1651class ParenType : public Type, public llvm::FoldingSetNode {
1652  QualType Inner;
1653
1654  ParenType(QualType InnerType, QualType CanonType) :
1655    Type(Paren, CanonType, InnerType->isDependentType(),
1656         InnerType->isVariablyModifiedType(),
1657         InnerType->containsUnexpandedParameterPack()),
1658    Inner(InnerType) {
1659  }
1660  friend class ASTContext;  // ASTContext creates these.
1661
1662public:
1663
1664  QualType getInnerType() const { return Inner; }
1665
1666  bool isSugared() const { return true; }
1667  QualType desugar() const { return getInnerType(); }
1668
1669  void Profile(llvm::FoldingSetNodeID &ID) {
1670    Profile(ID, getInnerType());
1671  }
1672  static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
1673    Inner.Profile(ID);
1674  }
1675
1676  static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
1677  static bool classof(const ParenType *) { return true; }
1678};
1679
1680/// PointerType - C99 6.7.5.1 - Pointer Declarators.
1681///
1682class PointerType : public Type, public llvm::FoldingSetNode {
1683  QualType PointeeType;
1684
1685  PointerType(QualType Pointee, QualType CanonicalPtr) :
1686    Type(Pointer, CanonicalPtr, Pointee->isDependentType(),
1687         Pointee->isVariablyModifiedType(),
1688         Pointee->containsUnexpandedParameterPack()),
1689    PointeeType(Pointee) {
1690  }
1691  friend class ASTContext;  // ASTContext creates these.
1692
1693public:
1694
1695  QualType getPointeeType() const { return PointeeType; }
1696
1697  bool isSugared() const { return false; }
1698  QualType desugar() const { return QualType(this, 0); }
1699
1700  void Profile(llvm::FoldingSetNodeID &ID) {
1701    Profile(ID, getPointeeType());
1702  }
1703  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
1704    ID.AddPointer(Pointee.getAsOpaquePtr());
1705  }
1706
1707  static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
1708  static bool classof(const PointerType *) { return true; }
1709};
1710
1711/// BlockPointerType - pointer to a block type.
1712/// This type is to represent types syntactically represented as
1713/// "void (^)(int)", etc. Pointee is required to always be a function type.
1714///
1715class BlockPointerType : public Type, public llvm::FoldingSetNode {
1716  QualType PointeeType;  // Block is some kind of pointer type
1717  BlockPointerType(QualType Pointee, QualType CanonicalCls) :
1718    Type(BlockPointer, CanonicalCls, Pointee->isDependentType(),
1719         Pointee->isVariablyModifiedType(),
1720         Pointee->containsUnexpandedParameterPack()),
1721    PointeeType(Pointee) {
1722  }
1723  friend class ASTContext;  // ASTContext creates these.
1724
1725public:
1726
1727  // Get the pointee type. Pointee is required to always be a function type.
1728  QualType getPointeeType() const { return PointeeType; }
1729
1730  bool isSugared() const { return false; }
1731  QualType desugar() const { return QualType(this, 0); }
1732
1733  void Profile(llvm::FoldingSetNodeID &ID) {
1734      Profile(ID, getPointeeType());
1735  }
1736  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
1737      ID.AddPointer(Pointee.getAsOpaquePtr());
1738  }
1739
1740  static bool classof(const Type *T) {
1741    return T->getTypeClass() == BlockPointer;
1742  }
1743  static bool classof(const BlockPointerType *) { return true; }
1744};
1745
1746/// ReferenceType - Base for LValueReferenceType and RValueReferenceType
1747///
1748class ReferenceType : public Type, public llvm::FoldingSetNode {
1749  QualType PointeeType;
1750
1751protected:
1752  ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
1753                bool SpelledAsLValue) :
1754    Type(tc, CanonicalRef, Referencee->isDependentType(),
1755         Referencee->isVariablyModifiedType(),
1756         Referencee->containsUnexpandedParameterPack()),
1757    PointeeType(Referencee)
1758  {
1759    ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
1760    ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
1761  }
1762
1763public:
1764  bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
1765  bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
1766
1767  QualType getPointeeTypeAsWritten() const { return PointeeType; }
1768  QualType getPointeeType() const {
1769    // FIXME: this might strip inner qualifiers; okay?
1770    const ReferenceType *T = this;
1771    while (T->isInnerRef())
1772      T = T->PointeeType->castAs<ReferenceType>();
1773    return T->PointeeType;
1774  }
1775
1776  void Profile(llvm::FoldingSetNodeID &ID) {
1777    Profile(ID, PointeeType, isSpelledAsLValue());
1778  }
1779  static void Profile(llvm::FoldingSetNodeID &ID,
1780                      QualType Referencee,
1781                      bool SpelledAsLValue) {
1782    ID.AddPointer(Referencee.getAsOpaquePtr());
1783    ID.AddBoolean(SpelledAsLValue);
1784  }
1785
1786  static bool classof(const Type *T) {
1787    return T->getTypeClass() == LValueReference ||
1788           T->getTypeClass() == RValueReference;
1789  }
1790  static bool classof(const ReferenceType *) { return true; }
1791};
1792
1793/// LValueReferenceType - C++ [dcl.ref] - Lvalue reference
1794///
1795class LValueReferenceType : public ReferenceType {
1796  LValueReferenceType(QualType Referencee, QualType CanonicalRef,
1797                      bool SpelledAsLValue) :
1798    ReferenceType(LValueReference, Referencee, CanonicalRef, SpelledAsLValue)
1799  {}
1800  friend class ASTContext; // ASTContext creates these
1801public:
1802  bool isSugared() const { return false; }
1803  QualType desugar() const { return QualType(this, 0); }
1804
1805  static bool classof(const Type *T) {
1806    return T->getTypeClass() == LValueReference;
1807  }
1808  static bool classof(const LValueReferenceType *) { return true; }
1809};
1810
1811/// RValueReferenceType - C++0x [dcl.ref] - Rvalue reference
1812///
1813class RValueReferenceType : public ReferenceType {
1814  RValueReferenceType(QualType Referencee, QualType CanonicalRef) :
1815    ReferenceType(RValueReference, Referencee, CanonicalRef, false) {
1816  }
1817  friend class ASTContext; // ASTContext creates these
1818public:
1819  bool isSugared() const { return false; }
1820  QualType desugar() const { return QualType(this, 0); }
1821
1822  static bool classof(const Type *T) {
1823    return T->getTypeClass() == RValueReference;
1824  }
1825  static bool classof(const RValueReferenceType *) { return true; }
1826};
1827
1828/// MemberPointerType - C++ 8.3.3 - Pointers to members
1829///
1830class MemberPointerType : public Type, public llvm::FoldingSetNode {
1831  QualType PointeeType;
1832  /// The class of which the pointee is a member. Must ultimately be a
1833  /// RecordType, but could be a typedef or a template parameter too.
1834  const Type *Class;
1835
1836  MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr) :
1837    Type(MemberPointer, CanonicalPtr,
1838         Cls->isDependentType() || Pointee->isDependentType(),
1839         Pointee->isVariablyModifiedType(),
1840         (Cls->containsUnexpandedParameterPack() ||
1841          Pointee->containsUnexpandedParameterPack())),
1842    PointeeType(Pointee), Class(Cls) {
1843  }
1844  friend class ASTContext; // ASTContext creates these.
1845
1846public:
1847  QualType getPointeeType() const { return PointeeType; }
1848
1849  /// Returns true if the member type (i.e. the pointee type) is a
1850  /// function type rather than a data-member type.
1851  bool isMemberFunctionPointer() const {
1852    return PointeeType->isFunctionProtoType();
1853  }
1854
1855  /// Returns true if the member type (i.e. the pointee type) is a
1856  /// data type rather than a function type.
1857  bool isMemberDataPointer() const {
1858    return !PointeeType->isFunctionProtoType();
1859  }
1860
1861  const Type *getClass() const { return Class; }
1862
1863  bool isSugared() const { return false; }
1864  QualType desugar() const { return QualType(this, 0); }
1865
1866  void Profile(llvm::FoldingSetNodeID &ID) {
1867    Profile(ID, getPointeeType(), getClass());
1868  }
1869  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
1870                      const Type *Class) {
1871    ID.AddPointer(Pointee.getAsOpaquePtr());
1872    ID.AddPointer(Class);
1873  }
1874
1875  static bool classof(const Type *T) {
1876    return T->getTypeClass() == MemberPointer;
1877  }
1878  static bool classof(const MemberPointerType *) { return true; }
1879};
1880
1881/// ArrayType - C99 6.7.5.2 - Array Declarators.
1882///
1883class ArrayType : public Type, public llvm::FoldingSetNode {
1884public:
1885  /// ArraySizeModifier - Capture whether this is a normal array (e.g. int X[4])
1886  /// an array with a static size (e.g. int X[static 4]), or an array
1887  /// with a star size (e.g. int X[*]).
1888  /// 'static' is only allowed on function parameters.
1889  enum ArraySizeModifier {
1890    Normal, Static, Star
1891  };
1892private:
1893  /// ElementType - The element type of the array.
1894  QualType ElementType;
1895
1896protected:
1897  // C++ [temp.dep.type]p1:
1898  //   A type is dependent if it is...
1899  //     - an array type constructed from any dependent type or whose
1900  //       size is specified by a constant expression that is
1901  //       value-dependent,
1902  ArrayType(TypeClass tc, QualType et, QualType can,
1903            ArraySizeModifier sm, unsigned tq,
1904            bool ContainsUnexpandedParameterPack)
1905    : Type(tc, can, et->isDependentType() || tc == DependentSizedArray,
1906           (tc == VariableArray || et->isVariablyModifiedType()),
1907           ContainsUnexpandedParameterPack),
1908      ElementType(et) {
1909    ArrayTypeBits.IndexTypeQuals = tq;
1910    ArrayTypeBits.SizeModifier = sm;
1911  }
1912
1913  friend class ASTContext;  // ASTContext creates these.
1914
1915public:
1916  QualType getElementType() const { return ElementType; }
1917  ArraySizeModifier getSizeModifier() const {
1918    return ArraySizeModifier(ArrayTypeBits.SizeModifier);
1919  }
1920  Qualifiers getIndexTypeQualifiers() const {
1921    return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
1922  }
1923  unsigned getIndexTypeCVRQualifiers() const {
1924    return ArrayTypeBits.IndexTypeQuals;
1925  }
1926
1927  static bool classof(const Type *T) {
1928    return T->getTypeClass() == ConstantArray ||
1929           T->getTypeClass() == VariableArray ||
1930           T->getTypeClass() == IncompleteArray ||
1931           T->getTypeClass() == DependentSizedArray;
1932  }
1933  static bool classof(const ArrayType *) { return true; }
1934};
1935
1936/// ConstantArrayType - This class represents the canonical version of
1937/// C arrays with a specified constant size.  For example, the canonical
1938/// type for 'int A[4 + 4*100]' is a ConstantArrayType where the element
1939/// type is 'int' and the size is 404.
1940class ConstantArrayType : public ArrayType {
1941  llvm::APInt Size; // Allows us to unique the type.
1942
1943  ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
1944                    ArraySizeModifier sm, unsigned tq)
1945    : ArrayType(ConstantArray, et, can, sm, tq,
1946                et->containsUnexpandedParameterPack()),
1947      Size(size) {}
1948protected:
1949  ConstantArrayType(TypeClass tc, QualType et, QualType can,
1950                    const llvm::APInt &size, ArraySizeModifier sm, unsigned tq)
1951    : ArrayType(tc, et, can, sm, tq, et->containsUnexpandedParameterPack()),
1952      Size(size) {}
1953  friend class ASTContext;  // ASTContext creates these.
1954public:
1955  const llvm::APInt &getSize() const { return Size; }
1956  bool isSugared() const { return false; }
1957  QualType desugar() const { return QualType(this, 0); }
1958
1959
1960  /// \brief Determine the number of bits required to address a member of
1961  // an array with the given element type and number of elements.
1962  static unsigned getNumAddressingBits(ASTContext &Context,
1963                                       QualType ElementType,
1964                                       const llvm::APInt &NumElements);
1965
1966  /// \brief Determine the maximum number of active bits that an array's size
1967  /// can require, which limits the maximum size of the array.
1968  static unsigned getMaxSizeBits(ASTContext &Context);
1969
1970  void Profile(llvm::FoldingSetNodeID &ID) {
1971    Profile(ID, getElementType(), getSize(),
1972            getSizeModifier(), getIndexTypeCVRQualifiers());
1973  }
1974  static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
1975                      const llvm::APInt &ArraySize, ArraySizeModifier SizeMod,
1976                      unsigned TypeQuals) {
1977    ID.AddPointer(ET.getAsOpaquePtr());
1978    ID.AddInteger(ArraySize.getZExtValue());
1979    ID.AddInteger(SizeMod);
1980    ID.AddInteger(TypeQuals);
1981  }
1982  static bool classof(const Type *T) {
1983    return T->getTypeClass() == ConstantArray;
1984  }
1985  static bool classof(const ConstantArrayType *) { return true; }
1986};
1987
1988/// IncompleteArrayType - This class represents C arrays with an unspecified
1989/// size.  For example 'int A[]' has an IncompleteArrayType where the element
1990/// type is 'int' and the size is unspecified.
1991class IncompleteArrayType : public ArrayType {
1992
1993  IncompleteArrayType(QualType et, QualType can,
1994                      ArraySizeModifier sm, unsigned tq)
1995    : ArrayType(IncompleteArray, et, can, sm, tq,
1996                et->containsUnexpandedParameterPack()) {}
1997  friend class ASTContext;  // ASTContext creates these.
1998public:
1999  bool isSugared() const { return false; }
2000  QualType desugar() const { return QualType(this, 0); }
2001
2002  static bool classof(const Type *T) {
2003    return T->getTypeClass() == IncompleteArray;
2004  }
2005  static bool classof(const IncompleteArrayType *) { return true; }
2006
2007  friend class StmtIteratorBase;
2008
2009  void Profile(llvm::FoldingSetNodeID &ID) {
2010    Profile(ID, getElementType(), getSizeModifier(),
2011            getIndexTypeCVRQualifiers());
2012  }
2013
2014  static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2015                      ArraySizeModifier SizeMod, unsigned TypeQuals) {
2016    ID.AddPointer(ET.getAsOpaquePtr());
2017    ID.AddInteger(SizeMod);
2018    ID.AddInteger(TypeQuals);
2019  }
2020};
2021
2022/// VariableArrayType - This class represents C arrays with a specified size
2023/// which is not an integer-constant-expression.  For example, 'int s[x+foo()]'.
2024/// Since the size expression is an arbitrary expression, we store it as such.
2025///
2026/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
2027/// should not be: two lexically equivalent variable array types could mean
2028/// different things, for example, these variables do not have the same type
2029/// dynamically:
2030///
2031/// void foo(int x) {
2032///   int Y[x];
2033///   ++x;
2034///   int Z[x];
2035/// }
2036///
2037class VariableArrayType : public ArrayType {
2038  /// SizeExpr - An assignment expression. VLA's are only permitted within
2039  /// a function block.
2040  Stmt *SizeExpr;
2041  /// Brackets - The left and right array brackets.
2042  SourceRange Brackets;
2043
2044  VariableArrayType(QualType et, QualType can, Expr *e,
2045                    ArraySizeModifier sm, unsigned tq,
2046                    SourceRange brackets)
2047    : ArrayType(VariableArray, et, can, sm, tq,
2048                et->containsUnexpandedParameterPack()),
2049      SizeExpr((Stmt*) e), Brackets(brackets) {}
2050  friend class ASTContext;  // ASTContext creates these.
2051
2052public:
2053  Expr *getSizeExpr() const {
2054    // We use C-style casts instead of cast<> here because we do not wish
2055    // to have a dependency of Type.h on Stmt.h/Expr.h.
2056    return (Expr*) SizeExpr;
2057  }
2058  SourceRange getBracketsRange() const { return Brackets; }
2059  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2060  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2061
2062  bool isSugared() const { return false; }
2063  QualType desugar() const { return QualType(this, 0); }
2064
2065  static bool classof(const Type *T) {
2066    return T->getTypeClass() == VariableArray;
2067  }
2068  static bool classof(const VariableArrayType *) { return true; }
2069
2070  friend class StmtIteratorBase;
2071
2072  void Profile(llvm::FoldingSetNodeID &ID) {
2073    assert(0 && "Cannot unique VariableArrayTypes.");
2074  }
2075};
2076
2077/// DependentSizedArrayType - This type represents an array type in
2078/// C++ whose size is a value-dependent expression. For example:
2079///
2080/// \code
2081/// template<typename T, int Size>
2082/// class array {
2083///   T data[Size];
2084/// };
2085/// \endcode
2086///
2087/// For these types, we won't actually know what the array bound is
2088/// until template instantiation occurs, at which point this will
2089/// become either a ConstantArrayType or a VariableArrayType.
2090class DependentSizedArrayType : public ArrayType {
2091  const ASTContext &Context;
2092
2093  /// \brief An assignment expression that will instantiate to the
2094  /// size of the array.
2095  ///
2096  /// The expression itself might be NULL, in which case the array
2097  /// type will have its size deduced from an initializer.
2098  Stmt *SizeExpr;
2099
2100  /// Brackets - The left and right array brackets.
2101  SourceRange Brackets;
2102
2103  DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
2104                          Expr *e, ArraySizeModifier sm, unsigned tq,
2105                          SourceRange brackets);
2106
2107  friend class ASTContext;  // ASTContext creates these.
2108
2109public:
2110  Expr *getSizeExpr() const {
2111    // We use C-style casts instead of cast<> here because we do not wish
2112    // to have a dependency of Type.h on Stmt.h/Expr.h.
2113    return (Expr*) SizeExpr;
2114  }
2115  SourceRange getBracketsRange() const { return Brackets; }
2116  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
2117  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
2118
2119  bool isSugared() const { return false; }
2120  QualType desugar() const { return QualType(this, 0); }
2121
2122  static bool classof(const Type *T) {
2123    return T->getTypeClass() == DependentSizedArray;
2124  }
2125  static bool classof(const DependentSizedArrayType *) { return true; }
2126
2127  friend class StmtIteratorBase;
2128
2129
2130  void Profile(llvm::FoldingSetNodeID &ID) {
2131    Profile(ID, Context, getElementType(),
2132            getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
2133  }
2134
2135  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2136                      QualType ET, ArraySizeModifier SizeMod,
2137                      unsigned TypeQuals, Expr *E);
2138};
2139
2140/// DependentSizedExtVectorType - This type represent an extended vector type
2141/// where either the type or size is dependent. For example:
2142/// @code
2143/// template<typename T, int Size>
2144/// class vector {
2145///   typedef T __attribute__((ext_vector_type(Size))) type;
2146/// }
2147/// @endcode
2148class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
2149  const ASTContext &Context;
2150  Expr *SizeExpr;
2151  /// ElementType - The element type of the array.
2152  QualType ElementType;
2153  SourceLocation loc;
2154
2155  DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
2156                              QualType can, Expr *SizeExpr, SourceLocation loc);
2157
2158  friend class ASTContext;
2159
2160public:
2161  Expr *getSizeExpr() const { return SizeExpr; }
2162  QualType getElementType() const { return ElementType; }
2163  SourceLocation getAttributeLoc() const { return loc; }
2164
2165  bool isSugared() const { return false; }
2166  QualType desugar() const { return QualType(this, 0); }
2167
2168  static bool classof(const Type *T) {
2169    return T->getTypeClass() == DependentSizedExtVector;
2170  }
2171  static bool classof(const DependentSizedExtVectorType *) { return true; }
2172
2173  void Profile(llvm::FoldingSetNodeID &ID) {
2174    Profile(ID, Context, getElementType(), getSizeExpr());
2175  }
2176
2177  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2178                      QualType ElementType, Expr *SizeExpr);
2179};
2180
2181
2182/// VectorType - GCC generic vector type. This type is created using
2183/// __attribute__((vector_size(n)), where "n" specifies the vector size in
2184/// bytes; or from an Altivec __vector or vector declaration.
2185/// Since the constructor takes the number of vector elements, the
2186/// client is responsible for converting the size into the number of elements.
2187class VectorType : public Type, public llvm::FoldingSetNode {
2188public:
2189  enum VectorKind {
2190    GenericVector,  // not a target-specific vector type
2191    AltiVecVector,  // is AltiVec vector
2192    AltiVecPixel,   // is AltiVec 'vector Pixel'
2193    AltiVecBool,    // is AltiVec 'vector bool ...'
2194    NeonVector,     // is ARM Neon vector
2195    NeonPolyVector  // is ARM Neon polynomial vector
2196  };
2197protected:
2198  /// ElementType - The element type of the vector.
2199  QualType ElementType;
2200
2201  VectorType(QualType vecType, unsigned nElements, QualType canonType,
2202             VectorKind vecKind);
2203
2204  VectorType(TypeClass tc, QualType vecType, unsigned nElements,
2205             QualType canonType, VectorKind vecKind);
2206
2207  friend class ASTContext;  // ASTContext creates these.
2208
2209public:
2210
2211  QualType getElementType() const { return ElementType; }
2212  unsigned getNumElements() const { return VectorTypeBits.NumElements; }
2213
2214  bool isSugared() const { return false; }
2215  QualType desugar() const { return QualType(this, 0); }
2216
2217  VectorKind getVectorKind() const {
2218    return VectorKind(VectorTypeBits.VecKind);
2219  }
2220
2221  void Profile(llvm::FoldingSetNodeID &ID) {
2222    Profile(ID, getElementType(), getNumElements(),
2223            getTypeClass(), getVectorKind());
2224  }
2225  static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
2226                      unsigned NumElements, TypeClass TypeClass,
2227                      VectorKind VecKind) {
2228    ID.AddPointer(ElementType.getAsOpaquePtr());
2229    ID.AddInteger(NumElements);
2230    ID.AddInteger(TypeClass);
2231    ID.AddInteger(VecKind);
2232  }
2233
2234  static bool classof(const Type *T) {
2235    return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
2236  }
2237  static bool classof(const VectorType *) { return true; }
2238};
2239
2240/// ExtVectorType - Extended vector type. This type is created using
2241/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
2242/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
2243/// class enables syntactic extensions, like Vector Components for accessing
2244/// points, colors, and textures (modeled after OpenGL Shading Language).
2245class ExtVectorType : public VectorType {
2246  ExtVectorType(QualType vecType, unsigned nElements, QualType canonType) :
2247    VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
2248  friend class ASTContext;  // ASTContext creates these.
2249public:
2250  static int getPointAccessorIdx(char c) {
2251    switch (c) {
2252    default: return -1;
2253    case 'x': return 0;
2254    case 'y': return 1;
2255    case 'z': return 2;
2256    case 'w': return 3;
2257    }
2258  }
2259  static int getNumericAccessorIdx(char c) {
2260    switch (c) {
2261      default: return -1;
2262      case '0': return 0;
2263      case '1': return 1;
2264      case '2': return 2;
2265      case '3': return 3;
2266      case '4': return 4;
2267      case '5': return 5;
2268      case '6': return 6;
2269      case '7': return 7;
2270      case '8': return 8;
2271      case '9': return 9;
2272      case 'A':
2273      case 'a': return 10;
2274      case 'B':
2275      case 'b': return 11;
2276      case 'C':
2277      case 'c': return 12;
2278      case 'D':
2279      case 'd': return 13;
2280      case 'E':
2281      case 'e': return 14;
2282      case 'F':
2283      case 'f': return 15;
2284    }
2285  }
2286
2287  static int getAccessorIdx(char c) {
2288    if (int idx = getPointAccessorIdx(c)+1) return idx-1;
2289    return getNumericAccessorIdx(c);
2290  }
2291
2292  bool isAccessorWithinNumElements(char c) const {
2293    if (int idx = getAccessorIdx(c)+1)
2294      return unsigned(idx-1) < getNumElements();
2295    return false;
2296  }
2297  bool isSugared() const { return false; }
2298  QualType desugar() const { return QualType(this, 0); }
2299
2300  static bool classof(const Type *T) {
2301    return T->getTypeClass() == ExtVector;
2302  }
2303  static bool classof(const ExtVectorType *) { return true; }
2304};
2305
2306/// FunctionType - C99 6.7.5.3 - Function Declarators.  This is the common base
2307/// class of FunctionNoProtoType and FunctionProtoType.
2308///
2309class FunctionType : public Type {
2310  // The type returned by the function.
2311  QualType ResultType;
2312
2313 public:
2314  /// ExtInfo - A class which abstracts out some details necessary for
2315  /// making a call.
2316  ///
2317  /// It is not actually used directly for storing this information in
2318  /// a FunctionType, although FunctionType does currently use the
2319  /// same bit-pattern.
2320  ///
2321  // If you add a field (say Foo), other than the obvious places (both,
2322  // constructors, compile failures), what you need to update is
2323  // * Operator==
2324  // * getFoo
2325  // * withFoo
2326  // * functionType. Add Foo, getFoo.
2327  // * ASTContext::getFooType
2328  // * ASTContext::mergeFunctionTypes
2329  // * FunctionNoProtoType::Profile
2330  // * FunctionProtoType::Profile
2331  // * TypePrinter::PrintFunctionProto
2332  // * AST read and write
2333  // * Codegen
2334  class ExtInfo {
2335    // Feel free to rearrange or add bits, but if you go over 8,
2336    // you'll need to adjust both the Bits field below and
2337    // Type::FunctionTypeBitfields.
2338
2339    //   |  CC  |noreturn|hasregparm|regparm
2340    //   |0 .. 2|   3    |    4     |5 ..  7
2341    enum { CallConvMask = 0x7 };
2342    enum { NoReturnMask = 0x8 };
2343    enum { HasRegParmMask = 0x10 };
2344    enum { RegParmMask = ~(CallConvMask | NoReturnMask),
2345           RegParmOffset = 5 };
2346
2347    unsigned char Bits;
2348
2349    ExtInfo(unsigned Bits) : Bits(static_cast<unsigned char>(Bits)) {}
2350
2351    friend class FunctionType;
2352
2353   public:
2354    // Constructor with no defaults. Use this when you know that you
2355    // have all the elements (when reading an AST file for example).
2356    ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc) {
2357      Bits = ((unsigned) cc) |
2358             (noReturn ? NoReturnMask : 0) |
2359             (hasRegParm ? HasRegParmMask : 0) |
2360             (regParm << RegParmOffset);
2361    }
2362
2363    // Constructor with all defaults. Use when for example creating a
2364    // function know to use defaults.
2365    ExtInfo() : Bits(0) {}
2366
2367    bool getNoReturn() const { return Bits & NoReturnMask; }
2368    bool getHasRegParm() const { return Bits & HasRegParmMask; }
2369    unsigned getRegParm() const { return Bits >> RegParmOffset; }
2370    CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
2371
2372    bool operator==(ExtInfo Other) const {
2373      return Bits == Other.Bits;
2374    }
2375    bool operator!=(ExtInfo Other) const {
2376      return Bits != Other.Bits;
2377    }
2378
2379    // Note that we don't have setters. That is by design, use
2380    // the following with methods instead of mutating these objects.
2381
2382    ExtInfo withNoReturn(bool noReturn) const {
2383      if (noReturn)
2384        return ExtInfo(Bits | NoReturnMask);
2385      else
2386        return ExtInfo(Bits & ~NoReturnMask);
2387    }
2388
2389    ExtInfo withRegParm(unsigned RegParm) const {
2390      return ExtInfo(HasRegParmMask | (Bits & ~RegParmMask) | (RegParm << RegParmOffset));
2391    }
2392
2393    ExtInfo withCallingConv(CallingConv cc) const {
2394      return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
2395    }
2396
2397    void Profile(llvm::FoldingSetNodeID &ID) const {
2398      ID.AddInteger(Bits);
2399    }
2400  };
2401
2402protected:
2403  FunctionType(TypeClass tc, QualType res, bool variadic,
2404               unsigned typeQuals, RefQualifierKind RefQualifier,
2405               QualType Canonical, bool Dependent,
2406               bool VariablyModified, bool ContainsUnexpandedParameterPack,
2407               ExtInfo Info)
2408    : Type(tc, Canonical, Dependent, VariablyModified,
2409           ContainsUnexpandedParameterPack),
2410      ResultType(res) {
2411    FunctionTypeBits.ExtInfo = Info.Bits;
2412    FunctionTypeBits.Variadic = variadic;
2413    FunctionTypeBits.TypeQuals = typeQuals;
2414    FunctionTypeBits.RefQualifier = static_cast<unsigned>(RefQualifier);
2415  }
2416  bool isVariadic() const { return FunctionTypeBits.Variadic; }
2417  unsigned getTypeQuals() const { return FunctionTypeBits.TypeQuals; }
2418
2419  RefQualifierKind getRefQualifier() const {
2420    return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
2421  }
2422
2423public:
2424
2425  QualType getResultType() const { return ResultType; }
2426
2427  bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
2428  unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
2429  bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
2430  CallingConv getCallConv() const { return getExtInfo().getCC(); }
2431  ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
2432
2433  /// \brief Determine the type of an expression that calls a function of
2434  /// this type.
2435  QualType getCallResultType(ASTContext &Context) const {
2436    return getResultType().getNonLValueExprType(Context);
2437  }
2438
2439  static llvm::StringRef getNameForCallConv(CallingConv CC);
2440
2441  static bool classof(const Type *T) {
2442    return T->getTypeClass() == FunctionNoProto ||
2443           T->getTypeClass() == FunctionProto;
2444  }
2445  static bool classof(const FunctionType *) { return true; }
2446};
2447
2448/// FunctionNoProtoType - Represents a K&R-style 'int foo()' function, which has
2449/// no information available about its arguments.
2450class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
2451  FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
2452    : FunctionType(FunctionNoProto, Result, false, 0, RQ_None, Canonical,
2453                   /*Dependent=*/false, Result->isVariablyModifiedType(),
2454                   /*ContainsUnexpandedParameterPack=*/false, Info) {}
2455
2456  friend class ASTContext;  // ASTContext creates these.
2457
2458public:
2459  // No additional state past what FunctionType provides.
2460
2461  bool isSugared() const { return false; }
2462  QualType desugar() const { return QualType(this, 0); }
2463
2464  void Profile(llvm::FoldingSetNodeID &ID) {
2465    Profile(ID, getResultType(), getExtInfo());
2466  }
2467  static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
2468                      ExtInfo Info) {
2469    Info.Profile(ID);
2470    ID.AddPointer(ResultType.getAsOpaquePtr());
2471  }
2472
2473  static bool classof(const Type *T) {
2474    return T->getTypeClass() == FunctionNoProto;
2475  }
2476  static bool classof(const FunctionNoProtoType *) { return true; }
2477};
2478
2479/// FunctionProtoType - Represents a prototype with argument type info, e.g.
2480/// 'int foo(int)' or 'int foo(void)'.  'void' is represented as having no
2481/// arguments, not as having a single void argument. Such a type can have an
2482/// exception specification, but this specification is not part of the canonical
2483/// type.
2484class FunctionProtoType : public FunctionType, public llvm::FoldingSetNode {
2485public:
2486  /// ExtProtoInfo - Extra information about a function prototype.
2487  struct ExtProtoInfo {
2488    ExtProtoInfo() :
2489      Variadic(false), ExceptionSpecType(EST_None), TypeQuals(0),
2490      RefQualifier(RQ_None), NumExceptions(0), Exceptions(0), NoexceptExpr(0) {}
2491
2492    FunctionType::ExtInfo ExtInfo;
2493    bool Variadic;
2494    ExceptionSpecificationType ExceptionSpecType;
2495    unsigned char TypeQuals;
2496    RefQualifierKind RefQualifier;
2497    unsigned NumExceptions;
2498    const QualType *Exceptions;
2499    Expr *NoexceptExpr;
2500  };
2501
2502private:
2503  /// \brief Determine whether there are any argument types that
2504  /// contain an unexpanded parameter pack.
2505  static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
2506                                                 unsigned numArgs) {
2507    for (unsigned Idx = 0; Idx < numArgs; ++Idx)
2508      if (ArgArray[Idx]->containsUnexpandedParameterPack())
2509        return true;
2510
2511    return false;
2512  }
2513
2514  FunctionProtoType(QualType result, const QualType *args, unsigned numArgs,
2515                    QualType canonical, const ExtProtoInfo &epi);
2516
2517  /// NumArgs - The number of arguments this function has, not counting '...'.
2518  unsigned NumArgs : 20;
2519
2520  /// NumExceptions - The number of types in the exception spec, if any.
2521  unsigned NumExceptions : 9;
2522
2523  /// ExceptionSpecType - The type of exception specification this function has.
2524  unsigned ExceptionSpecType : 3;
2525
2526  /// ArgInfo - There is an variable size array after the class in memory that
2527  /// holds the argument types.
2528
2529  /// Exceptions - There is another variable size array after ArgInfo that
2530  /// holds the exception types.
2531
2532  /// NoexceptExpr - Instead of Exceptions, there may be a single Expr* pointing
2533  /// to the expression in the noexcept() specifier.
2534
2535  friend class ASTContext;  // ASTContext creates these.
2536
2537public:
2538  unsigned getNumArgs() const { return NumArgs; }
2539  QualType getArgType(unsigned i) const {
2540    assert(i < NumArgs && "Invalid argument number!");
2541    return arg_type_begin()[i];
2542  }
2543
2544  ExtProtoInfo getExtProtoInfo() const {
2545    ExtProtoInfo EPI;
2546    EPI.ExtInfo = getExtInfo();
2547    EPI.Variadic = isVariadic();
2548    EPI.ExceptionSpecType = getExceptionSpecType();
2549    EPI.TypeQuals = static_cast<unsigned char>(getTypeQuals());
2550    EPI.RefQualifier = getRefQualifier();
2551    if (EPI.ExceptionSpecType == EST_Dynamic) {
2552      EPI.NumExceptions = NumExceptions;
2553      EPI.Exceptions = exception_begin();
2554    } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
2555      EPI.NoexceptExpr = getNoexceptExpr();
2556    }
2557    return EPI;
2558  }
2559
2560  /// \brief Get the kind of exception specification on this function.
2561  ExceptionSpecificationType getExceptionSpecType() const {
2562    return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
2563  }
2564  /// \brief Return whether this function has any kind of exception spec.
2565  bool hasExceptionSpec() const {
2566    return getExceptionSpecType() != EST_None;
2567  }
2568  /// \brief Return whether this function has a dynamic (throw) exception spec.
2569  bool hasDynamicExceptionSpec() const {
2570    return isDynamicExceptionSpec(getExceptionSpecType());
2571  }
2572  /// \brief Return whether this function has a noexcept exception spec.
2573  bool hasNoexceptExceptionSpec() const {
2574    return isNoexceptExceptionSpec(getExceptionSpecType());
2575  }
2576  /// \brief Result type of getNoexceptSpec().
2577  enum NoexceptResult {
2578    NR_NoNoexcept,  ///< There is no noexcept specifier.
2579    NR_BadNoexcept, ///< The noexcept specifier has a bad expression.
2580    NR_Dependent,   ///< The noexcept specifier is dependent.
2581    NR_Throw,       ///< The noexcept specifier evaluates to false.
2582    NR_Nothrow      ///< The noexcept specifier evaluates to true.
2583  };
2584  /// \brief Get the meaning of the noexcept spec on this function, if any.
2585  NoexceptResult getNoexceptSpec(ASTContext &Ctx) const;
2586  unsigned getNumExceptions() const { return NumExceptions; }
2587  QualType getExceptionType(unsigned i) const {
2588    assert(i < NumExceptions && "Invalid exception number!");
2589    return exception_begin()[i];
2590  }
2591  Expr *getNoexceptExpr() const {
2592    if (getExceptionSpecType() != EST_ComputedNoexcept)
2593      return 0;
2594    // NoexceptExpr sits where the arguments end.
2595    return *reinterpret_cast<Expr *const *>(arg_type_end());
2596  }
2597  bool isNothrow(ASTContext &Ctx) const {
2598    ExceptionSpecificationType EST = getExceptionSpecType();
2599    if (EST == EST_DynamicNone || EST == EST_BasicNoexcept)
2600      return true;
2601    if (EST != EST_ComputedNoexcept)
2602      return false;
2603    return getNoexceptSpec(Ctx) == NR_Nothrow;
2604  }
2605
2606  using FunctionType::isVariadic;
2607
2608  /// \brief Determines whether this function prototype contains a
2609  /// parameter pack at the end.
2610  ///
2611  /// A function template whose last parameter is a parameter pack can be
2612  /// called with an arbitrary number of arguments, much like a variadic
2613  /// function. However,
2614  bool isTemplateVariadic() const;
2615
2616  unsigned getTypeQuals() const { return FunctionType::getTypeQuals(); }
2617
2618
2619  /// \brief Retrieve the ref-qualifier associated with this function type.
2620  RefQualifierKind getRefQualifier() const {
2621    return FunctionType::getRefQualifier();
2622  }
2623
2624  typedef const QualType *arg_type_iterator;
2625  arg_type_iterator arg_type_begin() const {
2626    return reinterpret_cast<const QualType *>(this+1);
2627  }
2628  arg_type_iterator arg_type_end() const { return arg_type_begin()+NumArgs; }
2629
2630  typedef const QualType *exception_iterator;
2631  exception_iterator exception_begin() const {
2632    // exceptions begin where arguments end
2633    return arg_type_end();
2634  }
2635  exception_iterator exception_end() const {
2636    if (getExceptionSpecType() != EST_Dynamic)
2637      return exception_begin();
2638    return exception_begin() + NumExceptions;
2639  }
2640
2641  bool isSugared() const { return false; }
2642  QualType desugar() const { return QualType(this, 0); }
2643
2644  static bool classof(const Type *T) {
2645    return T->getTypeClass() == FunctionProto;
2646  }
2647  static bool classof(const FunctionProtoType *) { return true; }
2648
2649  void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
2650  static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
2651                      arg_type_iterator ArgTys, unsigned NumArgs,
2652                      const ExtProtoInfo &EPI, const ASTContext &Context);
2653};
2654
2655
2656/// \brief Represents the dependent type named by a dependently-scoped
2657/// typename using declaration, e.g.
2658///   using typename Base<T>::foo;
2659/// Template instantiation turns these into the underlying type.
2660class UnresolvedUsingType : public Type {
2661  UnresolvedUsingTypenameDecl *Decl;
2662
2663  UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
2664    : Type(UnresolvedUsing, QualType(), true, false,
2665           /*ContainsUnexpandedParameterPack=*/false),
2666      Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
2667  friend class ASTContext; // ASTContext creates these.
2668public:
2669
2670  UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
2671
2672  bool isSugared() const { return false; }
2673  QualType desugar() const { return QualType(this, 0); }
2674
2675  static bool classof(const Type *T) {
2676    return T->getTypeClass() == UnresolvedUsing;
2677  }
2678  static bool classof(const UnresolvedUsingType *) { return true; }
2679
2680  void Profile(llvm::FoldingSetNodeID &ID) {
2681    return Profile(ID, Decl);
2682  }
2683  static void Profile(llvm::FoldingSetNodeID &ID,
2684                      UnresolvedUsingTypenameDecl *D) {
2685    ID.AddPointer(D);
2686  }
2687};
2688
2689
2690class TypedefType : public Type {
2691  TypedefNameDecl *Decl;
2692protected:
2693  TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can)
2694    : Type(tc, can, can->isDependentType(), can->isVariablyModifiedType(),
2695           /*ContainsUnexpandedParameterPack=*/false),
2696      Decl(const_cast<TypedefNameDecl*>(D)) {
2697    assert(!isa<TypedefType>(can) && "Invalid canonical type");
2698  }
2699  friend class ASTContext;  // ASTContext creates these.
2700public:
2701
2702  TypedefNameDecl *getDecl() const { return Decl; }
2703
2704  bool isSugared() const { return true; }
2705  QualType desugar() const;
2706
2707  static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
2708  static bool classof(const TypedefType *) { return true; }
2709};
2710
2711/// TypeOfExprType (GCC extension).
2712class TypeOfExprType : public Type {
2713  Expr *TOExpr;
2714
2715protected:
2716  TypeOfExprType(Expr *E, QualType can = QualType());
2717  friend class ASTContext;  // ASTContext creates these.
2718public:
2719  Expr *getUnderlyingExpr() const { return TOExpr; }
2720
2721  /// \brief Remove a single level of sugar.
2722  QualType desugar() const;
2723
2724  /// \brief Returns whether this type directly provides sugar.
2725  bool isSugared() const { return true; }
2726
2727  static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
2728  static bool classof(const TypeOfExprType *) { return true; }
2729};
2730
2731/// \brief Internal representation of canonical, dependent
2732/// typeof(expr) types.
2733///
2734/// This class is used internally by the ASTContext to manage
2735/// canonical, dependent types, only. Clients will only see instances
2736/// of this class via TypeOfExprType nodes.
2737class DependentTypeOfExprType
2738  : public TypeOfExprType, public llvm::FoldingSetNode {
2739  const ASTContext &Context;
2740
2741public:
2742  DependentTypeOfExprType(const ASTContext &Context, Expr *E)
2743    : TypeOfExprType(E), Context(Context) { }
2744
2745  bool isSugared() const { return false; }
2746  QualType desugar() const { return QualType(this, 0); }
2747
2748  void Profile(llvm::FoldingSetNodeID &ID) {
2749    Profile(ID, Context, getUnderlyingExpr());
2750  }
2751
2752  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2753                      Expr *E);
2754};
2755
2756/// TypeOfType (GCC extension).
2757class TypeOfType : public Type {
2758  QualType TOType;
2759  TypeOfType(QualType T, QualType can)
2760    : Type(TypeOf, can, T->isDependentType(), T->isVariablyModifiedType(),
2761           T->containsUnexpandedParameterPack()),
2762      TOType(T) {
2763    assert(!isa<TypedefType>(can) && "Invalid canonical type");
2764  }
2765  friend class ASTContext;  // ASTContext creates these.
2766public:
2767  QualType getUnderlyingType() const { return TOType; }
2768
2769  /// \brief Remove a single level of sugar.
2770  QualType desugar() const { return getUnderlyingType(); }
2771
2772  /// \brief Returns whether this type directly provides sugar.
2773  bool isSugared() const { return true; }
2774
2775  static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
2776  static bool classof(const TypeOfType *) { return true; }
2777};
2778
2779/// DecltypeType (C++0x)
2780class DecltypeType : public Type {
2781  Expr *E;
2782
2783  // FIXME: We could get rid of UnderlyingType if we wanted to: We would have to
2784  // Move getDesugaredType to ASTContext so that it can call getDecltypeForExpr
2785  // from it.
2786  QualType UnderlyingType;
2787
2788protected:
2789  DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
2790  friend class ASTContext;  // ASTContext creates these.
2791public:
2792  Expr *getUnderlyingExpr() const { return E; }
2793  QualType getUnderlyingType() const { return UnderlyingType; }
2794
2795  /// \brief Remove a single level of sugar.
2796  QualType desugar() const { return getUnderlyingType(); }
2797
2798  /// \brief Returns whether this type directly provides sugar.
2799  bool isSugared() const { return !isDependentType(); }
2800
2801  static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
2802  static bool classof(const DecltypeType *) { return true; }
2803};
2804
2805/// \brief Internal representation of canonical, dependent
2806/// decltype(expr) types.
2807///
2808/// This class is used internally by the ASTContext to manage
2809/// canonical, dependent types, only. Clients will only see instances
2810/// of this class via DecltypeType nodes.
2811class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
2812  const ASTContext &Context;
2813
2814public:
2815  DependentDecltypeType(const ASTContext &Context, Expr *E);
2816
2817  bool isSugared() const { return false; }
2818  QualType desugar() const { return QualType(this, 0); }
2819
2820  void Profile(llvm::FoldingSetNodeID &ID) {
2821    Profile(ID, Context, getUnderlyingExpr());
2822  }
2823
2824  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
2825                      Expr *E);
2826};
2827
2828/// \brief A unary type transform, which is a type constructed from another
2829class UnaryTransformType : public Type {
2830public:
2831  enum UTTKind {
2832    EnumUnderlyingType
2833  };
2834
2835private:
2836  /// The untransformed type.
2837  QualType BaseType;
2838  /// The transformed type if not dependent, otherwise the same as BaseType.
2839  QualType UnderlyingType;
2840
2841  UTTKind UKind;
2842protected:
2843  UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
2844                     QualType CanonicalTy);
2845  friend class ASTContext;
2846public:
2847  bool isSugared() const { return !isDependentType(); }
2848  QualType desugar() const { return UnderlyingType; }
2849
2850  QualType getUnderlyingType() const { return UnderlyingType; }
2851  QualType getBaseType() const { return BaseType; }
2852
2853  UTTKind getUTTKind() const { return UKind; }
2854
2855  static bool classof(const Type *T) {
2856    return T->getTypeClass() == UnaryTransform;
2857  }
2858  static bool classof(const UnaryTransformType *) { return true; }
2859};
2860
2861class TagType : public Type {
2862  /// Stores the TagDecl associated with this type. The decl may point to any
2863  /// TagDecl that declares the entity.
2864  TagDecl * decl;
2865
2866protected:
2867  TagType(TypeClass TC, const TagDecl *D, QualType can);
2868
2869public:
2870  TagDecl *getDecl() const;
2871
2872  /// @brief Determines whether this type is in the process of being
2873  /// defined.
2874  bool isBeingDefined() const;
2875
2876  static bool classof(const Type *T) {
2877    return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast;
2878  }
2879  static bool classof(const TagType *) { return true; }
2880  static bool classof(const RecordType *) { return true; }
2881  static bool classof(const EnumType *) { return true; }
2882};
2883
2884/// RecordType - This is a helper class that allows the use of isa/cast/dyncast
2885/// to detect TagType objects of structs/unions/classes.
2886class RecordType : public TagType {
2887protected:
2888  explicit RecordType(const RecordDecl *D)
2889    : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) { }
2890  explicit RecordType(TypeClass TC, RecordDecl *D)
2891    : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) { }
2892  friend class ASTContext;   // ASTContext creates these.
2893public:
2894
2895  RecordDecl *getDecl() const {
2896    return reinterpret_cast<RecordDecl*>(TagType::getDecl());
2897  }
2898
2899  // FIXME: This predicate is a helper to QualType/Type. It needs to
2900  // recursively check all fields for const-ness. If any field is declared
2901  // const, it needs to return false.
2902  bool hasConstFields() const { return false; }
2903
2904  bool isSugared() const { return false; }
2905  QualType desugar() const { return QualType(this, 0); }
2906
2907  static bool classof(const TagType *T);
2908  static bool classof(const Type *T) {
2909    return isa<TagType>(T) && classof(cast<TagType>(T));
2910  }
2911  static bool classof(const RecordType *) { return true; }
2912};
2913
2914/// EnumType - This is a helper class that allows the use of isa/cast/dyncast
2915/// to detect TagType objects of enums.
2916class EnumType : public TagType {
2917  explicit EnumType(const EnumDecl *D)
2918    : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) { }
2919  friend class ASTContext;   // ASTContext creates these.
2920public:
2921
2922  EnumDecl *getDecl() const {
2923    return reinterpret_cast<EnumDecl*>(TagType::getDecl());
2924  }
2925
2926  bool isSugared() const { return false; }
2927  QualType desugar() const { return QualType(this, 0); }
2928
2929  static bool classof(const TagType *T);
2930  static bool classof(const Type *T) {
2931    return isa<TagType>(T) && classof(cast<TagType>(T));
2932  }
2933  static bool classof(const EnumType *) { return true; }
2934};
2935
2936/// AttributedType - An attributed type is a type to which a type
2937/// attribute has been applied.  The "modified type" is the
2938/// fully-sugared type to which the attributed type was applied;
2939/// generally it is not canonically equivalent to the attributed type.
2940/// The "equivalent type" is the minimally-desugared type which the
2941/// type is canonically equivalent to.
2942///
2943/// For example, in the following attributed type:
2944///     int32_t __attribute__((vector_size(16)))
2945///   - the modified type is the TypedefType for int32_t
2946///   - the equivalent type is VectorType(16, int32_t)
2947///   - the canonical type is VectorType(16, int)
2948class AttributedType : public Type, public llvm::FoldingSetNode {
2949public:
2950  // It is really silly to have yet another attribute-kind enum, but
2951  // clang::attr::Kind doesn't currently cover the pure type attrs.
2952  enum Kind {
2953    // Expression operand.
2954    attr_address_space,
2955    attr_regparm,
2956    attr_vector_size,
2957    attr_neon_vector_type,
2958    attr_neon_polyvector_type,
2959
2960    FirstExprOperandKind = attr_address_space,
2961    LastExprOperandKind = attr_neon_polyvector_type,
2962
2963    // Enumerated operand (string or keyword).
2964    attr_objc_gc,
2965    attr_pcs,
2966
2967    FirstEnumOperandKind = attr_objc_gc,
2968    LastEnumOperandKind = attr_pcs,
2969
2970    // No operand.
2971    attr_noreturn,
2972    attr_cdecl,
2973    attr_fastcall,
2974    attr_stdcall,
2975    attr_thiscall,
2976    attr_pascal
2977  };
2978
2979private:
2980  QualType ModifiedType;
2981  QualType EquivalentType;
2982
2983  friend class ASTContext; // creates these
2984
2985  AttributedType(QualType canon, Kind attrKind,
2986                 QualType modified, QualType equivalent)
2987    : Type(Attributed, canon, canon->isDependentType(),
2988           canon->isVariablyModifiedType(),
2989           canon->containsUnexpandedParameterPack()),
2990      ModifiedType(modified), EquivalentType(equivalent) {
2991    AttributedTypeBits.AttrKind = attrKind;
2992  }
2993
2994public:
2995  Kind getAttrKind() const {
2996    return static_cast<Kind>(AttributedTypeBits.AttrKind);
2997  }
2998
2999  QualType getModifiedType() const { return ModifiedType; }
3000  QualType getEquivalentType() const { return EquivalentType; }
3001
3002  bool isSugared() const { return true; }
3003  QualType desugar() const { return getEquivalentType(); }
3004
3005  void Profile(llvm::FoldingSetNodeID &ID) {
3006    Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
3007  }
3008
3009  static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
3010                      QualType modified, QualType equivalent) {
3011    ID.AddInteger(attrKind);
3012    ID.AddPointer(modified.getAsOpaquePtr());
3013    ID.AddPointer(equivalent.getAsOpaquePtr());
3014  }
3015
3016  static bool classof(const Type *T) {
3017    return T->getTypeClass() == Attributed;
3018  }
3019  static bool classof(const AttributedType *T) { return true; }
3020};
3021
3022class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
3023  // Helper data collector for canonical types.
3024  struct CanonicalTTPTInfo {
3025    unsigned Depth : 15;
3026    unsigned ParameterPack : 1;
3027    unsigned Index : 16;
3028  };
3029
3030  union {
3031    // Info for the canonical type.
3032    CanonicalTTPTInfo CanTTPTInfo;
3033    // Info for the non-canonical type.
3034    TemplateTypeParmDecl *TTPDecl;
3035  };
3036
3037  /// Build a non-canonical type.
3038  TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
3039    : Type(TemplateTypeParm, Canon, /*Dependent=*/true,
3040           /*VariablyModified=*/false,
3041           Canon->containsUnexpandedParameterPack()),
3042      TTPDecl(TTPDecl) { }
3043
3044  /// Build the canonical type.
3045  TemplateTypeParmType(unsigned D, unsigned I, bool PP)
3046    : Type(TemplateTypeParm, QualType(this, 0), /*Dependent=*/true,
3047           /*VariablyModified=*/false, PP) {
3048    CanTTPTInfo.Depth = D;
3049    CanTTPTInfo.Index = I;
3050    CanTTPTInfo.ParameterPack = PP;
3051  }
3052
3053  friend class ASTContext;  // ASTContext creates these
3054
3055  const CanonicalTTPTInfo& getCanTTPTInfo() const {
3056    QualType Can = getCanonicalTypeInternal();
3057    return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
3058  }
3059
3060public:
3061  unsigned getDepth() const { return getCanTTPTInfo().Depth; }
3062  unsigned getIndex() const { return getCanTTPTInfo().Index; }
3063  bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
3064
3065  TemplateTypeParmDecl *getDecl() const {
3066    return isCanonicalUnqualified() ? 0 : TTPDecl;
3067  }
3068
3069  IdentifierInfo *getIdentifier() const;
3070
3071  bool isSugared() const { return false; }
3072  QualType desugar() const { return QualType(this, 0); }
3073
3074  void Profile(llvm::FoldingSetNodeID &ID) {
3075    Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
3076  }
3077
3078  static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
3079                      unsigned Index, bool ParameterPack,
3080                      TemplateTypeParmDecl *TTPDecl) {
3081    ID.AddInteger(Depth);
3082    ID.AddInteger(Index);
3083    ID.AddBoolean(ParameterPack);
3084    ID.AddPointer(TTPDecl);
3085  }
3086
3087  static bool classof(const Type *T) {
3088    return T->getTypeClass() == TemplateTypeParm;
3089  }
3090  static bool classof(const TemplateTypeParmType *T) { return true; }
3091};
3092
3093/// \brief Represents the result of substituting a type for a template
3094/// type parameter.
3095///
3096/// Within an instantiated template, all template type parameters have
3097/// been replaced with these.  They are used solely to record that a
3098/// type was originally written as a template type parameter;
3099/// therefore they are never canonical.
3100class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
3101  // The original type parameter.
3102  const TemplateTypeParmType *Replaced;
3103
3104  SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
3105    : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(),
3106           Canon->isVariablyModifiedType(),
3107           Canon->containsUnexpandedParameterPack()),
3108      Replaced(Param) { }
3109
3110  friend class ASTContext;
3111
3112public:
3113  /// Gets the template parameter that was substituted for.
3114  const TemplateTypeParmType *getReplacedParameter() const {
3115    return Replaced;
3116  }
3117
3118  /// Gets the type that was substituted for the template
3119  /// parameter.
3120  QualType getReplacementType() const {
3121    return getCanonicalTypeInternal();
3122  }
3123
3124  bool isSugared() const { return true; }
3125  QualType desugar() const { return getReplacementType(); }
3126
3127  void Profile(llvm::FoldingSetNodeID &ID) {
3128    Profile(ID, getReplacedParameter(), getReplacementType());
3129  }
3130  static void Profile(llvm::FoldingSetNodeID &ID,
3131                      const TemplateTypeParmType *Replaced,
3132                      QualType Replacement) {
3133    ID.AddPointer(Replaced);
3134    ID.AddPointer(Replacement.getAsOpaquePtr());
3135  }
3136
3137  static bool classof(const Type *T) {
3138    return T->getTypeClass() == SubstTemplateTypeParm;
3139  }
3140  static bool classof(const SubstTemplateTypeParmType *T) { return true; }
3141};
3142
3143/// \brief Represents the result of substituting a set of types for a template
3144/// type parameter pack.
3145///
3146/// When a pack expansion in the source code contains multiple parameter packs
3147/// and those parameter packs correspond to different levels of template
3148/// parameter lists, this type node is used to represent a template type
3149/// parameter pack from an outer level, which has already had its argument pack
3150/// substituted but that still lives within a pack expansion that itself
3151/// could not be instantiated. When actually performing a substitution into
3152/// that pack expansion (e.g., when all template parameters have corresponding
3153/// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
3154/// at the current pack substitution index.
3155class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
3156  /// \brief The original type parameter.
3157  const TemplateTypeParmType *Replaced;
3158
3159  /// \brief A pointer to the set of template arguments that this
3160  /// parameter pack is instantiated with.
3161  const TemplateArgument *Arguments;
3162
3163  /// \brief The number of template arguments in \c Arguments.
3164  unsigned NumArguments;
3165
3166  SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
3167                                QualType Canon,
3168                                const TemplateArgument &ArgPack);
3169
3170  friend class ASTContext;
3171
3172public:
3173  IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
3174
3175  /// Gets the template parameter that was substituted for.
3176  const TemplateTypeParmType *getReplacedParameter() const {
3177    return Replaced;
3178  }
3179
3180  bool isSugared() const { return false; }
3181  QualType desugar() const { return QualType(this, 0); }
3182
3183  TemplateArgument getArgumentPack() const;
3184
3185  void Profile(llvm::FoldingSetNodeID &ID);
3186  static void Profile(llvm::FoldingSetNodeID &ID,
3187                      const TemplateTypeParmType *Replaced,
3188                      const TemplateArgument &ArgPack);
3189
3190  static bool classof(const Type *T) {
3191    return T->getTypeClass() == SubstTemplateTypeParmPack;
3192  }
3193  static bool classof(const SubstTemplateTypeParmPackType *T) { return true; }
3194};
3195
3196/// \brief Represents a C++0x auto type.
3197///
3198/// These types are usually a placeholder for a deduced type. However, within
3199/// templates and before the initializer is attached, there is no deduced type
3200/// and an auto type is type-dependent and canonical.
3201class AutoType : public Type, public llvm::FoldingSetNode {
3202  AutoType(QualType DeducedType)
3203    : Type(Auto, DeducedType.isNull() ? QualType(this, 0) : DeducedType,
3204           /*Dependent=*/DeducedType.isNull(),
3205           /*VariablyModified=*/false, /*ContainsParameterPack=*/false) {
3206    assert((DeducedType.isNull() || !DeducedType->isDependentType()) &&
3207           "deduced a dependent type for auto");
3208  }
3209
3210  friend class ASTContext;  // ASTContext creates these
3211
3212public:
3213  bool isSugared() const { return isDeduced(); }
3214  QualType desugar() const { return getCanonicalTypeInternal(); }
3215
3216  QualType getDeducedType() const {
3217    return isDeduced() ? getCanonicalTypeInternal() : QualType();
3218  }
3219  bool isDeduced() const {
3220    return !isDependentType();
3221  }
3222
3223  void Profile(llvm::FoldingSetNodeID &ID) {
3224    Profile(ID, getDeducedType());
3225  }
3226
3227  static void Profile(llvm::FoldingSetNodeID &ID,
3228                      QualType Deduced) {
3229    ID.AddPointer(Deduced.getAsOpaquePtr());
3230  }
3231
3232  static bool classof(const Type *T) {
3233    return T->getTypeClass() == Auto;
3234  }
3235  static bool classof(const AutoType *T) { return true; }
3236};
3237
3238/// \brief Represents the type of a template specialization as written
3239/// in the source code.
3240///
3241/// Template specialization types represent the syntactic form of a
3242/// template-id that refers to a type, e.g., @c vector<int>. Some
3243/// template specialization types are syntactic sugar, whose canonical
3244/// type will point to some other type node that represents the
3245/// instantiation or class template specialization. For example, a
3246/// class template specialization type of @c vector<int> will refer to
3247/// a tag type for the instantiation
3248/// @c std::vector<int, std::allocator<int>>.
3249///
3250/// Other template specialization types, for which the template name
3251/// is dependent, may be canonical types. These types are always
3252/// dependent.
3253///
3254/// An instance of this type is followed by an array of TemplateArgument*s,
3255/// then, if the template specialization type is for a type alias template,
3256/// a QualType representing the non-canonical aliased type.
3257class TemplateSpecializationType
3258  : public Type, public llvm::FoldingSetNode {
3259  /// \brief The name of the template being specialized.
3260  TemplateName Template;
3261
3262  /// \brief - The number of template arguments named in this class
3263  /// template specialization.
3264  unsigned NumArgs;
3265
3266  TemplateSpecializationType(TemplateName T,
3267                             const TemplateArgument *Args,
3268                             unsigned NumArgs, QualType Canon,
3269                             QualType Aliased);
3270
3271  friend class ASTContext;  // ASTContext creates these
3272
3273public:
3274  /// \brief Determine whether any of the given template arguments are
3275  /// dependent.
3276  static bool anyDependentTemplateArguments(const TemplateArgument *Args,
3277                                            unsigned NumArgs);
3278
3279  static bool anyDependentTemplateArguments(const TemplateArgumentLoc *Args,
3280                                            unsigned NumArgs);
3281
3282  static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &);
3283
3284  /// \brief Print a template argument list, including the '<' and '>'
3285  /// enclosing the template arguments.
3286  static std::string PrintTemplateArgumentList(const TemplateArgument *Args,
3287                                               unsigned NumArgs,
3288                                               const PrintingPolicy &Policy,
3289                                               bool SkipBrackets = false);
3290
3291  static std::string PrintTemplateArgumentList(const TemplateArgumentLoc *Args,
3292                                               unsigned NumArgs,
3293                                               const PrintingPolicy &Policy);
3294
3295  static std::string PrintTemplateArgumentList(const TemplateArgumentListInfo &,
3296                                               const PrintingPolicy &Policy);
3297
3298  /// True if this template specialization type matches a current
3299  /// instantiation in the context in which it is found.
3300  bool isCurrentInstantiation() const {
3301    return isa<InjectedClassNameType>(getCanonicalTypeInternal());
3302  }
3303
3304  /// True if this template specialization type is for a type alias
3305  /// template.
3306  bool isTypeAlias() const;
3307  /// Get the aliased type, if this is a specialization of a type alias
3308  /// template.
3309  QualType getAliasedType() const {
3310    assert(isTypeAlias() && "not a type alias template specialization");
3311    return *reinterpret_cast<const QualType*>(end());
3312  }
3313
3314  typedef const TemplateArgument * iterator;
3315
3316  iterator begin() const { return getArgs(); }
3317  iterator end() const; // defined inline in TemplateBase.h
3318
3319  /// \brief Retrieve the name of the template that we are specializing.
3320  TemplateName getTemplateName() const { return Template; }
3321
3322  /// \brief Retrieve the template arguments.
3323  const TemplateArgument *getArgs() const {
3324    return reinterpret_cast<const TemplateArgument *>(this + 1);
3325  }
3326
3327  /// \brief Retrieve the number of template arguments.
3328  unsigned getNumArgs() const { return NumArgs; }
3329
3330  /// \brief Retrieve a specific template argument as a type.
3331  /// \precondition @c isArgType(Arg)
3332  const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
3333
3334  bool isSugared() const {
3335    return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
3336  }
3337  QualType desugar() const { return getCanonicalTypeInternal(); }
3338
3339  void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
3340    Profile(ID, Template, getArgs(), NumArgs, Ctx);
3341    if (isTypeAlias())
3342      getAliasedType().Profile(ID);
3343  }
3344
3345  static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
3346                      const TemplateArgument *Args,
3347                      unsigned NumArgs,
3348                      const ASTContext &Context);
3349
3350  static bool classof(const Type *T) {
3351    return T->getTypeClass() == TemplateSpecialization;
3352  }
3353  static bool classof(const TemplateSpecializationType *T) { return true; }
3354};
3355
3356/// \brief The injected class name of a C++ class template or class
3357/// template partial specialization.  Used to record that a type was
3358/// spelled with a bare identifier rather than as a template-id; the
3359/// equivalent for non-templated classes is just RecordType.
3360///
3361/// Injected class name types are always dependent.  Template
3362/// instantiation turns these into RecordTypes.
3363///
3364/// Injected class name types are always canonical.  This works
3365/// because it is impossible to compare an injected class name type
3366/// with the corresponding non-injected template type, for the same
3367/// reason that it is impossible to directly compare template
3368/// parameters from different dependent contexts: injected class name
3369/// types can only occur within the scope of a particular templated
3370/// declaration, and within that scope every template specialization
3371/// will canonicalize to the injected class name (when appropriate
3372/// according to the rules of the language).
3373class InjectedClassNameType : public Type {
3374  CXXRecordDecl *Decl;
3375
3376  /// The template specialization which this type represents.
3377  /// For example, in
3378  ///   template <class T> class A { ... };
3379  /// this is A<T>, whereas in
3380  ///   template <class X, class Y> class A<B<X,Y> > { ... };
3381  /// this is A<B<X,Y> >.
3382  ///
3383  /// It is always unqualified, always a template specialization type,
3384  /// and always dependent.
3385  QualType InjectedType;
3386
3387  friend class ASTContext; // ASTContext creates these.
3388  friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
3389                          // currently suitable for AST reading, too much
3390                          // interdependencies.
3391  InjectedClassNameType(CXXRecordDecl *D, QualType TST)
3392    : Type(InjectedClassName, QualType(), /*Dependent=*/true,
3393           /*VariablyModified=*/false,
3394           /*ContainsUnexpandedParameterPack=*/false),
3395      Decl(D), InjectedType(TST) {
3396    assert(isa<TemplateSpecializationType>(TST));
3397    assert(!TST.hasQualifiers());
3398    assert(TST->isDependentType());
3399  }
3400
3401public:
3402  QualType getInjectedSpecializationType() const { return InjectedType; }
3403  const TemplateSpecializationType *getInjectedTST() const {
3404    return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
3405  }
3406
3407  CXXRecordDecl *getDecl() const;
3408
3409  bool isSugared() const { return false; }
3410  QualType desugar() const { return QualType(this, 0); }
3411
3412  static bool classof(const Type *T) {
3413    return T->getTypeClass() == InjectedClassName;
3414  }
3415  static bool classof(const InjectedClassNameType *T) { return true; }
3416};
3417
3418/// \brief The kind of a tag type.
3419enum TagTypeKind {
3420  /// \brief The "struct" keyword.
3421  TTK_Struct,
3422  /// \brief The "union" keyword.
3423  TTK_Union,
3424  /// \brief The "class" keyword.
3425  TTK_Class,
3426  /// \brief The "enum" keyword.
3427  TTK_Enum
3428};
3429
3430/// \brief The elaboration keyword that precedes a qualified type name or
3431/// introduces an elaborated-type-specifier.
3432enum ElaboratedTypeKeyword {
3433  /// \brief The "struct" keyword introduces the elaborated-type-specifier.
3434  ETK_Struct,
3435  /// \brief The "union" keyword introduces the elaborated-type-specifier.
3436  ETK_Union,
3437  /// \brief The "class" keyword introduces the elaborated-type-specifier.
3438  ETK_Class,
3439  /// \brief The "enum" keyword introduces the elaborated-type-specifier.
3440  ETK_Enum,
3441  /// \brief The "typename" keyword precedes the qualified type name, e.g.,
3442  /// \c typename T::type.
3443  ETK_Typename,
3444  /// \brief No keyword precedes the qualified type name.
3445  ETK_None
3446};
3447
3448/// A helper class for Type nodes having an ElaboratedTypeKeyword.
3449/// The keyword in stored in the free bits of the base class.
3450/// Also provides a few static helpers for converting and printing
3451/// elaborated type keyword and tag type kind enumerations.
3452class TypeWithKeyword : public Type {
3453protected:
3454  TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
3455                  QualType Canonical, bool Dependent, bool VariablyModified,
3456                  bool ContainsUnexpandedParameterPack)
3457  : Type(tc, Canonical, Dependent, VariablyModified,
3458         ContainsUnexpandedParameterPack) {
3459    TypeWithKeywordBits.Keyword = Keyword;
3460  }
3461
3462public:
3463  ElaboratedTypeKeyword getKeyword() const {
3464    return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
3465  }
3466
3467  /// getKeywordForTypeSpec - Converts a type specifier (DeclSpec::TST)
3468  /// into an elaborated type keyword.
3469  static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
3470
3471  /// getTagTypeKindForTypeSpec - Converts a type specifier (DeclSpec::TST)
3472  /// into a tag type kind.  It is an error to provide a type specifier
3473  /// which *isn't* a tag kind here.
3474  static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
3475
3476  /// getKeywordForTagDeclKind - Converts a TagTypeKind into an
3477  /// elaborated type keyword.
3478  static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
3479
3480  /// getTagTypeKindForKeyword - Converts an elaborated type keyword into
3481  // a TagTypeKind. It is an error to provide an elaborated type keyword
3482  /// which *isn't* a tag kind here.
3483  static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
3484
3485  static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
3486
3487  static const char *getKeywordName(ElaboratedTypeKeyword Keyword);
3488
3489  static const char *getTagTypeKindName(TagTypeKind Kind) {
3490    return getKeywordName(getKeywordForTagTypeKind(Kind));
3491  }
3492
3493  class CannotCastToThisType {};
3494  static CannotCastToThisType classof(const Type *);
3495};
3496
3497/// \brief Represents a type that was referred to using an elaborated type
3498/// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
3499/// or both.
3500///
3501/// This type is used to keep track of a type name as written in the
3502/// source code, including tag keywords and any nested-name-specifiers.
3503/// The type itself is always "sugar", used to express what was written
3504/// in the source code but containing no additional semantic information.
3505class ElaboratedType : public TypeWithKeyword, public llvm::FoldingSetNode {
3506
3507  /// \brief The nested name specifier containing the qualifier.
3508  NestedNameSpecifier *NNS;
3509
3510  /// \brief The type that this qualified name refers to.
3511  QualType NamedType;
3512
3513  ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
3514                 QualType NamedType, QualType CanonType)
3515    : TypeWithKeyword(Keyword, Elaborated, CanonType,
3516                      NamedType->isDependentType(),
3517                      NamedType->isVariablyModifiedType(),
3518                      NamedType->containsUnexpandedParameterPack()),
3519      NNS(NNS), NamedType(NamedType) {
3520    assert(!(Keyword == ETK_None && NNS == 0) &&
3521           "ElaboratedType cannot have elaborated type keyword "
3522           "and name qualifier both null.");
3523  }
3524
3525  friend class ASTContext;  // ASTContext creates these
3526
3527public:
3528  ~ElaboratedType();
3529
3530  /// \brief Retrieve the qualification on this type.
3531  NestedNameSpecifier *getQualifier() const { return NNS; }
3532
3533  /// \brief Retrieve the type named by the qualified-id.
3534  QualType getNamedType() const { return NamedType; }
3535
3536  /// \brief Remove a single level of sugar.
3537  QualType desugar() const { return getNamedType(); }
3538
3539  /// \brief Returns whether this type directly provides sugar.
3540  bool isSugared() const { return true; }
3541
3542  void Profile(llvm::FoldingSetNodeID &ID) {
3543    Profile(ID, getKeyword(), NNS, NamedType);
3544  }
3545
3546  static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
3547                      NestedNameSpecifier *NNS, QualType NamedType) {
3548    ID.AddInteger(Keyword);
3549    ID.AddPointer(NNS);
3550    NamedType.Profile(ID);
3551  }
3552
3553  static bool classof(const Type *T) {
3554    return T->getTypeClass() == Elaborated;
3555  }
3556  static bool classof(const ElaboratedType *T) { return true; }
3557};
3558
3559/// \brief Represents a qualified type name for which the type name is
3560/// dependent.
3561///
3562/// DependentNameType represents a class of dependent types that involve a
3563/// dependent nested-name-specifier (e.g., "T::") followed by a (dependent)
3564/// name of a type. The DependentNameType may start with a "typename" (for a
3565/// typename-specifier), "class", "struct", "union", or "enum" (for a
3566/// dependent elaborated-type-specifier), or nothing (in contexts where we
3567/// know that we must be referring to a type, e.g., in a base class specifier).
3568class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
3569
3570  /// \brief The nested name specifier containing the qualifier.
3571  NestedNameSpecifier *NNS;
3572
3573  /// \brief The type that this typename specifier refers to.
3574  const IdentifierInfo *Name;
3575
3576  DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
3577                    const IdentifierInfo *Name, QualType CanonType)
3578    : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true,
3579                      /*VariablyModified=*/false,
3580                      NNS->containsUnexpandedParameterPack()),
3581      NNS(NNS), Name(Name) {
3582    assert(NNS->isDependent() &&
3583           "DependentNameType requires a dependent nested-name-specifier");
3584  }
3585
3586  friend class ASTContext;  // ASTContext creates these
3587
3588public:
3589  /// \brief Retrieve the qualification on this type.
3590  NestedNameSpecifier *getQualifier() const { return NNS; }
3591
3592  /// \brief Retrieve the type named by the typename specifier as an
3593  /// identifier.
3594  ///
3595  /// This routine will return a non-NULL identifier pointer when the
3596  /// form of the original typename was terminated by an identifier,
3597  /// e.g., "typename T::type".
3598  const IdentifierInfo *getIdentifier() const {
3599    return Name;
3600  }
3601
3602  bool isSugared() const { return false; }
3603  QualType desugar() const { return QualType(this, 0); }
3604
3605  void Profile(llvm::FoldingSetNodeID &ID) {
3606    Profile(ID, getKeyword(), NNS, Name);
3607  }
3608
3609  static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
3610                      NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
3611    ID.AddInteger(Keyword);
3612    ID.AddPointer(NNS);
3613    ID.AddPointer(Name);
3614  }
3615
3616  static bool classof(const Type *T) {
3617    return T->getTypeClass() == DependentName;
3618  }
3619  static bool classof(const DependentNameType *T) { return true; }
3620};
3621
3622/// DependentTemplateSpecializationType - Represents a template
3623/// specialization type whose template cannot be resolved, e.g.
3624///   A<T>::template B<T>
3625class DependentTemplateSpecializationType :
3626  public TypeWithKeyword, public llvm::FoldingSetNode {
3627
3628  /// \brief The nested name specifier containing the qualifier.
3629  NestedNameSpecifier *NNS;
3630
3631  /// \brief The identifier of the template.
3632  const IdentifierInfo *Name;
3633
3634  /// \brief - The number of template arguments named in this class
3635  /// template specialization.
3636  unsigned NumArgs;
3637
3638  const TemplateArgument *getArgBuffer() const {
3639    return reinterpret_cast<const TemplateArgument*>(this+1);
3640  }
3641  TemplateArgument *getArgBuffer() {
3642    return reinterpret_cast<TemplateArgument*>(this+1);
3643  }
3644
3645  DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
3646                                      NestedNameSpecifier *NNS,
3647                                      const IdentifierInfo *Name,
3648                                      unsigned NumArgs,
3649                                      const TemplateArgument *Args,
3650                                      QualType Canon);
3651
3652  friend class ASTContext;  // ASTContext creates these
3653
3654public:
3655  NestedNameSpecifier *getQualifier() const { return NNS; }
3656  const IdentifierInfo *getIdentifier() const { return Name; }
3657
3658  /// \brief Retrieve the template arguments.
3659  const TemplateArgument *getArgs() const {
3660    return getArgBuffer();
3661  }
3662
3663  /// \brief Retrieve the number of template arguments.
3664  unsigned getNumArgs() const { return NumArgs; }
3665
3666  const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
3667
3668  typedef const TemplateArgument * iterator;
3669  iterator begin() const { return getArgs(); }
3670  iterator end() const; // inline in TemplateBase.h
3671
3672  bool isSugared() const { return false; }
3673  QualType desugar() const { return QualType(this, 0); }
3674
3675  void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
3676    Profile(ID, Context, getKeyword(), NNS, Name, NumArgs, getArgs());
3677  }
3678
3679  static void Profile(llvm::FoldingSetNodeID &ID,
3680                      const ASTContext &Context,
3681                      ElaboratedTypeKeyword Keyword,
3682                      NestedNameSpecifier *Qualifier,
3683                      const IdentifierInfo *Name,
3684                      unsigned NumArgs,
3685                      const TemplateArgument *Args);
3686
3687  static bool classof(const Type *T) {
3688    return T->getTypeClass() == DependentTemplateSpecialization;
3689  }
3690  static bool classof(const DependentTemplateSpecializationType *T) {
3691    return true;
3692  }
3693};
3694
3695/// \brief Represents a pack expansion of types.
3696///
3697/// Pack expansions are part of C++0x variadic templates. A pack
3698/// expansion contains a pattern, which itself contains one or more
3699/// "unexpanded" parameter packs. When instantiated, a pack expansion
3700/// produces a series of types, each instantiated from the pattern of
3701/// the expansion, where the Ith instantiation of the pattern uses the
3702/// Ith arguments bound to each of the unexpanded parameter packs. The
3703/// pack expansion is considered to "expand" these unexpanded
3704/// parameter packs.
3705///
3706/// \code
3707/// template<typename ...Types> struct tuple;
3708///
3709/// template<typename ...Types>
3710/// struct tuple_of_references {
3711///   typedef tuple<Types&...> type;
3712/// };
3713/// \endcode
3714///
3715/// Here, the pack expansion \c Types&... is represented via a
3716/// PackExpansionType whose pattern is Types&.
3717class PackExpansionType : public Type, public llvm::FoldingSetNode {
3718  /// \brief The pattern of the pack expansion.
3719  QualType Pattern;
3720
3721  /// \brief The number of expansions that this pack expansion will
3722  /// generate when substituted (+1), or indicates that
3723  ///
3724  /// This field will only have a non-zero value when some of the parameter
3725  /// packs that occur within the pattern have been substituted but others have
3726  /// not.
3727  unsigned NumExpansions;
3728
3729  PackExpansionType(QualType Pattern, QualType Canon,
3730                    llvm::Optional<unsigned> NumExpansions)
3731    : Type(PackExpansion, Canon, /*Dependent=*/true,
3732           /*VariableModified=*/Pattern->isVariablyModifiedType(),
3733           /*ContainsUnexpandedParameterPack=*/false),
3734      Pattern(Pattern),
3735      NumExpansions(NumExpansions? *NumExpansions + 1: 0) { }
3736
3737  friend class ASTContext;  // ASTContext creates these
3738
3739public:
3740  /// \brief Retrieve the pattern of this pack expansion, which is the
3741  /// type that will be repeatedly instantiated when instantiating the
3742  /// pack expansion itself.
3743  QualType getPattern() const { return Pattern; }
3744
3745  /// \brief Retrieve the number of expansions that this pack expansion will
3746  /// generate, if known.
3747  llvm::Optional<unsigned> getNumExpansions() const {
3748    if (NumExpansions)
3749      return NumExpansions - 1;
3750
3751    return llvm::Optional<unsigned>();
3752  }
3753
3754  bool isSugared() const { return false; }
3755  QualType desugar() const { return QualType(this, 0); }
3756
3757  void Profile(llvm::FoldingSetNodeID &ID) {
3758    Profile(ID, getPattern(), getNumExpansions());
3759  }
3760
3761  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
3762                      llvm::Optional<unsigned> NumExpansions) {
3763    ID.AddPointer(Pattern.getAsOpaquePtr());
3764    ID.AddBoolean(NumExpansions);
3765    if (NumExpansions)
3766      ID.AddInteger(*NumExpansions);
3767  }
3768
3769  static bool classof(const Type *T) {
3770    return T->getTypeClass() == PackExpansion;
3771  }
3772  static bool classof(const PackExpansionType *T) {
3773    return true;
3774  }
3775};
3776
3777/// ObjCObjectType - Represents a class type in Objective C.
3778/// Every Objective C type is a combination of a base type and a
3779/// list of protocols.
3780///
3781/// Given the following declarations:
3782///   @class C;
3783///   @protocol P;
3784///
3785/// 'C' is an ObjCInterfaceType C.  It is sugar for an ObjCObjectType
3786/// with base C and no protocols.
3787///
3788/// 'C<P>' is an ObjCObjectType with base C and protocol list [P].
3789///
3790/// 'id' is a TypedefType which is sugar for an ObjCPointerType whose
3791/// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
3792/// and no protocols.
3793///
3794/// 'id<P>' is an ObjCPointerType whose pointee is an ObjCObjecType
3795/// with base BuiltinType::ObjCIdType and protocol list [P].  Eventually
3796/// this should get its own sugar class to better represent the source.
3797class ObjCObjectType : public Type {
3798  // ObjCObjectType.NumProtocols - the number of protocols stored
3799  // after the ObjCObjectPointerType node.
3800  //
3801  // These protocols are those written directly on the type.  If
3802  // protocol qualifiers ever become additive, the iterators will need
3803  // to get kindof complicated.
3804  //
3805  // In the canonical object type, these are sorted alphabetically
3806  // and uniqued.
3807
3808  /// Either a BuiltinType or an InterfaceType or sugar for either.
3809  QualType BaseType;
3810
3811  ObjCProtocolDecl * const *getProtocolStorage() const {
3812    return const_cast<ObjCObjectType*>(this)->getProtocolStorage();
3813  }
3814
3815  ObjCProtocolDecl **getProtocolStorage();
3816
3817protected:
3818  ObjCObjectType(QualType Canonical, QualType Base,
3819                 ObjCProtocolDecl * const *Protocols, unsigned NumProtocols);
3820
3821  enum Nonce_ObjCInterface { Nonce_ObjCInterface };
3822  ObjCObjectType(enum Nonce_ObjCInterface)
3823        : Type(ObjCInterface, QualType(), false, false, false),
3824      BaseType(QualType(this_(), 0)) {
3825    ObjCObjectTypeBits.NumProtocols = 0;
3826  }
3827
3828public:
3829  /// getBaseType - Gets the base type of this object type.  This is
3830  /// always (possibly sugar for) one of:
3831  ///  - the 'id' builtin type (as opposed to the 'id' type visible to the
3832  ///    user, which is a typedef for an ObjCPointerType)
3833  ///  - the 'Class' builtin type (same caveat)
3834  ///  - an ObjCObjectType (currently always an ObjCInterfaceType)
3835  QualType getBaseType() const { return BaseType; }
3836
3837  bool isObjCId() const {
3838    return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
3839  }
3840  bool isObjCClass() const {
3841    return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
3842  }
3843  bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
3844  bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
3845  bool isObjCUnqualifiedIdOrClass() const {
3846    if (!qual_empty()) return false;
3847    if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
3848      return T->getKind() == BuiltinType::ObjCId ||
3849             T->getKind() == BuiltinType::ObjCClass;
3850    return false;
3851  }
3852  bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
3853  bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
3854
3855  /// Gets the interface declaration for this object type, if the base type
3856  /// really is an interface.
3857  ObjCInterfaceDecl *getInterface() const;
3858
3859  typedef ObjCProtocolDecl * const *qual_iterator;
3860
3861  qual_iterator qual_begin() const { return getProtocolStorage(); }
3862  qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
3863
3864  bool qual_empty() const { return getNumProtocols() == 0; }
3865
3866  /// getNumProtocols - Return the number of qualifying protocols in this
3867  /// interface type, or 0 if there are none.
3868  unsigned getNumProtocols() const { return ObjCObjectTypeBits.NumProtocols; }
3869
3870  /// \brief Fetch a protocol by index.
3871  ObjCProtocolDecl *getProtocol(unsigned I) const {
3872    assert(I < getNumProtocols() && "Out-of-range protocol access");
3873    return qual_begin()[I];
3874  }
3875
3876  bool isSugared() const { return false; }
3877  QualType desugar() const { return QualType(this, 0); }
3878
3879  static bool classof(const Type *T) {
3880    return T->getTypeClass() == ObjCObject ||
3881           T->getTypeClass() == ObjCInterface;
3882  }
3883  static bool classof(const ObjCObjectType *) { return true; }
3884};
3885
3886/// ObjCObjectTypeImpl - A class providing a concrete implementation
3887/// of ObjCObjectType, so as to not increase the footprint of
3888/// ObjCInterfaceType.  Code outside of ASTContext and the core type
3889/// system should not reference this type.
3890class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
3891  friend class ASTContext;
3892
3893  // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
3894  // will need to be modified.
3895
3896  ObjCObjectTypeImpl(QualType Canonical, QualType Base,
3897                     ObjCProtocolDecl * const *Protocols,
3898                     unsigned NumProtocols)
3899    : ObjCObjectType(Canonical, Base, Protocols, NumProtocols) {}
3900
3901public:
3902  void Profile(llvm::FoldingSetNodeID &ID);
3903  static void Profile(llvm::FoldingSetNodeID &ID,
3904                      QualType Base,
3905                      ObjCProtocolDecl *const *protocols,
3906                      unsigned NumProtocols);
3907};
3908
3909inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorage() {
3910  return reinterpret_cast<ObjCProtocolDecl**>(
3911            static_cast<ObjCObjectTypeImpl*>(this) + 1);
3912}
3913
3914/// ObjCInterfaceType - Interfaces are the core concept in Objective-C for
3915/// object oriented design.  They basically correspond to C++ classes.  There
3916/// are two kinds of interface types, normal interfaces like "NSString" and
3917/// qualified interfaces, which are qualified with a protocol list like
3918/// "NSString<NSCopyable, NSAmazing>".
3919///
3920/// ObjCInterfaceType guarantees the following properties when considered
3921/// as a subtype of its superclass, ObjCObjectType:
3922///   - There are no protocol qualifiers.  To reinforce this, code which
3923///     tries to invoke the protocol methods via an ObjCInterfaceType will
3924///     fail to compile.
3925///   - It is its own base type.  That is, if T is an ObjCInterfaceType*,
3926///     T->getBaseType() == QualType(T, 0).
3927class ObjCInterfaceType : public ObjCObjectType {
3928  ObjCInterfaceDecl *Decl;
3929
3930  ObjCInterfaceType(const ObjCInterfaceDecl *D)
3931    : ObjCObjectType(Nonce_ObjCInterface),
3932      Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
3933  friend class ASTContext;  // ASTContext creates these.
3934
3935public:
3936  /// getDecl - Get the declaration of this interface.
3937  ObjCInterfaceDecl *getDecl() const { return Decl; }
3938
3939  bool isSugared() const { return false; }
3940  QualType desugar() const { return QualType(this, 0); }
3941
3942  static bool classof(const Type *T) {
3943    return T->getTypeClass() == ObjCInterface;
3944  }
3945  static bool classof(const ObjCInterfaceType *) { return true; }
3946
3947  // Nonsense to "hide" certain members of ObjCObjectType within this
3948  // class.  People asking for protocols on an ObjCInterfaceType are
3949  // not going to get what they want: ObjCInterfaceTypes are
3950  // guaranteed to have no protocols.
3951  enum {
3952    qual_iterator,
3953    qual_begin,
3954    qual_end,
3955    getNumProtocols,
3956    getProtocol
3957  };
3958};
3959
3960inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
3961  if (const ObjCInterfaceType *T =
3962        getBaseType()->getAs<ObjCInterfaceType>())
3963    return T->getDecl();
3964  return 0;
3965}
3966
3967/// ObjCObjectPointerType - Used to represent a pointer to an
3968/// Objective C object.  These are constructed from pointer
3969/// declarators when the pointee type is an ObjCObjectType (or sugar
3970/// for one).  In addition, the 'id' and 'Class' types are typedefs
3971/// for these, and the protocol-qualified types 'id<P>' and 'Class<P>'
3972/// are translated into these.
3973///
3974/// Pointers to pointers to Objective C objects are still PointerTypes;
3975/// only the first level of pointer gets it own type implementation.
3976class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
3977  QualType PointeeType;
3978
3979  ObjCObjectPointerType(QualType Canonical, QualType Pointee)
3980    : Type(ObjCObjectPointer, Canonical, false, false, false),
3981      PointeeType(Pointee) {}
3982  friend class ASTContext;  // ASTContext creates these.
3983
3984public:
3985  /// getPointeeType - Gets the type pointed to by this ObjC pointer.
3986  /// The result will always be an ObjCObjectType or sugar thereof.
3987  QualType getPointeeType() const { return PointeeType; }
3988
3989  /// getObjCObjectType - Gets the type pointed to by this ObjC
3990  /// pointer.  This method always returns non-null.
3991  ///
3992  /// This method is equivalent to getPointeeType() except that
3993  /// it discards any typedefs (or other sugar) between this
3994  /// type and the "outermost" object type.  So for:
3995  ///   @class A; @protocol P; @protocol Q;
3996  ///   typedef A<P> AP;
3997  ///   typedef A A1;
3998  ///   typedef A1<P> A1P;
3999  ///   typedef A1P<Q> A1PQ;
4000  /// For 'A*', getObjectType() will return 'A'.
4001  /// For 'A<P>*', getObjectType() will return 'A<P>'.
4002  /// For 'AP*', getObjectType() will return 'A<P>'.
4003  /// For 'A1*', getObjectType() will return 'A'.
4004  /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
4005  /// For 'A1P*', getObjectType() will return 'A1<P>'.
4006  /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
4007  ///   adding protocols to a protocol-qualified base discards the
4008  ///   old qualifiers (for now).  But if it didn't, getObjectType()
4009  ///   would return 'A1P<Q>' (and we'd have to make iterating over
4010  ///   qualifiers more complicated).
4011  const ObjCObjectType *getObjectType() const {
4012    return PointeeType->castAs<ObjCObjectType>();
4013  }
4014
4015  /// getInterfaceType - If this pointer points to an Objective C
4016  /// @interface type, gets the type for that interface.  Any protocol
4017  /// qualifiers on the interface are ignored.
4018  ///
4019  /// \return null if the base type for this pointer is 'id' or 'Class'
4020  const ObjCInterfaceType *getInterfaceType() const {
4021    return getObjectType()->getBaseType()->getAs<ObjCInterfaceType>();
4022  }
4023
4024  /// getInterfaceDecl - If this pointer points to an Objective @interface
4025  /// type, gets the declaration for that interface.
4026  ///
4027  /// \return null if the base type for this pointer is 'id' or 'Class'
4028  ObjCInterfaceDecl *getInterfaceDecl() const {
4029    return getObjectType()->getInterface();
4030  }
4031
4032  /// isObjCIdType - True if this is equivalent to the 'id' type, i.e. if
4033  /// its object type is the primitive 'id' type with no protocols.
4034  bool isObjCIdType() const {
4035    return getObjectType()->isObjCUnqualifiedId();
4036  }
4037
4038  /// isObjCClassType - True if this is equivalent to the 'Class' type,
4039  /// i.e. if its object tive is the primitive 'Class' type with no protocols.
4040  bool isObjCClassType() const {
4041    return getObjectType()->isObjCUnqualifiedClass();
4042  }
4043
4044  /// isObjCQualifiedIdType - True if this is equivalent to 'id<P>' for some
4045  /// non-empty set of protocols.
4046  bool isObjCQualifiedIdType() const {
4047    return getObjectType()->isObjCQualifiedId();
4048  }
4049
4050  /// isObjCQualifiedClassType - True if this is equivalent to 'Class<P>' for
4051  /// some non-empty set of protocols.
4052  bool isObjCQualifiedClassType() const {
4053    return getObjectType()->isObjCQualifiedClass();
4054  }
4055
4056  /// An iterator over the qualifiers on the object type.  Provided
4057  /// for convenience.  This will always iterate over the full set of
4058  /// protocols on a type, not just those provided directly.
4059  typedef ObjCObjectType::qual_iterator qual_iterator;
4060
4061  qual_iterator qual_begin() const {
4062    return getObjectType()->qual_begin();
4063  }
4064  qual_iterator qual_end() const {
4065    return getObjectType()->qual_end();
4066  }
4067  bool qual_empty() const { return getObjectType()->qual_empty(); }
4068
4069  /// getNumProtocols - Return the number of qualifying protocols on
4070  /// the object type.
4071  unsigned getNumProtocols() const {
4072    return getObjectType()->getNumProtocols();
4073  }
4074
4075  /// \brief Retrieve a qualifying protocol by index on the object
4076  /// type.
4077  ObjCProtocolDecl *getProtocol(unsigned I) const {
4078    return getObjectType()->getProtocol(I);
4079  }
4080
4081  bool isSugared() const { return false; }
4082  QualType desugar() const { return QualType(this, 0); }
4083
4084  void Profile(llvm::FoldingSetNodeID &ID) {
4085    Profile(ID, getPointeeType());
4086  }
4087  static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
4088    ID.AddPointer(T.getAsOpaquePtr());
4089  }
4090  static bool classof(const Type *T) {
4091    return T->getTypeClass() == ObjCObjectPointer;
4092  }
4093  static bool classof(const ObjCObjectPointerType *) { return true; }
4094};
4095
4096/// A qualifier set is used to build a set of qualifiers.
4097class QualifierCollector : public Qualifiers {
4098public:
4099  QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
4100
4101  /// Collect any qualifiers on the given type and return an
4102  /// unqualified type.  The qualifiers are assumed to be consistent
4103  /// with those already in the type.
4104  const Type *strip(QualType type) {
4105    addFastQualifiers(type.getLocalFastQualifiers());
4106    if (!type.hasLocalNonFastQualifiers())
4107      return type.getTypePtrUnsafe();
4108
4109    const ExtQuals *extQuals = type.getExtQualsUnsafe();
4110    addConsistentQualifiers(extQuals->getQualifiers());
4111    return extQuals->getBaseType();
4112  }
4113
4114  /// Apply the collected qualifiers to the given type.
4115  QualType apply(const ASTContext &Context, QualType QT) const;
4116
4117  /// Apply the collected qualifiers to the given type.
4118  QualType apply(const ASTContext &Context, const Type* T) const;
4119};
4120
4121
4122// Inline function definitions.
4123
4124inline const Type *QualType::getTypePtr() const {
4125  return getCommonPtr()->BaseType;
4126}
4127
4128inline const Type *QualType::getTypePtrOrNull() const {
4129  return (isNull() ? 0 : getCommonPtr()->BaseType);
4130}
4131
4132inline SplitQualType QualType::split() const {
4133  if (!hasLocalNonFastQualifiers())
4134    return SplitQualType(getTypePtrUnsafe(),
4135                         Qualifiers::fromFastMask(getLocalFastQualifiers()));
4136
4137  const ExtQuals *eq = getExtQualsUnsafe();
4138  Qualifiers qs = eq->getQualifiers();
4139  qs.addFastQualifiers(getLocalFastQualifiers());
4140  return SplitQualType(eq->getBaseType(), qs);
4141}
4142
4143inline Qualifiers QualType::getLocalQualifiers() const {
4144  Qualifiers Quals;
4145  if (hasLocalNonFastQualifiers())
4146    Quals = getExtQualsUnsafe()->getQualifiers();
4147  Quals.addFastQualifiers(getLocalFastQualifiers());
4148  return Quals;
4149}
4150
4151inline Qualifiers QualType::getQualifiers() const {
4152  Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
4153  quals.addFastQualifiers(getLocalFastQualifiers());
4154  return quals;
4155}
4156
4157inline unsigned QualType::getCVRQualifiers() const {
4158  unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
4159  cvr |= getLocalCVRQualifiers();
4160  return cvr;
4161}
4162
4163inline QualType QualType::getCanonicalType() const {
4164  QualType canon = getCommonPtr()->CanonicalType;
4165  return canon.withFastQualifiers(getLocalFastQualifiers());
4166}
4167
4168inline bool QualType::isCanonical() const {
4169  return getTypePtr()->isCanonicalUnqualified();
4170}
4171
4172inline bool QualType::isCanonicalAsParam() const {
4173  if (!isCanonical()) return false;
4174  if (hasLocalQualifiers()) return false;
4175
4176  const Type *T = getTypePtr();
4177  if (T->isVariablyModifiedType() && T->hasSizedVLAType())
4178    return false;
4179
4180  return !isa<FunctionType>(T) && !isa<ArrayType>(T);
4181}
4182
4183inline bool QualType::isConstQualified() const {
4184  return isLocalConstQualified() ||
4185         getCommonPtr()->CanonicalType.isLocalConstQualified();
4186}
4187
4188inline bool QualType::isRestrictQualified() const {
4189  return isLocalRestrictQualified() ||
4190         getCommonPtr()->CanonicalType.isLocalRestrictQualified();
4191}
4192
4193
4194inline bool QualType::isVolatileQualified() const {
4195  return isLocalVolatileQualified() ||
4196         getCommonPtr()->CanonicalType.isLocalVolatileQualified();
4197}
4198
4199inline bool QualType::hasQualifiers() const {
4200  return hasLocalQualifiers() ||
4201         getCommonPtr()->CanonicalType.hasLocalQualifiers();
4202}
4203
4204inline QualType QualType::getUnqualifiedType() const {
4205  if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
4206    return QualType(getTypePtr(), 0);
4207
4208  return QualType(getSplitUnqualifiedTypeImpl(*this).first, 0);
4209}
4210
4211inline SplitQualType QualType::getSplitUnqualifiedType() const {
4212  if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
4213    return split();
4214
4215  return getSplitUnqualifiedTypeImpl(*this);
4216}
4217
4218inline void QualType::removeLocalConst() {
4219  removeLocalFastQualifiers(Qualifiers::Const);
4220}
4221
4222inline void QualType::removeLocalRestrict() {
4223  removeLocalFastQualifiers(Qualifiers::Restrict);
4224}
4225
4226inline void QualType::removeLocalVolatile() {
4227  removeLocalFastQualifiers(Qualifiers::Volatile);
4228}
4229
4230inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
4231  assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits");
4232  assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask);
4233
4234  // Fast path: we don't need to touch the slow qualifiers.
4235  removeLocalFastQualifiers(Mask);
4236}
4237
4238/// getAddressSpace - Return the address space of this type.
4239inline unsigned QualType::getAddressSpace() const {
4240  return getQualifiers().getAddressSpace();
4241}
4242
4243/// getObjCGCAttr - Return the gc attribute of this type.
4244inline Qualifiers::GC QualType::getObjCGCAttr() const {
4245  return getQualifiers().getObjCGCAttr();
4246}
4247
4248inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
4249  if (const PointerType *PT = t.getAs<PointerType>()) {
4250    if (const FunctionType *FT = PT->getPointeeType()->getAs<FunctionType>())
4251      return FT->getExtInfo();
4252  } else if (const FunctionType *FT = t.getAs<FunctionType>())
4253    return FT->getExtInfo();
4254
4255  return FunctionType::ExtInfo();
4256}
4257
4258inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
4259  return getFunctionExtInfo(*t);
4260}
4261
4262/// isMoreQualifiedThan - Determine whether this type is more
4263/// qualified than the Other type. For example, "const volatile int"
4264/// is more qualified than "const int", "volatile int", and
4265/// "int". However, it is not more qualified than "const volatile
4266/// int".
4267inline bool QualType::isMoreQualifiedThan(QualType other) const {
4268  Qualifiers myQuals = getQualifiers();
4269  Qualifiers otherQuals = other.getQualifiers();
4270  return (myQuals != otherQuals && myQuals.compatiblyIncludes(otherQuals));
4271}
4272
4273/// isAtLeastAsQualifiedAs - Determine whether this type is at last
4274/// as qualified as the Other type. For example, "const volatile
4275/// int" is at least as qualified as "const int", "volatile int",
4276/// "int", and "const volatile int".
4277inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
4278  return getQualifiers().compatiblyIncludes(other.getQualifiers());
4279}
4280
4281/// getNonReferenceType - If Type is a reference type (e.g., const
4282/// int&), returns the type that the reference refers to ("const
4283/// int"). Otherwise, returns the type itself. This routine is used
4284/// throughout Sema to implement C++ 5p6:
4285///
4286///   If an expression initially has the type "reference to T" (8.3.2,
4287///   8.5.3), the type is adjusted to "T" prior to any further
4288///   analysis, the expression designates the object or function
4289///   denoted by the reference, and the expression is an lvalue.
4290inline QualType QualType::getNonReferenceType() const {
4291  if (const ReferenceType *RefType = (*this)->getAs<ReferenceType>())
4292    return RefType->getPointeeType();
4293  else
4294    return *this;
4295}
4296
4297/// \brief Tests whether the type is categorized as a fundamental type.
4298///
4299/// \returns True for types specified in C++0x [basic.fundamental].
4300inline bool Type::isFundamentalType() const {
4301  return isVoidType() ||
4302         // FIXME: It's really annoying that we don't have an
4303         // 'isArithmeticType()' which agrees with the standard definition.
4304         (isArithmeticType() && !isEnumeralType());
4305}
4306
4307/// \brief Tests whether the type is categorized as a compound type.
4308///
4309/// \returns True for types specified in C++0x [basic.compound].
4310inline bool Type::isCompoundType() const {
4311  // C++0x [basic.compound]p1:
4312  //   Compound types can be constructed in the following ways:
4313  //    -- arrays of objects of a given type [...];
4314  return isArrayType() ||
4315  //    -- functions, which have parameters of given types [...];
4316         isFunctionType() ||
4317  //    -- pointers to void or objects or functions [...];
4318         isPointerType() ||
4319  //    -- references to objects or functions of a given type. [...]
4320         isReferenceType() ||
4321  //    -- classes containing a sequence of objects of various types, [...];
4322         isRecordType() ||
4323  //    -- unions, which ar classes capable of containing objects of different types at different times;
4324         isUnionType() ||
4325  //    -- enumerations, which comprise a set of named constant values. [...];
4326         isEnumeralType() ||
4327  //    -- pointers to non-static class members, [...].
4328         isMemberPointerType();
4329}
4330
4331inline bool Type::isFunctionType() const {
4332  return isa<FunctionType>(CanonicalType);
4333}
4334inline bool Type::isPointerType() const {
4335  return isa<PointerType>(CanonicalType);
4336}
4337inline bool Type::isAnyPointerType() const {
4338  return isPointerType() || isObjCObjectPointerType();
4339}
4340inline bool Type::isBlockPointerType() const {
4341  return isa<BlockPointerType>(CanonicalType);
4342}
4343inline bool Type::isReferenceType() const {
4344  return isa<ReferenceType>(CanonicalType);
4345}
4346inline bool Type::isLValueReferenceType() const {
4347  return isa<LValueReferenceType>(CanonicalType);
4348}
4349inline bool Type::isRValueReferenceType() const {
4350  return isa<RValueReferenceType>(CanonicalType);
4351}
4352inline bool Type::isFunctionPointerType() const {
4353  if (const PointerType *T = getAs<PointerType>())
4354    return T->getPointeeType()->isFunctionType();
4355  else
4356    return false;
4357}
4358inline bool Type::isMemberPointerType() const {
4359  return isa<MemberPointerType>(CanonicalType);
4360}
4361inline bool Type::isMemberFunctionPointerType() const {
4362  if (const MemberPointerType* T = getAs<MemberPointerType>())
4363    return T->isMemberFunctionPointer();
4364  else
4365    return false;
4366}
4367inline bool Type::isMemberDataPointerType() const {
4368  if (const MemberPointerType* T = getAs<MemberPointerType>())
4369    return T->isMemberDataPointer();
4370  else
4371    return false;
4372}
4373inline bool Type::isArrayType() const {
4374  return isa<ArrayType>(CanonicalType);
4375}
4376inline bool Type::isConstantArrayType() const {
4377  return isa<ConstantArrayType>(CanonicalType);
4378}
4379inline bool Type::isIncompleteArrayType() const {
4380  return isa<IncompleteArrayType>(CanonicalType);
4381}
4382inline bool Type::isVariableArrayType() const {
4383  return isa<VariableArrayType>(CanonicalType);
4384}
4385inline bool Type::isDependentSizedArrayType() const {
4386  return isa<DependentSizedArrayType>(CanonicalType);
4387}
4388inline bool Type::isBuiltinType() const {
4389  return isa<BuiltinType>(CanonicalType);
4390}
4391inline bool Type::isRecordType() const {
4392  return isa<RecordType>(CanonicalType);
4393}
4394inline bool Type::isEnumeralType() const {
4395  return isa<EnumType>(CanonicalType);
4396}
4397inline bool Type::isAnyComplexType() const {
4398  return isa<ComplexType>(CanonicalType);
4399}
4400inline bool Type::isVectorType() const {
4401  return isa<VectorType>(CanonicalType);
4402}
4403inline bool Type::isExtVectorType() const {
4404  return isa<ExtVectorType>(CanonicalType);
4405}
4406inline bool Type::isObjCObjectPointerType() const {
4407  return isa<ObjCObjectPointerType>(CanonicalType);
4408}
4409inline bool Type::isObjCObjectType() const {
4410  return isa<ObjCObjectType>(CanonicalType);
4411}
4412inline bool Type::isObjCObjectOrInterfaceType() const {
4413  return isa<ObjCInterfaceType>(CanonicalType) ||
4414    isa<ObjCObjectType>(CanonicalType);
4415}
4416
4417inline bool Type::isObjCQualifiedIdType() const {
4418  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4419    return OPT->isObjCQualifiedIdType();
4420  return false;
4421}
4422inline bool Type::isObjCQualifiedClassType() const {
4423  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4424    return OPT->isObjCQualifiedClassType();
4425  return false;
4426}
4427inline bool Type::isObjCIdType() const {
4428  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4429    return OPT->isObjCIdType();
4430  return false;
4431}
4432inline bool Type::isObjCClassType() const {
4433  if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
4434    return OPT->isObjCClassType();
4435  return false;
4436}
4437inline bool Type::isObjCSelType() const {
4438  if (const PointerType *OPT = getAs<PointerType>())
4439    return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
4440  return false;
4441}
4442inline bool Type::isObjCBuiltinType() const {
4443  return isObjCIdType() || isObjCClassType() || isObjCSelType();
4444}
4445inline bool Type::isTemplateTypeParmType() const {
4446  return isa<TemplateTypeParmType>(CanonicalType);
4447}
4448
4449inline bool Type::isSpecificBuiltinType(unsigned K) const {
4450  if (const BuiltinType *BT = getAs<BuiltinType>())
4451    if (BT->getKind() == (BuiltinType::Kind) K)
4452      return true;
4453  return false;
4454}
4455
4456inline bool Type::isPlaceholderType() const {
4457  if (const BuiltinType *BT = getAs<BuiltinType>())
4458    return BT->isPlaceholderType();
4459  return false;
4460}
4461
4462inline bool Type::isSpecificPlaceholderType(unsigned K) const {
4463  if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
4464    return (BT->getKind() == (BuiltinType::Kind) K);
4465  return false;
4466}
4467
4468/// \brief Determines whether this is a type for which one can define
4469/// an overloaded operator.
4470inline bool Type::isOverloadableType() const {
4471  return isDependentType() || isRecordType() || isEnumeralType();
4472}
4473
4474inline bool Type::hasPointerRepresentation() const {
4475  return (isPointerType() || isReferenceType() || isBlockPointerType() ||
4476          isObjCObjectPointerType() || isNullPtrType());
4477}
4478
4479inline bool Type::hasObjCPointerRepresentation() const {
4480  return isObjCObjectPointerType();
4481}
4482
4483inline const Type *Type::getBaseElementTypeUnsafe() const {
4484  const Type *type = this;
4485  while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
4486    type = arrayType->getElementType().getTypePtr();
4487  return type;
4488}
4489
4490/// Insertion operator for diagnostics.  This allows sending QualType's into a
4491/// diagnostic with <<.
4492inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
4493                                           QualType T) {
4494  DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
4495                  Diagnostic::ak_qualtype);
4496  return DB;
4497}
4498
4499/// Insertion operator for partial diagnostics.  This allows sending QualType's
4500/// into a diagnostic with <<.
4501inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
4502                                           QualType T) {
4503  PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
4504                  Diagnostic::ak_qualtype);
4505  return PD;
4506}
4507
4508// Helper class template that is used by Type::getAs to ensure that one does
4509// not try to look through a qualified type to get to an array type.
4510template<typename T,
4511         bool isArrayType = (llvm::is_same<T, ArrayType>::value ||
4512                             llvm::is_base_of<ArrayType, T>::value)>
4513struct ArrayType_cannot_be_used_with_getAs { };
4514
4515template<typename T>
4516struct ArrayType_cannot_be_used_with_getAs<T, true>;
4517
4518/// Member-template getAs<specific type>'.
4519template <typename T> const T *Type::getAs() const {
4520  ArrayType_cannot_be_used_with_getAs<T> at;
4521  (void)at;
4522
4523  // If this is directly a T type, return it.
4524  if (const T *Ty = dyn_cast<T>(this))
4525    return Ty;
4526
4527  // If the canonical form of this type isn't the right kind, reject it.
4528  if (!isa<T>(CanonicalType))
4529    return 0;
4530
4531  // If this is a typedef for the type, strip the typedef off without
4532  // losing all typedef information.
4533  return cast<T>(getUnqualifiedDesugaredType());
4534}
4535
4536inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
4537  // If this is directly an array type, return it.
4538  if (const ArrayType *arr = dyn_cast<ArrayType>(this))
4539    return arr;
4540
4541  // If the canonical form of this type isn't the right kind, reject it.
4542  if (!isa<ArrayType>(CanonicalType))
4543    return 0;
4544
4545  // If this is a typedef for the type, strip the typedef off without
4546  // losing all typedef information.
4547  return cast<ArrayType>(getUnqualifiedDesugaredType());
4548}
4549
4550template <typename T> const T *Type::castAs() const {
4551  ArrayType_cannot_be_used_with_getAs<T> at;
4552  (void) at;
4553
4554  assert(isa<T>(CanonicalType));
4555  if (const T *ty = dyn_cast<T>(this)) return ty;
4556  return cast<T>(getUnqualifiedDesugaredType());
4557}
4558
4559inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
4560  assert(isa<ArrayType>(CanonicalType));
4561  if (const ArrayType *arr = dyn_cast<ArrayType>(this)) return arr;
4562  return cast<ArrayType>(getUnqualifiedDesugaredType());
4563}
4564
4565}  // end namespace clang
4566
4567#endif
4568