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