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