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