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