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