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