clang  14.0.0git
Type.h
Go to the documentation of this file.
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 
22 #include "clang/AST/TemplateName.h"
24 #include "clang/Basic/AttrKinds.h"
25 #include "clang/Basic/Diagnostic.h"
27 #include "clang/Basic/LLVM.h"
28 #include "clang/Basic/Linkage.h"
31 #include "clang/Basic/Specifiers.h"
32 #include "clang/Basic/Visibility.h"
33 #include "llvm/ADT/APInt.h"
34 #include "llvm/ADT/APSInt.h"
35 #include "llvm/ADT/ArrayRef.h"
36 #include "llvm/ADT/FoldingSet.h"
37 #include "llvm/ADT/None.h"
38 #include "llvm/ADT/Optional.h"
39 #include "llvm/ADT/PointerIntPair.h"
40 #include "llvm/ADT/PointerUnion.h"
41 #include "llvm/ADT/StringRef.h"
42 #include "llvm/ADT/Twine.h"
43 #include "llvm/ADT/iterator_range.h"
44 #include "llvm/Support/Casting.h"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/PointerLikeTypeTraits.h"
48 #include "llvm/Support/TrailingObjects.h"
49 #include "llvm/Support/type_traits.h"
50 #include <cassert>
51 #include <cstddef>
52 #include <cstdint>
53 #include <cstring>
54 #include <string>
55 #include <type_traits>
56 #include <utility>
57 
58 namespace clang {
59 
60 class ExtQuals;
61 class QualType;
62 class ConceptDecl;
63 class TagDecl;
64 class TemplateParameterList;
65 class Type;
66 
67 enum {
70 };
71 
72 namespace serialization {
73  template <class T> class AbstractTypeReader;
74  template <class T> class AbstractTypeWriter;
75 }
76 
77 } // namespace clang
78 
79 namespace llvm {
80 
81  template <typename T>
82  struct PointerLikeTypeTraits;
83  template<>
85  static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
86 
88  return static_cast< ::clang::Type*>(P);
89  }
90 
91  static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
92  };
93 
94  template<>
96  static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
97 
98  static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
99  return static_cast< ::clang::ExtQuals*>(P);
100  }
101 
102  static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
103  };
104 
105 } // namespace llvm
106 
107 namespace clang {
108 
109 class ASTContext;
110 template <typename> class CanQual;
111 class CXXRecordDecl;
112 class DeclContext;
113 class EnumDecl;
114 class Expr;
115 class ExtQualsTypeCommonBase;
116 class FunctionDecl;
117 class IdentifierInfo;
118 class NamedDecl;
119 class ObjCInterfaceDecl;
120 class ObjCProtocolDecl;
121 class ObjCTypeParamDecl;
122 struct PrintingPolicy;
123 class RecordDecl;
124 class Stmt;
125 class TagDecl;
126 class TemplateArgument;
127 class TemplateArgumentListInfo;
128 class TemplateArgumentLoc;
129 class TemplateTypeParmDecl;
130 class TypedefNameDecl;
131 class UnresolvedUsingTypenameDecl;
132 
133 using CanQualType = CanQual<Type>;
134 
135 // Provide forward declarations for all of the *Type classes.
136 #define TYPE(Class, Base) class Class##Type;
137 #include "clang/AST/TypeNodes.inc"
138 
139 /// The collection of all-type qualifiers we support.
140 /// Clang supports five independent qualifiers:
141 /// * C99: const, volatile, and restrict
142 /// * MS: __unaligned
143 /// * Embedded C (TR18037): address spaces
144 /// * Objective C: the GC attributes (none, weak, or strong)
145 class Qualifiers {
146 public:
147  enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
148  Const = 0x1,
149  Restrict = 0x2,
150  Volatile = 0x4,
152  };
153 
154  enum GC {
155  GCNone = 0,
158  };
159 
161  /// There is no lifetime qualification on this type.
163 
164  /// This object can be modified without requiring retains or
165  /// releases.
167 
168  /// Assigning into this object requires the old value to be
169  /// released and the new value to be retained. The timing of the
170  /// release of the old value is inexact: it may be moved to
171  /// immediately after the last known point where the value is
172  /// live.
174 
175  /// Reading or writing from this object requires a barrier call.
177 
178  /// Assigning into this object requires a lifetime extension.
180  };
181 
182  enum {
183  /// The maximum supported address space number.
184  /// 23 bits should be enough for anyone.
185  MaxAddressSpace = 0x7fffffu,
186 
187  /// The width of the "fast" qualifier mask.
189 
190  /// The fast qualifier mask.
191  FastMask = (1 << FastWidth) - 1
192  };
193 
194  /// Returns the common set of qualifiers while removing them from
195  /// the given sets.
197  // If both are only CVR-qualified, bit operations are sufficient.
198  if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
199  Qualifiers Q;
200  Q.Mask = L.Mask & R.Mask;
201  L.Mask &= ~Q.Mask;
202  R.Mask &= ~Q.Mask;
203  return Q;
204  }
205 
206  Qualifiers Q;
207  unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
208  Q.addCVRQualifiers(CommonCRV);
209  L.removeCVRQualifiers(CommonCRV);
210  R.removeCVRQualifiers(CommonCRV);
211 
212  if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
214  L.removeObjCGCAttr();
215  R.removeObjCGCAttr();
216  }
217 
218  if (L.getObjCLifetime() == R.getObjCLifetime()) {
220  L.removeObjCLifetime();
221  R.removeObjCLifetime();
222  }
223 
224  if (L.getAddressSpace() == R.getAddressSpace()) {
226  L.removeAddressSpace();
227  R.removeAddressSpace();
228  }
229  return Q;
230  }
231 
232  static Qualifiers fromFastMask(unsigned Mask) {
233  Qualifiers Qs;
234  Qs.addFastQualifiers(Mask);
235  return Qs;
236  }
237 
238  static Qualifiers fromCVRMask(unsigned CVR) {
239  Qualifiers Qs;
240  Qs.addCVRQualifiers(CVR);
241  return Qs;
242  }
243 
244  static Qualifiers fromCVRUMask(unsigned CVRU) {
245  Qualifiers Qs;
246  Qs.addCVRUQualifiers(CVRU);
247  return Qs;
248  }
249 
250  // Deserialize qualifiers from an opaque representation.
251  static Qualifiers fromOpaqueValue(unsigned opaque) {
252  Qualifiers Qs;
253  Qs.Mask = opaque;
254  return Qs;
255  }
256 
257  // Serialize these qualifiers into an opaque representation.
258  unsigned getAsOpaqueValue() const {
259  return Mask;
260  }
261 
262  bool hasConst() const { return Mask & Const; }
263  bool hasOnlyConst() const { return Mask == Const; }
264  void removeConst() { Mask &= ~Const; }
265  void addConst() { Mask |= Const; }
266 
267  bool hasVolatile() const { return Mask & Volatile; }
268  bool hasOnlyVolatile() const { return Mask == Volatile; }
269  void removeVolatile() { Mask &= ~Volatile; }
270  void addVolatile() { Mask |= Volatile; }
271 
272  bool hasRestrict() const { return Mask & Restrict; }
273  bool hasOnlyRestrict() const { return Mask == Restrict; }
274  void removeRestrict() { Mask &= ~Restrict; }
275  void addRestrict() { Mask |= Restrict; }
276 
277  bool hasCVRQualifiers() const { return getCVRQualifiers(); }
278  unsigned getCVRQualifiers() const { return Mask & CVRMask; }
279  unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); }
280 
281  void setCVRQualifiers(unsigned mask) {
282  assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
283  Mask = (Mask & ~CVRMask) | mask;
284  }
285  void removeCVRQualifiers(unsigned mask) {
286  assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
287  Mask &= ~mask;
288  }
291  }
292  void addCVRQualifiers(unsigned mask) {
293  assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits");
294  Mask |= mask;
295  }
296  void addCVRUQualifiers(unsigned mask) {
297  assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits");
298  Mask |= mask;
299  }
300 
301  bool hasUnaligned() const { return Mask & UMask; }
302  void setUnaligned(bool flag) {
303  Mask = (Mask & ~UMask) | (flag ? UMask : 0);
304  }
305  void removeUnaligned() { Mask &= ~UMask; }
306  void addUnaligned() { Mask |= UMask; }
307 
308  bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
309  GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
311  Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
312  }
315  assert(type);
317  }
319  Qualifiers qs = *this;
320  qs.removeObjCGCAttr();
321  return qs;
322  }
324  Qualifiers qs = *this;
325  qs.removeObjCLifetime();
326  return qs;
327  }
329  Qualifiers qs = *this;
330  qs.removeAddressSpace();
331  return qs;
332  }
333 
334  bool hasObjCLifetime() const { return Mask & LifetimeMask; }
336  return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
337  }
339  Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
340  }
343  assert(type);
344  assert(!hasObjCLifetime());
345  Mask |= (type << LifetimeShift);
346  }
347 
348  /// True if the lifetime is neither None or ExplicitNone.
350  ObjCLifetime lifetime = getObjCLifetime();
351  return (lifetime > OCL_ExplicitNone);
352  }
353 
354  /// True if the lifetime is either strong or weak.
356  ObjCLifetime lifetime = getObjCLifetime();
357  return (lifetime == OCL_Strong || lifetime == OCL_Weak);
358  }
359 
360  bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
362  return static_cast<LangAS>(Mask >> AddressSpaceShift);
363  }
366  }
367  /// Get the address space attribute value to be printed by diagnostics.
369  auto Addr = getAddressSpace();
370  // This function is not supposed to be used with language specific
371  // address spaces. If that happens, the diagnostic message should consider
372  // printing the QualType instead of the address space value.
373  assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace());
374  if (Addr != LangAS::Default)
375  return toTargetAddressSpace(Addr);
376  // TODO: The diagnostic messages where Addr may be 0 should be fixed
377  // since it cannot differentiate the situation where 0 denotes the default
378  // address space or user specified __attribute__((address_space(0))).
379  return 0;
380  }
381  void setAddressSpace(LangAS space) {
382  assert((unsigned)space <= MaxAddressSpace);
383  Mask = (Mask & ~AddressSpaceMask)
384  | (((uint32_t) space) << AddressSpaceShift);
385  }
387  void addAddressSpace(LangAS space) {
388  assert(space != LangAS::Default);
389  setAddressSpace(space);
390  }
391 
392  // Fast qualifiers are those that can be allocated directly
393  // on a QualType object.
394  bool hasFastQualifiers() const { return getFastQualifiers(); }
395  unsigned getFastQualifiers() const { return Mask & FastMask; }
396  void setFastQualifiers(unsigned mask) {
397  assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
398  Mask = (Mask & ~FastMask) | mask;
399  }
400  void removeFastQualifiers(unsigned mask) {
401  assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
402  Mask &= ~mask;
403  }
406  }
407  void addFastQualifiers(unsigned mask) {
408  assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits");
409  Mask |= mask;
410  }
411 
412  /// Return true if the set contains any qualifiers which require an ExtQuals
413  /// node to be allocated.
414  bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
416  Qualifiers Quals = *this;
417  Quals.setFastQualifiers(0);
418  return Quals;
419  }
420 
421  /// Return true if the set contains any qualifiers.
422  bool hasQualifiers() const { return Mask; }
423  bool empty() const { return !Mask; }
424 
425  /// Add the qualifiers from the given set to this set.
427  // If the other set doesn't have any non-boolean qualifiers, just
428  // bit-or it in.
429  if (!(Q.Mask & ~CVRMask))
430  Mask |= Q.Mask;
431  else {
432  Mask |= (Q.Mask & CVRMask);
433  if (Q.hasAddressSpace())
435  if (Q.hasObjCGCAttr())
437  if (Q.hasObjCLifetime())
439  }
440  }
441 
442  /// Remove the qualifiers from the given set from this set.
444  // If the other set doesn't have any non-boolean qualifiers, just
445  // bit-and the inverse in.
446  if (!(Q.Mask & ~CVRMask))
447  Mask &= ~Q.Mask;
448  else {
449  Mask &= ~(Q.Mask & CVRMask);
450  if (getObjCGCAttr() == Q.getObjCGCAttr())
452  if (getObjCLifetime() == Q.getObjCLifetime())
454  if (getAddressSpace() == Q.getAddressSpace())
456  }
457  }
458 
459  /// Add the qualifiers from the given set to this set, given that
460  /// they don't conflict.
462  assert(getAddressSpace() == qs.getAddressSpace() ||
463  !hasAddressSpace() || !qs.hasAddressSpace());
464  assert(getObjCGCAttr() == qs.getObjCGCAttr() ||
465  !hasObjCGCAttr() || !qs.hasObjCGCAttr());
466  assert(getObjCLifetime() == qs.getObjCLifetime() ||
467  !hasObjCLifetime() || !qs.hasObjCLifetime());
468  Mask |= qs.Mask;
469  }
470 
471  /// Returns true if address space A is equal to or a superset of B.
472  /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
473  /// overlapping address spaces.
474  /// CL1.1 or CL1.2:
475  /// every address space is a superset of itself.
476  /// CL2.0 adds:
477  /// __generic is a superset of any address space except for __constant.
479  // Address spaces must match exactly.
480  return A == B ||
481  // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
482  // for __constant can be used as __generic.
484  // We also define global_device and global_host address spaces,
485  // to distinguish global pointers allocated on host from pointers
486  // allocated on device, which are a subset of __global.
490  B == LangAS::sycl_global_host)) ||
491  // Consider pointer size address spaces to be equivalent to default.
492  ((isPtrSizeAddressSpace(A) || A == LangAS::Default) &&
493  (isPtrSizeAddressSpace(B) || B == LangAS::Default)) ||
494  // Default is a superset of SYCL address spaces.
495  (A == LangAS::Default &&
498  B == LangAS::sycl_global_host)) ||
499  // In HIP device compilation, any cuda address space is allowed
500  // to implicitly cast into the default address space.
501  (A == LangAS::Default &&
503  B == LangAS::cuda_shared));
504  }
505 
506  /// Returns true if the address space in these qualifiers is equal to or
507  /// a superset of the address space in the argument qualifiers.
510  }
511 
512  /// Determines if these qualifiers compatibly include another set.
513  /// Generally this answers the question of whether an object with the other
514  /// qualifiers can be safely used as an object with these qualifiers.
515  bool compatiblyIncludes(Qualifiers other) const {
516  return isAddressSpaceSupersetOf(other) &&
517  // ObjC GC qualifiers can match, be added, or be removed, but can't
518  // be changed.
519  (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
520  !other.hasObjCGCAttr()) &&
521  // ObjC lifetime qualifiers must match exactly.
522  getObjCLifetime() == other.getObjCLifetime() &&
523  // CVR qualifiers may subset.
524  (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
525  // U qualifier may superset.
526  (!other.hasUnaligned() || hasUnaligned());
527  }
528 
529  /// Determines if these qualifiers compatibly include another set of
530  /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
531  ///
532  /// One set of Objective-C lifetime qualifiers compatibly includes the other
533  /// if the lifetime qualifiers match, or if both are non-__weak and the
534  /// including set also contains the 'const' qualifier, or both are non-__weak
535  /// and one is None (which can only happen in non-ARC modes).
537  if (getObjCLifetime() == other.getObjCLifetime())
538  return true;
539 
540  if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
541  return false;
542 
543  if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
544  return true;
545 
546  return hasConst();
547  }
548 
549  /// Determine whether this set of qualifiers is a strict superset of
550  /// another set of qualifiers, not considering qualifier compatibility.
551  bool isStrictSupersetOf(Qualifiers Other) const;
552 
553  bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
554  bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
555 
556  explicit operator bool() const { return hasQualifiers(); }
557 
559  addQualifiers(R);
560  return *this;
561  }
562 
563  // Union two qualifier sets. If an enumerated qualifier appears
564  // in both sets, use the one from the right.
566  L += R;
567  return L;
568  }
569 
571  removeQualifiers(R);
572  return *this;
573  }
574 
575  /// Compute the difference between two qualifier sets.
577  L -= R;
578  return L;
579  }
580 
581  std::string getAsString() const;
582  std::string getAsString(const PrintingPolicy &Policy) const;
583 
585 
586  bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
587  void print(raw_ostream &OS, const PrintingPolicy &Policy,
588  bool appendSpaceIfNonEmpty = false) const;
589 
590  void Profile(llvm::FoldingSetNodeID &ID) const {
591  ID.AddInteger(Mask);
592  }
593 
594 private:
595  // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
596  // |C R V|U|GCAttr|Lifetime|AddressSpace|
597  uint32_t Mask = 0;
598 
599  static const uint32_t UMask = 0x8;
600  static const uint32_t UShift = 3;
601  static const uint32_t GCAttrMask = 0x30;
602  static const uint32_t GCAttrShift = 4;
603  static const uint32_t LifetimeMask = 0x1C0;
604  static const uint32_t LifetimeShift = 6;
605  static const uint32_t AddressSpaceMask =
606  ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
607  static const uint32_t AddressSpaceShift = 9;
608 };
609 
610 /// A std::pair-like structure for storing a qualified type split
611 /// into its local qualifiers and its locally-unqualified type.
613  /// The locally-unqualified type.
614  const Type *Ty = nullptr;
615 
616  /// The local qualifiers.
618 
619  SplitQualType() = default;
620  SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
621 
622  SplitQualType getSingleStepDesugaredType() const; // end of this file
623 
624  // Make std::tie work.
625  std::pair<const Type *,Qualifiers> asPair() const {
626  return std::pair<const Type *, Qualifiers>(Ty, Quals);
627  }
628 
630  return a.Ty == b.Ty && a.Quals == b.Quals;
631  }
633  return a.Ty != b.Ty || a.Quals != b.Quals;
634  }
635 };
636 
637 /// The kind of type we are substituting Objective-C type arguments into.
638 ///
639 /// The kind of substitution affects the replacement of type parameters when
640 /// no concrete type information is provided, e.g., when dealing with an
641 /// unspecialized type.
643  /// An ordinary type.
644  Ordinary,
645 
646  /// The result type of a method or function.
647  Result,
648 
649  /// The parameter type of a method or function.
650  Parameter,
651 
652  /// The type of a property.
653  Property,
654 
655  /// The superclass of a type.
656  Superclass,
657 };
658 
659 /// A (possibly-)qualified type.
660 ///
661 /// For efficiency, we don't store CV-qualified types as nodes on their
662 /// own: instead each reference to a type stores the qualifiers. This
663 /// greatly reduces the number of nodes we need to allocate for types (for
664 /// example we only need one for 'int', 'const int', 'volatile int',
665 /// 'const volatile int', etc).
666 ///
667 /// As an added efficiency bonus, instead of making this a pair, we
668 /// just store the two bits we care about in the low bits of the
669 /// pointer. To handle the packing/unpacking, we make QualType be a
670 /// simple wrapper class that acts like a smart pointer. A third bit
671 /// indicates whether there are extended qualifiers present, in which
672 /// case the pointer points to a special structure.
673 class QualType {
674  friend class QualifierCollector;
675 
676  // Thankfully, these are efficiently composable.
677  llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
679 
680  const ExtQuals *getExtQualsUnsafe() const {
681  return Value.getPointer().get<const ExtQuals*>();
682  }
683 
684  const Type *getTypePtrUnsafe() const {
685  return Value.getPointer().get<const Type*>();
686  }
687 
688  const ExtQualsTypeCommonBase *getCommonPtr() const {
689  assert(!isNull() && "Cannot retrieve a NULL type pointer");
690  auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
691  CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
692  return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
693  }
694 
695 public:
696  QualType() = default;
697  QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
698  QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
699 
700  unsigned getLocalFastQualifiers() const { return Value.getInt(); }
701  void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
702 
703  /// Retrieves a pointer to the underlying (unqualified) type.
704  ///
705  /// This function requires that the type not be NULL. If the type might be
706  /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
707  const Type *getTypePtr() const;
708 
709  const Type *getTypePtrOrNull() const;
710 
711  /// Retrieves a pointer to the name of the base type.
712  const IdentifierInfo *getBaseTypeIdentifier() const;
713 
714  /// Divides a QualType into its unqualified type and a set of local
715  /// qualifiers.
716  SplitQualType split() const;
717 
718  void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
719 
720  static QualType getFromOpaquePtr(const void *Ptr) {
721  QualType T;
722  T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
723  return T;
724  }
725 
726  const Type &operator*() const {
727  return *getTypePtr();
728  }
729 
730  const Type *operator->() const {
731  return getTypePtr();
732  }
733 
734  bool isCanonical() const;
735  bool isCanonicalAsParam() const;
736 
737  /// Return true if this QualType doesn't point to a type yet.
738  bool isNull() const {
739  return Value.getPointer().isNull();
740  }
741 
742  /// Determine whether this particular QualType instance has the
743  /// "const" qualifier set, without looking through typedefs that may have
744  /// added "const" at a different level.
745  bool isLocalConstQualified() const {
747  }
748 
749  /// Determine whether this type is const-qualified.
750  bool isConstQualified() const;
751 
752  /// Determine whether this particular QualType instance has the
753  /// "restrict" qualifier set, without looking through typedefs that may have
754  /// added "restrict" at a different level.
757  }
758 
759  /// Determine whether this type is restrict-qualified.
760  bool isRestrictQualified() const;
761 
762  /// Determine whether this particular QualType instance has the
763  /// "volatile" qualifier set, without looking through typedefs that may have
764  /// added "volatile" at a different level.
767  }
768 
769  /// Determine whether this type is volatile-qualified.
770  bool isVolatileQualified() const;
771 
772  /// Determine whether this particular QualType instance has any
773  /// qualifiers, without looking through any typedefs that might add
774  /// qualifiers at a different level.
775  bool hasLocalQualifiers() const {
777  }
778 
779  /// Determine whether this type has any qualifiers.
780  bool hasQualifiers() const;
781 
782  /// Determine whether this particular QualType instance has any
783  /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
784  /// instance.
786  return Value.getPointer().is<const ExtQuals*>();
787  }
788 
789  /// Retrieve the set of qualifiers local to this particular QualType
790  /// instance, not including any qualifiers acquired through typedefs or
791  /// other sugar.
793 
794  /// Retrieve the set of qualifiers applied to this type.
795  Qualifiers getQualifiers() const;
796 
797  /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
798  /// local to this particular QualType instance, not including any qualifiers
799  /// acquired through typedefs or other sugar.
800  unsigned getLocalCVRQualifiers() const {
801  return getLocalFastQualifiers();
802  }
803 
804  /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
805  /// applied to this type.
806  unsigned getCVRQualifiers() const;
807 
808  bool isConstant(const ASTContext& Ctx) const {
809  return QualType::isConstant(*this, Ctx);
810  }
811 
812  /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
813  bool isPODType(const ASTContext &Context) const;
814 
815  /// Return true if this is a POD type according to the rules of the C++98
816  /// standard, regardless of the current compilation's language.
817  bool isCXX98PODType(const ASTContext &Context) const;
818 
819  /// Return true if this is a POD type according to the more relaxed rules
820  /// of the C++11 standard, regardless of the current compilation's language.
821  /// (C++0x [basic.types]p9). Note that, unlike
822  /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account.
823  bool isCXX11PODType(const ASTContext &Context) const;
824 
825  /// Return true if this is a trivial type per (C++0x [basic.types]p9)
826  bool isTrivialType(const ASTContext &Context) const;
827 
828  /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
829  bool isTriviallyCopyableType(const ASTContext &Context) const;
830 
831 
832  /// Returns true if it is a class and it might be dynamic.
833  bool mayBeDynamicClass() const;
834 
835  /// Returns true if it is not a class or if the class might not be dynamic.
836  bool mayBeNotDynamicClass() const;
837 
838  // Don't promise in the API that anything besides 'const' can be
839  // easily added.
840 
841  /// Add the `const` type qualifier to this QualType.
842  void addConst() {
844  }
845  QualType withConst() const {
847  }
848 
849  /// Add the `volatile` type qualifier to this QualType.
850  void addVolatile() {
852  }
855  }
856 
857  /// Add the `restrict` qualifier to this QualType.
858  void addRestrict() {
860  }
863  }
864 
865  QualType withCVRQualifiers(unsigned CVR) const {
866  return withFastQualifiers(CVR);
867  }
868 
869  void addFastQualifiers(unsigned TQs) {
870  assert(!(TQs & ~Qualifiers::FastMask)
871  && "non-fast qualifier bits set in mask!");
872  Value.setInt(Value.getInt() | TQs);
873  }
874 
875  void removeLocalConst();
876  void removeLocalVolatile();
877  void removeLocalRestrict();
878  void removeLocalCVRQualifiers(unsigned Mask);
879 
880  void removeLocalFastQualifiers() { Value.setInt(0); }
881  void removeLocalFastQualifiers(unsigned Mask) {
882  assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers");
883  Value.setInt(Value.getInt() & ~Mask);
884  }
885 
886  // Creates a type with the given qualifiers in addition to any
887  // qualifiers already on this type.
888  QualType withFastQualifiers(unsigned TQs) const {
889  QualType T = *this;
890  T.addFastQualifiers(TQs);
891  return T;
892  }
893 
894  // Creates a type with exactly the given fast qualifiers, removing
895  // any existing fast qualifiers.
898  }
899 
900  // Removes fast qualifiers, but leaves any extended qualifiers in place.
902  QualType T = *this;
904  return T;
905  }
906 
907  QualType getCanonicalType() const;
908 
909  /// Return this type with all of the instance-specific qualifiers
910  /// removed, but without removing any qualifiers that may have been applied
911  /// through typedefs.
913 
914  /// Retrieve the unqualified variant of the given type,
915  /// removing as little sugar as possible.
916  ///
917  /// This routine looks through various kinds of sugar to find the
918  /// least-desugared type that is unqualified. For example, given:
919  ///
920  /// \code
921  /// typedef int Integer;
922  /// typedef const Integer CInteger;
923  /// typedef CInteger DifferenceType;
924  /// \endcode
925  ///
926  /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
927  /// desugar until we hit the type \c Integer, which has no qualifiers on it.
928  ///
929  /// The resulting type might still be qualified if it's sugar for an array
930  /// type. To strip qualifiers even from within a sugared array type, use
931  /// ASTContext::getUnqualifiedArrayType.
932  inline QualType getUnqualifiedType() const;
933 
934  /// Retrieve the unqualified variant of the given type, removing as little
935  /// sugar as possible.
936  ///
937  /// Like getUnqualifiedType(), but also returns the set of
938  /// qualifiers that were built up.
939  ///
940  /// The resulting type might still be qualified if it's sugar for an array
941  /// type. To strip qualifiers even from within a sugared array type, use
942  /// ASTContext::getUnqualifiedArrayType.
943  inline SplitQualType getSplitUnqualifiedType() const;
944 
945  /// Determine whether this type is more qualified than the other
946  /// given type, requiring exact equality for non-CVR qualifiers.
947  bool isMoreQualifiedThan(QualType Other) const;
948 
949  /// Determine whether this type is at least as qualified as the other
950  /// given type, requiring exact equality for non-CVR qualifiers.
951  bool isAtLeastAsQualifiedAs(QualType Other) const;
952 
954 
955  /// Determine the type of a (typically non-lvalue) expression with the
956  /// specified result type.
957  ///
958  /// This routine should be used for expressions for which the return type is
959  /// explicitly specified (e.g., in a cast or call) and isn't necessarily
960  /// an lvalue. It removes a top-level reference (since there are no
961  /// expressions of reference type) and deletes top-level cvr-qualifiers
962  /// from non-class types (in C++) or all types (in C).
963  QualType getNonLValueExprType(const ASTContext &Context) const;
964 
965  /// Remove an outer pack expansion type (if any) from this type. Used as part
966  /// of converting the type of a declaration to the type of an expression that
967  /// references that expression. It's meaningless for an expression to have a
968  /// pack expansion type.
970 
971  /// Return the specified type with any "sugar" removed from
972  /// the type. This takes off typedefs, typeof's etc. If the outer level of
973  /// the type is already concrete, it returns it unmodified. This is similar
974  /// to getting the canonical type, but it doesn't remove *all* typedefs. For
975  /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
976  /// concrete.
977  ///
978  /// Qualifiers are left in place.
979  QualType getDesugaredType(const ASTContext &Context) const {
980  return getDesugaredType(*this, Context);
981  }
982 
984  return getSplitDesugaredType(*this);
985  }
986 
987  /// Return the specified type with one level of "sugar" removed from
988  /// the type.
989  ///
990  /// This routine takes off the first typedef, typeof, etc. If the outer level
991  /// of the type is already concrete, it returns it unmodified.
993  return getSingleStepDesugaredTypeImpl(*this, Context);
994  }
995 
996  /// Returns the specified type after dropping any
997  /// outer-level parentheses.
999  if (isa<ParenType>(*this))
1000  return QualType::IgnoreParens(*this);
1001  return *this;
1002  }
1003 
1004  /// Indicate whether the specified types and qualifiers are identical.
1005  friend bool operator==(const QualType &LHS, const QualType &RHS) {
1006  return LHS.Value == RHS.Value;
1007  }
1008  friend bool operator!=(const QualType &LHS, const QualType &RHS) {
1009  return LHS.Value != RHS.Value;
1010  }
1011  friend bool operator<(const QualType &LHS, const QualType &RHS) {
1012  return LHS.Value < RHS.Value;
1013  }
1014 
1016  const PrintingPolicy &Policy) {
1017  return getAsString(split.Ty, split.Quals, Policy);
1018  }
1019  static std::string getAsString(const Type *ty, Qualifiers qs,
1020  const PrintingPolicy &Policy);
1021 
1022  std::string getAsString() const;
1023  std::string getAsString(const PrintingPolicy &Policy) const;
1024 
1025  void print(raw_ostream &OS, const PrintingPolicy &Policy,
1026  const Twine &PlaceHolder = Twine(),
1027  unsigned Indentation = 0) const;
1028 
1029  static void print(SplitQualType split, raw_ostream &OS,
1030  const PrintingPolicy &policy, const Twine &PlaceHolder,
1031  unsigned Indentation = 0) {
1032  return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
1033  }
1034 
1035  static void print(const Type *ty, Qualifiers qs,
1036  raw_ostream &OS, const PrintingPolicy &policy,
1037  const Twine &PlaceHolder,
1038  unsigned Indentation = 0);
1039 
1040  void getAsStringInternal(std::string &Str,
1041  const PrintingPolicy &Policy) const;
1042 
1044  const PrintingPolicy &policy) {
1045  return getAsStringInternal(split.Ty, split.Quals, out, policy);
1046  }
1047 
1048  static void getAsStringInternal(const Type *ty, Qualifiers qs,
1049  std::string &out,
1050  const PrintingPolicy &policy);
1051 
1053  const QualType &T;
1054  const PrintingPolicy &Policy;
1055  const Twine &PlaceHolder;
1056  unsigned Indentation;
1057 
1058  public:
1060  const Twine &PlaceHolder, unsigned Indentation)
1061  : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
1062  Indentation(Indentation) {}
1063 
1064  friend raw_ostream &operator<<(raw_ostream &OS,
1065  const StreamedQualTypeHelper &SQT) {
1066  SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
1067  return OS;
1068  }
1069  };
1070 
1072  const Twine &PlaceHolder = Twine(),
1073  unsigned Indentation = 0) const {
1074  return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
1075  }
1076 
1077  void dump(const char *s) const;
1078  void dump() const;
1079  void dump(llvm::raw_ostream &OS, const ASTContext &Context) const;
1080 
1081  void Profile(llvm::FoldingSetNodeID &ID) const {
1082  ID.AddPointer(getAsOpaquePtr());
1083  }
1084 
1085  /// Check if this type has any address space qualifier.
1086  inline bool hasAddressSpace() const;
1087 
1088  /// Return the address space of this type.
1089  inline LangAS getAddressSpace() const;
1090 
1091  /// Returns true if address space qualifiers overlap with T address space
1092  /// qualifiers.
1093  /// OpenCL C defines conversion rules for pointers to different address spaces
1094  /// and notion of overlapping address spaces.
1095  /// CL1.1 or CL1.2:
1096  /// address spaces overlap iff they are they same.
1097  /// OpenCL C v2.0 s6.5.5 adds:
1098  /// __generic overlaps with any address space except for __constant.
1100  Qualifiers Q = getQualifiers();
1101  Qualifiers TQ = T.getQualifiers();
1102  // Address spaces overlap if at least one of them is a superset of another
1103  return Q.isAddressSpaceSupersetOf(TQ) || TQ.isAddressSpaceSupersetOf(Q);
1104  }
1105 
1106  /// Returns gc attribute of this type.
1107  inline Qualifiers::GC getObjCGCAttr() const;
1108 
1109  /// true when Type is objc's weak.
1110  bool isObjCGCWeak() const {
1111  return getObjCGCAttr() == Qualifiers::Weak;
1112  }
1113 
1114  /// true when Type is objc's strong.
1115  bool isObjCGCStrong() const {
1116  return getObjCGCAttr() == Qualifiers::Strong;
1117  }
1118 
1119  /// Returns lifetime attribute of this type.
1121  return getQualifiers().getObjCLifetime();
1122  }
1123 
1126  }
1127 
1130  }
1131 
1132  // true when Type is objc's weak and weak is enabled but ARC isn't.
1133  bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
1134 
1136  /// The type does not fall into any of the following categories. Note that
1137  /// this case is zero-valued so that values of this enum can be used as a
1138  /// boolean condition for non-triviality.
1140 
1141  /// The type is an Objective-C retainable pointer type that is qualified
1142  /// with the ARC __strong qualifier.
1144 
1145  /// The type is an Objective-C retainable pointer type that is qualified
1146  /// with the ARC __weak qualifier.
1148 
1149  /// The type is a struct containing a field whose type is not PCK_Trivial.
1151  };
1152 
1153  /// Functions to query basic properties of non-trivial C struct types.
1154 
1155  /// Check if this is a non-trivial type that would cause a C struct
1156  /// transitively containing this type to be non-trivial to default initialize
1157  /// and return the kind.
1160 
1162  /// The type does not fall into any of the following categories. Note that
1163  /// this case is zero-valued so that values of this enum can be used as a
1164  /// boolean condition for non-triviality.
1166 
1167  /// The type would be trivial except that it is volatile-qualified. Types
1168  /// that fall into one of the other non-trivial cases may additionally be
1169  /// volatile-qualified.
1171 
1172  /// The type is an Objective-C retainable pointer type that is qualified
1173  /// with the ARC __strong qualifier.
1175 
1176  /// The type is an Objective-C retainable pointer type that is qualified
1177  /// with the ARC __weak qualifier.
1179 
1180  /// The type is a struct containing a field whose type is neither
1181  /// PCK_Trivial nor PCK_VolatileTrivial.
1182  /// Note that a C++ struct type does not necessarily match this; C++ copying
1183  /// semantics are too complex to express here, in part because they depend
1184  /// on the exact constructor or assignment operator that is chosen by
1185  /// overload resolution to do the copy.
1187  };
1188 
1189  /// Check if this is a non-trivial type that would cause a C struct
1190  /// transitively containing this type to be non-trivial to copy and return the
1191  /// kind.
1193 
1194  /// Check if this is a non-trivial type that would cause a C struct
1195  /// transitively containing this type to be non-trivial to destructively
1196  /// move and return the kind. Destructive move in this context is a C++-style
1197  /// move in which the source object is placed in a valid but unspecified state
1198  /// after it is moved, as opposed to a truly destructive move in which the
1199  /// source object is placed in an uninitialized state.
1201 
1208  };
1209 
1210  /// Returns a nonzero value if objects of this type require
1211  /// non-trivial work to clean up after. Non-zero because it's
1212  /// conceivable that qualifiers (objc_gc(weak)?) could make
1213  /// something require destruction.
1215  return isDestructedTypeImpl(*this);
1216  }
1217 
1218  /// Check if this is or contains a C union that is non-trivial to
1219  /// default-initialize, which is a union that has a member that is non-trivial
1220  /// to default-initialize. If this returns true,
1221  /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct.
1223 
1224  /// Check if this is or contains a C union that is non-trivial to destruct,
1225  /// which is a union that has a member that is non-trivial to destruct. If
1226  /// this returns true, isDestructedType returns DK_nontrivial_c_struct.
1228 
1229  /// Check if this is or contains a C union that is non-trivial to copy, which
1230  /// is a union that has a member that is non-trivial to copy. If this returns
1231  /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct.
1233 
1234  /// Determine whether expressions of the given type are forbidden
1235  /// from being lvalues in C.
1236  ///
1237  /// The expression types that are forbidden to be lvalues are:
1238  /// - 'void', but not qualified void
1239  /// - function types
1240  ///
1241  /// The exact rule here is C99 6.3.2.1:
1242  /// An lvalue is an expression with an object type or an incomplete
1243  /// type other than void.
1244  bool isCForbiddenLValueType() const;
1245 
1246  /// Substitute type arguments for the Objective-C type parameters used in the
1247  /// subject type.
1248  ///
1249  /// \param ctx ASTContext in which the type exists.
1250  ///
1251  /// \param typeArgs The type arguments that will be substituted for the
1252  /// Objective-C type parameters in the subject type, which are generally
1253  /// computed via \c Type::getObjCSubstitutions. If empty, the type
1254  /// parameters will be replaced with their bounds or id/Class, as appropriate
1255  /// for the context.
1256  ///
1257  /// \param context The context in which the subject type was written.
1258  ///
1259  /// \returns the resulting type.
1261  ArrayRef<QualType> typeArgs,
1262  ObjCSubstitutionContext context) const;
1263 
1264  /// Substitute type arguments from an object type for the Objective-C type
1265  /// parameters used in the subject type.
1266  ///
1267  /// This operation combines the computation of type arguments for
1268  /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1269  /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1270  /// callers that need to perform a single substitution in isolation.
1271  ///
1272  /// \param objectType The type of the object whose member type we're
1273  /// substituting into. For example, this might be the receiver of a message
1274  /// or the base of a property access.
1275  ///
1276  /// \param dc The declaration context from which the subject type was
1277  /// retrieved, which indicates (for example) which type parameters should
1278  /// be substituted.
1279  ///
1280  /// \param context The context in which the subject type was written.
1281  ///
1282  /// \returns the subject type after replacing all of the Objective-C type
1283  /// parameters with their corresponding arguments.
1285  const DeclContext *dc,
1286  ObjCSubstitutionContext context) const;
1287 
1288  /// Strip Objective-C "__kindof" types from the given type.
1289  QualType stripObjCKindOfType(const ASTContext &ctx) const;
1290 
1291  /// Remove all qualifiers including _Atomic.
1293 
1294 private:
1295  // These methods are implemented in a separate translation unit;
1296  // "static"-ize them to avoid creating temporary QualTypes in the
1297  // caller.
1298  static bool isConstant(QualType T, const ASTContext& Ctx);
1299  static QualType getDesugaredType(QualType T, const ASTContext &Context);
1301  static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1302  static QualType getSingleStepDesugaredTypeImpl(QualType type,
1303  const ASTContext &C);
1304  static QualType IgnoreParens(QualType T);
1305  static DestructionKind isDestructedTypeImpl(QualType type);
1306 
1307  /// Check if \param RD is or contains a non-trivial C union.
1309  static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD);
1310  static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD);
1311 };
1312 
1313 } // namespace clang
1314 
1315 namespace llvm {
1316 
1317 /// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1318 /// to a specific Type class.
1319 template<> struct simplify_type< ::clang::QualType> {
1321 
1323  return Val.getTypePtr();
1324  }
1325 };
1326 
1327 // Teach SmallPtrSet that QualType is "basically a pointer".
1328 template<>
1329 struct PointerLikeTypeTraits<clang::QualType> {
1330  static inline void *getAsVoidPointer(clang::QualType P) {
1331  return P.getAsOpaquePtr();
1332  }
1333 
1334  static inline clang::QualType getFromVoidPointer(void *P) {
1336  }
1337 
1338  // Various qualifiers go in low bits.
1339  static constexpr int NumLowBitsAvailable = 0;
1340 };
1341 
1342 } // namespace llvm
1343 
1344 namespace clang {
1345 
1346 /// Base class that is common to both the \c ExtQuals and \c Type
1347 /// classes, which allows \c QualType to access the common fields between the
1348 /// two.
1350  friend class ExtQuals;
1351  friend class QualType;
1352  friend class Type;
1353 
1354  /// The "base" type of an extended qualifiers type (\c ExtQuals) or
1355  /// a self-referential pointer (for \c Type).
1356  ///
1357  /// This pointer allows an efficient mapping from a QualType to its
1358  /// underlying type pointer.
1359  const Type *const BaseType;
1360 
1361  /// The canonical type of this type. A QualType.
1362  QualType CanonicalType;
1363 
1364  ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1365  : BaseType(baseType), CanonicalType(canon) {}
1366 };
1367 
1368 /// We can encode up to four bits in the low bits of a
1369 /// type pointer, but there are many more type qualifiers that we want
1370 /// to be able to apply to an arbitrary type. Therefore we have this
1371 /// struct, intended to be heap-allocated and used by QualType to
1372 /// store qualifiers.
1373 ///
1374 /// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1375 /// in three low bits on the QualType pointer; a fourth bit records whether
1376 /// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1377 /// Objective-C GC attributes) are much more rare.
1378 class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1379  // NOTE: changing the fast qualifiers should be straightforward as
1380  // long as you don't make 'const' non-fast.
1381  // 1. Qualifiers:
1382  // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1383  // Fast qualifiers must occupy the low-order bits.
1384  // b) Update Qualifiers::FastWidth and FastMask.
1385  // 2. QualType:
1386  // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1387  // b) Update remove{Volatile,Restrict}, defined near the end of
1388  // this header.
1389  // 3. ASTContext:
1390  // a) Update get{Volatile,Restrict}Type.
1391 
1392  /// The immutable set of qualifiers applied by this node. Always contains
1393  /// extended qualifiers.
1394  Qualifiers Quals;
1395 
1396  ExtQuals *this_() { return this; }
1397 
1398 public:
1399  ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1400  : ExtQualsTypeCommonBase(baseType,
1401  canon.isNull() ? QualType(this_(), 0) : canon),
1402  Quals(quals) {
1403  assert(Quals.hasNonFastQualifiers()
1404  && "ExtQuals created with no fast qualifiers");
1405  assert(!Quals.hasFastQualifiers()
1406  && "ExtQuals created with fast qualifiers");
1407  }
1408 
1409  Qualifiers getQualifiers() const { return Quals; }
1410 
1411  bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1412  Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1413 
1414  bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1416  return Quals.getObjCLifetime();
1417  }
1418 
1419  bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1420  LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
1421 
1422  const Type *getBaseType() const { return BaseType; }
1423 
1424 public:
1425  void Profile(llvm::FoldingSetNodeID &ID) const {
1426  Profile(ID, getBaseType(), Quals);
1427  }
1428 
1429  static void Profile(llvm::FoldingSetNodeID &ID,
1430  const Type *BaseType,
1431  Qualifiers Quals) {
1432  assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!");
1433  ID.AddPointer(BaseType);
1434  Quals.Profile(ID);
1435  }
1436 };
1437 
1438 /// The kind of C++11 ref-qualifier associated with a function type.
1439 /// This determines whether a member function's "this" object can be an
1440 /// lvalue, rvalue, or neither.
1442  /// No ref-qualifier was provided.
1443  RQ_None = 0,
1444 
1445  /// An lvalue ref-qualifier was provided (\c &).
1447 
1448  /// An rvalue ref-qualifier was provided (\c &&).
1450 };
1451 
1452 /// Which keyword(s) were used to create an AutoType.
1453 enum class AutoTypeKeyword {
1454  /// auto
1455  Auto,
1456 
1457  /// decltype(auto)
1458  DecltypeAuto,
1459 
1460  /// __auto_type (GNU extension)
1461  GNUAutoType
1462 };
1463 
1464 /// The base class of the type hierarchy.
1465 ///
1466 /// A central concept with types is that each type always has a canonical
1467 /// type. A canonical type is the type with any typedef names stripped out
1468 /// of it or the types it references. For example, consider:
1469 ///
1470 /// typedef int foo;
1471 /// typedef foo* bar;
1472 /// 'int *' 'foo *' 'bar'
1473 ///
1474 /// There will be a Type object created for 'int'. Since int is canonical, its
1475 /// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1476 /// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1477 /// there is a PointerType that represents 'int*', which, like 'int', is
1478 /// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1479 /// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1480 /// is also 'int*'.
1481 ///
1482 /// Non-canonical types are useful for emitting diagnostics, without losing
1483 /// information about typedefs being used. Canonical types are useful for type
1484 /// comparisons (they allow by-pointer equality tests) and useful for reasoning
1485 /// about whether something has a particular form (e.g. is a function type),
1486 /// because they implicitly, recursively, strip all typedefs out of a type.
1487 ///
1488 /// Types, once created, are immutable.
1489 ///
1490 class alignas(8) Type : public ExtQualsTypeCommonBase {
1491 public:
1492  enum TypeClass {
1493 #define TYPE(Class, Base) Class,
1494 #define LAST_TYPE(Class) TypeLast = Class
1495 #define ABSTRACT_TYPE(Class, Base)
1496 #include "clang/AST/TypeNodes.inc"
1497  };
1498 
1499 private:
1500  /// Bitfields required by the Type class.
1501  class TypeBitfields {
1502  friend class Type;
1503  template <class T> friend class TypePropertyCache;
1504 
1505  /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1506  unsigned TC : 8;
1507 
1508  /// Store information on the type dependency.
1509  unsigned Dependence : llvm::BitWidth<TypeDependence>;
1510 
1511  /// True if the cache (i.e. the bitfields here starting with
1512  /// 'Cache') is valid.
1513  mutable unsigned CacheValid : 1;
1514 
1515  /// Linkage of this type.
1516  mutable unsigned CachedLinkage : 3;
1517 
1518  /// Whether this type involves and local or unnamed types.
1519  mutable unsigned CachedLocalOrUnnamed : 1;
1520 
1521  /// Whether this type comes from an AST file.
1522  mutable unsigned FromAST : 1;
1523 
1524  bool isCacheValid() const {
1525  return CacheValid;
1526  }
1527 
1528  Linkage getLinkage() const {
1529  assert(isCacheValid() && "getting linkage from invalid cache");
1530  return static_cast<Linkage>(CachedLinkage);
1531  }
1532 
1533  bool hasLocalOrUnnamedType() const {
1534  assert(isCacheValid() && "getting linkage from invalid cache");
1535  return CachedLocalOrUnnamed;
1536  }
1537  };
1538  enum { NumTypeBits = 8 + llvm::BitWidth<TypeDependence> + 6 };
1539 
1540 protected:
1541  // These classes allow subclasses to somewhat cleanly pack bitfields
1542  // into Type.
1543 
1545  friend class ArrayType;
1546 
1547  unsigned : NumTypeBits;
1548 
1549  /// CVR qualifiers from declarations like
1550  /// 'int X[static restrict 4]'. For function parameters only.
1551  unsigned IndexTypeQuals : 3;
1552 
1553  /// Storage class qualifiers from declarations like
1554  /// 'int X[static restrict 4]'. For function parameters only.
1555  /// Actually an ArrayType::ArraySizeModifier.
1556  unsigned SizeModifier : 3;
1557  };
1558 
1560  friend class ConstantArrayType;
1561 
1562  unsigned : NumTypeBits + 3 + 3;
1563 
1564  /// Whether we have a stored size expression.
1565  unsigned HasStoredSizeExpr : 1;
1566  };
1567 
1569  friend class BuiltinType;
1570 
1571  unsigned : NumTypeBits;
1572 
1573  /// The kind (BuiltinType::Kind) of builtin type this is.
1574  unsigned Kind : 8;
1575  };
1576 
1577  /// FunctionTypeBitfields store various bits belonging to FunctionProtoType.
1578  /// Only common bits are stored here. Additional uncommon bits are stored
1579  /// in a trailing object after FunctionProtoType.
1581  friend class FunctionProtoType;
1582  friend class FunctionType;
1583 
1584  unsigned : NumTypeBits;
1585 
1586  /// Extra information which affects how the function is called, like
1587  /// regparm and the calling convention.
1588  unsigned ExtInfo : 13;
1589 
1590  /// The ref-qualifier associated with a \c FunctionProtoType.
1591  ///
1592  /// This is a value of type \c RefQualifierKind.
1593  unsigned RefQualifier : 2;
1594 
1595  /// Used only by FunctionProtoType, put here to pack with the
1596  /// other bitfields.
1597  /// The qualifiers are part of FunctionProtoType because...
1598  ///
1599  /// C++ 8.3.5p4: The return type, the parameter type list and the
1600  /// cv-qualifier-seq, [...], are part of the function type.
1601  unsigned FastTypeQuals : Qualifiers::FastWidth;
1602  /// Whether this function has extended Qualifiers.
1603  unsigned HasExtQuals : 1;
1604 
1605  /// The number of parameters this function has, not counting '...'.
1606  /// According to [implimits] 8 bits should be enough here but this is
1607  /// somewhat easy to exceed with metaprogramming and so we would like to
1608  /// keep NumParams as wide as reasonably possible.
1609  unsigned NumParams : 16;
1610 
1611  /// The type of exception specification this function has.
1612  unsigned ExceptionSpecType : 4;
1613 
1614  /// Whether this function has extended parameter information.
1615  unsigned HasExtParameterInfos : 1;
1616 
1617  /// Whether the function is variadic.
1618  unsigned Variadic : 1;
1619 
1620  /// Whether this function has a trailing return type.
1621  unsigned HasTrailingReturn : 1;
1622  };
1623 
1625  friend class ObjCObjectType;
1626 
1627  unsigned : NumTypeBits;
1628 
1629  /// The number of type arguments stored directly on this object type.
1630  unsigned NumTypeArgs : 7;
1631 
1632  /// The number of protocols stored directly on this object type.
1633  unsigned NumProtocols : 6;
1634 
1635  /// Whether this is a "kindof" type.
1636  unsigned IsKindOf : 1;
1637  };
1638 
1640  friend class ReferenceType;
1641 
1642  unsigned : NumTypeBits;
1643 
1644  /// True if the type was originally spelled with an lvalue sigil.
1645  /// This is never true of rvalue references but can also be false
1646  /// on lvalue references because of C++0x [dcl.typedef]p9,
1647  /// as follows:
1648  ///
1649  /// typedef int &ref; // lvalue, spelled lvalue
1650  /// typedef int &&rvref; // rvalue
1651  /// ref &a; // lvalue, inner ref, spelled lvalue
1652  /// ref &&a; // lvalue, inner ref
1653  /// rvref &a; // lvalue, inner ref, spelled lvalue
1654  /// rvref &&a; // rvalue, inner ref
1655  unsigned SpelledAsLValue : 1;
1656 
1657  /// True if the inner type is a reference type. This only happens
1658  /// in non-canonical forms.
1659  unsigned InnerRef : 1;
1660  };
1661 
1663  friend class TypeWithKeyword;
1664 
1665  unsigned : NumTypeBits;
1666 
1667  /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1668  unsigned Keyword : 8;
1669  };
1670 
1672 
1674  friend class ElaboratedType;
1675 
1676  unsigned : NumTypeBits;
1678 
1679  /// Whether the ElaboratedType has a trailing OwnedTagDecl.
1680  unsigned HasOwnedTagDecl : 1;
1681  };
1682 
1684  friend class VectorType;
1685  friend class DependentVectorType;
1686 
1687  unsigned : NumTypeBits;
1688 
1689  /// The kind of vector, either a generic vector type or some
1690  /// target-specific vector type such as for AltiVec or Neon.
1691  unsigned VecKind : 3;
1692  /// The number of elements in the vector.
1693  uint32_t NumElements;
1694  };
1695 
1697  friend class AttributedType;
1698 
1699  unsigned : NumTypeBits;
1700 
1701  /// An AttributedType::Kind
1702  unsigned AttrKind : 32 - NumTypeBits;
1703  };
1704 
1706  friend class AutoType;
1707 
1708  unsigned : NumTypeBits;
1709 
1710  /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1711  /// or '__auto_type'? AutoTypeKeyword value.
1712  unsigned Keyword : 2;
1713 
1714  /// The number of template arguments in the type-constraints, which is
1715  /// expected to be able to hold at least 1024 according to [implimits].
1716  /// However as this limit is somewhat easy to hit with template
1717  /// metaprogramming we'd prefer to keep it as large as possible.
1718  /// At the moment it has been left as a non-bitfield since this type
1719  /// safely fits in 64 bits as an unsigned, so there is no reason to
1720  /// introduce the performance impact of a bitfield.
1721  unsigned NumArgs;
1722  };
1723 
1726 
1727  unsigned : NumTypeBits;
1728 
1729  /// The number of template arguments in \c Arguments, which is
1730  /// expected to be able to hold at least 1024 according to [implimits].
1731  /// However as this limit is somewhat easy to hit with template
1732  /// metaprogramming we'd prefer to keep it as large as possible.
1733  /// At the moment it has been left as a non-bitfield since this type
1734  /// safely fits in 64 bits as an unsigned, so there is no reason to
1735  /// introduce the performance impact of a bitfield.
1736  unsigned NumArgs;
1737  };
1738 
1741 
1742  unsigned : NumTypeBits;
1743 
1744  /// Whether this template specialization type is a substituted type alias.
1745  unsigned TypeAlias : 1;
1746 
1747  /// The number of template arguments named in this class template
1748  /// specialization, which is expected to be able to hold at least 1024
1749  /// according to [implimits]. However, as this limit is somewhat easy to
1750  /// hit with template metaprogramming we'd prefer to keep it as large
1751  /// as possible. At the moment it has been left as a non-bitfield since
1752  /// this type safely fits in 64 bits as an unsigned, so there is no reason
1753  /// to introduce the performance impact of a bitfield.
1754  unsigned NumArgs;
1755  };
1756 
1759 
1760  unsigned : NumTypeBits;
1762 
1763  /// The number of template arguments named in this class template
1764  /// specialization, which is expected to be able to hold at least 1024
1765  /// according to [implimits]. However, as this limit is somewhat easy to
1766  /// hit with template metaprogramming we'd prefer to keep it as large
1767  /// as possible. At the moment it has been left as a non-bitfield since
1768  /// this type safely fits in 64 bits as an unsigned, so there is no reason
1769  /// to introduce the performance impact of a bitfield.
1770  unsigned NumArgs;
1771  };
1772 
1774  friend class PackExpansionType;
1775 
1776  unsigned : NumTypeBits;
1777 
1778  /// The number of expansions that this pack expansion will
1779  /// generate when substituted (+1), which is expected to be able to
1780  /// hold at least 1024 according to [implimits]. However, as this limit
1781  /// is somewhat easy to hit with template metaprogramming we'd prefer to
1782  /// keep it as large as possible. At the moment it has been left as a
1783  /// non-bitfield since this type safely fits in 64 bits as an unsigned, so
1784  /// there is no reason to introduce the performance impact of a bitfield.
1785  ///
1786  /// This field will only have a non-zero value when some of the parameter
1787  /// packs that occur within the pattern have been substituted but others
1788  /// have not.
1789  unsigned NumExpansions;
1790  };
1791 
1792  union {
1793  TypeBitfields TypeBits;
1810  };
1811 
1812 private:
1813  template <class T> friend class TypePropertyCache;
1814 
1815  /// Set whether this type comes from an AST file.
1816  void setFromAST(bool V = true) const {
1817  TypeBits.FromAST = V;
1818  }
1819 
1820 protected:
1821  friend class ASTContext;
1822 
1824  : ExtQualsTypeCommonBase(this,
1825  canon.isNull() ? QualType(this_(), 0) : canon) {
1826  static_assert(sizeof(*this) <= 8 + sizeof(ExtQualsTypeCommonBase),
1827  "changing bitfields changed sizeof(Type)!");
1828  static_assert(alignof(decltype(*this)) % sizeof(void *) == 0,
1829  "Insufficient alignment!");
1830  TypeBits.TC = tc;
1831  TypeBits.Dependence = static_cast<unsigned>(Dependence);
1832  TypeBits.CacheValid = false;
1833  TypeBits.CachedLocalOrUnnamed = false;
1834  TypeBits.CachedLinkage = NoLinkage;
1835  TypeBits.FromAST = false;
1836  }
1837 
1838  // silence VC++ warning C4355: 'this' : used in base member initializer list
1839  Type *this_() { return this; }
1840 
1842  TypeBits.Dependence = static_cast<unsigned>(D);
1843  }
1844 
1846 
1847 public:
1848  friend class ASTReader;
1849  friend class ASTWriter;
1850  template <class T> friend class serialization::AbstractTypeReader;
1851  template <class T> friend class serialization::AbstractTypeWriter;
1852 
1853  Type(const Type &) = delete;
1854  Type(Type &&) = delete;
1855  Type &operator=(const Type &) = delete;
1856  Type &operator=(Type &&) = delete;
1857 
1858  TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1859 
1860  /// Whether this type comes from an AST file.
1861  bool isFromAST() const { return TypeBits.FromAST; }
1862 
1863  /// Whether this type is or contains an unexpanded parameter
1864  /// pack, used to support C++0x variadic templates.
1865  ///
1866  /// A type that contains a parameter pack shall be expanded by the
1867  /// ellipsis operator at some point. For example, the typedef in the
1868  /// following example contains an unexpanded parameter pack 'T':
1869  ///
1870  /// \code
1871  /// template<typename ...T>
1872  /// struct X {
1873  /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1874  /// };
1875  /// \endcode
1876  ///
1877  /// Note that this routine does not specify which
1879  return getDependence() & TypeDependence::UnexpandedPack;
1880  }
1881 
1882  /// Determines if this type would be canonical if it had no further
1883  /// qualification.
1884  bool isCanonicalUnqualified() const {
1885  return CanonicalType == QualType(this, 0);
1886  }
1887 
1888  /// Pull a single level of sugar off of this locally-unqualified type.
1889  /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1890  /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1892 
1893  /// As an extension, we classify types as one of "sized" or "sizeless";
1894  /// every type is one or the other. Standard types are all sized;
1895  /// sizeless types are purely an extension.
1896  ///
1897  /// Sizeless types contain data with no specified size, alignment,
1898  /// or layout.
1899  bool isSizelessType() const;
1900  bool isSizelessBuiltinType() const;
1901 
1902  /// Determines if this is a sizeless type supported by the
1903  /// 'arm_sve_vector_bits' type attribute, which can be applied to a single
1904  /// SVE vector or predicate, excluding tuple types such as svint32x4_t.
1905  bool isVLSTBuiltinType() const;
1906 
1907  /// Returns the representative type for the element of an SVE builtin type.
1908  /// This is used to represent fixed-length SVE vectors created with the
1909  /// 'arm_sve_vector_bits' type attribute as VectorType.
1910  QualType getSveEltType(const ASTContext &Ctx) const;
1911 
1912  /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1913  /// object types, function types, and incomplete types.
1914 
1915  /// Return true if this is an incomplete type.
1916  /// A type that can describe objects, but which lacks information needed to
1917  /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1918  /// routine will need to determine if the size is actually required.
1919  ///
1920  /// Def If non-null, and the type refers to some kind of declaration
1921  /// that can be completed (such as a C struct, C++ class, or Objective-C
1922  /// class), will be set to the declaration.
1923  bool isIncompleteType(NamedDecl **Def = nullptr) const;
1924 
1925  /// Return true if this is an incomplete or object
1926  /// type, in other words, not a function type.
1928  return !isFunctionType();
1929  }
1930 
1931  /// Determine whether this type is an object type.
1932  bool isObjectType() const {
1933  // C++ [basic.types]p8:
1934  // An object type is a (possibly cv-qualified) type that is not a
1935  // function type, not a reference type, and not a void type.
1936  return !isReferenceType() && !isFunctionType() && !isVoidType();
1937  }
1938 
1939  /// Return true if this is a literal type
1940  /// (C++11 [basic.types]p10)
1941  bool isLiteralType(const ASTContext &Ctx) const;
1942 
1943  /// Determine if this type is a structural type, per C++20 [temp.param]p7.
1944  bool isStructuralType() const;
1945 
1946  /// Test if this type is a standard-layout type.
1947  /// (C++0x [basic.type]p9)
1948  bool isStandardLayoutType() const;
1949 
1950  /// Helper methods to distinguish type categories. All type predicates
1951  /// operate on the canonical type, ignoring typedefs and qualifiers.
1952 
1953  /// Returns true if the type is a builtin type.
1954  bool isBuiltinType() const;
1955 
1956  /// Test for a particular builtin type.
1957  bool isSpecificBuiltinType(unsigned K) const;
1958 
1959  /// Test for a type which does not represent an actual type-system type but
1960  /// is instead used as a placeholder for various convenient purposes within
1961  /// Clang. All such types are BuiltinTypes.
1962  bool isPlaceholderType() const;
1963  const BuiltinType *getAsPlaceholderType() const;
1964 
1965  /// Test for a specific placeholder type.
1966  bool isSpecificPlaceholderType(unsigned K) const;
1967 
1968  /// Test for a placeholder type other than Overload; see
1969  /// BuiltinType::isNonOverloadPlaceholderType.
1970  bool isNonOverloadPlaceholderType() const;
1971 
1972  /// isIntegerType() does *not* include complex integers (a GCC extension).
1973  /// isComplexIntegerType() can be used to test for complex integers.
1974  bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1975  bool isEnumeralType() const;
1976 
1977  /// Determine whether this type is a scoped enumeration type.
1978  bool isScopedEnumeralType() const;
1979  bool isBooleanType() const;
1980  bool isCharType() const;
1981  bool isWideCharType() const;
1982  bool isChar8Type() const;
1983  bool isChar16Type() const;
1984  bool isChar32Type() const;
1985  bool isAnyCharacterType() const;
1986  bool isIntegralType(const ASTContext &Ctx) const;
1987 
1988  /// Determine whether this type is an integral or enumeration type.
1989  bool isIntegralOrEnumerationType() const;
1990 
1991  /// Determine whether this type is an integral or unscoped enumeration type.
1993  bool isUnscopedEnumerationType() const;
1994 
1995  /// Floating point categories.
1996  bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1997  /// isComplexType() does *not* include complex integers (a GCC extension).
1998  /// isComplexIntegerType() can be used to test for complex integers.
1999  bool isComplexType() const; // C99 6.2.5p11 (complex)
2000  bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
2001  bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
2002  bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
2003  bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661
2004  bool isBFloat16Type() const;
2005  bool isFloat128Type() const;
2006  bool isIbm128Type() const;
2007  bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
2008  bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
2009  bool isVoidType() const; // C99 6.2.5p19
2010  bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
2011  bool isAggregateType() const;
2012  bool isFundamentalType() const;
2013  bool isCompoundType() const;
2014 
2015  // Type Predicates: Check to see if this type is structurally the specified
2016  // type, ignoring typedefs and qualifiers.
2017  bool isFunctionType() const;
2018  bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
2019  bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
2020  bool isPointerType() const;
2021  bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
2022  bool isBlockPointerType() const;
2023  bool isVoidPointerType() const;
2024  bool isReferenceType() const;
2025  bool isLValueReferenceType() const;
2026  bool isRValueReferenceType() const;
2027  bool isObjectPointerType() const;
2028  bool isFunctionPointerType() const;
2029  bool isFunctionReferenceType() const;
2030  bool isMemberPointerType() const;
2031  bool isMemberFunctionPointerType() const;
2032  bool isMemberDataPointerType() const;
2033  bool isArrayType() const;
2034  bool isConstantArrayType() const;
2035  bool isIncompleteArrayType() const;
2036  bool isVariableArrayType() const;
2037  bool isDependentSizedArrayType() const;
2038  bool isRecordType() const;
2039  bool isClassType() const;
2040  bool isStructureType() const;
2041  bool isObjCBoxableRecordType() const;
2042  bool isInterfaceType() const;
2043  bool isStructureOrClassType() const;
2044  bool isUnionType() const;
2045  bool isComplexIntegerType() const; // GCC _Complex integer type.
2046  bool isVectorType() const; // GCC vector type.
2047  bool isExtVectorType() const; // Extended vector type.
2048  bool isMatrixType() const; // Matrix type.
2049  bool isConstantMatrixType() const; // Constant matrix type.
2050  bool isDependentAddressSpaceType() const; // value-dependent address space qualifier
2051  bool isObjCObjectPointerType() const; // pointer to ObjC object
2052  bool isObjCRetainableType() const; // ObjC object or block pointer
2053  bool isObjCLifetimeType() const; // (array of)* retainable type
2054  bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
2055  bool isObjCNSObjectType() const; // __attribute__((NSObject))
2056  bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
2057  // FIXME: change this to 'raw' interface type, so we can used 'interface' type
2058  // for the common case.
2059  bool isObjCObjectType() const; // NSString or typeof(*(id)0)
2060  bool isObjCQualifiedInterfaceType() const; // NSString<foo>
2061  bool isObjCQualifiedIdType() const; // id<foo>
2062  bool isObjCQualifiedClassType() const; // Class<foo>
2063  bool isObjCObjectOrInterfaceType() const;
2064  bool isObjCIdType() const; // id
2065  bool isDecltypeType() const;
2066  /// Was this type written with the special inert-in-ARC __unsafe_unretained
2067  /// qualifier?
2068  ///
2069  /// This approximates the answer to the following question: if this
2070  /// translation unit were compiled in ARC, would this type be qualified
2071  /// with __unsafe_unretained?
2073  return hasAttr(attr::ObjCInertUnsafeUnretained);
2074  }
2075 
2076  /// Whether the type is Objective-C 'id' or a __kindof type of an
2077  /// object type, e.g., __kindof NSView * or __kindof id
2078  /// <NSCopying>.
2079  ///
2080  /// \param bound Will be set to the bound on non-id subtype types,
2081  /// which will be (possibly specialized) Objective-C class type, or
2082  /// null for 'id.
2083  bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
2084  const ObjCObjectType *&bound) const;
2085 
2086  bool isObjCClassType() const; // Class
2087 
2088  /// Whether the type is Objective-C 'Class' or a __kindof type of an
2089  /// Class type, e.g., __kindof Class <NSCopying>.
2090  ///
2091  /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
2092  /// here because Objective-C's type system cannot express "a class
2093  /// object for a subclass of NSFoo".
2094  bool isObjCClassOrClassKindOfType() const;
2095 
2097  bool isObjCSelType() const; // Class
2098  bool isObjCBuiltinType() const; // 'id' or 'Class'
2099  bool isObjCARCBridgableType() const;
2100  bool isCARCBridgableType() const;
2101  bool isTemplateTypeParmType() const; // C++ template type parameter
2102  bool isNullPtrType() const; // C++11 std::nullptr_t
2103  bool isNothrowT() const; // C++ std::nothrow_t
2104  bool isAlignValT() const; // C++17 std::align_val_t
2105  bool isStdByteType() const; // C++17 std::byte
2106  bool isAtomicType() const; // C11 _Atomic()
2107  bool isUndeducedAutoType() const; // C++11 auto or
2108  // C++14 decltype(auto)
2109  bool isTypedefNameType() const; // typedef or alias template
2110 
2111 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2112  bool is##Id##Type() const;
2113 #include "clang/Basic/OpenCLImageTypes.def"
2114 
2115  bool isImageType() const; // Any OpenCL image type
2116 
2117  bool isSamplerT() const; // OpenCL sampler_t
2118  bool isEventT() const; // OpenCL event_t
2119  bool isClkEventT() const; // OpenCL clk_event_t
2120  bool isQueueT() const; // OpenCL queue_t
2121  bool isReserveIDT() const; // OpenCL reserve_id_t
2122 
2123 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2124  bool is##Id##Type() const;
2125 #include "clang/Basic/OpenCLExtensionTypes.def"
2126  // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension
2127  bool isOCLIntelSubgroupAVCType() const;
2128  bool isOCLExtOpaqueType() const; // Any OpenCL extension type
2129 
2130  bool isPipeType() const; // OpenCL pipe type
2131  bool isExtIntType() const; // Extended Int Type
2132  bool isOpenCLSpecificType() const; // Any OpenCL specific type
2133 
2134  /// Determines if this type, which must satisfy
2135  /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
2136  /// than implicitly __strong.
2137  bool isObjCARCImplicitlyUnretainedType() const;
2138 
2139  /// Check if the type is the CUDA device builtin surface type.
2140  bool isCUDADeviceBuiltinSurfaceType() const;
2141  /// Check if the type is the CUDA device builtin texture type.
2142  bool isCUDADeviceBuiltinTextureType() const;
2143 
2144  /// Return the implicit lifetime for this type, which must not be dependent.
2146 
2158  };
2159 
2160  /// Given that this is a scalar type, classify it.
2162 
2164  return static_cast<TypeDependence>(TypeBits.Dependence);
2165  }
2166 
2167  /// Whether this type is an error type.
2168  bool containsErrors() const {
2170  }
2171 
2172  /// Whether this type is a dependent type, meaning that its definition
2173  /// somehow depends on a template parameter (C++ [temp.dep.type]).
2174  bool isDependentType() const {
2175  return getDependence() & TypeDependence::Dependent;
2176  }
2177 
2178  /// Determine whether this type is an instantiation-dependent type,
2179  /// meaning that the type involves a template parameter (even if the
2180  /// definition does not actually depend on the type substituted for that
2181  /// template parameter).
2183  return getDependence() & TypeDependence::Instantiation;
2184  }
2185 
2186  /// Determine whether this type is an undeduced type, meaning that
2187  /// it somehow involves a C++11 'auto' type or similar which has not yet been
2188  /// deduced.
2189  bool isUndeducedType() const;
2190 
2191  /// Whether this type is a variably-modified type (C99 6.7.5).
2192  bool isVariablyModifiedType() const {
2193  return getDependence() & TypeDependence::VariablyModified;
2194  }
2195 
2196  /// Whether this type involves a variable-length array type
2197  /// with a definite size.
2198  bool hasSizedVLAType() const;
2199 
2200  /// Whether this type is or contains a local or unnamed type.
2201  bool hasUnnamedOrLocalType() const;
2202 
2203  bool isOverloadableType() const;
2204 
2205  /// Determine wither this type is a C++ elaborated-type-specifier.
2206  bool isElaboratedTypeSpecifier() const;
2207 
2208  bool canDecayToPointerType() const;
2209 
2210  /// Whether this type is represented natively as a pointer. This includes
2211  /// pointers, references, block pointers, and Objective-C interface,
2212  /// qualified id, and qualified interface types, as well as nullptr_t.
2213  bool hasPointerRepresentation() const;
2214 
2215  /// Whether this type can represent an objective pointer type for the
2216  /// purpose of GC'ability
2217  bool hasObjCPointerRepresentation() const;
2218 
2219  /// Determine whether this type has an integer representation
2220  /// of some sort, e.g., it is an integer type or a vector.
2221  bool hasIntegerRepresentation() const;
2222 
2223  /// Determine whether this type has an signed integer representation
2224  /// of some sort, e.g., it is an signed integer type or a vector.
2225  bool hasSignedIntegerRepresentation() const;
2226 
2227  /// Determine whether this type has an unsigned integer representation
2228  /// of some sort, e.g., it is an unsigned integer type or a vector.
2229  bool hasUnsignedIntegerRepresentation() const;
2230 
2231  /// Determine whether this type has a floating-point representation
2232  /// of some sort, e.g., it is a floating-point type or a vector thereof.
2233  bool hasFloatingRepresentation() const;
2234 
2235  // Type Checking Functions: Check to see if this type is structurally the
2236  // specified type, ignoring typedefs and qualifiers, and return a pointer to
2237  // the best type we can.
2238  const RecordType *getAsStructureType() const;
2239  /// NOTE: getAs*ArrayType are methods on ASTContext.
2240  const RecordType *getAsUnionType() const;
2241  const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
2242  const ObjCObjectType *getAsObjCInterfaceType() const;
2243 
2244  // The following is a convenience method that returns an ObjCObjectPointerType
2245  // for object declared using an interface.
2250 
2251  /// Retrieves the CXXRecordDecl that this type refers to, either
2252  /// because the type is a RecordType or because it is the injected-class-name
2253  /// type of a class template or class template partial specialization.
2255 
2256  /// Retrieves the RecordDecl this type refers to.
2257  RecordDecl *getAsRecordDecl() const;
2258 
2259  /// Retrieves the TagDecl that this type refers to, either
2260  /// because the type is a TagType or because it is the injected-class-name
2261  /// type of a class template or class template partial specialization.
2262  TagDecl *getAsTagDecl() const;
2263 
2264  /// If this is a pointer or reference to a RecordType, return the
2265  /// CXXRecordDecl that the type refers to.
2266  ///
2267  /// If this is not a pointer or reference, or the type being pointed to does
2268  /// not refer to a CXXRecordDecl, returns NULL.
2269  const CXXRecordDecl *getPointeeCXXRecordDecl() const;
2270 
2271  /// Get the DeducedType whose type will be deduced for a variable with
2272  /// an initializer of this type. This looks through declarators like pointer
2273  /// types, but not through decltype or typedefs.
2275 
2276  /// Get the AutoType whose type will be deduced for a variable with
2277  /// an initializer of this type. This looks through declarators like pointer
2278  /// types, but not through decltype or typedefs.
2280  return dyn_cast_or_null<AutoType>(getContainedDeducedType());
2281  }
2282 
2283  /// Determine whether this type was written with a leading 'auto'
2284  /// corresponding to a trailing return type (possibly for a nested
2285  /// function type within a pointer to function type or similar).
2286  bool hasAutoForTrailingReturnType() const;
2287 
2288  /// Member-template getAs<specific type>'. Look through sugar for
2289  /// an instance of <specific type>. This scheme will eventually
2290  /// replace the specific getAsXXXX methods above.
2291  ///
2292  /// There are some specializations of this member template listed
2293  /// immediately following this class.
2294  template <typename T> const T *getAs() const;
2295 
2296  /// Member-template getAsAdjusted<specific type>. Look through specific kinds
2297  /// of sugar (parens, attributes, etc) for an instance of <specific type>.
2298  /// This is used when you need to walk over sugar nodes that represent some
2299  /// kind of type adjustment from a type that was written as a <specific type>
2300  /// to another type that is still canonically a <specific type>.
2301  template <typename T> const T *getAsAdjusted() const;
2302 
2303  /// A variant of getAs<> for array types which silently discards
2304  /// qualifiers from the outermost type.
2305  const ArrayType *getAsArrayTypeUnsafe() const;
2306 
2307  /// Member-template castAs<specific type>. Look through sugar for
2308  /// the underlying instance of <specific type>.
2309  ///
2310  /// This method has the same relationship to getAs<T> as cast<T> has
2311  /// to dyn_cast<T>; which is to say, the underlying type *must*
2312  /// have the intended type, and this method will never return null.
2313  template <typename T> const T *castAs() const;
2314 
2315  /// A variant of castAs<> for array type which silently discards
2316  /// qualifiers from the outermost type.
2317  const ArrayType *castAsArrayTypeUnsafe() const;
2318 
2319  /// Determine whether this type had the specified attribute applied to it
2320  /// (looking through top-level type sugar).
2321  bool hasAttr(attr::Kind AK) const;
2322 
2323  /// Get the base element type of this type, potentially discarding type
2324  /// qualifiers. This should never be used when type qualifiers
2325  /// are meaningful.
2326  const Type *getBaseElementTypeUnsafe() const;
2327 
2328  /// If this is an array type, return the element type of the array,
2329  /// potentially with type qualifiers missing.
2330  /// This should never be used when type qualifiers are meaningful.
2331  const Type *getArrayElementTypeNoTypeQual() const;
2332 
2333  /// If this is a pointer type, return the pointee type.
2334  /// If this is an array type, return the array element type.
2335  /// This should never be used when type qualifiers are meaningful.
2336  const Type *getPointeeOrArrayElementType() const;
2337 
2338  /// If this is a pointer, ObjC object pointer, or block
2339  /// pointer, this returns the respective pointee.
2340  QualType getPointeeType() const;
2341 
2342  /// Return the specified type with any "sugar" removed from the type,
2343  /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2344  const Type *getUnqualifiedDesugaredType() const;
2345 
2346  /// More type predicates useful for type checking/promotion
2347  bool isPromotableIntegerType() const; // C99 6.3.1.1p2
2348 
2349  /// Return true if this is an integer type that is
2350  /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2351  /// or an enum decl which has a signed representation.
2352  bool isSignedIntegerType() const;
2353 
2354  /// Return true if this is an integer type that is
2355  /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2356  /// or an enum decl which has an unsigned representation.
2357  bool isUnsignedIntegerType() const;
2358 
2359  /// Determines whether this is an integer type that is signed or an
2360  /// enumeration types whose underlying type is a signed integer type.
2361  bool isSignedIntegerOrEnumerationType() const;
2362 
2363  /// Determines whether this is an integer type that is unsigned or an
2364  /// enumeration types whose underlying type is a unsigned integer type.
2366 
2367  /// Return true if this is a fixed point type according to
2368  /// ISO/IEC JTC1 SC22 WG14 N1169.
2369  bool isFixedPointType() const;
2370 
2371  /// Return true if this is a fixed point or integer type.
2372  bool isFixedPointOrIntegerType() const;
2373 
2374  /// Return true if this is a saturated fixed point type according to
2375  /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2376  bool isSaturatedFixedPointType() const;
2377 
2378  /// Return true if this is a saturated fixed point type according to
2379  /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2380  bool isUnsaturatedFixedPointType() const;
2381 
2382  /// Return true if this is a fixed point type that is signed according
2383  /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2384  bool isSignedFixedPointType() const;
2385 
2386  /// Return true if this is a fixed point type that is unsigned according
2387  /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2388  bool isUnsignedFixedPointType() const;
2389 
2390  /// Return true if this is not a variable sized type,
2391  /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2392  /// incomplete types.
2393  bool isConstantSizeType() const;
2394 
2395  /// Returns true if this type can be represented by some
2396  /// set of type specifiers.
2397  bool isSpecifierType() const;
2398 
2399  /// Determine the linkage of this type.
2400  Linkage getLinkage() const;
2401 
2402  /// Determine the visibility of this type.
2405  }
2406 
2407  /// Return true if the visibility was explicitly set is the code.
2408  bool isVisibilityExplicit() const {
2410  }
2411 
2412  /// Determine the linkage and visibility of this type.
2414 
2415  /// True if the computed linkage is valid. Used for consistency
2416  /// checking. Should always return true.
2417  bool isLinkageValid() const;
2418 
2419  /// Determine the nullability of the given type.
2420  ///
2421  /// Note that nullability is only captured as sugar within the type
2422  /// system, not as part of the canonical type, so nullability will
2423  /// be lost by canonicalization and desugaring.
2424  Optional<NullabilityKind> getNullability(const ASTContext &context) const;
2425 
2426  /// Determine whether the given type can have a nullability
2427  /// specifier applied to it, i.e., if it is any kind of pointer type.
2428  ///
2429  /// \param ResultIfUnknown The value to return if we don't yet know whether
2430  /// this type can have nullability because it is dependent.
2431  bool canHaveNullability(bool ResultIfUnknown = true) const;
2432 
2433  /// Retrieve the set of substitutions required when accessing a member
2434  /// of the Objective-C receiver type that is declared in the given context.
2435  ///
2436  /// \c *this is the type of the object we're operating on, e.g., the
2437  /// receiver for a message send or the base of a property access, and is
2438  /// expected to be of some object or object pointer type.
2439  ///
2440  /// \param dc The declaration context for which we are building up a
2441  /// substitution mapping, which should be an Objective-C class, extension,
2442  /// category, or method within.
2443  ///
2444  /// \returns an array of type arguments that can be substituted for
2445  /// the type parameters of the given declaration context in any type described
2446  /// within that context, or an empty optional to indicate that no
2447  /// substitution is required.
2449  getObjCSubstitutions(const DeclContext *dc) const;
2450 
2451  /// Determines if this is an ObjC interface type that may accept type
2452  /// parameters.
2453  bool acceptsObjCTypeParams() const;
2454 
2455  const char *getTypeClassName() const;
2456 
2458  return CanonicalType;
2459  }
2460 
2461  CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2462  void dump() const;
2463  void dump(llvm::raw_ostream &OS, const ASTContext &Context) const;
2464 };
2465 
2466 /// This will check for a TypedefType by removing any existing sugar
2467 /// until it reaches a TypedefType or a non-sugared type.
2468 template <> const TypedefType *Type::getAs() const;
2469 
2470 /// This will check for a TemplateSpecializationType by removing any
2471 /// existing sugar until it reaches a TemplateSpecializationType or a
2472 /// non-sugared type.
2473 template <> const TemplateSpecializationType *Type::getAs() const;
2474 
2475 /// This will check for an AttributedType by removing any existing sugar
2476 /// until it reaches an AttributedType or a non-sugared type.
2477 template <> const AttributedType *Type::getAs() const;
2478 
2479 // We can do canonical leaf types faster, because we don't have to
2480 // worry about preserving child type decoration.
2481 #define TYPE(Class, Base)
2482 #define LEAF_TYPE(Class) \
2483 template <> inline const Class##Type *Type::getAs() const { \
2484  return dyn_cast<Class##Type>(CanonicalType); \
2485 } \
2486 template <> inline const Class##Type *Type::castAs() const { \
2487  return cast<Class##Type>(CanonicalType); \
2488 }
2489 #include "clang/AST/TypeNodes.inc"
2490 
2491 /// This class is used for builtin types like 'int'. Builtin
2492 /// types are always canonical and have a literal name field.
2493 class BuiltinType : public Type {
2494 public:
2495  enum Kind {
2496 // OpenCL image types
2497 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2498 #include "clang/Basic/OpenCLImageTypes.def"
2499 // OpenCL extension types
2500 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id,
2501 #include "clang/Basic/OpenCLExtensionTypes.def"
2502 // SVE Types
2503 #define SVE_TYPE(Name, Id, SingletonId) Id,
2504 #include "clang/Basic/AArch64SVEACLETypes.def"
2505 // PPC MMA Types
2506 #define PPC_VECTOR_TYPE(Name, Id, Size) Id,
2507 #include "clang/Basic/PPCTypes.def"
2508 // RVV Types
2509 #define RVV_TYPE(Name, Id, SingletonId) Id,
2510 #include "clang/Basic/RISCVVTypes.def"
2511 // All other builtin types
2512 #define BUILTIN_TYPE(Id, SingletonId) Id,
2513 #define LAST_BUILTIN_TYPE(Id) LastKind = Id
2514 #include "clang/AST/BuiltinTypes.def"
2515  };
2516 
2517 private:
2518  friend class ASTContext; // ASTContext creates these.
2519 
2520  BuiltinType(Kind K)
2521  : Type(Builtin, QualType(),
2522  K == Dependent ? TypeDependence::DependentInstantiation
2523  : TypeDependence::None) {
2524  BuiltinTypeBits.Kind = K;
2525  }
2526 
2527 public:
2528  Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2529  StringRef getName(const PrintingPolicy &Policy) const;
2530 
2531  const char *getNameAsCString(const PrintingPolicy &Policy) const {
2532  // The StringRef is null-terminated.
2533  StringRef str = getName(Policy);
2534  assert(!str.empty() && str.data()[str.size()] == '\0');
2535  return str.data();
2536  }
2537 
2538  bool isSugared() const { return false; }
2539  QualType desugar() const { return QualType(this, 0); }
2540 
2541  bool isInteger() const {
2542  return getKind() >= Bool && getKind() <= Int128;
2543  }
2544 
2545  bool isSignedInteger() const {
2546  return getKind() >= Char_S && getKind() <= Int128;
2547  }
2548 
2549  bool isUnsignedInteger() const {
2550  return getKind() >= Bool && getKind() <= UInt128;
2551  }
2552 
2553  bool isFloatingPoint() const {
2554  return getKind() >= Half && getKind() <= Ibm128;
2555  }
2556 
2557  /// Determines whether the given kind corresponds to a placeholder type.
2558  static bool isPlaceholderTypeKind(Kind K) {
2559  return K >= Overload;
2560  }
2561 
2562  /// Determines whether this type is a placeholder type, i.e. a type
2563  /// which cannot appear in arbitrary positions in a fully-formed
2564  /// expression.
2565  bool isPlaceholderType() const {
2566  return isPlaceholderTypeKind(getKind());
2567  }
2568 
2569  /// Determines whether this type is a placeholder type other than
2570  /// Overload. Most placeholder types require only syntactic
2571  /// information about their context in order to be resolved (e.g.
2572  /// whether it is a call expression), which means they can (and
2573  /// should) be resolved in an earlier "phase" of analysis.
2574  /// Overload expressions sometimes pick up further information
2575  /// from their context, like whether the context expects a
2576  /// specific function-pointer type, and so frequently need
2577  /// special treatment.
2579  return getKind() > Overload;
2580  }
2581 
2582  static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2583 };
2584 
2585 /// Complex values, per C99 6.2.5p11. This supports the C99 complex
2586 /// types (_Complex float etc) as well as the GCC integer complex extensions.
2587 class ComplexType : public Type, public llvm::FoldingSetNode {
2588  friend class ASTContext; // ASTContext creates these.
2589 
2590  QualType ElementType;
2591 
2592  ComplexType(QualType Element, QualType CanonicalPtr)
2593  : Type(Complex, CanonicalPtr, Element->getDependence()),
2594  ElementType(Element) {}
2595 
2596 public:
2597  QualType getElementType() const { return ElementType; }
2598 
2599  bool isSugared() const { return false; }
2600  QualType desugar() const { return QualType(this, 0); }
2601 
2602  void Profile(llvm::FoldingSetNodeID &ID) {
2604  }
2605 
2606  static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2607  ID.AddPointer(Element.getAsOpaquePtr());
2608  }
2609 
2610  static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2611 };
2612 
2613 /// Sugar for parentheses used when specifying types.
2614 class ParenType : public Type, public llvm::FoldingSetNode {
2615  friend class ASTContext; // ASTContext creates these.
2616 
2617  QualType Inner;
2618 
2619  ParenType(QualType InnerType, QualType CanonType)
2620  : Type(Paren, CanonType, InnerType->getDependence()), Inner(InnerType) {}
2621 
2622 public:
2623  QualType getInnerType() const { return Inner; }
2624 
2625  bool isSugared() const { return true; }
2626  QualType desugar() const { return getInnerType(); }
2627 
2628  void Profile(llvm::FoldingSetNodeID &ID) {
2629  Profile(ID, getInnerType());
2630  }
2631 
2632  static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2633  Inner.Profile(ID);
2634  }
2635 
2636  static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2637 };
2638 
2639 /// PointerType - C99 6.7.5.1 - Pointer Declarators.
2640 class PointerType : public Type, public llvm::FoldingSetNode {
2641  friend class ASTContext; // ASTContext creates these.
2642 
2643  QualType PointeeType;
2644 
2645  PointerType(QualType Pointee, QualType CanonicalPtr)
2646  : Type(Pointer, CanonicalPtr, Pointee->getDependence()),
2647  PointeeType(Pointee) {}
2648 
2649 public:
2650  QualType getPointeeType() const { return PointeeType; }
2651 
2652  bool isSugared() const { return false; }
2653  QualType desugar() const { return QualType(this, 0); }
2654 
2655  void Profile(llvm::FoldingSetNodeID &ID) {
2657  }
2658 
2659  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2660  ID.AddPointer(Pointee.getAsOpaquePtr());
2661  }
2662 
2663  static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2664 };
2665 
2666 /// Represents a type which was implicitly adjusted by the semantic
2667 /// engine for arbitrary reasons. For example, array and function types can
2668 /// decay, and function types can have their calling conventions adjusted.
2669 class AdjustedType : public Type, public llvm::FoldingSetNode {
2670  QualType OriginalTy;
2671  QualType AdjustedTy;
2672 
2673 protected:
2674  friend class ASTContext; // ASTContext creates these.
2675 
2676  AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2677  QualType CanonicalPtr)
2678  : Type(TC, CanonicalPtr, OriginalTy->getDependence()),
2679  OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2680 
2681 public:
2682  QualType getOriginalType() const { return OriginalTy; }
2683  QualType getAdjustedType() const { return AdjustedTy; }
2684 
2685  bool isSugared() const { return true; }
2686  QualType desugar() const { return AdjustedTy; }
2687 
2688  void Profile(llvm::FoldingSetNodeID &ID) {
2689  Profile(ID, OriginalTy, AdjustedTy);
2690  }
2691 
2692  static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2693  ID.AddPointer(Orig.getAsOpaquePtr());
2694  ID.AddPointer(New.getAsOpaquePtr());
2695  }
2696 
2697  static bool classof(const Type *T) {
2698  return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2699  }
2700 };
2701 
2702 /// Represents a pointer type decayed from an array or function type.
2703 class DecayedType : public AdjustedType {
2704  friend class ASTContext; // ASTContext creates these.
2705 
2706  inline
2707  DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
2708 
2709 public:
2711 
2712  inline QualType getPointeeType() const;
2713 
2714  static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2715 };
2716 
2717 /// Pointer to a block type.
2718 /// This type is to represent types syntactically represented as
2719 /// "void (^)(int)", etc. Pointee is required to always be a function type.
2720 class BlockPointerType : public Type, public llvm::FoldingSetNode {
2721  friend class ASTContext; // ASTContext creates these.
2722 
2723  // Block is some kind of pointer type
2724  QualType PointeeType;
2725 
2726  BlockPointerType(QualType Pointee, QualType CanonicalCls)
2727  : Type(BlockPointer, CanonicalCls, Pointee->getDependence()),
2728  PointeeType(Pointee) {}
2729 
2730 public:
2731  // Get the pointee type. Pointee is required to always be a function type.
2732  QualType getPointeeType() const { return PointeeType; }
2733 
2734  bool isSugared() const { return false; }
2735  QualType desugar() const { return QualType(this, 0); }
2736 
2737  void Profile(llvm::FoldingSetNodeID &ID) {
2739  }
2740 
2741  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2742  ID.AddPointer(Pointee.getAsOpaquePtr());
2743  }
2744 
2745  static bool classof(const Type *T) {
2746  return T->getTypeClass() == BlockPointer;
2747  }
2748 };
2749 
2750 /// Base for LValueReferenceType and RValueReferenceType
2751 class ReferenceType : public Type, public llvm::FoldingSetNode {
2752  QualType PointeeType;
2753 
2754 protected:
2755  ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2756  bool SpelledAsLValue)
2757  : Type(tc, CanonicalRef, Referencee->getDependence()),
2758  PointeeType(Referencee) {
2759  ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2760  ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2761  }
2762 
2763 public:
2764  bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2765  bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2766 
2767  QualType getPointeeTypeAsWritten() const { return PointeeType; }
2768 
2770  // FIXME: this might strip inner qualifiers; okay?
2771  const ReferenceType *T = this;
2772  while (T->isInnerRef())
2773  T = T->PointeeType->castAs<ReferenceType>();
2774  return T->PointeeType;
2775  }
2776 
2777  void Profile(llvm::FoldingSetNodeID &ID) {
2778  Profile(ID, PointeeType, isSpelledAsLValue());
2779  }
2780 
2781  static void Profile(llvm::FoldingSetNodeID &ID,
2782  QualType Referencee,
2783  bool SpelledAsLValue) {
2784  ID.AddPointer(Referencee.getAsOpaquePtr());
2785  ID.AddBoolean(SpelledAsLValue);
2786  }
2787 
2788  static bool classof(const Type *T) {
2789  return T->getTypeClass() == LValueReference ||
2790  T->getTypeClass() == RValueReference;
2791  }
2792 };
2793 
2794 /// An lvalue reference type, per C++11 [dcl.ref].
2796  friend class ASTContext; // ASTContext creates these
2797 
2798  LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2799  bool SpelledAsLValue)
2800  : ReferenceType(LValueReference, Referencee, CanonicalRef,
2801  SpelledAsLValue) {}
2802 
2803 public:
2804  bool isSugared() const { return false; }
2805  QualType desugar() const { return QualType(this, 0); }
2806 
2807  static bool classof(const Type *T) {
2808  return T->getTypeClass() == LValueReference;
2809  }
2810 };
2811 
2812 /// An rvalue reference type, per C++11 [dcl.ref].
2814  friend class ASTContext; // ASTContext creates these
2815 
2816  RValueReferenceType(QualType Referencee, QualType CanonicalRef)
2817  : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
2818 
2819 public:
2820  bool isSugared() const { return false; }
2821  QualType desugar() const { return QualType(this, 0); }
2822 
2823  static bool classof(const Type *T) {
2824  return T->getTypeClass() == RValueReference;
2825  }
2826 };
2827 
2828 /// A pointer to member type per C++ 8.3.3 - Pointers to members.
2829 ///
2830 /// This includes both pointers to data members and pointer to member functions.
2831 class MemberPointerType : public Type, public llvm::FoldingSetNode {
2832  friend class ASTContext; // ASTContext creates these.
2833 
2834  QualType PointeeType;
2835 
2836  /// The class of which the pointee is a member. Must ultimately be a
2837  /// RecordType, but could be a typedef or a template parameter too.
2838  const Type *Class;
2839 
2840  MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
2841  : Type(MemberPointer, CanonicalPtr,
2842  (Cls->getDependence() & ~TypeDependence::VariablyModified) |
2843  Pointee->getDependence()),
2844  PointeeType(Pointee), Class(Cls) {}
2845 
2846 public:
2847  QualType getPointeeType() const { return PointeeType; }
2848 
2849  /// Returns true if the member type (i.e. the pointee type) is a
2850  /// function type rather than a data-member type.
2852  return PointeeType->isFunctionProtoType();
2853  }
2854 
2855  /// Returns true if the member type (i.e. the pointee type) is a
2856  /// data type rather than a function type.
2857  bool isMemberDataPointer() const {
2858  return !PointeeType->isFunctionProtoType();
2859  }
2860 
2861  const Type *getClass() const { return Class; }
2863 
2864  bool isSugared() const { return false; }
2865  QualType desugar() const { return QualType(this, 0); }
2866 
2867  void Profile(llvm::FoldingSetNodeID &ID) {
2869  }
2870 
2871  static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2872  const Type *Class) {
2873  ID.AddPointer(Pointee.getAsOpaquePtr());
2874  ID.AddPointer(Class);
2875  }
2876 
2877  static bool classof(const Type *T) {
2878  return T->getTypeClass() == MemberPointer;
2879  }
2880 };
2881 
2882 /// Represents an array type, per C99 6.7.5.2 - Array Declarators.
2883 class ArrayType : public Type, public llvm::FoldingSetNode {
2884 public:
2885  /// Capture whether this is a normal array (e.g. int X[4])
2886  /// an array with a static size (e.g. int X[static 4]), or an array
2887  /// with a star size (e.g. int X[*]).
2888  /// 'static' is only allowed on function parameters.
2891  };
2892 
2893 private:
2894  /// The element type of the array.
2895  QualType ElementType;
2896 
2897 protected:
2898  friend class ASTContext; // ASTContext creates these.
2899 
2901  unsigned tq, const Expr *sz = nullptr);
2902 
2903 public:
2904  QualType getElementType() const { return ElementType; }
2905 
2907  return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2908  }
2909 
2912  }
2913 
2914  unsigned getIndexTypeCVRQualifiers() const {
2915  return ArrayTypeBits.IndexTypeQuals;
2916  }
2917 
2918  static bool classof(const Type *T) {
2919  return T->getTypeClass() == ConstantArray ||
2920  T->getTypeClass() == VariableArray ||
2921  T->getTypeClass() == IncompleteArray ||
2922  T->getTypeClass() == DependentSizedArray;
2923  }
2924 };
2925 
2926 /// Represents the canonical version of C arrays with a specified constant size.
2927 /// For example, the canonical type for 'int A[4 + 4*100]' is a
2928 /// ConstantArrayType where the element type is 'int' and the size is 404.
2930  : public ArrayType,
2931  private llvm::TrailingObjects<ConstantArrayType, const Expr *> {
2932  friend class ASTContext; // ASTContext creates these.
2933  friend TrailingObjects;
2934 
2935  llvm::APInt Size; // Allows us to unique the type.
2936 
2937  ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2938  const Expr *sz, ArraySizeModifier sm, unsigned tq)
2939  : ArrayType(ConstantArray, et, can, sm, tq, sz), Size(size) {
2940  ConstantArrayTypeBits.HasStoredSizeExpr = sz != nullptr;
2941  if (ConstantArrayTypeBits.HasStoredSizeExpr) {
2942  assert(!can.isNull() && "canonical constant array should not have size");
2943  *getTrailingObjects<const Expr*>() = sz;
2944  }
2945  }
2946 
2947  unsigned numTrailingObjects(OverloadToken<const Expr*>) const {
2948  return ConstantArrayTypeBits.HasStoredSizeExpr;
2949  }
2950 
2951 public:
2952  const llvm::APInt &getSize() const { return Size; }
2953  const Expr *getSizeExpr() const {
2954  return ConstantArrayTypeBits.HasStoredSizeExpr
2955  ? *getTrailingObjects<const Expr *>()
2956  : nullptr;
2957  }
2958  bool isSugared() const { return false; }
2959  QualType desugar() const { return QualType(this, 0); }
2960 
2961  /// Determine the number of bits required to address a member of
2962  // an array with the given element type and number of elements.
2963  static unsigned getNumAddressingBits(const ASTContext &Context,
2964  QualType ElementType,
2965  const llvm::APInt &NumElements);
2966 
2967  /// Determine the maximum number of active bits that an array's size
2968  /// can require, which limits the maximum size of the array.
2969  static unsigned getMaxSizeBits(const ASTContext &Context);
2970 
2971  void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
2974  }
2975 
2976  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx,
2977  QualType ET, const llvm::APInt &ArraySize,
2978  const Expr *SizeExpr, ArraySizeModifier SizeMod,
2979  unsigned TypeQuals);
2980 
2981  static bool classof(const Type *T) {
2982  return T->getTypeClass() == ConstantArray;
2983  }
2984 };
2985 
2986 /// Represents a C array with an unspecified size. For example 'int A[]' has
2987 /// an IncompleteArrayType where the element type is 'int' and the size is
2988 /// unspecified.
2990  friend class ASTContext; // ASTContext creates these.
2991 
2993  ArraySizeModifier sm, unsigned tq)
2994  : ArrayType(IncompleteArray, et, can, sm, tq) {}
2995 
2996 public:
2997  friend class StmtIteratorBase;
2998 
2999  bool isSugared() const { return false; }
3000  QualType desugar() const { return QualType(this, 0); }
3001 
3002  static bool classof(const Type *T) {
3003  return T->getTypeClass() == IncompleteArray;
3004  }
3005 
3006  void Profile(llvm::FoldingSetNodeID &ID) {
3009  }
3010 
3011  static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
3012  ArraySizeModifier SizeMod, unsigned TypeQuals) {
3013  ID.AddPointer(ET.getAsOpaquePtr());
3014  ID.AddInteger(SizeMod);
3015  ID.AddInteger(TypeQuals);
3016  }
3017 };
3018 
3019 /// Represents a C array with a specified size that is not an
3020 /// integer-constant-expression. For example, 'int s[x+foo()]'.
3021 /// Since the size expression is an arbitrary expression, we store it as such.
3022 ///
3023 /// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
3024 /// should not be: two lexically equivalent variable array types could mean
3025 /// different things, for example, these variables do not have the same type
3026 /// dynamically:
3027 ///
3028 /// void foo(int x) {
3029 /// int Y[x];
3030 /// ++x;
3031 /// int Z[x];
3032 /// }
3034  friend class ASTContext; // ASTContext creates these.
3035 
3036  /// An assignment-expression. VLA's are only permitted within
3037  /// a function block.
3038  Stmt *SizeExpr;
3039 
3040  /// The range spanned by the left and right array brackets.
3041  SourceRange Brackets;
3042 
3044  ArraySizeModifier sm, unsigned tq,
3045  SourceRange brackets)
3046  : ArrayType(VariableArray, et, can, sm, tq, e),
3047  SizeExpr((Stmt*) e), Brackets(brackets) {}
3048 
3049 public:
3050  friend class StmtIteratorBase;
3051 
3052  Expr *getSizeExpr() const {
3053  // We use C-style casts instead of cast<> here because we do not wish
3054  // to have a dependency of Type.h on Stmt.h/Expr.h.
3055  return (Expr*) SizeExpr;
3056  }
3057 
3058  SourceRange getBracketsRange() const { return Brackets; }
3059  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3060  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3061 
3062  bool isSugared() const { return false; }
3063  QualType desugar() const { return QualType(this, 0); }
3064 
3065  static bool classof(const Type *T) {
3066  return T->getTypeClass() == VariableArray;
3067  }
3068 
3069  void Profile(llvm::FoldingSetNodeID &ID) {
3070  llvm_unreachable("Cannot unique VariableArrayTypes.");
3071  }
3072 };
3073 
3074 /// Represents an array type in C++ whose size is a value-dependent expression.
3075 ///
3076 /// For example:
3077 /// \code
3078 /// template<typename T, int Size>
3079 /// class array {
3080 /// T data[Size];
3081 /// };
3082 /// \endcode
3083 ///
3084 /// For these types, we won't actually know what the array bound is
3085 /// until template instantiation occurs, at which point this will
3086 /// become either a ConstantArrayType or a VariableArrayType.
3088  friend class ASTContext; // ASTContext creates these.
3089 
3090  const ASTContext &Context;
3091 
3092  /// An assignment expression that will instantiate to the
3093  /// size of the array.
3094  ///
3095  /// The expression itself might be null, in which case the array
3096  /// type will have its size deduced from an initializer.
3097  Stmt *SizeExpr;
3098 
3099  /// The range spanned by the left and right array brackets.
3100  SourceRange Brackets;
3101 
3102  DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
3103  Expr *e, ArraySizeModifier sm, unsigned tq,
3104  SourceRange brackets);
3105 
3106 public:
3107  friend class StmtIteratorBase;
3108 
3109  Expr *getSizeExpr() const {
3110  // We use C-style casts instead of cast<> here because we do not wish
3111  // to have a dependency of Type.h on Stmt.h/Expr.h.
3112  return (Expr*) SizeExpr;
3113  }
3114 
3115  SourceRange getBracketsRange() const { return Brackets; }
3116  SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3117  SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3118 
3119  bool isSugared() const { return false; }
3120  QualType desugar() const { return QualType(this, 0); }
3121 
3122  static bool classof(const Type *T) {
3123  return T->getTypeClass() == DependentSizedArray;
3124  }
3125 
3126  void Profile(llvm::FoldingSetNodeID &ID) {
3127  Profile(ID, Context, getElementType(),
3129  }
3130 
3131  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3132  QualType ET, ArraySizeModifier SizeMod,
3133  unsigned TypeQuals, Expr *E);
3134 };
3135 
3136 /// Represents an extended address space qualifier where the input address space
3137 /// value is dependent. Non-dependent address spaces are not represented with a
3138 /// special Type subclass; they are stored on an ExtQuals node as part of a QualType.
3139 ///
3140 /// For example:
3141 /// \code
3142 /// template<typename T, int AddrSpace>
3143 /// class AddressSpace {
3144 /// typedef T __attribute__((address_space(AddrSpace))) type;
3145 /// }
3146 /// \endcode
3147 class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
3148  friend class ASTContext;
3149 
3150  const ASTContext &Context;
3151  Expr *AddrSpaceExpr;
3152  QualType PointeeType;
3153  SourceLocation loc;
3154 
3155  DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType,
3156  QualType can, Expr *AddrSpaceExpr,
3157  SourceLocation loc);
3158 
3159 public:
3160  Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
3161  QualType getPointeeType() const { return PointeeType; }
3162  SourceLocation getAttributeLoc() const { return loc; }
3163 
3164  bool isSugared() const { return false; }
3165  QualType desugar() const { return QualType(this, 0); }
3166 
3167  static bool classof(const Type *T) {
3168  return T->getTypeClass() == DependentAddressSpace;
3169  }
3170 
3171  void Profile(llvm::FoldingSetNodeID &ID) {
3172  Profile(ID, Context, getPointeeType(), getAddrSpaceExpr());
3173  }
3174 
3175  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3176  QualType PointeeType, Expr *AddrSpaceExpr);
3177 };
3178 
3179 /// Represents an extended vector type where either the type or size is
3180 /// dependent.
3181 ///
3182 /// For example:
3183 /// \code
3184 /// template<typename T, int Size>
3185 /// class vector {
3186 /// typedef T __attribute__((ext_vector_type(Size))) type;
3187 /// }
3188 /// \endcode
3189 class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
3190  friend class ASTContext;
3191 
3192  const ASTContext &Context;
3193  Expr *SizeExpr;
3194 
3195  /// The element type of the array.
3196  QualType ElementType;
3197 
3198  SourceLocation loc;
3199 
3200  DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
3201  QualType can, Expr *SizeExpr, SourceLocation loc);
3202 
3203 public:
3204  Expr *getSizeExpr() const { return SizeExpr; }
3205  QualType getElementType() const { return ElementType; }
3206  SourceLocation getAttributeLoc() const { return loc; }
3207 
3208  bool isSugared() const { return false; }
3209  QualType desugar() const { return QualType(this, 0); }
3210 
3211  static bool classof(const Type *T) {
3212  return T->getTypeClass() == DependentSizedExtVector;
3213  }
3214 
3215  void Profile(llvm::FoldingSetNodeID &ID) {
3216  Profile(ID, Context, getElementType(), getSizeExpr());
3217  }
3218 
3219  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3220  QualType ElementType, Expr *SizeExpr);
3221 };
3222 
3223 
3224 /// Represents a GCC generic vector type. This type is created using
3225 /// __attribute__((vector_size(n)), where "n" specifies the vector size in
3226 /// bytes; or from an Altivec __vector or vector declaration.
3227 /// Since the constructor takes the number of vector elements, the
3228 /// client is responsible for converting the size into the number of elements.
3229 class VectorType : public Type, public llvm::FoldingSetNode {
3230 public:
3231  enum VectorKind {
3232  /// not a target-specific vector type
3234 
3235  /// is AltiVec vector
3237 
3238  /// is AltiVec 'vector Pixel'
3240 
3241  /// is AltiVec 'vector bool ...'
3243 
3244  /// is ARM Neon vector
3246 
3247  /// is ARM Neon polynomial vector
3249 
3250  /// is AArch64 SVE fixed-length data vector
3252 
3253  /// is AArch64 SVE fixed-length predicate vector
3255  };
3256 
3257 protected:
3258  friend class ASTContext; // ASTContext creates these.
3259 
3260  /// The element type of the vector.
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 
3269 public:
3271  unsigned getNumElements() const { return VectorTypeBits.NumElements; }
3272 
3273  bool isSugared() const { return false; }
3274  QualType desugar() const { return QualType(this, 0); }
3275 
3277  return VectorKind(VectorTypeBits.VecKind);
3278  }
3279 
3280  void Profile(llvm::FoldingSetNodeID &ID) {
3283  }
3284 
3285  static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3286  unsigned NumElements, TypeClass TypeClass,
3287  VectorKind VecKind) {
3288  ID.AddPointer(ElementType.getAsOpaquePtr());
3289  ID.AddInteger(NumElements);
3290  ID.AddInteger(TypeClass);
3291  ID.AddInteger(VecKind);
3292  }
3293 
3294  static bool classof(const Type *T) {
3295  return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
3296  }
3297 };
3298 
3299 /// Represents a vector type where either the type or size is dependent.
3300 ////
3301 /// For example:
3302 /// \code
3303 /// template<typename T, int Size>
3304 /// class vector {
3305 /// typedef T __attribute__((vector_size(Size))) type;
3306 /// }
3307 /// \endcode
3308 class DependentVectorType : public Type, public llvm::FoldingSetNode {
3309  friend class ASTContext;
3310 
3311  const ASTContext &Context;
3312  QualType ElementType;
3313  Expr *SizeExpr;
3314  SourceLocation Loc;
3315 
3316  DependentVectorType(const ASTContext &Context, QualType ElementType,
3317  QualType CanonType, Expr *SizeExpr,
3318  SourceLocation Loc, VectorType::VectorKind vecKind);
3319 
3320 public:
3321  Expr *getSizeExpr() const { return SizeExpr; }
3322  QualType getElementType() const { return ElementType; }
3323  SourceLocation getAttributeLoc() const { return Loc; }
3325  return VectorType::VectorKind(VectorTypeBits.VecKind);
3326  }
3327 
3328  bool isSugared() const { return false; }
3329  QualType desugar() const { return QualType(this, 0); }
3330 
3331  static bool classof(const Type *T) {
3332  return T->getTypeClass() == DependentVector;
3333  }
3334 
3335  void Profile(llvm::FoldingSetNodeID &ID) {
3336  Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind());
3337  }
3338 
3339  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3340  QualType ElementType, const Expr *SizeExpr,
3341  VectorType::VectorKind VecKind);
3342 };
3343 
3344 /// ExtVectorType - Extended vector type. This type is created using
3345 /// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
3346 /// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
3347 /// class enables syntactic extensions, like Vector Components for accessing
3348 /// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
3349 /// Shading Language).
3350 class ExtVectorType : public VectorType {
3351  friend class ASTContext; // ASTContext creates these.
3352 
3353  ExtVectorType(QualType vecType, unsigned nElements, QualType canonType)
3354  : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
3355 
3356 public:
3357  static int getPointAccessorIdx(char c) {
3358  switch (c) {
3359  default: return -1;
3360  case 'x': case 'r': return 0;
3361  case 'y': case 'g': return 1;
3362  case 'z': case 'b': return 2;
3363  case 'w': case 'a': return 3;
3364  }
3365  }
3366 
3367  static int getNumericAccessorIdx(char c) {
3368  switch (c) {
3369  default: return -1;
3370  case '0': return 0;
3371  case '1': return 1;
3372  case '2': return 2;
3373  case '3': return 3;
3374  case '4': return 4;
3375  case '5': return 5;
3376  case '6': return 6;
3377  case '7': return 7;
3378  case '8': return 8;
3379  case '9': return 9;
3380  case 'A':
3381  case 'a': return 10;
3382  case 'B':
3383  case 'b': return 11;
3384  case 'C':
3385  case 'c': return 12;
3386  case 'D':
3387  case 'd': return 13;
3388  case 'E':
3389  case 'e': return 14;
3390  case 'F':
3391  case 'f': return 15;
3392  }
3393  }
3394 
3395  static int getAccessorIdx(char c, bool isNumericAccessor) {
3396  if (isNumericAccessor)
3397  return getNumericAccessorIdx(c);
3398  else
3399  return getPointAccessorIdx(c);
3400  }
3401 
3402  bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
3403  if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
3404  return unsigned(idx-1) < getNumElements();
3405  return false;
3406  }
3407 
3408  bool isSugared() const { return false; }
3409  QualType desugar() const { return QualType(this, 0); }
3410 
3411  static bool classof(const Type *T) {
3412  return T->getTypeClass() == ExtVector;
3413  }
3414 };
3415 
3416 /// Represents a matrix type, as defined in the Matrix Types clang extensions.
3417 /// __attribute__((matrix_type(rows, columns))), where "rows" specifies
3418 /// number of rows and "columns" specifies the number of columns.
3419 class MatrixType : public Type, public llvm::FoldingSetNode {
3420 protected:
3421  friend class ASTContext;
3422 
3423  /// The element type of the matrix.
3425 
3426  MatrixType(QualType ElementTy, QualType CanonElementTy);
3427 
3428  MatrixType(TypeClass TypeClass, QualType ElementTy, QualType CanonElementTy,
3429  const Expr *RowExpr = nullptr, const Expr *ColumnExpr = nullptr);
3430 
3431 public:
3432  /// Returns type of the elements being stored in the matrix
3434 
3435  /// Valid elements types are the following:
3436  /// * an integer type (as in C2x 6.2.5p19), but excluding enumerated types
3437  /// and _Bool
3438  /// * the standard floating types float or double
3439  /// * a half-precision floating point type, if one is supported on the target
3440  static bool isValidElementType(QualType T) {
3441  return T->isDependentType() ||
3442  (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
3443  }
3444 
3445  bool isSugared() const { return false; }
3446  QualType desugar() const { return QualType(this, 0); }
3447 
3448  static bool classof(const Type *T) {
3449  return T->getTypeClass() == ConstantMatrix ||
3450  T->getTypeClass() == DependentSizedMatrix;
3451  }
3452 };
3453 
3454 /// Represents a concrete matrix type with constant number of rows and columns
3455 class ConstantMatrixType final : public MatrixType {
3456 protected:
3457  friend class ASTContext;
3458 
3459  /// Number of rows and columns.
3460  unsigned NumRows;
3461  unsigned NumColumns;
3462 
3463  static constexpr unsigned MaxElementsPerDimension = (1 << 20) - 1;
3464 
3465  ConstantMatrixType(QualType MatrixElementType, unsigned NRows,
3466  unsigned NColumns, QualType CanonElementType);
3467 
3468  ConstantMatrixType(TypeClass typeClass, QualType MatrixType, unsigned NRows,
3469  unsigned NColumns, QualType CanonElementType);
3470 
3471 public:
3472  /// Returns the number of rows in the matrix.
3473  unsigned getNumRows() const { return NumRows; }
3474 
3475  /// Returns the number of columns in the matrix.
3476  unsigned getNumColumns() const { return NumColumns; }
3477 
3478  /// Returns the number of elements required to embed the matrix into a vector.
3479  unsigned getNumElementsFlattened() const {
3480  return getNumRows() * getNumColumns();
3481  }
3482 
3483  /// Returns true if \p NumElements is a valid matrix dimension.
3484  static constexpr bool isDimensionValid(size_t NumElements) {
3485  return NumElements > 0 && NumElements <= MaxElementsPerDimension;
3486  }
3487 
3488  /// Returns the maximum number of elements per dimension.
3489  static constexpr unsigned getMaxElementsPerDimension() {
3490  return MaxElementsPerDimension;
3491  }
3492 
3493  void Profile(llvm::FoldingSetNodeID &ID) {
3495  getTypeClass());
3496  }
3497 
3498  static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3499  unsigned NumRows, unsigned NumColumns,
3500  TypeClass TypeClass) {
3501  ID.AddPointer(ElementType.getAsOpaquePtr());
3502  ID.AddInteger(NumRows);
3503  ID.AddInteger(NumColumns);
3504  ID.AddInteger(TypeClass);
3505  }
3506 
3507  static bool classof(const Type *T) {
3508  return T->getTypeClass() == ConstantMatrix;
3509  }
3510 };
3511 
3512 /// Represents a matrix type where the type and the number of rows and columns
3513 /// is dependent on a template.
3514 class DependentSizedMatrixType final : public MatrixType {
3515  friend class ASTContext;
3516 
3517  const ASTContext &Context;
3518  Expr *RowExpr;
3519  Expr *ColumnExpr;
3520 
3521  SourceLocation loc;
3522 
3524  QualType CanonicalType, Expr *RowExpr,
3525  Expr *ColumnExpr, SourceLocation loc);
3526 
3527 public:
3528  Expr *getRowExpr() const { return RowExpr; }
3529  Expr *getColumnExpr() const { return ColumnExpr; }
3530  SourceLocation getAttributeLoc() const { return loc; }
3531 
3532  static bool classof(const Type *T) {
3533  return T->getTypeClass() == DependentSizedMatrix;
3534  }
3535 
3536  void Profile(llvm::FoldingSetNodeID &ID) {
3537  Profile(ID, Context, getElementType(), getRowExpr(), getColumnExpr());
3538  }
3539 
3540  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3541  QualType ElementType, Expr *RowExpr, Expr *ColumnExpr);
3542 };
3543 
3544 /// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
3545 /// class of FunctionNoProtoType and FunctionProtoType.
3546 class FunctionType : public Type {
3547  // The type returned by the function.
3548  QualType ResultType;
3549 
3550 public:
3551  /// Interesting information about a specific parameter that can't simply
3552  /// be reflected in parameter's type. This is only used by FunctionProtoType
3553  /// but is in FunctionType to make this class available during the
3554  /// specification of the bases of FunctionProtoType.
3555  ///
3556  /// It makes sense to model language features this way when there's some
3557  /// sort of parameter-specific override (such as an attribute) that
3558  /// affects how the function is called. For example, the ARC ns_consumed
3559  /// attribute changes whether a parameter is passed at +0 (the default)
3560  /// or +1 (ns_consumed). This must be reflected in the function type,
3561  /// but isn't really a change to the parameter type.
3562  ///
3563  /// One serious disadvantage of modelling language features this way is
3564  /// that they generally do not work with language features that attempt
3565  /// to destructure types. For example, template argument deduction will
3566  /// not be able to match a parameter declared as
3567  /// T (*)(U)
3568  /// against an argument of type
3569  /// void (*)(__attribute__((ns_consumed)) id)
3570  /// because the substitution of T=void, U=id into the former will
3571  /// not produce the latter.
3573  enum {
3574  ABIMask = 0x0F,
3575  IsConsumed = 0x10,
3576  HasPassObjSize = 0x20,
3577  IsNoEscape = 0x40,
3578  };
3579  unsigned char Data = 0;
3580 
3581  public:
3582  ExtParameterInfo() = default;
3583 
3584  /// Return the ABI treatment of this parameter.
3585  ParameterABI getABI() const { return ParameterABI(Data & ABIMask); }
3587  ExtParameterInfo copy = *this;
3588  copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
3589  return copy;
3590  }
3591 
3592  /// Is this parameter considered "consumed" by Objective-C ARC?
3593  /// Consumed parameters must have retainable object type.
3594  bool isConsumed() const { return (Data & IsConsumed); }
3595  ExtParameterInfo withIsConsumed(bool consumed) const {
3596  ExtParameterInfo copy = *this;
3597  if (consumed)
3598  copy.Data |= IsConsumed;
3599  else
3600  copy.Data &= ~IsConsumed;
3601  return copy;
3602  }
3603 
3604  bool hasPassObjectSize() const { return Data & HasPassObjSize; }
3606  ExtParameterInfo Copy = *this;
3607  Copy.Data |= HasPassObjSize;
3608  return Copy;
3609  }
3610 
3611  bool isNoEscape() const { return Data & IsNoEscape; }
3612  ExtParameterInfo withIsNoEscape(bool NoEscape) const {
3613  ExtParameterInfo Copy = *this;
3614  if (NoEscape)
3615  Copy.Data |= IsNoEscape;
3616  else
3617  Copy.Data &= ~IsNoEscape;
3618  return Copy;
3619  }
3620 
3621  unsigned char getOpaqueValue() const { return Data; }
3622  static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
3623  ExtParameterInfo result;
3624  result.Data = data;
3625  return result;
3626  }
3627 
3629  return lhs.Data == rhs.Data;
3630  }
3631 
3633  return lhs.Data != rhs.Data;
3634  }
3635  };
3636 
3637  /// A class which abstracts out some details necessary for
3638  /// making a call.
3639  ///
3640  /// It is not actually used directly for storing this information in
3641  /// a FunctionType, although FunctionType does currently use the
3642  /// same bit-pattern.
3643  ///
3644  // If you add a field (say Foo), other than the obvious places (both,
3645  // constructors, compile failures), what you need to update is
3646  // * Operator==
3647  // * getFoo
3648  // * withFoo
3649  // * functionType. Add Foo, getFoo.
3650  // * ASTContext::getFooType
3651  // * ASTContext::mergeFunctionTypes
3652  // * FunctionNoProtoType::Profile
3653  // * FunctionProtoType::Profile
3654  // * TypePrinter::PrintFunctionProto
3655  // * AST read and write
3656  // * Codegen
3657  class ExtInfo {
3658  friend class FunctionType;
3659 
3660  // Feel free to rearrange or add bits, but if you go over 16, you'll need to
3661  // adjust the Bits field below, and if you add bits, you'll need to adjust
3662  // Type::FunctionTypeBitfields::ExtInfo as well.
3663 
3664  // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|cmsenscall|
3665  // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 | 12 |
3666  //
3667  // regparm is either 0 (no regparm attribute) or the regparm value+1.
3668  enum { CallConvMask = 0x1F };
3669  enum { NoReturnMask = 0x20 };
3670  enum { ProducesResultMask = 0x40 };
3671  enum { NoCallerSavedRegsMask = 0x80 };
3672  enum {
3673  RegParmMask = 0x700,
3674  RegParmOffset = 8
3675  };
3676  enum { NoCfCheckMask = 0x800 };
3677  enum { CmseNSCallMask = 0x1000 };
3678  uint16_t Bits = CC_C;
3679 
3680  ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
3681 
3682  public:
3683  // Constructor with no defaults. Use this when you know that you
3684  // have all the elements (when reading an AST file for example).
3685  ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
3686  bool producesResult, bool noCallerSavedRegs, bool NoCfCheck,
3687  bool cmseNSCall) {
3688  assert((!hasRegParm || regParm < 7) && "Invalid regparm value");
3689  Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) |
3690  (producesResult ? ProducesResultMask : 0) |
3691  (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) |
3692  (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) |
3693  (NoCfCheck ? NoCfCheckMask : 0) |
3694  (cmseNSCall ? CmseNSCallMask : 0);
3695  }
3696 
3697  // Constructor with all defaults. Use when for example creating a
3698  // function known to use defaults.
3699  ExtInfo() = default;
3700 
3701  // Constructor with just the calling convention, which is an important part
3702  // of the canonical type.
3703  ExtInfo(CallingConv CC) : Bits(CC) {}
3704 
3705  bool getNoReturn() const { return Bits & NoReturnMask; }
3706  bool getProducesResult() const { return Bits & ProducesResultMask; }
3707  bool getCmseNSCall() const { return Bits & CmseNSCallMask; }
3708  bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; }
3709  bool getNoCfCheck() const { return Bits & NoCfCheckMask; }
3710  bool getHasRegParm() const { return ((Bits & RegParmMask) >> RegParmOffset) != 0; }
3711 
3712  unsigned getRegParm() const {
3713  unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset;
3714  if (RegParm > 0)
3715  --RegParm;
3716  return RegParm;
3717  }
3718 
3719  CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
3720 
3721  bool operator==(ExtInfo Other) const {
3722  return Bits == Other.Bits;
3723  }
3724  bool operator!=(ExtInfo Other) const {
3725  return Bits != Other.Bits;
3726  }
3727 
3728  // Note that we don't have setters. That is by design, use
3729  // the following with methods instead of mutating these objects.
3730 
3731  ExtInfo withNoReturn(bool noReturn) const {
3732  if (noReturn)
3733  return ExtInfo(Bits | NoReturnMask);
3734  else
3735  return ExtInfo(Bits & ~NoReturnMask);
3736  }
3737 
3738  ExtInfo withProducesResult(bool producesResult) const {
3739  if (producesResult)
3740  return ExtInfo(Bits | ProducesResultMask);
3741  else
3742  return ExtInfo(Bits & ~ProducesResultMask);
3743  }
3744 
3745  ExtInfo withCmseNSCall(bool cmseNSCall) const {
3746  if (cmseNSCall)
3747  return ExtInfo(Bits | CmseNSCallMask);
3748  else
3749  return ExtInfo(Bits & ~CmseNSCallMask);
3750  }
3751 
3752  ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const {
3753  if (noCallerSavedRegs)
3754  return ExtInfo(Bits | NoCallerSavedRegsMask);
3755  else
3756  return ExtInfo(Bits & ~NoCallerSavedRegsMask);
3757  }
3758 
3759  ExtInfo withNoCfCheck(bool noCfCheck) const {
3760  if (noCfCheck)
3761  return ExtInfo(Bits | NoCfCheckMask);
3762  else
3763  return ExtInfo(Bits & ~NoCfCheckMask);
3764  }
3765 
3766  ExtInfo withRegParm(unsigned RegParm) const {
3767  assert(RegParm < 7 && "Invalid regparm value");
3768  return ExtInfo((Bits & ~RegParmMask) |
3769  ((RegParm + 1) << RegParmOffset));
3770  }
3771 
3773  return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
3774  }
3775 
3776  void Profile(llvm::FoldingSetNodeID &ID) const {
3777  ID.AddInteger(Bits);
3778  }
3779  };
3780 
3781  /// A simple holder for a QualType representing a type in an
3782  /// exception specification. Unfortunately needed by FunctionProtoType
3783  /// because TrailingObjects cannot handle repeated types.
3785 
3786  /// A simple holder for various uncommon bits which do not fit in
3787  /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the
3788  /// alignment of subsequent objects in TrailingObjects. You must update
3789  /// hasExtraBitfields in FunctionProtoType after adding extra data here.
3790  struct alignas(void *) FunctionTypeExtraBitfields {
3791  /// The number of types in the exception specification.
3792  /// A whole unsigned is not needed here and according to
3793  /// [implimits] 8 bits would be enough here.
3795  };
3796 
3797 protected:
3800  : Type(tc, Canonical, Dependence), ResultType(res) {
3801  FunctionTypeBits.ExtInfo = Info.Bits;
3802  }
3803 
3805  return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals);
3806  }
3807 
3808 public:
3809  QualType getReturnType() const { return ResultType; }
3810 
3811  bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
3812  unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
3813 
3814  /// Determine whether this function type includes the GNU noreturn
3815  /// attribute. The C++11 [[noreturn]] attribute does not affect the function
3816  /// type.
3817  bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
3818 
3819  bool getCmseNSCallAttr() const { return getExtInfo().getCmseNSCall(); }
3820  CallingConv getCallConv() const { return getExtInfo().getCC(); }
3821  ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
3822 
3823  static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0,
3824  "Const, volatile and restrict are assumed to be a subset of "
3825  "the fast qualifiers.");
3826 
3827  bool isConst() const { return getFastTypeQuals().hasConst(); }
3828  bool isVolatile() const { return getFastTypeQuals().hasVolatile(); }
3829  bool isRestrict() const { return getFastTypeQuals().hasRestrict(); }
3830 
3831  /// Determine the type of an expression that calls a function of
3832  /// this type.
3833  QualType getCallResultType(const ASTContext &Context) const {
3834  return getReturnType().getNonLValueExprType(Context);
3835  }
3836 
3837  static StringRef getNameForCallConv(CallingConv CC);
3838 
3839  static bool classof(const Type *T) {
3840  return T->getTypeClass() == FunctionNoProto ||
3841  T->getTypeClass() == FunctionProto;
3842  }
3843 };
3844 
3845 /// Represents a K&R-style 'int foo()' function, which has
3846 /// no information available about its arguments.
3847 class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
3848  friend class ASTContext; // ASTContext creates these.
3849 
3850  FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
3851  : FunctionType(FunctionNoProto, Result, Canonical,
3852  Result->getDependence() &
3853  ~(TypeDependence::DependentInstantiation |
3854  TypeDependence::UnexpandedPack),
3855  Info) {}
3856 
3857 public:
3858  // No additional state past what FunctionType provides.
3859 
3860  bool isSugared() const { return false; }
3861  QualType desugar() const { return QualType(this, 0); }
3862 
3863  void Profile(llvm::FoldingSetNodeID &ID) {
3865  }
3866 
3867  static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
3868  ExtInfo Info) {
3869  Info.Profile(ID);
3870  ID.AddPointer(ResultType.getAsOpaquePtr());
3871  }
3872 
3873  static bool classof(const Type *T) {
3874  return T->getTypeClass() == FunctionNoProto;
3875  }
3876 };
3877 
3878 /// Represents a prototype with parameter type info, e.g.
3879 /// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
3880 /// parameters, not as having a single void parameter. Such a type can have
3881 /// an exception specification, but this specification is not part of the
3882 /// canonical type. FunctionProtoType has several trailing objects, some of
3883 /// which optional. For more information about the trailing objects see
3884 /// the first comment inside FunctionProtoType.
3886  : public FunctionType,
3887  public llvm::FoldingSetNode,
3888  private llvm::TrailingObjects<
3889  FunctionProtoType, QualType, SourceLocation,
3890  FunctionType::FunctionTypeExtraBitfields, FunctionType::ExceptionType,
3891  Expr *, FunctionDecl *, FunctionType::ExtParameterInfo, Qualifiers> {
3892  friend class ASTContext; // ASTContext creates these.
3893  friend TrailingObjects;
3894 
3895  // FunctionProtoType is followed by several trailing objects, some of
3896  // which optional. They are in order:
3897  //
3898  // * An array of getNumParams() QualType holding the parameter types.
3899  // Always present. Note that for the vast majority of FunctionProtoType,
3900  // these will be the only trailing objects.
3901  //
3902  // * Optionally if the function is variadic, the SourceLocation of the
3903  // ellipsis.
3904  //
3905  // * Optionally if some extra data is stored in FunctionTypeExtraBitfields
3906  // (see FunctionTypeExtraBitfields and FunctionTypeBitfields):
3907  // a single FunctionTypeExtraBitfields. Present if and only if
3908  // hasExtraBitfields() is true.
3909  //
3910  // * Optionally exactly one of:
3911  // * an array of getNumExceptions() ExceptionType,
3912  // * a single Expr *,
3913  // * a pair of FunctionDecl *,
3914  // * a single FunctionDecl *
3915  // used to store information about the various types of exception
3916  // specification. See getExceptionSpecSize for the details.
3917  //
3918  // * Optionally an array of getNumParams() ExtParameterInfo holding
3919  // an ExtParameterInfo for each of the parameters. Present if and
3920  // only if hasExtParameterInfos() is true.
3921  //
3922  // * Optionally a Qualifiers object to represent extra qualifiers that can't
3923  // be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only
3924  // if hasExtQualifiers() is true.
3925  //
3926  // The optional FunctionTypeExtraBitfields has to be before the data
3927  // related to the exception specification since it contains the number
3928  // of exception types.
3929  //
3930  // We put the ExtParameterInfos last. If all were equal, it would make
3931  // more sense to put these before the exception specification, because
3932  // it's much easier to skip past them compared to the elaborate switch
3933  // required to skip the exception specification. However, all is not
3934  // equal; ExtParameterInfos are used to model very uncommon features,
3935  // and it's better not to burden the more common paths.
3936 
3937 public:
3938  /// Holds information about the various types of exception specification.
3939  /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is
3940  /// used to group together the various bits of information about the
3941  /// exception specification.
3943  /// The kind of exception specification this is.
3945 
3946  /// Explicitly-specified list of exception types.
3948 
3949  /// Noexcept expression, if this is a computed noexcept specification.
3950  Expr *NoexceptExpr = nullptr;
3951 
3952  /// The function whose exception specification this is, for
3953  /// EST_Unevaluated and EST_Uninstantiated.
3955 
3956  /// The function template whose exception specification this is instantiated
3957  /// from, for EST_Uninstantiated.
3959 
3960  ExceptionSpecInfo() = default;
3961 
3963  };
3964 
3965  /// Extra information about a function prototype. ExtProtoInfo is not
3966  /// stored as such in FunctionProtoType but is used to group together
3967  /// the various bits of extra information about a function prototype.
3968  struct ExtProtoInfo {
3970  bool Variadic : 1;
3977 
3979 
3982 
3984  ExtProtoInfo Result(*this);
3985  Result.ExceptionSpec = ESI;
3986  return Result;
3987  }
3988  };
3989 
3990 private:
3991  unsigned numTrailingObjects(OverloadToken<QualType>) const {
3992  return getNumParams();
3993  }
3994 
3995  unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
3996  return isVariadic();
3997  }
3998 
3999  unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const {
4000  return hasExtraBitfields();
4001  }
4002 
4003  unsigned numTrailingObjects(OverloadToken<ExceptionType>) const {
4004  return getExceptionSpecSize().NumExceptionType;
4005  }
4006 
4007  unsigned numTrailingObjects(OverloadToken<Expr *>) const {
4008  return getExceptionSpecSize().NumExprPtr;
4009  }
4010 
4011  unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const {
4012  return getExceptionSpecSize().NumFunctionDeclPtr;
4013  }
4014 
4015  unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const {
4016  return hasExtParameterInfos() ? getNumParams() : 0;
4017  }
4018 
4019  /// Determine whether there are any argument types that
4020  /// contain an unexpanded parameter pack.
4021  static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
4022  unsigned numArgs) {
4023  for (unsigned Idx = 0; Idx < numArgs; ++Idx)
4024  if (ArgArray[Idx]->containsUnexpandedParameterPack())
4025  return true;
4026 
4027  return false;
4028  }
4029 
4030  FunctionProtoType(QualType result, ArrayRef<QualType> params,
4031  QualType canonical, const ExtProtoInfo &epi);
4032 
4033  /// This struct is returned by getExceptionSpecSize and is used to
4034  /// translate an ExceptionSpecificationType to the number and kind
4035  /// of trailing objects related to the exception specification.
4036  struct ExceptionSpecSizeHolder {
4037  unsigned NumExceptionType;
4038  unsigned NumExprPtr;
4039  unsigned NumFunctionDeclPtr;
4040  };
4041 
4042  /// Return the number and kind of trailing objects
4043  /// related to the exception specification.
4044  static ExceptionSpecSizeHolder
4045  getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) {
4046  switch (EST) {
4047  case EST_None:
4048  case EST_DynamicNone:
4049  case EST_MSAny:
4050  case EST_BasicNoexcept:
4051  case EST_Unparsed:
4052  case EST_NoThrow:
4053  return {0, 0, 0};
4054 
4055  case EST_Dynamic:
4056  return {NumExceptions, 0, 0};
4057 
4058  case EST_DependentNoexcept:
4059  case EST_NoexceptFalse:
4060  case EST_NoexceptTrue:
4061  return {0, 1, 0};
4062 
4063  case EST_Uninstantiated:
4064  return {0, 0, 2};
4065 
4066  case EST_Unevaluated:
4067  return {0, 0, 1};
4068  }
4069  llvm_unreachable("bad exception specification kind");
4070  }
4071 
4072  /// Return the number and kind of trailing objects
4073  /// related to the exception specification.
4074  ExceptionSpecSizeHolder getExceptionSpecSize() const {
4075  return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions());
4076  }
4077 
4078  /// Whether the trailing FunctionTypeExtraBitfields is present.
4079  static bool hasExtraBitfields(ExceptionSpecificationType EST) {
4080  // If the exception spec type is EST_Dynamic then we have > 0 exception
4081  // types and the exact number is stored in FunctionTypeExtraBitfields.
4082  return EST == EST_Dynamic;
4083  }
4084 
4085  /// Whether the trailing FunctionTypeExtraBitfields is present.
4086  bool hasExtraBitfields() const {
4087  return hasExtraBitfields(getExceptionSpecType());
4088  }
4089 
4090  bool hasExtQualifiers() const {
4091  return FunctionTypeBits.HasExtQuals;
4092  }
4093 
4094 public:
4095  unsigned getNumParams() const { return FunctionTypeBits.NumParams; }
4096 
4097  QualType getParamType(unsigned i) const {
4098  assert(i < getNumParams() && "invalid parameter index");
4099  return param_type_begin()[i];
4100  }
4101 
4103  return llvm::makeArrayRef(param_type_begin(), param_type_end());
4104  }
4105 
4107  ExtProtoInfo EPI;
4108  EPI.ExtInfo = getExtInfo();
4109  EPI.Variadic = isVariadic();
4110  EPI.EllipsisLoc = getEllipsisLoc();
4113  EPI.TypeQuals = getMethodQuals();
4114  EPI.RefQualifier = getRefQualifier();
4116  return EPI;
4117  }
4118 
4119  /// Get the kind of exception specification on this function.
4121  return static_cast<ExceptionSpecificationType>(
4122  FunctionTypeBits.ExceptionSpecType);
4123  }
4124 
4125  /// Return whether this function has any kind of exception spec.
4126  bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; }
4127 
4128  /// Return whether this function has a dynamic (throw) exception spec.
4131  }
4132 
4133  /// Return whether this function has a noexcept exception spec.
4136  }
4137 
4138  /// Return whether this function has a dependent exception spec.
4139  bool hasDependentExceptionSpec() const;
4140 
4141  /// Return whether this function has an instantiation-dependent exception
4142  /// spec.
4144 
4145  /// Return all the available information about this type's exception spec.
4147  ExceptionSpecInfo Result;
4148  Result.Type = getExceptionSpecType();
4149  if (Result.Type == EST_Dynamic) {
4150  Result.Exceptions = exceptions();
4151  } else if (isComputedNoexcept(Result.Type)) {
4152  Result.NoexceptExpr = getNoexceptExpr();
4153  } else if (Result.Type == EST_Uninstantiated) {
4154  Result.SourceDecl = getExceptionSpecDecl();
4155  Result.SourceTemplate = getExceptionSpecTemplate();
4156  } else if (Result.Type == EST_Unevaluated) {
4157  Result.SourceDecl = getExceptionSpecDecl();
4158  }
4159  return Result;
4160  }
4161 
4162  /// Return the number of types in the exception specification.
4163  unsigned getNumExceptions() const {
4164  return getExceptionSpecType() == EST_Dynamic
4165  ? getTrailingObjects<FunctionTypeExtraBitfields>()
4166  ->NumExceptionType
4167  : 0;
4168  }
4169 
4170  /// Return the ith exception type, where 0 <= i < getNumExceptions().
4171  QualType getExceptionType(unsigned i) const {
4172  assert(i < getNumExceptions() && "Invalid exception number!");
4173  return exception_begin()[i];
4174  }
4175 
4176  /// Return the expression inside noexcept(expression), or a null pointer
4177  /// if there is none (because the exception spec is not of this form).
4180  return nullptr;
4181  return *getTrailingObjects<Expr *>();
4182  }
4183 
4184  /// If this function type has an exception specification which hasn't
4185  /// been determined yet (either because it has not been evaluated or because
4186  /// it has not been instantiated), this is the function whose exception
4187  /// specification is represented by this type.
4191  return nullptr;
4192  return getTrailingObjects<FunctionDecl *>()[0];
4193  }
4194 
4195  /// If this function type has an uninstantiated exception
4196  /// specification, this is the function whose exception specification
4197  /// should be instantiated to find the exception specification for
4198  /// this type.
4201  return nullptr;
4202  return getTrailingObjects<FunctionDecl *>()[1];
4203  }
4204 
4205  /// Determine whether this function type has a non-throwing exception
4206  /// specification.
4207  CanThrowResult canThrow() const;
4208 
4209  /// Determine whether this function type has a non-throwing exception
4210  /// specification. If this depends on template arguments, returns
4211  /// \c ResultIfDependent.
4212  bool isNothrow(bool ResultIfDependent = false) const {
4213  return ResultIfDependent ? canThrow() != CT_Can : canThrow() == CT_Cannot;
4214  }
4215 
4216  /// Whether this function prototype is variadic.
4217  bool isVariadic() const { return FunctionTypeBits.Variadic; }
4218 
4220  return isVariadic() ? *getTrailingObjects<SourceLocation>()
4221  : SourceLocation();
4222  }
4223 
4224  /// Determines whether this function prototype contains a
4225  /// parameter pack at the end.
4226  ///
4227  /// A function template whose last parameter is a parameter pack can be
4228  /// called with an arbitrary number of arguments, much like a variadic
4229  /// function.
4230  bool isTemplateVariadic() const;
4231 
4232  /// Whether this function prototype has a trailing return type.
4233  bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; }
4234 
4236  if (hasExtQualifiers())
4237  return *getTrailingObjects<Qualifiers>();
4238  else
4239  return getFastTypeQuals();
4240  }
4241 
4242  /// Retrieve the ref-qualifier associated with this function type.
4244  return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
4245  }
4246 
4248  using param_type_range = llvm::iterator_range<param_type_iterator>;
4249 
4252  }
4253 
4255  return getTrailingObjects<QualType>();
4256  }
4257 
4259  return param_type_begin() + getNumParams();
4260  }
4261 
4262  using exception_iterator = const QualType *;
4263 
4265  return llvm::makeArrayRef(exception_begin(), exception_end());
4266  }
4267 
4269  return reinterpret_cast<exception_iterator>(
4270  getTrailingObjects<ExceptionType>());
4271  }
4272 
4274  return exception_begin() + getNumExceptions();
4275  }
4276 
4277  /// Is there any interesting extra information for any of the parameters
4278  /// of this function type?
4279  bool hasExtParameterInfos() const {
4280  return FunctionTypeBits.HasExtParameterInfos;
4281  }
4282 
4284  assert(hasExtParameterInfos());
4285  return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(),
4286  getNumParams());
4287  }
4288 
4289  /// Return a pointer to the beginning of the array of extra parameter
4290  /// information, if present, or else null if none of the parameters
4291  /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos.
4293  if (!hasExtParameterInfos())
4294  return nullptr;
4295  return getTrailingObjects<ExtParameterInfo>();
4296  }
4297 
4299  assert(I < getNumParams() && "parameter index out of range");
4300  if (hasExtParameterInfos())
4301  return getTrailingObjects<ExtParameterInfo>()[I];
4302  return ExtParameterInfo();
4303  }
4304 
4305  ParameterABI getParameterABI(unsigned I) const {
4306  assert(I < getNumParams() && "parameter index out of range");
4307  if (hasExtParameterInfos())
4308  return getTrailingObjects<ExtParameterInfo>()[I].getABI();
4309  return ParameterABI::Ordinary;
4310  }
4311 
4312  bool isParamConsumed(unsigned I) const {
4313  assert(I < getNumParams() && "parameter index out of range");
4314  if (hasExtParameterInfos())
4315  return getTrailingObjects<ExtParameterInfo>()[I].isConsumed();
4316  return false;
4317  }
4318 
4319  bool isSugared() const { return false; }
4320  QualType desugar() const { return QualType(this, 0); }
4321 
4322  void printExceptionSpecification(raw_ostream &OS,
4323  const PrintingPolicy &Policy) const;
4324 
4325  static bool classof(const Type *T) {
4326  return T->getTypeClass() == FunctionProto;
4327  }
4328 
4329  void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
4330  static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
4331  param_type_iterator ArgTys, unsigned NumArgs,
4332  const ExtProtoInfo &EPI, const ASTContext &Context,
4333  bool Canonical);
4334 };
4335 
4336 /// Represents the dependent type named by a dependently-scoped
4337 /// typename using declaration, e.g.
4338 /// using typename Base<T>::foo;
4339 ///
4340 /// Template instantiation turns these into the underlying type.
4341 class UnresolvedUsingType : public Type {
4342  friend class ASTContext; // ASTContext creates these.
4343 
4345 
4347  : Type(UnresolvedUsing, QualType(),
4348  TypeDependence::DependentInstantiation),
4349  Decl(const_cast<UnresolvedUsingTypenameDecl *>(D)) {}
4350 
4351 public:
4353 
4354  bool isSugared() const { return false; }
4355  QualType desugar() const { return QualType(this, 0); }
4356 
4357  static bool classof(const Type *T) {
4358  return T->getTypeClass() == UnresolvedUsing;
4359  }
4360 
4361  void Profile(llvm::FoldingSetNodeID &ID) {
4362  return Profile(ID, Decl);
4363  }
4364 
4365  static void Profile(llvm::FoldingSetNodeID &ID,
4367  ID.AddPointer(D);
4368  }
4369 };
4370 
4371 class TypedefType : public Type {
4373 
4374 private:
4375  friend class ASTContext; // ASTContext creates these.
4376 
4377  TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType underlying,
4378  QualType can);
4379 
4380 public:
4381  TypedefNameDecl *getDecl() const { return Decl; }
4382 
4383  bool isSugared() const { return true; }
4384  QualType desugar() const;
4385 
4386  static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
4387 };
4388 
4389 /// Sugar type that represents a type that was qualified by a qualifier written
4390 /// as a macro invocation.
4391 class MacroQualifiedType : public Type {
4392  friend class ASTContext; // ASTContext creates these.
4393 
4394  QualType UnderlyingTy;
4395  const IdentifierInfo *MacroII;
4396 
4397  MacroQualifiedType(QualType UnderlyingTy, QualType CanonTy,
4398  const IdentifierInfo *MacroII)
4399  : Type(MacroQualified, CanonTy, UnderlyingTy->getDependence()),
4400  UnderlyingTy(UnderlyingTy), MacroII(MacroII) {
4401  assert(isa<AttributedType>(UnderlyingTy) &&
4402  "Expected a macro qualified type to only wrap attributed types.");
4403  }
4404 
4405 public:
4406  const IdentifierInfo *getMacroIdentifier() const { return MacroII; }
4407  QualType getUnderlyingType() const { return UnderlyingTy; }
4408 
4409  /// Return this attributed type's modified type with no qualifiers attached to
4410  /// it.
4411  QualType getModifiedType() const;
4412 
4413  bool isSugared() const { return true; }
4414  QualType desugar() const;
4415 
4416  static bool classof(const Type *T) {
4417  return T->getTypeClass() == MacroQualified;
4418  }
4419 };
4420 
4421 /// Represents a `typeof` (or __typeof__) expression (a GCC extension).
4422 class TypeOfExprType : public Type {
4423  Expr *TOExpr;
4424 
4425 protected:
4426  friend class ASTContext; // ASTContext creates these.
4427 
4428  TypeOfExprType(Expr *E, QualType can = QualType());
4429 
4430 public:
4431  Expr *getUnderlyingExpr() const { return TOExpr; }
4432 
4433  /// Remove a single level of sugar.
4434  QualType desugar() const;
4435 
4436  /// Returns whether this type directly provides sugar.
4437  bool isSugared() const;
4438 
4439  static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
4440 };
4441 
4442 /// Internal representation of canonical, dependent
4443 /// `typeof(expr)` types.
4444 ///
4445 /// This class is used internally by the ASTContext to manage
4446 /// canonical, dependent types, only. Clients will only see instances
4447 /// of this class via TypeOfExprType nodes.
4449  : public TypeOfExprType, public llvm::FoldingSetNode {
4450  const ASTContext &Context;
4451 
4452 public:
4454  : TypeOfExprType(E), Context(Context) {}
4455 
4456  void Profile(llvm::FoldingSetNodeID &ID) {
4457  Profile(ID, Context, getUnderlyingExpr());
4458  }
4459 
4460  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4461  Expr *E);
4462 };
4463 
4464 /// Represents `typeof(type)`, a GCC extension.
4465 class TypeOfType : public Type {
4466  friend class ASTContext; // ASTContext creates these.
4467 
4468  QualType TOType;
4469 
4470  TypeOfType(QualType T, QualType can)
4471  : Type(TypeOf, can, T->getDependence()), TOType(T) {
4472  assert(!isa<TypedefType>(can) && "Invalid canonical type");
4473  }
4474 
4475 public:
4476  QualType getUnderlyingType() const { return TOType; }
4477 
4478  /// Remove a single level of sugar.
4479  QualType desugar() const { return getUnderlyingType(); }
4480 
4481  /// Returns whether this type directly provides sugar.
4482  bool isSugared() const { return true; }
4483 
4484  static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
4485 };
4486 
4487 /// Represents the type `decltype(expr)` (C++11).
4488 class DecltypeType : public Type {
4489  Expr *E;
4490  QualType UnderlyingType;
4491 
4492 protected:
4493  friend class ASTContext; // ASTContext creates these.
4494 
4495  DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
4496 
4497 public:
4498  Expr *getUnderlyingExpr() const { return E; }
4499  QualType getUnderlyingType() const { return UnderlyingType; }
4500 
4501  /// Remove a single level of sugar.
4502  QualType desugar() const;
4503 
4504  /// Returns whether this type directly provides sugar.
4505  bool isSugared() const;
4506 
4507  static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
4508 };
4509 
4510 /// Internal representation of canonical, dependent
4511 /// decltype(expr) types.
4512 ///
4513 /// This class is used internally by the ASTContext to manage
4514 /// canonical, dependent types, only. Clients will only see instances
4515 /// of this class via DecltypeType nodes.
4516 class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
4517  const ASTContext &Context;
4518 
4519 public:
4520  DependentDecltypeType(const ASTContext &Context, Expr *E);
4521 
4522  void Profile(llvm::FoldingSetNodeID &ID) {
4523  Profile(ID, Context, getUnderlyingExpr());
4524  }
4525 
4526  static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4527  Expr *E);
4528 };
4529 
4530 /// A unary type transform, which is a type constructed from another.
4531 class UnaryTransformType : public Type {
4532 public:
4533  enum UTTKind {
4535  };
4536 
4537 private:
4538  /// The untransformed type.
4539  QualType BaseType;
4540 
4541  /// The transformed type if not dependent, otherwise the same as BaseType.
4542  QualType UnderlyingType;
4543 
4544  UTTKind UKind;
4545 
4546 protected:
4547  friend class ASTContext;
4548 
4549  UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
4550  QualType CanonicalTy);
4551 
4552 public:
4553  bool isSugared() const { return !isDependentType(); }
4554  QualType desugar() const { return UnderlyingType; }
4555 
4556  QualType getUnderlyingType() const { return UnderlyingType; }
4557  QualType getBaseType() const { return BaseType; }
4558 
4559  UTTKind getUTTKind() const { return UKind; }
4560 
4561  static bool classof(const Type *T) {
4562  return T->getTypeClass() == UnaryTransform;
4563  }
4564 };
4565 
4566 /// Internal representation of canonical, dependent
4567 /// __underlying_type(type) types.
4568 ///
4569 /// This class is used internally by the ASTContext to manage
4570 /// canonical, dependent types, only. Clients will only see instances
4571 /// of this class via UnaryTransformType nodes.
4573  public llvm::FoldingSetNode {
4574 public:
4575  DependentUnaryTransformType(const ASTContext &C, QualType BaseType,
4576  UTTKind UKind);
4577 
4578  void Profile(llvm::FoldingSetNodeID &ID) {
4580  }
4581 
4582  static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
4583  UTTKind UKind) {
4584  ID.AddPointer(BaseType.getAsOpaquePtr());
4585  ID.AddInteger((unsigned)UKind);
4586  }
4587 };
4588 
4589 class TagType : public Type {
4590  friend class ASTReader;
4591  template <class T> friend class serialization::AbstractTypeReader;
4592 
4593  /// Stores the TagDecl associated with this type. The decl may point to any
4594  /// TagDecl that declares the entity.
4595  TagDecl *decl;
4596 
4597 protected:
4598  TagType(TypeClass TC, const TagDecl *D, QualType can);
4599 
4600 public:
4601  TagDecl *getDecl() const;
4602 
4603  /// Determines whether this type is in the process of being defined.
4604  bool isBeingDefined() const;
4605 
4606  static bool classof(const Type *T) {
4607  return T->getTypeClass() == Enum || T->getTypeClass() == Record;
4608  }
4609 };
4610 
4611 /// A helper class that allows the use of isa/cast/dyncast
4612 /// to detect TagType objects of structs/unions/classes.
4613 class RecordType : public TagType {
4614 protected:
4615  friend class ASTContext; // ASTContext creates these.
4616 
4617  explicit RecordType(const RecordDecl *D)
4618  : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4620  : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4621 
4622 public:
4623  RecordDecl *getDecl() const {
4624  return reinterpret_cast<RecordDecl*>(TagType::getDecl());
4625  }
4626 
4627  /// Recursively check all fields in the record for const-ness. If any field
4628  /// is declared const, return true. Otherwise, return false.
4629  bool hasConstFields() const;
4630 
4631  bool isSugared() const { return false; }
4632  QualType desugar() const { return QualType(this, 0); }
4633 
4634  static bool classof(const Type *T) { return T->getTypeClass() == Record; }
4635 };
4636 
4637 /// A helper class that allows the use of isa/cast/dyncast
4638 /// to detect TagType objects of enums.
4639 class EnumType : public TagType {
4640  friend class ASTContext; // ASTContext creates these.
4641 
4642  explicit EnumType(const EnumDecl *D)
4643  : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4644 
4645 public:
4646  EnumDecl *getDecl() const {
4647  return reinterpret_cast<EnumDecl*>(TagType::getDecl());
4648  }
4649 
4650  bool isSugared() const { return false; }
4651  QualType desugar() const { return QualType(this, 0); }
4652 
4653  static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
4654 };
4655 
4656 /// An attributed type is a type to which a type attribute has been applied.
4657 ///
4658 /// The "modified type" is the fully-sugared type to which the attributed
4659 /// type was applied; generally it is not canonically equivalent to the
4660 /// attributed type. The "equivalent type" is the minimally-desugared type
4661 /// which the type is canonically equivalent to.
4662 ///
4663 /// For example, in the following attributed type:
4664 /// int32_t __attribute__((vector_size(16)))
4665 /// - the modified type is the TypedefType for int32_t
4666 /// - the equivalent type is VectorType(16, int32_t)
4667 /// - the canonical type is VectorType(16, int)
4668 class AttributedType : public Type, public llvm::FoldingSetNode {
4669 public:
4670  using Kind = attr::Kind;
4671 
4672 private:
4673  friend class ASTContext; // ASTContext creates these
4674 
4675  QualType ModifiedType;
4676  QualType EquivalentType;
4677 
4678  AttributedType(QualType canon, attr::Kind attrKind, QualType modified,
4679  QualType equivalent)
4680  : Type(Attributed, canon, equivalent->getDependence()),
4681  ModifiedType(modified), EquivalentType(equivalent) {
4682  AttributedTypeBits.AttrKind = attrKind;
4683  }
4684 
4685 public:
4686  Kind getAttrKind() const {
4687  return static_cast<Kind>(AttributedTypeBits.AttrKind);
4688  }
4689 
4690  QualType getModifiedType() const { return ModifiedType; }
4691  QualType getEquivalentType() const { return EquivalentType; }
4692 
4693  bool isSugared() const { return true; }
4694  QualType desugar() const { return getEquivalentType(); }
4695 
4696  /// Does this attribute behave like a type qualifier?
4697  ///
4698  /// A type qualifier adjusts a type to provide specialized rules for
4699  /// a specific object, like the standard const and volatile qualifiers.
4700  /// This includes attributes controlling things like nullability,
4701  /// address spaces, and ARC ownership. The value of the object is still
4702  /// largely described by the modified type.
4703  ///
4704  /// In contrast, many type attributes "rewrite" their modified type to
4705  /// produce a fundamentally different type, not necessarily related in any
4706  /// formalizable way to the original type. For example, calling convention
4707  /// and vector attributes are not simple type qualifiers.
4708  ///
4709  /// Type qualifiers are often, but not always, reflected in the canonical
4710  /// type.
4711  bool isQualifier() const;
4712 
4713  bool isMSTypeSpec() const;
4714 
4715  bool isCallingConv() const;
4716 
4718 
4719  /// Retrieve the attribute kind corresponding to the given
4720  /// nullability kind.
4722  switch (kind) {
4724  return attr::TypeNonNull;
4725 
4727  return attr::TypeNullable;
4728 
4730  return attr::TypeNullableResult;
4731 
4733  return attr::TypeNullUnspecified;
4734  }
4735  llvm_unreachable("Unknown nullability kind.");
4736  }
4737 
4738  /// Strip off the top-level nullability annotation on the given
4739  /// type, if it's there.
4740  ///
4741  /// \param T The type to strip. If the type is exactly an
4742  /// AttributedType specifying nullability (without looking through
4743  /// type sugar), the nullability is returned and this type changed
4744  /// to the underlying modified type.
4745  ///
4746  /// \returns the top-level nullability, if present.
4748 
4749  void Profile(llvm::FoldingSetNodeID &ID) {
4750  Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
4751  }
4752 
4753  static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
4754  QualType modified, QualType equivalent) {
4755  ID.AddInteger(attrKind);
4756  ID.AddPointer(modified.getAsOpaquePtr());
4757  ID.AddPointer(equivalent.getAsOpaquePtr());
4758  }
4759 
4760  static bool classof(const Type *T) {
4761  return T->getTypeClass() == Attributed;
4762  }
4763 };
4764 
4765 class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4766  friend class ASTContext; // ASTContext creates these
4767 
4768  // Helper data collector for canonical types.
4769  struct CanonicalTTPTInfo {
4770  unsigned Depth : 15;
4771  unsigned ParameterPack : 1;
4772  unsigned Index : 16;
4773  };
4774 
4775  union {
4776  // Info for the canonical type.
4777  CanonicalTTPTInfo CanTTPTInfo;
4778 
4779  // Info for the non-canonical type.
4781  };
4782 
4783  /// Build a non-canonical type.
4785  : Type(TemplateTypeParm, Canon,
4786  TypeDependence::DependentInstantiation |
4787  (Canon->getDependence() & TypeDependence::UnexpandedPack)),
4788  TTPDecl(TTPDecl) {}
4789 
4790  /// Build the canonical type.
4791  TemplateTypeParmType(unsigned D, unsigned I, bool PP)
4792  : Type(TemplateTypeParm, QualType(this, 0),
4793  TypeDependence::DependentInstantiation |
4794  (PP ? TypeDependence::UnexpandedPack : TypeDependence::None)) {
4795  CanTTPTInfo.Depth = D;
4796  CanTTPTInfo.Index = I;
4797  CanTTPTInfo.ParameterPack = PP;
4798  }
4799 
4800  const CanonicalTTPTInfo& getCanTTPTInfo() const {
4802  return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
4803  }
4804 
4805 public: