clang API Documentation

SemaCast.cpp
Go to the documentation of this file.
00001 //===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===//
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 semantic analysis for cast expressions, including
00011 //  1) C-style casts like '(int) x'
00012 //  2) C++ functional casts like 'int(x)'
00013 //  3) C++ named casts like 'static_cast<int>(x)'
00014 //
00015 //===----------------------------------------------------------------------===//
00016 
00017 #include "clang/Sema/SemaInternal.h"
00018 #include "clang/AST/ASTContext.h"
00019 #include "clang/AST/CXXInheritance.h"
00020 #include "clang/AST/ExprCXX.h"
00021 #include "clang/AST/ExprObjC.h"
00022 #include "clang/AST/RecordLayout.h"
00023 #include "clang/Basic/PartialDiagnostic.h"
00024 #include "clang/Basic/TargetInfo.h"
00025 #include "clang/Sema/Initialization.h"
00026 #include "llvm/ADT/SmallVector.h"
00027 #include <set>
00028 using namespace clang;
00029 
00030 
00031 
00032 enum TryCastResult {
00033   TC_NotApplicable, ///< The cast method is not applicable.
00034   TC_Success,       ///< The cast method is appropriate and successful.
00035   TC_Failed         ///< The cast method is appropriate, but failed. A
00036                     ///< diagnostic has been emitted.
00037 };
00038 
00039 enum CastType {
00040   CT_Const,       ///< const_cast
00041   CT_Static,      ///< static_cast
00042   CT_Reinterpret, ///< reinterpret_cast
00043   CT_Dynamic,     ///< dynamic_cast
00044   CT_CStyle,      ///< (Type)expr
00045   CT_Functional   ///< Type(expr)
00046 };
00047 
00048 namespace {
00049   struct CastOperation {
00050     CastOperation(Sema &S, QualType destType, ExprResult src)
00051       : Self(S), SrcExpr(src), DestType(destType),
00052         ResultType(destType.getNonLValueExprType(S.Context)),
00053         ValueKind(Expr::getValueKindForType(destType)),
00054         Kind(CK_Dependent), IsARCUnbridgedCast(false) {
00055 
00056       if (const BuiltinType *placeholder =
00057             src.get()->getType()->getAsPlaceholderType()) {
00058         PlaceholderKind = placeholder->getKind();
00059       } else {
00060         PlaceholderKind = (BuiltinType::Kind) 0;
00061       }
00062     }
00063 
00064     Sema &Self;
00065     ExprResult SrcExpr;
00066     QualType DestType;
00067     QualType ResultType;
00068     ExprValueKind ValueKind;
00069     CastKind Kind;
00070     BuiltinType::Kind PlaceholderKind;
00071     CXXCastPath BasePath;
00072     bool IsARCUnbridgedCast;
00073 
00074     SourceRange OpRange;
00075     SourceRange DestRange;
00076 
00077     // Top-level semantics-checking routines.
00078     void CheckConstCast();
00079     void CheckReinterpretCast();
00080     void CheckStaticCast();
00081     void CheckDynamicCast();
00082     void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
00083     void CheckCStyleCast();
00084 
00085     /// Complete an apparently-successful cast operation that yields
00086     /// the given expression.
00087     ExprResult complete(CastExpr *castExpr) {
00088       // If this is an unbridged cast, wrap the result in an implicit
00089       // cast that yields the unbridged-cast placeholder type.
00090       if (IsARCUnbridgedCast) {
00091         castExpr = ImplicitCastExpr::Create(Self.Context,
00092                                             Self.Context.ARCUnbridgedCastTy,
00093                                             CK_Dependent, castExpr, nullptr,
00094                                             castExpr->getValueKind());
00095       }
00096       return castExpr;
00097     }
00098 
00099     // Internal convenience methods.
00100 
00101     /// Try to handle the given placeholder expression kind.  Return
00102     /// true if the source expression has the appropriate placeholder
00103     /// kind.  A placeholder can only be claimed once.
00104     bool claimPlaceholder(BuiltinType::Kind K) {
00105       if (PlaceholderKind != K) return false;
00106 
00107       PlaceholderKind = (BuiltinType::Kind) 0;
00108       return true;
00109     }
00110 
00111     bool isPlaceholder() const {
00112       return PlaceholderKind != 0;
00113     }
00114     bool isPlaceholder(BuiltinType::Kind K) const {
00115       return PlaceholderKind == K;
00116     }
00117 
00118     void checkCastAlign() {
00119       Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
00120     }
00121 
00122     void checkObjCARCConversion(Sema::CheckedConversionKind CCK) {
00123       assert(Self.getLangOpts().ObjCAutoRefCount);
00124 
00125       Expr *src = SrcExpr.get();
00126       if (Self.CheckObjCARCConversion(OpRange, DestType, src, CCK) ==
00127             Sema::ACR_unbridged)
00128         IsARCUnbridgedCast = true;
00129       SrcExpr = src;
00130     }
00131 
00132     /// Check for and handle non-overload placeholder expressions.
00133     void checkNonOverloadPlaceholders() {
00134       if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
00135         return;
00136 
00137       SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
00138       if (SrcExpr.isInvalid())
00139         return;
00140       PlaceholderKind = (BuiltinType::Kind) 0;
00141     }
00142   };
00143 }
00144 
00145 static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
00146                                bool CheckCVR, bool CheckObjCLifetime);
00147 
00148 // The Try functions attempt a specific way of casting. If they succeed, they
00149 // return TC_Success. If their way of casting is not appropriate for the given
00150 // arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
00151 // to emit if no other way succeeds. If their way of casting is appropriate but
00152 // fails, they return TC_Failed and *must* set diag; they can set it to 0 if
00153 // they emit a specialized diagnostic.
00154 // All diagnostics returned by these functions must expect the same three
00155 // arguments:
00156 // %0: Cast Type (a value from the CastType enumeration)
00157 // %1: Source Type
00158 // %2: Destination Type
00159 static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
00160                                            QualType DestType, bool CStyle,
00161                                            CastKind &Kind,
00162                                            CXXCastPath &BasePath,
00163                                            unsigned &msg);
00164 static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
00165                                                QualType DestType, bool CStyle,
00166                                                const SourceRange &OpRange,
00167                                                unsigned &msg,
00168                                                CastKind &Kind,
00169                                                CXXCastPath &BasePath);
00170 static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
00171                                               QualType DestType, bool CStyle,
00172                                               const SourceRange &OpRange,
00173                                               unsigned &msg,
00174                                               CastKind &Kind,
00175                                               CXXCastPath &BasePath);
00176 static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
00177                                        CanQualType DestType, bool CStyle,
00178                                        const SourceRange &OpRange,
00179                                        QualType OrigSrcType,
00180                                        QualType OrigDestType, unsigned &msg,
00181                                        CastKind &Kind,
00182                                        CXXCastPath &BasePath);
00183 static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
00184                                                QualType SrcType,
00185                                                QualType DestType,bool CStyle,
00186                                                const SourceRange &OpRange,
00187                                                unsigned &msg,
00188                                                CastKind &Kind,
00189                                                CXXCastPath &BasePath);
00190 
00191 static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
00192                                            QualType DestType, 
00193                                            Sema::CheckedConversionKind CCK,
00194                                            const SourceRange &OpRange,
00195                                            unsigned &msg, CastKind &Kind,
00196                                            bool ListInitialization);
00197 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
00198                                    QualType DestType, 
00199                                    Sema::CheckedConversionKind CCK,
00200                                    const SourceRange &OpRange,
00201                                    unsigned &msg, CastKind &Kind,
00202                                    CXXCastPath &BasePath,
00203                                    bool ListInitialization);
00204 static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
00205                                   QualType DestType, bool CStyle,
00206                                   unsigned &msg);
00207 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
00208                                         QualType DestType, bool CStyle,
00209                                         const SourceRange &OpRange,
00210                                         unsigned &msg,
00211                                         CastKind &Kind);
00212 
00213 
00214 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
00215 ExprResult
00216 Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
00217                         SourceLocation LAngleBracketLoc, Declarator &D,
00218                         SourceLocation RAngleBracketLoc,
00219                         SourceLocation LParenLoc, Expr *E,
00220                         SourceLocation RParenLoc) {
00221 
00222   assert(!D.isInvalidType());
00223 
00224   TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
00225   if (D.isInvalidType())
00226     return ExprError();
00227 
00228   if (getLangOpts().CPlusPlus) {
00229     // Check that there are no default arguments (C++ only).
00230     CheckExtraCXXDefaultArguments(D);
00231   }
00232 
00233   return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
00234                            SourceRange(LAngleBracketLoc, RAngleBracketLoc),
00235                            SourceRange(LParenLoc, RParenLoc));
00236 }
00237 
00238 ExprResult
00239 Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
00240                         TypeSourceInfo *DestTInfo, Expr *E,
00241                         SourceRange AngleBrackets, SourceRange Parens) {
00242   ExprResult Ex = E;
00243   QualType DestType = DestTInfo->getType();
00244 
00245   // If the type is dependent, we won't do the semantic analysis now.
00246   // FIXME: should we check this in a more fine-grained manner?
00247   bool TypeDependent = DestType->isDependentType() ||
00248                        Ex.get()->isTypeDependent() ||
00249                        Ex.get()->isValueDependent();
00250 
00251   CastOperation Op(*this, DestType, E);
00252   Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
00253   Op.DestRange = AngleBrackets;
00254 
00255   switch (Kind) {
00256   default: llvm_unreachable("Unknown C++ cast!");
00257 
00258   case tok::kw_const_cast:
00259     if (!TypeDependent) {
00260       Op.CheckConstCast();
00261       if (Op.SrcExpr.isInvalid())
00262         return ExprError();
00263     }
00264     return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
00265                                   Op.ValueKind, Op.SrcExpr.get(), DestTInfo,
00266                                                 OpLoc, Parens.getEnd(),
00267                                                 AngleBrackets));
00268 
00269   case tok::kw_dynamic_cast: {
00270     if (!TypeDependent) {
00271       Op.CheckDynamicCast();
00272       if (Op.SrcExpr.isInvalid())
00273         return ExprError();
00274     }
00275     return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
00276                                     Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
00277                                                   &Op.BasePath, DestTInfo,
00278                                                   OpLoc, Parens.getEnd(),
00279                                                   AngleBrackets));
00280   }
00281   case tok::kw_reinterpret_cast: {
00282     if (!TypeDependent) {
00283       Op.CheckReinterpretCast();
00284       if (Op.SrcExpr.isInvalid())
00285         return ExprError();
00286     }
00287     return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
00288                                     Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
00289                                                       nullptr, DestTInfo, OpLoc,
00290                                                       Parens.getEnd(),
00291                                                       AngleBrackets));
00292   }
00293   case tok::kw_static_cast: {
00294     if (!TypeDependent) {
00295       Op.CheckStaticCast();
00296       if (Op.SrcExpr.isInvalid())
00297         return ExprError();
00298     }
00299     
00300     return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
00301                                    Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
00302                                                  &Op.BasePath, DestTInfo,
00303                                                  OpLoc, Parens.getEnd(),
00304                                                  AngleBrackets));
00305   }
00306   }
00307 }
00308 
00309 /// Try to diagnose a failed overloaded cast.  Returns true if
00310 /// diagnostics were emitted.
00311 static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
00312                                       SourceRange range, Expr *src,
00313                                       QualType destType,
00314                                       bool listInitialization) {
00315   switch (CT) {
00316   // These cast kinds don't consider user-defined conversions.
00317   case CT_Const:
00318   case CT_Reinterpret:
00319   case CT_Dynamic:
00320     return false;
00321 
00322   // These do.
00323   case CT_Static:
00324   case CT_CStyle:
00325   case CT_Functional:
00326     break;
00327   }
00328 
00329   QualType srcType = src->getType();
00330   if (!destType->isRecordType() && !srcType->isRecordType())
00331     return false;
00332 
00333   InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
00334   InitializationKind initKind
00335     = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
00336                                                       range, listInitialization)
00337     : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
00338                                                              listInitialization)
00339     : InitializationKind::CreateCast(/*type range?*/ range);
00340   InitializationSequence sequence(S, entity, initKind, src);
00341 
00342   assert(sequence.Failed() && "initialization succeeded on second try?");
00343   switch (sequence.getFailureKind()) {
00344   default: return false;
00345 
00346   case InitializationSequence::FK_ConstructorOverloadFailed:
00347   case InitializationSequence::FK_UserConversionOverloadFailed:
00348     break;
00349   }
00350 
00351   OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
00352 
00353   unsigned msg = 0;
00354   OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
00355 
00356   switch (sequence.getFailedOverloadResult()) {
00357   case OR_Success: llvm_unreachable("successful failed overload");
00358   case OR_No_Viable_Function:
00359     if (candidates.empty())
00360       msg = diag::err_ovl_no_conversion_in_cast;
00361     else
00362       msg = diag::err_ovl_no_viable_conversion_in_cast;
00363     howManyCandidates = OCD_AllCandidates;
00364     break;
00365 
00366   case OR_Ambiguous:
00367     msg = diag::err_ovl_ambiguous_conversion_in_cast;
00368     howManyCandidates = OCD_ViableCandidates;
00369     break;
00370 
00371   case OR_Deleted:
00372     msg = diag::err_ovl_deleted_conversion_in_cast;
00373     howManyCandidates = OCD_ViableCandidates;
00374     break;
00375   }
00376 
00377   S.Diag(range.getBegin(), msg)
00378     << CT << srcType << destType
00379     << range << src->getSourceRange();
00380 
00381   candidates.NoteCandidates(S, howManyCandidates, src);
00382 
00383   return true;
00384 }
00385 
00386 /// Diagnose a failed cast.
00387 static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
00388                             SourceRange opRange, Expr *src, QualType destType,
00389                             bool listInitialization) {
00390   if (msg == diag::err_bad_cxx_cast_generic &&
00391       tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
00392                                 listInitialization))
00393     return;
00394 
00395   S.Diag(opRange.getBegin(), msg) << castType
00396     << src->getType() << destType << opRange << src->getSourceRange();
00397 }
00398 
00399 /// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
00400 /// this removes one level of indirection from both types, provided that they're
00401 /// the same kind of pointer (plain or to-member). Unlike the Sema function,
00402 /// this one doesn't care if the two pointers-to-member don't point into the
00403 /// same class. This is because CastsAwayConstness doesn't care.
00404 static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
00405   const PointerType *T1PtrType = T1->getAs<PointerType>(),
00406                     *T2PtrType = T2->getAs<PointerType>();
00407   if (T1PtrType && T2PtrType) {
00408     T1 = T1PtrType->getPointeeType();
00409     T2 = T2PtrType->getPointeeType();
00410     return true;
00411   }
00412   const ObjCObjectPointerType *T1ObjCPtrType = 
00413                                             T1->getAs<ObjCObjectPointerType>(),
00414                               *T2ObjCPtrType = 
00415                                             T2->getAs<ObjCObjectPointerType>();
00416   if (T1ObjCPtrType) {
00417     if (T2ObjCPtrType) {
00418       T1 = T1ObjCPtrType->getPointeeType();
00419       T2 = T2ObjCPtrType->getPointeeType();
00420       return true;
00421     }
00422     else if (T2PtrType) {
00423       T1 = T1ObjCPtrType->getPointeeType();
00424       T2 = T2PtrType->getPointeeType();
00425       return true;
00426     }
00427   }
00428   else if (T2ObjCPtrType) {
00429     if (T1PtrType) {
00430       T2 = T2ObjCPtrType->getPointeeType();
00431       T1 = T1PtrType->getPointeeType();
00432       return true;
00433     }
00434   }
00435   
00436   const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
00437                           *T2MPType = T2->getAs<MemberPointerType>();
00438   if (T1MPType && T2MPType) {
00439     T1 = T1MPType->getPointeeType();
00440     T2 = T2MPType->getPointeeType();
00441     return true;
00442   }
00443   
00444   const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
00445                          *T2BPType = T2->getAs<BlockPointerType>();
00446   if (T1BPType && T2BPType) {
00447     T1 = T1BPType->getPointeeType();
00448     T2 = T2BPType->getPointeeType();
00449     return true;
00450   }
00451   
00452   return false;
00453 }
00454 
00455 /// CastsAwayConstness - Check if the pointer conversion from SrcType to
00456 /// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
00457 /// the cast checkers.  Both arguments must denote pointer (possibly to member)
00458 /// types.
00459 ///
00460 /// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
00461 ///
00462 /// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
00463 static bool
00464 CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
00465                    bool CheckCVR, bool CheckObjCLifetime) {
00466   // If the only checking we care about is for Objective-C lifetime qualifiers,
00467   // and we're not in ARC mode, there's nothing to check.
00468   if (!CheckCVR && CheckObjCLifetime && 
00469       !Self.Context.getLangOpts().ObjCAutoRefCount)
00470     return false;
00471     
00472   // Casting away constness is defined in C++ 5.2.11p8 with reference to
00473   // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
00474   // the rules are non-trivial. So first we construct Tcv *...cv* as described
00475   // in C++ 5.2.11p8.
00476   assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
00477           SrcType->isBlockPointerType()) &&
00478          "Source type is not pointer or pointer to member.");
00479   assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
00480           DestType->isBlockPointerType()) &&
00481          "Destination type is not pointer or pointer to member.");
00482 
00483   QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType), 
00484            UnwrappedDestType = Self.Context.getCanonicalType(DestType);
00485   SmallVector<Qualifiers, 8> cv1, cv2;
00486 
00487   // Find the qualifiers. We only care about cvr-qualifiers for the 
00488   // purpose of this check, because other qualifiers (address spaces, 
00489   // Objective-C GC, etc.) are part of the type's identity.
00490   while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
00491     // Determine the relevant qualifiers at this level.
00492     Qualifiers SrcQuals, DestQuals;
00493     Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
00494     Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
00495     
00496     Qualifiers RetainedSrcQuals, RetainedDestQuals;
00497     if (CheckCVR) {
00498       RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
00499       RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
00500     }
00501     
00502     if (CheckObjCLifetime &&
00503         !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
00504       return true;
00505     
00506     cv1.push_back(RetainedSrcQuals);
00507     cv2.push_back(RetainedDestQuals);
00508   }
00509   if (cv1.empty())
00510     return false;
00511 
00512   // Construct void pointers with those qualifiers (in reverse order of
00513   // unwrapping, of course).
00514   QualType SrcConstruct = Self.Context.VoidTy;
00515   QualType DestConstruct = Self.Context.VoidTy;
00516   ASTContext &Context = Self.Context;
00517   for (SmallVectorImpl<Qualifiers>::reverse_iterator i1 = cv1.rbegin(),
00518                                                      i2 = cv2.rbegin();
00519        i1 != cv1.rend(); ++i1, ++i2) {
00520     SrcConstruct
00521       = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
00522     DestConstruct
00523       = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
00524   }
00525 
00526   // Test if they're compatible.
00527   bool ObjCLifetimeConversion;
00528   return SrcConstruct != DestConstruct &&
00529     !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
00530                                     ObjCLifetimeConversion);
00531 }
00532 
00533 /// CheckDynamicCast - Check that a dynamic_cast<DestType>(SrcExpr) is valid.
00534 /// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
00535 /// checked downcasts in class hierarchies.
00536 void CastOperation::CheckDynamicCast() {
00537   if (ValueKind == VK_RValue)
00538     SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
00539   else if (isPlaceholder())
00540     SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
00541   if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
00542     return;
00543 
00544   QualType OrigSrcType = SrcExpr.get()->getType();
00545   QualType DestType = Self.Context.getCanonicalType(this->DestType);
00546 
00547   // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
00548   //   or "pointer to cv void".
00549 
00550   QualType DestPointee;
00551   const PointerType *DestPointer = DestType->getAs<PointerType>();
00552   const ReferenceType *DestReference = nullptr;
00553   if (DestPointer) {
00554     DestPointee = DestPointer->getPointeeType();
00555   } else if ((DestReference = DestType->getAs<ReferenceType>())) {
00556     DestPointee = DestReference->getPointeeType();
00557   } else {
00558     Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
00559       << this->DestType << DestRange;
00560     SrcExpr = ExprError();
00561     return;
00562   }
00563 
00564   const RecordType *DestRecord = DestPointee->getAs<RecordType>();
00565   if (DestPointee->isVoidType()) {
00566     assert(DestPointer && "Reference to void is not possible");
00567   } else if (DestRecord) {
00568     if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
00569                                  diag::err_bad_dynamic_cast_incomplete,
00570                                  DestRange)) {
00571       SrcExpr = ExprError();
00572       return;
00573     }
00574   } else {
00575     Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
00576       << DestPointee.getUnqualifiedType() << DestRange;
00577     SrcExpr = ExprError();
00578     return;
00579   }
00580 
00581   // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
00582   //   complete class type, [...]. If T is an lvalue reference type, v shall be
00583   //   an lvalue of a complete class type, [...]. If T is an rvalue reference 
00584   //   type, v shall be an expression having a complete class type, [...]
00585   QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
00586   QualType SrcPointee;
00587   if (DestPointer) {
00588     if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
00589       SrcPointee = SrcPointer->getPointeeType();
00590     } else {
00591       Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
00592         << OrigSrcType << SrcExpr.get()->getSourceRange();
00593       SrcExpr = ExprError();
00594       return;
00595     }
00596   } else if (DestReference->isLValueReferenceType()) {
00597     if (!SrcExpr.get()->isLValue()) {
00598       Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
00599         << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
00600     }
00601     SrcPointee = SrcType;
00602   } else {
00603     // If we're dynamic_casting from a prvalue to an rvalue reference, we need
00604     // to materialize the prvalue before we bind the reference to it.
00605     if (SrcExpr.get()->isRValue())
00606       SrcExpr = new (Self.Context) MaterializeTemporaryExpr(
00607           SrcType, SrcExpr.get(), /*IsLValueReference*/false);
00608     SrcPointee = SrcType;
00609   }
00610 
00611   const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
00612   if (SrcRecord) {
00613     if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
00614                                  diag::err_bad_dynamic_cast_incomplete,
00615                                  SrcExpr.get())) {
00616       SrcExpr = ExprError();
00617       return;
00618     }
00619   } else {
00620     Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
00621       << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
00622     SrcExpr = ExprError();
00623     return;
00624   }
00625 
00626   assert((DestPointer || DestReference) &&
00627     "Bad destination non-ptr/ref slipped through.");
00628   assert((DestRecord || DestPointee->isVoidType()) &&
00629     "Bad destination pointee slipped through.");
00630   assert(SrcRecord && "Bad source pointee slipped through.");
00631 
00632   // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
00633   if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
00634     Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
00635       << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
00636     SrcExpr = ExprError();
00637     return;
00638   }
00639 
00640   // C++ 5.2.7p3: If the type of v is the same as the required result type,
00641   //   [except for cv].
00642   if (DestRecord == SrcRecord) {
00643     Kind = CK_NoOp;
00644     return;
00645   }
00646 
00647   // C++ 5.2.7p5
00648   // Upcasts are resolved statically.
00649   if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
00650     if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
00651                                            OpRange.getBegin(), OpRange, 
00652                                            &BasePath)) {
00653       SrcExpr = ExprError();
00654       return;
00655     }
00656 
00657     Kind = CK_DerivedToBase;
00658 
00659     // If we are casting to or through a virtual base class, we need a
00660     // vtable.
00661     if (Self.BasePathInvolvesVirtualBase(BasePath))
00662       Self.MarkVTableUsed(OpRange.getBegin(), 
00663                           cast<CXXRecordDecl>(SrcRecord->getDecl()));
00664     return;
00665   }
00666 
00667   // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
00668   const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
00669   assert(SrcDecl && "Definition missing");
00670   if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
00671     Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
00672       << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
00673     SrcExpr = ExprError();
00674   }
00675   Self.MarkVTableUsed(OpRange.getBegin(), 
00676                       cast<CXXRecordDecl>(SrcRecord->getDecl()));
00677 
00678   // dynamic_cast is not available with -fno-rtti.
00679   // As an exception, dynamic_cast to void* is available because it doesn't
00680   // use RTTI.
00681   if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) {
00682     Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti);
00683     SrcExpr = ExprError();
00684     return;
00685   }
00686 
00687   // Done. Everything else is run-time checks.
00688   Kind = CK_Dynamic;
00689 }
00690 
00691 /// CheckConstCast - Check that a const_cast<DestType>(SrcExpr) is valid.
00692 /// Refer to C++ 5.2.11 for details. const_cast is typically used in code
00693 /// like this:
00694 /// const char *str = "literal";
00695 /// legacy_function(const_cast<char*>(str));
00696 void CastOperation::CheckConstCast() {
00697   if (ValueKind == VK_RValue)
00698     SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
00699   else if (isPlaceholder())
00700     SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
00701   if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
00702     return;
00703 
00704   unsigned msg = diag::err_bad_cxx_cast_generic;
00705   if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
00706       && msg != 0) {
00707     Self.Diag(OpRange.getBegin(), msg) << CT_Const
00708       << SrcExpr.get()->getType() << DestType << OpRange;
00709     SrcExpr = ExprError();
00710   }
00711 }
00712 
00713 /// Check that a reinterpret_cast<DestType>(SrcExpr) is not used as upcast
00714 /// or downcast between respective pointers or references.
00715 static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
00716                                           QualType DestType,
00717                                           SourceRange OpRange) {
00718   QualType SrcType = SrcExpr->getType();
00719   // When casting from pointer or reference, get pointee type; use original
00720   // type otherwise.
00721   const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
00722   const CXXRecordDecl *SrcRD =
00723     SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
00724 
00725   // Examining subobjects for records is only possible if the complete and
00726   // valid definition is available.  Also, template instantiation is not
00727   // allowed here.
00728   if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
00729     return;
00730 
00731   const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
00732 
00733   if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
00734     return;
00735 
00736   enum {
00737     ReinterpretUpcast,
00738     ReinterpretDowncast
00739   } ReinterpretKind;
00740 
00741   CXXBasePaths BasePaths;
00742 
00743   if (SrcRD->isDerivedFrom(DestRD, BasePaths))
00744     ReinterpretKind = ReinterpretUpcast;
00745   else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
00746     ReinterpretKind = ReinterpretDowncast;
00747   else
00748     return;
00749 
00750   bool VirtualBase = true;
00751   bool NonZeroOffset = false;
00752   for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
00753                                           E = BasePaths.end();
00754        I != E; ++I) {
00755     const CXXBasePath &Path = *I;
00756     CharUnits Offset = CharUnits::Zero();
00757     bool IsVirtual = false;
00758     for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
00759          IElem != EElem; ++IElem) {
00760       IsVirtual = IElem->Base->isVirtual();
00761       if (IsVirtual)
00762         break;
00763       const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
00764       assert(BaseRD && "Base type should be a valid unqualified class type");
00765       // Don't check if any base has invalid declaration or has no definition
00766       // since it has no layout info.
00767       const CXXRecordDecl *Class = IElem->Class,
00768                           *ClassDefinition = Class->getDefinition();
00769       if (Class->isInvalidDecl() || !ClassDefinition ||
00770           !ClassDefinition->isCompleteDefinition())
00771         return;
00772 
00773       const ASTRecordLayout &DerivedLayout =
00774           Self.Context.getASTRecordLayout(Class);
00775       Offset += DerivedLayout.getBaseClassOffset(BaseRD);
00776     }
00777     if (!IsVirtual) {
00778       // Don't warn if any path is a non-virtually derived base at offset zero.
00779       if (Offset.isZero())
00780         return;
00781       // Offset makes sense only for non-virtual bases.
00782       else
00783         NonZeroOffset = true;
00784     }
00785     VirtualBase = VirtualBase && IsVirtual;
00786   }
00787 
00788   (void) NonZeroOffset; // Silence set but not used warning.
00789   assert((VirtualBase || NonZeroOffset) &&
00790          "Should have returned if has non-virtual base with zero offset");
00791 
00792   QualType BaseType =
00793       ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
00794   QualType DerivedType =
00795       ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
00796 
00797   SourceLocation BeginLoc = OpRange.getBegin();
00798   Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
00799     << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind)
00800     << OpRange;
00801   Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
00802     << int(ReinterpretKind)
00803     << FixItHint::CreateReplacement(BeginLoc, "static_cast");
00804 }
00805 
00806 /// CheckReinterpretCast - Check that a reinterpret_cast<DestType>(SrcExpr) is
00807 /// valid.
00808 /// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
00809 /// like this:
00810 /// char *bytes = reinterpret_cast<char*>(int_ptr);
00811 void CastOperation::CheckReinterpretCast() {
00812   if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
00813     SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
00814   else
00815     checkNonOverloadPlaceholders();
00816   if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
00817     return;
00818 
00819   unsigned msg = diag::err_bad_cxx_cast_generic;
00820   TryCastResult tcr = 
00821     TryReinterpretCast(Self, SrcExpr, DestType, 
00822                        /*CStyle*/false, OpRange, msg, Kind);
00823   if (tcr != TC_Success && msg != 0)
00824   {
00825     if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
00826       return;
00827     if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
00828       //FIXME: &f<int>; is overloaded and resolvable 
00829       Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload) 
00830         << OverloadExpr::find(SrcExpr.get()).Expression->getName()
00831         << DestType << OpRange;
00832       Self.NoteAllOverloadCandidates(SrcExpr.get());
00833 
00834     } else {
00835       diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
00836                       DestType, /*listInitialization=*/false);
00837     }
00838     SrcExpr = ExprError();
00839   } else if (tcr == TC_Success) {
00840     if (Self.getLangOpts().ObjCAutoRefCount)
00841       checkObjCARCConversion(Sema::CCK_OtherCast);
00842     DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
00843   }
00844 }
00845 
00846 
00847 /// CheckStaticCast - Check that a static_cast<DestType>(SrcExpr) is valid.
00848 /// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
00849 /// implicit conversions explicit and getting rid of data loss warnings.
00850 void CastOperation::CheckStaticCast() {
00851   if (isPlaceholder()) {
00852     checkNonOverloadPlaceholders();
00853     if (SrcExpr.isInvalid())
00854       return;
00855   }
00856 
00857   // This test is outside everything else because it's the only case where
00858   // a non-lvalue-reference target type does not lead to decay.
00859   // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
00860   if (DestType->isVoidType()) {
00861     Kind = CK_ToVoid;
00862 
00863     if (claimPlaceholder(BuiltinType::Overload)) {
00864       Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr, 
00865                 false, // Decay Function to ptr 
00866                 true, // Complain
00867                 OpRange, DestType, diag::err_bad_static_cast_overload);
00868       if (SrcExpr.isInvalid())
00869         return;
00870     }
00871 
00872     SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
00873     return;
00874   }
00875 
00876   if (ValueKind == VK_RValue && !DestType->isRecordType() &&
00877       !isPlaceholder(BuiltinType::Overload)) {
00878     SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
00879     if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
00880       return;
00881   }
00882 
00883   unsigned msg = diag::err_bad_cxx_cast_generic;
00884   TryCastResult tcr
00885     = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
00886                     Kind, BasePath, /*ListInitialization=*/false);
00887   if (tcr != TC_Success && msg != 0) {
00888     if (SrcExpr.isInvalid())
00889       return;
00890     if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
00891       OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
00892       Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
00893         << oe->getName() << DestType << OpRange 
00894         << oe->getQualifierLoc().getSourceRange();
00895       Self.NoteAllOverloadCandidates(SrcExpr.get());
00896     } else {
00897       diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
00898                       /*listInitialization=*/false);
00899     }
00900     SrcExpr = ExprError();
00901   } else if (tcr == TC_Success) {
00902     if (Kind == CK_BitCast)
00903       checkCastAlign();
00904     if (Self.getLangOpts().ObjCAutoRefCount)
00905       checkObjCARCConversion(Sema::CCK_OtherCast);
00906   } else if (Kind == CK_BitCast) {
00907     checkCastAlign();
00908   }
00909 }
00910 
00911 /// TryStaticCast - Check if a static cast can be performed, and do so if
00912 /// possible. If @p CStyle, ignore access restrictions on hierarchy casting
00913 /// and casting away constness.
00914 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
00915                                    QualType DestType, 
00916                                    Sema::CheckedConversionKind CCK,
00917                                    const SourceRange &OpRange, unsigned &msg,
00918                                    CastKind &Kind, CXXCastPath &BasePath,
00919                                    bool ListInitialization) {
00920   // Determine whether we have the semantics of a C-style cast.
00921   bool CStyle 
00922     = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
00923   
00924   // The order the tests is not entirely arbitrary. There is one conversion
00925   // that can be handled in two different ways. Given:
00926   // struct A {};
00927   // struct B : public A {
00928   //   B(); B(const A&);
00929   // };
00930   // const A &a = B();
00931   // the cast static_cast<const B&>(a) could be seen as either a static
00932   // reference downcast, or an explicit invocation of the user-defined
00933   // conversion using B's conversion constructor.
00934   // DR 427 specifies that the downcast is to be applied here.
00935 
00936   // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
00937   // Done outside this function.
00938 
00939   TryCastResult tcr;
00940 
00941   // C++ 5.2.9p5, reference downcast.
00942   // See the function for details.
00943   // DR 427 specifies that this is to be applied before paragraph 2.
00944   tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
00945                                    OpRange, msg, Kind, BasePath);
00946   if (tcr != TC_NotApplicable)
00947     return tcr;
00948 
00949   // C++0x [expr.static.cast]p3: 
00950   //   A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
00951   //   T2" if "cv2 T2" is reference-compatible with "cv1 T1".
00952   tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind, 
00953                               BasePath, msg);
00954   if (tcr != TC_NotApplicable)
00955     return tcr;
00956 
00957   // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
00958   //   [...] if the declaration "T t(e);" is well-formed, [...].
00959   tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
00960                               Kind, ListInitialization);
00961   if (SrcExpr.isInvalid())
00962     return TC_Failed;
00963   if (tcr != TC_NotApplicable)
00964     return tcr;
00965   
00966   // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
00967   // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
00968   // conversions, subject to further restrictions.
00969   // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
00970   // of qualification conversions impossible.
00971   // In the CStyle case, the earlier attempt to const_cast should have taken
00972   // care of reverse qualification conversions.
00973 
00974   QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
00975 
00976   // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
00977   // converted to an integral type. [...] A value of a scoped enumeration type
00978   // can also be explicitly converted to a floating-point type [...].
00979   if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
00980     if (Enum->getDecl()->isScoped()) {
00981       if (DestType->isBooleanType()) {
00982         Kind = CK_IntegralToBoolean;
00983         return TC_Success;
00984       } else if (DestType->isIntegralType(Self.Context)) {
00985         Kind = CK_IntegralCast;
00986         return TC_Success;
00987       } else if (DestType->isRealFloatingType()) {
00988         Kind = CK_IntegralToFloating;
00989         return TC_Success;
00990       }
00991     }
00992   }
00993   
00994   // Reverse integral promotion/conversion. All such conversions are themselves
00995   // again integral promotions or conversions and are thus already handled by
00996   // p2 (TryDirectInitialization above).
00997   // (Note: any data loss warnings should be suppressed.)
00998   // The exception is the reverse of enum->integer, i.e. integer->enum (and
00999   // enum->enum). See also C++ 5.2.9p7.
01000   // The same goes for reverse floating point promotion/conversion and
01001   // floating-integral conversions. Again, only floating->enum is relevant.
01002   if (DestType->isEnumeralType()) {
01003     if (SrcType->isIntegralOrEnumerationType()) {
01004       Kind = CK_IntegralCast;
01005       return TC_Success;
01006     } else if (SrcType->isRealFloatingType())   {
01007       Kind = CK_FloatingToIntegral;
01008       return TC_Success;
01009     }
01010   }
01011 
01012   // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
01013   // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
01014   tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
01015                                  Kind, BasePath);
01016   if (tcr != TC_NotApplicable)
01017     return tcr;
01018 
01019   // Reverse member pointer conversion. C++ 4.11 specifies member pointer
01020   // conversion. C++ 5.2.9p9 has additional information.
01021   // DR54's access restrictions apply here also.
01022   tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
01023                                      OpRange, msg, Kind, BasePath);
01024   if (tcr != TC_NotApplicable)
01025     return tcr;
01026 
01027   // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
01028   // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
01029   // just the usual constness stuff.
01030   if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
01031     QualType SrcPointee = SrcPointer->getPointeeType();
01032     if (SrcPointee->isVoidType()) {
01033       if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
01034         QualType DestPointee = DestPointer->getPointeeType();
01035         if (DestPointee->isIncompleteOrObjectType()) {
01036           // This is definitely the intended conversion, but it might fail due
01037           // to a qualifier violation. Note that we permit Objective-C lifetime
01038           // and GC qualifier mismatches here.
01039           if (!CStyle) {
01040             Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
01041             Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
01042             DestPointeeQuals.removeObjCGCAttr();
01043             DestPointeeQuals.removeObjCLifetime();
01044             SrcPointeeQuals.removeObjCGCAttr();
01045             SrcPointeeQuals.removeObjCLifetime();
01046             if (DestPointeeQuals != SrcPointeeQuals &&
01047                 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
01048               msg = diag::err_bad_cxx_cast_qualifiers_away;
01049               return TC_Failed;
01050             }
01051           }
01052           Kind = CK_BitCast;
01053           return TC_Success;
01054         }
01055       }
01056       else if (DestType->isObjCObjectPointerType()) {
01057         // allow both c-style cast and static_cast of objective-c pointers as 
01058         // they are pervasive.
01059         Kind = CK_CPointerToObjCPointerCast;
01060         return TC_Success;
01061       }
01062       else if (CStyle && DestType->isBlockPointerType()) {
01063         // allow c-style cast of void * to block pointers.
01064         Kind = CK_AnyPointerToBlockPointerCast;
01065         return TC_Success;
01066       }
01067     }
01068   }
01069   // Allow arbitray objective-c pointer conversion with static casts.
01070   if (SrcType->isObjCObjectPointerType() &&
01071       DestType->isObjCObjectPointerType()) {
01072     Kind = CK_BitCast;
01073     return TC_Success;
01074   }
01075   // Allow ns-pointer to cf-pointer conversion in either direction
01076   // with static casts.
01077   if (!CStyle &&
01078       Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind))
01079     return TC_Success;
01080   
01081   // We tried everything. Everything! Nothing works! :-(
01082   return TC_NotApplicable;
01083 }
01084 
01085 /// Tests whether a conversion according to N2844 is valid.
01086 TryCastResult
01087 TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
01088                       bool CStyle, CastKind &Kind, CXXCastPath &BasePath, 
01089                       unsigned &msg) {
01090   // C++0x [expr.static.cast]p3:
01091   //   A glvalue of type "cv1 T1" can be cast to type "rvalue reference to 
01092   //   cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
01093   const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
01094   if (!R)
01095     return TC_NotApplicable;
01096 
01097   if (!SrcExpr->isGLValue())
01098     return TC_NotApplicable;
01099 
01100   // Because we try the reference downcast before this function, from now on
01101   // this is the only cast possibility, so we issue an error if we fail now.
01102   // FIXME: Should allow casting away constness if CStyle.
01103   bool DerivedToBase;
01104   bool ObjCConversion;
01105   bool ObjCLifetimeConversion;
01106   QualType FromType = SrcExpr->getType();
01107   QualType ToType = R->getPointeeType();
01108   if (CStyle) {
01109     FromType = FromType.getUnqualifiedType();
01110     ToType = ToType.getUnqualifiedType();
01111   }
01112   
01113   if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
01114                                         ToType, FromType,
01115                                         DerivedToBase, ObjCConversion,
01116                                         ObjCLifetimeConversion) 
01117         < Sema::Ref_Compatible_With_Added_Qualification) {
01118     msg = diag::err_bad_lvalue_to_rvalue_cast;
01119     return TC_Failed;
01120   }
01121 
01122   if (DerivedToBase) {
01123     Kind = CK_DerivedToBase;
01124     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
01125                        /*DetectVirtual=*/true);
01126     if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
01127       return TC_NotApplicable;
01128   
01129     Self.BuildBasePathArray(Paths, BasePath);
01130   } else
01131     Kind = CK_NoOp;
01132   
01133   return TC_Success;
01134 }
01135 
01136 /// Tests whether a conversion according to C++ 5.2.9p5 is valid.
01137 TryCastResult
01138 TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
01139                            bool CStyle, const SourceRange &OpRange,
01140                            unsigned &msg, CastKind &Kind,
01141                            CXXCastPath &BasePath) {
01142   // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
01143   //   cast to type "reference to cv2 D", where D is a class derived from B,
01144   //   if a valid standard conversion from "pointer to D" to "pointer to B"
01145   //   exists, cv2 >= cv1, and B is not a virtual base class of D.
01146   // In addition, DR54 clarifies that the base must be accessible in the
01147   // current context. Although the wording of DR54 only applies to the pointer
01148   // variant of this rule, the intent is clearly for it to apply to the this
01149   // conversion as well.
01150 
01151   const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
01152   if (!DestReference) {
01153     return TC_NotApplicable;
01154   }
01155   bool RValueRef = DestReference->isRValueReferenceType();
01156   if (!RValueRef && !SrcExpr->isLValue()) {
01157     // We know the left side is an lvalue reference, so we can suggest a reason.
01158     msg = diag::err_bad_cxx_cast_rvalue;
01159     return TC_NotApplicable;
01160   }
01161 
01162   QualType DestPointee = DestReference->getPointeeType();
01163 
01164   // FIXME: If the source is a prvalue, we should issue a warning (because the
01165   // cast always has undefined behavior), and for AST consistency, we should
01166   // materialize a temporary.
01167   return TryStaticDowncast(Self, 
01168                            Self.Context.getCanonicalType(SrcExpr->getType()), 
01169                            Self.Context.getCanonicalType(DestPointee), CStyle,
01170                            OpRange, SrcExpr->getType(), DestType, msg, Kind,
01171                            BasePath);
01172 }
01173 
01174 /// Tests whether a conversion according to C++ 5.2.9p8 is valid.
01175 TryCastResult
01176 TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
01177                          bool CStyle, const SourceRange &OpRange,
01178                          unsigned &msg, CastKind &Kind,
01179                          CXXCastPath &BasePath) {
01180   // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
01181   //   type, can be converted to an rvalue of type "pointer to cv2 D", where D
01182   //   is a class derived from B, if a valid standard conversion from "pointer
01183   //   to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
01184   //   class of D.
01185   // In addition, DR54 clarifies that the base must be accessible in the
01186   // current context.
01187 
01188   const PointerType *DestPointer = DestType->getAs<PointerType>();
01189   if (!DestPointer) {
01190     return TC_NotApplicable;
01191   }
01192 
01193   const PointerType *SrcPointer = SrcType->getAs<PointerType>();
01194   if (!SrcPointer) {
01195     msg = diag::err_bad_static_cast_pointer_nonpointer;
01196     return TC_NotApplicable;
01197   }
01198 
01199   return TryStaticDowncast(Self, 
01200                    Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
01201                   Self.Context.getCanonicalType(DestPointer->getPointeeType()), 
01202                            CStyle, OpRange, SrcType, DestType, msg, Kind,
01203                            BasePath);
01204 }
01205 
01206 /// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
01207 /// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
01208 /// DestType is possible and allowed.
01209 TryCastResult
01210 TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
01211                   bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
01212                   QualType OrigDestType, unsigned &msg, 
01213                   CastKind &Kind, CXXCastPath &BasePath) {
01214   // We can only work with complete types. But don't complain if it doesn't work
01215   if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, 0) ||
01216       Self.RequireCompleteType(OpRange.getBegin(), DestType, 0))
01217     return TC_NotApplicable;
01218 
01219   // Downcast can only happen in class hierarchies, so we need classes.
01220   if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
01221     return TC_NotApplicable;
01222   }
01223 
01224   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
01225                      /*DetectVirtual=*/true);
01226   if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
01227     return TC_NotApplicable;
01228   }
01229 
01230   // Target type does derive from source type. Now we're serious. If an error
01231   // appears now, it's not ignored.
01232   // This may not be entirely in line with the standard. Take for example:
01233   // struct A {};
01234   // struct B : virtual A {
01235   //   B(A&);
01236   // };
01237   //
01238   // void f()
01239   // {
01240   //   (void)static_cast<const B&>(*((A*)0));
01241   // }
01242   // As far as the standard is concerned, p5 does not apply (A is virtual), so
01243   // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
01244   // However, both GCC and Comeau reject this example, and accepting it would
01245   // mean more complex code if we're to preserve the nice error message.
01246   // FIXME: Being 100% compliant here would be nice to have.
01247 
01248   // Must preserve cv, as always, unless we're in C-style mode.
01249   if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
01250     msg = diag::err_bad_cxx_cast_qualifiers_away;
01251     return TC_Failed;
01252   }
01253 
01254   if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
01255     // This code is analoguous to that in CheckDerivedToBaseConversion, except
01256     // that it builds the paths in reverse order.
01257     // To sum up: record all paths to the base and build a nice string from
01258     // them. Use it to spice up the error message.
01259     if (!Paths.isRecordingPaths()) {
01260       Paths.clear();
01261       Paths.setRecordingPaths(true);
01262       Self.IsDerivedFrom(DestType, SrcType, Paths);
01263     }
01264     std::string PathDisplayStr;
01265     std::set<unsigned> DisplayedPaths;
01266     for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
01267          PI != PE; ++PI) {
01268       if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
01269         // We haven't displayed a path to this particular base
01270         // class subobject yet.
01271         PathDisplayStr += "\n    ";
01272         for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
01273                                                  EE = PI->rend();
01274              EI != EE; ++EI)
01275           PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
01276         PathDisplayStr += QualType(DestType).getAsString();
01277       }
01278     }
01279 
01280     Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
01281       << QualType(SrcType).getUnqualifiedType() 
01282       << QualType(DestType).getUnqualifiedType()
01283       << PathDisplayStr << OpRange;
01284     msg = 0;
01285     return TC_Failed;
01286   }
01287 
01288   if (Paths.getDetectedVirtual() != nullptr) {
01289     QualType VirtualBase(Paths.getDetectedVirtual(), 0);
01290     Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
01291       << OrigSrcType << OrigDestType << VirtualBase << OpRange;
01292     msg = 0;
01293     return TC_Failed;
01294   }
01295 
01296   if (!CStyle) {
01297     switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
01298                                       SrcType, DestType,
01299                                       Paths.front(),
01300                                 diag::err_downcast_from_inaccessible_base)) {
01301     case Sema::AR_accessible:
01302     case Sema::AR_delayed:     // be optimistic
01303     case Sema::AR_dependent:   // be optimistic
01304       break;
01305 
01306     case Sema::AR_inaccessible:
01307       msg = 0;
01308       return TC_Failed;
01309     }
01310   }
01311 
01312   Self.BuildBasePathArray(Paths, BasePath);
01313   Kind = CK_BaseToDerived;
01314   return TC_Success;
01315 }
01316 
01317 /// TryStaticMemberPointerUpcast - Tests whether a conversion according to
01318 /// C++ 5.2.9p9 is valid:
01319 ///
01320 ///   An rvalue of type "pointer to member of D of type cv1 T" can be
01321 ///   converted to an rvalue of type "pointer to member of B of type cv2 T",
01322 ///   where B is a base class of D [...].
01323 ///
01324 TryCastResult
01325 TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType, 
01326                              QualType DestType, bool CStyle, 
01327                              const SourceRange &OpRange,
01328                              unsigned &msg, CastKind &Kind,
01329                              CXXCastPath &BasePath) {
01330   const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
01331   if (!DestMemPtr)
01332     return TC_NotApplicable;
01333 
01334   bool WasOverloadedFunction = false;
01335   DeclAccessPair FoundOverload;
01336   if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
01337     if (FunctionDecl *Fn
01338           = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
01339                                                     FoundOverload)) {
01340       CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
01341       SrcType = Self.Context.getMemberPointerType(Fn->getType(),
01342                       Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
01343       WasOverloadedFunction = true;
01344     }
01345   }
01346   
01347   const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
01348   if (!SrcMemPtr) {
01349     msg = diag::err_bad_static_cast_member_pointer_nonmp;
01350     return TC_NotApplicable;
01351   }
01352 
01353   // T == T, modulo cv
01354   if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
01355                                            DestMemPtr->getPointeeType()))
01356     return TC_NotApplicable;
01357 
01358   // B base of D
01359   QualType SrcClass(SrcMemPtr->getClass(), 0);
01360   QualType DestClass(DestMemPtr->getClass(), 0);
01361   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
01362                   /*DetectVirtual=*/true);
01363   if (Self.RequireCompleteType(OpRange.getBegin(), SrcClass, 0) ||
01364       !Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
01365     return TC_NotApplicable;
01366   }
01367 
01368   // B is a base of D. But is it an allowed base? If not, it's a hard error.
01369   if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
01370     Paths.clear();
01371     Paths.setRecordingPaths(true);
01372     bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
01373     assert(StillOkay);
01374     (void)StillOkay;
01375     std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
01376     Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
01377       << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
01378     msg = 0;
01379     return TC_Failed;
01380   }
01381 
01382   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
01383     Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
01384       << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
01385     msg = 0;
01386     return TC_Failed;
01387   }
01388 
01389   if (!CStyle) {
01390     switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
01391                                       DestClass, SrcClass,
01392                                       Paths.front(),
01393                                       diag::err_upcast_to_inaccessible_base)) {
01394     case Sema::AR_accessible:
01395     case Sema::AR_delayed:
01396     case Sema::AR_dependent:
01397       // Optimistically assume that the delayed and dependent cases
01398       // will work out.
01399       break;
01400 
01401     case Sema::AR_inaccessible:
01402       msg = 0;
01403       return TC_Failed;
01404     }
01405   }
01406 
01407   if (WasOverloadedFunction) {
01408     // Resolve the address of the overloaded function again, this time
01409     // allowing complaints if something goes wrong.
01410     FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), 
01411                                                                DestType, 
01412                                                                true,
01413                                                                FoundOverload);
01414     if (!Fn) {
01415       msg = 0;
01416       return TC_Failed;
01417     }
01418 
01419     SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
01420     if (!SrcExpr.isUsable()) {
01421       msg = 0;
01422       return TC_Failed;
01423     }
01424   }
01425 
01426   Self.BuildBasePathArray(Paths, BasePath);
01427   Kind = CK_DerivedToBaseMemberPointer;
01428   return TC_Success;
01429 }
01430 
01431 /// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
01432 /// is valid:
01433 ///
01434 ///   An expression e can be explicitly converted to a type T using a
01435 ///   @c static_cast if the declaration "T t(e);" is well-formed [...].
01436 TryCastResult
01437 TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
01438                       Sema::CheckedConversionKind CCK, 
01439                       const SourceRange &OpRange, unsigned &msg,
01440                       CastKind &Kind, bool ListInitialization) {
01441   if (DestType->isRecordType()) {
01442     if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
01443                                  diag::err_bad_dynamic_cast_incomplete) ||
01444         Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
01445                                     diag::err_allocation_of_abstract_type)) {
01446       msg = 0;
01447       return TC_Failed;
01448     }
01449   } else if (DestType->isMemberPointerType()) {
01450     if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
01451       Self.RequireCompleteType(OpRange.getBegin(), DestType, 0);
01452     }
01453   }
01454 
01455   InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
01456   InitializationKind InitKind
01457     = (CCK == Sema::CCK_CStyleCast)
01458         ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
01459                                                ListInitialization)
01460     : (CCK == Sema::CCK_FunctionalCast)
01461         ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
01462     : InitializationKind::CreateCast(OpRange);
01463   Expr *SrcExprRaw = SrcExpr.get();
01464   InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
01465 
01466   // At this point of CheckStaticCast, if the destination is a reference,
01467   // or the expression is an overload expression this has to work. 
01468   // There is no other way that works.
01469   // On the other hand, if we're checking a C-style cast, we've still got
01470   // the reinterpret_cast way.
01471   bool CStyle 
01472     = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
01473   if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
01474     return TC_NotApplicable;
01475     
01476   ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
01477   if (Result.isInvalid()) {
01478     msg = 0;
01479     return TC_Failed;
01480   }
01481   
01482   if (InitSeq.isConstructorInitialization())
01483     Kind = CK_ConstructorConversion;
01484   else
01485     Kind = CK_NoOp;
01486   
01487   SrcExpr = Result;
01488   return TC_Success;
01489 }
01490 
01491 /// TryConstCast - See if a const_cast from source to destination is allowed,
01492 /// and perform it if it is.
01493 static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
01494                                   QualType DestType, bool CStyle,
01495                                   unsigned &msg) {
01496   DestType = Self.Context.getCanonicalType(DestType);
01497   QualType SrcType = SrcExpr.get()->getType();
01498   bool NeedToMaterializeTemporary = false;
01499 
01500   if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
01501     // C++11 5.2.11p4:
01502     //   if a pointer to T1 can be explicitly converted to the type "pointer to
01503     //   T2" using a const_cast, then the following conversions can also be
01504     //   made:
01505     //    -- an lvalue of type T1 can be explicitly converted to an lvalue of
01506     //       type T2 using the cast const_cast<T2&>;
01507     //    -- a glvalue of type T1 can be explicitly converted to an xvalue of
01508     //       type T2 using the cast const_cast<T2&&>; and
01509     //    -- if T1 is a class type, a prvalue of type T1 can be explicitly
01510     //       converted to an xvalue of type T2 using the cast const_cast<T2&&>.
01511 
01512     if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) {
01513       // Cannot const_cast non-lvalue to lvalue reference type. But if this
01514       // is C-style, static_cast might find a way, so we simply suggest a
01515       // message and tell the parent to keep searching.
01516       msg = diag::err_bad_cxx_cast_rvalue;
01517       return TC_NotApplicable;
01518     }
01519 
01520     if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) {
01521       if (!SrcType->isRecordType()) {
01522         // Cannot const_cast non-class prvalue to rvalue reference type. But if
01523         // this is C-style, static_cast can do this.
01524         msg = diag::err_bad_cxx_cast_rvalue;
01525         return TC_NotApplicable;
01526       }
01527 
01528       // Materialize the class prvalue so that the const_cast can bind a
01529       // reference to it.
01530       NeedToMaterializeTemporary = true;
01531     }
01532 
01533     // It's not completely clear under the standard whether we can
01534     // const_cast bit-field gl-values.  Doing so would not be
01535     // intrinsically complicated, but for now, we say no for
01536     // consistency with other compilers and await the word of the
01537     // committee.
01538     if (SrcExpr.get()->refersToBitField()) {
01539       msg = diag::err_bad_cxx_cast_bitfield;
01540       return TC_NotApplicable;
01541     }
01542 
01543     DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
01544     SrcType = Self.Context.getPointerType(SrcType);
01545   }
01546 
01547   // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
01548   //   the rules for const_cast are the same as those used for pointers.
01549 
01550   if (!DestType->isPointerType() &&
01551       !DestType->isMemberPointerType() &&
01552       !DestType->isObjCObjectPointerType()) {
01553     // Cannot cast to non-pointer, non-reference type. Note that, if DestType
01554     // was a reference type, we converted it to a pointer above.
01555     // The status of rvalue references isn't entirely clear, but it looks like
01556     // conversion to them is simply invalid.
01557     // C++ 5.2.11p3: For two pointer types [...]
01558     if (!CStyle)
01559       msg = diag::err_bad_const_cast_dest;
01560     return TC_NotApplicable;
01561   }
01562   if (DestType->isFunctionPointerType() ||
01563       DestType->isMemberFunctionPointerType()) {
01564     // Cannot cast direct function pointers.
01565     // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
01566     // T is the ultimate pointee of source and target type.
01567     if (!CStyle)
01568       msg = diag::err_bad_const_cast_dest;
01569     return TC_NotApplicable;
01570   }
01571   SrcType = Self.Context.getCanonicalType(SrcType);
01572 
01573   // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
01574   // completely equal.
01575   // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
01576   // in multi-level pointers may change, but the level count must be the same,
01577   // as must be the final pointee type.
01578   while (SrcType != DestType &&
01579          Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
01580     Qualifiers SrcQuals, DestQuals;
01581     SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
01582     DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
01583     
01584     // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
01585     // the other qualifiers (e.g., address spaces) are identical.
01586     SrcQuals.removeCVRQualifiers();
01587     DestQuals.removeCVRQualifiers();
01588     if (SrcQuals != DestQuals)
01589       return TC_NotApplicable;
01590   }
01591 
01592   // Since we're dealing in canonical types, the remainder must be the same.
01593   if (SrcType != DestType)
01594     return TC_NotApplicable;
01595 
01596   if (NeedToMaterializeTemporary)
01597     // This is a const_cast from a class prvalue to an rvalue reference type.
01598     // Materialize a temporary to store the result of the conversion.
01599     SrcExpr = new (Self.Context) MaterializeTemporaryExpr(
01600         SrcType, SrcExpr.get(), /*IsLValueReference*/ false);
01601 
01602   return TC_Success;
01603 }
01604 
01605 // Checks for undefined behavior in reinterpret_cast.
01606 // The cases that is checked for is:
01607 // *reinterpret_cast<T*>(&a)
01608 // reinterpret_cast<T&>(a)
01609 // where accessing 'a' as type 'T' will result in undefined behavior.
01610 void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
01611                                           bool IsDereference,
01612                                           SourceRange Range) {
01613   unsigned DiagID = IsDereference ?
01614                         diag::warn_pointer_indirection_from_incompatible_type :
01615                         diag::warn_undefined_reinterpret_cast;
01616 
01617   if (Diags.isIgnored(DiagID, Range.getBegin()))
01618     return;
01619 
01620   QualType SrcTy, DestTy;
01621   if (IsDereference) {
01622     if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
01623       return;
01624     }
01625     SrcTy = SrcType->getPointeeType();
01626     DestTy = DestType->getPointeeType();
01627   } else {
01628     if (!DestType->getAs<ReferenceType>()) {
01629       return;
01630     }
01631     SrcTy = SrcType;
01632     DestTy = DestType->getPointeeType();
01633   }
01634 
01635   // Cast is compatible if the types are the same.
01636   if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
01637     return;
01638   }
01639   // or one of the types is a char or void type
01640   if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
01641       SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
01642     return;
01643   }
01644   // or one of the types is a tag type.
01645   if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
01646     return;
01647   }
01648 
01649   // FIXME: Scoped enums?
01650   if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
01651       (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
01652     if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
01653       return;
01654     }
01655   }
01656 
01657   Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
01658 }
01659 
01660 static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
01661                                   QualType DestType) {
01662   QualType SrcType = SrcExpr.get()->getType();
01663   if (Self.Context.hasSameType(SrcType, DestType))
01664     return;
01665   if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
01666     if (SrcPtrTy->isObjCSelType()) {
01667       QualType DT = DestType;
01668       if (isa<PointerType>(DestType))
01669         DT = DestType->getPointeeType();
01670       if (!DT.getUnqualifiedType()->isVoidType())
01671         Self.Diag(SrcExpr.get()->getExprLoc(),
01672                   diag::warn_cast_pointer_from_sel)
01673         << SrcType << DestType << SrcExpr.get()->getSourceRange();
01674     }
01675 }
01676 
01677 static void checkIntToPointerCast(bool CStyle, SourceLocation Loc,
01678                                   const Expr *SrcExpr, QualType DestType,
01679                                   Sema &Self) {
01680   QualType SrcType = SrcExpr->getType();
01681 
01682   // Not warning on reinterpret_cast, boolean, constant expressions, etc
01683   // are not explicit design choices, but consistent with GCC's behavior.
01684   // Feel free to modify them if you've reason/evidence for an alternative.
01685   if (CStyle && SrcType->isIntegralType(Self.Context)
01686       && !SrcType->isBooleanType()
01687       && !SrcType->isEnumeralType()
01688       && !SrcExpr->isIntegerConstantExpr(Self.Context)
01689       && Self.Context.getTypeSize(DestType) >
01690          Self.Context.getTypeSize(SrcType)) {
01691     // Separate between casts to void* and non-void* pointers.
01692     // Some APIs use (abuse) void* for something like a user context,
01693     // and often that value is an integer even if it isn't a pointer itself.
01694     // Having a separate warning flag allows users to control the warning
01695     // for their workflow.
01696     unsigned Diag = DestType->isVoidPointerType() ?
01697                       diag::warn_int_to_void_pointer_cast
01698                     : diag::warn_int_to_pointer_cast;
01699     Self.Diag(Loc, Diag) << SrcType << DestType;
01700   }
01701 }
01702 
01703 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
01704                                         QualType DestType, bool CStyle,
01705                                         const SourceRange &OpRange,
01706                                         unsigned &msg,
01707                                         CastKind &Kind) {
01708   bool IsLValueCast = false;
01709   
01710   DestType = Self.Context.getCanonicalType(DestType);
01711   QualType SrcType = SrcExpr.get()->getType();
01712 
01713   // Is the source an overloaded name? (i.e. &foo)
01714   // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ...
01715   if (SrcType == Self.Context.OverloadTy) {
01716     // ... unless foo<int> resolves to an lvalue unambiguously.
01717     // TODO: what if this fails because of DiagnoseUseOfDecl or something
01718     // like it?
01719     ExprResult SingleFunctionExpr = SrcExpr;
01720     if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
01721           SingleFunctionExpr,
01722           Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr 
01723         ) && SingleFunctionExpr.isUsable()) {
01724       SrcExpr = SingleFunctionExpr;
01725       SrcType = SrcExpr.get()->getType();
01726     } else {
01727       return TC_NotApplicable;
01728     }
01729   }
01730 
01731   if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
01732     if (!SrcExpr.get()->isGLValue()) {
01733       // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
01734       // similar comment in const_cast.
01735       msg = diag::err_bad_cxx_cast_rvalue;
01736       return TC_NotApplicable;
01737     }
01738 
01739     if (!CStyle) {
01740       Self.CheckCompatibleReinterpretCast(SrcType, DestType,
01741                                           /*isDereference=*/false, OpRange);
01742     }
01743 
01744     // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
01745     //   same effect as the conversion *reinterpret_cast<T*>(&x) with the
01746     //   built-in & and * operators.
01747 
01748     const char *inappropriate = nullptr;
01749     switch (SrcExpr.get()->getObjectKind()) {
01750     case OK_Ordinary:
01751       break;
01752     case OK_BitField:        inappropriate = "bit-field";           break;
01753     case OK_VectorComponent: inappropriate = "vector element";      break;
01754     case OK_ObjCProperty:    inappropriate = "property expression"; break;
01755     case OK_ObjCSubscript:   inappropriate = "container subscripting expression"; 
01756                              break;
01757     }
01758     if (inappropriate) {
01759       Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
01760           << inappropriate << DestType
01761           << OpRange << SrcExpr.get()->getSourceRange();
01762       msg = 0; SrcExpr = ExprError();
01763       return TC_NotApplicable;
01764     }
01765 
01766     // This code does this transformation for the checked types.
01767     DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
01768     SrcType = Self.Context.getPointerType(SrcType);
01769     
01770     IsLValueCast = true;
01771   }
01772 
01773   // Canonicalize source for comparison.
01774   SrcType = Self.Context.getCanonicalType(SrcType);
01775 
01776   const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
01777                           *SrcMemPtr = SrcType->getAs<MemberPointerType>();
01778   if (DestMemPtr && SrcMemPtr) {
01779     // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
01780     //   can be explicitly converted to an rvalue of type "pointer to member
01781     //   of Y of type T2" if T1 and T2 are both function types or both object
01782     //   types.
01783     if (DestMemPtr->getPointeeType()->isFunctionType() !=
01784         SrcMemPtr->getPointeeType()->isFunctionType())
01785       return TC_NotApplicable;
01786 
01787     // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
01788     //   constness.
01789     // A reinterpret_cast followed by a const_cast can, though, so in C-style,
01790     // we accept it.
01791     if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
01792                            /*CheckObjCLifetime=*/CStyle)) {
01793       msg = diag::err_bad_cxx_cast_qualifiers_away;
01794       return TC_Failed;
01795     }
01796 
01797     if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
01798       // We need to determine the inheritance model that the class will use if
01799       // haven't yet.
01800       Self.RequireCompleteType(OpRange.getBegin(), SrcType, 0);
01801       Self.RequireCompleteType(OpRange.getBegin(), DestType, 0);
01802     }
01803 
01804     // Don't allow casting between member pointers of different sizes.
01805     if (Self.Context.getTypeSize(DestMemPtr) !=
01806         Self.Context.getTypeSize(SrcMemPtr)) {
01807       msg = diag::err_bad_cxx_cast_member_pointer_size;
01808       return TC_Failed;
01809     }
01810 
01811     // A valid member pointer cast.
01812     assert(!IsLValueCast);
01813     Kind = CK_ReinterpretMemberPointer;
01814     return TC_Success;
01815   }
01816 
01817   // See below for the enumeral issue.
01818   if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
01819     // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
01820     //   type large enough to hold it. A value of std::nullptr_t can be
01821     //   converted to an integral type; the conversion has the same meaning
01822     //   and validity as a conversion of (void*)0 to the integral type.
01823     if (Self.Context.getTypeSize(SrcType) >
01824         Self.Context.getTypeSize(DestType)) {
01825       msg = diag::err_bad_reinterpret_cast_small_int;
01826       return TC_Failed;
01827     }
01828     Kind = CK_PointerToIntegral;
01829     return TC_Success;
01830   }
01831 
01832   bool destIsVector = DestType->isVectorType();
01833   bool srcIsVector = SrcType->isVectorType();
01834   if (srcIsVector || destIsVector) {
01835     // FIXME: Should this also apply to floating point types?
01836     bool srcIsScalar = SrcType->isIntegralType(Self.Context);
01837     bool destIsScalar = DestType->isIntegralType(Self.Context);
01838     
01839     // Check if this is a cast between a vector and something else.
01840     if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
01841         !(srcIsVector && destIsVector))
01842       return TC_NotApplicable;
01843 
01844     // If both types have the same size, we can successfully cast.
01845     if (Self.Context.getTypeSize(SrcType)
01846           == Self.Context.getTypeSize(DestType)) {
01847       Kind = CK_BitCast;
01848       return TC_Success;
01849     }
01850     
01851     if (destIsScalar)
01852       msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
01853     else if (srcIsScalar)
01854       msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
01855     else
01856       msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
01857     
01858     return TC_Failed;
01859   }
01860 
01861   if (SrcType == DestType) {
01862     // C++ 5.2.10p2 has a note that mentions that, subject to all other
01863     // restrictions, a cast to the same type is allowed so long as it does not
01864     // cast away constness. In C++98, the intent was not entirely clear here, 
01865     // since all other paragraphs explicitly forbid casts to the same type.
01866     // C++11 clarifies this case with p2.
01867     //
01868     // The only allowed types are: integral, enumeration, pointer, or 
01869     // pointer-to-member types.  We also won't restrict Obj-C pointers either.
01870     Kind = CK_NoOp;
01871     TryCastResult Result = TC_NotApplicable;
01872     if (SrcType->isIntegralOrEnumerationType() ||
01873         SrcType->isAnyPointerType() ||
01874         SrcType->isMemberPointerType() ||
01875         SrcType->isBlockPointerType()) {
01876       Result = TC_Success;
01877     }
01878     return Result;
01879   }
01880 
01881   bool destIsPtr = DestType->isAnyPointerType() ||
01882                    DestType->isBlockPointerType();
01883   bool srcIsPtr = SrcType->isAnyPointerType() ||
01884                   SrcType->isBlockPointerType();
01885   if (!destIsPtr && !srcIsPtr) {
01886     // Except for std::nullptr_t->integer and lvalue->reference, which are
01887     // handled above, at least one of the two arguments must be a pointer.
01888     return TC_NotApplicable;
01889   }
01890 
01891   if (DestType->isIntegralType(Self.Context)) {
01892     assert(srcIsPtr && "One type must be a pointer");
01893     // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
01894     //   type large enough to hold it; except in Microsoft mode, where the
01895     //   integral type size doesn't matter (except we don't allow bool).
01896     bool MicrosoftException = Self.getLangOpts().MicrosoftExt &&
01897                               !DestType->isBooleanType();
01898     if ((Self.Context.getTypeSize(SrcType) >
01899          Self.Context.getTypeSize(DestType)) &&
01900          !MicrosoftException) {
01901       msg = diag::err_bad_reinterpret_cast_small_int;
01902       return TC_Failed;
01903     }
01904     Kind = CK_PointerToIntegral;
01905     return TC_Success;
01906   }
01907 
01908   if (SrcType->isIntegralOrEnumerationType()) {
01909     assert(destIsPtr && "One type must be a pointer");
01910     checkIntToPointerCast(CStyle, OpRange.getBegin(), SrcExpr.get(), DestType,
01911                           Self);
01912     // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
01913     //   converted to a pointer.
01914     // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
01915     //   necessarily converted to a null pointer value.]
01916     Kind = CK_IntegralToPointer;
01917     return TC_Success;
01918   }
01919 
01920   if (!destIsPtr || !srcIsPtr) {
01921     // With the valid non-pointer conversions out of the way, we can be even
01922     // more stringent.
01923     return TC_NotApplicable;
01924   }
01925 
01926   // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
01927   // The C-style cast operator can.
01928   if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
01929                          /*CheckObjCLifetime=*/CStyle)) {
01930     msg = diag::err_bad_cxx_cast_qualifiers_away;
01931     return TC_Failed;
01932   }
01933   
01934   // Cannot convert between block pointers and Objective-C object pointers.
01935   if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
01936       (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
01937     return TC_NotApplicable;
01938 
01939   if (IsLValueCast) {
01940     Kind = CK_LValueBitCast;
01941   } else if (DestType->isObjCObjectPointerType()) {
01942     Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
01943   } else if (DestType->isBlockPointerType()) {
01944     if (!SrcType->isBlockPointerType()) {
01945       Kind = CK_AnyPointerToBlockPointerCast;
01946     } else {
01947       Kind = CK_BitCast;
01948     }
01949   } else {
01950     Kind = CK_BitCast;
01951   }
01952 
01953   // Any pointer can be cast to an Objective-C pointer type with a C-style
01954   // cast.
01955   if (CStyle && DestType->isObjCObjectPointerType()) {
01956     return TC_Success;
01957   }
01958   if (CStyle)
01959     DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
01960   
01961   // Not casting away constness, so the only remaining check is for compatible
01962   // pointer categories.
01963 
01964   if (SrcType->isFunctionPointerType()) {
01965     if (DestType->isFunctionPointerType()) {
01966       // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
01967       // a pointer to a function of a different type.
01968       return TC_Success;
01969     }
01970 
01971     // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
01972     //   an object type or vice versa is conditionally-supported.
01973     // Compilers support it in C++03 too, though, because it's necessary for
01974     // casting the return value of dlsym() and GetProcAddress().
01975     // FIXME: Conditionally-supported behavior should be configurable in the
01976     // TargetInfo or similar.
01977     Self.Diag(OpRange.getBegin(),
01978               Self.getLangOpts().CPlusPlus11 ?
01979                 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
01980       << OpRange;
01981     return TC_Success;
01982   }
01983 
01984   if (DestType->isFunctionPointerType()) {
01985     // See above.
01986     Self.Diag(OpRange.getBegin(),
01987               Self.getLangOpts().CPlusPlus11 ?
01988                 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
01989       << OpRange;
01990     return TC_Success;
01991   }
01992   
01993   // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
01994   //   a pointer to an object of different type.
01995   // Void pointers are not specified, but supported by every compiler out there.
01996   // So we finish by allowing everything that remains - it's got to be two
01997   // object pointers.
01998   return TC_Success;
01999 }                                     
02000 
02001 void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
02002                                        bool ListInitialization) {
02003   // Handle placeholders.
02004   if (isPlaceholder()) {
02005     // C-style casts can resolve __unknown_any types.
02006     if (claimPlaceholder(BuiltinType::UnknownAny)) {
02007       SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
02008                                          SrcExpr.get(), Kind,
02009                                          ValueKind, BasePath);
02010       return;
02011     }
02012 
02013     checkNonOverloadPlaceholders();
02014     if (SrcExpr.isInvalid())
02015       return;
02016   }
02017 
02018   // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
02019   // This test is outside everything else because it's the only case where
02020   // a non-lvalue-reference target type does not lead to decay.
02021   if (DestType->isVoidType()) {
02022     Kind = CK_ToVoid;
02023 
02024     if (claimPlaceholder(BuiltinType::Overload)) {
02025       Self.ResolveAndFixSingleFunctionTemplateSpecialization(
02026                   SrcExpr, /* Decay Function to ptr */ false, 
02027                   /* Complain */ true, DestRange, DestType,
02028                   diag::err_bad_cstyle_cast_overload);
02029       if (SrcExpr.isInvalid())
02030         return;
02031     }
02032 
02033     SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
02034     return;
02035   }
02036 
02037   // If the type is dependent, we won't do any other semantic analysis now.
02038   if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
02039       SrcExpr.get()->isValueDependent()) {
02040     assert(Kind == CK_Dependent);
02041     return;
02042   }
02043 
02044   if (ValueKind == VK_RValue && !DestType->isRecordType() &&
02045       !isPlaceholder(BuiltinType::Overload)) {
02046     SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
02047     if (SrcExpr.isInvalid())
02048       return;
02049   }
02050 
02051   // AltiVec vector initialization with a single literal.
02052   if (const VectorType *vecTy = DestType->getAs<VectorType>())
02053     if (vecTy->getVectorKind() == VectorType::AltiVecVector
02054         && (SrcExpr.get()->getType()->isIntegerType()
02055             || SrcExpr.get()->getType()->isFloatingType())) {
02056       Kind = CK_VectorSplat;
02057       return;
02058     }
02059 
02060   // C++ [expr.cast]p5: The conversions performed by
02061   //   - a const_cast,
02062   //   - a static_cast,
02063   //   - a static_cast followed by a const_cast,
02064   //   - a reinterpret_cast, or
02065   //   - a reinterpret_cast followed by a const_cast,
02066   //   can be performed using the cast notation of explicit type conversion.
02067   //   [...] If a conversion can be interpreted in more than one of the ways
02068   //   listed above, the interpretation that appears first in the list is used,
02069   //   even if a cast resulting from that interpretation is ill-formed.
02070   // In plain language, this means trying a const_cast ...
02071   unsigned msg = diag::err_bad_cxx_cast_generic;
02072   TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
02073                                    /*CStyle*/true, msg);
02074   if (SrcExpr.isInvalid())
02075     return;
02076   if (tcr == TC_Success)
02077     Kind = CK_NoOp;
02078 
02079   Sema::CheckedConversionKind CCK
02080     = FunctionalStyle? Sema::CCK_FunctionalCast
02081                      : Sema::CCK_CStyleCast;
02082   if (tcr == TC_NotApplicable) {
02083     // ... or if that is not possible, a static_cast, ignoring const, ...
02084     tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
02085                         msg, Kind, BasePath, ListInitialization);
02086     if (SrcExpr.isInvalid())
02087       return;
02088 
02089     if (tcr == TC_NotApplicable) {
02090       // ... and finally a reinterpret_cast, ignoring const.
02091       tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
02092                                OpRange, msg, Kind);
02093       if (SrcExpr.isInvalid())
02094         return;
02095     }
02096   }
02097 
02098   if (Self.getLangOpts().ObjCAutoRefCount && tcr == TC_Success)
02099     checkObjCARCConversion(CCK);
02100 
02101   if (tcr != TC_Success && msg != 0) {
02102     if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
02103       DeclAccessPair Found;
02104       FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
02105                                 DestType,
02106                                 /*Complain*/ true,
02107                                 Found);
02108       if (Fn) {
02109         // If DestType is a function type (not to be confused with the function
02110         // pointer type), it will be possible to resolve the function address,
02111         // but the type cast should be considered as failure.
02112         OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression;
02113         Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload)
02114           << OE->getName() << DestType << OpRange
02115           << OE->getQualifierLoc().getSourceRange();
02116         Self.NoteAllOverloadCandidates(SrcExpr.get());
02117       }
02118     } else {
02119       diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
02120                       OpRange, SrcExpr.get(), DestType, ListInitialization);
02121     }
02122   } else if (Kind == CK_BitCast) {
02123     checkCastAlign();
02124   }
02125 
02126   // Clear out SrcExpr if there was a fatal error.
02127   if (tcr != TC_Success)
02128     SrcExpr = ExprError();
02129 }
02130 
02131 /// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a 
02132 ///  non-matching type. Such as enum function call to int, int call to
02133 /// pointer; etc. Cast to 'void' is an exception.
02134 static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
02135                                   QualType DestType) {
02136   if (Self.Diags.isIgnored(diag::warn_bad_function_cast,
02137                            SrcExpr.get()->getExprLoc()))
02138     return;
02139   
02140   if (!isa<CallExpr>(SrcExpr.get()))
02141     return;
02142   
02143   QualType SrcType = SrcExpr.get()->getType();
02144   if (DestType.getUnqualifiedType()->isVoidType())
02145     return;
02146   if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
02147       && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
02148     return;
02149   if (SrcType->isIntegerType() && DestType->isIntegerType() &&
02150       (SrcType->isBooleanType() == DestType->isBooleanType()) &&
02151       (SrcType->isEnumeralType() == DestType->isEnumeralType()))
02152     return;
02153   if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
02154     return;
02155   if (SrcType->isEnumeralType() && DestType->isEnumeralType())
02156     return;
02157   if (SrcType->isComplexType() && DestType->isComplexType())
02158     return;
02159   if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
02160     return;
02161   
02162   Self.Diag(SrcExpr.get()->getExprLoc(),
02163             diag::warn_bad_function_cast)
02164             << SrcType << DestType << SrcExpr.get()->getSourceRange();
02165 }
02166 
02167 /// Check the semantics of a C-style cast operation, in C.
02168 void CastOperation::CheckCStyleCast() {
02169   assert(!Self.getLangOpts().CPlusPlus);
02170 
02171   // C-style casts can resolve __unknown_any types.
02172   if (claimPlaceholder(BuiltinType::UnknownAny)) {
02173     SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
02174                                        SrcExpr.get(), Kind,
02175                                        ValueKind, BasePath);
02176     return;
02177   }
02178 
02179   // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
02180   // type needs to be scalar.
02181   if (DestType->isVoidType()) {
02182     // We don't necessarily do lvalue-to-rvalue conversions on this.
02183     SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
02184     if (SrcExpr.isInvalid())
02185       return;
02186 
02187     // Cast to void allows any expr type.
02188     Kind = CK_ToVoid;
02189     return;
02190   }
02191 
02192   SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
02193   if (SrcExpr.isInvalid())
02194     return;
02195   QualType SrcType = SrcExpr.get()->getType();
02196 
02197   assert(!SrcType->isPlaceholderType());
02198 
02199   // OpenCL v1 s6.5: Casting a pointer to address space A to a pointer to
02200   // address space B is illegal.
02201   if (Self.getLangOpts().OpenCL && DestType->isPointerType() &&
02202       SrcType->isPointerType()) {
02203     if (DestType->getPointeeType().getAddressSpace() !=
02204         SrcType->getPointeeType().getAddressSpace()) {
02205       Self.Diag(OpRange.getBegin(),
02206                 diag::err_typecheck_incompatible_address_space)
02207           << SrcType << DestType << Sema::AA_Casting
02208           << SrcExpr.get()->getSourceRange();
02209       SrcExpr = ExprError();
02210       return;
02211     }
02212   }
02213 
02214   if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
02215                                diag::err_typecheck_cast_to_incomplete)) {
02216     SrcExpr = ExprError();
02217     return;
02218   }
02219 
02220   if (!DestType->isScalarType() && !DestType->isVectorType()) {
02221     const RecordType *DestRecordTy = DestType->getAs<RecordType>();
02222 
02223     if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
02224       // GCC struct/union extension: allow cast to self.
02225       Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
02226         << DestType << SrcExpr.get()->getSourceRange();
02227       Kind = CK_NoOp;
02228       return;
02229     }
02230 
02231     // GCC's cast to union extension.
02232     if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
02233       RecordDecl *RD = DestRecordTy->getDecl();
02234       RecordDecl::field_iterator Field, FieldEnd;
02235       for (Field = RD->field_begin(), FieldEnd = RD->field_end();
02236            Field != FieldEnd; ++Field) {
02237         if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) &&
02238             !Field->isUnnamedBitfield()) {
02239           Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
02240             << SrcExpr.get()->getSourceRange();
02241           break;
02242         }
02243       }
02244       if (Field == FieldEnd) {
02245         Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
02246           << SrcType << SrcExpr.get()->getSourceRange();
02247         SrcExpr = ExprError();
02248         return;
02249       }
02250       Kind = CK_ToUnion;
02251       return;
02252     }
02253 
02254     // Reject any other conversions to non-scalar types.
02255     Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
02256       << DestType << SrcExpr.get()->getSourceRange();
02257     SrcExpr = ExprError();
02258     return;
02259   }
02260 
02261   // The type we're casting to is known to be a scalar or vector.
02262 
02263   // Require the operand to be a scalar or vector.
02264   if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
02265     Self.Diag(SrcExpr.get()->getExprLoc(),
02266               diag::err_typecheck_expect_scalar_operand)
02267       << SrcType << SrcExpr.get()->getSourceRange();
02268     SrcExpr = ExprError();
02269     return;
02270   }
02271 
02272   if (DestType->isExtVectorType()) {
02273     SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind);
02274     return;
02275   }
02276 
02277   if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
02278     if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
02279           (SrcType->isIntegerType() || SrcType->isFloatingType())) {
02280       Kind = CK_VectorSplat;
02281     } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
02282       SrcExpr = ExprError();
02283     }
02284     return;
02285   }
02286 
02287   if (SrcType->isVectorType()) {
02288     if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
02289       SrcExpr = ExprError();
02290     return;
02291   }
02292 
02293   // The source and target types are both scalars, i.e.
02294   //   - arithmetic types (fundamental, enum, and complex)
02295   //   - all kinds of pointers
02296   // Note that member pointers were filtered out with C++, above.
02297 
02298   if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
02299     Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
02300     SrcExpr = ExprError();
02301     return;
02302   }
02303 
02304   // If either type is a pointer, the other type has to be either an
02305   // integer or a pointer.
02306   if (!DestType->isArithmeticType()) {
02307     if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
02308       Self.Diag(SrcExpr.get()->getExprLoc(),
02309                 diag::err_cast_pointer_from_non_pointer_int)
02310         << SrcType << SrcExpr.get()->getSourceRange();
02311       SrcExpr = ExprError();
02312       return;
02313     }
02314     checkIntToPointerCast(/* CStyle */ true, OpRange.getBegin(), SrcExpr.get(),
02315                           DestType, Self);
02316   } else if (!SrcType->isArithmeticType()) {
02317     if (!DestType->isIntegralType(Self.Context) &&
02318         DestType->isArithmeticType()) {
02319       Self.Diag(SrcExpr.get()->getLocStart(),
02320            diag::err_cast_pointer_to_non_pointer_int)
02321         << DestType << SrcExpr.get()->getSourceRange();
02322       SrcExpr = ExprError();
02323       return;
02324     }
02325   }
02326 
02327   if (Self.getLangOpts().OpenCL && !Self.getOpenCLOptions().cl_khr_fp16) {
02328     if (DestType->isHalfType()) {
02329       Self.Diag(SrcExpr.get()->getLocStart(), diag::err_opencl_cast_to_half)
02330         << DestType << SrcExpr.get()->getSourceRange();
02331       SrcExpr = ExprError();
02332       return;
02333     }
02334   }
02335 
02336   // ARC imposes extra restrictions on casts.
02337   if (Self.getLangOpts().ObjCAutoRefCount) {
02338     checkObjCARCConversion(Sema::CCK_CStyleCast);
02339     if (SrcExpr.isInvalid())
02340       return;
02341     
02342     if (const PointerType *CastPtr = DestType->getAs<PointerType>()) {
02343       if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
02344         Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
02345         Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
02346         if (CastPtr->getPointeeType()->isObjCLifetimeType() && 
02347             ExprPtr->getPointeeType()->isObjCLifetimeType() &&
02348             !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
02349           Self.Diag(SrcExpr.get()->getLocStart(), 
02350                     diag::err_typecheck_incompatible_ownership)
02351             << SrcType << DestType << Sema::AA_Casting
02352             << SrcExpr.get()->getSourceRange();
02353           return;
02354         }
02355       }
02356     } 
02357     else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
02358       Self.Diag(SrcExpr.get()->getLocStart(), 
02359                 diag::err_arc_convesion_of_weak_unavailable)
02360         << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
02361       SrcExpr = ExprError();
02362       return;
02363     }
02364   }
02365   
02366   DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
02367   DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
02368   Kind = Self.PrepareScalarCast(SrcExpr, DestType);
02369   if (SrcExpr.isInvalid())
02370     return;
02371 
02372   if (Kind == CK_BitCast)
02373     checkCastAlign();
02374 }
02375 
02376 ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
02377                                      TypeSourceInfo *CastTypeInfo,
02378                                      SourceLocation RPLoc,
02379                                      Expr *CastExpr) {
02380   CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);  
02381   Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
02382   Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
02383 
02384   if (getLangOpts().CPlusPlus) {
02385     Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false,
02386                           isa<InitListExpr>(CastExpr));
02387   } else {
02388     Op.CheckCStyleCast();
02389   }
02390 
02391   if (Op.SrcExpr.isInvalid())
02392     return ExprError();
02393 
02394   return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
02395                               Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
02396                               &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
02397 }
02398 
02399 ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
02400                                             SourceLocation LPLoc,
02401                                             Expr *CastExpr,
02402                                             SourceLocation RPLoc) {
02403   assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
02404   CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
02405   Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
02406   Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
02407 
02408   Op.CheckCXXCStyleCast(/*FunctionalStyle=*/true, /*ListInit=*/false);
02409   if (Op.SrcExpr.isInvalid())
02410     return ExprError();
02411   
02412   if (CXXConstructExpr *ConstructExpr = dyn_cast<CXXConstructExpr>(Op.SrcExpr.get()))
02413     ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc));
02414 
02415   return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
02416                          Op.ValueKind, CastTypeInfo, Op.Kind,
02417                          Op.SrcExpr.get(), &Op.BasePath, LPLoc, RPLoc));
02418 }