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