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