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