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