Home | History | Annotate | Line # | Download | only in Sema
      1 //===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===//
      2 //
      3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
      4 // See https://llvm.org/LICENSE.txt for license information.
      5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
      6 //
      7 //===----------------------------------------------------------------------===//
      8 //
      9 //  This file implements semantic analysis for cast expressions, including
     10 //  1) C-style casts like '(int) x'
     11 //  2) C++ functional casts like 'int(x)'
     12 //  3) C++ named casts like 'static_cast<int>(x)'
     13 //
     14 //===----------------------------------------------------------------------===//
     15 
     16 #include "clang/AST/ASTContext.h"
     17 #include "clang/AST/ASTStructuralEquivalence.h"
     18 #include "clang/AST/CXXInheritance.h"
     19 #include "clang/AST/ExprCXX.h"
     20 #include "clang/AST/ExprObjC.h"
     21 #include "clang/AST/RecordLayout.h"
     22 #include "clang/Basic/PartialDiagnostic.h"
     23 #include "clang/Basic/TargetInfo.h"
     24 #include "clang/Lex/Preprocessor.h"
     25 #include "clang/Sema/Initialization.h"
     26 #include "clang/Sema/SemaInternal.h"
     27 #include "llvm/ADT/SmallVector.h"
     28 #include <set>
     29 using namespace clang;
     30 
     31 
     32 
     33 enum TryCastResult {
     34   TC_NotApplicable, ///< The cast method is not applicable.
     35   TC_Success,       ///< The cast method is appropriate and successful.
     36   TC_Extension,     ///< The cast method is appropriate and accepted as a
     37                     ///< language extension.
     38   TC_Failed         ///< The cast method is appropriate, but failed. A
     39                     ///< diagnostic has been emitted.
     40 };
     41 
     42 static bool isValidCast(TryCastResult TCR) {
     43   return TCR == TC_Success || TCR == TC_Extension;
     44 }
     45 
     46 enum CastType {
     47   CT_Const,       ///< const_cast
     48   CT_Static,      ///< static_cast
     49   CT_Reinterpret, ///< reinterpret_cast
     50   CT_Dynamic,     ///< dynamic_cast
     51   CT_CStyle,      ///< (Type)expr
     52   CT_Functional,  ///< Type(expr)
     53   CT_Addrspace    ///< addrspace_cast
     54 };
     55 
     56 namespace {
     57   struct CastOperation {
     58     CastOperation(Sema &S, QualType destType, ExprResult src)
     59       : Self(S), SrcExpr(src), DestType(destType),
     60         ResultType(destType.getNonLValueExprType(S.Context)),
     61         ValueKind(Expr::getValueKindForType(destType)),
     62         Kind(CK_Dependent), IsARCUnbridgedCast(false) {
     63 
     64       if (const BuiltinType *placeholder =
     65             src.get()->getType()->getAsPlaceholderType()) {
     66         PlaceholderKind = placeholder->getKind();
     67       } else {
     68         PlaceholderKind = (BuiltinType::Kind) 0;
     69       }
     70     }
     71 
     72     Sema &Self;
     73     ExprResult SrcExpr;
     74     QualType DestType;
     75     QualType ResultType;
     76     ExprValueKind ValueKind;
     77     CastKind Kind;
     78     BuiltinType::Kind PlaceholderKind;
     79     CXXCastPath BasePath;
     80     bool IsARCUnbridgedCast;
     81 
     82     SourceRange OpRange;
     83     SourceRange DestRange;
     84 
     85     // Top-level semantics-checking routines.
     86     void CheckConstCast();
     87     void CheckReinterpretCast();
     88     void CheckStaticCast();
     89     void CheckDynamicCast();
     90     void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
     91     void CheckCStyleCast();
     92     void CheckBuiltinBitCast();
     93     void CheckAddrspaceCast();
     94 
     95     void updatePartOfExplicitCastFlags(CastExpr *CE) {
     96       // Walk down from the CE to the OrigSrcExpr, and mark all immediate
     97       // ImplicitCastExpr's as being part of ExplicitCastExpr. The original CE
     98       // (which is a ExplicitCastExpr), and the OrigSrcExpr are not touched.
     99       for (; auto *ICE = dyn_cast<ImplicitCastExpr>(CE->getSubExpr()); CE = ICE)
    100         ICE->setIsPartOfExplicitCast(true);
    101     }
    102 
    103     /// Complete an apparently-successful cast operation that yields
    104     /// the given expression.
    105     ExprResult complete(CastExpr *castExpr) {
    106       // If this is an unbridged cast, wrap the result in an implicit
    107       // cast that yields the unbridged-cast placeholder type.
    108       if (IsARCUnbridgedCast) {
    109         castExpr = ImplicitCastExpr::Create(
    110             Self.Context, Self.Context.ARCUnbridgedCastTy, CK_Dependent,
    111             castExpr, nullptr, castExpr->getValueKind(),
    112             Self.CurFPFeatureOverrides());
    113       }
    114       updatePartOfExplicitCastFlags(castExpr);
    115       return castExpr;
    116     }
    117 
    118     // Internal convenience methods.
    119 
    120     /// Try to handle the given placeholder expression kind.  Return
    121     /// true if the source expression has the appropriate placeholder
    122     /// kind.  A placeholder can only be claimed once.
    123     bool claimPlaceholder(BuiltinType::Kind K) {
    124       if (PlaceholderKind != K) return false;
    125 
    126       PlaceholderKind = (BuiltinType::Kind) 0;
    127       return true;
    128     }
    129 
    130     bool isPlaceholder() const {
    131       return PlaceholderKind != 0;
    132     }
    133     bool isPlaceholder(BuiltinType::Kind K) const {
    134       return PlaceholderKind == K;
    135     }
    136 
    137     // Language specific cast restrictions for address spaces.
    138     void checkAddressSpaceCast(QualType SrcType, QualType DestType);
    139 
    140     void checkCastAlign() {
    141       Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
    142     }
    143 
    144     void checkObjCConversion(Sema::CheckedConversionKind CCK) {
    145       assert(Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers());
    146 
    147       Expr *src = SrcExpr.get();
    148       if (Self.CheckObjCConversion(OpRange, DestType, src, CCK) ==
    149           Sema::ACR_unbridged)
    150         IsARCUnbridgedCast = true;
    151       SrcExpr = src;
    152     }
    153 
    154     /// Check for and handle non-overload placeholder expressions.
    155     void checkNonOverloadPlaceholders() {
    156       if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
    157         return;
    158 
    159       SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
    160       if (SrcExpr.isInvalid())
    161         return;
    162       PlaceholderKind = (BuiltinType::Kind) 0;
    163     }
    164   };
    165 
    166   void CheckNoDeref(Sema &S, const QualType FromType, const QualType ToType,
    167                     SourceLocation OpLoc) {
    168     if (const auto *PtrType = dyn_cast<PointerType>(FromType)) {
    169       if (PtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
    170         if (const auto *DestType = dyn_cast<PointerType>(ToType)) {
    171           if (!DestType->getPointeeType()->hasAttr(attr::NoDeref)) {
    172             S.Diag(OpLoc, diag::warn_noderef_to_dereferenceable_pointer);
    173           }
    174         }
    175       }
    176     }
    177   }
    178 
    179   struct CheckNoDerefRAII {
    180     CheckNoDerefRAII(CastOperation &Op) : Op(Op) {}
    181     ~CheckNoDerefRAII() {
    182       if (!Op.SrcExpr.isInvalid())
    183         CheckNoDeref(Op.Self, Op.SrcExpr.get()->getType(), Op.ResultType,
    184                      Op.OpRange.getBegin());
    185     }
    186 
    187     CastOperation &Op;
    188   };
    189 }
    190 
    191 static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
    192                              QualType DestType);
    193 
    194 // The Try functions attempt a specific way of casting. If they succeed, they
    195 // return TC_Success. If their way of casting is not appropriate for the given
    196 // arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
    197 // to emit if no other way succeeds. If their way of casting is appropriate but
    198 // fails, they return TC_Failed and *must* set diag; they can set it to 0 if
    199 // they emit a specialized diagnostic.
    200 // All diagnostics returned by these functions must expect the same three
    201 // arguments:
    202 // %0: Cast Type (a value from the CastType enumeration)
    203 // %1: Source Type
    204 // %2: Destination Type
    205 static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
    206                                            QualType DestType, bool CStyle,
    207                                            CastKind &Kind,
    208                                            CXXCastPath &BasePath,
    209                                            unsigned &msg);
    210 static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
    211                                                QualType DestType, bool CStyle,
    212                                                SourceRange OpRange,
    213                                                unsigned &msg,
    214                                                CastKind &Kind,
    215                                                CXXCastPath &BasePath);
    216 static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
    217                                               QualType DestType, bool CStyle,
    218                                               SourceRange OpRange,
    219                                               unsigned &msg,
    220                                               CastKind &Kind,
    221                                               CXXCastPath &BasePath);
    222 static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
    223                                        CanQualType DestType, bool CStyle,
    224                                        SourceRange OpRange,
    225                                        QualType OrigSrcType,
    226                                        QualType OrigDestType, unsigned &msg,
    227                                        CastKind &Kind,
    228                                        CXXCastPath &BasePath);
    229 static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
    230                                                QualType SrcType,
    231                                                QualType DestType,bool CStyle,
    232                                                SourceRange OpRange,
    233                                                unsigned &msg,
    234                                                CastKind &Kind,
    235                                                CXXCastPath &BasePath);
    236 
    237 static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
    238                                            QualType DestType,
    239                                            Sema::CheckedConversionKind CCK,
    240                                            SourceRange OpRange,
    241                                            unsigned &msg, CastKind &Kind,
    242                                            bool ListInitialization);
    243 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
    244                                    QualType DestType,
    245                                    Sema::CheckedConversionKind CCK,
    246                                    SourceRange OpRange,
    247                                    unsigned &msg, CastKind &Kind,
    248                                    CXXCastPath &BasePath,
    249                                    bool ListInitialization);
    250 static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
    251                                   QualType DestType, bool CStyle,
    252                                   unsigned &msg);
    253 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
    254                                         QualType DestType, bool CStyle,
    255                                         SourceRange OpRange, unsigned &msg,
    256                                         CastKind &Kind);
    257 static TryCastResult TryAddressSpaceCast(Sema &Self, ExprResult &SrcExpr,
    258                                          QualType DestType, bool CStyle,
    259                                          unsigned &msg, CastKind &Kind);
    260 
    261 /// ActOnCXXNamedCast - Parse
    262 /// {dynamic,static,reinterpret,const,addrspace}_cast's.
    263 ExprResult
    264 Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
    265                         SourceLocation LAngleBracketLoc, Declarator &D,
    266                         SourceLocation RAngleBracketLoc,
    267                         SourceLocation LParenLoc, Expr *E,
    268                         SourceLocation RParenLoc) {
    269 
    270   assert(!D.isInvalidType());
    271 
    272   TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
    273   if (D.isInvalidType())
    274     return ExprError();
    275 
    276   if (getLangOpts().CPlusPlus) {
    277     // Check that there are no default arguments (C++ only).
    278     CheckExtraCXXDefaultArguments(D);
    279   }
    280 
    281   return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
    282                            SourceRange(LAngleBracketLoc, RAngleBracketLoc),
    283                            SourceRange(LParenLoc, RParenLoc));
    284 }
    285 
    286 ExprResult
    287 Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
    288                         TypeSourceInfo *DestTInfo, Expr *E,
    289                         SourceRange AngleBrackets, SourceRange Parens) {
    290   ExprResult Ex = E;
    291   QualType DestType = DestTInfo->getType();
    292 
    293   // If the type is dependent, we won't do the semantic analysis now.
    294   bool TypeDependent =
    295       DestType->isDependentType() || Ex.get()->isTypeDependent();
    296 
    297   CastOperation Op(*this, DestType, E);
    298   Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
    299   Op.DestRange = AngleBrackets;
    300 
    301   switch (Kind) {
    302   default: llvm_unreachable("Unknown C++ cast!");
    303 
    304   case tok::kw_addrspace_cast:
    305     if (!TypeDependent) {
    306       Op.CheckAddrspaceCast();
    307       if (Op.SrcExpr.isInvalid())
    308         return ExprError();
    309     }
    310     return Op.complete(CXXAddrspaceCastExpr::Create(
    311         Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
    312         DestTInfo, OpLoc, Parens.getEnd(), AngleBrackets));
    313 
    314   case tok::kw_const_cast:
    315     if (!TypeDependent) {
    316       Op.CheckConstCast();
    317       if (Op.SrcExpr.isInvalid())
    318         return ExprError();
    319       DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
    320     }
    321     return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
    322                                   Op.ValueKind, Op.SrcExpr.get(), DestTInfo,
    323                                                 OpLoc, Parens.getEnd(),
    324                                                 AngleBrackets));
    325 
    326   case tok::kw_dynamic_cast: {
    327     // dynamic_cast is not supported in C++ for OpenCL.
    328     if (getLangOpts().OpenCLCPlusPlus) {
    329       return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
    330                        << "dynamic_cast");
    331     }
    332 
    333     if (!TypeDependent) {
    334       Op.CheckDynamicCast();
    335       if (Op.SrcExpr.isInvalid())
    336         return ExprError();
    337     }
    338     return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
    339                                     Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
    340                                                   &Op.BasePath, DestTInfo,
    341                                                   OpLoc, Parens.getEnd(),
    342                                                   AngleBrackets));
    343   }
    344   case tok::kw_reinterpret_cast: {
    345     if (!TypeDependent) {
    346       Op.CheckReinterpretCast();
    347       if (Op.SrcExpr.isInvalid())
    348         return ExprError();
    349       DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
    350     }
    351     return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
    352                                     Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
    353                                                       nullptr, DestTInfo, OpLoc,
    354                                                       Parens.getEnd(),
    355                                                       AngleBrackets));
    356   }
    357   case tok::kw_static_cast: {
    358     if (!TypeDependent) {
    359       Op.CheckStaticCast();
    360       if (Op.SrcExpr.isInvalid())
    361         return ExprError();
    362       DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
    363     }
    364 
    365     return Op.complete(CXXStaticCastExpr::Create(
    366         Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
    367         &Op.BasePath, DestTInfo, CurFPFeatureOverrides(), OpLoc,
    368         Parens.getEnd(), AngleBrackets));
    369   }
    370   }
    371 }
    372 
    373 ExprResult Sema::ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &D,
    374                                          ExprResult Operand,
    375                                          SourceLocation RParenLoc) {
    376   assert(!D.isInvalidType());
    377 
    378   TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, Operand.get()->getType());
    379   if (D.isInvalidType())
    380     return ExprError();
    381 
    382   return BuildBuiltinBitCastExpr(KWLoc, TInfo, Operand.get(), RParenLoc);
    383 }
    384 
    385 ExprResult Sema::BuildBuiltinBitCastExpr(SourceLocation KWLoc,
    386                                          TypeSourceInfo *TSI, Expr *Operand,
    387                                          SourceLocation RParenLoc) {
    388   CastOperation Op(*this, TSI->getType(), Operand);
    389   Op.OpRange = SourceRange(KWLoc, RParenLoc);
    390   TypeLoc TL = TSI->getTypeLoc();
    391   Op.DestRange = SourceRange(TL.getBeginLoc(), TL.getEndLoc());
    392 
    393   if (!Operand->isTypeDependent() && !TSI->getType()->isDependentType()) {
    394     Op.CheckBuiltinBitCast();
    395     if (Op.SrcExpr.isInvalid())
    396       return ExprError();
    397   }
    398 
    399   BuiltinBitCastExpr *BCE =
    400       new (Context) BuiltinBitCastExpr(Op.ResultType, Op.ValueKind, Op.Kind,
    401                                        Op.SrcExpr.get(), TSI, KWLoc, RParenLoc);
    402   return Op.complete(BCE);
    403 }
    404 
    405 /// Try to diagnose a failed overloaded cast.  Returns true if
    406 /// diagnostics were emitted.
    407 static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
    408                                       SourceRange range, Expr *src,
    409                                       QualType destType,
    410                                       bool listInitialization) {
    411   switch (CT) {
    412   // These cast kinds don't consider user-defined conversions.
    413   case CT_Const:
    414   case CT_Reinterpret:
    415   case CT_Dynamic:
    416   case CT_Addrspace:
    417     return false;
    418 
    419   // These do.
    420   case CT_Static:
    421   case CT_CStyle:
    422   case CT_Functional:
    423     break;
    424   }
    425 
    426   QualType srcType = src->getType();
    427   if (!destType->isRecordType() && !srcType->isRecordType())
    428     return false;
    429 
    430   InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
    431   InitializationKind initKind
    432     = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
    433                                                       range, listInitialization)
    434     : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
    435                                                              listInitialization)
    436     : InitializationKind::CreateCast(/*type range?*/ range);
    437   InitializationSequence sequence(S, entity, initKind, src);
    438 
    439   assert(sequence.Failed() && "initialization succeeded on second try?");
    440   switch (sequence.getFailureKind()) {
    441   default: return false;
    442 
    443   case InitializationSequence::FK_ConstructorOverloadFailed:
    444   case InitializationSequence::FK_UserConversionOverloadFailed:
    445     break;
    446   }
    447 
    448   OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
    449 
    450   unsigned msg = 0;
    451   OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
    452 
    453   switch (sequence.getFailedOverloadResult()) {
    454   case OR_Success: llvm_unreachable("successful failed overload");
    455   case OR_No_Viable_Function:
    456     if (candidates.empty())
    457       msg = diag::err_ovl_no_conversion_in_cast;
    458     else
    459       msg = diag::err_ovl_no_viable_conversion_in_cast;
    460     howManyCandidates = OCD_AllCandidates;
    461     break;
    462 
    463   case OR_Ambiguous:
    464     msg = diag::err_ovl_ambiguous_conversion_in_cast;
    465     howManyCandidates = OCD_AmbiguousCandidates;
    466     break;
    467 
    468   case OR_Deleted:
    469     msg = diag::err_ovl_deleted_conversion_in_cast;
    470     howManyCandidates = OCD_ViableCandidates;
    471     break;
    472   }
    473 
    474   candidates.NoteCandidates(
    475       PartialDiagnosticAt(range.getBegin(),
    476                           S.PDiag(msg) << CT << srcType << destType << range
    477                                        << src->getSourceRange()),
    478       S, howManyCandidates, src);
    479 
    480   return true;
    481 }
    482 
    483 /// Diagnose a failed cast.
    484 static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
    485                             SourceRange opRange, Expr *src, QualType destType,
    486                             bool listInitialization) {
    487   if (msg == diag::err_bad_cxx_cast_generic &&
    488       tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
    489                                 listInitialization))
    490     return;
    491 
    492   S.Diag(opRange.getBegin(), msg) << castType
    493     << src->getType() << destType << opRange << src->getSourceRange();
    494 
    495   // Detect if both types are (ptr to) class, and note any incompleteness.
    496   int DifferentPtrness = 0;
    497   QualType From = destType;
    498   if (auto Ptr = From->getAs<PointerType>()) {
    499     From = Ptr->getPointeeType();
    500     DifferentPtrness++;
    501   }
    502   QualType To = src->getType();
    503   if (auto Ptr = To->getAs<PointerType>()) {
    504     To = Ptr->getPointeeType();
    505     DifferentPtrness--;
    506   }
    507   if (!DifferentPtrness) {
    508     auto RecFrom = From->getAs<RecordType>();
    509     auto RecTo = To->getAs<RecordType>();
    510     if (RecFrom && RecTo) {
    511       auto DeclFrom = RecFrom->getAsCXXRecordDecl();
    512       if (!DeclFrom->isCompleteDefinition())
    513         S.Diag(DeclFrom->getLocation(), diag::note_type_incomplete) << DeclFrom;
    514       auto DeclTo = RecTo->getAsCXXRecordDecl();
    515       if (!DeclTo->isCompleteDefinition())
    516         S.Diag(DeclTo->getLocation(), diag::note_type_incomplete) << DeclTo;
    517     }
    518   }
    519 }
    520 
    521 namespace {
    522 /// The kind of unwrapping we did when determining whether a conversion casts
    523 /// away constness.
    524 enum CastAwayConstnessKind {
    525   /// The conversion does not cast away constness.
    526   CACK_None = 0,
    527   /// We unwrapped similar types.
    528   CACK_Similar = 1,
    529   /// We unwrapped dissimilar types with similar representations (eg, a pointer
    530   /// versus an Objective-C object pointer).
    531   CACK_SimilarKind = 2,
    532   /// We unwrapped representationally-unrelated types, such as a pointer versus
    533   /// a pointer-to-member.
    534   CACK_Incoherent = 3,
    535 };
    536 }
    537 
    538 /// Unwrap one level of types for CastsAwayConstness.
    539 ///
    540 /// Like Sema::UnwrapSimilarTypes, this removes one level of indirection from
    541 /// both types, provided that they're both pointer-like or array-like. Unlike
    542 /// the Sema function, doesn't care if the unwrapped pieces are related.
    543 ///
    544 /// This function may remove additional levels as necessary for correctness:
    545 /// the resulting T1 is unwrapped sufficiently that it is never an array type,
    546 /// so that its qualifiers can be directly compared to those of T2 (which will
    547 /// have the combined set of qualifiers from all indermediate levels of T2),
    548 /// as (effectively) required by [expr.const.cast]p7 replacing T1's qualifiers
    549 /// with those from T2.
    550 static CastAwayConstnessKind
    551 unwrapCastAwayConstnessLevel(ASTContext &Context, QualType &T1, QualType &T2) {
    552   enum { None, Ptr, MemPtr, BlockPtr, Array };
    553   auto Classify = [](QualType T) {
    554     if (T->isAnyPointerType()) return Ptr;
    555     if (T->isMemberPointerType()) return MemPtr;
    556     if (T->isBlockPointerType()) return BlockPtr;
    557     // We somewhat-arbitrarily don't look through VLA types here. This is at
    558     // least consistent with the behavior of UnwrapSimilarTypes.
    559     if (T->isConstantArrayType() || T->isIncompleteArrayType()) return Array;
    560     return None;
    561   };
    562 
    563   auto Unwrap = [&](QualType T) {
    564     if (auto *AT = Context.getAsArrayType(T))
    565       return AT->getElementType();
    566     return T->getPointeeType();
    567   };
    568 
    569   CastAwayConstnessKind Kind;
    570 
    571   if (T2->isReferenceType()) {
    572     // Special case: if the destination type is a reference type, unwrap it as
    573     // the first level. (The source will have been an lvalue expression in this
    574     // case, so there is no corresponding "reference to" in T1 to remove.) This
    575     // simulates removing a "pointer to" from both sides.
    576     T2 = T2->getPointeeType();
    577     Kind = CastAwayConstnessKind::CACK_Similar;
    578   } else if (Context.UnwrapSimilarTypes(T1, T2)) {
    579     Kind = CastAwayConstnessKind::CACK_Similar;
    580   } else {
    581     // Try unwrapping mismatching levels.
    582     int T1Class = Classify(T1);
    583     if (T1Class == None)
    584       return CastAwayConstnessKind::CACK_None;
    585 
    586     int T2Class = Classify(T2);
    587     if (T2Class == None)
    588       return CastAwayConstnessKind::CACK_None;
    589 
    590     T1 = Unwrap(T1);
    591     T2 = Unwrap(T2);
    592     Kind = T1Class == T2Class ? CastAwayConstnessKind::CACK_SimilarKind
    593                               : CastAwayConstnessKind::CACK_Incoherent;
    594   }
    595 
    596   // We've unwrapped at least one level. If the resulting T1 is a (possibly
    597   // multidimensional) array type, any qualifier on any matching layer of
    598   // T2 is considered to correspond to T1. Decompose down to the element
    599   // type of T1 so that we can compare properly.
    600   while (true) {
    601     Context.UnwrapSimilarArrayTypes(T1, T2);
    602 
    603     if (Classify(T1) != Array)
    604       break;
    605 
    606     auto T2Class = Classify(T2);
    607     if (T2Class == None)
    608       break;
    609 
    610     if (T2Class != Array)
    611       Kind = CastAwayConstnessKind::CACK_Incoherent;
    612     else if (Kind != CastAwayConstnessKind::CACK_Incoherent)
    613       Kind = CastAwayConstnessKind::CACK_SimilarKind;
    614 
    615     T1 = Unwrap(T1);
    616     T2 = Unwrap(T2).withCVRQualifiers(T2.getCVRQualifiers());
    617   }
    618 
    619   return Kind;
    620 }
    621 
    622 /// Check if the pointer conversion from SrcType to DestType casts away
    623 /// constness as defined in C++ [expr.const.cast]. This is used by the cast
    624 /// checkers. Both arguments must denote pointer (possibly to member) types.
    625 ///
    626 /// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
    627 /// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
    628 static CastAwayConstnessKind
    629 CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
    630                    bool CheckCVR, bool CheckObjCLifetime,
    631                    QualType *TheOffendingSrcType = nullptr,
    632                    QualType *TheOffendingDestType = nullptr,
    633                    Qualifiers *CastAwayQualifiers = nullptr) {
    634   // If the only checking we care about is for Objective-C lifetime qualifiers,
    635   // and we're not in ObjC mode, there's nothing to check.
    636   if (!CheckCVR && CheckObjCLifetime && !Self.Context.getLangOpts().ObjC)
    637     return CastAwayConstnessKind::CACK_None;
    638 
    639   if (!DestType->isReferenceType()) {
    640     assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
    641             SrcType->isBlockPointerType()) &&
    642            "Source type is not pointer or pointer to member.");
    643     assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
    644             DestType->isBlockPointerType()) &&
    645            "Destination type is not pointer or pointer to member.");
    646   }
    647 
    648   QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
    649            UnwrappedDestType = Self.Context.getCanonicalType(DestType);
    650 
    651   // Find the qualifiers. We only care about cvr-qualifiers for the
    652   // purpose of this check, because other qualifiers (address spaces,
    653   // Objective-C GC, etc.) are part of the type's identity.
    654   QualType PrevUnwrappedSrcType = UnwrappedSrcType;
    655   QualType PrevUnwrappedDestType = UnwrappedDestType;
    656   auto WorstKind = CastAwayConstnessKind::CACK_Similar;
    657   bool AllConstSoFar = true;
    658   while (auto Kind = unwrapCastAwayConstnessLevel(
    659              Self.Context, UnwrappedSrcType, UnwrappedDestType)) {
    660     // Track the worst kind of unwrap we needed to do before we found a
    661     // problem.
    662     if (Kind > WorstKind)
    663       WorstKind = Kind;
    664 
    665     // Determine the relevant qualifiers at this level.
    666     Qualifiers SrcQuals, DestQuals;
    667     Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
    668     Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
    669 
    670     // We do not meaningfully track object const-ness of Objective-C object
    671     // types. Remove const from the source type if either the source or
    672     // the destination is an Objective-C object type.
    673     if (UnwrappedSrcType->isObjCObjectType() ||
    674         UnwrappedDestType->isObjCObjectType())
    675       SrcQuals.removeConst();
    676 
    677     if (CheckCVR) {
    678       Qualifiers SrcCvrQuals =
    679           Qualifiers::fromCVRMask(SrcQuals.getCVRQualifiers());
    680       Qualifiers DestCvrQuals =
    681           Qualifiers::fromCVRMask(DestQuals.getCVRQualifiers());
    682 
    683       if (SrcCvrQuals != DestCvrQuals) {
    684         if (CastAwayQualifiers)
    685           *CastAwayQualifiers = SrcCvrQuals - DestCvrQuals;
    686 
    687         // If we removed a cvr-qualifier, this is casting away 'constness'.
    688         if (!DestCvrQuals.compatiblyIncludes(SrcCvrQuals)) {
    689           if (TheOffendingSrcType)
    690             *TheOffendingSrcType = PrevUnwrappedSrcType;
    691           if (TheOffendingDestType)
    692             *TheOffendingDestType = PrevUnwrappedDestType;
    693           return WorstKind;
    694         }
    695 
    696         // If any prior level was not 'const', this is also casting away
    697         // 'constness'. We noted the outermost type missing a 'const' already.
    698         if (!AllConstSoFar)
    699           return WorstKind;
    700       }
    701     }
    702 
    703     if (CheckObjCLifetime &&
    704         !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
    705       return WorstKind;
    706 
    707     // If we found our first non-const-qualified type, this may be the place
    708     // where things start to go wrong.
    709     if (AllConstSoFar && !DestQuals.hasConst()) {
    710       AllConstSoFar = false;
    711       if (TheOffendingSrcType)
    712         *TheOffendingSrcType = PrevUnwrappedSrcType;
    713       if (TheOffendingDestType)
    714         *TheOffendingDestType = PrevUnwrappedDestType;
    715     }
    716 
    717     PrevUnwrappedSrcType = UnwrappedSrcType;
    718     PrevUnwrappedDestType = UnwrappedDestType;
    719   }
    720 
    721   return CastAwayConstnessKind::CACK_None;
    722 }
    723 
    724 static TryCastResult getCastAwayConstnessCastKind(CastAwayConstnessKind CACK,
    725                                                   unsigned &DiagID) {
    726   switch (CACK) {
    727   case CastAwayConstnessKind::CACK_None:
    728     llvm_unreachable("did not cast away constness");
    729 
    730   case CastAwayConstnessKind::CACK_Similar:
    731     // FIXME: Accept these as an extension too?
    732   case CastAwayConstnessKind::CACK_SimilarKind:
    733     DiagID = diag::err_bad_cxx_cast_qualifiers_away;
    734     return TC_Failed;
    735 
    736   case CastAwayConstnessKind::CACK_Incoherent:
    737     DiagID = diag::ext_bad_cxx_cast_qualifiers_away_incoherent;
    738     return TC_Extension;
    739   }
    740 
    741   llvm_unreachable("unexpected cast away constness kind");
    742 }
    743 
    744 /// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
    745 /// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
    746 /// checked downcasts in class hierarchies.
    747 void CastOperation::CheckDynamicCast() {
    748   CheckNoDerefRAII NoderefCheck(*this);
    749 
    750   if (ValueKind == VK_RValue)
    751     SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
    752   else if (isPlaceholder())
    753     SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
    754   if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
    755     return;
    756 
    757   QualType OrigSrcType = SrcExpr.get()->getType();
    758   QualType DestType = Self.Context.getCanonicalType(this->DestType);
    759 
    760   // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
    761   //   or "pointer to cv void".
    762 
    763   QualType DestPointee;
    764   const PointerType *DestPointer = DestType->getAs<PointerType>();
    765   const ReferenceType *DestReference = nullptr;
    766   if (DestPointer) {
    767     DestPointee = DestPointer->getPointeeType();
    768   } else if ((DestReference = DestType->getAs<ReferenceType>())) {
    769     DestPointee = DestReference->getPointeeType();
    770   } else {
    771     Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
    772       << this->DestType << DestRange;
    773     SrcExpr = ExprError();
    774     return;
    775   }
    776 
    777   const RecordType *DestRecord = DestPointee->getAs<RecordType>();
    778   if (DestPointee->isVoidType()) {
    779     assert(DestPointer && "Reference to void is not possible");
    780   } else if (DestRecord) {
    781     if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
    782                                  diag::err_bad_cast_incomplete,
    783                                  DestRange)) {
    784       SrcExpr = ExprError();
    785       return;
    786     }
    787   } else {
    788     Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
    789       << DestPointee.getUnqualifiedType() << DestRange;
    790     SrcExpr = ExprError();
    791     return;
    792   }
    793 
    794   // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
    795   //   complete class type, [...]. If T is an lvalue reference type, v shall be
    796   //   an lvalue of a complete class type, [...]. If T is an rvalue reference
    797   //   type, v shall be an expression having a complete class type, [...]
    798   QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
    799   QualType SrcPointee;
    800   if (DestPointer) {
    801     if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
    802       SrcPointee = SrcPointer->getPointeeType();
    803     } else {
    804       Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
    805           << OrigSrcType << this->DestType << SrcExpr.get()->getSourceRange();
    806       SrcExpr = ExprError();
    807       return;
    808     }
    809   } else if (DestReference->isLValueReferenceType()) {
    810     if (!SrcExpr.get()->isLValue()) {
    811       Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
    812         << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
    813     }
    814     SrcPointee = SrcType;
    815   } else {
    816     // If we're dynamic_casting from a prvalue to an rvalue reference, we need
    817     // to materialize the prvalue before we bind the reference to it.
    818     if (SrcExpr.get()->isRValue())
    819       SrcExpr = Self.CreateMaterializeTemporaryExpr(
    820           SrcType, SrcExpr.get(), /*IsLValueReference*/ false);
    821     SrcPointee = SrcType;
    822   }
    823 
    824   const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
    825   if (SrcRecord) {
    826     if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
    827                                  diag::err_bad_cast_incomplete,
    828                                  SrcExpr.get())) {
    829       SrcExpr = ExprError();
    830       return;
    831     }
    832   } else {
    833     Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
    834       << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
    835     SrcExpr = ExprError();
    836     return;
    837   }
    838 
    839   assert((DestPointer || DestReference) &&
    840     "Bad destination non-ptr/ref slipped through.");
    841   assert((DestRecord || DestPointee->isVoidType()) &&
    842     "Bad destination pointee slipped through.");
    843   assert(SrcRecord && "Bad source pointee slipped through.");
    844 
    845   // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
    846   if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
    847     Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
    848       << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
    849     SrcExpr = ExprError();
    850     return;
    851   }
    852 
    853   // C++ 5.2.7p3: If the type of v is the same as the required result type,
    854   //   [except for cv].
    855   if (DestRecord == SrcRecord) {
    856     Kind = CK_NoOp;
    857     return;
    858   }
    859 
    860   // C++ 5.2.7p5
    861   // Upcasts are resolved statically.
    862   if (DestRecord &&
    863       Self.IsDerivedFrom(OpRange.getBegin(), SrcPointee, DestPointee)) {
    864     if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
    865                                            OpRange.getBegin(), OpRange,
    866                                            &BasePath)) {
    867       SrcExpr = ExprError();
    868       return;
    869     }
    870 
    871     Kind = CK_DerivedToBase;
    872     return;
    873   }
    874 
    875   // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
    876   const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
    877   assert(SrcDecl && "Definition missing");
    878   if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
    879     Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
    880       << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
    881     SrcExpr = ExprError();
    882   }
    883 
    884   // dynamic_cast is not available with -fno-rtti.
    885   // As an exception, dynamic_cast to void* is available because it doesn't
    886   // use RTTI.
    887   if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) {
    888     Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti);
    889     SrcExpr = ExprError();
    890     return;
    891   }
    892 
    893   // Warns when dynamic_cast is used with RTTI data disabled.
    894   if (!Self.getLangOpts().RTTIData) {
    895     bool MicrosoftABI =
    896         Self.getASTContext().getTargetInfo().getCXXABI().isMicrosoft();
    897     bool isClangCL = Self.getDiagnostics().getDiagnosticOptions().getFormat() ==
    898                      DiagnosticOptions::MSVC;
    899     if (MicrosoftABI || !DestPointee->isVoidType())
    900       Self.Diag(OpRange.getBegin(),
    901                 diag::warn_no_dynamic_cast_with_rtti_disabled)
    902           << isClangCL;
    903   }
    904 
    905   // Done. Everything else is run-time checks.
    906   Kind = CK_Dynamic;
    907 }
    908 
    909 /// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
    910 /// Refer to C++ 5.2.11 for details. const_cast is typically used in code
    911 /// like this:
    912 /// const char *str = "literal";
    913 /// legacy_function(const_cast\<char*\>(str));
    914 void CastOperation::CheckConstCast() {
    915   CheckNoDerefRAII NoderefCheck(*this);
    916 
    917   if (ValueKind == VK_RValue)
    918     SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
    919   else if (isPlaceholder())
    920     SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
    921   if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
    922     return;
    923 
    924   unsigned msg = diag::err_bad_cxx_cast_generic;
    925   auto TCR = TryConstCast(Self, SrcExpr, DestType, /*CStyle*/ false, msg);
    926   if (TCR != TC_Success && msg != 0) {
    927     Self.Diag(OpRange.getBegin(), msg) << CT_Const
    928       << SrcExpr.get()->getType() << DestType << OpRange;
    929   }
    930   if (!isValidCast(TCR))
    931     SrcExpr = ExprError();
    932 }
    933 
    934 void CastOperation::CheckAddrspaceCast() {
    935   unsigned msg = diag::err_bad_cxx_cast_generic;
    936   auto TCR =
    937       TryAddressSpaceCast(Self, SrcExpr, DestType, /*CStyle*/ false, msg, Kind);
    938   if (TCR != TC_Success && msg != 0) {
    939     Self.Diag(OpRange.getBegin(), msg)
    940         << CT_Addrspace << SrcExpr.get()->getType() << DestType << OpRange;
    941   }
    942   if (!isValidCast(TCR))
    943     SrcExpr = ExprError();
    944 }
    945 
    946 /// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
    947 /// or downcast between respective pointers or references.
    948 static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
    949                                           QualType DestType,
    950                                           SourceRange OpRange) {
    951   QualType SrcType = SrcExpr->getType();
    952   // When casting from pointer or reference, get pointee type; use original
    953   // type otherwise.
    954   const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
    955   const CXXRecordDecl *SrcRD =
    956     SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
    957 
    958   // Examining subobjects for records is only possible if the complete and
    959   // valid definition is available.  Also, template instantiation is not
    960   // allowed here.
    961   if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
    962     return;
    963 
    964   const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
    965 
    966   if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
    967     return;
    968 
    969   enum {
    970     ReinterpretUpcast,
    971     ReinterpretDowncast
    972   } ReinterpretKind;
    973 
    974   CXXBasePaths BasePaths;
    975 
    976   if (SrcRD->isDerivedFrom(DestRD, BasePaths))
    977     ReinterpretKind = ReinterpretUpcast;
    978   else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
    979     ReinterpretKind = ReinterpretDowncast;
    980   else
    981     return;
    982 
    983   bool VirtualBase = true;
    984   bool NonZeroOffset = false;
    985   for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
    986                                           E = BasePaths.end();
    987        I != E; ++I) {
    988     const CXXBasePath &Path = *I;
    989     CharUnits Offset = CharUnits::Zero();
    990     bool IsVirtual = false;
    991     for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
    992          IElem != EElem; ++IElem) {
    993       IsVirtual = IElem->Base->isVirtual();
    994       if (IsVirtual)
    995         break;
    996       const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
    997       assert(BaseRD && "Base type should be a valid unqualified class type");
    998       // Don't check if any base has invalid declaration or has no definition
    999       // since it has no layout info.
   1000       const CXXRecordDecl *Class = IElem->Class,
   1001                           *ClassDefinition = Class->getDefinition();
   1002       if (Class->isInvalidDecl() || !ClassDefinition ||
   1003           !ClassDefinition->isCompleteDefinition())
   1004         return;
   1005 
   1006       const ASTRecordLayout &DerivedLayout =
   1007           Self.Context.getASTRecordLayout(Class);
   1008       Offset += DerivedLayout.getBaseClassOffset(BaseRD);
   1009     }
   1010     if (!IsVirtual) {
   1011       // Don't warn if any path is a non-virtually derived base at offset zero.
   1012       if (Offset.isZero())
   1013         return;
   1014       // Offset makes sense only for non-virtual bases.
   1015       else
   1016         NonZeroOffset = true;
   1017     }
   1018     VirtualBase = VirtualBase && IsVirtual;
   1019   }
   1020 
   1021   (void) NonZeroOffset; // Silence set but not used warning.
   1022   assert((VirtualBase || NonZeroOffset) &&
   1023          "Should have returned if has non-virtual base with zero offset");
   1024 
   1025   QualType BaseType =
   1026       ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
   1027   QualType DerivedType =
   1028       ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
   1029 
   1030   SourceLocation BeginLoc = OpRange.getBegin();
   1031   Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
   1032     << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind)
   1033     << OpRange;
   1034   Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
   1035     << int(ReinterpretKind)
   1036     << FixItHint::CreateReplacement(BeginLoc, "static_cast");
   1037 }
   1038 
   1039 static bool argTypeIsABIEquivalent(QualType SrcType, QualType DestType,
   1040                                    ASTContext &Context) {
   1041   if (SrcType->isPointerType() && DestType->isPointerType())
   1042     return true;
   1043 
   1044   // Allow integral type mismatch if their size are equal.
   1045   if (SrcType->isIntegralType(Context) && DestType->isIntegralType(Context))
   1046     if (Context.getTypeInfoInChars(SrcType).Width ==
   1047         Context.getTypeInfoInChars(DestType).Width)
   1048       return true;
   1049 
   1050   return Context.hasSameUnqualifiedType(SrcType, DestType);
   1051 }
   1052 
   1053 static bool checkCastFunctionType(Sema &Self, const ExprResult &SrcExpr,
   1054                                   QualType DestType) {
   1055   if (Self.Diags.isIgnored(diag::warn_cast_function_type,
   1056                            SrcExpr.get()->getExprLoc()))
   1057     return true;
   1058 
   1059   QualType SrcType = SrcExpr.get()->getType();
   1060   const FunctionType *SrcFTy = nullptr;
   1061   const FunctionType *DstFTy = nullptr;
   1062   if (((SrcType->isBlockPointerType() || SrcType->isFunctionPointerType()) &&
   1063        DestType->isFunctionPointerType()) ||
   1064       (SrcType->isMemberFunctionPointerType() &&
   1065        DestType->isMemberFunctionPointerType())) {
   1066     SrcFTy = SrcType->getPointeeType()->castAs<FunctionType>();
   1067     DstFTy = DestType->getPointeeType()->castAs<FunctionType>();
   1068   } else if (SrcType->isFunctionType() && DestType->isFunctionReferenceType()) {
   1069     SrcFTy = SrcType->castAs<FunctionType>();
   1070     DstFTy = DestType.getNonReferenceType()->castAs<FunctionType>();
   1071   } else {
   1072     return true;
   1073   }
   1074   assert(SrcFTy && DstFTy);
   1075 
   1076   auto IsVoidVoid = [](const FunctionType *T) {
   1077     if (!T->getReturnType()->isVoidType())
   1078       return false;
   1079     if (const auto *PT = T->getAs<FunctionProtoType>())
   1080       return !PT->isVariadic() && PT->getNumParams() == 0;
   1081     return false;
   1082   };
   1083 
   1084   // Skip if either function type is void(*)(void)
   1085   if (IsVoidVoid(SrcFTy) || IsVoidVoid(DstFTy))
   1086     return true;
   1087 
   1088   // Check return type.
   1089   if (!argTypeIsABIEquivalent(SrcFTy->getReturnType(), DstFTy->getReturnType(),
   1090                               Self.Context))
   1091     return false;
   1092 
   1093   // Check if either has unspecified number of parameters
   1094   if (SrcFTy->isFunctionNoProtoType() || DstFTy->isFunctionNoProtoType())
   1095     return true;
   1096 
   1097   // Check parameter types.
   1098 
   1099   const auto *SrcFPTy = cast<FunctionProtoType>(SrcFTy);
   1100   const auto *DstFPTy = cast<FunctionProtoType>(DstFTy);
   1101 
   1102   // In a cast involving function types with a variable argument list only the
   1103   // types of initial arguments that are provided are considered.
   1104   unsigned NumParams = SrcFPTy->getNumParams();
   1105   unsigned DstNumParams = DstFPTy->getNumParams();
   1106   if (NumParams > DstNumParams) {
   1107     if (!DstFPTy->isVariadic())
   1108       return false;
   1109     NumParams = DstNumParams;
   1110   } else if (NumParams < DstNumParams) {
   1111     if (!SrcFPTy->isVariadic())
   1112       return false;
   1113   }
   1114 
   1115   for (unsigned i = 0; i < NumParams; ++i)
   1116     if (!argTypeIsABIEquivalent(SrcFPTy->getParamType(i),
   1117                                 DstFPTy->getParamType(i), Self.Context))
   1118       return false;
   1119 
   1120   return true;
   1121 }
   1122 
   1123 /// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
   1124 /// valid.
   1125 /// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
   1126 /// like this:
   1127 /// char *bytes = reinterpret_cast\<char*\>(int_ptr);
   1128 void CastOperation::CheckReinterpretCast() {
   1129   if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
   1130     SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
   1131   else
   1132     checkNonOverloadPlaceholders();
   1133   if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
   1134     return;
   1135 
   1136   unsigned msg = diag::err_bad_cxx_cast_generic;
   1137   TryCastResult tcr =
   1138     TryReinterpretCast(Self, SrcExpr, DestType,
   1139                        /*CStyle*/false, OpRange, msg, Kind);
   1140   if (tcr != TC_Success && msg != 0) {
   1141     if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
   1142       return;
   1143     if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
   1144       //FIXME: &f<int>; is overloaded and resolvable
   1145       Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
   1146         << OverloadExpr::find(SrcExpr.get()).Expression->getName()
   1147         << DestType << OpRange;
   1148       Self.NoteAllOverloadCandidates(SrcExpr.get());
   1149 
   1150     } else {
   1151       diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
   1152                       DestType, /*listInitialization=*/false);
   1153     }
   1154   }
   1155 
   1156   if (isValidCast(tcr)) {
   1157     if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
   1158       checkObjCConversion(Sema::CCK_OtherCast);
   1159     DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
   1160 
   1161     if (!checkCastFunctionType(Self, SrcExpr, DestType))
   1162       Self.Diag(OpRange.getBegin(), diag::warn_cast_function_type)
   1163           << SrcExpr.get()->getType() << DestType << OpRange;
   1164   } else {
   1165     SrcExpr = ExprError();
   1166   }
   1167 }
   1168 
   1169 
   1170 /// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
   1171 /// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
   1172 /// implicit conversions explicit and getting rid of data loss warnings.
   1173 void CastOperation::CheckStaticCast() {
   1174   CheckNoDerefRAII NoderefCheck(*this);
   1175 
   1176   if (isPlaceholder()) {
   1177     checkNonOverloadPlaceholders();
   1178     if (SrcExpr.isInvalid())
   1179       return;
   1180   }
   1181 
   1182   if (DestType->getAs<MatrixType>() ||
   1183       SrcExpr.get()->getType()->getAs<MatrixType>()) {
   1184     if (Self.CheckMatrixCast(OpRange, DestType, SrcExpr.get()->getType(), Kind))
   1185       SrcExpr = ExprError();
   1186     return;
   1187   }
   1188 
   1189   // This test is outside everything else because it's the only case where
   1190   // a non-lvalue-reference target type does not lead to decay.
   1191   // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
   1192   if (DestType->isVoidType()) {
   1193     Kind = CK_ToVoid;
   1194 
   1195     if (claimPlaceholder(BuiltinType::Overload)) {
   1196       Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
   1197                 false, // Decay Function to ptr
   1198                 true, // Complain
   1199                 OpRange, DestType, diag::err_bad_static_cast_overload);
   1200       if (SrcExpr.isInvalid())
   1201         return;
   1202     }
   1203 
   1204     SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
   1205     return;
   1206   }
   1207 
   1208   if (ValueKind == VK_RValue && !DestType->isRecordType() &&
   1209       !isPlaceholder(BuiltinType::Overload)) {
   1210     SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
   1211     if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
   1212       return;
   1213   }
   1214 
   1215   unsigned msg = diag::err_bad_cxx_cast_generic;
   1216   TryCastResult tcr
   1217     = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
   1218                     Kind, BasePath, /*ListInitialization=*/false);
   1219   if (tcr != TC_Success && msg != 0) {
   1220     if (SrcExpr.isInvalid())
   1221       return;
   1222     if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
   1223       OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
   1224       Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
   1225         << oe->getName() << DestType << OpRange
   1226         << oe->getQualifierLoc().getSourceRange();
   1227       Self.NoteAllOverloadCandidates(SrcExpr.get());
   1228     } else {
   1229       diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
   1230                       /*listInitialization=*/false);
   1231     }
   1232   }
   1233 
   1234   if (isValidCast(tcr)) {
   1235     if (Kind == CK_BitCast)
   1236       checkCastAlign();
   1237     if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
   1238       checkObjCConversion(Sema::CCK_OtherCast);
   1239   } else {
   1240     SrcExpr = ExprError();
   1241   }
   1242 }
   1243 
   1244 static bool IsAddressSpaceConversion(QualType SrcType, QualType DestType) {
   1245   auto *SrcPtrType = SrcType->getAs<PointerType>();
   1246   if (!SrcPtrType)
   1247     return false;
   1248   auto *DestPtrType = DestType->getAs<PointerType>();
   1249   if (!DestPtrType)
   1250     return false;
   1251   return SrcPtrType->getPointeeType().getAddressSpace() !=
   1252          DestPtrType->getPointeeType().getAddressSpace();
   1253 }
   1254 
   1255 /// TryStaticCast - Check if a static cast can be performed, and do so if
   1256 /// possible. If @p CStyle, ignore access restrictions on hierarchy casting
   1257 /// and casting away constness.
   1258 static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
   1259                                    QualType DestType,
   1260                                    Sema::CheckedConversionKind CCK,
   1261                                    SourceRange OpRange, unsigned &msg,
   1262                                    CastKind &Kind, CXXCastPath &BasePath,
   1263                                    bool ListInitialization) {
   1264   // Determine whether we have the semantics of a C-style cast.
   1265   bool CStyle
   1266     = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
   1267 
   1268   // The order the tests is not entirely arbitrary. There is one conversion
   1269   // that can be handled in two different ways. Given:
   1270   // struct A {};
   1271   // struct B : public A {
   1272   //   B(); B(const A&);
   1273   // };
   1274   // const A &a = B();
   1275   // the cast static_cast<const B&>(a) could be seen as either a static
   1276   // reference downcast, or an explicit invocation of the user-defined
   1277   // conversion using B's conversion constructor.
   1278   // DR 427 specifies that the downcast is to be applied here.
   1279 
   1280   // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
   1281   // Done outside this function.
   1282 
   1283   TryCastResult tcr;
   1284 
   1285   // C++ 5.2.9p5, reference downcast.
   1286   // See the function for details.
   1287   // DR 427 specifies that this is to be applied before paragraph 2.
   1288   tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
   1289                                    OpRange, msg, Kind, BasePath);
   1290   if (tcr != TC_NotApplicable)
   1291     return tcr;
   1292 
   1293   // C++11 [expr.static.cast]p3:
   1294   //   A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
   1295   //   T2" if "cv2 T2" is reference-compatible with "cv1 T1".
   1296   tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
   1297                               BasePath, msg);
   1298   if (tcr != TC_NotApplicable)
   1299     return tcr;
   1300 
   1301   // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
   1302   //   [...] if the declaration "T t(e);" is well-formed, [...].
   1303   tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
   1304                               Kind, ListInitialization);
   1305   if (SrcExpr.isInvalid())
   1306     return TC_Failed;
   1307   if (tcr != TC_NotApplicable)
   1308     return tcr;
   1309 
   1310   // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
   1311   // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
   1312   // conversions, subject to further restrictions.
   1313   // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
   1314   // of qualification conversions impossible.
   1315   // In the CStyle case, the earlier attempt to const_cast should have taken
   1316   // care of reverse qualification conversions.
   1317 
   1318   QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
   1319 
   1320   // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
   1321   // converted to an integral type. [...] A value of a scoped enumeration type
   1322   // can also be explicitly converted to a floating-point type [...].
   1323   if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
   1324     if (Enum->getDecl()->isScoped()) {
   1325       if (DestType->isBooleanType()) {
   1326         Kind = CK_IntegralToBoolean;
   1327         return TC_Success;
   1328       } else if (DestType->isIntegralType(Self.Context)) {
   1329         Kind = CK_IntegralCast;
   1330         return TC_Success;
   1331       } else if (DestType->isRealFloatingType()) {
   1332         Kind = CK_IntegralToFloating;
   1333         return TC_Success;
   1334       }
   1335     }
   1336   }
   1337 
   1338   // Reverse integral promotion/conversion. All such conversions are themselves
   1339   // again integral promotions or conversions and are thus already handled by
   1340   // p2 (TryDirectInitialization above).
   1341   // (Note: any data loss warnings should be suppressed.)
   1342   // The exception is the reverse of enum->integer, i.e. integer->enum (and
   1343   // enum->enum). See also C++ 5.2.9p7.
   1344   // The same goes for reverse floating point promotion/conversion and
   1345   // floating-integral conversions. Again, only floating->enum is relevant.
   1346   if (DestType->isEnumeralType()) {
   1347     if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
   1348                                  diag::err_bad_cast_incomplete)) {
   1349       SrcExpr = ExprError();
   1350       return TC_Failed;
   1351     }
   1352     if (SrcType->isIntegralOrEnumerationType()) {
   1353       // [expr.static.cast]p10 If the enumeration type has a fixed underlying
   1354       // type, the value is first converted to that type by integral conversion
   1355       const EnumType *Enum = DestType->getAs<EnumType>();
   1356       Kind = Enum->getDecl()->isFixed() &&
   1357                      Enum->getDecl()->getIntegerType()->isBooleanType()
   1358                  ? CK_IntegralToBoolean
   1359                  : CK_IntegralCast;
   1360       return TC_Success;
   1361     } else if (SrcType->isRealFloatingType())   {
   1362       Kind = CK_FloatingToIntegral;
   1363       return TC_Success;
   1364     }
   1365   }
   1366 
   1367   // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
   1368   // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
   1369   tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
   1370                                  Kind, BasePath);
   1371   if (tcr != TC_NotApplicable)
   1372     return tcr;
   1373 
   1374   // Reverse member pointer conversion. C++ 4.11 specifies member pointer
   1375   // conversion. C++ 5.2.9p9 has additional information.
   1376   // DR54's access restrictions apply here also.
   1377   tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
   1378                                      OpRange, msg, Kind, BasePath);
   1379   if (tcr != TC_NotApplicable)
   1380     return tcr;
   1381 
   1382   // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
   1383   // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
   1384   // just the usual constness stuff.
   1385   if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
   1386     QualType SrcPointee = SrcPointer->getPointeeType();
   1387     if (SrcPointee->isVoidType()) {
   1388       if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
   1389         QualType DestPointee = DestPointer->getPointeeType();
   1390         if (DestPointee->isIncompleteOrObjectType()) {
   1391           // This is definitely the intended conversion, but it might fail due
   1392           // to a qualifier violation. Note that we permit Objective-C lifetime
   1393           // and GC qualifier mismatches here.
   1394           if (!CStyle) {
   1395             Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
   1396             Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
   1397             DestPointeeQuals.removeObjCGCAttr();
   1398             DestPointeeQuals.removeObjCLifetime();
   1399             SrcPointeeQuals.removeObjCGCAttr();
   1400             SrcPointeeQuals.removeObjCLifetime();
   1401             if (DestPointeeQuals != SrcPointeeQuals &&
   1402                 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
   1403               msg = diag::err_bad_cxx_cast_qualifiers_away;
   1404               return TC_Failed;
   1405             }
   1406           }
   1407           Kind = IsAddressSpaceConversion(SrcType, DestType)
   1408                      ? CK_AddressSpaceConversion
   1409                      : CK_BitCast;
   1410           return TC_Success;
   1411         }
   1412 
   1413         // Microsoft permits static_cast from 'pointer-to-void' to
   1414         // 'pointer-to-function'.
   1415         if (!CStyle && Self.getLangOpts().MSVCCompat &&
   1416             DestPointee->isFunctionType()) {
   1417           Self.Diag(OpRange.getBegin(), diag::ext_ms_cast_fn_obj) << OpRange;
   1418           Kind = CK_BitCast;
   1419           return TC_Success;
   1420         }
   1421       }
   1422       else if (DestType->isObjCObjectPointerType()) {
   1423         // allow both c-style cast and static_cast of objective-c pointers as
   1424         // they are pervasive.
   1425         Kind = CK_CPointerToObjCPointerCast;
   1426         return TC_Success;
   1427       }
   1428       else if (CStyle && DestType->isBlockPointerType()) {
   1429         // allow c-style cast of void * to block pointers.
   1430         Kind = CK_AnyPointerToBlockPointerCast;
   1431         return TC_Success;
   1432       }
   1433     }
   1434   }
   1435   // Allow arbitrary objective-c pointer conversion with static casts.
   1436   if (SrcType->isObjCObjectPointerType() &&
   1437       DestType->isObjCObjectPointerType()) {
   1438     Kind = CK_BitCast;
   1439     return TC_Success;
   1440   }
   1441   // Allow ns-pointer to cf-pointer conversion in either direction
   1442   // with static casts.
   1443   if (!CStyle &&
   1444       Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind))
   1445     return TC_Success;
   1446 
   1447   // See if it looks like the user is trying to convert between
   1448   // related record types, and select a better diagnostic if so.
   1449   if (auto SrcPointer = SrcType->getAs<PointerType>())
   1450     if (auto DestPointer = DestType->getAs<PointerType>())
   1451       if (SrcPointer->getPointeeType()->getAs<RecordType>() &&
   1452           DestPointer->getPointeeType()->getAs<RecordType>())
   1453        msg = diag::err_bad_cxx_cast_unrelated_class;
   1454 
   1455   // We tried everything. Everything! Nothing works! :-(
   1456   return TC_NotApplicable;
   1457 }
   1458 
   1459 /// Tests whether a conversion according to N2844 is valid.
   1460 TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
   1461                                     QualType DestType, bool CStyle,
   1462                                     CastKind &Kind, CXXCastPath &BasePath,
   1463                                     unsigned &msg) {
   1464   // C++11 [expr.static.cast]p3:
   1465   //   A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
   1466   //   cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
   1467   const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
   1468   if (!R)
   1469     return TC_NotApplicable;
   1470 
   1471   if (!SrcExpr->isGLValue())
   1472     return TC_NotApplicable;
   1473 
   1474   // Because we try the reference downcast before this function, from now on
   1475   // this is the only cast possibility, so we issue an error if we fail now.
   1476   // FIXME: Should allow casting away constness if CStyle.
   1477   QualType FromType = SrcExpr->getType();
   1478   QualType ToType = R->getPointeeType();
   1479   if (CStyle) {
   1480     FromType = FromType.getUnqualifiedType();
   1481     ToType = ToType.getUnqualifiedType();
   1482   }
   1483 
   1484   Sema::ReferenceConversions RefConv;
   1485   Sema::ReferenceCompareResult RefResult = Self.CompareReferenceRelationship(
   1486       SrcExpr->getBeginLoc(), ToType, FromType, &RefConv);
   1487   if (RefResult != Sema::Ref_Compatible) {
   1488     if (CStyle || RefResult == Sema::Ref_Incompatible)
   1489       return TC_NotApplicable;
   1490     // Diagnose types which are reference-related but not compatible here since
   1491     // we can provide better diagnostics. In these cases forwarding to
   1492     // [expr.static.cast]p4 should never result in a well-formed cast.
   1493     msg = SrcExpr->isLValue() ? diag::err_bad_lvalue_to_rvalue_cast
   1494                               : diag::err_bad_rvalue_to_rvalue_cast;
   1495     return TC_Failed;
   1496   }
   1497 
   1498   if (RefConv & Sema::ReferenceConversions::DerivedToBase) {
   1499     Kind = CK_DerivedToBase;
   1500     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
   1501                        /*DetectVirtual=*/true);
   1502     if (!Self.IsDerivedFrom(SrcExpr->getBeginLoc(), SrcExpr->getType(),
   1503                             R->getPointeeType(), Paths))
   1504       return TC_NotApplicable;
   1505 
   1506     Self.BuildBasePathArray(Paths, BasePath);
   1507   } else
   1508     Kind = CK_NoOp;
   1509 
   1510   return TC_Success;
   1511 }
   1512 
   1513 /// Tests whether a conversion according to C++ 5.2.9p5 is valid.
   1514 TryCastResult
   1515 TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
   1516                            bool CStyle, SourceRange OpRange,
   1517                            unsigned &msg, CastKind &Kind,
   1518                            CXXCastPath &BasePath) {
   1519   // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
   1520   //   cast to type "reference to cv2 D", where D is a class derived from B,
   1521   //   if a valid standard conversion from "pointer to D" to "pointer to B"
   1522   //   exists, cv2 >= cv1, and B is not a virtual base class of D.
   1523   // In addition, DR54 clarifies that the base must be accessible in the
   1524   // current context. Although the wording of DR54 only applies to the pointer
   1525   // variant of this rule, the intent is clearly for it to apply to the this
   1526   // conversion as well.
   1527 
   1528   const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
   1529   if (!DestReference) {
   1530     return TC_NotApplicable;
   1531   }
   1532   bool RValueRef = DestReference->isRValueReferenceType();
   1533   if (!RValueRef && !SrcExpr->isLValue()) {
   1534     // We know the left side is an lvalue reference, so we can suggest a reason.
   1535     msg = diag::err_bad_cxx_cast_rvalue;
   1536     return TC_NotApplicable;
   1537   }
   1538 
   1539   QualType DestPointee = DestReference->getPointeeType();
   1540 
   1541   // FIXME: If the source is a prvalue, we should issue a warning (because the
   1542   // cast always has undefined behavior), and for AST consistency, we should
   1543   // materialize a temporary.
   1544   return TryStaticDowncast(Self,
   1545                            Self.Context.getCanonicalType(SrcExpr->getType()),
   1546                            Self.Context.getCanonicalType(DestPointee), CStyle,
   1547                            OpRange, SrcExpr->getType(), DestType, msg, Kind,
   1548                            BasePath);
   1549 }
   1550 
   1551 /// Tests whether a conversion according to C++ 5.2.9p8 is valid.
   1552 TryCastResult
   1553 TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
   1554                          bool CStyle, SourceRange OpRange,
   1555                          unsigned &msg, CastKind &Kind,
   1556                          CXXCastPath &BasePath) {
   1557   // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
   1558   //   type, can be converted to an rvalue of type "pointer to cv2 D", where D
   1559   //   is a class derived from B, if a valid standard conversion from "pointer
   1560   //   to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
   1561   //   class of D.
   1562   // In addition, DR54 clarifies that the base must be accessible in the
   1563   // current context.
   1564 
   1565   const PointerType *DestPointer = DestType->getAs<PointerType>();
   1566   if (!DestPointer) {
   1567     return TC_NotApplicable;
   1568   }
   1569 
   1570   const PointerType *SrcPointer = SrcType->getAs<PointerType>();
   1571   if (!SrcPointer) {
   1572     msg = diag::err_bad_static_cast_pointer_nonpointer;
   1573     return TC_NotApplicable;
   1574   }
   1575 
   1576   return TryStaticDowncast(Self,
   1577                    Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
   1578                   Self.Context.getCanonicalType(DestPointer->getPointeeType()),
   1579                            CStyle, OpRange, SrcType, DestType, msg, Kind,
   1580                            BasePath);
   1581 }
   1582 
   1583 /// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
   1584 /// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
   1585 /// DestType is possible and allowed.
   1586 TryCastResult
   1587 TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
   1588                   bool CStyle, SourceRange OpRange, QualType OrigSrcType,
   1589                   QualType OrigDestType, unsigned &msg,
   1590                   CastKind &Kind, CXXCastPath &BasePath) {
   1591   // We can only work with complete types. But don't complain if it doesn't work
   1592   if (!Self.isCompleteType(OpRange.getBegin(), SrcType) ||
   1593       !Self.isCompleteType(OpRange.getBegin(), DestType))
   1594     return TC_NotApplicable;
   1595 
   1596   // Downcast can only happen in class hierarchies, so we need classes.
   1597   if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
   1598     return TC_NotApplicable;
   1599   }
   1600 
   1601   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
   1602                      /*DetectVirtual=*/true);
   1603   if (!Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths)) {
   1604     return TC_NotApplicable;
   1605   }
   1606 
   1607   // Target type does derive from source type. Now we're serious. If an error
   1608   // appears now, it's not ignored.
   1609   // This may not be entirely in line with the standard. Take for example:
   1610   // struct A {};
   1611   // struct B : virtual A {
   1612   //   B(A&);
   1613   // };
   1614   //
   1615   // void f()
   1616   // {
   1617   //   (void)static_cast<const B&>(*((A*)0));
   1618   // }
   1619   // As far as the standard is concerned, p5 does not apply (A is virtual), so
   1620   // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
   1621   // However, both GCC and Comeau reject this example, and accepting it would
   1622   // mean more complex code if we're to preserve the nice error message.
   1623   // FIXME: Being 100% compliant here would be nice to have.
   1624 
   1625   // Must preserve cv, as always, unless we're in C-style mode.
   1626   if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
   1627     msg = diag::err_bad_cxx_cast_qualifiers_away;
   1628     return TC_Failed;
   1629   }
   1630 
   1631   if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
   1632     // This code is analoguous to that in CheckDerivedToBaseConversion, except
   1633     // that it builds the paths in reverse order.
   1634     // To sum up: record all paths to the base and build a nice string from
   1635     // them. Use it to spice up the error message.
   1636     if (!Paths.isRecordingPaths()) {
   1637       Paths.clear();
   1638       Paths.setRecordingPaths(true);
   1639       Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths);
   1640     }
   1641     std::string PathDisplayStr;
   1642     std::set<unsigned> DisplayedPaths;
   1643     for (clang::CXXBasePath &Path : Paths) {
   1644       if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) {
   1645         // We haven't displayed a path to this particular base
   1646         // class subobject yet.
   1647         PathDisplayStr += "\n    ";
   1648         for (CXXBasePathElement &PE : llvm::reverse(Path))
   1649           PathDisplayStr += PE.Base->getType().getAsString() + " -> ";
   1650         PathDisplayStr += QualType(DestType).getAsString();
   1651       }
   1652     }
   1653 
   1654     Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
   1655       << QualType(SrcType).getUnqualifiedType()
   1656       << QualType(DestType).getUnqualifiedType()
   1657       << PathDisplayStr << OpRange;
   1658     msg = 0;
   1659     return TC_Failed;
   1660   }
   1661 
   1662   if (Paths.getDetectedVirtual() != nullptr) {
   1663     QualType VirtualBase(Paths.getDetectedVirtual(), 0);
   1664     Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
   1665       << OrigSrcType << OrigDestType << VirtualBase << OpRange;
   1666     msg = 0;
   1667     return TC_Failed;
   1668   }
   1669 
   1670   if (!CStyle) {
   1671     switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
   1672                                       SrcType, DestType,
   1673                                       Paths.front(),
   1674                                 diag::err_downcast_from_inaccessible_base)) {
   1675     case Sema::AR_accessible:
   1676     case Sema::AR_delayed:     // be optimistic
   1677     case Sema::AR_dependent:   // be optimistic
   1678       break;
   1679 
   1680     case Sema::AR_inaccessible:
   1681       msg = 0;
   1682       return TC_Failed;
   1683     }
   1684   }
   1685 
   1686   Self.BuildBasePathArray(Paths, BasePath);
   1687   Kind = CK_BaseToDerived;
   1688   return TC_Success;
   1689 }
   1690 
   1691 /// TryStaticMemberPointerUpcast - Tests whether a conversion according to
   1692 /// C++ 5.2.9p9 is valid:
   1693 ///
   1694 ///   An rvalue of type "pointer to member of D of type cv1 T" can be
   1695 ///   converted to an rvalue of type "pointer to member of B of type cv2 T",
   1696 ///   where B is a base class of D [...].
   1697 ///
   1698 TryCastResult
   1699 TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
   1700                              QualType DestType, bool CStyle,
   1701                              SourceRange OpRange,
   1702                              unsigned &msg, CastKind &Kind,
   1703                              CXXCastPath &BasePath) {
   1704   const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
   1705   if (!DestMemPtr)
   1706     return TC_NotApplicable;
   1707 
   1708   bool WasOverloadedFunction = false;
   1709   DeclAccessPair FoundOverload;
   1710   if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
   1711     if (FunctionDecl *Fn
   1712           = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
   1713                                                     FoundOverload)) {
   1714       CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
   1715       SrcType = Self.Context.getMemberPointerType(Fn->getType(),
   1716                       Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
   1717       WasOverloadedFunction = true;
   1718     }
   1719   }
   1720 
   1721   const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
   1722   if (!SrcMemPtr) {
   1723     msg = diag::err_bad_static_cast_member_pointer_nonmp;
   1724     return TC_NotApplicable;
   1725   }
   1726 
   1727   // Lock down the inheritance model right now in MS ABI, whether or not the
   1728   // pointee types are the same.
   1729   if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
   1730     (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
   1731     (void)Self.isCompleteType(OpRange.getBegin(), DestType);
   1732   }
   1733 
   1734   // T == T, modulo cv
   1735   if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
   1736                                            DestMemPtr->getPointeeType()))
   1737     return TC_NotApplicable;
   1738 
   1739   // B base of D
   1740   QualType SrcClass(SrcMemPtr->getClass(), 0);
   1741   QualType DestClass(DestMemPtr->getClass(), 0);
   1742   CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
   1743                   /*DetectVirtual=*/true);
   1744   if (!Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths))
   1745     return TC_NotApplicable;
   1746 
   1747   // B is a base of D. But is it an allowed base? If not, it's a hard error.
   1748   if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
   1749     Paths.clear();
   1750     Paths.setRecordingPaths(true);
   1751     bool StillOkay =
   1752         Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths);
   1753     assert(StillOkay);
   1754     (void)StillOkay;
   1755     std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
   1756     Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
   1757       << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
   1758     msg = 0;
   1759     return TC_Failed;
   1760   }
   1761 
   1762   if (const RecordType *VBase = Paths.getDetectedVirtual()) {
   1763     Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
   1764       << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
   1765     msg = 0;
   1766     return TC_Failed;
   1767   }
   1768 
   1769   if (!CStyle) {
   1770     switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
   1771                                       DestClass, SrcClass,
   1772                                       Paths.front(),
   1773                                       diag::err_upcast_to_inaccessible_base)) {
   1774     case Sema::AR_accessible:
   1775     case Sema::AR_delayed:
   1776     case Sema::AR_dependent:
   1777       // Optimistically assume that the delayed and dependent cases
   1778       // will work out.
   1779       break;
   1780 
   1781     case Sema::AR_inaccessible:
   1782       msg = 0;
   1783       return TC_Failed;
   1784     }
   1785   }
   1786 
   1787   if (WasOverloadedFunction) {
   1788     // Resolve the address of the overloaded function again, this time
   1789     // allowing complaints if something goes wrong.
   1790     FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
   1791                                                                DestType,
   1792                                                                true,
   1793                                                                FoundOverload);
   1794     if (!Fn) {
   1795       msg = 0;
   1796       return TC_Failed;
   1797     }
   1798 
   1799     SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
   1800     if (!SrcExpr.isUsable()) {
   1801       msg = 0;
   1802       return TC_Failed;
   1803     }
   1804   }
   1805 
   1806   Self.BuildBasePathArray(Paths, BasePath);
   1807   Kind = CK_DerivedToBaseMemberPointer;
   1808   return TC_Success;
   1809 }
   1810 
   1811 /// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
   1812 /// is valid:
   1813 ///
   1814 ///   An expression e can be explicitly converted to a type T using a
   1815 ///   @c static_cast if the declaration "T t(e);" is well-formed [...].
   1816 TryCastResult
   1817 TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
   1818                       Sema::CheckedConversionKind CCK,
   1819                       SourceRange OpRange, unsigned &msg,
   1820                       CastKind &Kind, bool ListInitialization) {
   1821   if (DestType->isRecordType()) {
   1822     if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
   1823                                  diag::err_bad_cast_incomplete) ||
   1824         Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
   1825                                     diag::err_allocation_of_abstract_type)) {
   1826       msg = 0;
   1827       return TC_Failed;
   1828     }
   1829   }
   1830 
   1831   InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
   1832   InitializationKind InitKind
   1833     = (CCK == Sema::CCK_CStyleCast)
   1834         ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
   1835                                                ListInitialization)
   1836     : (CCK == Sema::CCK_FunctionalCast)
   1837         ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
   1838     : InitializationKind::CreateCast(OpRange);
   1839   Expr *SrcExprRaw = SrcExpr.get();
   1840   // FIXME: Per DR242, we should check for an implicit conversion sequence
   1841   // or for a constructor that could be invoked by direct-initialization
   1842   // here, not for an initialization sequence.
   1843   InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
   1844 
   1845   // At this point of CheckStaticCast, if the destination is a reference,
   1846   // or the expression is an overload expression this has to work.
   1847   // There is no other way that works.
   1848   // On the other hand, if we're checking a C-style cast, we've still got
   1849   // the reinterpret_cast way.
   1850   bool CStyle
   1851     = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
   1852   if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
   1853     return TC_NotApplicable;
   1854 
   1855   ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
   1856   if (Result.isInvalid()) {
   1857     msg = 0;
   1858     return TC_Failed;
   1859   }
   1860 
   1861   if (InitSeq.isConstructorInitialization())
   1862     Kind = CK_ConstructorConversion;
   1863   else
   1864     Kind = CK_NoOp;
   1865 
   1866   SrcExpr = Result;
   1867   return TC_Success;
   1868 }
   1869 
   1870 /// TryConstCast - See if a const_cast from source to destination is allowed,
   1871 /// and perform it if it is.
   1872 static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
   1873                                   QualType DestType, bool CStyle,
   1874                                   unsigned &msg) {
   1875   DestType = Self.Context.getCanonicalType(DestType);
   1876   QualType SrcType = SrcExpr.get()->getType();
   1877   bool NeedToMaterializeTemporary = false;
   1878 
   1879   if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
   1880     // C++11 5.2.11p4:
   1881     //   if a pointer to T1 can be explicitly converted to the type "pointer to
   1882     //   T2" using a const_cast, then the following conversions can also be
   1883     //   made:
   1884     //    -- an lvalue of type T1 can be explicitly converted to an lvalue of
   1885     //       type T2 using the cast const_cast<T2&>;
   1886     //    -- a glvalue of type T1 can be explicitly converted to an xvalue of
   1887     //       type T2 using the cast const_cast<T2&&>; and
   1888     //    -- if T1 is a class type, a prvalue of type T1 can be explicitly
   1889     //       converted to an xvalue of type T2 using the cast const_cast<T2&&>.
   1890 
   1891     if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) {
   1892       // Cannot const_cast non-lvalue to lvalue reference type. But if this
   1893       // is C-style, static_cast might find a way, so we simply suggest a
   1894       // message and tell the parent to keep searching.
   1895       msg = diag::err_bad_cxx_cast_rvalue;
   1896       return TC_NotApplicable;
   1897     }
   1898 
   1899     if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) {
   1900       if (!SrcType->isRecordType()) {
   1901         // Cannot const_cast non-class prvalue to rvalue reference type. But if
   1902         // this is C-style, static_cast can do this.
   1903         msg = diag::err_bad_cxx_cast_rvalue;
   1904         return TC_NotApplicable;
   1905       }
   1906 
   1907       // Materialize the class prvalue so that the const_cast can bind a
   1908       // reference to it.
   1909       NeedToMaterializeTemporary = true;
   1910     }
   1911 
   1912     // It's not completely clear under the standard whether we can
   1913     // const_cast bit-field gl-values.  Doing so would not be
   1914     // intrinsically complicated, but for now, we say no for
   1915     // consistency with other compilers and await the word of the
   1916     // committee.
   1917     if (SrcExpr.get()->refersToBitField()) {
   1918       msg = diag::err_bad_cxx_cast_bitfield;
   1919       return TC_NotApplicable;
   1920     }
   1921 
   1922     DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
   1923     SrcType = Self.Context.getPointerType(SrcType);
   1924   }
   1925 
   1926   // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
   1927   //   the rules for const_cast are the same as those used for pointers.
   1928 
   1929   if (!DestType->isPointerType() &&
   1930       !DestType->isMemberPointerType() &&
   1931       !DestType->isObjCObjectPointerType()) {
   1932     // Cannot cast to non-pointer, non-reference type. Note that, if DestType
   1933     // was a reference type, we converted it to a pointer above.
   1934     // The status of rvalue references isn't entirely clear, but it looks like
   1935     // conversion to them is simply invalid.
   1936     // C++ 5.2.11p3: For two pointer types [...]
   1937     if (!CStyle)
   1938       msg = diag::err_bad_const_cast_dest;
   1939     return TC_NotApplicable;
   1940   }
   1941   if (DestType->isFunctionPointerType() ||
   1942       DestType->isMemberFunctionPointerType()) {
   1943     // Cannot cast direct function pointers.
   1944     // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
   1945     // T is the ultimate pointee of source and target type.
   1946     if (!CStyle)
   1947       msg = diag::err_bad_const_cast_dest;
   1948     return TC_NotApplicable;
   1949   }
   1950 
   1951   // C++ [expr.const.cast]p3:
   1952   //   "For two similar types T1 and T2, [...]"
   1953   //
   1954   // We only allow a const_cast to change cvr-qualifiers, not other kinds of
   1955   // type qualifiers. (Likewise, we ignore other changes when determining
   1956   // whether a cast casts away constness.)
   1957   if (!Self.Context.hasCvrSimilarType(SrcType, DestType))
   1958     return TC_NotApplicable;
   1959 
   1960   if (NeedToMaterializeTemporary)
   1961     // This is a const_cast from a class prvalue to an rvalue reference type.
   1962     // Materialize a temporary to store the result of the conversion.
   1963     SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcExpr.get()->getType(),
   1964                                                   SrcExpr.get(),
   1965                                                   /*IsLValueReference*/ false);
   1966 
   1967   return TC_Success;
   1968 }
   1969 
   1970 // Checks for undefined behavior in reinterpret_cast.
   1971 // The cases that is checked for is:
   1972 // *reinterpret_cast<T*>(&a)
   1973 // reinterpret_cast<T&>(a)
   1974 // where accessing 'a' as type 'T' will result in undefined behavior.
   1975 void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
   1976                                           bool IsDereference,
   1977                                           SourceRange Range) {
   1978   unsigned DiagID = IsDereference ?
   1979                         diag::warn_pointer_indirection_from_incompatible_type :
   1980                         diag::warn_undefined_reinterpret_cast;
   1981 
   1982   if (Diags.isIgnored(DiagID, Range.getBegin()))
   1983     return;
   1984 
   1985   QualType SrcTy, DestTy;
   1986   if (IsDereference) {
   1987     if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
   1988       return;
   1989     }
   1990     SrcTy = SrcType->getPointeeType();
   1991     DestTy = DestType->getPointeeType();
   1992   } else {
   1993     if (!DestType->getAs<ReferenceType>()) {
   1994       return;
   1995     }
   1996     SrcTy = SrcType;
   1997     DestTy = DestType->getPointeeType();
   1998   }
   1999 
   2000   // Cast is compatible if the types are the same.
   2001   if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
   2002     return;
   2003   }
   2004   // or one of the types is a char or void type
   2005   if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
   2006       SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
   2007     return;
   2008   }
   2009   // or one of the types is a tag type.
   2010   if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
   2011     return;
   2012   }
   2013 
   2014   // FIXME: Scoped enums?
   2015   if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
   2016       (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
   2017     if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
   2018       return;
   2019     }
   2020   }
   2021 
   2022   Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
   2023 }
   2024 
   2025 static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
   2026                                   QualType DestType) {
   2027   QualType SrcType = SrcExpr.get()->getType();
   2028   if (Self.Context.hasSameType(SrcType, DestType))
   2029     return;
   2030   if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
   2031     if (SrcPtrTy->isObjCSelType()) {
   2032       QualType DT = DestType;
   2033       if (isa<PointerType>(DestType))
   2034         DT = DestType->getPointeeType();
   2035       if (!DT.getUnqualifiedType()->isVoidType())
   2036         Self.Diag(SrcExpr.get()->getExprLoc(),
   2037                   diag::warn_cast_pointer_from_sel)
   2038         << SrcType << DestType << SrcExpr.get()->getSourceRange();
   2039     }
   2040 }
   2041 
   2042 /// Diagnose casts that change the calling convention of a pointer to a function
   2043 /// defined in the current TU.
   2044 static void DiagnoseCallingConvCast(Sema &Self, const ExprResult &SrcExpr,
   2045                                     QualType DstType, SourceRange OpRange) {
   2046   // Check if this cast would change the calling convention of a function
   2047   // pointer type.
   2048   QualType SrcType = SrcExpr.get()->getType();
   2049   if (Self.Context.hasSameType(SrcType, DstType) ||
   2050       !SrcType->isFunctionPointerType() || !DstType->isFunctionPointerType())
   2051     return;
   2052   const auto *SrcFTy =
   2053       SrcType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
   2054   const auto *DstFTy =
   2055       DstType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
   2056   CallingConv SrcCC = SrcFTy->getCallConv();
   2057   CallingConv DstCC = DstFTy->getCallConv();
   2058   if (SrcCC == DstCC)
   2059     return;
   2060 
   2061   // We have a calling convention cast. Check if the source is a pointer to a
   2062   // known, specific function that has already been defined.
   2063   Expr *Src = SrcExpr.get()->IgnoreParenImpCasts();
   2064   if (auto *UO = dyn_cast<UnaryOperator>(Src))
   2065     if (UO->getOpcode() == UO_AddrOf)
   2066       Src = UO->getSubExpr()->IgnoreParenImpCasts();
   2067   auto *DRE = dyn_cast<DeclRefExpr>(Src);
   2068   if (!DRE)
   2069     return;
   2070   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
   2071   if (!FD)
   2072     return;
   2073 
   2074   // Only warn if we are casting from the default convention to a non-default
   2075   // convention. This can happen when the programmer forgot to apply the calling
   2076   // convention to the function declaration and then inserted this cast to
   2077   // satisfy the type system.
   2078   CallingConv DefaultCC = Self.getASTContext().getDefaultCallingConvention(
   2079       FD->isVariadic(), FD->isCXXInstanceMember());
   2080   if (DstCC == DefaultCC || SrcCC != DefaultCC)
   2081     return;
   2082 
   2083   // Diagnose this cast, as it is probably bad.
   2084   StringRef SrcCCName = FunctionType::getNameForCallConv(SrcCC);
   2085   StringRef DstCCName = FunctionType::getNameForCallConv(DstCC);
   2086   Self.Diag(OpRange.getBegin(), diag::warn_cast_calling_conv)
   2087       << SrcCCName << DstCCName << OpRange;
   2088 
   2089   // The checks above are cheaper than checking if the diagnostic is enabled.
   2090   // However, it's worth checking if the warning is enabled before we construct
   2091   // a fixit.
   2092   if (Self.Diags.isIgnored(diag::warn_cast_calling_conv, OpRange.getBegin()))
   2093     return;
   2094 
   2095   // Try to suggest a fixit to change the calling convention of the function
   2096   // whose address was taken. Try to use the latest macro for the convention.
   2097   // For example, users probably want to write "WINAPI" instead of "__stdcall"
   2098   // to match the Windows header declarations.
   2099   SourceLocation NameLoc = FD->getFirstDecl()->getNameInfo().getLoc();
   2100   Preprocessor &PP = Self.getPreprocessor();
   2101   SmallVector<TokenValue, 6> AttrTokens;
   2102   SmallString<64> CCAttrText;
   2103   llvm::raw_svector_ostream OS(CCAttrText);
   2104   if (Self.getLangOpts().MicrosoftExt) {
   2105     // __stdcall or __vectorcall
   2106     OS << "__" << DstCCName;
   2107     IdentifierInfo *II = PP.getIdentifierInfo(OS.str());
   2108     AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
   2109                              ? TokenValue(II->getTokenID())
   2110                              : TokenValue(II));
   2111   } else {
   2112     // __attribute__((stdcall)) or __attribute__((vectorcall))
   2113     OS << "__attribute__((" << DstCCName << "))";
   2114     AttrTokens.push_back(tok::kw___attribute);
   2115     AttrTokens.push_back(tok::l_paren);
   2116     AttrTokens.push_back(tok::l_paren);
   2117     IdentifierInfo *II = PP.getIdentifierInfo(DstCCName);
   2118     AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
   2119                              ? TokenValue(II->getTokenID())
   2120                              : TokenValue(II));
   2121     AttrTokens.push_back(tok::r_paren);
   2122     AttrTokens.push_back(tok::r_paren);
   2123   }
   2124   StringRef AttrSpelling = PP.getLastMacroWithSpelling(NameLoc, AttrTokens);
   2125   if (!AttrSpelling.empty())
   2126     CCAttrText = AttrSpelling;
   2127   OS << ' ';
   2128   Self.Diag(NameLoc, diag::note_change_calling_conv_fixit)
   2129       << FD << DstCCName << FixItHint::CreateInsertion(NameLoc, CCAttrText);
   2130 }
   2131 
   2132 static void checkIntToPointerCast(bool CStyle, const SourceRange &OpRange,
   2133                                   const Expr *SrcExpr, QualType DestType,
   2134                                   Sema &Self) {
   2135   QualType SrcType = SrcExpr->getType();
   2136 
   2137   // Not warning on reinterpret_cast, boolean, constant expressions, etc
   2138   // are not explicit design choices, but consistent with GCC's behavior.
   2139   // Feel free to modify them if you've reason/evidence for an alternative.
   2140   if (CStyle && SrcType->isIntegralType(Self.Context)
   2141       && !SrcType->isBooleanType()
   2142       && !SrcType->isEnumeralType()
   2143       && !SrcExpr->isIntegerConstantExpr(Self.Context)
   2144       && Self.Context.getTypeSize(DestType) >
   2145          Self.Context.getTypeSize(SrcType)) {
   2146     // Separate between casts to void* and non-void* pointers.
   2147     // Some APIs use (abuse) void* for something like a user context,
   2148     // and often that value is an integer even if it isn't a pointer itself.
   2149     // Having a separate warning flag allows users to control the warning
   2150     // for their workflow.
   2151     unsigned Diag = DestType->isVoidPointerType() ?
   2152                       diag::warn_int_to_void_pointer_cast
   2153                     : diag::warn_int_to_pointer_cast;
   2154     Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange;
   2155   }
   2156 }
   2157 
   2158 static bool fixOverloadedReinterpretCastExpr(Sema &Self, QualType DestType,
   2159                                              ExprResult &Result) {
   2160   // We can only fix an overloaded reinterpret_cast if
   2161   // - it is a template with explicit arguments that resolves to an lvalue
   2162   //   unambiguously, or
   2163   // - it is the only function in an overload set that may have its address
   2164   //   taken.
   2165 
   2166   Expr *E = Result.get();
   2167   // TODO: what if this fails because of DiagnoseUseOfDecl or something
   2168   // like it?
   2169   if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
   2170           Result,
   2171           Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
   2172           ) &&
   2173       Result.isUsable())
   2174     return true;
   2175 
   2176   // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
   2177   // preserves Result.
   2178   Result = E;
   2179   if (!Self.resolveAndFixAddressOfSingleOverloadCandidate(
   2180           Result, /*DoFunctionPointerConversion=*/true))
   2181     return false;
   2182   return Result.isUsable();
   2183 }
   2184 
   2185 static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
   2186                                         QualType DestType, bool CStyle,
   2187                                         SourceRange OpRange,
   2188                                         unsigned &msg,
   2189                                         CastKind &Kind) {
   2190   bool IsLValueCast = false;
   2191 
   2192   DestType = Self.Context.getCanonicalType(DestType);
   2193   QualType SrcType = SrcExpr.get()->getType();
   2194 
   2195   // Is the source an overloaded name? (i.e. &foo)
   2196   // If so, reinterpret_cast generally can not help us here (13.4, p1, bullet 5)
   2197   if (SrcType == Self.Context.OverloadTy) {
   2198     ExprResult FixedExpr = SrcExpr;
   2199     if (!fixOverloadedReinterpretCastExpr(Self, DestType, FixedExpr))
   2200       return TC_NotApplicable;
   2201 
   2202     assert(FixedExpr.isUsable() && "Invalid result fixing overloaded expr");
   2203     SrcExpr = FixedExpr;
   2204     SrcType = SrcExpr.get()->getType();
   2205   }
   2206 
   2207   if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
   2208     if (!SrcExpr.get()->isGLValue()) {
   2209       // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
   2210       // similar comment in const_cast.
   2211       msg = diag::err_bad_cxx_cast_rvalue;
   2212       return TC_NotApplicable;
   2213     }
   2214 
   2215     if (!CStyle) {
   2216       Self.CheckCompatibleReinterpretCast(SrcType, DestType,
   2217                                           /*IsDereference=*/false, OpRange);
   2218     }
   2219 
   2220     // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
   2221     //   same effect as the conversion *reinterpret_cast<T*>(&x) with the
   2222     //   built-in & and * operators.
   2223 
   2224     const char *inappropriate = nullptr;
   2225     switch (SrcExpr.get()->getObjectKind()) {
   2226     case OK_Ordinary:
   2227       break;
   2228     case OK_BitField:
   2229       msg = diag::err_bad_cxx_cast_bitfield;
   2230       return TC_NotApplicable;
   2231       // FIXME: Use a specific diagnostic for the rest of these cases.
   2232     case OK_VectorComponent: inappropriate = "vector element";      break;
   2233     case OK_MatrixComponent:
   2234       inappropriate = "matrix element";
   2235       break;
   2236     case OK_ObjCProperty:    inappropriate = "property expression"; break;
   2237     case OK_ObjCSubscript:   inappropriate = "container subscripting expression";
   2238                              break;
   2239     }
   2240     if (inappropriate) {
   2241       Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
   2242           << inappropriate << DestType
   2243           << OpRange << SrcExpr.get()->getSourceRange();
   2244       msg = 0; SrcExpr = ExprError();
   2245       return TC_NotApplicable;
   2246     }
   2247 
   2248     // This code does this transformation for the checked types.
   2249     DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
   2250     SrcType = Self.Context.getPointerType(SrcType);
   2251 
   2252     IsLValueCast = true;
   2253   }
   2254 
   2255   // Canonicalize source for comparison.
   2256   SrcType = Self.Context.getCanonicalType(SrcType);
   2257 
   2258   const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
   2259                           *SrcMemPtr = SrcType->getAs<MemberPointerType>();
   2260   if (DestMemPtr && SrcMemPtr) {
   2261     // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
   2262     //   can be explicitly converted to an rvalue of type "pointer to member
   2263     //   of Y of type T2" if T1 and T2 are both function types or both object
   2264     //   types.
   2265     if (DestMemPtr->isMemberFunctionPointer() !=
   2266         SrcMemPtr->isMemberFunctionPointer())
   2267       return TC_NotApplicable;
   2268 
   2269     if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
   2270       // We need to determine the inheritance model that the class will use if
   2271       // haven't yet.
   2272       (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
   2273       (void)Self.isCompleteType(OpRange.getBegin(), DestType);
   2274     }
   2275 
   2276     // Don't allow casting between member pointers of different sizes.
   2277     if (Self.Context.getTypeSize(DestMemPtr) !=
   2278         Self.Context.getTypeSize(SrcMemPtr)) {
   2279       msg = diag::err_bad_cxx_cast_member_pointer_size;
   2280       return TC_Failed;
   2281     }
   2282 
   2283     // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
   2284     //   constness.
   2285     // A reinterpret_cast followed by a const_cast can, though, so in C-style,
   2286     // we accept it.
   2287     if (auto CACK =
   2288             CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
   2289                                /*CheckObjCLifetime=*/CStyle))
   2290       return getCastAwayConstnessCastKind(CACK, msg);
   2291 
   2292     // A valid member pointer cast.
   2293     assert(!IsLValueCast);
   2294     Kind = CK_ReinterpretMemberPointer;
   2295     return TC_Success;
   2296   }
   2297 
   2298   // See below for the enumeral issue.
   2299   if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
   2300     // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
   2301     //   type large enough to hold it. A value of std::nullptr_t can be
   2302     //   converted to an integral type; the conversion has the same meaning
   2303     //   and validity as a conversion of (void*)0 to the integral type.
   2304     if (Self.Context.getTypeSize(SrcType) >
   2305         Self.Context.getTypeSize(DestType)) {
   2306       msg = diag::err_bad_reinterpret_cast_small_int;
   2307       return TC_Failed;
   2308     }
   2309     Kind = CK_PointerToIntegral;
   2310     return TC_Success;
   2311   }
   2312 
   2313   // Allow reinterpret_casts between vectors of the same size and
   2314   // between vectors and integers of the same size.
   2315   bool destIsVector = DestType->isVectorType();
   2316   bool srcIsVector = SrcType->isVectorType();
   2317   if (srcIsVector || destIsVector) {
   2318     // Allow bitcasting between SVE VLATs and VLSTs, and vice-versa.
   2319     if (Self.isValidSveBitcast(SrcType, DestType)) {
   2320       Kind = CK_BitCast;
   2321       return TC_Success;
   2322     }
   2323 
   2324     // The non-vector type, if any, must have integral type.  This is
   2325     // the same rule that C vector casts use; note, however, that enum
   2326     // types are not integral in C++.
   2327     if ((!destIsVector && !DestType->isIntegralType(Self.Context)) ||
   2328         (!srcIsVector && !SrcType->isIntegralType(Self.Context)))
   2329       return TC_NotApplicable;
   2330 
   2331     // The size we want to consider is eltCount * eltSize.
   2332     // That's exactly what the lax-conversion rules will check.
   2333     if (Self.areLaxCompatibleVectorTypes(SrcType, DestType)) {
   2334       Kind = CK_BitCast;
   2335       return TC_Success;
   2336     }
   2337 
   2338     if (Self.LangOpts.OpenCL && !CStyle) {
   2339       if (DestType->isExtVectorType() || SrcType->isExtVectorType()) {
   2340         // FIXME: Allow for reinterpret cast between 3 and 4 element vectors
   2341         if (Self.areVectorTypesSameSize(SrcType, DestType)) {
   2342           Kind = CK_BitCast;
   2343           return TC_Success;
   2344         }
   2345       }
   2346     }
   2347 
   2348     // Otherwise, pick a reasonable diagnostic.
   2349     if (!destIsVector)
   2350       msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
   2351     else if (!srcIsVector)
   2352       msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
   2353     else
   2354       msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
   2355 
   2356     return TC_Failed;
   2357   }
   2358 
   2359   if (SrcType == DestType) {
   2360     // C++ 5.2.10p2 has a note that mentions that, subject to all other
   2361     // restrictions, a cast to the same type is allowed so long as it does not
   2362     // cast away constness. In C++98, the intent was not entirely clear here,
   2363     // since all other paragraphs explicitly forbid casts to the same type.
   2364     // C++11 clarifies this case with p2.
   2365     //
   2366     // The only allowed types are: integral, enumeration, pointer, or
   2367     // pointer-to-member types.  We also won't restrict Obj-C pointers either.
   2368     Kind = CK_NoOp;
   2369     TryCastResult Result = TC_NotApplicable;
   2370     if (SrcType->isIntegralOrEnumerationType() ||
   2371         SrcType->isAnyPointerType() ||
   2372         SrcType->isMemberPointerType() ||
   2373         SrcType->isBlockPointerType()) {
   2374       Result = TC_Success;
   2375     }
   2376     return Result;
   2377   }
   2378 
   2379   bool destIsPtr = DestType->isAnyPointerType() ||
   2380                    DestType->isBlockPointerType();
   2381   bool srcIsPtr = SrcType->isAnyPointerType() ||
   2382                   SrcType->isBlockPointerType();
   2383   if (!destIsPtr && !srcIsPtr) {
   2384     // Except for std::nullptr_t->integer and lvalue->reference, which are
   2385     // handled above, at least one of the two arguments must be a pointer.
   2386     return TC_NotApplicable;
   2387   }
   2388 
   2389   if (DestType->isIntegralType(Self.Context)) {
   2390     assert(srcIsPtr && "One type must be a pointer");
   2391     // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
   2392     //   type large enough to hold it; except in Microsoft mode, where the
   2393     //   integral type size doesn't matter (except we don't allow bool).
   2394     if ((Self.Context.getTypeSize(SrcType) >
   2395          Self.Context.getTypeSize(DestType))) {
   2396       bool MicrosoftException =
   2397           Self.getLangOpts().MicrosoftExt && !DestType->isBooleanType();
   2398       if (MicrosoftException) {
   2399         unsigned Diag = SrcType->isVoidPointerType()
   2400                             ? diag::warn_void_pointer_to_int_cast
   2401                             : diag::warn_pointer_to_int_cast;
   2402         Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange;
   2403       } else {
   2404         msg = diag::err_bad_reinterpret_cast_small_int;
   2405         return TC_Failed;
   2406       }
   2407     }
   2408     Kind = CK_PointerToIntegral;
   2409     return TC_Success;
   2410   }
   2411 
   2412   if (SrcType->isIntegralOrEnumerationType()) {
   2413     assert(destIsPtr && "One type must be a pointer");
   2414     checkIntToPointerCast(CStyle, OpRange, SrcExpr.get(), DestType, Self);
   2415     // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
   2416     //   converted to a pointer.
   2417     // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
   2418     //   necessarily converted to a null pointer value.]
   2419     Kind = CK_IntegralToPointer;
   2420     return TC_Success;
   2421   }
   2422 
   2423   if (!destIsPtr || !srcIsPtr) {
   2424     // With the valid non-pointer conversions out of the way, we can be even
   2425     // more stringent.
   2426     return TC_NotApplicable;
   2427   }
   2428 
   2429   // Cannot convert between block pointers and Objective-C object pointers.
   2430   if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
   2431       (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
   2432     return TC_NotApplicable;
   2433 
   2434   // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
   2435   // The C-style cast operator can.
   2436   TryCastResult SuccessResult = TC_Success;
   2437   if (auto CACK =
   2438           CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
   2439                              /*CheckObjCLifetime=*/CStyle))
   2440     SuccessResult = getCastAwayConstnessCastKind(CACK, msg);
   2441 
   2442   if (IsAddressSpaceConversion(SrcType, DestType)) {
   2443     Kind = CK_AddressSpaceConversion;
   2444     assert(SrcType->isPointerType() && DestType->isPointerType());
   2445     if (!CStyle &&
   2446         !DestType->getPointeeType().getQualifiers().isAddressSpaceSupersetOf(
   2447             SrcType->getPointeeType().getQualifiers())) {
   2448       SuccessResult = TC_Failed;
   2449     }
   2450   } else if (IsLValueCast) {
   2451     Kind = CK_LValueBitCast;
   2452   } else if (DestType->isObjCObjectPointerType()) {
   2453     Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
   2454   } else if (DestType->isBlockPointerType()) {
   2455     if (!SrcType->isBlockPointerType()) {
   2456       Kind = CK_AnyPointerToBlockPointerCast;
   2457     } else {
   2458       Kind = CK_BitCast;
   2459     }
   2460   } else {
   2461     Kind = CK_BitCast;
   2462   }
   2463 
   2464   // Any pointer can be cast to an Objective-C pointer type with a C-style
   2465   // cast.
   2466   if (CStyle && DestType->isObjCObjectPointerType()) {
   2467     return SuccessResult;
   2468   }
   2469   if (CStyle)
   2470     DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
   2471 
   2472   DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
   2473 
   2474   // Not casting away constness, so the only remaining check is for compatible
   2475   // pointer categories.
   2476 
   2477   if (SrcType->isFunctionPointerType()) {
   2478     if (DestType->isFunctionPointerType()) {
   2479       // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
   2480       // a pointer to a function of a different type.
   2481       return SuccessResult;
   2482     }
   2483 
   2484     // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
   2485     //   an object type or vice versa is conditionally-supported.
   2486     // Compilers support it in C++03 too, though, because it's necessary for
   2487     // casting the return value of dlsym() and GetProcAddress().
   2488     // FIXME: Conditionally-supported behavior should be configurable in the
   2489     // TargetInfo or similar.
   2490     Self.Diag(OpRange.getBegin(),
   2491               Self.getLangOpts().CPlusPlus11 ?
   2492                 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
   2493       << OpRange;
   2494     return SuccessResult;
   2495   }
   2496 
   2497   if (DestType->isFunctionPointerType()) {
   2498     // See above.
   2499     Self.Diag(OpRange.getBegin(),
   2500               Self.getLangOpts().CPlusPlus11 ?
   2501                 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
   2502       << OpRange;
   2503     return SuccessResult;
   2504   }
   2505 
   2506   // Diagnose address space conversion in nested pointers.
   2507   QualType DestPtee = DestType->getPointeeType().isNull()
   2508                           ? DestType->getPointeeType()
   2509                           : DestType->getPointeeType()->getPointeeType();
   2510   QualType SrcPtee = SrcType->getPointeeType().isNull()
   2511                          ? SrcType->getPointeeType()
   2512                          : SrcType->getPointeeType()->getPointeeType();
   2513   while (!DestPtee.isNull() && !SrcPtee.isNull()) {
   2514     if (DestPtee.getAddressSpace() != SrcPtee.getAddressSpace()) {
   2515       Self.Diag(OpRange.getBegin(),
   2516                 diag::warn_bad_cxx_cast_nested_pointer_addr_space)
   2517           << CStyle << SrcType << DestType << SrcExpr.get()->getSourceRange();
   2518       break;
   2519     }
   2520     DestPtee = DestPtee->getPointeeType();
   2521     SrcPtee = SrcPtee->getPointeeType();
   2522   }
   2523 
   2524   // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
   2525   //   a pointer to an object of different type.
   2526   // Void pointers are not specified, but supported by every compiler out there.
   2527   // So we finish by allowing everything that remains - it's got to be two
   2528   // object pointers.
   2529   return SuccessResult;
   2530 }
   2531 
   2532 static TryCastResult TryAddressSpaceCast(Sema &Self, ExprResult &SrcExpr,
   2533                                          QualType DestType, bool CStyle,
   2534                                          unsigned &msg, CastKind &Kind) {
   2535   if (!Self.getLangOpts().OpenCL)
   2536     // FIXME: As compiler doesn't have any information about overlapping addr
   2537     // spaces at the moment we have to be permissive here.
   2538     return TC_NotApplicable;
   2539   // Even though the logic below is general enough and can be applied to
   2540   // non-OpenCL mode too, we fast-path above because no other languages
   2541   // define overlapping address spaces currently.
   2542   auto SrcType = SrcExpr.get()->getType();
   2543   // FIXME: Should this be generalized to references? The reference parameter
   2544   // however becomes a reference pointee type here and therefore rejected.
   2545   // Perhaps this is the right behavior though according to C++.
   2546   auto SrcPtrType = SrcType->getAs<PointerType>();
   2547   if (!SrcPtrType)
   2548     return TC_NotApplicable;
   2549   auto DestPtrType = DestType->getAs<PointerType>();
   2550   if (!DestPtrType)
   2551     return TC_NotApplicable;
   2552   auto SrcPointeeType = SrcPtrType->getPointeeType();
   2553   auto DestPointeeType = DestPtrType->getPointeeType();
   2554   if (!DestPointeeType.isAddressSpaceOverlapping(SrcPointeeType)) {
   2555     msg = diag::err_bad_cxx_cast_addr_space_mismatch;
   2556     return TC_Failed;
   2557   }
   2558   auto SrcPointeeTypeWithoutAS =
   2559       Self.Context.removeAddrSpaceQualType(SrcPointeeType.getCanonicalType());
   2560   auto DestPointeeTypeWithoutAS =
   2561       Self.Context.removeAddrSpaceQualType(DestPointeeType.getCanonicalType());
   2562   if (Self.Context.hasSameType(SrcPointeeTypeWithoutAS,
   2563                                DestPointeeTypeWithoutAS)) {
   2564     Kind = SrcPointeeType.getAddressSpace() == DestPointeeType.getAddressSpace()
   2565                ? CK_NoOp
   2566                : CK_AddressSpaceConversion;
   2567     return TC_Success;
   2568   } else {
   2569     return TC_NotApplicable;
   2570   }
   2571 }
   2572 
   2573 void CastOperation::checkAddressSpaceCast(QualType SrcType, QualType DestType) {
   2574   // In OpenCL only conversions between pointers to objects in overlapping
   2575   // addr spaces are allowed. v2.0 s6.5.5 - Generic addr space overlaps
   2576   // with any named one, except for constant.
   2577 
   2578   // Converting the top level pointee addrspace is permitted for compatible
   2579   // addrspaces (such as 'generic int *' to 'local int *' or vice versa), but
   2580   // if any of the nested pointee addrspaces differ, we emit a warning
   2581   // regardless of addrspace compatibility. This makes
   2582   //   local int ** p;
   2583   //   return (generic int **) p;
   2584   // warn even though local -> generic is permitted.
   2585   if (Self.getLangOpts().OpenCL) {
   2586     const Type *DestPtr, *SrcPtr;
   2587     bool Nested = false;
   2588     unsigned DiagID = diag::err_typecheck_incompatible_address_space;
   2589     DestPtr = Self.getASTContext().getCanonicalType(DestType.getTypePtr()),
   2590     SrcPtr  = Self.getASTContext().getCanonicalType(SrcType.getTypePtr());
   2591 
   2592     while (isa<PointerType>(DestPtr) && isa<PointerType>(SrcPtr)) {
   2593       const PointerType *DestPPtr = cast<PointerType>(DestPtr);
   2594       const PointerType *SrcPPtr = cast<PointerType>(SrcPtr);
   2595       QualType DestPPointee = DestPPtr->getPointeeType();
   2596       QualType SrcPPointee = SrcPPtr->getPointeeType();
   2597       if (Nested
   2598               ? DestPPointee.getAddressSpace() != SrcPPointee.getAddressSpace()
   2599               : !DestPPointee.isAddressSpaceOverlapping(SrcPPointee)) {
   2600         Self.Diag(OpRange.getBegin(), DiagID)
   2601             << SrcType << DestType << Sema::AA_Casting
   2602             << SrcExpr.get()->getSourceRange();
   2603         if (!Nested)
   2604           SrcExpr = ExprError();
   2605         return;
   2606       }
   2607 
   2608       DestPtr = DestPPtr->getPointeeType().getTypePtr();
   2609       SrcPtr = SrcPPtr->getPointeeType().getTypePtr();
   2610       Nested = true;
   2611       DiagID = diag::ext_nested_pointer_qualifier_mismatch;
   2612     }
   2613   }
   2614 }
   2615 
   2616 void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
   2617                                        bool ListInitialization) {
   2618   assert(Self.getLangOpts().CPlusPlus);
   2619 
   2620   // Handle placeholders.
   2621   if (isPlaceholder()) {
   2622     // C-style casts can resolve __unknown_any types.
   2623     if (claimPlaceholder(BuiltinType::UnknownAny)) {
   2624       SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
   2625                                          SrcExpr.get(), Kind,
   2626                                          ValueKind, BasePath);
   2627       return;
   2628     }
   2629 
   2630     checkNonOverloadPlaceholders();
   2631     if (SrcExpr.isInvalid())
   2632       return;
   2633   }
   2634 
   2635   // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
   2636   // This test is outside everything else because it's the only case where
   2637   // a non-lvalue-reference target type does not lead to decay.
   2638   if (DestType->isVoidType()) {
   2639     Kind = CK_ToVoid;
   2640 
   2641     if (claimPlaceholder(BuiltinType::Overload)) {
   2642       Self.ResolveAndFixSingleFunctionTemplateSpecialization(
   2643                   SrcExpr, /* Decay Function to ptr */ false,
   2644                   /* Complain */ true, DestRange, DestType,
   2645                   diag::err_bad_cstyle_cast_overload);
   2646       if (SrcExpr.isInvalid())
   2647         return;
   2648     }
   2649 
   2650     SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
   2651     return;
   2652   }
   2653 
   2654   // If the type is dependent, we won't do any other semantic analysis now.
   2655   if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
   2656       SrcExpr.get()->isValueDependent()) {
   2657     assert(Kind == CK_Dependent);
   2658     return;
   2659   }
   2660 
   2661   if (ValueKind == VK_RValue && !DestType->isRecordType() &&
   2662       !isPlaceholder(BuiltinType::Overload)) {
   2663     SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
   2664     if (SrcExpr.isInvalid())
   2665       return;
   2666   }
   2667 
   2668   if (DestType->getAs<MatrixType>() ||
   2669       SrcExpr.get()->getType()->getAs<MatrixType>()) {
   2670     if (Self.CheckMatrixCast(OpRange, DestType, SrcExpr.get()->getType(), Kind))
   2671       SrcExpr = ExprError();
   2672     return;
   2673   }
   2674 
   2675   // AltiVec vector initialization with a single literal.
   2676   if (const VectorType *vecTy = DestType->getAs<VectorType>())
   2677     if (vecTy->getVectorKind() == VectorType::AltiVecVector
   2678         && (SrcExpr.get()->getType()->isIntegerType()
   2679             || SrcExpr.get()->getType()->isFloatingType())) {
   2680       Kind = CK_VectorSplat;
   2681       SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
   2682       return;
   2683     }
   2684 
   2685   // C++ [expr.cast]p5: The conversions performed by
   2686   //   - a const_cast,
   2687   //   - a static_cast,
   2688   //   - a static_cast followed by a const_cast,
   2689   //   - a reinterpret_cast, or
   2690   //   - a reinterpret_cast followed by a const_cast,
   2691   //   can be performed using the cast notation of explicit type conversion.
   2692   //   [...] If a conversion can be interpreted in more than one of the ways
   2693   //   listed above, the interpretation that appears first in the list is used,
   2694   //   even if a cast resulting from that interpretation is ill-formed.
   2695   // In plain language, this means trying a const_cast ...
   2696   // Note that for address space we check compatibility after const_cast.
   2697   unsigned msg = diag::err_bad_cxx_cast_generic;
   2698   TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
   2699                                    /*CStyle*/ true, msg);
   2700   if (SrcExpr.isInvalid())
   2701     return;
   2702   if (isValidCast(tcr))
   2703     Kind = CK_NoOp;
   2704 
   2705   Sema::CheckedConversionKind CCK =
   2706       FunctionalStyle ? Sema::CCK_FunctionalCast : Sema::CCK_CStyleCast;
   2707   if (tcr == TC_NotApplicable) {
   2708     tcr = TryAddressSpaceCast(Self, SrcExpr, DestType, /*CStyle*/ true, msg,
   2709                               Kind);
   2710     if (SrcExpr.isInvalid())
   2711       return;
   2712 
   2713     if (tcr == TC_NotApplicable) {
   2714       // ... or if that is not possible, a static_cast, ignoring const and
   2715       // addr space, ...
   2716       tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange, msg, Kind,
   2717                           BasePath, ListInitialization);
   2718       if (SrcExpr.isInvalid())
   2719         return;
   2720 
   2721       if (tcr == TC_NotApplicable) {
   2722         // ... and finally a reinterpret_cast, ignoring const and addr space.
   2723         tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/ true,
   2724                                  OpRange, msg, Kind);
   2725         if (SrcExpr.isInvalid())
   2726           return;
   2727       }
   2728     }
   2729   }
   2730 
   2731   if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
   2732       isValidCast(tcr))
   2733     checkObjCConversion(CCK);
   2734 
   2735   if (tcr != TC_Success && msg != 0) {
   2736     if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
   2737       DeclAccessPair Found;
   2738       FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
   2739                                 DestType,
   2740                                 /*Complain*/ true,
   2741                                 Found);
   2742       if (Fn) {
   2743         // If DestType is a function type (not to be confused with the function
   2744         // pointer type), it will be possible to resolve the function address,
   2745         // but the type cast should be considered as failure.
   2746         OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression;
   2747         Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload)
   2748           << OE->getName() << DestType << OpRange
   2749           << OE->getQualifierLoc().getSourceRange();
   2750         Self.NoteAllOverloadCandidates(SrcExpr.get());
   2751       }
   2752     } else {
   2753       diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
   2754                       OpRange, SrcExpr.get(), DestType, ListInitialization);
   2755     }
   2756   }
   2757 
   2758   if (isValidCast(tcr)) {
   2759     if (Kind == CK_BitCast)
   2760       checkCastAlign();
   2761 
   2762     if (!checkCastFunctionType(Self, SrcExpr, DestType))
   2763       Self.Diag(OpRange.getBegin(), diag::warn_cast_function_type)
   2764           << SrcExpr.get()->getType() << DestType << OpRange;
   2765 
   2766   } else {
   2767     SrcExpr = ExprError();
   2768   }
   2769 }
   2770 
   2771 /// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
   2772 ///  non-matching type. Such as enum function call to int, int call to
   2773 /// pointer; etc. Cast to 'void' is an exception.
   2774 static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
   2775                                   QualType DestType) {
   2776   if (Self.Diags.isIgnored(diag::warn_bad_function_cast,
   2777                            SrcExpr.get()->getExprLoc()))
   2778     return;
   2779 
   2780   if (!isa<CallExpr>(SrcExpr.get()))
   2781     return;
   2782 
   2783   QualType SrcType = SrcExpr.get()->getType();
   2784   if (DestType.getUnqualifiedType()->isVoidType())
   2785     return;
   2786   if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
   2787       && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
   2788     return;
   2789   if (SrcType->isIntegerType() && DestType->isIntegerType() &&
   2790       (SrcType->isBooleanType() == DestType->isBooleanType()) &&
   2791       (SrcType->isEnumeralType() == DestType->isEnumeralType()))
   2792     return;
   2793   if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
   2794     return;
   2795   if (SrcType->isEnumeralType() && DestType->isEnumeralType())
   2796     return;
   2797   if (SrcType->isComplexType() && DestType->isComplexType())
   2798     return;
   2799   if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
   2800     return;
   2801   if (SrcType->isFixedPointType() && DestType->isFixedPointType())
   2802     return;
   2803 
   2804   Self.Diag(SrcExpr.get()->getExprLoc(),
   2805             diag::warn_bad_function_cast)
   2806             << SrcType << DestType << SrcExpr.get()->getSourceRange();
   2807 }
   2808 
   2809 /// Check the semantics of a C-style cast operation, in C.
   2810 void CastOperation::CheckCStyleCast() {
   2811   assert(!Self.getLangOpts().CPlusPlus);
   2812 
   2813   // C-style casts can resolve __unknown_any types.
   2814   if (claimPlaceholder(BuiltinType::UnknownAny)) {
   2815     SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
   2816                                        SrcExpr.get(), Kind,
   2817                                        ValueKind, BasePath);
   2818     return;
   2819   }
   2820 
   2821   // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
   2822   // type needs to be scalar.
   2823   if (DestType->isVoidType()) {
   2824     // We don't necessarily do lvalue-to-rvalue conversions on this.
   2825     SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
   2826     if (SrcExpr.isInvalid())
   2827       return;
   2828 
   2829     // Cast to void allows any expr type.
   2830     Kind = CK_ToVoid;
   2831     return;
   2832   }
   2833 
   2834   // If the type is dependent, we won't do any other semantic analysis now.
   2835   if (Self.getASTContext().isDependenceAllowed() &&
   2836       (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
   2837        SrcExpr.get()->isValueDependent())) {
   2838     assert((DestType->containsErrors() || SrcExpr.get()->containsErrors() ||
   2839             SrcExpr.get()->containsErrors()) &&
   2840            "should only occur in error-recovery path.");
   2841     assert(Kind == CK_Dependent);
   2842     return;
   2843   }
   2844 
   2845   // Overloads are allowed with C extensions, so we need to support them.
   2846   if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
   2847     DeclAccessPair DAP;
   2848     if (FunctionDecl *FD = Self.ResolveAddressOfOverloadedFunction(
   2849             SrcExpr.get(), DestType, /*Complain=*/true, DAP))
   2850       SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr.get(), DAP, FD);
   2851     else
   2852       return;
   2853     assert(SrcExpr.isUsable());
   2854   }
   2855   SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
   2856   if (SrcExpr.isInvalid())
   2857     return;
   2858   QualType SrcType = SrcExpr.get()->getType();
   2859 
   2860   assert(!SrcType->isPlaceholderType());
   2861 
   2862   checkAddressSpaceCast(SrcType, DestType);
   2863   if (SrcExpr.isInvalid())
   2864     return;
   2865 
   2866   if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
   2867                                diag::err_typecheck_cast_to_incomplete)) {
   2868     SrcExpr = ExprError();
   2869     return;
   2870   }
   2871 
   2872   // Allow casting a sizeless built-in type to itself.
   2873   if (DestType->isSizelessBuiltinType() &&
   2874       Self.Context.hasSameUnqualifiedType(DestType, SrcType)) {
   2875     Kind = CK_NoOp;
   2876     return;
   2877   }
   2878 
   2879   // Allow bitcasting between compatible SVE vector types.
   2880   if ((SrcType->isVectorType() || DestType->isVectorType()) &&
   2881       Self.isValidSveBitcast(SrcType, DestType)) {
   2882     Kind = CK_BitCast;
   2883     return;
   2884   }
   2885 
   2886   if (!DestType->isScalarType() && !DestType->isVectorType() &&
   2887       !DestType->isMatrixType()) {
   2888     const RecordType *DestRecordTy = DestType->getAs<RecordType>();
   2889 
   2890     if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
   2891       // GCC struct/union extension: allow cast to self.
   2892       Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
   2893         << DestType << SrcExpr.get()->getSourceRange();
   2894       Kind = CK_NoOp;
   2895       return;
   2896     }
   2897 
   2898     // GCC's cast to union extension.
   2899     if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
   2900       RecordDecl *RD = DestRecordTy->getDecl();
   2901       if (CastExpr::getTargetFieldForToUnionCast(RD, SrcType)) {
   2902         Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
   2903           << SrcExpr.get()->getSourceRange();
   2904         Kind = CK_ToUnion;
   2905         return;
   2906       } else {
   2907         Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
   2908           << SrcType << SrcExpr.get()->getSourceRange();
   2909         SrcExpr = ExprError();
   2910         return;
   2911       }
   2912     }
   2913 
   2914     // OpenCL v2.0 s6.13.10 - Allow casts from '0' to event_t type.
   2915     if (Self.getLangOpts().OpenCL && DestType->isEventT()) {
   2916       Expr::EvalResult Result;
   2917       if (SrcExpr.get()->EvaluateAsInt(Result, Self.Context)) {
   2918         llvm::APSInt CastInt = Result.Val.getInt();
   2919         if (0 == CastInt) {
   2920           Kind = CK_ZeroToOCLOpaqueType;
   2921           return;
   2922         }
   2923         Self.Diag(OpRange.getBegin(),
   2924                   diag::err_opencl_cast_non_zero_to_event_t)
   2925                   << CastInt.toString(10) << SrcExpr.get()->getSourceRange();
   2926         SrcExpr = ExprError();
   2927         return;
   2928       }
   2929     }
   2930 
   2931     // Reject any other conversions to non-scalar types.
   2932     Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
   2933       << DestType << SrcExpr.get()->getSourceRange();
   2934     SrcExpr = ExprError();
   2935     return;
   2936   }
   2937 
   2938   // The type we're casting to is known to be a scalar, a vector, or a matrix.
   2939 
   2940   // Require the operand to be a scalar, a vector, or a matrix.
   2941   if (!SrcType->isScalarType() && !SrcType->isVectorType() &&
   2942       !SrcType->isMatrixType()) {
   2943     Self.Diag(SrcExpr.get()->getExprLoc(),
   2944               diag::err_typecheck_expect_scalar_operand)
   2945       << SrcType << SrcExpr.get()->getSourceRange();
   2946     SrcExpr = ExprError();
   2947     return;
   2948   }
   2949 
   2950   if (DestType->isExtVectorType()) {
   2951     SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind);
   2952     return;
   2953   }
   2954 
   2955   if (DestType->getAs<MatrixType>() || SrcType->getAs<MatrixType>()) {
   2956     if (Self.CheckMatrixCast(OpRange, DestType, SrcType, Kind))
   2957       SrcExpr = ExprError();
   2958     return;
   2959   }
   2960 
   2961   if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
   2962     if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
   2963           (SrcType->isIntegerType() || SrcType->isFloatingType())) {
   2964       Kind = CK_VectorSplat;
   2965       SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
   2966     } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
   2967       SrcExpr = ExprError();
   2968     }
   2969     return;
   2970   }
   2971 
   2972   if (SrcType->isVectorType()) {
   2973     if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
   2974       SrcExpr = ExprError();
   2975     return;
   2976   }
   2977 
   2978   // The source and target types are both scalars, i.e.
   2979   //   - arithmetic types (fundamental, enum, and complex)
   2980   //   - all kinds of pointers
   2981   // Note that member pointers were filtered out with C++, above.
   2982 
   2983   if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
   2984     Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
   2985     SrcExpr = ExprError();
   2986     return;
   2987   }
   2988 
   2989   // Can't cast to or from bfloat
   2990   if (DestType->isBFloat16Type() && !SrcType->isBFloat16Type()) {
   2991     Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_to_bfloat16)
   2992         << SrcExpr.get()->getSourceRange();
   2993     SrcExpr = ExprError();
   2994     return;
   2995   }
   2996   if (SrcType->isBFloat16Type() && !DestType->isBFloat16Type()) {
   2997     Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_from_bfloat16)
   2998         << SrcExpr.get()->getSourceRange();
   2999     SrcExpr = ExprError();
   3000     return;
   3001   }
   3002 
   3003   // If either type is a pointer, the other type has to be either an
   3004   // integer or a pointer.
   3005   if (!DestType->isArithmeticType()) {
   3006     if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
   3007       Self.Diag(SrcExpr.get()->getExprLoc(),
   3008                 diag::err_cast_pointer_from_non_pointer_int)
   3009         << SrcType << SrcExpr.get()->getSourceRange();
   3010       SrcExpr = ExprError();
   3011       return;
   3012     }
   3013     checkIntToPointerCast(/* CStyle */ true, OpRange, SrcExpr.get(), DestType,
   3014                           Self);
   3015   } else if (!SrcType->isArithmeticType()) {
   3016     if (!DestType->isIntegralType(Self.Context) &&
   3017         DestType->isArithmeticType()) {
   3018       Self.Diag(SrcExpr.get()->getBeginLoc(),
   3019                 diag::err_cast_pointer_to_non_pointer_int)
   3020           << DestType << SrcExpr.get()->getSourceRange();
   3021       SrcExpr = ExprError();
   3022       return;
   3023     }
   3024 
   3025     if ((Self.Context.getTypeSize(SrcType) >
   3026          Self.Context.getTypeSize(DestType)) &&
   3027         !DestType->isBooleanType()) {
   3028       // C 6.3.2.3p6: Any pointer type may be converted to an integer type.
   3029       // Except as previously specified, the result is implementation-defined.
   3030       // If the result cannot be represented in the integer type, the behavior
   3031       // is undefined. The result need not be in the range of values of any
   3032       // integer type.
   3033       unsigned Diag;
   3034       if (SrcType->isVoidPointerType())
   3035         Diag = DestType->isEnumeralType() ? diag::warn_void_pointer_to_enum_cast
   3036                                           : diag::warn_void_pointer_to_int_cast;
   3037       else if (DestType->isEnumeralType())
   3038         Diag = diag::warn_pointer_to_enum_cast;
   3039       else
   3040         Diag = diag::warn_pointer_to_int_cast;
   3041       Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange;
   3042     }
   3043   }
   3044 
   3045   if (Self.getLangOpts().OpenCL && !Self.getOpenCLOptions().isAvailableOption(
   3046                                        "cl_khr_fp16", Self.getLangOpts())) {
   3047     if (DestType->isHalfType()) {
   3048       Self.Diag(SrcExpr.get()->getBeginLoc(), diag::err_opencl_cast_to_half)
   3049           << DestType << SrcExpr.get()->getSourceRange();
   3050       SrcExpr = ExprError();
   3051       return;
   3052     }
   3053   }
   3054 
   3055   // ARC imposes extra restrictions on casts.
   3056   if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) {
   3057     checkObjCConversion(Sema::CCK_CStyleCast);
   3058     if (SrcExpr.isInvalid())
   3059       return;
   3060 
   3061     const PointerType *CastPtr = DestType->getAs<PointerType>();
   3062     if (Self.getLangOpts().ObjCAutoRefCount && CastPtr) {
   3063       if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
   3064         Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
   3065         Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
   3066         if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
   3067             ExprPtr->getPointeeType()->isObjCLifetimeType() &&
   3068             !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
   3069           Self.Diag(SrcExpr.get()->getBeginLoc(),
   3070                     diag::err_typecheck_incompatible_ownership)
   3071               << SrcType << DestType << Sema::AA_Casting
   3072               << SrcExpr.get()->getSourceRange();
   3073           return;
   3074         }
   3075       }
   3076     }
   3077     else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
   3078       Self.Diag(SrcExpr.get()->getBeginLoc(),
   3079                 diag::err_arc_convesion_of_weak_unavailable)
   3080           << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
   3081       SrcExpr = ExprError();
   3082       return;
   3083     }
   3084   }
   3085 
   3086   if (!checkCastFunctionType(Self, SrcExpr, DestType))
   3087     Self.Diag(OpRange.getBegin(), diag::warn_cast_function_type)
   3088         << SrcType << DestType << OpRange;
   3089 
   3090   DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
   3091   DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
   3092   DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
   3093   Kind = Self.PrepareScalarCast(SrcExpr, DestType);
   3094   if (SrcExpr.isInvalid())
   3095     return;
   3096 
   3097   if (Kind == CK_BitCast)
   3098     checkCastAlign();
   3099 }
   3100 
   3101 void CastOperation::CheckBuiltinBitCast() {
   3102   QualType SrcType = SrcExpr.get()->getType();
   3103 
   3104   if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
   3105                                diag::err_typecheck_cast_to_incomplete) ||
   3106       Self.RequireCompleteType(OpRange.getBegin(), SrcType,
   3107                                diag::err_incomplete_type)) {
   3108     SrcExpr = ExprError();
   3109     return;
   3110   }
   3111 
   3112   if (SrcExpr.get()->isRValue())
   3113     SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcType, SrcExpr.get(),
   3114                                                   /*IsLValueReference=*/false);
   3115 
   3116   CharUnits DestSize = Self.Context.getTypeSizeInChars(DestType);
   3117   CharUnits SourceSize = Self.Context.getTypeSizeInChars(SrcType);
   3118   if (DestSize != SourceSize) {
   3119     Self.Diag(OpRange.getBegin(), diag::err_bit_cast_type_size_mismatch)
   3120         << (int)SourceSize.getQuantity() << (int)DestSize.getQuantity();
   3121     SrcExpr = ExprError();
   3122     return;
   3123   }
   3124 
   3125   if (!DestType.isTriviallyCopyableType(Self.Context)) {
   3126     Self.Diag(OpRange.getBegin(), diag::err_bit_cast_non_trivially_copyable)
   3127         << 1;
   3128     SrcExpr = ExprError();
   3129     return;
   3130   }
   3131 
   3132   if (!SrcType.isTriviallyCopyableType(Self.Context)) {
   3133     Self.Diag(OpRange.getBegin(), diag::err_bit_cast_non_trivially_copyable)
   3134         << 0;
   3135     SrcExpr = ExprError();
   3136     return;
   3137   }
   3138 
   3139   Kind = CK_LValueToRValueBitCast;
   3140 }
   3141 
   3142 /// DiagnoseCastQual - Warn whenever casts discards a qualifiers, be it either
   3143 /// const, volatile or both.
   3144 static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
   3145                              QualType DestType) {
   3146   if (SrcExpr.isInvalid())
   3147     return;
   3148 
   3149   QualType SrcType = SrcExpr.get()->getType();
   3150   if (!((SrcType->isAnyPointerType() && DestType->isAnyPointerType()) ||
   3151         DestType->isLValueReferenceType()))
   3152     return;
   3153 
   3154   QualType TheOffendingSrcType, TheOffendingDestType;
   3155   Qualifiers CastAwayQualifiers;
   3156   if (CastsAwayConstness(Self, SrcType, DestType, true, false,
   3157                          &TheOffendingSrcType, &TheOffendingDestType,
   3158                          &CastAwayQualifiers) !=
   3159       CastAwayConstnessKind::CACK_Similar)
   3160     return;
   3161 
   3162   // FIXME: 'restrict' is not properly handled here.
   3163   int qualifiers = -1;
   3164   if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) {
   3165     qualifiers = 0;
   3166   } else if (CastAwayQualifiers.hasConst()) {
   3167     qualifiers = 1;
   3168   } else if (CastAwayQualifiers.hasVolatile()) {
   3169     qualifiers = 2;
   3170   }
   3171   // This is a variant of int **x; const int **y = (const int **)x;
   3172   if (qualifiers == -1)
   3173     Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual2)
   3174         << SrcType << DestType;
   3175   else
   3176     Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual)
   3177         << TheOffendingSrcType << TheOffendingDestType << qualifiers;
   3178 }
   3179 
   3180 ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
   3181                                      TypeSourceInfo *CastTypeInfo,
   3182                                      SourceLocation RPLoc,
   3183                                      Expr *CastExpr) {
   3184   CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
   3185   Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
   3186   Op.OpRange = SourceRange(LPLoc, CastExpr->getEndLoc());
   3187 
   3188   if (getLangOpts().CPlusPlus) {
   3189     Op.CheckCXXCStyleCast(/*FunctionalCast=*/ false,
   3190                           isa<InitListExpr>(CastExpr));
   3191   } else {
   3192     Op.CheckCStyleCast();
   3193   }
   3194 
   3195   if (Op.SrcExpr.isInvalid())
   3196     return ExprError();
   3197 
   3198   // -Wcast-qual
   3199   DiagnoseCastQual(Op.Self, Op.SrcExpr, Op.DestType);
   3200 
   3201   return Op.complete(CStyleCastExpr::Create(
   3202       Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
   3203       &Op.BasePath, CurFPFeatureOverrides(), CastTypeInfo, LPLoc, RPLoc));
   3204 }
   3205 
   3206 ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
   3207                                             QualType Type,
   3208                                             SourceLocation LPLoc,
   3209                                             Expr *CastExpr,
   3210                                             SourceLocation RPLoc) {
   3211   assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
   3212   CastOperation Op(*this, Type, CastExpr);
   3213   Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
   3214   Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getEndLoc());
   3215 
   3216   Op.CheckCXXCStyleCast(/*FunctionalCast=*/true, /*ListInit=*/false);
   3217   if (Op.SrcExpr.isInvalid())
   3218     return ExprError();
   3219 
   3220   auto *SubExpr = Op.SrcExpr.get();
   3221   if (auto *BindExpr = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
   3222     SubExpr = BindExpr->getSubExpr();
   3223   if (auto *ConstructExpr = dyn_cast<CXXConstructExpr>(SubExpr))
   3224     ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc));
   3225 
   3226   return Op.complete(CXXFunctionalCastExpr::Create(
   3227       Context, Op.ResultType, Op.ValueKind, CastTypeInfo, Op.Kind,
   3228       Op.SrcExpr.get(), &Op.BasePath, CurFPFeatureOverrides(), LPLoc, RPLoc));
   3229 }
   3230