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