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