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