]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/include/clang/AST/Type.h
Merge lldb trunk r300422 and resolve conflicts.
[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 : 10;
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 10,
2945     // you'll need to adjust both the Bits field below and
2946     // Type::FunctionTypeBitfields.
2947
2948     //   |  CC  |noreturn|produces|regparm|
2949     //   |0 .. 4|   5    |    6   | 7 .. 9|
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 { RegParmMask = ~(CallConvMask | NoReturnMask | ProducesResultMask),
2956            RegParmOffset = 7 }; // Assumed to be the last field
2957
2958     uint16_t Bits;
2959
2960     ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
2961
2962     friend class FunctionType;
2963
2964    public:
2965     // Constructor with no defaults. Use this when you know that you
2966     // have all the elements (when reading an AST file for example).
2967     ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
2968             bool producesResult) {
2969       assert((!hasRegParm || regParm < 7) && "Invalid regparm value");
2970       Bits = ((unsigned) cc) |
2971              (noReturn ? NoReturnMask : 0) |
2972              (producesResult ? ProducesResultMask : 0) |
2973              (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0);
2974     }
2975
2976     // Constructor with all defaults. Use when for example creating a
2977     // function known to use defaults.
2978     ExtInfo() : Bits(CC_C) { }
2979
2980     // Constructor with just the calling convention, which is an important part
2981     // of the canonical type.
2982     ExtInfo(CallingConv CC) : Bits(CC) { }
2983
2984     bool getNoReturn() const { return Bits & NoReturnMask; }
2985     bool getProducesResult() const { return Bits & ProducesResultMask; }
2986     bool getHasRegParm() const { return (Bits >> RegParmOffset) != 0; }
2987     unsigned getRegParm() const {
2988       unsigned RegParm = Bits >> RegParmOffset;
2989       if (RegParm > 0)
2990         --RegParm;
2991       return RegParm;
2992     }
2993     CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
2994
2995     bool operator==(ExtInfo Other) const {
2996       return Bits == Other.Bits;
2997     }
2998     bool operator!=(ExtInfo Other) const {
2999       return Bits != Other.Bits;
3000     }
3001
3002     // Note that we don't have setters. That is by design, use
3003     // the following with methods instead of mutating these objects.
3004
3005     ExtInfo withNoReturn(bool noReturn) const {
3006       if (noReturn)
3007         return ExtInfo(Bits | NoReturnMask);
3008       else
3009         return ExtInfo(Bits & ~NoReturnMask);
3010     }
3011
3012     ExtInfo withProducesResult(bool producesResult) const {
3013       if (producesResult)
3014         return ExtInfo(Bits | ProducesResultMask);
3015       else
3016         return ExtInfo(Bits & ~ProducesResultMask);
3017     }
3018
3019     ExtInfo withRegParm(unsigned RegParm) const {
3020       assert(RegParm < 7 && "Invalid regparm value");
3021       return ExtInfo((Bits & ~RegParmMask) |
3022                      ((RegParm + 1) << RegParmOffset));
3023     }
3024
3025     ExtInfo withCallingConv(CallingConv cc) const {
3026       return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
3027     }
3028
3029     void Profile(llvm::FoldingSetNodeID &ID) const {
3030       ID.AddInteger(Bits);
3031     }
3032   };
3033
3034 protected:
3035   FunctionType(TypeClass tc, QualType res,
3036                QualType Canonical, bool Dependent,
3037                bool InstantiationDependent,
3038                bool VariablyModified, bool ContainsUnexpandedParameterPack,
3039                ExtInfo Info)
3040     : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
3041            ContainsUnexpandedParameterPack),
3042       ResultType(res) {
3043     FunctionTypeBits.ExtInfo = Info.Bits;
3044   }
3045   unsigned getTypeQuals() const { return FunctionTypeBits.TypeQuals; }
3046
3047 public:
3048   QualType getReturnType() const { return ResultType; }
3049
3050   bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
3051   unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
3052   /// Determine whether this function type includes the GNU noreturn
3053   /// attribute. The C++11 [[noreturn]] attribute does not affect the function
3054   /// type.
3055   bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
3056   CallingConv getCallConv() const { return getExtInfo().getCC(); }
3057   ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
3058   bool isConst() const { return getTypeQuals() & Qualifiers::Const; }
3059   bool isVolatile() const { return getTypeQuals() & Qualifiers::Volatile; }
3060   bool isRestrict() const { return getTypeQuals() & Qualifiers::Restrict; }
3061
3062   /// \brief Determine the type of an expression that calls a function of
3063   /// this type.
3064   QualType getCallResultType(const ASTContext &Context) const {
3065     return getReturnType().getNonLValueExprType(Context);
3066   }
3067
3068   static StringRef getNameForCallConv(CallingConv CC);
3069
3070   static bool classof(const Type *T) {
3071     return T->getTypeClass() == FunctionNoProto ||
3072            T->getTypeClass() == FunctionProto;
3073   }
3074 };
3075
3076 /// Represents a K&R-style 'int foo()' function, which has
3077 /// no information available about its arguments.
3078 class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
3079   FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
3080     : FunctionType(FunctionNoProto, Result, Canonical,
3081                    /*Dependent=*/false, /*InstantiationDependent=*/false,
3082                    Result->isVariablyModifiedType(),
3083                    /*ContainsUnexpandedParameterPack=*/false, Info) {}
3084
3085   friend class ASTContext;  // ASTContext creates these.
3086
3087 public:
3088   // No additional state past what FunctionType provides.
3089
3090   bool isSugared() const { return false; }
3091   QualType desugar() const { return QualType(this, 0); }
3092
3093   void Profile(llvm::FoldingSetNodeID &ID) {
3094     Profile(ID, getReturnType(), getExtInfo());
3095   }
3096   static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
3097                       ExtInfo Info) {
3098     Info.Profile(ID);
3099     ID.AddPointer(ResultType.getAsOpaquePtr());
3100   }
3101
3102   static bool classof(const Type *T) {
3103     return T->getTypeClass() == FunctionNoProto;
3104   }
3105 };
3106
3107 /// Represents a prototype with parameter type info, e.g.
3108 /// 'int foo(int)' or 'int foo(void)'.  'void' is represented as having no
3109 /// parameters, not as having a single void parameter. Such a type can have an
3110 /// exception specification, but this specification is not part of the canonical
3111 /// type.
3112 class FunctionProtoType : public FunctionType, public llvm::FoldingSetNode {
3113 public:
3114   /// Interesting information about a specific parameter that can't simply
3115   /// be reflected in parameter's type.
3116   ///
3117   /// It makes sense to model language features this way when there's some
3118   /// sort of parameter-specific override (such as an attribute) that
3119   /// affects how the function is called.  For example, the ARC ns_consumed
3120   /// attribute changes whether a parameter is passed at +0 (the default)
3121   /// or +1 (ns_consumed).  This must be reflected in the function type,
3122   /// but isn't really a change to the parameter type.
3123   ///
3124   /// One serious disadvantage of modelling language features this way is
3125   /// that they generally do not work with language features that attempt
3126   /// to destructure types.  For example, template argument deduction will
3127   /// not be able to match a parameter declared as
3128   ///   T (*)(U)
3129   /// against an argument of type
3130   ///   void (*)(__attribute__((ns_consumed)) id)
3131   /// because the substitution of T=void, U=id into the former will
3132   /// not produce the latter.
3133   class ExtParameterInfo {
3134     enum {
3135       ABIMask         = 0x0F,
3136       IsConsumed      = 0x10,
3137       HasPassObjSize  = 0x20,
3138     };
3139     unsigned char Data;
3140
3141   public:
3142     ExtParameterInfo() : Data(0) {}
3143
3144     /// Return the ABI treatment of this parameter.
3145     ParameterABI getABI() const {
3146       return ParameterABI(Data & ABIMask);
3147     }
3148     ExtParameterInfo withABI(ParameterABI kind) const {
3149       ExtParameterInfo copy = *this;
3150       copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
3151       return copy;
3152     }
3153
3154     /// Is this parameter considered "consumed" by Objective-C ARC?
3155     /// Consumed parameters must have retainable object type.
3156     bool isConsumed() const {
3157       return (Data & IsConsumed);
3158     }
3159     ExtParameterInfo withIsConsumed(bool consumed) const {
3160       ExtParameterInfo copy = *this;
3161       if (consumed) {
3162         copy.Data |= IsConsumed;
3163       } else {
3164         copy.Data &= ~IsConsumed;
3165       }
3166       return copy;
3167     }
3168
3169     bool hasPassObjectSize() const {
3170       return Data & HasPassObjSize;
3171     }
3172     ExtParameterInfo withHasPassObjectSize() const {
3173       ExtParameterInfo Copy = *this;
3174       Copy.Data |= HasPassObjSize;
3175       return Copy;
3176     }
3177
3178     unsigned char getOpaqueValue() const { return Data; }
3179     static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
3180       ExtParameterInfo result;
3181       result.Data = data;
3182       return result;
3183     }
3184
3185     friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3186       return lhs.Data == rhs.Data;
3187     }
3188     friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3189       return lhs.Data != rhs.Data;
3190     }
3191   };
3192
3193   struct ExceptionSpecInfo {
3194     ExceptionSpecInfo()
3195         : Type(EST_None), NoexceptExpr(nullptr),
3196           SourceDecl(nullptr), SourceTemplate(nullptr) {}
3197
3198     ExceptionSpecInfo(ExceptionSpecificationType EST)
3199         : Type(EST), NoexceptExpr(nullptr), SourceDecl(nullptr),
3200           SourceTemplate(nullptr) {}
3201
3202     /// The kind of exception specification this is.
3203     ExceptionSpecificationType Type;
3204     /// Explicitly-specified list of exception types.
3205     ArrayRef<QualType> Exceptions;
3206     /// Noexcept expression, if this is EST_ComputedNoexcept.
3207     Expr *NoexceptExpr;
3208     /// The function whose exception specification this is, for
3209     /// EST_Unevaluated and EST_Uninstantiated.
3210     FunctionDecl *SourceDecl;
3211     /// The function template whose exception specification this is instantiated
3212     /// from, for EST_Uninstantiated.
3213     FunctionDecl *SourceTemplate;
3214   };
3215
3216   /// Extra information about a function prototype.
3217   struct ExtProtoInfo {
3218     ExtProtoInfo()
3219         : Variadic(false), HasTrailingReturn(false), TypeQuals(0),
3220           RefQualifier(RQ_None), ExtParameterInfos(nullptr) {}
3221
3222     ExtProtoInfo(CallingConv CC)
3223         : ExtInfo(CC), Variadic(false), HasTrailingReturn(false), TypeQuals(0),
3224           RefQualifier(RQ_None), ExtParameterInfos(nullptr) {}
3225
3226     ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &O) {
3227       ExtProtoInfo Result(*this);
3228       Result.ExceptionSpec = O;
3229       return Result;
3230     }
3231
3232     FunctionType::ExtInfo ExtInfo;
3233     bool Variadic : 1;
3234     bool HasTrailingReturn : 1;
3235     unsigned char TypeQuals;
3236     RefQualifierKind RefQualifier;
3237     ExceptionSpecInfo ExceptionSpec;
3238     const ExtParameterInfo *ExtParameterInfos;
3239   };
3240
3241 private:
3242   /// \brief Determine whether there are any argument types that
3243   /// contain an unexpanded parameter pack.
3244   static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
3245                                                  unsigned numArgs) {
3246     for (unsigned Idx = 0; Idx < numArgs; ++Idx)
3247       if (ArgArray[Idx]->containsUnexpandedParameterPack())
3248         return true;
3249
3250     return false;
3251   }
3252
3253   FunctionProtoType(QualType result, ArrayRef<QualType> params,
3254                     QualType canonical, const ExtProtoInfo &epi);
3255
3256   /// The number of parameters this function has, not counting '...'.
3257   unsigned NumParams : 15;
3258
3259   /// The number of types in the exception spec, if any.
3260   unsigned NumExceptions : 9;
3261
3262   /// The type of exception specification this function has.
3263   unsigned ExceptionSpecType : 4;
3264
3265   /// Whether this function has extended parameter information.
3266   unsigned HasExtParameterInfos : 1;
3267
3268   /// Whether the function is variadic.
3269   unsigned Variadic : 1;
3270
3271   /// Whether this function has a trailing return type.
3272   unsigned HasTrailingReturn : 1;
3273
3274   // ParamInfo - There is an variable size array after the class in memory that
3275   // holds the parameter types.
3276
3277   // Exceptions - There is another variable size array after ArgInfo that
3278   // holds the exception types.
3279
3280   // NoexceptExpr - Instead of Exceptions, there may be a single Expr* pointing
3281   // to the expression in the noexcept() specifier.
3282
3283   // ExceptionSpecDecl, ExceptionSpecTemplate - Instead of Exceptions, there may
3284   // be a pair of FunctionDecl* pointing to the function which should be used to
3285   // instantiate this function type's exception specification, and the function
3286   // from which it should be instantiated.
3287
3288   // ExtParameterInfos - A variable size array, following the exception
3289   // specification and of length NumParams, holding an ExtParameterInfo
3290   // for each of the parameters.  This only appears if HasExtParameterInfos
3291   // is true.
3292
3293   friend class ASTContext;  // ASTContext creates these.
3294
3295   const ExtParameterInfo *getExtParameterInfosBuffer() const {
3296     assert(hasExtParameterInfos());
3297
3298     // Find the end of the exception specification.
3299     const char *ptr = reinterpret_cast<const char *>(exception_begin());
3300     ptr += getExceptionSpecSize();
3301
3302     return reinterpret_cast<const ExtParameterInfo *>(ptr);
3303   }
3304
3305   size_t getExceptionSpecSize() const {
3306     switch (getExceptionSpecType()) {
3307     case EST_None:             return 0;
3308     case EST_DynamicNone:      return 0;
3309     case EST_MSAny:            return 0;
3310     case EST_BasicNoexcept:    return 0;
3311     case EST_Unparsed:         return 0;
3312     case EST_Dynamic:          return getNumExceptions() * sizeof(QualType);
3313     case EST_ComputedNoexcept: return sizeof(Expr*);
3314     case EST_Uninstantiated:   return 2 * sizeof(FunctionDecl*);
3315     case EST_Unevaluated:      return sizeof(FunctionDecl*);
3316     }
3317     llvm_unreachable("bad exception specification kind");
3318   }
3319
3320 public:
3321   unsigned getNumParams() const { return NumParams; }
3322   QualType getParamType(unsigned i) const {
3323     assert(i < NumParams && "invalid parameter index");
3324     return param_type_begin()[i];
3325   }
3326   ArrayRef<QualType> getParamTypes() const {
3327     return llvm::makeArrayRef(param_type_begin(), param_type_end());
3328   }
3329
3330   ExtProtoInfo getExtProtoInfo() const {
3331     ExtProtoInfo EPI;
3332     EPI.ExtInfo = getExtInfo();
3333     EPI.Variadic = isVariadic();
3334     EPI.HasTrailingReturn = hasTrailingReturn();
3335     EPI.ExceptionSpec.Type = getExceptionSpecType();
3336     EPI.TypeQuals = static_cast<unsigned char>(getTypeQuals());
3337     EPI.RefQualifier = getRefQualifier();
3338     if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3339       EPI.ExceptionSpec.Exceptions = exceptions();
3340     } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
3341       EPI.ExceptionSpec.NoexceptExpr = getNoexceptExpr();
3342     } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
3343       EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3344       EPI.ExceptionSpec.SourceTemplate = getExceptionSpecTemplate();
3345     } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
3346       EPI.ExceptionSpec.SourceDecl = getExceptionSpecDecl();
3347     }
3348     if (hasExtParameterInfos())
3349       EPI.ExtParameterInfos = getExtParameterInfosBuffer();
3350     return EPI;
3351   }
3352
3353   /// Get the kind of exception specification on this function.
3354   ExceptionSpecificationType getExceptionSpecType() const {
3355     return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
3356   }
3357   /// Return whether this function has any kind of exception spec.
3358   bool hasExceptionSpec() const {
3359     return getExceptionSpecType() != EST_None;
3360   }
3361   /// Return whether this function has a dynamic (throw) exception spec.
3362   bool hasDynamicExceptionSpec() const {
3363     return isDynamicExceptionSpec(getExceptionSpecType());
3364   }
3365   /// Return whether this function has a noexcept exception spec.
3366   bool hasNoexceptExceptionSpec() const {
3367     return isNoexceptExceptionSpec(getExceptionSpecType());
3368   }
3369   /// Return whether this function has a dependent exception spec.
3370   bool hasDependentExceptionSpec() const;
3371   /// Return whether this function has an instantiation-dependent exception
3372   /// spec.
3373   bool hasInstantiationDependentExceptionSpec() const;
3374   /// Result type of getNoexceptSpec().
3375   enum NoexceptResult {
3376     NR_NoNoexcept,  ///< There is no noexcept specifier.
3377     NR_BadNoexcept, ///< The noexcept specifier has a bad expression.
3378     NR_Dependent,   ///< The noexcept specifier is dependent.
3379     NR_Throw,       ///< The noexcept specifier evaluates to false.
3380     NR_Nothrow      ///< The noexcept specifier evaluates to true.
3381   };
3382   /// Get the meaning of the noexcept spec on this function, if any.
3383   NoexceptResult getNoexceptSpec(const ASTContext &Ctx) const;
3384   unsigned getNumExceptions() const { return NumExceptions; }
3385   QualType getExceptionType(unsigned i) const {
3386     assert(i < NumExceptions && "Invalid exception number!");
3387     return exception_begin()[i];
3388   }
3389   Expr *getNoexceptExpr() const {
3390     if (getExceptionSpecType() != EST_ComputedNoexcept)
3391       return nullptr;
3392     // NoexceptExpr sits where the arguments end.
3393     return *reinterpret_cast<Expr *const *>(param_type_end());
3394   }
3395   /// \brief If this function type has an exception specification which hasn't
3396   /// been determined yet (either because it has not been evaluated or because
3397   /// it has not been instantiated), this is the function whose exception
3398   /// specification is represented by this type.
3399   FunctionDecl *getExceptionSpecDecl() const {
3400     if (getExceptionSpecType() != EST_Uninstantiated &&
3401         getExceptionSpecType() != EST_Unevaluated)
3402       return nullptr;
3403     return reinterpret_cast<FunctionDecl *const *>(param_type_end())[0];
3404   }
3405   /// \brief If this function type has an uninstantiated exception
3406   /// specification, this is the function whose exception specification
3407   /// should be instantiated to find the exception specification for
3408   /// this type.
3409   FunctionDecl *getExceptionSpecTemplate() const {
3410     if (getExceptionSpecType() != EST_Uninstantiated)
3411       return nullptr;
3412     return reinterpret_cast<FunctionDecl *const *>(param_type_end())[1];
3413   }
3414   /// Determine whether this function type has a non-throwing exception
3415   /// specification.
3416   CanThrowResult canThrow(const ASTContext &Ctx) const;
3417   /// Determine whether this function type has a non-throwing exception
3418   /// specification. If this depends on template arguments, returns
3419   /// \c ResultIfDependent.
3420   bool isNothrow(const ASTContext &Ctx, bool ResultIfDependent = false) const {
3421     return ResultIfDependent ? canThrow(Ctx) != CT_Can
3422                              : canThrow(Ctx) == CT_Cannot;
3423   }
3424
3425   bool isVariadic() const { return Variadic; }
3426
3427   /// Determines whether this function prototype contains a
3428   /// parameter pack at the end.
3429   ///
3430   /// A function template whose last parameter is a parameter pack can be
3431   /// called with an arbitrary number of arguments, much like a variadic
3432   /// function.
3433   bool isTemplateVariadic() const;
3434
3435   bool hasTrailingReturn() const { return HasTrailingReturn; }
3436
3437   unsigned getTypeQuals() const { return FunctionType::getTypeQuals(); }
3438
3439
3440   /// Retrieve the ref-qualifier associated with this function type.
3441   RefQualifierKind getRefQualifier() const {
3442     return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
3443   }
3444
3445   typedef const QualType *param_type_iterator;
3446   typedef llvm::iterator_range<param_type_iterator> param_type_range;
3447
3448   param_type_range param_types() const {
3449     return param_type_range(param_type_begin(), param_type_end());
3450   }
3451   param_type_iterator param_type_begin() const {
3452     return reinterpret_cast<const QualType *>(this+1);
3453   }
3454   param_type_iterator param_type_end() const {
3455     return param_type_begin() + NumParams;
3456   }
3457
3458   typedef const QualType *exception_iterator;
3459
3460   ArrayRef<QualType> exceptions() const {
3461     return llvm::makeArrayRef(exception_begin(), exception_end());
3462   }
3463   exception_iterator exception_begin() const {
3464     // exceptions begin where arguments end
3465     return param_type_end();
3466   }
3467   exception_iterator exception_end() const {
3468     if (getExceptionSpecType() != EST_Dynamic)
3469       return exception_begin();
3470     return exception_begin() + NumExceptions;
3471   }
3472
3473   /// Is there any interesting extra information for any of the parameters
3474   /// of this function type?
3475   bool hasExtParameterInfos() const { return HasExtParameterInfos; }
3476   ArrayRef<ExtParameterInfo> getExtParameterInfos() const {
3477     assert(hasExtParameterInfos());
3478     return ArrayRef<ExtParameterInfo>(getExtParameterInfosBuffer(),
3479                                       getNumParams());
3480   }
3481   /// Return a pointer to the beginning of the array of extra parameter
3482   /// information, if present, or else null if none of the parameters
3483   /// carry it.  This is equivalent to getExtProtoInfo().ExtParameterInfos.
3484   const ExtParameterInfo *getExtParameterInfosOrNull() const {
3485     if (!hasExtParameterInfos())
3486       return nullptr;
3487     return getExtParameterInfosBuffer();
3488   }
3489
3490   ExtParameterInfo getExtParameterInfo(unsigned I) const {
3491     assert(I < getNumParams() && "parameter index out of range");
3492     if (hasExtParameterInfos())
3493       return getExtParameterInfosBuffer()[I];
3494     return ExtParameterInfo();
3495   }
3496
3497   ParameterABI getParameterABI(unsigned I) const {
3498     assert(I < getNumParams() && "parameter index out of range");
3499     if (hasExtParameterInfos())
3500       return getExtParameterInfosBuffer()[I].getABI();
3501     return ParameterABI::Ordinary;
3502   }
3503
3504   bool isParamConsumed(unsigned I) const {
3505     assert(I < getNumParams() && "parameter index out of range");
3506     if (hasExtParameterInfos())
3507       return getExtParameterInfosBuffer()[I].isConsumed();
3508     return false;
3509   }
3510
3511   bool isSugared() const { return false; }
3512   QualType desugar() const { return QualType(this, 0); }
3513
3514   void printExceptionSpecification(raw_ostream &OS,
3515                                    const PrintingPolicy &Policy) const;
3516
3517   static bool classof(const Type *T) {
3518     return T->getTypeClass() == FunctionProto;
3519   }
3520
3521   void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
3522   static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
3523                       param_type_iterator ArgTys, unsigned NumArgs,
3524                       const ExtProtoInfo &EPI, const ASTContext &Context,
3525                       bool Canonical);
3526 };
3527
3528 /// \brief Represents the dependent type named by a dependently-scoped
3529 /// typename using declaration, e.g.
3530 ///   using typename Base<T>::foo;
3531 ///
3532 /// Template instantiation turns these into the underlying type.
3533 class UnresolvedUsingType : public Type {
3534   UnresolvedUsingTypenameDecl *Decl;
3535
3536   UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
3537     : Type(UnresolvedUsing, QualType(), true, true, false,
3538            /*ContainsUnexpandedParameterPack=*/false),
3539       Decl(const_cast<UnresolvedUsingTypenameDecl*>(D)) {}
3540   friend class ASTContext; // ASTContext creates these.
3541 public:
3542
3543   UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
3544
3545   bool isSugared() const { return false; }
3546   QualType desugar() const { return QualType(this, 0); }
3547
3548   static bool classof(const Type *T) {
3549     return T->getTypeClass() == UnresolvedUsing;
3550   }
3551
3552   void Profile(llvm::FoldingSetNodeID &ID) {
3553     return Profile(ID, Decl);
3554   }
3555   static void Profile(llvm::FoldingSetNodeID &ID,
3556                       UnresolvedUsingTypenameDecl *D) {
3557     ID.AddPointer(D);
3558   }
3559 };
3560
3561
3562 class TypedefType : public Type {
3563   TypedefNameDecl *Decl;
3564 protected:
3565   TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can)
3566     : Type(tc, can, can->isDependentType(),
3567            can->isInstantiationDependentType(),
3568            can->isVariablyModifiedType(),
3569            /*ContainsUnexpandedParameterPack=*/false),
3570       Decl(const_cast<TypedefNameDecl*>(D)) {
3571     assert(!isa<TypedefType>(can) && "Invalid canonical type");
3572   }
3573   friend class ASTContext;  // ASTContext creates these.
3574 public:
3575
3576   TypedefNameDecl *getDecl() const { return Decl; }
3577
3578   bool isSugared() const { return true; }
3579   QualType desugar() const;
3580
3581   static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
3582 };
3583
3584 /// Represents a `typeof` (or __typeof__) expression (a GCC extension).
3585 class TypeOfExprType : public Type {
3586   Expr *TOExpr;
3587
3588 protected:
3589   TypeOfExprType(Expr *E, QualType can = QualType());
3590   friend class ASTContext;  // ASTContext creates these.
3591 public:
3592   Expr *getUnderlyingExpr() const { return TOExpr; }
3593
3594   /// \brief Remove a single level of sugar.
3595   QualType desugar() const;
3596
3597   /// \brief Returns whether this type directly provides sugar.
3598   bool isSugared() const;
3599
3600   static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
3601 };
3602
3603 /// \brief Internal representation of canonical, dependent
3604 /// `typeof(expr)` types.
3605 ///
3606 /// This class is used internally by the ASTContext to manage
3607 /// canonical, dependent types, only. Clients will only see instances
3608 /// of this class via TypeOfExprType nodes.
3609 class DependentTypeOfExprType
3610   : public TypeOfExprType, public llvm::FoldingSetNode {
3611   const ASTContext &Context;
3612
3613 public:
3614   DependentTypeOfExprType(const ASTContext &Context, Expr *E)
3615     : TypeOfExprType(E), Context(Context) { }
3616
3617   void Profile(llvm::FoldingSetNodeID &ID) {
3618     Profile(ID, Context, getUnderlyingExpr());
3619   }
3620
3621   static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3622                       Expr *E);
3623 };
3624
3625 /// Represents `typeof(type)`, a GCC extension.
3626 class TypeOfType : public Type {
3627   QualType TOType;
3628   TypeOfType(QualType T, QualType can)
3629     : Type(TypeOf, can, T->isDependentType(),
3630            T->isInstantiationDependentType(),
3631            T->isVariablyModifiedType(),
3632            T->containsUnexpandedParameterPack()),
3633       TOType(T) {
3634     assert(!isa<TypedefType>(can) && "Invalid canonical type");
3635   }
3636   friend class ASTContext;  // ASTContext creates these.
3637 public:
3638   QualType getUnderlyingType() const { return TOType; }
3639
3640   /// \brief Remove a single level of sugar.
3641   QualType desugar() const { return getUnderlyingType(); }
3642
3643   /// \brief Returns whether this type directly provides sugar.
3644   bool isSugared() const { return true; }
3645
3646   static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
3647 };
3648
3649 /// Represents the type `decltype(expr)` (C++11).
3650 class DecltypeType : public Type {
3651   Expr *E;
3652   QualType UnderlyingType;
3653
3654 protected:
3655   DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
3656   friend class ASTContext;  // ASTContext creates these.
3657 public:
3658   Expr *getUnderlyingExpr() const { return E; }
3659   QualType getUnderlyingType() const { return UnderlyingType; }
3660
3661   /// \brief Remove a single level of sugar.
3662   QualType desugar() const;
3663
3664   /// \brief Returns whether this type directly provides sugar.
3665   bool isSugared() const;
3666
3667   static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
3668 };
3669
3670 /// \brief Internal representation of canonical, dependent
3671 /// decltype(expr) types.
3672 ///
3673 /// This class is used internally by the ASTContext to manage
3674 /// canonical, dependent types, only. Clients will only see instances
3675 /// of this class via DecltypeType nodes.
3676 class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
3677   const ASTContext &Context;
3678
3679 public:
3680   DependentDecltypeType(const ASTContext &Context, Expr *E);
3681
3682   void Profile(llvm::FoldingSetNodeID &ID) {
3683     Profile(ID, Context, getUnderlyingExpr());
3684   }
3685
3686   static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3687                       Expr *E);
3688 };
3689
3690 /// A unary type transform, which is a type constructed from another.
3691 class UnaryTransformType : public Type {
3692 public:
3693   enum UTTKind {
3694     EnumUnderlyingType
3695   };
3696
3697 private:
3698   /// The untransformed type.
3699   QualType BaseType;
3700   /// The transformed type if not dependent, otherwise the same as BaseType.
3701   QualType UnderlyingType;
3702
3703   UTTKind UKind;
3704 protected:
3705   UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
3706                      QualType CanonicalTy);
3707   friend class ASTContext;
3708 public:
3709   bool isSugared() const { return !isDependentType(); }
3710   QualType desugar() const { return UnderlyingType; }
3711
3712   QualType getUnderlyingType() const { return UnderlyingType; }
3713   QualType getBaseType() const { return BaseType; }
3714
3715   UTTKind getUTTKind() const { return UKind; }
3716
3717   static bool classof(const Type *T) {
3718     return T->getTypeClass() == UnaryTransform;
3719   }
3720 };
3721
3722 /// \brief Internal representation of canonical, dependent
3723 /// __underlying_type(type) types.
3724 ///
3725 /// This class is used internally by the ASTContext to manage
3726 /// canonical, dependent types, only. Clients will only see instances
3727 /// of this class via UnaryTransformType nodes.
3728 class DependentUnaryTransformType : public UnaryTransformType,
3729                                     public llvm::FoldingSetNode {
3730 public:
3731   DependentUnaryTransformType(const ASTContext &C, QualType BaseType,
3732                               UTTKind UKind);
3733   void Profile(llvm::FoldingSetNodeID &ID) {
3734     Profile(ID, getBaseType(), getUTTKind());
3735   }
3736
3737   static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
3738                       UTTKind UKind) {
3739     ID.AddPointer(BaseType.getAsOpaquePtr());
3740     ID.AddInteger((unsigned)UKind);
3741   }
3742 };
3743
3744 class TagType : public Type {
3745   /// Stores the TagDecl associated with this type. The decl may point to any
3746   /// TagDecl that declares the entity.
3747   TagDecl * decl;
3748
3749   friend class ASTReader;
3750
3751 protected:
3752   TagType(TypeClass TC, const TagDecl *D, QualType can);
3753
3754 public:
3755   TagDecl *getDecl() const;
3756
3757   /// Determines whether this type is in the process of being defined.
3758   bool isBeingDefined() const;
3759
3760   static bool classof(const Type *T) {
3761     return T->getTypeClass() >= TagFirst && T->getTypeClass() <= TagLast;
3762   }
3763 };
3764
3765 /// A helper class that allows the use of isa/cast/dyncast
3766 /// to detect TagType objects of structs/unions/classes.
3767 class RecordType : public TagType {
3768 protected:
3769   explicit RecordType(const RecordDecl *D)
3770     : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3771   explicit RecordType(TypeClass TC, RecordDecl *D)
3772     : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3773   friend class ASTContext;   // ASTContext creates these.
3774 public:
3775
3776   RecordDecl *getDecl() const {
3777     return reinterpret_cast<RecordDecl*>(TagType::getDecl());
3778   }
3779
3780   // FIXME: This predicate is a helper to QualType/Type. It needs to
3781   // recursively check all fields for const-ness. If any field is declared
3782   // const, it needs to return false.
3783   bool hasConstFields() const { return false; }
3784
3785   bool isSugared() const { return false; }
3786   QualType desugar() const { return QualType(this, 0); }
3787
3788   static bool classof(const Type *T) { return T->getTypeClass() == Record; }
3789 };
3790
3791 /// A helper class that allows the use of isa/cast/dyncast
3792 /// to detect TagType objects of enums.
3793 class EnumType : public TagType {
3794   explicit EnumType(const EnumDecl *D)
3795     : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) { }
3796   friend class ASTContext;   // ASTContext creates these.
3797 public:
3798
3799   EnumDecl *getDecl() const {
3800     return reinterpret_cast<EnumDecl*>(TagType::getDecl());
3801   }
3802
3803   bool isSugared() const { return false; }
3804   QualType desugar() const { return QualType(this, 0); }
3805
3806   static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
3807 };
3808
3809 /// An attributed type is a type to which a type attribute has been applied.
3810 ///
3811 /// The "modified type" is the fully-sugared type to which the attributed
3812 /// type was applied; generally it is not canonically equivalent to the
3813 /// attributed type. The "equivalent type" is the minimally-desugared type
3814 /// which the type is canonically equivalent to.
3815 ///
3816 /// For example, in the following attributed type:
3817 ///     int32_t __attribute__((vector_size(16)))
3818 ///   - the modified type is the TypedefType for int32_t
3819 ///   - the equivalent type is VectorType(16, int32_t)
3820 ///   - the canonical type is VectorType(16, int)
3821 class AttributedType : public Type, public llvm::FoldingSetNode {
3822 public:
3823   // It is really silly to have yet another attribute-kind enum, but
3824   // clang::attr::Kind doesn't currently cover the pure type attrs.
3825   enum Kind {
3826     // Expression operand.
3827     attr_address_space,
3828     attr_regparm,
3829     attr_vector_size,
3830     attr_neon_vector_type,
3831     attr_neon_polyvector_type,
3832
3833     FirstExprOperandKind = attr_address_space,
3834     LastExprOperandKind = attr_neon_polyvector_type,
3835
3836     // Enumerated operand (string or keyword).
3837     attr_objc_gc,
3838     attr_objc_ownership,
3839     attr_pcs,
3840     attr_pcs_vfp,
3841
3842     FirstEnumOperandKind = attr_objc_gc,
3843     LastEnumOperandKind = attr_pcs_vfp,
3844
3845     // No operand.
3846     attr_noreturn,
3847     attr_cdecl,
3848     attr_fastcall,
3849     attr_stdcall,
3850     attr_thiscall,
3851     attr_regcall,
3852     attr_pascal,
3853     attr_swiftcall,
3854     attr_vectorcall,
3855     attr_inteloclbicc,
3856     attr_ms_abi,
3857     attr_sysv_abi,
3858     attr_preserve_most,
3859     attr_preserve_all,
3860     attr_ptr32,
3861     attr_ptr64,
3862     attr_sptr,
3863     attr_uptr,
3864     attr_nonnull,
3865     attr_nullable,
3866     attr_null_unspecified,
3867     attr_objc_kindof,
3868     attr_objc_inert_unsafe_unretained,
3869   };
3870
3871 private:
3872   QualType ModifiedType;
3873   QualType EquivalentType;
3874
3875   friend class ASTContext; // creates these
3876
3877   AttributedType(QualType canon, Kind attrKind, QualType modified,
3878                  QualType equivalent)
3879       : Type(Attributed, canon, equivalent->isDependentType(),
3880              equivalent->isInstantiationDependentType(),
3881              equivalent->isVariablyModifiedType(),
3882              equivalent->containsUnexpandedParameterPack()),
3883         ModifiedType(modified), EquivalentType(equivalent) {
3884     AttributedTypeBits.AttrKind = attrKind;
3885   }
3886
3887 public:
3888   Kind getAttrKind() const {
3889     return static_cast<Kind>(AttributedTypeBits.AttrKind);
3890   }
3891
3892   QualType getModifiedType() const { return ModifiedType; }
3893   QualType getEquivalentType() const { return EquivalentType; }
3894
3895   bool isSugared() const { return true; }
3896   QualType desugar() const { return getEquivalentType(); }
3897
3898   /// Does this attribute behave like a type qualifier?
3899   ///
3900   /// A type qualifier adjusts a type to provide specialized rules for
3901   /// a specific object, like the standard const and volatile qualifiers.
3902   /// This includes attributes controlling things like nullability,
3903   /// address spaces, and ARC ownership.  The value of the object is still
3904   /// largely described by the modified type.
3905   ///
3906   /// In contrast, many type attributes "rewrite" their modified type to
3907   /// produce a fundamentally different type, not necessarily related in any
3908   /// formalizable way to the original type.  For example, calling convention
3909   /// and vector attributes are not simple type qualifiers.
3910   ///
3911   /// Type qualifiers are often, but not always, reflected in the canonical
3912   /// type.
3913   bool isQualifier() const;
3914
3915   bool isMSTypeSpec() const;
3916
3917   bool isCallingConv() const;
3918
3919   llvm::Optional<NullabilityKind> getImmediateNullability() const;
3920
3921   /// Retrieve the attribute kind corresponding to the given
3922   /// nullability kind.
3923   static Kind getNullabilityAttrKind(NullabilityKind kind) {
3924     switch (kind) {
3925     case NullabilityKind::NonNull:
3926       return attr_nonnull;
3927
3928     case NullabilityKind::Nullable:
3929       return attr_nullable;
3930
3931     case NullabilityKind::Unspecified:
3932       return attr_null_unspecified;
3933     }
3934     llvm_unreachable("Unknown nullability kind.");
3935   }
3936
3937   /// Strip off the top-level nullability annotation on the given
3938   /// type, if it's there.
3939   ///
3940   /// \param T The type to strip. If the type is exactly an
3941   /// AttributedType specifying nullability (without looking through
3942   /// type sugar), the nullability is returned and this type changed
3943   /// to the underlying modified type.
3944   ///
3945   /// \returns the top-level nullability, if present.
3946   static Optional<NullabilityKind> stripOuterNullability(QualType &T);
3947
3948   void Profile(llvm::FoldingSetNodeID &ID) {
3949     Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
3950   }
3951
3952   static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
3953                       QualType modified, QualType equivalent) {
3954     ID.AddInteger(attrKind);
3955     ID.AddPointer(modified.getAsOpaquePtr());
3956     ID.AddPointer(equivalent.getAsOpaquePtr());
3957   }
3958
3959   static bool classof(const Type *T) {
3960     return T->getTypeClass() == Attributed;
3961   }
3962 };
3963
3964 class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
3965   // Helper data collector for canonical types.
3966   struct CanonicalTTPTInfo {
3967     unsigned Depth : 15;
3968     unsigned ParameterPack : 1;
3969     unsigned Index : 16;
3970   };
3971
3972   union {
3973     // Info for the canonical type.
3974     CanonicalTTPTInfo CanTTPTInfo;
3975     // Info for the non-canonical type.
3976     TemplateTypeParmDecl *TTPDecl;
3977   };
3978
3979   /// Build a non-canonical type.
3980   TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
3981     : Type(TemplateTypeParm, Canon, /*Dependent=*/true,
3982            /*InstantiationDependent=*/true,
3983            /*VariablyModified=*/false,
3984            Canon->containsUnexpandedParameterPack()),
3985       TTPDecl(TTPDecl) { }
3986
3987   /// Build the canonical type.
3988   TemplateTypeParmType(unsigned D, unsigned I, bool PP)
3989     : Type(TemplateTypeParm, QualType(this, 0),
3990            /*Dependent=*/true,
3991            /*InstantiationDependent=*/true,
3992            /*VariablyModified=*/false, PP) {
3993     CanTTPTInfo.Depth = D;
3994     CanTTPTInfo.Index = I;
3995     CanTTPTInfo.ParameterPack = PP;
3996   }
3997
3998   friend class ASTContext;  // ASTContext creates these
3999
4000   const CanonicalTTPTInfo& getCanTTPTInfo() const {
4001     QualType Can = getCanonicalTypeInternal();
4002     return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
4003   }
4004
4005 public:
4006   unsigned getDepth() const { return getCanTTPTInfo().Depth; }
4007   unsigned getIndex() const { return getCanTTPTInfo().Index; }
4008   bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
4009
4010   TemplateTypeParmDecl *getDecl() const {
4011     return isCanonicalUnqualified() ? nullptr : TTPDecl;
4012   }
4013
4014   IdentifierInfo *getIdentifier() const;
4015
4016   bool isSugared() const { return false; }
4017   QualType desugar() const { return QualType(this, 0); }
4018
4019   void Profile(llvm::FoldingSetNodeID &ID) {
4020     Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
4021   }
4022
4023   static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
4024                       unsigned Index, bool ParameterPack,
4025                       TemplateTypeParmDecl *TTPDecl) {
4026     ID.AddInteger(Depth);
4027     ID.AddInteger(Index);
4028     ID.AddBoolean(ParameterPack);
4029     ID.AddPointer(TTPDecl);
4030   }
4031
4032   static bool classof(const Type *T) {
4033     return T->getTypeClass() == TemplateTypeParm;
4034   }
4035 };
4036
4037 /// \brief Represents the result of substituting a type for a template
4038 /// type parameter.
4039 ///
4040 /// Within an instantiated template, all template type parameters have
4041 /// been replaced with these.  They are used solely to record that a
4042 /// type was originally written as a template type parameter;
4043 /// therefore they are never canonical.
4044 class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4045   // The original type parameter.
4046   const TemplateTypeParmType *Replaced;
4047
4048   SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
4049     : Type(SubstTemplateTypeParm, Canon, Canon->isDependentType(),
4050            Canon->isInstantiationDependentType(),
4051            Canon->isVariablyModifiedType(),
4052            Canon->containsUnexpandedParameterPack()),
4053       Replaced(Param) { }
4054
4055   friend class ASTContext;
4056
4057 public:
4058   /// Gets the template parameter that was substituted for.
4059   const TemplateTypeParmType *getReplacedParameter() const {
4060     return Replaced;
4061   }
4062
4063   /// Gets the type that was substituted for the template
4064   /// parameter.
4065   QualType getReplacementType() const {
4066     return getCanonicalTypeInternal();
4067   }
4068
4069   bool isSugared() const { return true; }
4070   QualType desugar() const { return getReplacementType(); }
4071
4072   void Profile(llvm::FoldingSetNodeID &ID) {
4073     Profile(ID, getReplacedParameter(), getReplacementType());
4074   }
4075   static void Profile(llvm::FoldingSetNodeID &ID,
4076                       const TemplateTypeParmType *Replaced,
4077                       QualType Replacement) {
4078     ID.AddPointer(Replaced);
4079     ID.AddPointer(Replacement.getAsOpaquePtr());
4080   }
4081
4082   static bool classof(const Type *T) {
4083     return T->getTypeClass() == SubstTemplateTypeParm;
4084   }
4085 };
4086
4087 /// \brief Represents the result of substituting a set of types for a template
4088 /// type parameter pack.
4089 ///
4090 /// When a pack expansion in the source code contains multiple parameter packs
4091 /// and those parameter packs correspond to different levels of template
4092 /// parameter lists, this type node is used to represent a template type
4093 /// parameter pack from an outer level, which has already had its argument pack
4094 /// substituted but that still lives within a pack expansion that itself
4095 /// could not be instantiated. When actually performing a substitution into
4096 /// that pack expansion (e.g., when all template parameters have corresponding
4097 /// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
4098 /// at the current pack substitution index.
4099 class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
4100   /// \brief The original type parameter.
4101   const TemplateTypeParmType *Replaced;
4102
4103   /// \brief A pointer to the set of template arguments that this
4104   /// parameter pack is instantiated with.
4105   const TemplateArgument *Arguments;
4106
4107   /// \brief The number of template arguments in \c Arguments.
4108   unsigned NumArguments;
4109
4110   SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
4111                                 QualType Canon,
4112                                 const TemplateArgument &ArgPack);
4113
4114   friend class ASTContext;
4115
4116 public:
4117   IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
4118
4119   /// Gets the template parameter that was substituted for.
4120   const TemplateTypeParmType *getReplacedParameter() const {
4121     return Replaced;
4122   }
4123
4124   bool isSugared() const { return false; }
4125   QualType desugar() const { return QualType(this, 0); }
4126
4127   TemplateArgument getArgumentPack() const;
4128
4129   void Profile(llvm::FoldingSetNodeID &ID);
4130   static void Profile(llvm::FoldingSetNodeID &ID,
4131                       const TemplateTypeParmType *Replaced,
4132                       const TemplateArgument &ArgPack);
4133
4134   static bool classof(const Type *T) {
4135     return T->getTypeClass() == SubstTemplateTypeParmPack;
4136   }
4137 };
4138
4139 /// \brief Common base class for placeholders for types that get replaced by
4140 /// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced
4141 /// class template types, and (eventually) constrained type names from the C++
4142 /// Concepts TS.
4143 ///
4144 /// These types are usually a placeholder for a deduced type. However, before
4145 /// the initializer is attached, or (usually) if the initializer is
4146 /// type-dependent, there is no deduced type and the type is canonical. In
4147 /// the latter case, it is also a dependent type.
4148 class DeducedType : public Type {
4149 protected:
4150   DeducedType(TypeClass TC, QualType DeducedAsType, bool IsDependent,
4151               bool IsInstantiationDependent, bool ContainsParameterPack)
4152       : Type(TC,
4153              // FIXME: Retain the sugared deduced type?
4154              DeducedAsType.isNull() ? QualType(this, 0)
4155                                     : DeducedAsType.getCanonicalType(),
4156              IsDependent, IsInstantiationDependent,
4157              /*VariablyModified=*/false, ContainsParameterPack) {
4158     if (!DeducedAsType.isNull()) {
4159       if (DeducedAsType->isDependentType())
4160         setDependent();
4161       if (DeducedAsType->isInstantiationDependentType())
4162         setInstantiationDependent();
4163       if (DeducedAsType->containsUnexpandedParameterPack())
4164         setContainsUnexpandedParameterPack();
4165     }
4166   }
4167
4168 public:
4169   bool isSugared() const { return !isCanonicalUnqualified(); }
4170   QualType desugar() const { return getCanonicalTypeInternal(); }
4171
4172   /// \brief Get the type deduced for this placeholder type, or null if it's
4173   /// either not been deduced or was deduced to a dependent type.
4174   QualType getDeducedType() const {
4175     return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType();
4176   }
4177   bool isDeduced() const {
4178     return !isCanonicalUnqualified() || isDependentType();
4179   }
4180
4181   static bool classof(const Type *T) {
4182     return T->getTypeClass() == Auto ||
4183            T->getTypeClass() == DeducedTemplateSpecialization;
4184   }
4185 };
4186
4187 /// \brief Represents a C++11 auto or C++14 decltype(auto) type.
4188 class AutoType : public DeducedType, public llvm::FoldingSetNode {
4189   AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
4190            bool IsDeducedAsDependent)
4191       : DeducedType(Auto, DeducedAsType, IsDeducedAsDependent,
4192                     IsDeducedAsDependent, /*ContainsPack=*/false) {
4193     AutoTypeBits.Keyword = (unsigned)Keyword;
4194   }
4195
4196   friend class ASTContext;  // ASTContext creates these
4197
4198 public:
4199   bool isDecltypeAuto() const {
4200     return getKeyword() == AutoTypeKeyword::DecltypeAuto;
4201   }
4202   AutoTypeKeyword getKeyword() const {
4203     return (AutoTypeKeyword)AutoTypeBits.Keyword;
4204   }
4205
4206   void Profile(llvm::FoldingSetNodeID &ID) {
4207     Profile(ID, getDeducedType(), getKeyword(), isDependentType());
4208   }
4209
4210   static void Profile(llvm::FoldingSetNodeID &ID, QualType Deduced,
4211                       AutoTypeKeyword Keyword, bool IsDependent) {
4212     ID.AddPointer(Deduced.getAsOpaquePtr());
4213     ID.AddInteger((unsigned)Keyword);
4214     ID.AddBoolean(IsDependent);
4215   }
4216
4217   static bool classof(const Type *T) {
4218     return T->getTypeClass() == Auto;
4219   }
4220 };
4221
4222 /// \brief Represents a C++17 deduced template specialization type.
4223 class DeducedTemplateSpecializationType : public DeducedType,
4224                                           public llvm::FoldingSetNode {
4225   /// The name of the template whose arguments will be deduced.
4226   TemplateName Template;
4227
4228   DeducedTemplateSpecializationType(TemplateName Template,
4229                                     QualType DeducedAsType,
4230                                     bool IsDeducedAsDependent)
4231       : DeducedType(DeducedTemplateSpecialization, DeducedAsType,
4232                     IsDeducedAsDependent || Template.isDependent(),
4233                     IsDeducedAsDependent || Template.isInstantiationDependent(),
4234                     Template.containsUnexpandedParameterPack()),
4235         Template(Template) {}
4236
4237   friend class ASTContext;  // ASTContext creates these
4238
4239 public:
4240   /// Retrieve the name of the template that we are deducing.
4241   TemplateName getTemplateName() const { return Template;}
4242
4243   void Profile(llvm::FoldingSetNodeID &ID) {
4244     Profile(ID, getTemplateName(), getDeducedType(), isDependentType());
4245   }
4246
4247   static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template,
4248                       QualType Deduced, bool IsDependent) {
4249     Template.Profile(ID);
4250     ID.AddPointer(Deduced.getAsOpaquePtr());
4251     ID.AddBoolean(IsDependent);
4252   }
4253
4254   static bool classof(const Type *T) {
4255     return T->getTypeClass() == DeducedTemplateSpecialization;
4256   }
4257 };
4258
4259 /// \brief Represents a type template specialization; the template
4260 /// must be a class template, a type alias template, or a template
4261 /// template parameter.  A template which cannot be resolved to one of
4262 /// these, e.g. because it is written with a dependent scope
4263 /// specifier, is instead represented as a
4264 /// @c DependentTemplateSpecializationType.
4265 ///
4266 /// A non-dependent template specialization type is always "sugar",
4267 /// typically for a \c RecordType.  For example, a class template
4268 /// specialization type of \c vector<int> will refer to a tag type for
4269 /// the instantiation \c std::vector<int, std::allocator<int>>
4270 ///
4271 /// Template specializations are dependent if either the template or
4272 /// any of the template arguments are dependent, in which case the
4273 /// type may also be canonical.
4274 ///
4275 /// Instances of this type are allocated with a trailing array of
4276 /// TemplateArguments, followed by a QualType representing the
4277 /// non-canonical aliased type when the template is a type alias
4278 /// template.
4279 class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) TemplateSpecializationType
4280     : public Type,
4281       public llvm::FoldingSetNode {
4282   /// The name of the template being specialized.  This is
4283   /// either a TemplateName::Template (in which case it is a
4284   /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
4285   /// TypeAliasTemplateDecl*), a
4286   /// TemplateName::SubstTemplateTemplateParmPack, or a
4287   /// TemplateName::SubstTemplateTemplateParm (in which case the
4288   /// replacement must, recursively, be one of these).
4289   TemplateName Template;
4290
4291   /// The number of template arguments named in this class template
4292   /// specialization.
4293   unsigned NumArgs : 31;
4294
4295   /// Whether this template specialization type is a substituted type alias.
4296   unsigned TypeAlias : 1;
4297
4298   TemplateSpecializationType(TemplateName T,
4299                              ArrayRef<TemplateArgument> Args,
4300                              QualType Canon,
4301                              QualType Aliased);
4302
4303   friend class ASTContext;  // ASTContext creates these
4304
4305 public:
4306   /// Determine whether any of the given template arguments are dependent.
4307   static bool anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
4308                                             bool &InstantiationDependent);
4309
4310   static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &,
4311                                             bool &InstantiationDependent);
4312
4313   /// \brief Print a template argument list, including the '<' and '>'
4314   /// enclosing the template arguments.
4315   static void PrintTemplateArgumentList(raw_ostream &OS,
4316                                         ArrayRef<TemplateArgument> Args,
4317                                         const PrintingPolicy &Policy,
4318                                         bool SkipBrackets = false);
4319
4320   static void PrintTemplateArgumentList(raw_ostream &OS,
4321                                         ArrayRef<TemplateArgumentLoc> Args,
4322                                         const PrintingPolicy &Policy);
4323
4324   static void PrintTemplateArgumentList(raw_ostream &OS,
4325                                         const TemplateArgumentListInfo &,
4326                                         const PrintingPolicy &Policy);
4327
4328   /// True if this template specialization type matches a current
4329   /// instantiation in the context in which it is found.
4330   bool isCurrentInstantiation() const {
4331     return isa<InjectedClassNameType>(getCanonicalTypeInternal());
4332   }
4333
4334   /// \brief Determine if this template specialization type is for a type alias
4335   /// template that has been substituted.
4336   ///
4337   /// Nearly every template specialization type whose template is an alias
4338   /// template will be substituted. However, this is not the case when
4339   /// the specialization contains a pack expansion but the template alias
4340   /// does not have a corresponding parameter pack, e.g.,
4341   ///
4342   /// \code
4343   /// template<typename T, typename U, typename V> struct S;
4344   /// template<typename T, typename U> using A = S<T, int, U>;
4345   /// template<typename... Ts> struct X {
4346   ///   typedef A<Ts...> type; // not a type alias
4347   /// };
4348   /// \endcode
4349   bool isTypeAlias() const { return TypeAlias; }
4350
4351   /// Get the aliased type, if this is a specialization of a type alias
4352   /// template.
4353   QualType getAliasedType() const {
4354     assert(isTypeAlias() && "not a type alias template specialization");
4355     return *reinterpret_cast<const QualType*>(end());
4356   }
4357
4358   typedef const TemplateArgument * iterator;
4359
4360   iterator begin() const { return getArgs(); }
4361   iterator end() const; // defined inline in TemplateBase.h
4362
4363   /// Retrieve the name of the template that we are specializing.
4364   TemplateName getTemplateName() const { return Template; }
4365
4366   /// Retrieve the template arguments.
4367   const TemplateArgument *getArgs() const {
4368     return reinterpret_cast<const TemplateArgument *>(this + 1);
4369   }
4370
4371   /// Retrieve the number of template arguments.
4372   unsigned getNumArgs() const { return NumArgs; }
4373
4374   /// Retrieve a specific template argument as a type.
4375   /// \pre \c isArgType(Arg)
4376   const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4377
4378   ArrayRef<TemplateArgument> template_arguments() const {
4379     return {getArgs(), NumArgs};
4380   }
4381
4382   bool isSugared() const {
4383     return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
4384   }
4385   QualType desugar() const { return getCanonicalTypeInternal(); }
4386
4387   void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
4388     Profile(ID, Template, template_arguments(), Ctx);
4389     if (isTypeAlias())
4390       getAliasedType().Profile(ID);
4391   }
4392
4393   static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
4394                       ArrayRef<TemplateArgument> Args,
4395                       const ASTContext &Context);
4396
4397   static bool classof(const Type *T) {
4398     return T->getTypeClass() == TemplateSpecialization;
4399   }
4400 };
4401
4402 /// The injected class name of a C++ class template or class
4403 /// template partial specialization.  Used to record that a type was
4404 /// spelled with a bare identifier rather than as a template-id; the
4405 /// equivalent for non-templated classes is just RecordType.
4406 ///
4407 /// Injected class name types are always dependent.  Template
4408 /// instantiation turns these into RecordTypes.
4409 ///
4410 /// Injected class name types are always canonical.  This works
4411 /// because it is impossible to compare an injected class name type
4412 /// with the corresponding non-injected template type, for the same
4413 /// reason that it is impossible to directly compare template
4414 /// parameters from different dependent contexts: injected class name
4415 /// types can only occur within the scope of a particular templated
4416 /// declaration, and within that scope every template specialization
4417 /// will canonicalize to the injected class name (when appropriate
4418 /// according to the rules of the language).
4419 class InjectedClassNameType : public Type {
4420   CXXRecordDecl *Decl;
4421
4422   /// The template specialization which this type represents.
4423   /// For example, in
4424   ///   template <class T> class A { ... };
4425   /// this is A<T>, whereas in
4426   ///   template <class X, class Y> class A<B<X,Y> > { ... };
4427   /// this is A<B<X,Y> >.
4428   ///
4429   /// It is always unqualified, always a template specialization type,
4430   /// and always dependent.
4431   QualType InjectedType;
4432
4433   friend class ASTContext; // ASTContext creates these.
4434   friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
4435                           // currently suitable for AST reading, too much
4436                           // interdependencies.
4437   friend class ASTNodeImporter;
4438
4439   InjectedClassNameType(CXXRecordDecl *D, QualType TST)
4440     : Type(InjectedClassName, QualType(), /*Dependent=*/true,
4441            /*InstantiationDependent=*/true,
4442            /*VariablyModified=*/false,
4443            /*ContainsUnexpandedParameterPack=*/false),
4444       Decl(D), InjectedType(TST) {
4445     assert(isa<TemplateSpecializationType>(TST));
4446     assert(!TST.hasQualifiers());
4447     assert(TST->isDependentType());
4448   }
4449
4450 public:
4451   QualType getInjectedSpecializationType() const { return InjectedType; }
4452   const TemplateSpecializationType *getInjectedTST() const {
4453     return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
4454   }
4455   TemplateName getTemplateName() const {
4456     return getInjectedTST()->getTemplateName();
4457   }
4458
4459   CXXRecordDecl *getDecl() const;
4460
4461   bool isSugared() const { return false; }
4462   QualType desugar() const { return QualType(this, 0); }
4463
4464   static bool classof(const Type *T) {
4465     return T->getTypeClass() == InjectedClassName;
4466   }
4467 };
4468
4469 /// \brief The kind of a tag type.
4470 enum TagTypeKind {
4471   /// \brief The "struct" keyword.
4472   TTK_Struct,
4473   /// \brief The "__interface" keyword.
4474   TTK_Interface,
4475   /// \brief The "union" keyword.
4476   TTK_Union,
4477   /// \brief The "class" keyword.
4478   TTK_Class,
4479   /// \brief The "enum" keyword.
4480   TTK_Enum
4481 };
4482
4483 /// \brief The elaboration keyword that precedes a qualified type name or
4484 /// introduces an elaborated-type-specifier.
4485 enum ElaboratedTypeKeyword {
4486   /// \brief The "struct" keyword introduces the elaborated-type-specifier.
4487   ETK_Struct,
4488   /// \brief The "__interface" keyword introduces the elaborated-type-specifier.
4489   ETK_Interface,
4490   /// \brief The "union" keyword introduces the elaborated-type-specifier.
4491   ETK_Union,
4492   /// \brief The "class" keyword introduces the elaborated-type-specifier.
4493   ETK_Class,
4494   /// \brief The "enum" keyword introduces the elaborated-type-specifier.
4495   ETK_Enum,
4496   /// \brief The "typename" keyword precedes the qualified type name, e.g.,
4497   /// \c typename T::type.
4498   ETK_Typename,
4499   /// \brief No keyword precedes the qualified type name.
4500   ETK_None
4501 };
4502
4503 /// A helper class for Type nodes having an ElaboratedTypeKeyword.
4504 /// The keyword in stored in the free bits of the base class.
4505 /// Also provides a few static helpers for converting and printing
4506 /// elaborated type keyword and tag type kind enumerations.
4507 class TypeWithKeyword : public Type {
4508 protected:
4509   TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
4510                   QualType Canonical, bool Dependent,
4511                   bool InstantiationDependent, bool VariablyModified,
4512                   bool ContainsUnexpandedParameterPack)
4513   : Type(tc, Canonical, Dependent, InstantiationDependent, VariablyModified,
4514          ContainsUnexpandedParameterPack) {
4515     TypeWithKeywordBits.Keyword = Keyword;
4516   }
4517
4518 public:
4519   ElaboratedTypeKeyword getKeyword() const {
4520     return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
4521   }
4522
4523   /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
4524   static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
4525
4526   /// Converts a type specifier (DeclSpec::TST) into a tag type kind.
4527   /// It is an error to provide a type specifier which *isn't* a tag kind here.
4528   static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
4529
4530   /// Converts a TagTypeKind into an elaborated type keyword.
4531   static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
4532
4533   /// Converts an elaborated type keyword into a TagTypeKind.
4534   /// It is an error to provide an elaborated type keyword
4535   /// which *isn't* a tag kind here.
4536   static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
4537
4538   static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
4539
4540   static StringRef getKeywordName(ElaboratedTypeKeyword Keyword);
4541
4542   static StringRef getTagTypeKindName(TagTypeKind Kind) {
4543     return getKeywordName(getKeywordForTagTypeKind(Kind));
4544   }
4545
4546   class CannotCastToThisType {};
4547   static CannotCastToThisType classof(const Type *);
4548 };
4549
4550 /// \brief Represents a type that was referred to using an elaborated type
4551 /// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
4552 /// or both.
4553 ///
4554 /// This type is used to keep track of a type name as written in the
4555 /// source code, including tag keywords and any nested-name-specifiers.
4556 /// The type itself is always "sugar", used to express what was written
4557 /// in the source code but containing no additional semantic information.
4558 class ElaboratedType : public TypeWithKeyword, public llvm::FoldingSetNode {
4559
4560   /// The nested name specifier containing the qualifier.
4561   NestedNameSpecifier *NNS;
4562
4563   /// The type that this qualified name refers to.
4564   QualType NamedType;
4565
4566   ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
4567                  QualType NamedType, QualType CanonType)
4568     : TypeWithKeyword(Keyword, Elaborated, CanonType,
4569                       NamedType->isDependentType(),
4570                       NamedType->isInstantiationDependentType(),
4571                       NamedType->isVariablyModifiedType(),
4572                       NamedType->containsUnexpandedParameterPack()),
4573       NNS(NNS), NamedType(NamedType) {
4574     assert(!(Keyword == ETK_None && NNS == nullptr) &&
4575            "ElaboratedType cannot have elaborated type keyword "
4576            "and name qualifier both null.");
4577   }
4578
4579   friend class ASTContext;  // ASTContext creates these
4580
4581 public:
4582   ~ElaboratedType();
4583
4584   /// Retrieve the qualification on this type.
4585   NestedNameSpecifier *getQualifier() const { return NNS; }
4586
4587   /// Retrieve the type named by the qualified-id.
4588   QualType getNamedType() const { return NamedType; }
4589
4590   /// Remove a single level of sugar.
4591   QualType desugar() const { return getNamedType(); }
4592
4593   /// Returns whether this type directly provides sugar.
4594   bool isSugared() const { return true; }
4595
4596   void Profile(llvm::FoldingSetNodeID &ID) {
4597     Profile(ID, getKeyword(), NNS, NamedType);
4598   }
4599
4600   static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
4601                       NestedNameSpecifier *NNS, QualType NamedType) {
4602     ID.AddInteger(Keyword);
4603     ID.AddPointer(NNS);
4604     NamedType.Profile(ID);
4605   }
4606
4607   static bool classof(const Type *T) {
4608     return T->getTypeClass() == Elaborated;
4609   }
4610 };
4611
4612 /// \brief Represents a qualified type name for which the type name is
4613 /// dependent.
4614 ///
4615 /// DependentNameType represents a class of dependent types that involve a
4616 /// possibly dependent nested-name-specifier (e.g., "T::") followed by a
4617 /// name of a type. The DependentNameType may start with a "typename" (for a
4618 /// typename-specifier), "class", "struct", "union", or "enum" (for a
4619 /// dependent elaborated-type-specifier), or nothing (in contexts where we
4620 /// know that we must be referring to a type, e.g., in a base class specifier).
4621 /// Typically the nested-name-specifier is dependent, but in MSVC compatibility
4622 /// mode, this type is used with non-dependent names to delay name lookup until
4623 /// instantiation.
4624 class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
4625
4626   /// \brief The nested name specifier containing the qualifier.
4627   NestedNameSpecifier *NNS;
4628
4629   /// \brief The type that this typename specifier refers to.
4630   const IdentifierInfo *Name;
4631
4632   DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
4633                     const IdentifierInfo *Name, QualType CanonType)
4634     : TypeWithKeyword(Keyword, DependentName, CanonType, /*Dependent=*/true,
4635                       /*InstantiationDependent=*/true,
4636                       /*VariablyModified=*/false,
4637                       NNS->containsUnexpandedParameterPack()),
4638       NNS(NNS), Name(Name) {}
4639
4640   friend class ASTContext;  // ASTContext creates these
4641
4642 public:
4643   /// Retrieve the qualification on this type.
4644   NestedNameSpecifier *getQualifier() const { return NNS; }
4645
4646   /// Retrieve the type named by the typename specifier as an identifier.
4647   ///
4648   /// This routine will return a non-NULL identifier pointer when the
4649   /// form of the original typename was terminated by an identifier,
4650   /// e.g., "typename T::type".
4651   const IdentifierInfo *getIdentifier() const {
4652     return Name;
4653   }
4654
4655   bool isSugared() const { return false; }
4656   QualType desugar() const { return QualType(this, 0); }
4657
4658   void Profile(llvm::FoldingSetNodeID &ID) {
4659     Profile(ID, getKeyword(), NNS, Name);
4660   }
4661
4662   static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
4663                       NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
4664     ID.AddInteger(Keyword);
4665     ID.AddPointer(NNS);
4666     ID.AddPointer(Name);
4667   }
4668
4669   static bool classof(const Type *T) {
4670     return T->getTypeClass() == DependentName;
4671   }
4672 };
4673
4674 /// Represents a template specialization type whose template cannot be
4675 /// resolved, e.g.
4676 ///   A<T>::template B<T>
4677 class LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) DependentTemplateSpecializationType
4678     : public TypeWithKeyword,
4679       public llvm::FoldingSetNode {
4680
4681   /// The nested name specifier containing the qualifier.
4682   NestedNameSpecifier *NNS;
4683
4684   /// The identifier of the template.
4685   const IdentifierInfo *Name;
4686
4687   /// \brief The number of template arguments named in this class template
4688   /// specialization.
4689   unsigned NumArgs;
4690
4691   const TemplateArgument *getArgBuffer() const {
4692     return reinterpret_cast<const TemplateArgument*>(this+1);
4693   }
4694   TemplateArgument *getArgBuffer() {
4695     return reinterpret_cast<TemplateArgument*>(this+1);
4696   }
4697
4698   DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
4699                                       NestedNameSpecifier *NNS,
4700                                       const IdentifierInfo *Name,
4701                                       ArrayRef<TemplateArgument> Args,
4702                                       QualType Canon);
4703
4704   friend class ASTContext;  // ASTContext creates these
4705
4706 public:
4707   NestedNameSpecifier *getQualifier() const { return NNS; }
4708   const IdentifierInfo *getIdentifier() const { return Name; }
4709
4710   /// \brief Retrieve the template arguments.
4711   const TemplateArgument *getArgs() const {
4712     return getArgBuffer();
4713   }
4714
4715   /// \brief Retrieve the number of template arguments.
4716   unsigned getNumArgs() const { return NumArgs; }
4717
4718   const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4719
4720   ArrayRef<TemplateArgument> template_arguments() const {
4721     return {getArgs(), NumArgs};
4722   }
4723
4724   typedef const TemplateArgument * iterator;
4725   iterator begin() const { return getArgs(); }
4726   iterator end() const; // inline in TemplateBase.h
4727
4728   bool isSugared() const { return false; }
4729   QualType desugar() const { return QualType(this, 0); }
4730
4731   void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
4732     Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), NumArgs});
4733   }
4734
4735   static void Profile(llvm::FoldingSetNodeID &ID,
4736                       const ASTContext &Context,
4737                       ElaboratedTypeKeyword Keyword,
4738                       NestedNameSpecifier *Qualifier,
4739                       const IdentifierInfo *Name,
4740                       ArrayRef<TemplateArgument> Args);
4741
4742   static bool classof(const Type *T) {
4743     return T->getTypeClass() == DependentTemplateSpecialization;
4744   }
4745 };
4746
4747 /// \brief Represents a pack expansion of types.
4748 ///
4749 /// Pack expansions are part of C++11 variadic templates. A pack
4750 /// expansion contains a pattern, which itself contains one or more
4751 /// "unexpanded" parameter packs. When instantiated, a pack expansion
4752 /// produces a series of types, each instantiated from the pattern of
4753 /// the expansion, where the Ith instantiation of the pattern uses the
4754 /// Ith arguments bound to each of the unexpanded parameter packs. The
4755 /// pack expansion is considered to "expand" these unexpanded
4756 /// parameter packs.
4757 ///
4758 /// \code
4759 /// template<typename ...Types> struct tuple;
4760 ///
4761 /// template<typename ...Types>
4762 /// struct tuple_of_references {
4763 ///   typedef tuple<Types&...> type;
4764 /// };
4765 /// \endcode
4766 ///
4767 /// Here, the pack expansion \c Types&... is represented via a
4768 /// PackExpansionType whose pattern is Types&.
4769 class PackExpansionType : public Type, public llvm::FoldingSetNode {
4770   /// \brief The pattern of the pack expansion.
4771   QualType Pattern;
4772
4773   /// \brief The number of expansions that this pack expansion will
4774   /// generate when substituted (+1), or indicates that
4775   ///
4776   /// This field will only have a non-zero value when some of the parameter
4777   /// packs that occur within the pattern have been substituted but others have
4778   /// not.
4779   unsigned NumExpansions;
4780
4781   PackExpansionType(QualType Pattern, QualType Canon,
4782                     Optional<unsigned> NumExpansions)
4783     : Type(PackExpansion, Canon, /*Dependent=*/Pattern->isDependentType(),
4784            /*InstantiationDependent=*/true,
4785            /*VariablyModified=*/Pattern->isVariablyModifiedType(),
4786            /*ContainsUnexpandedParameterPack=*/false),
4787       Pattern(Pattern),
4788       NumExpansions(NumExpansions? *NumExpansions + 1: 0) { }
4789
4790   friend class ASTContext;  // ASTContext creates these
4791
4792 public:
4793   /// \brief Retrieve the pattern of this pack expansion, which is the
4794   /// type that will be repeatedly instantiated when instantiating the
4795   /// pack expansion itself.
4796   QualType getPattern() const { return Pattern; }
4797
4798   /// \brief Retrieve the number of expansions that this pack expansion will
4799   /// generate, if known.
4800   Optional<unsigned> getNumExpansions() const {
4801     if (NumExpansions)
4802       return NumExpansions - 1;
4803
4804     return None;
4805   }
4806
4807   bool isSugared() const { return !Pattern->isDependentType(); }
4808   QualType desugar() const { return isSugared() ? Pattern : QualType(this, 0); }
4809
4810   void Profile(llvm::FoldingSetNodeID &ID) {
4811     Profile(ID, getPattern(), getNumExpansions());
4812   }
4813
4814   static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
4815                       Optional<unsigned> NumExpansions) {
4816     ID.AddPointer(Pattern.getAsOpaquePtr());
4817     ID.AddBoolean(NumExpansions.hasValue());
4818     if (NumExpansions)
4819       ID.AddInteger(*NumExpansions);
4820   }
4821
4822   static bool classof(const Type *T) {
4823     return T->getTypeClass() == PackExpansion;
4824   }
4825 };
4826
4827 /// This class wraps the list of protocol qualifiers. For types that can
4828 /// take ObjC protocol qualifers, they can subclass this class.
4829 template <class T>
4830 class ObjCProtocolQualifiers {
4831 protected:
4832   ObjCProtocolQualifiers() {}
4833   ObjCProtocolDecl * const *getProtocolStorage() const {
4834     return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage();
4835   }
4836
4837   ObjCProtocolDecl **getProtocolStorage() {
4838     return static_cast<T*>(this)->getProtocolStorageImpl();
4839   }
4840   void setNumProtocols(unsigned N) {
4841     static_cast<T*>(this)->setNumProtocolsImpl(N);
4842   }
4843   void initialize(ArrayRef<ObjCProtocolDecl *> protocols) {
4844     setNumProtocols(protocols.size());
4845     assert(getNumProtocols() == protocols.size() &&
4846            "bitfield overflow in protocol count");
4847     if (!protocols.empty())
4848       memcpy(getProtocolStorage(), protocols.data(),
4849              protocols.size() * sizeof(ObjCProtocolDecl*));
4850   }
4851
4852 public:
4853   typedef ObjCProtocolDecl * const *qual_iterator;
4854   typedef llvm::iterator_range<qual_iterator> qual_range;
4855
4856   qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
4857   qual_iterator qual_begin() const { return getProtocolStorage(); }
4858   qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
4859
4860   bool qual_empty() const { return getNumProtocols() == 0; }
4861
4862   /// Return the number of qualifying protocols in this type, or 0 if
4863   /// there are none.
4864   unsigned getNumProtocols() const {
4865     return static_cast<const T*>(this)->getNumProtocolsImpl();
4866   }
4867
4868   /// Fetch a protocol by index.
4869   ObjCProtocolDecl *getProtocol(unsigned I) const {
4870     assert(I < getNumProtocols() && "Out-of-range protocol access");
4871     return qual_begin()[I];
4872   }
4873
4874   /// Retrieve all of the protocol qualifiers.
4875   ArrayRef<ObjCProtocolDecl *> getProtocols() const {
4876     return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols());
4877   }
4878 };
4879
4880 /// Represents a type parameter type in Objective C. It can take
4881 /// a list of protocols.
4882 class ObjCTypeParamType : public Type,
4883                           public ObjCProtocolQualifiers<ObjCTypeParamType>,
4884                           public llvm::FoldingSetNode {
4885   friend class ASTContext;
4886   friend class ObjCProtocolQualifiers<ObjCTypeParamType>;
4887
4888   /// The number of protocols stored on this type.
4889   unsigned NumProtocols : 6;
4890
4891   ObjCTypeParamDecl *OTPDecl;
4892   /// The protocols are stored after the ObjCTypeParamType node. In the
4893   /// canonical type, the list of protocols are sorted alphabetically
4894   /// and uniqued.
4895   ObjCProtocolDecl **getProtocolStorageImpl();
4896   /// Return the number of qualifying protocols in this interface type,
4897   /// or 0 if there are none.
4898   unsigned getNumProtocolsImpl() const {
4899     return NumProtocols;
4900   }
4901   void setNumProtocolsImpl(unsigned N) {
4902     NumProtocols = N;
4903   }
4904   ObjCTypeParamType(const ObjCTypeParamDecl *D,
4905                     QualType can,
4906                     ArrayRef<ObjCProtocolDecl *> protocols);
4907 public:
4908   bool isSugared() const { return true; }
4909   QualType desugar() const { return getCanonicalTypeInternal(); }
4910
4911   static bool classof(const Type *T) {
4912     return T->getTypeClass() == ObjCTypeParam;
4913   }
4914
4915   void Profile(llvm::FoldingSetNodeID &ID);
4916   static void Profile(llvm::FoldingSetNodeID &ID,
4917                       const ObjCTypeParamDecl *OTPDecl,
4918                       ArrayRef<ObjCProtocolDecl *> protocols);
4919
4920   ObjCTypeParamDecl *getDecl() const { return OTPDecl; }
4921 };
4922
4923 /// Represents a class type in Objective C.
4924 ///
4925 /// Every Objective C type is a combination of a base type, a set of
4926 /// type arguments (optional, for parameterized classes) and a list of
4927 /// protocols.
4928 ///
4929 /// Given the following declarations:
4930 /// \code
4931 ///   \@class C<T>;
4932 ///   \@protocol P;
4933 /// \endcode
4934 ///
4935 /// 'C' is an ObjCInterfaceType C.  It is sugar for an ObjCObjectType
4936 /// with base C and no protocols.
4937 ///
4938 /// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P].
4939 /// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no 
4940 /// protocol list.
4941 /// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*',
4942 /// and protocol list [P].
4943 ///
4944 /// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose
4945 /// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
4946 /// and no protocols.
4947 ///
4948 /// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType
4949 /// with base BuiltinType::ObjCIdType and protocol list [P].  Eventually
4950 /// this should get its own sugar class to better represent the source.
4951 class ObjCObjectType : public Type,
4952                        public ObjCProtocolQualifiers<ObjCObjectType> {
4953   friend class ObjCProtocolQualifiers<ObjCObjectType>;
4954   // ObjCObjectType.NumTypeArgs - the number of type arguments stored
4955   // after the ObjCObjectPointerType node.
4956   // ObjCObjectType.NumProtocols - the number of protocols stored
4957   // after the type arguments of ObjCObjectPointerType node.
4958   //
4959   // These protocols are those written directly on the type.  If
4960   // protocol qualifiers ever become additive, the iterators will need
4961   // to get kindof complicated.
4962   //
4963   // In the canonical object type, these are sorted alphabetically
4964   // and uniqued.
4965
4966   /// Either a BuiltinType or an InterfaceType or sugar for either.
4967   QualType BaseType;
4968
4969   /// Cached superclass type.
4970   mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool>
4971     CachedSuperClassType;
4972
4973   QualType *getTypeArgStorage();
4974   const QualType *getTypeArgStorage() const {
4975     return const_cast<ObjCObjectType *>(this)->getTypeArgStorage();
4976   }
4977
4978   ObjCProtocolDecl **getProtocolStorageImpl();
4979   /// Return the number of qualifying protocols in this interface type,
4980   /// or 0 if there are none.
4981   unsigned getNumProtocolsImpl() const {
4982     return ObjCObjectTypeBits.NumProtocols;
4983   }
4984   void setNumProtocolsImpl(unsigned N) {
4985     ObjCObjectTypeBits.NumProtocols = N;
4986   }
4987
4988 protected:
4989   ObjCObjectType(QualType Canonical, QualType Base,
4990                  ArrayRef<QualType> typeArgs,
4991                  ArrayRef<ObjCProtocolDecl *> protocols,
4992                  bool isKindOf);
4993
4994   enum Nonce_ObjCInterface { Nonce_ObjCInterface };
4995   ObjCObjectType(enum Nonce_ObjCInterface)
4996         : Type(ObjCInterface, QualType(), false, false, false, false),
4997       BaseType(QualType(this_(), 0)) {
4998     ObjCObjectTypeBits.NumProtocols = 0;
4999     ObjCObjectTypeBits.NumTypeArgs = 0;
5000     ObjCObjectTypeBits.IsKindOf = 0;
5001   }
5002
5003   void computeSuperClassTypeSlow() const;
5004
5005 public:
5006   /// Gets the base type of this object type.  This is always (possibly
5007   /// sugar for) one of:
5008   ///  - the 'id' builtin type (as opposed to the 'id' type visible to the
5009   ///    user, which is a typedef for an ObjCObjectPointerType)
5010   ///  - the 'Class' builtin type (same caveat)
5011   ///  - an ObjCObjectType (currently always an ObjCInterfaceType)
5012   QualType getBaseType() const { return BaseType; }
5013
5014   bool isObjCId() const {
5015     return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
5016   }
5017   bool isObjCClass() const {
5018     return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
5019   }
5020   bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
5021   bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
5022   bool isObjCUnqualifiedIdOrClass() const {
5023     if (!qual_empty()) return false;
5024     if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
5025       return T->getKind() == BuiltinType::ObjCId ||
5026              T->getKind() == BuiltinType::ObjCClass;
5027     return false;
5028   }
5029   bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
5030   bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
5031
5032   /// Gets the interface declaration for this object type, if the base type
5033   /// really is an interface.
5034   ObjCInterfaceDecl *getInterface() const;
5035
5036   /// Determine whether this object type is "specialized", meaning
5037   /// that it has type arguments.
5038   bool isSpecialized() const;
5039
5040   /// Determine whether this object type was written with type arguments.
5041   bool isSpecializedAsWritten() const {
5042     return ObjCObjectTypeBits.NumTypeArgs > 0;
5043   }
5044
5045   /// Determine whether this object type is "unspecialized", meaning
5046   /// that it has no type arguments.
5047   bool isUnspecialized() const { return !isSpecialized(); }
5048
5049   /// Determine whether this object type is "unspecialized" as
5050   /// written, meaning that it has no type arguments.
5051   bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5052
5053   /// Retrieve the type arguments of this object type (semantically).
5054   ArrayRef<QualType> getTypeArgs() const;
5055
5056   /// Retrieve the type arguments of this object type as they were
5057   /// written.
5058   ArrayRef<QualType> getTypeArgsAsWritten() const {
5059     return llvm::makeArrayRef(getTypeArgStorage(),
5060                               ObjCObjectTypeBits.NumTypeArgs);
5061   }
5062
5063   /// Whether this is a "__kindof" type as written.
5064   bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; }
5065
5066   /// Whether this ia a "__kindof" type (semantically).
5067   bool isKindOfType() const;
5068
5069   /// Retrieve the type of the superclass of this object type.
5070   ///
5071   /// This operation substitutes any type arguments into the
5072   /// superclass of the current class type, potentially producing a
5073   /// specialization of the superclass type. Produces a null type if
5074   /// there is no superclass.
5075   QualType getSuperClassType() const {
5076     if (!CachedSuperClassType.getInt())
5077       computeSuperClassTypeSlow();
5078
5079     assert(CachedSuperClassType.getInt() && "Superclass not set?");
5080     return QualType(CachedSuperClassType.getPointer(), 0);
5081   }
5082
5083   /// Strip off the Objective-C "kindof" type and (with it) any
5084   /// protocol qualifiers.
5085   QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const;
5086
5087   bool isSugared() const { return false; }
5088   QualType desugar() const { return QualType(this, 0); }
5089
5090   static bool classof(const Type *T) {
5091     return T->getTypeClass() == ObjCObject ||
5092            T->getTypeClass() == ObjCInterface;
5093   }
5094 };
5095
5096 /// A class providing a concrete implementation
5097 /// of ObjCObjectType, so as to not increase the footprint of
5098 /// ObjCInterfaceType.  Code outside of ASTContext and the core type
5099 /// system should not reference this type.
5100 class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
5101   friend class ASTContext;
5102
5103   // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
5104   // will need to be modified.
5105
5106   ObjCObjectTypeImpl(QualType Canonical, QualType Base,
5107                      ArrayRef<QualType> typeArgs,
5108                      ArrayRef<ObjCProtocolDecl *> protocols,
5109                      bool isKindOf)
5110     : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {}
5111
5112 public:
5113   void Profile(llvm::FoldingSetNodeID &ID);
5114   static void Profile(llvm::FoldingSetNodeID &ID,
5115                       QualType Base,
5116                       ArrayRef<QualType> typeArgs,
5117                       ArrayRef<ObjCProtocolDecl *> protocols,
5118                       bool isKindOf);
5119 };
5120
5121 inline QualType *ObjCObjectType::getTypeArgStorage() {
5122   return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1);
5123 }
5124
5125 inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() {
5126     return reinterpret_cast<ObjCProtocolDecl**>(
5127              getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs);
5128 }
5129
5130 inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() {
5131     return reinterpret_cast<ObjCProtocolDecl**>(
5132              static_cast<ObjCTypeParamType*>(this)+1);
5133 }
5134
5135 /// Interfaces are the core concept in Objective-C for object oriented design.
5136 /// They basically correspond to C++ classes.  There are two kinds of interface
5137 /// types: normal interfaces like `NSString`, and qualified interfaces, which
5138 /// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`.
5139 ///
5140 /// ObjCInterfaceType guarantees the following properties when considered
5141 /// as a subtype of its superclass, ObjCObjectType:
5142 ///   - There are no protocol qualifiers.  To reinforce this, code which
5143 ///     tries to invoke the protocol methods via an ObjCInterfaceType will
5144 ///     fail to compile.
5145 ///   - It is its own base type.  That is, if T is an ObjCInterfaceType*,
5146 ///     T->getBaseType() == QualType(T, 0).
5147 class ObjCInterfaceType : public ObjCObjectType {
5148   mutable ObjCInterfaceDecl *Decl;
5149
5150   ObjCInterfaceType(const ObjCInterfaceDecl *D)
5151     : ObjCObjectType(Nonce_ObjCInterface),
5152       Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
5153   friend class ASTContext;  // ASTContext creates these.
5154   friend class ASTReader;
5155   friend class ObjCInterfaceDecl;
5156
5157 public:
5158   /// Get the declaration of this interface.
5159   ObjCInterfaceDecl *getDecl() const { return Decl; }
5160
5161   bool isSugared() const { return false; }
5162   QualType desugar() const { return QualType(this, 0); }
5163
5164   static bool classof(const Type *T) {
5165     return T->getTypeClass() == ObjCInterface;
5166   }
5167
5168   // Nonsense to "hide" certain members of ObjCObjectType within this
5169   // class.  People asking for protocols on an ObjCInterfaceType are
5170   // not going to get what they want: ObjCInterfaceTypes are
5171   // guaranteed to have no protocols.
5172   enum {
5173     qual_iterator,
5174     qual_begin,
5175     qual_end,
5176     getNumProtocols,
5177     getProtocol
5178   };
5179 };
5180
5181 inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
5182   QualType baseType = getBaseType();
5183   while (const ObjCObjectType *ObjT = baseType->getAs<ObjCObjectType>()) {
5184     if (const ObjCInterfaceType *T = dyn_cast<ObjCInterfaceType>(ObjT))
5185       return T->getDecl();
5186
5187     baseType = ObjT->getBaseType();
5188   }
5189
5190   return nullptr;
5191 }
5192
5193 /// Represents a pointer to an Objective C object.
5194 ///
5195 /// These are constructed from pointer declarators when the pointee type is
5196 /// an ObjCObjectType (or sugar for one).  In addition, the 'id' and 'Class'
5197 /// types are typedefs for these, and the protocol-qualified types 'id<P>'
5198 /// and 'Class<P>' are translated into these.
5199 ///
5200 /// Pointers to pointers to Objective C objects are still PointerTypes;
5201 /// only the first level of pointer gets it own type implementation.
5202 class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
5203   QualType PointeeType;
5204
5205   ObjCObjectPointerType(QualType Canonical, QualType Pointee)
5206     : Type(ObjCObjectPointer, Canonical,
5207            Pointee->isDependentType(),
5208            Pointee->isInstantiationDependentType(),
5209            Pointee->isVariablyModifiedType(),
5210            Pointee->containsUnexpandedParameterPack()),
5211       PointeeType(Pointee) {}
5212   friend class ASTContext;  // ASTContext creates these.
5213
5214 public:
5215   /// Gets the type pointed to by this ObjC pointer.
5216   /// The result will always be an ObjCObjectType or sugar thereof.
5217   QualType getPointeeType() const { return PointeeType; }
5218
5219   /// Gets the type pointed to by this ObjC pointer.  Always returns non-null.
5220   ///
5221   /// This method is equivalent to getPointeeType() except that
5222   /// it discards any typedefs (or other sugar) between this
5223   /// type and the "outermost" object type.  So for:
5224   /// \code
5225   ///   \@class A; \@protocol P; \@protocol Q;
5226   ///   typedef A<P> AP;
5227   ///   typedef A A1;
5228   ///   typedef A1<P> A1P;
5229   ///   typedef A1P<Q> A1PQ;
5230   /// \endcode
5231   /// For 'A*', getObjectType() will return 'A'.
5232   /// For 'A<P>*', getObjectType() will return 'A<P>'.
5233   /// For 'AP*', getObjectType() will return 'A<P>'.
5234   /// For 'A1*', getObjectType() will return 'A'.
5235   /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
5236   /// For 'A1P*', getObjectType() will return 'A1<P>'.
5237   /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
5238   ///   adding protocols to a protocol-qualified base discards the
5239   ///   old qualifiers (for now).  But if it didn't, getObjectType()
5240   ///   would return 'A1P<Q>' (and we'd have to make iterating over
5241   ///   qualifiers more complicated).
5242   const ObjCObjectType *getObjectType() const {
5243     return PointeeType->castAs<ObjCObjectType>();
5244   }
5245
5246   /// If this pointer points to an Objective C
5247   /// \@interface type, gets the type for that interface.  Any protocol
5248   /// qualifiers on the interface are ignored.
5249   ///
5250   /// \return null if the base type for this pointer is 'id' or 'Class'
5251   const ObjCInterfaceType *getInterfaceType() const;
5252
5253   /// If this pointer points to an Objective \@interface
5254   /// type, gets the declaration for that interface.
5255   ///
5256   /// \return null if the base type for this pointer is 'id' or 'Class'
5257   ObjCInterfaceDecl *getInterfaceDecl() const {
5258     return getObjectType()->getInterface();
5259   }
5260
5261   /// True if this is equivalent to the 'id' type, i.e. if
5262   /// its object type is the primitive 'id' type with no protocols.
5263   bool isObjCIdType() const {
5264     return getObjectType()->isObjCUnqualifiedId();
5265   }
5266
5267   /// True if this is equivalent to the 'Class' type,
5268   /// i.e. if its object tive is the primitive 'Class' type with no protocols.
5269   bool isObjCClassType() const {
5270     return getObjectType()->isObjCUnqualifiedClass();
5271   }
5272
5273   /// True if this is equivalent to the 'id' or 'Class' type,
5274   bool isObjCIdOrClassType() const {
5275     return getObjectType()->isObjCUnqualifiedIdOrClass();
5276   }
5277
5278   /// True if this is equivalent to 'id<P>' for some non-empty set of
5279   /// protocols.
5280   bool isObjCQualifiedIdType() const {
5281     return getObjectType()->isObjCQualifiedId();
5282   }
5283
5284   /// True if this is equivalent to 'Class<P>' for some non-empty set of
5285   /// protocols.
5286   bool isObjCQualifiedClassType() const {
5287     return getObjectType()->isObjCQualifiedClass();
5288   }
5289
5290   /// Whether this is a "__kindof" type.
5291   bool isKindOfType() const { return getObjectType()->isKindOfType(); }
5292
5293   /// Whether this type is specialized, meaning that it has type arguments.
5294   bool isSpecialized() const { return getObjectType()->isSpecialized(); }
5295
5296   /// Whether this type is specialized, meaning that it has type arguments.
5297   bool isSpecializedAsWritten() const {
5298     return getObjectType()->isSpecializedAsWritten();
5299   }
5300
5301   /// Whether this type is unspecialized, meaning that is has no type arguments.
5302   bool isUnspecialized() const { return getObjectType()->isUnspecialized(); }
5303
5304   /// Determine whether this object type is "unspecialized" as
5305   /// written, meaning that it has no type arguments.
5306   bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5307
5308   /// Retrieve the type arguments for this type.
5309   ArrayRef<QualType> getTypeArgs() const {
5310     return getObjectType()->getTypeArgs();
5311   }
5312
5313   /// Retrieve the type arguments for this type.
5314   ArrayRef<QualType> getTypeArgsAsWritten() const {
5315     return getObjectType()->getTypeArgsAsWritten();
5316   }
5317
5318   /// An iterator over the qualifiers on the object type.  Provided
5319   /// for convenience.  This will always iterate over the full set of
5320   /// protocols on a type, not just those provided directly.
5321   typedef ObjCObjectType::qual_iterator qual_iterator;
5322   typedef llvm::iterator_range<qual_iterator> qual_range;
5323
5324   qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5325   qual_iterator qual_begin() const {
5326     return getObjectType()->qual_begin();
5327   }
5328   qual_iterator qual_end() const {
5329     return getObjectType()->qual_end();
5330   }
5331   bool qual_empty() const { return getObjectType()->qual_empty(); }
5332
5333   /// Return the number of qualifying protocols on the object type.
5334   unsigned getNumProtocols() const {
5335     return getObjectType()->getNumProtocols();
5336   }
5337
5338   /// Retrieve a qualifying protocol by index on the object type.
5339   ObjCProtocolDecl *getProtocol(unsigned I) const {
5340     return getObjectType()->getProtocol(I);
5341   }
5342
5343   bool isSugared() const { return false; }
5344   QualType desugar() const { return QualType(this, 0); }
5345
5346   /// Retrieve the type of the superclass of this object pointer type.
5347   ///
5348   /// This operation substitutes any type arguments into the
5349   /// superclass of the current class type, potentially producing a
5350   /// pointer to a specialization of the superclass type. Produces a
5351   /// null type if there is no superclass.
5352   QualType getSuperClassType() const;
5353
5354   /// Strip off the Objective-C "kindof" type and (with it) any
5355   /// protocol qualifiers.
5356   const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals(
5357                                  const ASTContext &ctx) const;
5358
5359   void Profile(llvm::FoldingSetNodeID &ID) {
5360     Profile(ID, getPointeeType());
5361   }
5362   static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
5363     ID.AddPointer(T.getAsOpaquePtr());
5364   }
5365   static bool classof(const Type *T) {
5366     return T->getTypeClass() == ObjCObjectPointer;
5367   }
5368 };
5369
5370 class AtomicType : public Type, public llvm::FoldingSetNode {
5371   QualType ValueType;
5372
5373   AtomicType(QualType ValTy, QualType Canonical)
5374     : Type(Atomic, Canonical, ValTy->isDependentType(),
5375            ValTy->isInstantiationDependentType(),
5376            ValTy->isVariablyModifiedType(),
5377            ValTy->containsUnexpandedParameterPack()),
5378       ValueType(ValTy) {}
5379   friend class ASTContext;  // ASTContext creates these.
5380
5381   public:
5382   /// Gets the type contained by this atomic type, i.e.
5383   /// the type returned by performing an atomic load of this atomic type.
5384   QualType getValueType() const { return ValueType; }
5385
5386   bool isSugared() const { return false; }
5387   QualType desugar() const { return QualType(this, 0); }
5388
5389   void Profile(llvm::FoldingSetNodeID &ID) {
5390     Profile(ID, getValueType());
5391   }
5392   static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
5393     ID.AddPointer(T.getAsOpaquePtr());
5394   }
5395   static bool classof(const Type *T) {
5396     return T->getTypeClass() == Atomic;
5397   }
5398 };
5399
5400 /// PipeType - OpenCL20.
5401 class PipeType : public Type, public llvm::FoldingSetNode {
5402   QualType ElementType;
5403   bool isRead;
5404
5405   PipeType(QualType elemType, QualType CanonicalPtr, bool isRead) :
5406     Type(Pipe, CanonicalPtr, elemType->isDependentType(),
5407          elemType->isInstantiationDependentType(),
5408          elemType->isVariablyModifiedType(),
5409          elemType->containsUnexpandedParameterPack()),
5410     ElementType(elemType), isRead(isRead) {}
5411   friend class ASTContext;  // ASTContext creates these.
5412
5413 public:
5414   QualType getElementType() const { return ElementType; }
5415
5416   bool isSugared() const { return false; }
5417
5418   QualType desugar() const { return QualType(this, 0); }
5419
5420   void Profile(llvm::FoldingSetNodeID &ID) {
5421     Profile(ID, getElementType(), isReadOnly());
5422   }
5423
5424   static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) {
5425     ID.AddPointer(T.getAsOpaquePtr());
5426     ID.AddBoolean(isRead);
5427   }
5428
5429   static bool classof(const Type *T) {
5430     return T->getTypeClass() == Pipe;
5431   }
5432
5433   bool isReadOnly() const { return isRead; }
5434 };
5435
5436 /// A qualifier set is used to build a set of qualifiers.
5437 class QualifierCollector : public Qualifiers {
5438 public:
5439   QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
5440
5441   /// Collect any qualifiers on the given type and return an
5442   /// unqualified type.  The qualifiers are assumed to be consistent
5443   /// with those already in the type.
5444   const Type *strip(QualType type) {
5445     addFastQualifiers(type.getLocalFastQualifiers());
5446     if (!type.hasLocalNonFastQualifiers())
5447       return type.getTypePtrUnsafe();
5448
5449     const ExtQuals *extQuals = type.getExtQualsUnsafe();
5450     addConsistentQualifiers(extQuals->getQualifiers());
5451     return extQuals->getBaseType();
5452   }
5453
5454   /// Apply the collected qualifiers to the given type.
5455   QualType apply(const ASTContext &Context, QualType QT) const;
5456
5457   /// Apply the collected qualifiers to the given type.
5458   QualType apply(const ASTContext &Context, const Type* T) const;
5459 };
5460
5461
5462 // Inline function definitions.
5463
5464 inline SplitQualType SplitQualType::getSingleStepDesugaredType() const {
5465   SplitQualType desugar =
5466     Ty->getLocallyUnqualifiedSingleStepDesugaredType().split();
5467   desugar.Quals.addConsistentQualifiers(Quals);
5468   return desugar;
5469 }
5470
5471 inline const Type *QualType::getTypePtr() const {
5472   return getCommonPtr()->BaseType;
5473 }
5474
5475 inline const Type *QualType::getTypePtrOrNull() const {
5476   return (isNull() ? nullptr : getCommonPtr()->BaseType);
5477 }
5478
5479 inline SplitQualType QualType::split() const {
5480   if (!hasLocalNonFastQualifiers())
5481     return SplitQualType(getTypePtrUnsafe(),
5482                          Qualifiers::fromFastMask(getLocalFastQualifiers()));
5483
5484   const ExtQuals *eq = getExtQualsUnsafe();
5485   Qualifiers qs = eq->getQualifiers();
5486   qs.addFastQualifiers(getLocalFastQualifiers());
5487   return SplitQualType(eq->getBaseType(), qs);
5488 }
5489
5490 inline Qualifiers QualType::getLocalQualifiers() const {
5491   Qualifiers Quals;
5492   if (hasLocalNonFastQualifiers())
5493     Quals = getExtQualsUnsafe()->getQualifiers();
5494   Quals.addFastQualifiers(getLocalFastQualifiers());
5495   return Quals;
5496 }
5497
5498 inline Qualifiers QualType::getQualifiers() const {
5499   Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
5500   quals.addFastQualifiers(getLocalFastQualifiers());
5501   return quals;
5502 }
5503
5504 inline unsigned QualType::getCVRQualifiers() const {
5505   unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
5506   cvr |= getLocalCVRQualifiers();
5507   return cvr;
5508 }
5509
5510 inline QualType QualType::getCanonicalType() const {
5511   QualType canon = getCommonPtr()->CanonicalType;
5512   return canon.withFastQualifiers(getLocalFastQualifiers());
5513 }
5514
5515 inline bool QualType::isCanonical() const {
5516   return getTypePtr()->isCanonicalUnqualified();
5517 }
5518
5519 inline bool QualType::isCanonicalAsParam() const {
5520   if (!isCanonical()) return false;
5521   if (hasLocalQualifiers()) return false;
5522
5523   const Type *T = getTypePtr();
5524   if (T->isVariablyModifiedType() && T->hasSizedVLAType())
5525     return false;
5526
5527   return !isa<FunctionType>(T) && !isa<ArrayType>(T);
5528 }
5529
5530 inline bool QualType::isConstQualified() const {
5531   return isLocalConstQualified() ||
5532          getCommonPtr()->CanonicalType.isLocalConstQualified();
5533 }
5534
5535 inline bool QualType::isRestrictQualified() const {
5536   return isLocalRestrictQualified() ||
5537          getCommonPtr()->CanonicalType.isLocalRestrictQualified();
5538 }
5539
5540
5541 inline bool QualType::isVolatileQualified() const {
5542   return isLocalVolatileQualified() ||
5543          getCommonPtr()->CanonicalType.isLocalVolatileQualified();
5544 }
5545
5546 inline bool QualType::hasQualifiers() const {
5547   return hasLocalQualifiers() ||
5548          getCommonPtr()->CanonicalType.hasLocalQualifiers();
5549 }
5550
5551 inline QualType QualType::getUnqualifiedType() const {
5552   if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
5553     return QualType(getTypePtr(), 0);
5554
5555   return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0);
5556 }
5557   
5558 inline SplitQualType QualType::getSplitUnqualifiedType() const {
5559   if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
5560     return split();
5561
5562   return getSplitUnqualifiedTypeImpl(*this);
5563 }
5564
5565 inline void QualType::removeLocalConst() {
5566   removeLocalFastQualifiers(Qualifiers::Const);
5567 }
5568
5569 inline void QualType::removeLocalRestrict() {
5570   removeLocalFastQualifiers(Qualifiers::Restrict);
5571 }
5572
5573 inline void QualType::removeLocalVolatile() {
5574   removeLocalFastQualifiers(Qualifiers::Volatile);
5575 }
5576
5577 inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
5578   assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits");
5579   static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask,
5580                 "Fast bits differ from CVR bits!");
5581
5582   // Fast path: we don't need to touch the slow qualifiers.
5583   removeLocalFastQualifiers(Mask);
5584 }
5585
5586 /// Return the address space of this type.
5587 inline unsigned QualType::getAddressSpace() const {
5588   return getQualifiers().getAddressSpace();
5589 }
5590
5591 /// Return the gc attribute of this type.
5592 inline Qualifiers::GC QualType::getObjCGCAttr() const {
5593   return getQualifiers().getObjCGCAttr();
5594 }
5595
5596 inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
5597   if (const PointerType *PT = t.getAs<PointerType>()) {
5598     if (const FunctionType *FT = PT->getPointeeType()->getAs<FunctionType>())
5599       return FT->getExtInfo();
5600   } else if (const FunctionType *FT = t.getAs<FunctionType>())
5601     return FT->getExtInfo();
5602
5603   return FunctionType::ExtInfo();
5604 }
5605
5606 inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
5607   return getFunctionExtInfo(*t);
5608 }
5609
5610 /// Determine whether this type is more
5611 /// qualified than the Other type. For example, "const volatile int"
5612 /// is more qualified than "const int", "volatile int", and
5613 /// "int". However, it is not more qualified than "const volatile
5614 /// int".
5615 inline bool QualType::isMoreQualifiedThan(QualType other) const {
5616   Qualifiers MyQuals = getQualifiers();
5617   Qualifiers OtherQuals = other.getQualifiers();
5618   return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals));
5619 }
5620
5621 /// Determine whether this type is at last
5622 /// as qualified as the Other type. For example, "const volatile
5623 /// int" is at least as qualified as "const int", "volatile int",
5624 /// "int", and "const volatile int".
5625 inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
5626   Qualifiers OtherQuals = other.getQualifiers();
5627
5628   // Ignore __unaligned qualifier if this type is a void.
5629   if (getUnqualifiedType()->isVoidType())
5630     OtherQuals.removeUnaligned();
5631
5632   return getQualifiers().compatiblyIncludes(OtherQuals);
5633 }
5634
5635 /// If Type is a reference type (e.g., const
5636 /// int&), returns the type that the reference refers to ("const
5637 /// int"). Otherwise, returns the type itself. This routine is used
5638 /// throughout Sema to implement C++ 5p6:
5639 ///
5640 ///   If an expression initially has the type "reference to T" (8.3.2,
5641 ///   8.5.3), the type is adjusted to "T" prior to any further
5642 ///   analysis, the expression designates the object or function
5643 ///   denoted by the reference, and the expression is an lvalue.
5644 inline QualType QualType::getNonReferenceType() const {
5645   if (const ReferenceType *RefType = (*this)->getAs<ReferenceType>())
5646     return RefType->getPointeeType();
5647   else
5648     return *this;
5649 }
5650
5651 inline bool QualType::isCForbiddenLValueType() const {
5652   return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
5653           getTypePtr()->isFunctionType());
5654 }
5655
5656 /// Tests whether the type is categorized as a fundamental type.
5657 ///
5658 /// \returns True for types specified in C++0x [basic.fundamental].
5659 inline bool Type::isFundamentalType() const {
5660   return isVoidType() ||
5661          // FIXME: It's really annoying that we don't have an
5662          // 'isArithmeticType()' which agrees with the standard definition.
5663          (isArithmeticType() && !isEnumeralType());
5664 }
5665
5666 /// Tests whether the type is categorized as a compound type.
5667 ///
5668 /// \returns True for types specified in C++0x [basic.compound].
5669 inline bool Type::isCompoundType() const {
5670   // C++0x [basic.compound]p1:
5671   //   Compound types can be constructed in the following ways:
5672   //    -- arrays of objects of a given type [...];
5673   return isArrayType() ||
5674   //    -- functions, which have parameters of given types [...];
5675          isFunctionType() ||
5676   //    -- pointers to void or objects or functions [...];
5677          isPointerType() ||
5678   //    -- references to objects or functions of a given type. [...]
5679          isReferenceType() ||
5680   //    -- classes containing a sequence of objects of various types, [...];
5681          isRecordType() ||
5682   //    -- unions, which are classes capable of containing objects of different
5683   //               types at different times;
5684          isUnionType() ||
5685   //    -- enumerations, which comprise a set of named constant values. [...];
5686          isEnumeralType() ||
5687   //    -- pointers to non-static class members, [...].
5688          isMemberPointerType();
5689 }
5690
5691 inline bool Type::isFunctionType() const {
5692   return isa<FunctionType>(CanonicalType);
5693 }
5694 inline bool Type::isPointerType() const {
5695   return isa<PointerType>(CanonicalType);
5696 }
5697 inline bool Type::isAnyPointerType() const {
5698   return isPointerType() || isObjCObjectPointerType();
5699 }
5700 inline bool Type::isBlockPointerType() const {
5701   return isa<BlockPointerType>(CanonicalType);
5702 }
5703 inline bool Type::isReferenceType() const {
5704   return isa<ReferenceType>(CanonicalType);
5705 }
5706 inline bool Type::isLValueReferenceType() const {
5707   return isa<LValueReferenceType>(CanonicalType);
5708 }
5709 inline bool Type::isRValueReferenceType() const {
5710   return isa<RValueReferenceType>(CanonicalType);
5711 }
5712 inline bool Type::isFunctionPointerType() const {
5713   if (const PointerType *T = getAs<PointerType>())
5714     return T->getPointeeType()->isFunctionType();
5715   else
5716     return false;
5717 }
5718 inline bool Type::isMemberPointerType() const {
5719   return isa<MemberPointerType>(CanonicalType);
5720 }
5721 inline bool Type::isMemberFunctionPointerType() const {
5722   if (const MemberPointerType* T = getAs<MemberPointerType>())
5723     return T->isMemberFunctionPointer();
5724   else
5725     return false;
5726 }
5727 inline bool Type::isMemberDataPointerType() const {
5728   if (const MemberPointerType* T = getAs<MemberPointerType>())
5729     return T->isMemberDataPointer();
5730   else
5731     return false;
5732 }
5733 inline bool Type::isArrayType() const {
5734   return isa<ArrayType>(CanonicalType);
5735 }
5736 inline bool Type::isConstantArrayType() const {
5737   return isa<ConstantArrayType>(CanonicalType);
5738 }
5739 inline bool Type::isIncompleteArrayType() const {
5740   return isa<IncompleteArrayType>(CanonicalType);
5741 }
5742 inline bool Type::isVariableArrayType() const {
5743   return isa<VariableArrayType>(CanonicalType);
5744 }
5745 inline bool Type::isDependentSizedArrayType() const {
5746   return isa<DependentSizedArrayType>(CanonicalType);
5747 }
5748 inline bool Type::isBuiltinType() const {
5749   return isa<BuiltinType>(CanonicalType);
5750 }
5751 inline bool Type::isRecordType() const {
5752   return isa<RecordType>(CanonicalType);
5753 }
5754 inline bool Type::isEnumeralType() const {
5755   return isa<EnumType>(CanonicalType);
5756 }
5757 inline bool Type::isAnyComplexType() const {
5758   return isa<ComplexType>(CanonicalType);
5759 }
5760 inline bool Type::isVectorType() const {
5761   return isa<VectorType>(CanonicalType);
5762 }
5763 inline bool Type::isExtVectorType() const {
5764   return isa<ExtVectorType>(CanonicalType);
5765 }
5766 inline bool Type::isObjCObjectPointerType() const {
5767   return isa<ObjCObjectPointerType>(CanonicalType);
5768 }
5769 inline bool Type::isObjCObjectType() const {
5770   return isa<ObjCObjectType>(CanonicalType);
5771 }
5772 inline bool Type::isObjCObjectOrInterfaceType() const {
5773   return isa<ObjCInterfaceType>(CanonicalType) ||
5774     isa<ObjCObjectType>(CanonicalType);
5775 }
5776 inline bool Type::isAtomicType() const {
5777   return isa<AtomicType>(CanonicalType);
5778 }
5779
5780 inline bool Type::isObjCQualifiedIdType() const {
5781   if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
5782     return OPT->isObjCQualifiedIdType();
5783   return false;
5784 }
5785 inline bool Type::isObjCQualifiedClassType() const {
5786   if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
5787     return OPT->isObjCQualifiedClassType();
5788   return false;
5789 }
5790 inline bool Type::isObjCIdType() const {
5791   if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
5792     return OPT->isObjCIdType();
5793   return false;
5794 }
5795 inline bool Type::isObjCClassType() const {
5796   if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
5797     return OPT->isObjCClassType();
5798   return false;
5799 }
5800 inline bool Type::isObjCSelType() const {
5801   if (const PointerType *OPT = getAs<PointerType>())
5802     return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
5803   return false;
5804 }
5805 inline bool Type::isObjCBuiltinType() const {
5806   return isObjCIdType() || isObjCClassType() || isObjCSelType();
5807 }
5808
5809 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5810   inline bool Type::is##Id##Type() const { \
5811     return isSpecificBuiltinType(BuiltinType::Id); \
5812   }
5813 #include "clang/Basic/OpenCLImageTypes.def"
5814
5815 inline bool Type::isSamplerT() const {
5816   return isSpecificBuiltinType(BuiltinType::OCLSampler);
5817 }
5818
5819 inline bool Type::isEventT() const {
5820   return isSpecificBuiltinType(BuiltinType::OCLEvent);
5821 }
5822
5823 inline bool Type::isClkEventT() const {
5824   return isSpecificBuiltinType(BuiltinType::OCLClkEvent);
5825 }
5826
5827 inline bool Type::isQueueT() const {
5828   return isSpecificBuiltinType(BuiltinType::OCLQueue);
5829 }
5830
5831 inline bool Type::isReserveIDT() const {
5832   return isSpecificBuiltinType(BuiltinType::OCLReserveID);
5833 }
5834
5835 inline bool Type::isImageType() const {
5836 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() ||
5837   return
5838 #include "clang/Basic/OpenCLImageTypes.def"
5839       0; // end boolean or operation
5840 }
5841
5842 inline bool Type::isPipeType() const {
5843   return isa<PipeType>(CanonicalType);
5844 }
5845
5846 inline bool Type::isOpenCLSpecificType() const {
5847   return isSamplerT() || isEventT() || isImageType() || isClkEventT() ||
5848          isQueueT() || isReserveIDT() || isPipeType();
5849 }
5850
5851 inline bool Type::isTemplateTypeParmType() const {
5852   return isa<TemplateTypeParmType>(CanonicalType);
5853 }
5854
5855 inline bool Type::isSpecificBuiltinType(unsigned K) const {
5856   if (const BuiltinType *BT = getAs<BuiltinType>())
5857     if (BT->getKind() == (BuiltinType::Kind) K)
5858       return true;
5859   return false;
5860 }
5861
5862 inline bool Type::isPlaceholderType() const {
5863   if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
5864     return BT->isPlaceholderType();
5865   return false;
5866 }
5867
5868 inline const BuiltinType *Type::getAsPlaceholderType() const {
5869   if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
5870     if (BT->isPlaceholderType())
5871       return BT;
5872   return nullptr;
5873 }
5874
5875 inline bool Type::isSpecificPlaceholderType(unsigned K) const {
5876   assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K));
5877   if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
5878     return (BT->getKind() == (BuiltinType::Kind) K);
5879   return false;
5880 }
5881
5882 inline bool Type::isNonOverloadPlaceholderType() const {
5883   if (const BuiltinType *BT = dyn_cast<BuiltinType>(this))
5884     return BT->isNonOverloadPlaceholderType();
5885   return false;
5886 }
5887
5888 inline bool Type::isVoidType() const {
5889   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5890     return BT->getKind() == BuiltinType::Void;
5891   return false;
5892 }
5893
5894 inline bool Type::isHalfType() const {
5895   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5896     return BT->getKind() == BuiltinType::Half;
5897   // FIXME: Should we allow complex __fp16? Probably not.
5898   return false;
5899 }
5900
5901 inline bool Type::isNullPtrType() const {
5902   if (const BuiltinType *BT = getAs<BuiltinType>())
5903     return BT->getKind() == BuiltinType::NullPtr;
5904   return false;
5905 }
5906
5907 bool IsEnumDeclComplete(EnumDecl *);
5908 bool IsEnumDeclScoped(EnumDecl *);
5909
5910 inline bool Type::isIntegerType() const {
5911   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5912     return BT->getKind() >= BuiltinType::Bool &&
5913            BT->getKind() <= BuiltinType::Int128;
5914   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
5915     // Incomplete enum types are not treated as integer types.
5916     // FIXME: In C++, enum types are never integer types.
5917     return IsEnumDeclComplete(ET->getDecl()) &&
5918       !IsEnumDeclScoped(ET->getDecl());
5919   }
5920   return false;
5921 }
5922
5923 inline bool Type::isScalarType() const {
5924   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5925     return BT->getKind() > BuiltinType::Void &&
5926            BT->getKind() <= BuiltinType::NullPtr;
5927   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
5928     // Enums are scalar types, but only if they are defined.  Incomplete enums
5929     // are not treated as scalar types.
5930     return IsEnumDeclComplete(ET->getDecl());
5931   return isa<PointerType>(CanonicalType) ||
5932          isa<BlockPointerType>(CanonicalType) ||
5933          isa<MemberPointerType>(CanonicalType) ||
5934          isa<ComplexType>(CanonicalType) ||
5935          isa<ObjCObjectPointerType>(CanonicalType);
5936 }
5937
5938 inline bool Type::isIntegralOrEnumerationType() const {
5939   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5940     return BT->getKind() >= BuiltinType::Bool &&
5941            BT->getKind() <= BuiltinType::Int128;
5942
5943   // Check for a complete enum type; incomplete enum types are not properly an
5944   // enumeration type in the sense required here.
5945   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
5946     return IsEnumDeclComplete(ET->getDecl());
5947
5948   return false;  
5949 }
5950
5951 inline bool Type::isBooleanType() const {
5952   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
5953     return BT->getKind() == BuiltinType::Bool;
5954   return false;
5955 }
5956
5957 inline bool Type::isUndeducedType() const {
5958   auto *DT = getContainedDeducedType();
5959   return DT && !DT->isDeduced();
5960 }
5961
5962 /// \brief Determines whether this is a type for which one can define
5963 /// an overloaded operator.
5964 inline bool Type::isOverloadableType() const {
5965   return isDependentType() || isRecordType() || isEnumeralType();
5966 }
5967
5968 /// \brief Determines whether this type can decay to a pointer type.
5969 inline bool Type::canDecayToPointerType() const {
5970   return isFunctionType() || isArrayType();
5971 }
5972
5973 inline bool Type::hasPointerRepresentation() const {
5974   return (isPointerType() || isReferenceType() || isBlockPointerType() ||
5975           isObjCObjectPointerType() || isNullPtrType());
5976 }
5977
5978 inline bool Type::hasObjCPointerRepresentation() const {
5979   return isObjCObjectPointerType();
5980 }
5981
5982 inline const Type *Type::getBaseElementTypeUnsafe() const {
5983   const Type *type = this;
5984   while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
5985     type = arrayType->getElementType().getTypePtr();
5986   return type;
5987 }
5988
5989 inline const Type *Type::getPointeeOrArrayElementType() const {
5990   const Type *type = this;
5991   if (type->isAnyPointerType())
5992     return type->getPointeeType().getTypePtr();
5993   else if (type->isArrayType())
5994     return type->getBaseElementTypeUnsafe();
5995   return type;
5996 }
5997
5998 /// Insertion operator for diagnostics.  This allows sending QualType's into a
5999 /// diagnostic with <<.
6000 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
6001                                            QualType T) {
6002   DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
6003                   DiagnosticsEngine::ak_qualtype);
6004   return DB;
6005 }
6006
6007 /// Insertion operator for partial diagnostics.  This allows sending QualType's
6008 /// into a diagnostic with <<.
6009 inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
6010                                            QualType T) {
6011   PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
6012                   DiagnosticsEngine::ak_qualtype);
6013   return PD;
6014 }
6015
6016 // Helper class template that is used by Type::getAs to ensure that one does
6017 // not try to look through a qualified type to get to an array type.
6018 template <typename T>
6019 using TypeIsArrayType =
6020     std::integral_constant<bool, std::is_same<T, ArrayType>::value ||
6021                                      std::is_base_of<ArrayType, T>::value>;
6022
6023 // Member-template getAs<specific type>'.
6024 template <typename T> const T *Type::getAs() const {
6025   static_assert(!TypeIsArrayType<T>::value,
6026                 "ArrayType cannot be used with getAs!");
6027
6028   // If this is directly a T type, return it.
6029   if (const T *Ty = dyn_cast<T>(this))
6030     return Ty;
6031
6032   // If the canonical form of this type isn't the right kind, reject it.
6033   if (!isa<T>(CanonicalType))
6034     return nullptr;
6035
6036   // If this is a typedef for the type, strip the typedef off without
6037   // losing all typedef information.
6038   return cast<T>(getUnqualifiedDesugaredType());
6039 }
6040
6041 template <typename T> const T *Type::getAsAdjusted() const {
6042   static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!");
6043
6044   // If this is directly a T type, return it.
6045   if (const T *Ty = dyn_cast<T>(this))
6046     return Ty;
6047
6048   // If the canonical form of this type isn't the right kind, reject it.
6049   if (!isa<T>(CanonicalType))
6050     return nullptr;
6051
6052   // Strip off type adjustments that do not modify the underlying nature of the
6053   // type.
6054   const Type *Ty = this;
6055   while (Ty) {
6056     if (const auto *A = dyn_cast<AttributedType>(Ty))
6057       Ty = A->getModifiedType().getTypePtr();
6058     else if (const auto *E = dyn_cast<ElaboratedType>(Ty))
6059       Ty = E->desugar().getTypePtr();
6060     else if (const auto *P = dyn_cast<ParenType>(Ty))
6061       Ty = P->desugar().getTypePtr();
6062     else if (const auto *A = dyn_cast<AdjustedType>(Ty))
6063       Ty = A->desugar().getTypePtr();
6064     else
6065       break;
6066   }
6067
6068   // Just because the canonical type is correct does not mean we can use cast<>,
6069   // since we may not have stripped off all the sugar down to the base type.
6070   return dyn_cast<T>(Ty);
6071 }
6072
6073 inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
6074   // If this is directly an array type, return it.
6075   if (const ArrayType *arr = dyn_cast<ArrayType>(this))
6076     return arr;
6077
6078   // If the canonical form of this type isn't the right kind, reject it.
6079   if (!isa<ArrayType>(CanonicalType))
6080     return nullptr;
6081
6082   // If this is a typedef for the type, strip the typedef off without
6083   // losing all typedef information.
6084   return cast<ArrayType>(getUnqualifiedDesugaredType());
6085 }
6086
6087 template <typename T> const T *Type::castAs() const {
6088   static_assert(!TypeIsArrayType<T>::value,
6089                 "ArrayType cannot be used with castAs!");
6090
6091   if (const T *ty = dyn_cast<T>(this)) return ty;
6092   assert(isa<T>(CanonicalType));
6093   return cast<T>(getUnqualifiedDesugaredType());
6094 }
6095
6096 inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
6097   assert(isa<ArrayType>(CanonicalType));
6098   if (const ArrayType *arr = dyn_cast<ArrayType>(this)) return arr;
6099   return cast<ArrayType>(getUnqualifiedDesugaredType());
6100 }
6101
6102 DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr,
6103                          QualType CanonicalPtr)
6104     : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) {
6105 #ifndef NDEBUG
6106   QualType Adjusted = getAdjustedType();
6107   (void)AttributedType::stripOuterNullability(Adjusted);
6108   assert(isa<PointerType>(Adjusted));
6109 #endif
6110 }
6111
6112 QualType DecayedType::getPointeeType() const {
6113   QualType Decayed = getDecayedType();
6114   (void)AttributedType::stripOuterNullability(Decayed);
6115   return cast<PointerType>(Decayed)->getPointeeType();
6116 }
6117
6118
6119 }  // end namespace clang
6120
6121 #endif