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