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