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