clang API Documentation

Type.cpp
Go to the documentation of this file.
00001 //===--- Type.cpp - Type representation and manipulation ------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file implements type-related functionality.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/AST/ASTContext.h"
00015 #include "clang/AST/Attr.h"
00016 #include "clang/AST/CharUnits.h"
00017 #include "clang/AST/DeclCXX.h"
00018 #include "clang/AST/DeclObjC.h"
00019 #include "clang/AST/DeclTemplate.h"
00020 #include "clang/AST/Expr.h"
00021 #include "clang/AST/PrettyPrinter.h"
00022 #include "clang/AST/Type.h"
00023 #include "clang/AST/TypeVisitor.h"
00024 #include "clang/Basic/Specifiers.h"
00025 #include "llvm/ADT/APSInt.h"
00026 #include "llvm/ADT/StringExtras.h"
00027 #include "llvm/Support/raw_ostream.h"
00028 #include <algorithm>
00029 using namespace clang;
00030 
00031 bool Qualifiers::isStrictSupersetOf(Qualifiers Other) const {
00032   return (*this != Other) &&
00033     // CVR qualifiers superset
00034     (((Mask & CVRMask) | (Other.Mask & CVRMask)) == (Mask & CVRMask)) &&
00035     // ObjC GC qualifiers superset
00036     ((getObjCGCAttr() == Other.getObjCGCAttr()) ||
00037      (hasObjCGCAttr() && !Other.hasObjCGCAttr())) &&
00038     // Address space superset.
00039     ((getAddressSpace() == Other.getAddressSpace()) ||
00040      (hasAddressSpace()&& !Other.hasAddressSpace())) &&
00041     // Lifetime qualifier superset.
00042     ((getObjCLifetime() == Other.getObjCLifetime()) ||
00043      (hasObjCLifetime() && !Other.hasObjCLifetime()));
00044 }
00045 
00046 const IdentifierInfo* QualType::getBaseTypeIdentifier() const {
00047   const Type* ty = getTypePtr();
00048   NamedDecl *ND = nullptr;
00049   if (ty->isPointerType() || ty->isReferenceType())
00050     return ty->getPointeeType().getBaseTypeIdentifier();
00051   else if (ty->isRecordType())
00052     ND = ty->getAs<RecordType>()->getDecl();
00053   else if (ty->isEnumeralType())
00054     ND = ty->getAs<EnumType>()->getDecl();
00055   else if (ty->getTypeClass() == Type::Typedef)
00056     ND = ty->getAs<TypedefType>()->getDecl();
00057   else if (ty->isArrayType())
00058     return ty->castAsArrayTypeUnsafe()->
00059         getElementType().getBaseTypeIdentifier();
00060 
00061   if (ND)
00062     return ND->getIdentifier();
00063   return nullptr;
00064 }
00065 
00066 bool QualType::isConstant(QualType T, ASTContext &Ctx) {
00067   if (T.isConstQualified())
00068     return true;
00069 
00070   if (const ArrayType *AT = Ctx.getAsArrayType(T))
00071     return AT->getElementType().isConstant(Ctx);
00072 
00073   return T.getAddressSpace() == LangAS::opencl_constant;
00074 }
00075 
00076 unsigned ConstantArrayType::getNumAddressingBits(ASTContext &Context,
00077                                                  QualType ElementType,
00078                                                const llvm::APInt &NumElements) {
00079   uint64_t ElementSize = Context.getTypeSizeInChars(ElementType).getQuantity();
00080 
00081   // Fast path the common cases so we can avoid the conservative computation
00082   // below, which in common cases allocates "large" APSInt values, which are
00083   // slow.
00084 
00085   // If the element size is a power of 2, we can directly compute the additional
00086   // number of addressing bits beyond those required for the element count.
00087   if (llvm::isPowerOf2_64(ElementSize)) {
00088     return NumElements.getActiveBits() + llvm::Log2_64(ElementSize);
00089   }
00090 
00091   // If both the element count and element size fit in 32-bits, we can do the
00092   // computation directly in 64-bits.
00093   if ((ElementSize >> 32) == 0 && NumElements.getBitWidth() <= 64 &&
00094       (NumElements.getZExtValue() >> 32) == 0) {
00095     uint64_t TotalSize = NumElements.getZExtValue() * ElementSize;
00096     return 64 - llvm::countLeadingZeros(TotalSize);
00097   }
00098 
00099   // Otherwise, use APSInt to handle arbitrary sized values.
00100   llvm::APSInt SizeExtended(NumElements, true);
00101   unsigned SizeTypeBits = Context.getTypeSize(Context.getSizeType());
00102   SizeExtended = SizeExtended.extend(std::max(SizeTypeBits,
00103                                               SizeExtended.getBitWidth()) * 2);
00104 
00105   llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize));
00106   TotalSize *= SizeExtended;  
00107 
00108   return TotalSize.getActiveBits();
00109 }
00110 
00111 unsigned ConstantArrayType::getMaxSizeBits(ASTContext &Context) {
00112   unsigned Bits = Context.getTypeSize(Context.getSizeType());
00113   
00114   // Limit the number of bits in size_t so that maximal bit size fits 64 bit
00115   // integer (see PR8256).  We can do this as currently there is no hardware
00116   // that supports full 64-bit virtual space.
00117   if (Bits > 61)
00118     Bits = 61;
00119 
00120   return Bits;
00121 }
00122 
00123 DependentSizedArrayType::DependentSizedArrayType(const ASTContext &Context, 
00124                                                  QualType et, QualType can,
00125                                                  Expr *e, ArraySizeModifier sm,
00126                                                  unsigned tq,
00127                                                  SourceRange brackets)
00128     : ArrayType(DependentSizedArray, et, can, sm, tq, 
00129                 (et->containsUnexpandedParameterPack() ||
00130                  (e && e->containsUnexpandedParameterPack()))),
00131       Context(Context), SizeExpr((Stmt*) e), Brackets(brackets) 
00132 {
00133 }
00134 
00135 void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID,
00136                                       const ASTContext &Context,
00137                                       QualType ET,
00138                                       ArraySizeModifier SizeMod,
00139                                       unsigned TypeQuals,
00140                                       Expr *E) {
00141   ID.AddPointer(ET.getAsOpaquePtr());
00142   ID.AddInteger(SizeMod);
00143   ID.AddInteger(TypeQuals);
00144   E->Profile(ID, Context, true);
00145 }
00146 
00147 DependentSizedExtVectorType::DependentSizedExtVectorType(const
00148                                                          ASTContext &Context,
00149                                                          QualType ElementType,
00150                                                          QualType can, 
00151                                                          Expr *SizeExpr, 
00152                                                          SourceLocation loc)
00153     : Type(DependentSizedExtVector, can, /*Dependent=*/true,
00154            /*InstantiationDependent=*/true,
00155            ElementType->isVariablyModifiedType(), 
00156            (ElementType->containsUnexpandedParameterPack() ||
00157             (SizeExpr && SizeExpr->containsUnexpandedParameterPack()))),
00158       Context(Context), SizeExpr(SizeExpr), ElementType(ElementType),
00159       loc(loc) 
00160 {
00161 }
00162 
00163 void
00164 DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID,
00165                                      const ASTContext &Context,
00166                                      QualType ElementType, Expr *SizeExpr) {
00167   ID.AddPointer(ElementType.getAsOpaquePtr());
00168   SizeExpr->Profile(ID, Context, true);
00169 }
00170 
00171 VectorType::VectorType(QualType vecType, unsigned nElements, QualType canonType,
00172                        VectorKind vecKind)
00173   : Type(Vector, canonType, vecType->isDependentType(),
00174          vecType->isInstantiationDependentType(),
00175          vecType->isVariablyModifiedType(),
00176          vecType->containsUnexpandedParameterPack()),
00177     ElementType(vecType) 
00178 {
00179   VectorTypeBits.VecKind = vecKind;
00180   VectorTypeBits.NumElements = nElements;
00181 }
00182 
00183 VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements,
00184                        QualType canonType, VectorKind vecKind)
00185   : Type(tc, canonType, vecType->isDependentType(),
00186          vecType->isInstantiationDependentType(),
00187          vecType->isVariablyModifiedType(),
00188          vecType->containsUnexpandedParameterPack()), 
00189     ElementType(vecType) 
00190 {
00191   VectorTypeBits.VecKind = vecKind;
00192   VectorTypeBits.NumElements = nElements;
00193 }
00194 
00195 /// getArrayElementTypeNoTypeQual - If this is an array type, return the
00196 /// element type of the array, potentially with type qualifiers missing.
00197 /// This method should never be used when type qualifiers are meaningful.
00198 const Type *Type::getArrayElementTypeNoTypeQual() const {
00199   // If this is directly an array type, return it.
00200   if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
00201     return ATy->getElementType().getTypePtr();
00202 
00203   // If the canonical form of this type isn't the right kind, reject it.
00204   if (!isa<ArrayType>(CanonicalType))
00205     return nullptr;
00206 
00207   // If this is a typedef for an array type, strip the typedef off without
00208   // losing all typedef information.
00209   return cast<ArrayType>(getUnqualifiedDesugaredType())
00210     ->getElementType().getTypePtr();
00211 }
00212 
00213 /// getDesugaredType - Return the specified type with any "sugar" removed from
00214 /// the type.  This takes off typedefs, typeof's etc.  If the outer level of
00215 /// the type is already concrete, it returns it unmodified.  This is similar
00216 /// to getting the canonical type, but it doesn't remove *all* typedefs.  For
00217 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
00218 /// concrete.
00219 QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) {
00220   SplitQualType split = getSplitDesugaredType(T);
00221   return Context.getQualifiedType(split.Ty, split.Quals);
00222 }
00223 
00224 QualType QualType::getSingleStepDesugaredTypeImpl(QualType type,
00225                                                   const ASTContext &Context) {
00226   SplitQualType split = type.split();
00227   QualType desugar = split.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
00228   return Context.getQualifiedType(desugar, split.Quals);
00229 }
00230 
00231 QualType Type::getLocallyUnqualifiedSingleStepDesugaredType() const {
00232   switch (getTypeClass()) {
00233 #define ABSTRACT_TYPE(Class, Parent)
00234 #define TYPE(Class, Parent) \
00235   case Type::Class: { \
00236     const Class##Type *ty = cast<Class##Type>(this); \
00237     if (!ty->isSugared()) return QualType(ty, 0); \
00238     return ty->desugar(); \
00239   }
00240 #include "clang/AST/TypeNodes.def"
00241   }
00242   llvm_unreachable("bad type kind!");
00243 }
00244 
00245 SplitQualType QualType::getSplitDesugaredType(QualType T) {
00246   QualifierCollector Qs;
00247 
00248   QualType Cur = T;
00249   while (true) {
00250     const Type *CurTy = Qs.strip(Cur);
00251     switch (CurTy->getTypeClass()) {
00252 #define ABSTRACT_TYPE(Class, Parent)
00253 #define TYPE(Class, Parent) \
00254     case Type::Class: { \
00255       const Class##Type *Ty = cast<Class##Type>(CurTy); \
00256       if (!Ty->isSugared()) \
00257         return SplitQualType(Ty, Qs); \
00258       Cur = Ty->desugar(); \
00259       break; \
00260     }
00261 #include "clang/AST/TypeNodes.def"
00262     }
00263   }
00264 }
00265 
00266 SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) {
00267   SplitQualType split = type.split();
00268 
00269   // All the qualifiers we've seen so far.
00270   Qualifiers quals = split.Quals;
00271 
00272   // The last type node we saw with any nodes inside it.
00273   const Type *lastTypeWithQuals = split.Ty;
00274 
00275   while (true) {
00276     QualType next;
00277 
00278     // Do a single-step desugar, aborting the loop if the type isn't
00279     // sugared.
00280     switch (split.Ty->getTypeClass()) {
00281 #define ABSTRACT_TYPE(Class, Parent)
00282 #define TYPE(Class, Parent) \
00283     case Type::Class: { \
00284       const Class##Type *ty = cast<Class##Type>(split.Ty); \
00285       if (!ty->isSugared()) goto done; \
00286       next = ty->desugar(); \
00287       break; \
00288     }
00289 #include "clang/AST/TypeNodes.def"
00290     }
00291 
00292     // Otherwise, split the underlying type.  If that yields qualifiers,
00293     // update the information.
00294     split = next.split();
00295     if (!split.Quals.empty()) {
00296       lastTypeWithQuals = split.Ty;
00297       quals.addConsistentQualifiers(split.Quals);
00298     }
00299   }
00300 
00301  done:
00302   return SplitQualType(lastTypeWithQuals, quals);
00303 }
00304 
00305 QualType QualType::IgnoreParens(QualType T) {
00306   // FIXME: this seems inherently un-qualifiers-safe.
00307   while (const ParenType *PT = T->getAs<ParenType>())
00308     T = PT->getInnerType();
00309   return T;
00310 }
00311 
00312 /// \brief This will check for a T (which should be a Type which can act as
00313 /// sugar, such as a TypedefType) by removing any existing sugar until it
00314 /// reaches a T or a non-sugared type.
00315 template<typename T> static const T *getAsSugar(const Type *Cur) {
00316   while (true) {
00317     if (const T *Sugar = dyn_cast<T>(Cur))
00318       return Sugar;
00319     switch (Cur->getTypeClass()) {
00320 #define ABSTRACT_TYPE(Class, Parent)
00321 #define TYPE(Class, Parent) \
00322     case Type::Class: { \
00323       const Class##Type *Ty = cast<Class##Type>(Cur); \
00324       if (!Ty->isSugared()) return 0; \
00325       Cur = Ty->desugar().getTypePtr(); \
00326       break; \
00327     }
00328 #include "clang/AST/TypeNodes.def"
00329     }
00330   }
00331 }
00332 
00333 template <> const TypedefType *Type::getAs() const {
00334   return getAsSugar<TypedefType>(this);
00335 }
00336 
00337 template <> const TemplateSpecializationType *Type::getAs() const {
00338   return getAsSugar<TemplateSpecializationType>(this);
00339 }
00340 
00341 template <> const AttributedType *Type::getAs() const {
00342   return getAsSugar<AttributedType>(this);
00343 }
00344 
00345 /// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
00346 /// sugar off the given type.  This should produce an object of the
00347 /// same dynamic type as the canonical type.
00348 const Type *Type::getUnqualifiedDesugaredType() const {
00349   const Type *Cur = this;
00350 
00351   while (true) {
00352     switch (Cur->getTypeClass()) {
00353 #define ABSTRACT_TYPE(Class, Parent)
00354 #define TYPE(Class, Parent) \
00355     case Class: { \
00356       const Class##Type *Ty = cast<Class##Type>(Cur); \
00357       if (!Ty->isSugared()) return Cur; \
00358       Cur = Ty->desugar().getTypePtr(); \
00359       break; \
00360     }
00361 #include "clang/AST/TypeNodes.def"
00362     }
00363   }
00364 }
00365 bool Type::isClassType() const {
00366   if (const RecordType *RT = getAs<RecordType>())
00367     return RT->getDecl()->isClass();
00368   return false;
00369 }
00370 bool Type::isStructureType() const {
00371   if (const RecordType *RT = getAs<RecordType>())
00372     return RT->getDecl()->isStruct();
00373   return false;
00374 }
00375 bool Type::isInterfaceType() const {
00376   if (const RecordType *RT = getAs<RecordType>())
00377     return RT->getDecl()->isInterface();
00378   return false;
00379 }
00380 bool Type::isStructureOrClassType() const {
00381   if (const RecordType *RT = getAs<RecordType>()) {
00382     RecordDecl *RD = RT->getDecl();
00383     return RD->isStruct() || RD->isClass() || RD->isInterface();
00384   }
00385   return false;
00386 }
00387 bool Type::isVoidPointerType() const {
00388   if (const PointerType *PT = getAs<PointerType>())
00389     return PT->getPointeeType()->isVoidType();
00390   return false;
00391 }
00392 
00393 bool Type::isUnionType() const {
00394   if (const RecordType *RT = getAs<RecordType>())
00395     return RT->getDecl()->isUnion();
00396   return false;
00397 }
00398 
00399 bool Type::isComplexType() const {
00400   if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
00401     return CT->getElementType()->isFloatingType();
00402   return false;
00403 }
00404 
00405 bool Type::isComplexIntegerType() const {
00406   // Check for GCC complex integer extension.
00407   return getAsComplexIntegerType();
00408 }
00409 
00410 const ComplexType *Type::getAsComplexIntegerType() const {
00411   if (const ComplexType *Complex = getAs<ComplexType>())
00412     if (Complex->getElementType()->isIntegerType())
00413       return Complex;
00414   return nullptr;
00415 }
00416 
00417 QualType Type::getPointeeType() const {
00418   if (const PointerType *PT = getAs<PointerType>())
00419     return PT->getPointeeType();
00420   if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>())
00421     return OPT->getPointeeType();
00422   if (const BlockPointerType *BPT = getAs<BlockPointerType>())
00423     return BPT->getPointeeType();
00424   if (const ReferenceType *RT = getAs<ReferenceType>())
00425     return RT->getPointeeType();
00426   if (const MemberPointerType *MPT = getAs<MemberPointerType>())
00427     return MPT->getPointeeType();
00428   if (const DecayedType *DT = getAs<DecayedType>())
00429     return DT->getPointeeType();
00430   return QualType();
00431 }
00432 
00433 const RecordType *Type::getAsStructureType() const {
00434   // If this is directly a structure type, return it.
00435   if (const RecordType *RT = dyn_cast<RecordType>(this)) {
00436     if (RT->getDecl()->isStruct())
00437       return RT;
00438   }
00439 
00440   // If the canonical form of this type isn't the right kind, reject it.
00441   if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
00442     if (!RT->getDecl()->isStruct())
00443       return nullptr;
00444 
00445     // If this is a typedef for a structure type, strip the typedef off without
00446     // losing all typedef information.
00447     return cast<RecordType>(getUnqualifiedDesugaredType());
00448   }
00449   return nullptr;
00450 }
00451 
00452 const RecordType *Type::getAsUnionType() const {
00453   // If this is directly a union type, return it.
00454   if (const RecordType *RT = dyn_cast<RecordType>(this)) {
00455     if (RT->getDecl()->isUnion())
00456       return RT;
00457   }
00458 
00459   // If the canonical form of this type isn't the right kind, reject it.
00460   if (const RecordType *RT = dyn_cast<RecordType>(CanonicalType)) {
00461     if (!RT->getDecl()->isUnion())
00462       return nullptr;
00463 
00464     // If this is a typedef for a union type, strip the typedef off without
00465     // losing all typedef information.
00466     return cast<RecordType>(getUnqualifiedDesugaredType());
00467   }
00468 
00469   return nullptr;
00470 }
00471 
00472 ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base,
00473                                ObjCProtocolDecl * const *Protocols,
00474                                unsigned NumProtocols)
00475   : Type(ObjCObject, Canonical, false, false, false, false),
00476     BaseType(Base) 
00477 {
00478   ObjCObjectTypeBits.NumProtocols = NumProtocols;
00479   assert(getNumProtocols() == NumProtocols &&
00480          "bitfield overflow in protocol count");
00481   if (NumProtocols)
00482     memcpy(getProtocolStorage(), Protocols,
00483            NumProtocols * sizeof(ObjCProtocolDecl*));
00484 }
00485 
00486 const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const {
00487   // There is no sugar for ObjCObjectType's, just return the canonical
00488   // type pointer if it is the right class.  There is no typedef information to
00489   // return and these cannot be Address-space qualified.
00490   if (const ObjCObjectType *T = getAs<ObjCObjectType>())
00491     if (T->getNumProtocols() && T->getInterface())
00492       return T;
00493   return nullptr;
00494 }
00495 
00496 bool Type::isObjCQualifiedInterfaceType() const {
00497   return getAsObjCQualifiedInterfaceType() != nullptr;
00498 }
00499 
00500 const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
00501   // There is no sugar for ObjCQualifiedIdType's, just return the canonical
00502   // type pointer if it is the right class.
00503   if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
00504     if (OPT->isObjCQualifiedIdType())
00505       return OPT;
00506   }
00507   return nullptr;
00508 }
00509 
00510 const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const {
00511   // There is no sugar for ObjCQualifiedClassType's, just return the canonical
00512   // type pointer if it is the right class.
00513   if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
00514     if (OPT->isObjCQualifiedClassType())
00515       return OPT;
00516   }
00517   return nullptr;
00518 }
00519 
00520 const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
00521   if (const ObjCObjectPointerType *OPT = getAs<ObjCObjectPointerType>()) {
00522     if (OPT->getInterfaceType())
00523       return OPT;
00524   }
00525   return nullptr;
00526 }
00527 
00528 const CXXRecordDecl *Type::getPointeeCXXRecordDecl() const {
00529   QualType PointeeType;
00530   if (const PointerType *PT = getAs<PointerType>())
00531     PointeeType = PT->getPointeeType();
00532   else if (const ReferenceType *RT = getAs<ReferenceType>())
00533     PointeeType = RT->getPointeeType();
00534   else
00535     return nullptr;
00536 
00537   if (const RecordType *RT = PointeeType->getAs<RecordType>())
00538     return dyn_cast<CXXRecordDecl>(RT->getDecl());
00539 
00540   return nullptr;
00541 }
00542 
00543 CXXRecordDecl *Type::getAsCXXRecordDecl() const {
00544   if (const RecordType *RT = getAs<RecordType>())
00545     return dyn_cast<CXXRecordDecl>(RT->getDecl());
00546   else if (const InjectedClassNameType *Injected
00547                                   = getAs<InjectedClassNameType>())
00548     return Injected->getDecl();
00549 
00550   return nullptr;
00551 }
00552 
00553 namespace {
00554   class GetContainedAutoVisitor :
00555     public TypeVisitor<GetContainedAutoVisitor, AutoType*> {
00556   public:
00557     using TypeVisitor<GetContainedAutoVisitor, AutoType*>::Visit;
00558     AutoType *Visit(QualType T) {
00559       if (T.isNull())
00560         return nullptr;
00561       return Visit(T.getTypePtr());
00562     }
00563 
00564     // The 'auto' type itself.
00565     AutoType *VisitAutoType(const AutoType *AT) {
00566       return const_cast<AutoType*>(AT);
00567     }
00568 
00569     // Only these types can contain the desired 'auto' type.
00570     AutoType *VisitPointerType(const PointerType *T) {
00571       return Visit(T->getPointeeType());
00572     }
00573     AutoType *VisitBlockPointerType(const BlockPointerType *T) {
00574       return Visit(T->getPointeeType());
00575     }
00576     AutoType *VisitReferenceType(const ReferenceType *T) {
00577       return Visit(T->getPointeeTypeAsWritten());
00578     }
00579     AutoType *VisitMemberPointerType(const MemberPointerType *T) {
00580       return Visit(T->getPointeeType());
00581     }
00582     AutoType *VisitArrayType(const ArrayType *T) {
00583       return Visit(T->getElementType());
00584     }
00585     AutoType *VisitDependentSizedExtVectorType(
00586       const DependentSizedExtVectorType *T) {
00587       return Visit(T->getElementType());
00588     }
00589     AutoType *VisitVectorType(const VectorType *T) {
00590       return Visit(T->getElementType());
00591     }
00592     AutoType *VisitFunctionType(const FunctionType *T) {
00593       return Visit(T->getReturnType());
00594     }
00595     AutoType *VisitParenType(const ParenType *T) {
00596       return Visit(T->getInnerType());
00597     }
00598     AutoType *VisitAttributedType(const AttributedType *T) {
00599       return Visit(T->getModifiedType());
00600     }
00601     AutoType *VisitAdjustedType(const AdjustedType *T) {
00602       return Visit(T->getOriginalType());
00603     }
00604   };
00605 }
00606 
00607 AutoType *Type::getContainedAutoType() const {
00608   return GetContainedAutoVisitor().Visit(this);
00609 }
00610 
00611 bool Type::hasIntegerRepresentation() const {
00612   if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
00613     return VT->getElementType()->isIntegerType();
00614   else
00615     return isIntegerType();
00616 }
00617 
00618 /// \brief Determine whether this type is an integral type.
00619 ///
00620 /// This routine determines whether the given type is an integral type per 
00621 /// C++ [basic.fundamental]p7. Although the C standard does not define the
00622 /// term "integral type", it has a similar term "integer type", and in C++
00623 /// the two terms are equivalent. However, C's "integer type" includes 
00624 /// enumeration types, while C++'s "integer type" does not. The \c ASTContext
00625 /// parameter is used to determine whether we should be following the C or
00626 /// C++ rules when determining whether this type is an integral/integer type.
00627 ///
00628 /// For cases where C permits "an integer type" and C++ permits "an integral
00629 /// type", use this routine.
00630 ///
00631 /// For cases where C permits "an integer type" and C++ permits "an integral
00632 /// or enumeration type", use \c isIntegralOrEnumerationType() instead. 
00633 ///
00634 /// \param Ctx The context in which this type occurs.
00635 ///
00636 /// \returns true if the type is considered an integral type, false otherwise.
00637 bool Type::isIntegralType(ASTContext &Ctx) const {
00638   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
00639     return BT->getKind() >= BuiltinType::Bool &&
00640     BT->getKind() <= BuiltinType::Int128;
00641   
00642   if (!Ctx.getLangOpts().CPlusPlus)
00643     if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
00644       return ET->getDecl()->isComplete(); // Complete enum types are integral in C.
00645   
00646   return false;
00647 }
00648 
00649 
00650 bool Type::isIntegralOrUnscopedEnumerationType() const {
00651   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
00652     return BT->getKind() >= BuiltinType::Bool &&
00653            BT->getKind() <= BuiltinType::Int128;
00654 
00655   // Check for a complete enum type; incomplete enum types are not properly an
00656   // enumeration type in the sense required here.
00657   // C++0x: However, if the underlying type of the enum is fixed, it is
00658   // considered complete.
00659   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
00660     return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
00661 
00662   return false;
00663 }
00664 
00665 
00666 
00667 bool Type::isCharType() const {
00668   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
00669     return BT->getKind() == BuiltinType::Char_U ||
00670            BT->getKind() == BuiltinType::UChar ||
00671            BT->getKind() == BuiltinType::Char_S ||
00672            BT->getKind() == BuiltinType::SChar;
00673   return false;
00674 }
00675 
00676 bool Type::isWideCharType() const {
00677   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
00678     return BT->getKind() == BuiltinType::WChar_S ||
00679            BT->getKind() == BuiltinType::WChar_U;
00680   return false;
00681 }
00682 
00683 bool Type::isChar16Type() const {
00684   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
00685     return BT->getKind() == BuiltinType::Char16;
00686   return false;
00687 }
00688 
00689 bool Type::isChar32Type() const {
00690   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
00691     return BT->getKind() == BuiltinType::Char32;
00692   return false;
00693 }
00694 
00695 /// \brief Determine whether this type is any of the built-in character
00696 /// types.
00697 bool Type::isAnyCharacterType() const {
00698   const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType);
00699   if (!BT) return false;
00700   switch (BT->getKind()) {
00701   default: return false;
00702   case BuiltinType::Char_U:
00703   case BuiltinType::UChar:
00704   case BuiltinType::WChar_U:
00705   case BuiltinType::Char16:
00706   case BuiltinType::Char32:
00707   case BuiltinType::Char_S:
00708   case BuiltinType::SChar:
00709   case BuiltinType::WChar_S:
00710     return true;
00711   }
00712 }
00713 
00714 /// isSignedIntegerType - Return true if this is an integer type that is
00715 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
00716 /// an enum decl which has a signed representation
00717 bool Type::isSignedIntegerType() const {
00718   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
00719     return BT->getKind() >= BuiltinType::Char_S &&
00720            BT->getKind() <= BuiltinType::Int128;
00721   }
00722 
00723   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
00724     // Incomplete enum types are not treated as integer types.
00725     // FIXME: In C++, enum types are never integer types.
00726     if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
00727       return ET->getDecl()->getIntegerType()->isSignedIntegerType();
00728   }
00729 
00730   return false;
00731 }
00732 
00733 bool Type::isSignedIntegerOrEnumerationType() const {
00734   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
00735     return BT->getKind() >= BuiltinType::Char_S &&
00736     BT->getKind() <= BuiltinType::Int128;
00737   }
00738   
00739   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
00740     if (ET->getDecl()->isComplete())
00741       return ET->getDecl()->getIntegerType()->isSignedIntegerType();
00742   }
00743   
00744   return false;
00745 }
00746 
00747 bool Type::hasSignedIntegerRepresentation() const {
00748   if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
00749     return VT->getElementType()->isSignedIntegerOrEnumerationType();
00750   else
00751     return isSignedIntegerOrEnumerationType();
00752 }
00753 
00754 /// isUnsignedIntegerType - Return true if this is an integer type that is
00755 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
00756 /// decl which has an unsigned representation
00757 bool Type::isUnsignedIntegerType() const {
00758   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
00759     return BT->getKind() >= BuiltinType::Bool &&
00760            BT->getKind() <= BuiltinType::UInt128;
00761   }
00762 
00763   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
00764     // Incomplete enum types are not treated as integer types.
00765     // FIXME: In C++, enum types are never integer types.
00766     if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
00767       return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
00768   }
00769 
00770   return false;
00771 }
00772 
00773 bool Type::isUnsignedIntegerOrEnumerationType() const {
00774   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType)) {
00775     return BT->getKind() >= BuiltinType::Bool &&
00776     BT->getKind() <= BuiltinType::UInt128;
00777   }
00778   
00779   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
00780     if (ET->getDecl()->isComplete())
00781       return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
00782   }
00783   
00784   return false;
00785 }
00786 
00787 bool Type::hasUnsignedIntegerRepresentation() const {
00788   if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
00789     return VT->getElementType()->isUnsignedIntegerOrEnumerationType();
00790   else
00791     return isUnsignedIntegerOrEnumerationType();
00792 }
00793 
00794 bool Type::isFloatingType() const {
00795   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
00796     return BT->getKind() >= BuiltinType::Half &&
00797            BT->getKind() <= BuiltinType::LongDouble;
00798   if (const ComplexType *CT = dyn_cast<ComplexType>(CanonicalType))
00799     return CT->getElementType()->isFloatingType();
00800   return false;
00801 }
00802 
00803 bool Type::hasFloatingRepresentation() const {
00804   if (const VectorType *VT = dyn_cast<VectorType>(CanonicalType))
00805     return VT->getElementType()->isFloatingType();
00806   else
00807     return isFloatingType();
00808 }
00809 
00810 bool Type::isRealFloatingType() const {
00811   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
00812     return BT->isFloatingPoint();
00813   return false;
00814 }
00815 
00816 bool Type::isRealType() const {
00817   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
00818     return BT->getKind() >= BuiltinType::Bool &&
00819            BT->getKind() <= BuiltinType::LongDouble;
00820   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
00821       return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
00822   return false;
00823 }
00824 
00825 bool Type::isArithmeticType() const {
00826   if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
00827     return BT->getKind() >= BuiltinType::Bool &&
00828            BT->getKind() <= BuiltinType::LongDouble;
00829   if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
00830     // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
00831     // If a body isn't seen by the time we get here, return false.
00832     //
00833     // C++0x: Enumerations are not arithmetic types. For now, just return
00834     // false for scoped enumerations since that will disable any
00835     // unwanted implicit conversions.
00836     return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete();
00837   return isa<ComplexType>(CanonicalType);
00838 }
00839 
00840 Type::ScalarTypeKind Type::getScalarTypeKind() const {
00841   assert(isScalarType());
00842 
00843   const Type *T = CanonicalType.getTypePtr();
00844   if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) {
00845     if (BT->getKind() == BuiltinType::Bool) return STK_Bool;
00846     if (BT->getKind() == BuiltinType::NullPtr) return STK_CPointer;
00847     if (BT->isInteger()) return STK_Integral;
00848     if (BT->isFloatingPoint()) return STK_Floating;
00849     llvm_unreachable("unknown scalar builtin type");
00850   } else if (isa<PointerType>(T)) {
00851     return STK_CPointer;
00852   } else if (isa<BlockPointerType>(T)) {
00853     return STK_BlockPointer;
00854   } else if (isa<ObjCObjectPointerType>(T)) {
00855     return STK_ObjCObjectPointer;
00856   } else if (isa<MemberPointerType>(T)) {
00857     return STK_MemberPointer;
00858   } else if (isa<EnumType>(T)) {
00859     assert(cast<EnumType>(T)->getDecl()->isComplete());
00860     return STK_Integral;
00861   } else if (const ComplexType *CT = dyn_cast<ComplexType>(T)) {
00862     if (CT->getElementType()->isRealFloatingType())
00863       return STK_FloatingComplex;
00864     return STK_IntegralComplex;
00865   }
00866 
00867   llvm_unreachable("unknown scalar type");
00868 }
00869 
00870 /// \brief Determines whether the type is a C++ aggregate type or C
00871 /// aggregate or union type.
00872 ///
00873 /// An aggregate type is an array or a class type (struct, union, or
00874 /// class) that has no user-declared constructors, no private or
00875 /// protected non-static data members, no base classes, and no virtual
00876 /// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
00877 /// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
00878 /// includes union types.
00879 bool Type::isAggregateType() const {
00880   if (const RecordType *Record = dyn_cast<RecordType>(CanonicalType)) {
00881     if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
00882       return ClassDecl->isAggregate();
00883 
00884     return true;
00885   }
00886 
00887   return isa<ArrayType>(CanonicalType);
00888 }
00889 
00890 /// isConstantSizeType - Return true if this is not a variable sized type,
00891 /// according to the rules of C99 6.7.5p3.  It is not legal to call this on
00892 /// incomplete types or dependent types.
00893 bool Type::isConstantSizeType() const {
00894   assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
00895   assert(!isDependentType() && "This doesn't make sense for dependent types");
00896   // The VAT must have a size, as it is known to be complete.
00897   return !isa<VariableArrayType>(CanonicalType);
00898 }
00899 
00900 /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
00901 /// - a type that can describe objects, but which lacks information needed to
00902 /// determine its size.
00903 bool Type::isIncompleteType(NamedDecl **Def) const {
00904   if (Def)
00905     *Def = nullptr;
00906 
00907   switch (CanonicalType->getTypeClass()) {
00908   default: return false;
00909   case Builtin:
00910     // Void is the only incomplete builtin type.  Per C99 6.2.5p19, it can never
00911     // be completed.
00912     return isVoidType();
00913   case Enum: {
00914     EnumDecl *EnumD = cast<EnumType>(CanonicalType)->getDecl();
00915     if (Def)
00916       *Def = EnumD;
00917     
00918     // An enumeration with fixed underlying type is complete (C++0x 7.2p3).
00919     if (EnumD->isFixed())
00920       return false;
00921     
00922     return !EnumD->isCompleteDefinition();
00923   }
00924   case Record: {
00925     // A tagged type (struct/union/enum/class) is incomplete if the decl is a
00926     // forward declaration, but not a full definition (C99 6.2.5p22).
00927     RecordDecl *Rec = cast<RecordType>(CanonicalType)->getDecl();
00928     if (Def)
00929       *Def = Rec;
00930     return !Rec->isCompleteDefinition();
00931   }
00932   case ConstantArray:
00933     // An array is incomplete if its element type is incomplete
00934     // (C++ [dcl.array]p1).
00935     // We don't handle variable arrays (they're not allowed in C++) or
00936     // dependent-sized arrays (dependent types are never treated as incomplete).
00937     return cast<ArrayType>(CanonicalType)->getElementType()
00938              ->isIncompleteType(Def);
00939   case IncompleteArray:
00940     // An array of unknown size is an incomplete type (C99 6.2.5p22).
00941     return true;
00942   case ObjCObject:
00943     return cast<ObjCObjectType>(CanonicalType)->getBaseType()
00944              ->isIncompleteType(Def);
00945   case ObjCInterface: {
00946     // ObjC interfaces are incomplete if they are @class, not @interface.
00947     ObjCInterfaceDecl *Interface
00948       = cast<ObjCInterfaceType>(CanonicalType)->getDecl();
00949     if (Def)
00950       *Def = Interface;
00951     return !Interface->hasDefinition();
00952   }
00953   }
00954 }
00955 
00956 bool QualType::isPODType(ASTContext &Context) const {
00957   // C++11 has a more relaxed definition of POD.
00958   if (Context.getLangOpts().CPlusPlus11)
00959     return isCXX11PODType(Context);
00960 
00961   return isCXX98PODType(Context);
00962 }
00963 
00964 bool QualType::isCXX98PODType(ASTContext &Context) const {
00965   // The compiler shouldn't query this for incomplete types, but the user might.
00966   // We return false for that case. Except for incomplete arrays of PODs, which
00967   // are PODs according to the standard.
00968   if (isNull())
00969     return 0;
00970   
00971   if ((*this)->isIncompleteArrayType())
00972     return Context.getBaseElementType(*this).isCXX98PODType(Context);
00973     
00974   if ((*this)->isIncompleteType())
00975     return false;
00976 
00977   if (Context.getLangOpts().ObjCAutoRefCount) {
00978     switch (getObjCLifetime()) {
00979     case Qualifiers::OCL_ExplicitNone:
00980       return true;
00981       
00982     case Qualifiers::OCL_Strong:
00983     case Qualifiers::OCL_Weak:
00984     case Qualifiers::OCL_Autoreleasing:
00985       return false;
00986 
00987     case Qualifiers::OCL_None:
00988       break;
00989     }        
00990   }
00991   
00992   QualType CanonicalType = getTypePtr()->CanonicalType;
00993   switch (CanonicalType->getTypeClass()) {
00994     // Everything not explicitly mentioned is not POD.
00995   default: return false;
00996   case Type::VariableArray:
00997   case Type::ConstantArray:
00998     // IncompleteArray is handled above.
00999     return Context.getBaseElementType(*this).isCXX98PODType(Context);
01000         
01001   case Type::ObjCObjectPointer:
01002   case Type::BlockPointer:
01003   case Type::Builtin:
01004   case Type::Complex:
01005   case Type::Pointer:
01006   case Type::MemberPointer:
01007   case Type::Vector:
01008   case Type::ExtVector:
01009     return true;
01010 
01011   case Type::Enum:
01012     return true;
01013 
01014   case Type::Record:
01015     if (CXXRecordDecl *ClassDecl
01016           = dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
01017       return ClassDecl->isPOD();
01018 
01019     // C struct/union is POD.
01020     return true;
01021   }
01022 }
01023 
01024 bool QualType::isTrivialType(ASTContext &Context) const {
01025   // The compiler shouldn't query this for incomplete types, but the user might.
01026   // We return false for that case. Except for incomplete arrays of PODs, which
01027   // are PODs according to the standard.
01028   if (isNull())
01029     return 0;
01030   
01031   if ((*this)->isArrayType())
01032     return Context.getBaseElementType(*this).isTrivialType(Context);
01033   
01034   // Return false for incomplete types after skipping any incomplete array
01035   // types which are expressly allowed by the standard and thus our API.
01036   if ((*this)->isIncompleteType())
01037     return false;
01038   
01039   if (Context.getLangOpts().ObjCAutoRefCount) {
01040     switch (getObjCLifetime()) {
01041     case Qualifiers::OCL_ExplicitNone:
01042       return true;
01043       
01044     case Qualifiers::OCL_Strong:
01045     case Qualifiers::OCL_Weak:
01046     case Qualifiers::OCL_Autoreleasing:
01047       return false;
01048       
01049     case Qualifiers::OCL_None:
01050       if ((*this)->isObjCLifetimeType())
01051         return false;
01052       break;
01053     }        
01054   }
01055   
01056   QualType CanonicalType = getTypePtr()->CanonicalType;
01057   if (CanonicalType->isDependentType())
01058     return false;
01059   
01060   // C++0x [basic.types]p9:
01061   //   Scalar types, trivial class types, arrays of such types, and
01062   //   cv-qualified versions of these types are collectively called trivial
01063   //   types.
01064   
01065   // As an extension, Clang treats vector types as Scalar types.
01066   if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
01067     return true;
01068   if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
01069     if (const CXXRecordDecl *ClassDecl =
01070         dyn_cast<CXXRecordDecl>(RT->getDecl())) {
01071       // C++11 [class]p6:
01072       //   A trivial class is a class that has a default constructor,
01073       //   has no non-trivial default constructors, and is trivially
01074       //   copyable.
01075       return ClassDecl->hasDefaultConstructor() &&
01076              !ClassDecl->hasNonTrivialDefaultConstructor() &&
01077              ClassDecl->isTriviallyCopyable();
01078     }
01079     
01080     return true;
01081   }
01082   
01083   // No other types can match.
01084   return false;
01085 }
01086 
01087 bool QualType::isTriviallyCopyableType(ASTContext &Context) const {
01088   if ((*this)->isArrayType())
01089     return Context.getBaseElementType(*this).isTrivialType(Context);
01090 
01091   if (Context.getLangOpts().ObjCAutoRefCount) {
01092     switch (getObjCLifetime()) {
01093     case Qualifiers::OCL_ExplicitNone:
01094       return true;
01095       
01096     case Qualifiers::OCL_Strong:
01097     case Qualifiers::OCL_Weak:
01098     case Qualifiers::OCL_Autoreleasing:
01099       return false;
01100       
01101     case Qualifiers::OCL_None:
01102       if ((*this)->isObjCLifetimeType())
01103         return false;
01104       break;
01105     }        
01106   }
01107 
01108   // C++11 [basic.types]p9
01109   //   Scalar types, trivially copyable class types, arrays of such types, and
01110   //   non-volatile const-qualified versions of these types are collectively
01111   //   called trivially copyable types.
01112 
01113   QualType CanonicalType = getCanonicalType();
01114   if (CanonicalType->isDependentType())
01115     return false;
01116 
01117   if (CanonicalType.isVolatileQualified())
01118     return false;
01119 
01120   // Return false for incomplete types after skipping any incomplete array types
01121   // which are expressly allowed by the standard and thus our API.
01122   if (CanonicalType->isIncompleteType())
01123     return false;
01124  
01125   // As an extension, Clang treats vector types as Scalar types.
01126   if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
01127     return true;
01128 
01129   if (const RecordType *RT = CanonicalType->getAs<RecordType>()) {
01130     if (const CXXRecordDecl *ClassDecl =
01131           dyn_cast<CXXRecordDecl>(RT->getDecl())) {
01132       if (!ClassDecl->isTriviallyCopyable()) return false;
01133     }
01134 
01135     return true;
01136   }
01137 
01138   // No other types can match.
01139   return false;
01140 }
01141 
01142 
01143 
01144 bool Type::isLiteralType(const ASTContext &Ctx) const {
01145   if (isDependentType())
01146     return false;
01147 
01148   // C++1y [basic.types]p10:
01149   //   A type is a literal type if it is:
01150   //   -- cv void; or
01151   if (Ctx.getLangOpts().CPlusPlus14 && isVoidType())
01152     return true;
01153 
01154   // C++11 [basic.types]p10:
01155   //   A type is a literal type if it is:
01156   //   [...]
01157   //   -- an array of literal type other than an array of runtime bound; or
01158   if (isVariableArrayType())
01159     return false;
01160   const Type *BaseTy = getBaseElementTypeUnsafe();
01161   assert(BaseTy && "NULL element type");
01162 
01163   // Return false for incomplete types after skipping any incomplete array
01164   // types; those are expressly allowed by the standard and thus our API.
01165   if (BaseTy->isIncompleteType())
01166     return false;
01167 
01168   // C++11 [basic.types]p10:
01169   //   A type is a literal type if it is:
01170   //    -- a scalar type; or
01171   // As an extension, Clang treats vector types and complex types as
01172   // literal types.
01173   if (BaseTy->isScalarType() || BaseTy->isVectorType() ||
01174       BaseTy->isAnyComplexType())
01175     return true;
01176   //    -- a reference type; or
01177   if (BaseTy->isReferenceType())
01178     return true;
01179   //    -- a class type that has all of the following properties:
01180   if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
01181     //    -- a trivial destructor,
01182     //    -- every constructor call and full-expression in the
01183     //       brace-or-equal-initializers for non-static data members (if any)
01184     //       is a constant expression,
01185     //    -- it is an aggregate type or has at least one constexpr
01186     //       constructor or constructor template that is not a copy or move
01187     //       constructor, and
01188     //    -- all non-static data members and base classes of literal types
01189     //
01190     // We resolve DR1361 by ignoring the second bullet.
01191     if (const CXXRecordDecl *ClassDecl =
01192         dyn_cast<CXXRecordDecl>(RT->getDecl()))
01193       return ClassDecl->isLiteral();
01194 
01195     return true;
01196   }
01197 
01198   // We treat _Atomic T as a literal type if T is a literal type.
01199   if (const AtomicType *AT = BaseTy->getAs<AtomicType>())
01200     return AT->getValueType()->isLiteralType(Ctx);
01201 
01202   // If this type hasn't been deduced yet, then conservatively assume that
01203   // it'll work out to be a literal type.
01204   if (isa<AutoType>(BaseTy->getCanonicalTypeInternal()))
01205     return true;
01206 
01207   return false;
01208 }
01209 
01210 bool Type::isStandardLayoutType() const {
01211   if (isDependentType())
01212     return false;
01213 
01214   // C++0x [basic.types]p9:
01215   //   Scalar types, standard-layout class types, arrays of such types, and
01216   //   cv-qualified versions of these types are collectively called
01217   //   standard-layout types.
01218   const Type *BaseTy = getBaseElementTypeUnsafe();
01219   assert(BaseTy && "NULL element type");
01220 
01221   // Return false for incomplete types after skipping any incomplete array
01222   // types which are expressly allowed by the standard and thus our API.
01223   if (BaseTy->isIncompleteType())
01224     return false;
01225 
01226   // As an extension, Clang treats vector types as Scalar types.
01227   if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
01228   if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
01229     if (const CXXRecordDecl *ClassDecl =
01230         dyn_cast<CXXRecordDecl>(RT->getDecl()))
01231       if (!ClassDecl->isStandardLayout())
01232         return false;
01233 
01234     // Default to 'true' for non-C++ class types.
01235     // FIXME: This is a bit dubious, but plain C structs should trivially meet
01236     // all the requirements of standard layout classes.
01237     return true;
01238   }
01239 
01240   // No other types can match.
01241   return false;
01242 }
01243 
01244 // This is effectively the intersection of isTrivialType and
01245 // isStandardLayoutType. We implement it directly to avoid redundant
01246 // conversions from a type to a CXXRecordDecl.
01247 bool QualType::isCXX11PODType(ASTContext &Context) const {
01248   const Type *ty = getTypePtr();
01249   if (ty->isDependentType())
01250     return false;
01251 
01252   if (Context.getLangOpts().ObjCAutoRefCount) {
01253     switch (getObjCLifetime()) {
01254     case Qualifiers::OCL_ExplicitNone:
01255       return true;
01256       
01257     case Qualifiers::OCL_Strong:
01258     case Qualifiers::OCL_Weak:
01259     case Qualifiers::OCL_Autoreleasing:
01260       return false;
01261 
01262     case Qualifiers::OCL_None:
01263       break;
01264     }        
01265   }
01266 
01267   // C++11 [basic.types]p9:
01268   //   Scalar types, POD classes, arrays of such types, and cv-qualified
01269   //   versions of these types are collectively called trivial types.
01270   const Type *BaseTy = ty->getBaseElementTypeUnsafe();
01271   assert(BaseTy && "NULL element type");
01272 
01273   // Return false for incomplete types after skipping any incomplete array
01274   // types which are expressly allowed by the standard and thus our API.
01275   if (BaseTy->isIncompleteType())
01276     return false;
01277 
01278   // As an extension, Clang treats vector types as Scalar types.
01279   if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
01280   if (const RecordType *RT = BaseTy->getAs<RecordType>()) {
01281     if (const CXXRecordDecl *ClassDecl =
01282         dyn_cast<CXXRecordDecl>(RT->getDecl())) {
01283       // C++11 [class]p10:
01284       //   A POD struct is a non-union class that is both a trivial class [...]
01285       if (!ClassDecl->isTrivial()) return false;
01286 
01287       // C++11 [class]p10:
01288       //   A POD struct is a non-union class that is both a trivial class and
01289       //   a standard-layout class [...]
01290       if (!ClassDecl->isStandardLayout()) return false;
01291 
01292       // C++11 [class]p10:
01293       //   A POD struct is a non-union class that is both a trivial class and
01294       //   a standard-layout class, and has no non-static data members of type
01295       //   non-POD struct, non-POD union (or array of such types). [...]
01296       //
01297       // We don't directly query the recursive aspect as the requiremets for
01298       // both standard-layout classes and trivial classes apply recursively
01299       // already.
01300     }
01301 
01302     return true;
01303   }
01304 
01305   // No other types can match.
01306   return false;
01307 }
01308 
01309 bool Type::isPromotableIntegerType() const {
01310   if (const BuiltinType *BT = getAs<BuiltinType>())
01311     switch (BT->getKind()) {
01312     case BuiltinType::Bool:
01313     case BuiltinType::Char_S:
01314     case BuiltinType::Char_U:
01315     case BuiltinType::SChar:
01316     case BuiltinType::UChar:
01317     case BuiltinType::Short:
01318     case BuiltinType::UShort:
01319     case BuiltinType::WChar_S:
01320     case BuiltinType::WChar_U:
01321     case BuiltinType::Char16:
01322     case BuiltinType::Char32:
01323       return true;
01324     default:
01325       return false;
01326     }
01327 
01328   // Enumerated types are promotable to their compatible integer types
01329   // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
01330   if (const EnumType *ET = getAs<EnumType>()){
01331     if (this->isDependentType() || ET->getDecl()->getPromotionType().isNull()
01332         || ET->getDecl()->isScoped())
01333       return false;
01334     
01335     return true;
01336   }
01337   
01338   return false;
01339 }
01340 
01341 bool Type::isSpecifierType() const {
01342   // Note that this intentionally does not use the canonical type.
01343   switch (getTypeClass()) {
01344   case Builtin:
01345   case Record:
01346   case Enum:
01347   case Typedef:
01348   case Complex:
01349   case TypeOfExpr:
01350   case TypeOf:
01351   case TemplateTypeParm:
01352   case SubstTemplateTypeParm:
01353   case TemplateSpecialization:
01354   case Elaborated:
01355   case DependentName:
01356   case DependentTemplateSpecialization:
01357   case ObjCInterface:
01358   case ObjCObject:
01359   case ObjCObjectPointer: // FIXME: object pointers aren't really specifiers
01360     return true;
01361   default:
01362     return false;
01363   }
01364 }
01365 
01366 ElaboratedTypeKeyword
01367 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) {
01368   switch (TypeSpec) {
01369   default: return ETK_None;
01370   case TST_typename: return ETK_Typename;
01371   case TST_class: return ETK_Class;
01372   case TST_struct: return ETK_Struct;
01373   case TST_interface: return ETK_Interface;
01374   case TST_union: return ETK_Union;
01375   case TST_enum: return ETK_Enum;
01376   }
01377 }
01378 
01379 TagTypeKind
01380 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
01381   switch(TypeSpec) {
01382   case TST_class: return TTK_Class;
01383   case TST_struct: return TTK_Struct;
01384   case TST_interface: return TTK_Interface;
01385   case TST_union: return TTK_Union;
01386   case TST_enum: return TTK_Enum;
01387   }
01388   
01389   llvm_unreachable("Type specifier is not a tag type kind.");
01390 }
01391 
01392 ElaboratedTypeKeyword
01393 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) {
01394   switch (Kind) {
01395   case TTK_Class: return ETK_Class;
01396   case TTK_Struct: return ETK_Struct;
01397   case TTK_Interface: return ETK_Interface;
01398   case TTK_Union: return ETK_Union;
01399   case TTK_Enum: return ETK_Enum;
01400   }
01401   llvm_unreachable("Unknown tag type kind.");
01402 }
01403 
01404 TagTypeKind
01405 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
01406   switch (Keyword) {
01407   case ETK_Class: return TTK_Class;
01408   case ETK_Struct: return TTK_Struct;
01409   case ETK_Interface: return TTK_Interface;
01410   case ETK_Union: return TTK_Union;
01411   case ETK_Enum: return TTK_Enum;
01412   case ETK_None: // Fall through.
01413   case ETK_Typename:
01414     llvm_unreachable("Elaborated type keyword is not a tag type kind.");
01415   }
01416   llvm_unreachable("Unknown elaborated type keyword.");
01417 }
01418 
01419 bool
01420 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
01421   switch (Keyword) {
01422   case ETK_None:
01423   case ETK_Typename:
01424     return false;
01425   case ETK_Class:
01426   case ETK_Struct:
01427   case ETK_Interface:
01428   case ETK_Union:
01429   case ETK_Enum:
01430     return true;
01431   }
01432   llvm_unreachable("Unknown elaborated type keyword.");
01433 }
01434 
01435 StringRef TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) {
01436   switch (Keyword) {
01437   case ETK_None: return "";
01438   case ETK_Typename: return "typename";
01439   case ETK_Class:  return "class";
01440   case ETK_Struct: return "struct";
01441   case ETK_Interface: return "__interface";
01442   case ETK_Union:  return "union";
01443   case ETK_Enum:   return "enum";
01444   }
01445 
01446   llvm_unreachable("Unknown elaborated type keyword.");
01447 }
01448 
01449 DependentTemplateSpecializationType::DependentTemplateSpecializationType(
01450                          ElaboratedTypeKeyword Keyword,
01451                          NestedNameSpecifier *NNS, const IdentifierInfo *Name,
01452                          unsigned NumArgs, const TemplateArgument *Args,
01453                          QualType Canon)
01454   : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon, true, true,
01455                     /*VariablyModified=*/false,
01456                     NNS && NNS->containsUnexpandedParameterPack()),
01457     NNS(NNS), Name(Name), NumArgs(NumArgs) {
01458   assert((!NNS || NNS->isDependent()) &&
01459          "DependentTemplateSpecializatonType requires dependent qualifier");
01460   for (unsigned I = 0; I != NumArgs; ++I) {
01461     if (Args[I].containsUnexpandedParameterPack())
01462       setContainsUnexpandedParameterPack();
01463 
01464     new (&getArgBuffer()[I]) TemplateArgument(Args[I]);
01465   }
01466 }
01467 
01468 void
01469 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
01470                                              const ASTContext &Context,
01471                                              ElaboratedTypeKeyword Keyword,
01472                                              NestedNameSpecifier *Qualifier,
01473                                              const IdentifierInfo *Name,
01474                                              unsigned NumArgs,
01475                                              const TemplateArgument *Args) {
01476   ID.AddInteger(Keyword);
01477   ID.AddPointer(Qualifier);
01478   ID.AddPointer(Name);
01479   for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
01480     Args[Idx].Profile(ID, Context);
01481 }
01482 
01483 bool Type::isElaboratedTypeSpecifier() const {
01484   ElaboratedTypeKeyword Keyword;
01485   if (const ElaboratedType *Elab = dyn_cast<ElaboratedType>(this))
01486     Keyword = Elab->getKeyword();
01487   else if (const DependentNameType *DepName = dyn_cast<DependentNameType>(this))
01488     Keyword = DepName->getKeyword();
01489   else if (const DependentTemplateSpecializationType *DepTST =
01490              dyn_cast<DependentTemplateSpecializationType>(this))
01491     Keyword = DepTST->getKeyword();
01492   else
01493     return false;
01494 
01495   return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
01496 }
01497 
01498 const char *Type::getTypeClassName() const {
01499   switch (TypeBits.TC) {
01500 #define ABSTRACT_TYPE(Derived, Base)
01501 #define TYPE(Derived, Base) case Derived: return #Derived;
01502 #include "clang/AST/TypeNodes.def"
01503   }
01504   
01505   llvm_unreachable("Invalid type class.");
01506 }
01507 
01508 StringRef BuiltinType::getName(const PrintingPolicy &Policy) const {
01509   switch (getKind()) {
01510   case Void:              return "void";
01511   case Bool:              return Policy.Bool ? "bool" : "_Bool";
01512   case Char_S:            return "char";
01513   case Char_U:            return "char";
01514   case SChar:             return "signed char";
01515   case Short:             return "short";
01516   case Int:               return "int";
01517   case Long:              return "long";
01518   case LongLong:          return "long long";
01519   case Int128:            return "__int128";
01520   case UChar:             return "unsigned char";
01521   case UShort:            return "unsigned short";
01522   case UInt:              return "unsigned int";
01523   case ULong:             return "unsigned long";
01524   case ULongLong:         return "unsigned long long";
01525   case UInt128:           return "unsigned __int128";
01526   case Half:              return Policy.Half ? "half" : "__fp16";
01527   case Float:             return "float";
01528   case Double:            return "double";
01529   case LongDouble:        return "long double";
01530   case WChar_S:
01531   case WChar_U:           return Policy.MSWChar ? "__wchar_t" : "wchar_t";
01532   case Char16:            return "char16_t";
01533   case Char32:            return "char32_t";
01534   case NullPtr:           return "nullptr_t";
01535   case Overload:          return "<overloaded function type>";
01536   case BoundMember:       return "<bound member function type>";
01537   case PseudoObject:      return "<pseudo-object type>";
01538   case Dependent:         return "<dependent type>";
01539   case UnknownAny:        return "<unknown type>";
01540   case ARCUnbridgedCast:  return "<ARC unbridged cast type>";
01541   case BuiltinFn:         return "<builtin fn type>";
01542   case ObjCId:            return "id";
01543   case ObjCClass:         return "Class";
01544   case ObjCSel:           return "SEL";
01545   case OCLImage1d:        return "image1d_t";
01546   case OCLImage1dArray:   return "image1d_array_t";
01547   case OCLImage1dBuffer:  return "image1d_buffer_t";
01548   case OCLImage2d:        return "image2d_t";
01549   case OCLImage2dArray:   return "image2d_array_t";
01550   case OCLImage3d:        return "image3d_t";
01551   case OCLSampler:        return "sampler_t";
01552   case OCLEvent:          return "event_t";
01553   }
01554   
01555   llvm_unreachable("Invalid builtin type.");
01556 }
01557 
01558 QualType QualType::getNonLValueExprType(const ASTContext &Context) const {
01559   if (const ReferenceType *RefType = getTypePtr()->getAs<ReferenceType>())
01560     return RefType->getPointeeType();
01561   
01562   // C++0x [basic.lval]:
01563   //   Class prvalues can have cv-qualified types; non-class prvalues always 
01564   //   have cv-unqualified types.
01565   //
01566   // See also C99 6.3.2.1p2.
01567   if (!Context.getLangOpts().CPlusPlus ||
01568       (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
01569     return getUnqualifiedType();
01570   
01571   return *this;
01572 }
01573 
01574 StringRef FunctionType::getNameForCallConv(CallingConv CC) {
01575   switch (CC) {
01576   case CC_C: return "cdecl";
01577   case CC_X86StdCall: return "stdcall";
01578   case CC_X86FastCall: return "fastcall";
01579   case CC_X86ThisCall: return "thiscall";
01580   case CC_X86Pascal: return "pascal";
01581   case CC_X86VectorCall: return "vectorcall";
01582   case CC_X86_64Win64: return "ms_abi";
01583   case CC_X86_64SysV: return "sysv_abi";
01584   case CC_AAPCS: return "aapcs";
01585   case CC_AAPCS_VFP: return "aapcs-vfp";
01586   case CC_PnaclCall: return "pnaclcall";
01587   case CC_IntelOclBicc: return "intel_ocl_bicc";
01588   }
01589 
01590   llvm_unreachable("Invalid calling convention.");
01591 }
01592 
01593 FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> params,
01594                                      QualType canonical,
01595                                      const ExtProtoInfo &epi)
01596     : FunctionType(FunctionProto, result, canonical,
01597                    result->isDependentType(),
01598                    result->isInstantiationDependentType(),
01599                    result->isVariablyModifiedType(),
01600                    result->containsUnexpandedParameterPack(), epi.ExtInfo),
01601       NumParams(params.size()),
01602       NumExceptions(epi.ExceptionSpec.Exceptions.size()),
01603       ExceptionSpecType(epi.ExceptionSpec.Type),
01604       HasAnyConsumedParams(epi.ConsumedParameters != nullptr),
01605       Variadic(epi.Variadic), HasTrailingReturn(epi.HasTrailingReturn) {
01606   assert(NumParams == params.size() && "function has too many parameters");
01607 
01608   FunctionTypeBits.TypeQuals = epi.TypeQuals;
01609   FunctionTypeBits.RefQualifier = epi.RefQualifier;
01610 
01611   // Fill in the trailing argument array.
01612   QualType *argSlot = reinterpret_cast<QualType*>(this+1);
01613   for (unsigned i = 0; i != NumParams; ++i) {
01614     if (params[i]->isDependentType())
01615       setDependent();
01616     else if (params[i]->isInstantiationDependentType())
01617       setInstantiationDependent();
01618 
01619     if (params[i]->containsUnexpandedParameterPack())
01620       setContainsUnexpandedParameterPack();
01621 
01622     argSlot[i] = params[i];
01623   }
01624 
01625   if (getExceptionSpecType() == EST_Dynamic) {
01626     // Fill in the exception array.
01627     QualType *exnSlot = argSlot + NumParams;
01628     unsigned I = 0;
01629     for (QualType ExceptionType : epi.ExceptionSpec.Exceptions) {
01630       // Note that a dependent exception specification does *not* make
01631       // a type dependent; it's not even part of the C++ type system.
01632       if (ExceptionType->isInstantiationDependentType())
01633         setInstantiationDependent();
01634 
01635       if (ExceptionType->containsUnexpandedParameterPack())
01636         setContainsUnexpandedParameterPack();
01637 
01638       exnSlot[I++] = ExceptionType;
01639     }
01640   } else if (getExceptionSpecType() == EST_ComputedNoexcept) {
01641     // Store the noexcept expression and context.
01642     Expr **noexSlot = reinterpret_cast<Expr **>(argSlot + NumParams);
01643     *noexSlot = epi.ExceptionSpec.NoexceptExpr;
01644 
01645     if (epi.ExceptionSpec.NoexceptExpr) {
01646       if (epi.ExceptionSpec.NoexceptExpr->isValueDependent() ||
01647           epi.ExceptionSpec.NoexceptExpr->isInstantiationDependent())
01648         setInstantiationDependent();
01649 
01650       if (epi.ExceptionSpec.NoexceptExpr->containsUnexpandedParameterPack())
01651         setContainsUnexpandedParameterPack();
01652     }
01653   } else if (getExceptionSpecType() == EST_Uninstantiated) {
01654     // Store the function decl from which we will resolve our
01655     // exception specification.
01656     FunctionDecl **slot =
01657         reinterpret_cast<FunctionDecl **>(argSlot + NumParams);
01658     slot[0] = epi.ExceptionSpec.SourceDecl;
01659     slot[1] = epi.ExceptionSpec.SourceTemplate;
01660     // This exception specification doesn't make the type dependent, because
01661     // it's not instantiated as part of instantiating the type.
01662   } else if (getExceptionSpecType() == EST_Unevaluated) {
01663     // Store the function decl from which we will resolve our
01664     // exception specification.
01665     FunctionDecl **slot =
01666         reinterpret_cast<FunctionDecl **>(argSlot + NumParams);
01667     slot[0] = epi.ExceptionSpec.SourceDecl;
01668   }
01669 
01670   if (epi.ConsumedParameters) {
01671     bool *consumedParams = const_cast<bool *>(getConsumedParamsBuffer());
01672     for (unsigned i = 0; i != NumParams; ++i)
01673       consumedParams[i] = epi.ConsumedParameters[i];
01674   }
01675 }
01676 
01677 bool FunctionProtoType::hasDependentExceptionSpec() const {
01678   if (Expr *NE = getNoexceptExpr())
01679     return NE->isValueDependent();
01680   for (QualType ET : exceptions())
01681     // A pack expansion with a non-dependent pattern is still dependent,
01682     // because we don't know whether the pattern is in the exception spec
01683     // or not (that depends on whether the pack has 0 expansions).
01684     if (ET->isDependentType() || ET->getAs<PackExpansionType>())
01685       return true;
01686   return false;
01687 }
01688 
01689 FunctionProtoType::NoexceptResult
01690 FunctionProtoType::getNoexceptSpec(const ASTContext &ctx) const {
01691   ExceptionSpecificationType est = getExceptionSpecType();
01692   if (est == EST_BasicNoexcept)
01693     return NR_Nothrow;
01694 
01695   if (est != EST_ComputedNoexcept)
01696     return NR_NoNoexcept;
01697 
01698   Expr *noexceptExpr = getNoexceptExpr();
01699   if (!noexceptExpr)
01700     return NR_BadNoexcept;
01701   if (noexceptExpr->isValueDependent())
01702     return NR_Dependent;
01703 
01704   llvm::APSInt value;
01705   bool isICE = noexceptExpr->isIntegerConstantExpr(value, ctx, nullptr,
01706                                                    /*evaluated*/false);
01707   (void)isICE;
01708   assert(isICE && "AST should not contain bad noexcept expressions.");
01709 
01710   return value.getBoolValue() ? NR_Nothrow : NR_Throw;
01711 }
01712 
01713 bool FunctionProtoType::isNothrow(const ASTContext &Ctx,
01714                                   bool ResultIfDependent) const {
01715   ExceptionSpecificationType EST = getExceptionSpecType();
01716   assert(EST != EST_Unevaluated && EST != EST_Uninstantiated);
01717   if (EST == EST_DynamicNone || EST == EST_BasicNoexcept)
01718     return true;
01719 
01720   if (EST == EST_Dynamic && ResultIfDependent == true) {
01721     // A dynamic exception specification is throwing unless every exception
01722     // type is an (unexpanded) pack expansion type.
01723     for (unsigned I = 0, N = NumExceptions; I != N; ++I)
01724       if (!getExceptionType(I)->getAs<PackExpansionType>())
01725         return false;
01726     return ResultIfDependent;
01727   }
01728 
01729   if (EST != EST_ComputedNoexcept)
01730     return false;
01731 
01732   NoexceptResult NR = getNoexceptSpec(Ctx);
01733   if (NR == NR_Dependent)
01734     return ResultIfDependent;
01735   return NR == NR_Nothrow;
01736 }
01737 
01738 bool FunctionProtoType::isTemplateVariadic() const {
01739   for (unsigned ArgIdx = getNumParams(); ArgIdx; --ArgIdx)
01740     if (isa<PackExpansionType>(getParamType(ArgIdx - 1)))
01741       return true;
01742   
01743   return false;
01744 }
01745 
01746 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
01747                                 const QualType *ArgTys, unsigned NumParams,
01748                                 const ExtProtoInfo &epi,
01749                                 const ASTContext &Context) {
01750 
01751   // We have to be careful not to get ambiguous profile encodings.
01752   // Note that valid type pointers are never ambiguous with anything else.
01753   //
01754   // The encoding grammar begins:
01755   //      type type* bool int bool 
01756   // If that final bool is true, then there is a section for the EH spec:
01757   //      bool type*
01758   // This is followed by an optional "consumed argument" section of the
01759   // same length as the first type sequence:
01760   //      bool*
01761   // Finally, we have the ext info and trailing return type flag:
01762   //      int bool
01763   // 
01764   // There is no ambiguity between the consumed arguments and an empty EH
01765   // spec because of the leading 'bool' which unambiguously indicates
01766   // whether the following bool is the EH spec or part of the arguments.
01767 
01768   ID.AddPointer(Result.getAsOpaquePtr());
01769   for (unsigned i = 0; i != NumParams; ++i)
01770     ID.AddPointer(ArgTys[i].getAsOpaquePtr());
01771   // This method is relatively performance sensitive, so as a performance
01772   // shortcut, use one AddInteger call instead of four for the next four
01773   // fields.
01774   assert(!(unsigned(epi.Variadic) & ~1) &&
01775          !(unsigned(epi.TypeQuals) & ~255) &&
01776          !(unsigned(epi.RefQualifier) & ~3) &&
01777          !(unsigned(epi.ExceptionSpec.Type) & ~15) &&
01778          "Values larger than expected.");
01779   ID.AddInteger(unsigned(epi.Variadic) +
01780                 (epi.TypeQuals << 1) +
01781                 (epi.RefQualifier << 9) +
01782                 (epi.ExceptionSpec.Type << 11));
01783   if (epi.ExceptionSpec.Type == EST_Dynamic) {
01784     for (QualType Ex : epi.ExceptionSpec.Exceptions)
01785       ID.AddPointer(Ex.getAsOpaquePtr());
01786   } else if (epi.ExceptionSpec.Type == EST_ComputedNoexcept &&
01787              epi.ExceptionSpec.NoexceptExpr) {
01788     epi.ExceptionSpec.NoexceptExpr->Profile(ID, Context, false);
01789   } else if (epi.ExceptionSpec.Type == EST_Uninstantiated ||
01790              epi.ExceptionSpec.Type == EST_Unevaluated) {
01791     ID.AddPointer(epi.ExceptionSpec.SourceDecl->getCanonicalDecl());
01792   }
01793   if (epi.ConsumedParameters) {
01794     for (unsigned i = 0; i != NumParams; ++i)
01795       ID.AddBoolean(epi.ConsumedParameters[i]);
01796   }
01797   epi.ExtInfo.Profile(ID);
01798   ID.AddBoolean(epi.HasTrailingReturn);
01799 }
01800 
01801 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
01802                                 const ASTContext &Ctx) {
01803   Profile(ID, getReturnType(), param_type_begin(), NumParams, getExtProtoInfo(),
01804           Ctx);
01805 }
01806 
01807 QualType TypedefType::desugar() const {
01808   return getDecl()->getUnderlyingType();
01809 }
01810 
01811 TypeOfExprType::TypeOfExprType(Expr *E, QualType can)
01812   : Type(TypeOfExpr, can, E->isTypeDependent(), 
01813          E->isInstantiationDependent(),
01814          E->getType()->isVariablyModifiedType(),
01815          E->containsUnexpandedParameterPack()), 
01816     TOExpr(E) {
01817 }
01818 
01819 bool TypeOfExprType::isSugared() const {
01820   return !TOExpr->isTypeDependent();
01821 }
01822 
01823 QualType TypeOfExprType::desugar() const {
01824   if (isSugared())
01825     return getUnderlyingExpr()->getType();
01826   
01827   return QualType(this, 0);
01828 }
01829 
01830 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
01831                                       const ASTContext &Context, Expr *E) {
01832   E->Profile(ID, Context, true);
01833 }
01834 
01835 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
01836   // C++11 [temp.type]p2: "If an expression e involves a template parameter,
01837   // decltype(e) denotes a unique dependent type." Hence a decltype type is
01838   // type-dependent even if its expression is only instantiation-dependent.
01839   : Type(Decltype, can, E->isInstantiationDependent(),
01840          E->isInstantiationDependent(),
01841          E->getType()->isVariablyModifiedType(), 
01842          E->containsUnexpandedParameterPack()), 
01843     E(E),
01844   UnderlyingType(underlyingType) {
01845 }
01846 
01847 bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); }
01848 
01849 QualType DecltypeType::desugar() const {
01850   if (isSugared())
01851     return getUnderlyingType();
01852   
01853   return QualType(this, 0);
01854 }
01855 
01856 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E)
01857   : DecltypeType(E, Context.DependentTy), Context(Context) { }
01858 
01859 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
01860                                     const ASTContext &Context, Expr *E) {
01861   E->Profile(ID, Context, true);
01862 }
01863 
01864 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
01865   : Type(TC, can, D->isDependentType(), 
01866          /*InstantiationDependent=*/D->isDependentType(),
01867          /*VariablyModified=*/false, 
01868          /*ContainsUnexpandedParameterPack=*/false),
01869     decl(const_cast<TagDecl*>(D)) {}
01870 
01871 static TagDecl *getInterestingTagDecl(TagDecl *decl) {
01872   for (auto I : decl->redecls()) {
01873     if (I->isCompleteDefinition() || I->isBeingDefined())
01874       return I;
01875   }
01876   // If there's no definition (not even in progress), return what we have.
01877   return decl;
01878 }
01879 
01880 UnaryTransformType::UnaryTransformType(QualType BaseType,
01881                                        QualType UnderlyingType,
01882                                        UTTKind UKind,
01883                                        QualType CanonicalType)
01884   : Type(UnaryTransform, CanonicalType, UnderlyingType->isDependentType(),
01885          UnderlyingType->isInstantiationDependentType(),
01886          UnderlyingType->isVariablyModifiedType(),
01887          BaseType->containsUnexpandedParameterPack())
01888   , BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind)
01889 {}
01890 
01891 TagDecl *TagType::getDecl() const {
01892   return getInterestingTagDecl(decl);
01893 }
01894 
01895 bool TagType::isBeingDefined() const {
01896   return getDecl()->isBeingDefined();
01897 }
01898 
01899 bool AttributedType::isMSTypeSpec() const {
01900   switch (getAttrKind()) {
01901   default:  return false;
01902   case attr_ptr32:
01903   case attr_ptr64:
01904   case attr_sptr:
01905   case attr_uptr:
01906     return true;
01907   }
01908   llvm_unreachable("invalid attr kind");
01909 }
01910 
01911 bool AttributedType::isCallingConv() const {
01912   switch (getAttrKind()) {
01913   case attr_ptr32:
01914   case attr_ptr64:
01915   case attr_sptr:
01916   case attr_uptr:
01917   case attr_address_space:
01918   case attr_regparm:
01919   case attr_vector_size:
01920   case attr_neon_vector_type:
01921   case attr_neon_polyvector_type:
01922   case attr_objc_gc:
01923   case attr_objc_ownership:
01924   case attr_noreturn:
01925       return false;
01926   case attr_pcs:
01927   case attr_pcs_vfp:
01928   case attr_cdecl:
01929   case attr_fastcall:
01930   case attr_stdcall:
01931   case attr_thiscall:
01932   case attr_vectorcall:
01933   case attr_pascal:
01934   case attr_ms_abi:
01935   case attr_sysv_abi:
01936   case attr_pnaclcall:
01937   case attr_inteloclbicc:
01938     return true;
01939   }
01940   llvm_unreachable("invalid attr kind");
01941 }
01942 
01943 CXXRecordDecl *InjectedClassNameType::getDecl() const {
01944   return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
01945 }
01946 
01947 IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
01948   return isCanonicalUnqualified() ? nullptr : getDecl()->getIdentifier();
01949 }
01950 
01951 SubstTemplateTypeParmPackType::
01952 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param, 
01953                               QualType Canon,
01954                               const TemplateArgument &ArgPack)
01955   : Type(SubstTemplateTypeParmPack, Canon, true, true, false, true), 
01956     Replaced(Param), 
01957     Arguments(ArgPack.pack_begin()), NumArguments(ArgPack.pack_size()) 
01958 { 
01959 }
01960 
01961 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const {
01962   return TemplateArgument(Arguments, NumArguments);
01963 }
01964 
01965 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
01966   Profile(ID, getReplacedParameter(), getArgumentPack());
01967 }
01968 
01969 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
01970                                            const TemplateTypeParmType *Replaced,
01971                                             const TemplateArgument &ArgPack) {
01972   ID.AddPointer(Replaced);
01973   ID.AddInteger(ArgPack.pack_size());
01974   for (const auto &P : ArgPack.pack_elements())
01975     ID.AddPointer(P.getAsType().getAsOpaquePtr());
01976 }
01977 
01978 bool TemplateSpecializationType::
01979 anyDependentTemplateArguments(const TemplateArgumentListInfo &Args,
01980                               bool &InstantiationDependent) {
01981   return anyDependentTemplateArguments(Args.getArgumentArray(), Args.size(),
01982                                        InstantiationDependent);
01983 }
01984 
01985 bool TemplateSpecializationType::
01986 anyDependentTemplateArguments(const TemplateArgumentLoc *Args, unsigned N,
01987                               bool &InstantiationDependent) {
01988   for (unsigned i = 0; i != N; ++i) {
01989     if (Args[i].getArgument().isDependent()) {
01990       InstantiationDependent = true;
01991       return true;
01992     }
01993     
01994     if (Args[i].getArgument().isInstantiationDependent())
01995       InstantiationDependent = true;
01996   }
01997   return false;
01998 }
01999 
02000 TemplateSpecializationType::
02001 TemplateSpecializationType(TemplateName T,
02002                            const TemplateArgument *Args, unsigned NumArgs,
02003                            QualType Canon, QualType AliasedType)
02004   : Type(TemplateSpecialization,
02005          Canon.isNull()? QualType(this, 0) : Canon,
02006          Canon.isNull()? true : Canon->isDependentType(),
02007          Canon.isNull()? true : Canon->isInstantiationDependentType(),
02008          false,
02009          T.containsUnexpandedParameterPack()),
02010     Template(T), NumArgs(NumArgs), TypeAlias(!AliasedType.isNull()) {
02011   assert(!T.getAsDependentTemplateName() && 
02012          "Use DependentTemplateSpecializationType for dependent template-name");
02013   assert((T.getKind() == TemplateName::Template ||
02014           T.getKind() == TemplateName::SubstTemplateTemplateParm ||
02015           T.getKind() == TemplateName::SubstTemplateTemplateParmPack) &&
02016          "Unexpected template name for TemplateSpecializationType");
02017 
02018   TemplateArgument *TemplateArgs
02019     = reinterpret_cast<TemplateArgument *>(this + 1);
02020   for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
02021     // Update instantiation-dependent and variably-modified bits.
02022     // If the canonical type exists and is non-dependent, the template
02023     // specialization type can be non-dependent even if one of the type
02024     // arguments is. Given:
02025     //   template<typename T> using U = int;
02026     // U<T> is always non-dependent, irrespective of the type T.
02027     // However, U<Ts> contains an unexpanded parameter pack, even though
02028     // its expansion (and thus its desugared type) doesn't.
02029     if (Args[Arg].isInstantiationDependent())
02030       setInstantiationDependent();
02031     if (Args[Arg].getKind() == TemplateArgument::Type &&
02032         Args[Arg].getAsType()->isVariablyModifiedType())
02033       setVariablyModified();
02034     if (Args[Arg].containsUnexpandedParameterPack())
02035       setContainsUnexpandedParameterPack();
02036     new (&TemplateArgs[Arg]) TemplateArgument(Args[Arg]);
02037   }
02038 
02039   // Store the aliased type if this is a type alias template specialization.
02040   if (TypeAlias) {
02041     TemplateArgument *Begin = reinterpret_cast<TemplateArgument *>(this + 1);
02042     *reinterpret_cast<QualType*>(Begin + getNumArgs()) = AliasedType;
02043   }
02044 }
02045 
02046 void
02047 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
02048                                     TemplateName T,
02049                                     const TemplateArgument *Args,
02050                                     unsigned NumArgs,
02051                                     const ASTContext &Context) {
02052   T.Profile(ID);
02053   for (unsigned Idx = 0; Idx < NumArgs; ++Idx)
02054     Args[Idx].Profile(ID, Context);
02055 }
02056 
02057 QualType
02058 QualifierCollector::apply(const ASTContext &Context, QualType QT) const {
02059   if (!hasNonFastQualifiers())
02060     return QT.withFastQualifiers(getFastQualifiers());
02061 
02062   return Context.getQualifiedType(QT, *this);
02063 }
02064 
02065 QualType
02066 QualifierCollector::apply(const ASTContext &Context, const Type *T) const {
02067   if (!hasNonFastQualifiers())
02068     return QualType(T, getFastQualifiers());
02069 
02070   return Context.getQualifiedType(T, *this);
02071 }
02072 
02073 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
02074                                  QualType BaseType,
02075                                  ObjCProtocolDecl * const *Protocols,
02076                                  unsigned NumProtocols) {
02077   ID.AddPointer(BaseType.getAsOpaquePtr());
02078   for (unsigned i = 0; i != NumProtocols; i++)
02079     ID.AddPointer(Protocols[i]);
02080 }
02081 
02082 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
02083   Profile(ID, getBaseType(), qual_begin(), getNumProtocols());
02084 }
02085 
02086 namespace {
02087 
02088 /// \brief The cached properties of a type.
02089 class CachedProperties {
02090   Linkage L;
02091   bool local;
02092 
02093 public:
02094   CachedProperties(Linkage L, bool local) : L(L), local(local) {}
02095 
02096   Linkage getLinkage() const { return L; }
02097   bool hasLocalOrUnnamedType() const { return local; }
02098 
02099   friend CachedProperties merge(CachedProperties L, CachedProperties R) {
02100     Linkage MergedLinkage = minLinkage(L.L, R.L);
02101     return CachedProperties(MergedLinkage,
02102                          L.hasLocalOrUnnamedType() | R.hasLocalOrUnnamedType());
02103   }
02104 };
02105 }
02106 
02107 static CachedProperties computeCachedProperties(const Type *T);
02108 
02109 namespace clang {
02110 /// The type-property cache.  This is templated so as to be
02111 /// instantiated at an internal type to prevent unnecessary symbol
02112 /// leakage.
02113 template <class Private> class TypePropertyCache {
02114 public:
02115   static CachedProperties get(QualType T) {
02116     return get(T.getTypePtr());
02117   }
02118 
02119   static CachedProperties get(const Type *T) {
02120     ensure(T);
02121     return CachedProperties(T->TypeBits.getLinkage(),
02122                             T->TypeBits.hasLocalOrUnnamedType());
02123   }
02124 
02125   static void ensure(const Type *T) {
02126     // If the cache is valid, we're okay.
02127     if (T->TypeBits.isCacheValid()) return;
02128 
02129     // If this type is non-canonical, ask its canonical type for the
02130     // relevant information.
02131     if (!T->isCanonicalUnqualified()) {
02132       const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
02133       ensure(CT);
02134       T->TypeBits.CacheValid = true;
02135       T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
02136       T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
02137       return;
02138     }
02139 
02140     // Compute the cached properties and then set the cache.
02141     CachedProperties Result = computeCachedProperties(T);
02142     T->TypeBits.CacheValid = true;
02143     T->TypeBits.CachedLinkage = Result.getLinkage();
02144     T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
02145   }
02146 };
02147 }
02148 
02149 // Instantiate the friend template at a private class.  In a
02150 // reasonable implementation, these symbols will be internal.
02151 // It is terrible that this is the best way to accomplish this.
02152 namespace { class Private {}; }
02153 typedef TypePropertyCache<Private> Cache;
02154 
02155 static CachedProperties computeCachedProperties(const Type *T) {
02156   switch (T->getTypeClass()) {
02157 #define TYPE(Class,Base)
02158 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
02159 #include "clang/AST/TypeNodes.def"
02160     llvm_unreachable("didn't expect a non-canonical type here");
02161 
02162 #define TYPE(Class,Base)
02163 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
02164 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
02165 #include "clang/AST/TypeNodes.def"
02166     // Treat instantiation-dependent types as external.
02167     assert(T->isInstantiationDependentType());
02168     return CachedProperties(ExternalLinkage, false);
02169 
02170   case Type::Auto:
02171     // Give non-deduced 'auto' types external linkage. We should only see them
02172     // here in error recovery.
02173     return CachedProperties(ExternalLinkage, false);
02174 
02175   case Type::Builtin:
02176     // C++ [basic.link]p8:
02177     //   A type is said to have linkage if and only if:
02178     //     - it is a fundamental type (3.9.1); or
02179     return CachedProperties(ExternalLinkage, false);
02180 
02181   case Type::Record:
02182   case Type::Enum: {
02183     const TagDecl *Tag = cast<TagType>(T)->getDecl();
02184 
02185     // C++ [basic.link]p8:
02186     //     - it is a class or enumeration type that is named (or has a name
02187     //       for linkage purposes (7.1.3)) and the name has linkage; or
02188     //     -  it is a specialization of a class template (14); or
02189     Linkage L = Tag->getLinkageInternal();
02190     bool IsLocalOrUnnamed =
02191       Tag->getDeclContext()->isFunctionOrMethod() ||
02192       !Tag->hasNameForLinkage();
02193     return CachedProperties(L, IsLocalOrUnnamed);
02194   }
02195 
02196     // C++ [basic.link]p8:
02197     //   - it is a compound type (3.9.2) other than a class or enumeration, 
02198     //     compounded exclusively from types that have linkage; or
02199   case Type::Complex:
02200     return Cache::get(cast<ComplexType>(T)->getElementType());
02201   case Type::Pointer:
02202     return Cache::get(cast<PointerType>(T)->getPointeeType());
02203   case Type::BlockPointer:
02204     return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
02205   case Type::LValueReference:
02206   case Type::RValueReference:
02207     return Cache::get(cast<ReferenceType>(T)->getPointeeType());
02208   case Type::MemberPointer: {
02209     const MemberPointerType *MPT = cast<MemberPointerType>(T);
02210     return merge(Cache::get(MPT->getClass()),
02211                  Cache::get(MPT->getPointeeType()));
02212   }
02213   case Type::ConstantArray:
02214   case Type::IncompleteArray:
02215   case Type::VariableArray:
02216     return Cache::get(cast<ArrayType>(T)->getElementType());
02217   case Type::Vector:
02218   case Type::ExtVector:
02219     return Cache::get(cast<VectorType>(T)->getElementType());
02220   case Type::FunctionNoProto:
02221     return Cache::get(cast<FunctionType>(T)->getReturnType());
02222   case Type::FunctionProto: {
02223     const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
02224     CachedProperties result = Cache::get(FPT->getReturnType());
02225     for (const auto &ai : FPT->param_types())
02226       result = merge(result, Cache::get(ai));
02227     return result;
02228   }
02229   case Type::ObjCInterface: {
02230     Linkage L = cast<ObjCInterfaceType>(T)->getDecl()->getLinkageInternal();
02231     return CachedProperties(L, false);
02232   }
02233   case Type::ObjCObject:
02234     return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
02235   case Type::ObjCObjectPointer:
02236     return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
02237   case Type::Atomic:
02238     return Cache::get(cast<AtomicType>(T)->getValueType());
02239   }
02240 
02241   llvm_unreachable("unhandled type class");
02242 }
02243 
02244 /// \brief Determine the linkage of this type.
02245 Linkage Type::getLinkage() const {
02246   Cache::ensure(this);
02247   return TypeBits.getLinkage();
02248 }
02249 
02250 bool Type::hasUnnamedOrLocalType() const {
02251   Cache::ensure(this);
02252   return TypeBits.hasLocalOrUnnamedType();
02253 }
02254 
02255 static LinkageInfo computeLinkageInfo(QualType T);
02256 
02257 static LinkageInfo computeLinkageInfo(const Type *T) {
02258   switch (T->getTypeClass()) {
02259 #define TYPE(Class,Base)
02260 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
02261 #include "clang/AST/TypeNodes.def"
02262     llvm_unreachable("didn't expect a non-canonical type here");
02263 
02264 #define TYPE(Class,Base)
02265 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
02266 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
02267 #include "clang/AST/TypeNodes.def"
02268     // Treat instantiation-dependent types as external.
02269     assert(T->isInstantiationDependentType());
02270     return LinkageInfo::external();
02271 
02272   case Type::Builtin:
02273     return LinkageInfo::external();
02274 
02275   case Type::Auto:
02276     return LinkageInfo::external();
02277 
02278   case Type::Record:
02279   case Type::Enum:
02280     return cast<TagType>(T)->getDecl()->getLinkageAndVisibility();
02281 
02282   case Type::Complex:
02283     return computeLinkageInfo(cast<ComplexType>(T)->getElementType());
02284   case Type::Pointer:
02285     return computeLinkageInfo(cast<PointerType>(T)->getPointeeType());
02286   case Type::BlockPointer:
02287     return computeLinkageInfo(cast<BlockPointerType>(T)->getPointeeType());
02288   case Type::LValueReference:
02289   case Type::RValueReference:
02290     return computeLinkageInfo(cast<ReferenceType>(T)->getPointeeType());
02291   case Type::MemberPointer: {
02292     const MemberPointerType *MPT = cast<MemberPointerType>(T);
02293     LinkageInfo LV = computeLinkageInfo(MPT->getClass());
02294     LV.merge(computeLinkageInfo(MPT->getPointeeType()));
02295     return LV;
02296   }
02297   case Type::ConstantArray:
02298   case Type::IncompleteArray:
02299   case Type::VariableArray:
02300     return computeLinkageInfo(cast<ArrayType>(T)->getElementType());
02301   case Type::Vector:
02302   case Type::ExtVector:
02303     return computeLinkageInfo(cast<VectorType>(T)->getElementType());
02304   case Type::FunctionNoProto:
02305     return computeLinkageInfo(cast<FunctionType>(T)->getReturnType());
02306   case Type::FunctionProto: {
02307     const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
02308     LinkageInfo LV = computeLinkageInfo(FPT->getReturnType());
02309     for (const auto &ai : FPT->param_types())
02310       LV.merge(computeLinkageInfo(ai));
02311     return LV;
02312   }
02313   case Type::ObjCInterface:
02314     return cast<ObjCInterfaceType>(T)->getDecl()->getLinkageAndVisibility();
02315   case Type::ObjCObject:
02316     return computeLinkageInfo(cast<ObjCObjectType>(T)->getBaseType());
02317   case Type::ObjCObjectPointer:
02318     return computeLinkageInfo(cast<ObjCObjectPointerType>(T)->getPointeeType());
02319   case Type::Atomic:
02320     return computeLinkageInfo(cast<AtomicType>(T)->getValueType());
02321   }
02322 
02323   llvm_unreachable("unhandled type class");
02324 }
02325 
02326 static LinkageInfo computeLinkageInfo(QualType T) {
02327   return computeLinkageInfo(T.getTypePtr());
02328 }
02329 
02330 bool Type::isLinkageValid() const {
02331   if (!TypeBits.isCacheValid())
02332     return true;
02333 
02334   return computeLinkageInfo(getCanonicalTypeInternal()).getLinkage() ==
02335     TypeBits.getLinkage();
02336 }
02337 
02338 LinkageInfo Type::getLinkageAndVisibility() const {
02339   if (!isCanonicalUnqualified())
02340     return computeLinkageInfo(getCanonicalTypeInternal());
02341 
02342   LinkageInfo LV = computeLinkageInfo(this);
02343   assert(LV.getLinkage() == getLinkage());
02344   return LV;
02345 }
02346 
02347 Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const {
02348   if (isObjCARCImplicitlyUnretainedType())
02349     return Qualifiers::OCL_ExplicitNone;
02350   return Qualifiers::OCL_Strong;
02351 }
02352 
02353 bool Type::isObjCARCImplicitlyUnretainedType() const {
02354   assert(isObjCLifetimeType() &&
02355          "cannot query implicit lifetime for non-inferrable type");
02356 
02357   const Type *canon = getCanonicalTypeInternal().getTypePtr();
02358 
02359   // Walk down to the base type.  We don't care about qualifiers for this.
02360   while (const ArrayType *array = dyn_cast<ArrayType>(canon))
02361     canon = array->getElementType().getTypePtr();
02362 
02363   if (const ObjCObjectPointerType *opt
02364         = dyn_cast<ObjCObjectPointerType>(canon)) {
02365     // Class and Class<Protocol> don't require retension.
02366     if (opt->getObjectType()->isObjCClass())
02367       return true;
02368   }
02369 
02370   return false;
02371 }
02372 
02373 bool Type::isObjCNSObjectType() const {
02374   if (const TypedefType *typedefType = dyn_cast<TypedefType>(this))
02375     return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>();
02376   return false;
02377 }
02378 bool Type::isObjCRetainableType() const {
02379   return isObjCObjectPointerType() ||
02380          isBlockPointerType() ||
02381          isObjCNSObjectType();
02382 }
02383 bool Type::isObjCIndirectLifetimeType() const {
02384   if (isObjCLifetimeType())
02385     return true;
02386   if (const PointerType *OPT = getAs<PointerType>())
02387     return OPT->getPointeeType()->isObjCIndirectLifetimeType();
02388   if (const ReferenceType *Ref = getAs<ReferenceType>())
02389     return Ref->getPointeeType()->isObjCIndirectLifetimeType();
02390   if (const MemberPointerType *MemPtr = getAs<MemberPointerType>())
02391     return MemPtr->getPointeeType()->isObjCIndirectLifetimeType();
02392   return false;
02393 }
02394 
02395 /// Returns true if objects of this type have lifetime semantics under
02396 /// ARC.
02397 bool Type::isObjCLifetimeType() const {
02398   const Type *type = this;
02399   while (const ArrayType *array = type->getAsArrayTypeUnsafe())
02400     type = array->getElementType().getTypePtr();
02401   return type->isObjCRetainableType();
02402 }
02403 
02404 /// \brief Determine whether the given type T is a "bridgable" Objective-C type,
02405 /// which is either an Objective-C object pointer type or an 
02406 bool Type::isObjCARCBridgableType() const {
02407   return isObjCObjectPointerType() || isBlockPointerType();
02408 }
02409 
02410 /// \brief Determine whether the given type T is a "bridgeable" C type.
02411 bool Type::isCARCBridgableType() const {
02412   const PointerType *Pointer = getAs<PointerType>();
02413   if (!Pointer)
02414     return false;
02415   
02416   QualType Pointee = Pointer->getPointeeType();
02417   return Pointee->isVoidType() || Pointee->isRecordType();
02418 }
02419 
02420 bool Type::hasSizedVLAType() const {
02421   if (!isVariablyModifiedType()) return false;
02422 
02423   if (const PointerType *ptr = getAs<PointerType>())
02424     return ptr->getPointeeType()->hasSizedVLAType();
02425   if (const ReferenceType *ref = getAs<ReferenceType>())
02426     return ref->getPointeeType()->hasSizedVLAType();
02427   if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
02428     if (isa<VariableArrayType>(arr) && 
02429         cast<VariableArrayType>(arr)->getSizeExpr())
02430       return true;
02431 
02432     return arr->getElementType()->hasSizedVLAType();
02433   }
02434 
02435   return false;
02436 }
02437 
02438 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
02439   switch (type.getObjCLifetime()) {
02440   case Qualifiers::OCL_None:
02441   case Qualifiers::OCL_ExplicitNone:
02442   case Qualifiers::OCL_Autoreleasing:
02443     break;
02444 
02445   case Qualifiers::OCL_Strong:
02446     return DK_objc_strong_lifetime;
02447   case Qualifiers::OCL_Weak:
02448     return DK_objc_weak_lifetime;
02449   }
02450 
02451   /// Currently, the only destruction kind we recognize is C++ objects
02452   /// with non-trivial destructors.
02453   const CXXRecordDecl *record =
02454     type->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
02455   if (record && record->hasDefinition() && !record->hasTrivialDestructor())
02456     return DK_cxx_destructor;
02457 
02458   return DK_none;
02459 }
02460 
02461 CXXRecordDecl *MemberPointerType::getMostRecentCXXRecordDecl() const {
02462   return getClass()->getAsCXXRecordDecl()->getMostRecentDecl();
02463 }