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