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