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