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