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