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