Path: blob/main/contrib/llvm-project/clang/lib/Sema/SemaCast.cpp
35233 views
//===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements semantic analysis for cast expressions, including9// 1) C-style casts like '(int) x'10// 2) C++ functional casts like 'int(x)'11// 3) C++ named casts like 'static_cast<int>(x)'12//13//===----------------------------------------------------------------------===//1415#include "clang/AST/ASTContext.h"16#include "clang/AST/ASTStructuralEquivalence.h"17#include "clang/AST/CXXInheritance.h"18#include "clang/AST/ExprCXX.h"19#include "clang/AST/ExprObjC.h"20#include "clang/AST/RecordLayout.h"21#include "clang/Basic/PartialDiagnostic.h"22#include "clang/Basic/TargetInfo.h"23#include "clang/Lex/Preprocessor.h"24#include "clang/Sema/Initialization.h"25#include "clang/Sema/SemaInternal.h"26#include "clang/Sema/SemaObjC.h"27#include "clang/Sema/SemaRISCV.h"28#include "llvm/ADT/SmallVector.h"29#include "llvm/ADT/StringExtras.h"30#include <set>31using namespace clang;32333435enum TryCastResult {36TC_NotApplicable, ///< The cast method is not applicable.37TC_Success, ///< The cast method is appropriate and successful.38TC_Extension, ///< The cast method is appropriate and accepted as a39///< language extension.40TC_Failed ///< The cast method is appropriate, but failed. A41///< diagnostic has been emitted.42};4344static bool isValidCast(TryCastResult TCR) {45return TCR == TC_Success || TCR == TC_Extension;46}4748enum CastType {49CT_Const, ///< const_cast50CT_Static, ///< static_cast51CT_Reinterpret, ///< reinterpret_cast52CT_Dynamic, ///< dynamic_cast53CT_CStyle, ///< (Type)expr54CT_Functional, ///< Type(expr)55CT_Addrspace ///< addrspace_cast56};5758namespace {59struct CastOperation {60CastOperation(Sema &S, QualType destType, ExprResult src)61: Self(S), SrcExpr(src), DestType(destType),62ResultType(destType.getNonLValueExprType(S.Context)),63ValueKind(Expr::getValueKindForType(destType)),64Kind(CK_Dependent), IsARCUnbridgedCast(false) {6566// C++ [expr.type]/8.2.2:67// If a pr-value initially has the type cv-T, where T is a68// cv-unqualified non-class, non-array type, the type of the69// expression is adjusted to T prior to any further analysis.70// C23 6.5.4p6:71// Preceding an expression by a parenthesized type name converts the72// value of the expression to the unqualified, non-atomic version of73// the named type.74if (!S.Context.getLangOpts().ObjC && !DestType->isRecordType() &&75!DestType->isArrayType()) {76DestType = DestType.getAtomicUnqualifiedType();77}7879if (const BuiltinType *placeholder =80src.get()->getType()->getAsPlaceholderType()) {81PlaceholderKind = placeholder->getKind();82} else {83PlaceholderKind = (BuiltinType::Kind) 0;84}85}8687Sema &Self;88ExprResult SrcExpr;89QualType DestType;90QualType ResultType;91ExprValueKind ValueKind;92CastKind Kind;93BuiltinType::Kind PlaceholderKind;94CXXCastPath BasePath;95bool IsARCUnbridgedCast;9697SourceRange OpRange;98SourceRange DestRange;99100// Top-level semantics-checking routines.101void CheckConstCast();102void CheckReinterpretCast();103void CheckStaticCast();104void CheckDynamicCast();105void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);106void CheckCStyleCast();107void CheckBuiltinBitCast();108void CheckAddrspaceCast();109110void updatePartOfExplicitCastFlags(CastExpr *CE) {111// Walk down from the CE to the OrigSrcExpr, and mark all immediate112// ImplicitCastExpr's as being part of ExplicitCastExpr. The original CE113// (which is a ExplicitCastExpr), and the OrigSrcExpr are not touched.114for (; auto *ICE = dyn_cast<ImplicitCastExpr>(CE->getSubExpr()); CE = ICE)115ICE->setIsPartOfExplicitCast(true);116}117118/// Complete an apparently-successful cast operation that yields119/// the given expression.120ExprResult complete(CastExpr *castExpr) {121// If this is an unbridged cast, wrap the result in an implicit122// cast that yields the unbridged-cast placeholder type.123if (IsARCUnbridgedCast) {124castExpr = ImplicitCastExpr::Create(125Self.Context, Self.Context.ARCUnbridgedCastTy, CK_Dependent,126castExpr, nullptr, castExpr->getValueKind(),127Self.CurFPFeatureOverrides());128}129updatePartOfExplicitCastFlags(castExpr);130return castExpr;131}132133// Internal convenience methods.134135/// Try to handle the given placeholder expression kind. Return136/// true if the source expression has the appropriate placeholder137/// kind. A placeholder can only be claimed once.138bool claimPlaceholder(BuiltinType::Kind K) {139if (PlaceholderKind != K) return false;140141PlaceholderKind = (BuiltinType::Kind) 0;142return true;143}144145bool isPlaceholder() const {146return PlaceholderKind != 0;147}148bool isPlaceholder(BuiltinType::Kind K) const {149return PlaceholderKind == K;150}151152// Language specific cast restrictions for address spaces.153void checkAddressSpaceCast(QualType SrcType, QualType DestType);154155void checkCastAlign() {156Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);157}158159void checkObjCConversion(CheckedConversionKind CCK) {160assert(Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers());161162Expr *src = SrcExpr.get();163if (Self.ObjC().CheckObjCConversion(OpRange, DestType, src, CCK) ==164SemaObjC::ACR_unbridged)165IsARCUnbridgedCast = true;166SrcExpr = src;167}168169/// Check for and handle non-overload placeholder expressions.170void checkNonOverloadPlaceholders() {171if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))172return;173174SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());175if (SrcExpr.isInvalid())176return;177PlaceholderKind = (BuiltinType::Kind) 0;178}179};180181void CheckNoDeref(Sema &S, const QualType FromType, const QualType ToType,182SourceLocation OpLoc) {183if (const auto *PtrType = dyn_cast<PointerType>(FromType)) {184if (PtrType->getPointeeType()->hasAttr(attr::NoDeref)) {185if (const auto *DestType = dyn_cast<PointerType>(ToType)) {186if (!DestType->getPointeeType()->hasAttr(attr::NoDeref)) {187S.Diag(OpLoc, diag::warn_noderef_to_dereferenceable_pointer);188}189}190}191}192}193194struct CheckNoDerefRAII {195CheckNoDerefRAII(CastOperation &Op) : Op(Op) {}196~CheckNoDerefRAII() {197if (!Op.SrcExpr.isInvalid())198CheckNoDeref(Op.Self, Op.SrcExpr.get()->getType(), Op.ResultType,199Op.OpRange.getBegin());200}201202CastOperation &Op;203};204}205206static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,207QualType DestType);208209// The Try functions attempt a specific way of casting. If they succeed, they210// return TC_Success. If their way of casting is not appropriate for the given211// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic212// to emit if no other way succeeds. If their way of casting is appropriate but213// fails, they return TC_Failed and *must* set diag; they can set it to 0 if214// they emit a specialized diagnostic.215// All diagnostics returned by these functions must expect the same three216// arguments:217// %0: Cast Type (a value from the CastType enumeration)218// %1: Source Type219// %2: Destination Type220static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,221QualType DestType, bool CStyle,222CastKind &Kind,223CXXCastPath &BasePath,224unsigned &msg);225static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,226QualType DestType, bool CStyle,227SourceRange OpRange,228unsigned &msg,229CastKind &Kind,230CXXCastPath &BasePath);231static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,232QualType DestType, bool CStyle,233SourceRange OpRange,234unsigned &msg,235CastKind &Kind,236CXXCastPath &BasePath);237static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,238CanQualType DestType, bool CStyle,239SourceRange OpRange,240QualType OrigSrcType,241QualType OrigDestType, unsigned &msg,242CastKind &Kind,243CXXCastPath &BasePath);244static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,245QualType SrcType,246QualType DestType,bool CStyle,247SourceRange OpRange,248unsigned &msg,249CastKind &Kind,250CXXCastPath &BasePath);251252static TryCastResult253TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,254CheckedConversionKind CCK, SourceRange OpRange,255unsigned &msg, CastKind &Kind, bool ListInitialization);256static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,257QualType DestType, CheckedConversionKind CCK,258SourceRange OpRange, unsigned &msg,259CastKind &Kind, CXXCastPath &BasePath,260bool ListInitialization);261static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,262QualType DestType, bool CStyle,263unsigned &msg);264static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,265QualType DestType, bool CStyle,266SourceRange OpRange, unsigned &msg,267CastKind &Kind);268static TryCastResult TryAddressSpaceCast(Sema &Self, ExprResult &SrcExpr,269QualType DestType, bool CStyle,270unsigned &msg, CastKind &Kind);271272ExprResult273Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,274SourceLocation LAngleBracketLoc, Declarator &D,275SourceLocation RAngleBracketLoc,276SourceLocation LParenLoc, Expr *E,277SourceLocation RParenLoc) {278279assert(!D.isInvalidType());280281TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());282if (D.isInvalidType())283return ExprError();284285if (getLangOpts().CPlusPlus) {286// Check that there are no default arguments (C++ only).287CheckExtraCXXDefaultArguments(D);288}289290return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,291SourceRange(LAngleBracketLoc, RAngleBracketLoc),292SourceRange(LParenLoc, RParenLoc));293}294295ExprResult296Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,297TypeSourceInfo *DestTInfo, Expr *E,298SourceRange AngleBrackets, SourceRange Parens) {299ExprResult Ex = E;300QualType DestType = DestTInfo->getType();301302// If the type is dependent, we won't do the semantic analysis now.303bool TypeDependent =304DestType->isDependentType() || Ex.get()->isTypeDependent();305306CastOperation Op(*this, DestType, E);307Op.OpRange = SourceRange(OpLoc, Parens.getEnd());308Op.DestRange = AngleBrackets;309310switch (Kind) {311default: llvm_unreachable("Unknown C++ cast!");312313case tok::kw_addrspace_cast:314if (!TypeDependent) {315Op.CheckAddrspaceCast();316if (Op.SrcExpr.isInvalid())317return ExprError();318}319return Op.complete(CXXAddrspaceCastExpr::Create(320Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(),321DestTInfo, OpLoc, Parens.getEnd(), AngleBrackets));322323case tok::kw_const_cast:324if (!TypeDependent) {325Op.CheckConstCast();326if (Op.SrcExpr.isInvalid())327return ExprError();328DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);329}330return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,331Op.ValueKind, Op.SrcExpr.get(), DestTInfo,332OpLoc, Parens.getEnd(),333AngleBrackets));334335case tok::kw_dynamic_cast: {336// dynamic_cast is not supported in C++ for OpenCL.337if (getLangOpts().OpenCLCPlusPlus) {338return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)339<< "dynamic_cast");340}341342if (!TypeDependent) {343Op.CheckDynamicCast();344if (Op.SrcExpr.isInvalid())345return ExprError();346}347return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,348Op.ValueKind, Op.Kind, Op.SrcExpr.get(),349&Op.BasePath, DestTInfo,350OpLoc, Parens.getEnd(),351AngleBrackets));352}353case tok::kw_reinterpret_cast: {354if (!TypeDependent) {355Op.CheckReinterpretCast();356if (Op.SrcExpr.isInvalid())357return ExprError();358DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);359}360return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,361Op.ValueKind, Op.Kind, Op.SrcExpr.get(),362nullptr, DestTInfo, OpLoc,363Parens.getEnd(),364AngleBrackets));365}366case tok::kw_static_cast: {367if (!TypeDependent) {368Op.CheckStaticCast();369if (Op.SrcExpr.isInvalid())370return ExprError();371DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);372}373374return Op.complete(CXXStaticCastExpr::Create(375Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(),376&Op.BasePath, DestTInfo, CurFPFeatureOverrides(), OpLoc,377Parens.getEnd(), AngleBrackets));378}379}380}381382ExprResult Sema::ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &D,383ExprResult Operand,384SourceLocation RParenLoc) {385assert(!D.isInvalidType());386387TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, Operand.get()->getType());388if (D.isInvalidType())389return ExprError();390391return BuildBuiltinBitCastExpr(KWLoc, TInfo, Operand.get(), RParenLoc);392}393394ExprResult Sema::BuildBuiltinBitCastExpr(SourceLocation KWLoc,395TypeSourceInfo *TSI, Expr *Operand,396SourceLocation RParenLoc) {397CastOperation Op(*this, TSI->getType(), Operand);398Op.OpRange = SourceRange(KWLoc, RParenLoc);399TypeLoc TL = TSI->getTypeLoc();400Op.DestRange = SourceRange(TL.getBeginLoc(), TL.getEndLoc());401402if (!Operand->isTypeDependent() && !TSI->getType()->isDependentType()) {403Op.CheckBuiltinBitCast();404if (Op.SrcExpr.isInvalid())405return ExprError();406}407408BuiltinBitCastExpr *BCE =409new (Context) BuiltinBitCastExpr(Op.ResultType, Op.ValueKind, Op.Kind,410Op.SrcExpr.get(), TSI, KWLoc, RParenLoc);411return Op.complete(BCE);412}413414/// Try to diagnose a failed overloaded cast. Returns true if415/// diagnostics were emitted.416static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,417SourceRange range, Expr *src,418QualType destType,419bool listInitialization) {420switch (CT) {421// These cast kinds don't consider user-defined conversions.422case CT_Const:423case CT_Reinterpret:424case CT_Dynamic:425case CT_Addrspace:426return false;427428// These do.429case CT_Static:430case CT_CStyle:431case CT_Functional:432break;433}434435QualType srcType = src->getType();436if (!destType->isRecordType() && !srcType->isRecordType())437return false;438439InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);440InitializationKind initKind441= (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),442range, listInitialization)443: (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,444listInitialization)445: InitializationKind::CreateCast(/*type range?*/ range);446InitializationSequence sequence(S, entity, initKind, src);447448assert(sequence.Failed() && "initialization succeeded on second try?");449switch (sequence.getFailureKind()) {450default: return false;451452case InitializationSequence::FK_ParenthesizedListInitFailed:453// In C++20, if the underlying destination type is a RecordType, Clang454// attempts to perform parentesized aggregate initialization if constructor455// overload fails:456//457// C++20 [expr.static.cast]p4:458// An expression E can be explicitly converted to a type T...if overload459// resolution for a direct-initialization...would find at least one viable460// function ([over.match.viable]), or if T is an aggregate type having a461// first element X and there is an implicit conversion sequence from E to462// the type of X.463//464// If that fails, then we'll generate the diagnostics from the failed465// previous constructor overload attempt. Array initialization, however, is466// not done after attempting constructor overloading, so we exit as there467// won't be a failed overload result.468if (destType->isArrayType())469return false;470break;471case InitializationSequence::FK_ConstructorOverloadFailed:472case InitializationSequence::FK_UserConversionOverloadFailed:473break;474}475476OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();477478unsigned msg = 0;479OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;480481switch (sequence.getFailedOverloadResult()) {482case OR_Success: llvm_unreachable("successful failed overload");483case OR_No_Viable_Function:484if (candidates.empty())485msg = diag::err_ovl_no_conversion_in_cast;486else487msg = diag::err_ovl_no_viable_conversion_in_cast;488howManyCandidates = OCD_AllCandidates;489break;490491case OR_Ambiguous:492msg = diag::err_ovl_ambiguous_conversion_in_cast;493howManyCandidates = OCD_AmbiguousCandidates;494break;495496case OR_Deleted: {497OverloadCandidateSet::iterator Best;498[[maybe_unused]] OverloadingResult Res =499candidates.BestViableFunction(S, range.getBegin(), Best);500assert(Res == OR_Deleted && "Inconsistent overload resolution");501502StringLiteral *Msg = Best->Function->getDeletedMessage();503candidates.NoteCandidates(504PartialDiagnosticAt(range.getBegin(),505S.PDiag(diag::err_ovl_deleted_conversion_in_cast)506<< CT << srcType << destType << (Msg != nullptr)507<< (Msg ? Msg->getString() : StringRef())508<< range << src->getSourceRange()),509S, OCD_ViableCandidates, src);510return true;511}512}513514candidates.NoteCandidates(515PartialDiagnosticAt(range.getBegin(),516S.PDiag(msg) << CT << srcType << destType << range517<< src->getSourceRange()),518S, howManyCandidates, src);519520return true;521}522523/// Diagnose a failed cast.524static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,525SourceRange opRange, Expr *src, QualType destType,526bool listInitialization) {527if (msg == diag::err_bad_cxx_cast_generic &&528tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,529listInitialization))530return;531532S.Diag(opRange.getBegin(), msg) << castType533<< src->getType() << destType << opRange << src->getSourceRange();534535// Detect if both types are (ptr to) class, and note any incompleteness.536int DifferentPtrness = 0;537QualType From = destType;538if (auto Ptr = From->getAs<PointerType>()) {539From = Ptr->getPointeeType();540DifferentPtrness++;541}542QualType To = src->getType();543if (auto Ptr = To->getAs<PointerType>()) {544To = Ptr->getPointeeType();545DifferentPtrness--;546}547if (!DifferentPtrness) {548auto RecFrom = From->getAs<RecordType>();549auto RecTo = To->getAs<RecordType>();550if (RecFrom && RecTo) {551auto DeclFrom = RecFrom->getAsCXXRecordDecl();552if (!DeclFrom->isCompleteDefinition())553S.Diag(DeclFrom->getLocation(), diag::note_type_incomplete) << DeclFrom;554auto DeclTo = RecTo->getAsCXXRecordDecl();555if (!DeclTo->isCompleteDefinition())556S.Diag(DeclTo->getLocation(), diag::note_type_incomplete) << DeclTo;557}558}559}560561namespace {562/// The kind of unwrapping we did when determining whether a conversion casts563/// away constness.564enum CastAwayConstnessKind {565/// The conversion does not cast away constness.566CACK_None = 0,567/// We unwrapped similar types.568CACK_Similar = 1,569/// We unwrapped dissimilar types with similar representations (eg, a pointer570/// versus an Objective-C object pointer).571CACK_SimilarKind = 2,572/// We unwrapped representationally-unrelated types, such as a pointer versus573/// a pointer-to-member.574CACK_Incoherent = 3,575};576}577578/// Unwrap one level of types for CastsAwayConstness.579///580/// Like Sema::UnwrapSimilarTypes, this removes one level of indirection from581/// both types, provided that they're both pointer-like or array-like. Unlike582/// the Sema function, doesn't care if the unwrapped pieces are related.583///584/// This function may remove additional levels as necessary for correctness:585/// the resulting T1 is unwrapped sufficiently that it is never an array type,586/// so that its qualifiers can be directly compared to those of T2 (which will587/// have the combined set of qualifiers from all indermediate levels of T2),588/// as (effectively) required by [expr.const.cast]p7 replacing T1's qualifiers589/// with those from T2.590static CastAwayConstnessKind591unwrapCastAwayConstnessLevel(ASTContext &Context, QualType &T1, QualType &T2) {592enum { None, Ptr, MemPtr, BlockPtr, Array };593auto Classify = [](QualType T) {594if (T->isAnyPointerType()) return Ptr;595if (T->isMemberPointerType()) return MemPtr;596if (T->isBlockPointerType()) return BlockPtr;597// We somewhat-arbitrarily don't look through VLA types here. This is at598// least consistent with the behavior of UnwrapSimilarTypes.599if (T->isConstantArrayType() || T->isIncompleteArrayType()) return Array;600return None;601};602603auto Unwrap = [&](QualType T) {604if (auto *AT = Context.getAsArrayType(T))605return AT->getElementType();606return T->getPointeeType();607};608609CastAwayConstnessKind Kind;610611if (T2->isReferenceType()) {612// Special case: if the destination type is a reference type, unwrap it as613// the first level. (The source will have been an lvalue expression in this614// case, so there is no corresponding "reference to" in T1 to remove.) This615// simulates removing a "pointer to" from both sides.616T2 = T2->getPointeeType();617Kind = CastAwayConstnessKind::CACK_Similar;618} else if (Context.UnwrapSimilarTypes(T1, T2)) {619Kind = CastAwayConstnessKind::CACK_Similar;620} else {621// Try unwrapping mismatching levels.622int T1Class = Classify(T1);623if (T1Class == None)624return CastAwayConstnessKind::CACK_None;625626int T2Class = Classify(T2);627if (T2Class == None)628return CastAwayConstnessKind::CACK_None;629630T1 = Unwrap(T1);631T2 = Unwrap(T2);632Kind = T1Class == T2Class ? CastAwayConstnessKind::CACK_SimilarKind633: CastAwayConstnessKind::CACK_Incoherent;634}635636// We've unwrapped at least one level. If the resulting T1 is a (possibly637// multidimensional) array type, any qualifier on any matching layer of638// T2 is considered to correspond to T1. Decompose down to the element639// type of T1 so that we can compare properly.640while (true) {641Context.UnwrapSimilarArrayTypes(T1, T2);642643if (Classify(T1) != Array)644break;645646auto T2Class = Classify(T2);647if (T2Class == None)648break;649650if (T2Class != Array)651Kind = CastAwayConstnessKind::CACK_Incoherent;652else if (Kind != CastAwayConstnessKind::CACK_Incoherent)653Kind = CastAwayConstnessKind::CACK_SimilarKind;654655T1 = Unwrap(T1);656T2 = Unwrap(T2).withCVRQualifiers(T2.getCVRQualifiers());657}658659return Kind;660}661662/// Check if the pointer conversion from SrcType to DestType casts away663/// constness as defined in C++ [expr.const.cast]. This is used by the cast664/// checkers. Both arguments must denote pointer (possibly to member) types.665///666/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.667/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.668static CastAwayConstnessKind669CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,670bool CheckCVR, bool CheckObjCLifetime,671QualType *TheOffendingSrcType = nullptr,672QualType *TheOffendingDestType = nullptr,673Qualifiers *CastAwayQualifiers = nullptr) {674// If the only checking we care about is for Objective-C lifetime qualifiers,675// and we're not in ObjC mode, there's nothing to check.676if (!CheckCVR && CheckObjCLifetime && !Self.Context.getLangOpts().ObjC)677return CastAwayConstnessKind::CACK_None;678679if (!DestType->isReferenceType()) {680assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||681SrcType->isBlockPointerType()) &&682"Source type is not pointer or pointer to member.");683assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||684DestType->isBlockPointerType()) &&685"Destination type is not pointer or pointer to member.");686}687688QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),689UnwrappedDestType = Self.Context.getCanonicalType(DestType);690691// Find the qualifiers. We only care about cvr-qualifiers for the692// purpose of this check, because other qualifiers (address spaces,693// Objective-C GC, etc.) are part of the type's identity.694QualType PrevUnwrappedSrcType = UnwrappedSrcType;695QualType PrevUnwrappedDestType = UnwrappedDestType;696auto WorstKind = CastAwayConstnessKind::CACK_Similar;697bool AllConstSoFar = true;698while (auto Kind = unwrapCastAwayConstnessLevel(699Self.Context, UnwrappedSrcType, UnwrappedDestType)) {700// Track the worst kind of unwrap we needed to do before we found a701// problem.702if (Kind > WorstKind)703WorstKind = Kind;704705// Determine the relevant qualifiers at this level.706Qualifiers SrcQuals, DestQuals;707Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);708Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);709710// We do not meaningfully track object const-ness of Objective-C object711// types. Remove const from the source type if either the source or712// the destination is an Objective-C object type.713if (UnwrappedSrcType->isObjCObjectType() ||714UnwrappedDestType->isObjCObjectType())715SrcQuals.removeConst();716717if (CheckCVR) {718Qualifiers SrcCvrQuals =719Qualifiers::fromCVRMask(SrcQuals.getCVRQualifiers());720Qualifiers DestCvrQuals =721Qualifiers::fromCVRMask(DestQuals.getCVRQualifiers());722723if (SrcCvrQuals != DestCvrQuals) {724if (CastAwayQualifiers)725*CastAwayQualifiers = SrcCvrQuals - DestCvrQuals;726727// If we removed a cvr-qualifier, this is casting away 'constness'.728if (!DestCvrQuals.compatiblyIncludes(SrcCvrQuals)) {729if (TheOffendingSrcType)730*TheOffendingSrcType = PrevUnwrappedSrcType;731if (TheOffendingDestType)732*TheOffendingDestType = PrevUnwrappedDestType;733return WorstKind;734}735736// If any prior level was not 'const', this is also casting away737// 'constness'. We noted the outermost type missing a 'const' already.738if (!AllConstSoFar)739return WorstKind;740}741}742743if (CheckObjCLifetime &&744!DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))745return WorstKind;746747// If we found our first non-const-qualified type, this may be the place748// where things start to go wrong.749if (AllConstSoFar && !DestQuals.hasConst()) {750AllConstSoFar = false;751if (TheOffendingSrcType)752*TheOffendingSrcType = PrevUnwrappedSrcType;753if (TheOffendingDestType)754*TheOffendingDestType = PrevUnwrappedDestType;755}756757PrevUnwrappedSrcType = UnwrappedSrcType;758PrevUnwrappedDestType = UnwrappedDestType;759}760761return CastAwayConstnessKind::CACK_None;762}763764static TryCastResult getCastAwayConstnessCastKind(CastAwayConstnessKind CACK,765unsigned &DiagID) {766switch (CACK) {767case CastAwayConstnessKind::CACK_None:768llvm_unreachable("did not cast away constness");769770case CastAwayConstnessKind::CACK_Similar:771// FIXME: Accept these as an extension too?772case CastAwayConstnessKind::CACK_SimilarKind:773DiagID = diag::err_bad_cxx_cast_qualifiers_away;774return TC_Failed;775776case CastAwayConstnessKind::CACK_Incoherent:777DiagID = diag::ext_bad_cxx_cast_qualifiers_away_incoherent;778return TC_Extension;779}780781llvm_unreachable("unexpected cast away constness kind");782}783784/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.785/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-786/// checked downcasts in class hierarchies.787void CastOperation::CheckDynamicCast() {788CheckNoDerefRAII NoderefCheck(*this);789790if (ValueKind == VK_PRValue)791SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());792else if (isPlaceholder())793SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());794if (SrcExpr.isInvalid()) // if conversion failed, don't report another error795return;796797QualType OrigSrcType = SrcExpr.get()->getType();798QualType DestType = Self.Context.getCanonicalType(this->DestType);799800// C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,801// or "pointer to cv void".802803QualType DestPointee;804const PointerType *DestPointer = DestType->getAs<PointerType>();805const ReferenceType *DestReference = nullptr;806if (DestPointer) {807DestPointee = DestPointer->getPointeeType();808} else if ((DestReference = DestType->getAs<ReferenceType>())) {809DestPointee = DestReference->getPointeeType();810} else {811Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)812<< this->DestType << DestRange;813SrcExpr = ExprError();814return;815}816817const RecordType *DestRecord = DestPointee->getAs<RecordType>();818if (DestPointee->isVoidType()) {819assert(DestPointer && "Reference to void is not possible");820} else if (DestRecord) {821if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,822diag::err_bad_cast_incomplete,823DestRange)) {824SrcExpr = ExprError();825return;826}827} else {828Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)829<< DestPointee.getUnqualifiedType() << DestRange;830SrcExpr = ExprError();831return;832}833834// C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to835// complete class type, [...]. If T is an lvalue reference type, v shall be836// an lvalue of a complete class type, [...]. If T is an rvalue reference837// type, v shall be an expression having a complete class type, [...]838QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);839QualType SrcPointee;840if (DestPointer) {841if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {842SrcPointee = SrcPointer->getPointeeType();843} else {844Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)845<< OrigSrcType << this->DestType << SrcExpr.get()->getSourceRange();846SrcExpr = ExprError();847return;848}849} else if (DestReference->isLValueReferenceType()) {850if (!SrcExpr.get()->isLValue()) {851Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)852<< CT_Dynamic << OrigSrcType << this->DestType << OpRange;853}854SrcPointee = SrcType;855} else {856// If we're dynamic_casting from a prvalue to an rvalue reference, we need857// to materialize the prvalue before we bind the reference to it.858if (SrcExpr.get()->isPRValue())859SrcExpr = Self.CreateMaterializeTemporaryExpr(860SrcType, SrcExpr.get(), /*IsLValueReference*/ false);861SrcPointee = SrcType;862}863864const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();865if (SrcRecord) {866if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,867diag::err_bad_cast_incomplete,868SrcExpr.get())) {869SrcExpr = ExprError();870return;871}872} else {873Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)874<< SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();875SrcExpr = ExprError();876return;877}878879assert((DestPointer || DestReference) &&880"Bad destination non-ptr/ref slipped through.");881assert((DestRecord || DestPointee->isVoidType()) &&882"Bad destination pointee slipped through.");883assert(SrcRecord && "Bad source pointee slipped through.");884885// C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.886if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {887Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)888<< CT_Dynamic << OrigSrcType << this->DestType << OpRange;889SrcExpr = ExprError();890return;891}892893// C++ 5.2.7p3: If the type of v is the same as the required result type,894// [except for cv].895if (DestRecord == SrcRecord) {896Kind = CK_NoOp;897return;898}899900// C++ 5.2.7p5901// Upcasts are resolved statically.902if (DestRecord &&903Self.IsDerivedFrom(OpRange.getBegin(), SrcPointee, DestPointee)) {904if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,905OpRange.getBegin(), OpRange,906&BasePath)) {907SrcExpr = ExprError();908return;909}910911Kind = CK_DerivedToBase;912return;913}914915// C++ 5.2.7p6: Otherwise, v shall be [polymorphic].916const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();917assert(SrcDecl && "Definition missing");918if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {919Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)920<< SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();921SrcExpr = ExprError();922}923924// dynamic_cast is not available with -fno-rtti.925// As an exception, dynamic_cast to void* is available because it doesn't926// use RTTI.927if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) {928Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti);929SrcExpr = ExprError();930return;931}932933// Warns when dynamic_cast is used with RTTI data disabled.934if (!Self.getLangOpts().RTTIData) {935bool MicrosoftABI =936Self.getASTContext().getTargetInfo().getCXXABI().isMicrosoft();937bool isClangCL = Self.getDiagnostics().getDiagnosticOptions().getFormat() ==938DiagnosticOptions::MSVC;939if (MicrosoftABI || !DestPointee->isVoidType())940Self.Diag(OpRange.getBegin(),941diag::warn_no_dynamic_cast_with_rtti_disabled)942<< isClangCL;943}944945// For a dynamic_cast to a final type, IR generation might emit a reference946// to the vtable.947if (DestRecord) {948auto *DestDecl = DestRecord->getAsCXXRecordDecl();949if (DestDecl->isEffectivelyFinal())950Self.MarkVTableUsed(OpRange.getBegin(), DestDecl);951}952953// Done. Everything else is run-time checks.954Kind = CK_Dynamic;955}956957/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.958/// Refer to C++ 5.2.11 for details. const_cast is typically used in code959/// like this:960/// const char *str = "literal";961/// legacy_function(const_cast\<char*\>(str));962void CastOperation::CheckConstCast() {963CheckNoDerefRAII NoderefCheck(*this);964965if (ValueKind == VK_PRValue)966SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());967else if (isPlaceholder())968SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());969if (SrcExpr.isInvalid()) // if conversion failed, don't report another error970return;971972unsigned msg = diag::err_bad_cxx_cast_generic;973auto TCR = TryConstCast(Self, SrcExpr, DestType, /*CStyle*/ false, msg);974if (TCR != TC_Success && msg != 0) {975Self.Diag(OpRange.getBegin(), msg) << CT_Const976<< SrcExpr.get()->getType() << DestType << OpRange;977}978if (!isValidCast(TCR))979SrcExpr = ExprError();980}981982void CastOperation::CheckAddrspaceCast() {983unsigned msg = diag::err_bad_cxx_cast_generic;984auto TCR =985TryAddressSpaceCast(Self, SrcExpr, DestType, /*CStyle*/ false, msg, Kind);986if (TCR != TC_Success && msg != 0) {987Self.Diag(OpRange.getBegin(), msg)988<< CT_Addrspace << SrcExpr.get()->getType() << DestType << OpRange;989}990if (!isValidCast(TCR))991SrcExpr = ExprError();992}993994/// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast995/// or downcast between respective pointers or references.996static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,997QualType DestType,998SourceRange OpRange) {999QualType SrcType = SrcExpr->getType();1000// When casting from pointer or reference, get pointee type; use original1001// type otherwise.1002const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();1003const CXXRecordDecl *SrcRD =1004SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();10051006// Examining subobjects for records is only possible if the complete and1007// valid definition is available. Also, template instantiation is not1008// allowed here.1009if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())1010return;10111012const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();10131014if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())1015return;10161017enum {1018ReinterpretUpcast,1019ReinterpretDowncast1020} ReinterpretKind;10211022CXXBasePaths BasePaths;10231024if (SrcRD->isDerivedFrom(DestRD, BasePaths))1025ReinterpretKind = ReinterpretUpcast;1026else if (DestRD->isDerivedFrom(SrcRD, BasePaths))1027ReinterpretKind = ReinterpretDowncast;1028else1029return;10301031bool VirtualBase = true;1032bool NonZeroOffset = false;1033for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),1034E = BasePaths.end();1035I != E; ++I) {1036const CXXBasePath &Path = *I;1037CharUnits Offset = CharUnits::Zero();1038bool IsVirtual = false;1039for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();1040IElem != EElem; ++IElem) {1041IsVirtual = IElem->Base->isVirtual();1042if (IsVirtual)1043break;1044const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();1045assert(BaseRD && "Base type should be a valid unqualified class type");1046// Don't check if any base has invalid declaration or has no definition1047// since it has no layout info.1048const CXXRecordDecl *Class = IElem->Class,1049*ClassDefinition = Class->getDefinition();1050if (Class->isInvalidDecl() || !ClassDefinition ||1051!ClassDefinition->isCompleteDefinition())1052return;10531054const ASTRecordLayout &DerivedLayout =1055Self.Context.getASTRecordLayout(Class);1056Offset += DerivedLayout.getBaseClassOffset(BaseRD);1057}1058if (!IsVirtual) {1059// Don't warn if any path is a non-virtually derived base at offset zero.1060if (Offset.isZero())1061return;1062// Offset makes sense only for non-virtual bases.1063else1064NonZeroOffset = true;1065}1066VirtualBase = VirtualBase && IsVirtual;1067}10681069(void) NonZeroOffset; // Silence set but not used warning.1070assert((VirtualBase || NonZeroOffset) &&1071"Should have returned if has non-virtual base with zero offset");10721073QualType BaseType =1074ReinterpretKind == ReinterpretUpcast? DestType : SrcType;1075QualType DerivedType =1076ReinterpretKind == ReinterpretUpcast? SrcType : DestType;10771078SourceLocation BeginLoc = OpRange.getBegin();1079Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)1080<< DerivedType << BaseType << !VirtualBase << int(ReinterpretKind)1081<< OpRange;1082Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)1083<< int(ReinterpretKind)1084<< FixItHint::CreateReplacement(BeginLoc, "static_cast");1085}10861087static bool argTypeIsABIEquivalent(QualType SrcType, QualType DestType,1088ASTContext &Context) {1089if (SrcType->isPointerType() && DestType->isPointerType())1090return true;10911092// Allow integral type mismatch if their size are equal.1093if ((SrcType->isIntegralType(Context) || SrcType->isEnumeralType()) &&1094(DestType->isIntegralType(Context) || DestType->isEnumeralType()))1095if (Context.getTypeSizeInChars(SrcType) ==1096Context.getTypeSizeInChars(DestType))1097return true;10981099return Context.hasSameUnqualifiedType(SrcType, DestType);1100}11011102static unsigned int checkCastFunctionType(Sema &Self, const ExprResult &SrcExpr,1103QualType DestType) {1104unsigned int DiagID = 0;1105const unsigned int DiagList[] = {diag::warn_cast_function_type_strict,1106diag::warn_cast_function_type};1107for (auto ID : DiagList) {1108if (!Self.Diags.isIgnored(ID, SrcExpr.get()->getExprLoc())) {1109DiagID = ID;1110break;1111}1112}1113if (!DiagID)1114return 0;11151116QualType SrcType = SrcExpr.get()->getType();1117const FunctionType *SrcFTy = nullptr;1118const FunctionType *DstFTy = nullptr;1119if (((SrcType->isBlockPointerType() || SrcType->isFunctionPointerType()) &&1120DestType->isFunctionPointerType()) ||1121(SrcType->isMemberFunctionPointerType() &&1122DestType->isMemberFunctionPointerType())) {1123SrcFTy = SrcType->getPointeeType()->castAs<FunctionType>();1124DstFTy = DestType->getPointeeType()->castAs<FunctionType>();1125} else if (SrcType->isFunctionType() && DestType->isFunctionReferenceType()) {1126SrcFTy = SrcType->castAs<FunctionType>();1127DstFTy = DestType.getNonReferenceType()->castAs<FunctionType>();1128} else {1129return 0;1130}1131assert(SrcFTy && DstFTy);11321133if (Self.Context.hasSameType(SrcFTy, DstFTy))1134return 0;11351136// For strict checks, ensure we have an exact match.1137if (DiagID == diag::warn_cast_function_type_strict)1138return DiagID;11391140auto IsVoidVoid = [](const FunctionType *T) {1141if (!T->getReturnType()->isVoidType())1142return false;1143if (const auto *PT = T->getAs<FunctionProtoType>())1144return !PT->isVariadic() && PT->getNumParams() == 0;1145return false;1146};11471148// Skip if either function type is void(*)(void)1149if (IsVoidVoid(SrcFTy) || IsVoidVoid(DstFTy))1150return 0;11511152// Check return type.1153if (!argTypeIsABIEquivalent(SrcFTy->getReturnType(), DstFTy->getReturnType(),1154Self.Context))1155return DiagID;11561157// Check if either has unspecified number of parameters1158if (SrcFTy->isFunctionNoProtoType() || DstFTy->isFunctionNoProtoType())1159return 0;11601161// Check parameter types.11621163const auto *SrcFPTy = cast<FunctionProtoType>(SrcFTy);1164const auto *DstFPTy = cast<FunctionProtoType>(DstFTy);11651166// In a cast involving function types with a variable argument list only the1167// types of initial arguments that are provided are considered.1168unsigned NumParams = SrcFPTy->getNumParams();1169unsigned DstNumParams = DstFPTy->getNumParams();1170if (NumParams > DstNumParams) {1171if (!DstFPTy->isVariadic())1172return DiagID;1173NumParams = DstNumParams;1174} else if (NumParams < DstNumParams) {1175if (!SrcFPTy->isVariadic())1176return DiagID;1177}11781179for (unsigned i = 0; i < NumParams; ++i)1180if (!argTypeIsABIEquivalent(SrcFPTy->getParamType(i),1181DstFPTy->getParamType(i), Self.Context))1182return DiagID;11831184return 0;1185}11861187/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is1188/// valid.1189/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code1190/// like this:1191/// char *bytes = reinterpret_cast\<char*\>(int_ptr);1192void CastOperation::CheckReinterpretCast() {1193if (ValueKind == VK_PRValue && !isPlaceholder(BuiltinType::Overload))1194SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());1195else1196checkNonOverloadPlaceholders();1197if (SrcExpr.isInvalid()) // if conversion failed, don't report another error1198return;11991200unsigned msg = diag::err_bad_cxx_cast_generic;1201TryCastResult tcr =1202TryReinterpretCast(Self, SrcExpr, DestType,1203/*CStyle*/false, OpRange, msg, Kind);1204if (tcr != TC_Success && msg != 0) {1205if (SrcExpr.isInvalid()) // if conversion failed, don't report another error1206return;1207if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {1208//FIXME: &f<int>; is overloaded and resolvable1209Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)1210<< OverloadExpr::find(SrcExpr.get()).Expression->getName()1211<< DestType << OpRange;1212Self.NoteAllOverloadCandidates(SrcExpr.get());12131214} else {1215diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),1216DestType, /*listInitialization=*/false);1217}1218}12191220if (isValidCast(tcr)) {1221if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())1222checkObjCConversion(CheckedConversionKind::OtherCast);1223DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);12241225if (unsigned DiagID = checkCastFunctionType(Self, SrcExpr, DestType))1226Self.Diag(OpRange.getBegin(), DiagID)1227<< SrcExpr.get()->getType() << DestType << OpRange;1228} else {1229SrcExpr = ExprError();1230}1231}123212331234/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.1235/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making1236/// implicit conversions explicit and getting rid of data loss warnings.1237void CastOperation::CheckStaticCast() {1238CheckNoDerefRAII NoderefCheck(*this);12391240if (isPlaceholder()) {1241checkNonOverloadPlaceholders();1242if (SrcExpr.isInvalid())1243return;1244}12451246// This test is outside everything else because it's the only case where1247// a non-lvalue-reference target type does not lead to decay.1248// C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".1249if (DestType->isVoidType()) {1250Kind = CK_ToVoid;12511252if (claimPlaceholder(BuiltinType::Overload)) {1253Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,1254false, // Decay Function to ptr1255true, // Complain1256OpRange, DestType, diag::err_bad_static_cast_overload);1257if (SrcExpr.isInvalid())1258return;1259}12601261SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());1262return;1263}12641265if (ValueKind == VK_PRValue && !DestType->isRecordType() &&1266!isPlaceholder(BuiltinType::Overload)) {1267SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());1268if (SrcExpr.isInvalid()) // if conversion failed, don't report another error1269return;1270}12711272unsigned msg = diag::err_bad_cxx_cast_generic;1273TryCastResult tcr =1274TryStaticCast(Self, SrcExpr, DestType, CheckedConversionKind::OtherCast,1275OpRange, msg, Kind, BasePath, /*ListInitialization=*/false);1276if (tcr != TC_Success && msg != 0) {1277if (SrcExpr.isInvalid())1278return;1279if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {1280OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;1281Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)1282<< oe->getName() << DestType << OpRange1283<< oe->getQualifierLoc().getSourceRange();1284Self.NoteAllOverloadCandidates(SrcExpr.get());1285} else {1286diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,1287/*listInitialization=*/false);1288}1289}12901291if (isValidCast(tcr)) {1292if (Kind == CK_BitCast)1293checkCastAlign();1294if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())1295checkObjCConversion(CheckedConversionKind::OtherCast);1296} else {1297SrcExpr = ExprError();1298}1299}13001301static bool IsAddressSpaceConversion(QualType SrcType, QualType DestType) {1302auto *SrcPtrType = SrcType->getAs<PointerType>();1303if (!SrcPtrType)1304return false;1305auto *DestPtrType = DestType->getAs<PointerType>();1306if (!DestPtrType)1307return false;1308return SrcPtrType->getPointeeType().getAddressSpace() !=1309DestPtrType->getPointeeType().getAddressSpace();1310}13111312/// TryStaticCast - Check if a static cast can be performed, and do so if1313/// possible. If @p CStyle, ignore access restrictions on hierarchy casting1314/// and casting away constness.1315static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,1316QualType DestType, CheckedConversionKind CCK,1317SourceRange OpRange, unsigned &msg,1318CastKind &Kind, CXXCastPath &BasePath,1319bool ListInitialization) {1320// Determine whether we have the semantics of a C-style cast.1321bool CStyle = (CCK == CheckedConversionKind::CStyleCast ||1322CCK == CheckedConversionKind::FunctionalCast);13231324// The order the tests is not entirely arbitrary. There is one conversion1325// that can be handled in two different ways. Given:1326// struct A {};1327// struct B : public A {1328// B(); B(const A&);1329// };1330// const A &a = B();1331// the cast static_cast<const B&>(a) could be seen as either a static1332// reference downcast, or an explicit invocation of the user-defined1333// conversion using B's conversion constructor.1334// DR 427 specifies that the downcast is to be applied here.13351336// C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".1337// Done outside this function.13381339TryCastResult tcr;13401341// C++ 5.2.9p5, reference downcast.1342// See the function for details.1343// DR 427 specifies that this is to be applied before paragraph 2.1344tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,1345OpRange, msg, Kind, BasePath);1346if (tcr != TC_NotApplicable)1347return tcr;13481349// C++11 [expr.static.cast]p3:1350// A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv21351// T2" if "cv2 T2" is reference-compatible with "cv1 T1".1352tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,1353BasePath, msg);1354if (tcr != TC_NotApplicable)1355return tcr;13561357// C++ 5.2.9p2: An expression e can be explicitly converted to a type T1358// [...] if the declaration "T t(e);" is well-formed, [...].1359tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,1360Kind, ListInitialization);1361if (SrcExpr.isInvalid())1362return TC_Failed;1363if (tcr != TC_NotApplicable)1364return tcr;13651366// C++ 5.2.9p6: May apply the reverse of any standard conversion, except1367// lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean1368// conversions, subject to further restrictions.1369// Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal1370// of qualification conversions impossible. (In C++20, adding an array bound1371// would be the reverse of a qualification conversion, but adding permission1372// to add an array bound in a static_cast is a wording oversight.)1373// In the CStyle case, the earlier attempt to const_cast should have taken1374// care of reverse qualification conversions.13751376QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());13771378// C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly1379// converted to an integral type. [...] A value of a scoped enumeration type1380// can also be explicitly converted to a floating-point type [...].1381if (const EnumType *Enum = SrcType->getAs<EnumType>()) {1382if (Enum->getDecl()->isScoped()) {1383if (DestType->isBooleanType()) {1384Kind = CK_IntegralToBoolean;1385return TC_Success;1386} else if (DestType->isIntegralType(Self.Context)) {1387Kind = CK_IntegralCast;1388return TC_Success;1389} else if (DestType->isRealFloatingType()) {1390Kind = CK_IntegralToFloating;1391return TC_Success;1392}1393}1394}13951396// Reverse integral promotion/conversion. All such conversions are themselves1397// again integral promotions or conversions and are thus already handled by1398// p2 (TryDirectInitialization above).1399// (Note: any data loss warnings should be suppressed.)1400// The exception is the reverse of enum->integer, i.e. integer->enum (and1401// enum->enum). See also C++ 5.2.9p7.1402// The same goes for reverse floating point promotion/conversion and1403// floating-integral conversions. Again, only floating->enum is relevant.1404if (DestType->isEnumeralType()) {1405if (Self.RequireCompleteType(OpRange.getBegin(), DestType,1406diag::err_bad_cast_incomplete)) {1407SrcExpr = ExprError();1408return TC_Failed;1409}1410if (SrcType->isIntegralOrEnumerationType()) {1411// [expr.static.cast]p10 If the enumeration type has a fixed underlying1412// type, the value is first converted to that type by integral conversion1413const EnumType *Enum = DestType->castAs<EnumType>();1414Kind = Enum->getDecl()->isFixed() &&1415Enum->getDecl()->getIntegerType()->isBooleanType()1416? CK_IntegralToBoolean1417: CK_IntegralCast;1418return TC_Success;1419} else if (SrcType->isRealFloatingType()) {1420Kind = CK_FloatingToIntegral;1421return TC_Success;1422}1423}14241425// Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.1426// C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.1427tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,1428Kind, BasePath);1429if (tcr != TC_NotApplicable)1430return tcr;14311432// Reverse member pointer conversion. C++ 4.11 specifies member pointer1433// conversion. C++ 5.2.9p9 has additional information.1434// DR54's access restrictions apply here also.1435tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,1436OpRange, msg, Kind, BasePath);1437if (tcr != TC_NotApplicable)1438return tcr;14391440// Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to1441// void*. C++ 5.2.9p10 specifies additional restrictions, which really is1442// just the usual constness stuff.1443if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {1444QualType SrcPointee = SrcPointer->getPointeeType();1445if (SrcPointee->isVoidType()) {1446if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {1447QualType DestPointee = DestPointer->getPointeeType();1448if (DestPointee->isIncompleteOrObjectType()) {1449// This is definitely the intended conversion, but it might fail due1450// to a qualifier violation. Note that we permit Objective-C lifetime1451// and GC qualifier mismatches here.1452if (!CStyle) {1453Qualifiers DestPointeeQuals = DestPointee.getQualifiers();1454Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();1455DestPointeeQuals.removeObjCGCAttr();1456DestPointeeQuals.removeObjCLifetime();1457SrcPointeeQuals.removeObjCGCAttr();1458SrcPointeeQuals.removeObjCLifetime();1459if (DestPointeeQuals != SrcPointeeQuals &&1460!DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {1461msg = diag::err_bad_cxx_cast_qualifiers_away;1462return TC_Failed;1463}1464}1465Kind = IsAddressSpaceConversion(SrcType, DestType)1466? CK_AddressSpaceConversion1467: CK_BitCast;1468return TC_Success;1469}14701471// Microsoft permits static_cast from 'pointer-to-void' to1472// 'pointer-to-function'.1473if (!CStyle && Self.getLangOpts().MSVCCompat &&1474DestPointee->isFunctionType()) {1475Self.Diag(OpRange.getBegin(), diag::ext_ms_cast_fn_obj) << OpRange;1476Kind = CK_BitCast;1477return TC_Success;1478}1479}1480else if (DestType->isObjCObjectPointerType()) {1481// allow both c-style cast and static_cast of objective-c pointers as1482// they are pervasive.1483Kind = CK_CPointerToObjCPointerCast;1484return TC_Success;1485}1486else if (CStyle && DestType->isBlockPointerType()) {1487// allow c-style cast of void * to block pointers.1488Kind = CK_AnyPointerToBlockPointerCast;1489return TC_Success;1490}1491}1492}1493// Allow arbitrary objective-c pointer conversion with static casts.1494if (SrcType->isObjCObjectPointerType() &&1495DestType->isObjCObjectPointerType()) {1496Kind = CK_BitCast;1497return TC_Success;1498}1499// Allow ns-pointer to cf-pointer conversion in either direction1500// with static casts.1501if (!CStyle &&1502Self.ObjC().CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind))1503return TC_Success;15041505// See if it looks like the user is trying to convert between1506// related record types, and select a better diagnostic if so.1507if (auto SrcPointer = SrcType->getAs<PointerType>())1508if (auto DestPointer = DestType->getAs<PointerType>())1509if (SrcPointer->getPointeeType()->getAs<RecordType>() &&1510DestPointer->getPointeeType()->getAs<RecordType>())1511msg = diag::err_bad_cxx_cast_unrelated_class;15121513if (SrcType->isMatrixType() && DestType->isMatrixType()) {1514if (Self.CheckMatrixCast(OpRange, DestType, SrcType, Kind)) {1515SrcExpr = ExprError();1516return TC_Failed;1517}1518return TC_Success;1519}15201521// We tried everything. Everything! Nothing works! :-(1522return TC_NotApplicable;1523}15241525/// Tests whether a conversion according to N2844 is valid.1526TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,1527QualType DestType, bool CStyle,1528CastKind &Kind, CXXCastPath &BasePath,1529unsigned &msg) {1530// C++11 [expr.static.cast]p3:1531// A glvalue of type "cv1 T1" can be cast to type "rvalue reference to1532// cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".1533const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();1534if (!R)1535return TC_NotApplicable;15361537if (!SrcExpr->isGLValue())1538return TC_NotApplicable;15391540// Because we try the reference downcast before this function, from now on1541// this is the only cast possibility, so we issue an error if we fail now.1542// FIXME: Should allow casting away constness if CStyle.1543QualType FromType = SrcExpr->getType();1544QualType ToType = R->getPointeeType();1545if (CStyle) {1546FromType = FromType.getUnqualifiedType();1547ToType = ToType.getUnqualifiedType();1548}15491550Sema::ReferenceConversions RefConv;1551Sema::ReferenceCompareResult RefResult = Self.CompareReferenceRelationship(1552SrcExpr->getBeginLoc(), ToType, FromType, &RefConv);1553if (RefResult != Sema::Ref_Compatible) {1554if (CStyle || RefResult == Sema::Ref_Incompatible)1555return TC_NotApplicable;1556// Diagnose types which are reference-related but not compatible here since1557// we can provide better diagnostics. In these cases forwarding to1558// [expr.static.cast]p4 should never result in a well-formed cast.1559msg = SrcExpr->isLValue() ? diag::err_bad_lvalue_to_rvalue_cast1560: diag::err_bad_rvalue_to_rvalue_cast;1561return TC_Failed;1562}15631564if (RefConv & Sema::ReferenceConversions::DerivedToBase) {1565Kind = CK_DerivedToBase;1566CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,1567/*DetectVirtual=*/true);1568if (!Self.IsDerivedFrom(SrcExpr->getBeginLoc(), SrcExpr->getType(),1569R->getPointeeType(), Paths))1570return TC_NotApplicable;15711572Self.BuildBasePathArray(Paths, BasePath);1573} else1574Kind = CK_NoOp;15751576return TC_Success;1577}15781579/// Tests whether a conversion according to C++ 5.2.9p5 is valid.1580TryCastResult1581TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,1582bool CStyle, SourceRange OpRange,1583unsigned &msg, CastKind &Kind,1584CXXCastPath &BasePath) {1585// C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be1586// cast to type "reference to cv2 D", where D is a class derived from B,1587// if a valid standard conversion from "pointer to D" to "pointer to B"1588// exists, cv2 >= cv1, and B is not a virtual base class of D.1589// In addition, DR54 clarifies that the base must be accessible in the1590// current context. Although the wording of DR54 only applies to the pointer1591// variant of this rule, the intent is clearly for it to apply to the this1592// conversion as well.15931594const ReferenceType *DestReference = DestType->getAs<ReferenceType>();1595if (!DestReference) {1596return TC_NotApplicable;1597}1598bool RValueRef = DestReference->isRValueReferenceType();1599if (!RValueRef && !SrcExpr->isLValue()) {1600// We know the left side is an lvalue reference, so we can suggest a reason.1601msg = diag::err_bad_cxx_cast_rvalue;1602return TC_NotApplicable;1603}16041605QualType DestPointee = DestReference->getPointeeType();16061607// FIXME: If the source is a prvalue, we should issue a warning (because the1608// cast always has undefined behavior), and for AST consistency, we should1609// materialize a temporary.1610return TryStaticDowncast(Self,1611Self.Context.getCanonicalType(SrcExpr->getType()),1612Self.Context.getCanonicalType(DestPointee), CStyle,1613OpRange, SrcExpr->getType(), DestType, msg, Kind,1614BasePath);1615}16161617/// Tests whether a conversion according to C++ 5.2.9p8 is valid.1618TryCastResult1619TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,1620bool CStyle, SourceRange OpRange,1621unsigned &msg, CastKind &Kind,1622CXXCastPath &BasePath) {1623// C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class1624// type, can be converted to an rvalue of type "pointer to cv2 D", where D1625// is a class derived from B, if a valid standard conversion from "pointer1626// to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base1627// class of D.1628// In addition, DR54 clarifies that the base must be accessible in the1629// current context.16301631const PointerType *DestPointer = DestType->getAs<PointerType>();1632if (!DestPointer) {1633return TC_NotApplicable;1634}16351636const PointerType *SrcPointer = SrcType->getAs<PointerType>();1637if (!SrcPointer) {1638msg = diag::err_bad_static_cast_pointer_nonpointer;1639return TC_NotApplicable;1640}16411642return TryStaticDowncast(Self,1643Self.Context.getCanonicalType(SrcPointer->getPointeeType()),1644Self.Context.getCanonicalType(DestPointer->getPointeeType()),1645CStyle, OpRange, SrcType, DestType, msg, Kind,1646BasePath);1647}16481649/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and1650/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to1651/// DestType is possible and allowed.1652TryCastResult1653TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,1654bool CStyle, SourceRange OpRange, QualType OrigSrcType,1655QualType OrigDestType, unsigned &msg,1656CastKind &Kind, CXXCastPath &BasePath) {1657// We can only work with complete types. But don't complain if it doesn't work1658if (!Self.isCompleteType(OpRange.getBegin(), SrcType) ||1659!Self.isCompleteType(OpRange.getBegin(), DestType))1660return TC_NotApplicable;16611662// Downcast can only happen in class hierarchies, so we need classes.1663if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {1664return TC_NotApplicable;1665}16661667CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,1668/*DetectVirtual=*/true);1669if (!Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths)) {1670return TC_NotApplicable;1671}16721673// Target type does derive from source type. Now we're serious. If an error1674// appears now, it's not ignored.1675// This may not be entirely in line with the standard. Take for example:1676// struct A {};1677// struct B : virtual A {1678// B(A&);1679// };1680//1681// void f()1682// {1683// (void)static_cast<const B&>(*((A*)0));1684// }1685// As far as the standard is concerned, p5 does not apply (A is virtual), so1686// p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.1687// However, both GCC and Comeau reject this example, and accepting it would1688// mean more complex code if we're to preserve the nice error message.1689// FIXME: Being 100% compliant here would be nice to have.16901691// Must preserve cv, as always, unless we're in C-style mode.1692if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {1693msg = diag::err_bad_cxx_cast_qualifiers_away;1694return TC_Failed;1695}16961697if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {1698// This code is analoguous to that in CheckDerivedToBaseConversion, except1699// that it builds the paths in reverse order.1700// To sum up: record all paths to the base and build a nice string from1701// them. Use it to spice up the error message.1702if (!Paths.isRecordingPaths()) {1703Paths.clear();1704Paths.setRecordingPaths(true);1705Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths);1706}1707std::string PathDisplayStr;1708std::set<unsigned> DisplayedPaths;1709for (clang::CXXBasePath &Path : Paths) {1710if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) {1711// We haven't displayed a path to this particular base1712// class subobject yet.1713PathDisplayStr += "\n ";1714for (CXXBasePathElement &PE : llvm::reverse(Path))1715PathDisplayStr += PE.Base->getType().getAsString() + " -> ";1716PathDisplayStr += QualType(DestType).getAsString();1717}1718}17191720Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)1721<< QualType(SrcType).getUnqualifiedType()1722<< QualType(DestType).getUnqualifiedType()1723<< PathDisplayStr << OpRange;1724msg = 0;1725return TC_Failed;1726}17271728if (Paths.getDetectedVirtual() != nullptr) {1729QualType VirtualBase(Paths.getDetectedVirtual(), 0);1730Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)1731<< OrigSrcType << OrigDestType << VirtualBase << OpRange;1732msg = 0;1733return TC_Failed;1734}17351736if (!CStyle) {1737switch (Self.CheckBaseClassAccess(OpRange.getBegin(),1738SrcType, DestType,1739Paths.front(),1740diag::err_downcast_from_inaccessible_base)) {1741case Sema::AR_accessible:1742case Sema::AR_delayed: // be optimistic1743case Sema::AR_dependent: // be optimistic1744break;17451746case Sema::AR_inaccessible:1747msg = 0;1748return TC_Failed;1749}1750}17511752Self.BuildBasePathArray(Paths, BasePath);1753Kind = CK_BaseToDerived;1754return TC_Success;1755}17561757/// TryStaticMemberPointerUpcast - Tests whether a conversion according to1758/// C++ 5.2.9p9 is valid:1759///1760/// An rvalue of type "pointer to member of D of type cv1 T" can be1761/// converted to an rvalue of type "pointer to member of B of type cv2 T",1762/// where B is a base class of D [...].1763///1764TryCastResult1765TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,1766QualType DestType, bool CStyle,1767SourceRange OpRange,1768unsigned &msg, CastKind &Kind,1769CXXCastPath &BasePath) {1770const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();1771if (!DestMemPtr)1772return TC_NotApplicable;17731774bool WasOverloadedFunction = false;1775DeclAccessPair FoundOverload;1776if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {1777if (FunctionDecl *Fn1778= Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,1779FoundOverload)) {1780CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);1781SrcType = Self.Context.getMemberPointerType(Fn->getType(),1782Self.Context.getTypeDeclType(M->getParent()).getTypePtr());1783WasOverloadedFunction = true;1784}1785}17861787const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();1788if (!SrcMemPtr) {1789msg = diag::err_bad_static_cast_member_pointer_nonmp;1790return TC_NotApplicable;1791}17921793// Lock down the inheritance model right now in MS ABI, whether or not the1794// pointee types are the same.1795if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {1796(void)Self.isCompleteType(OpRange.getBegin(), SrcType);1797(void)Self.isCompleteType(OpRange.getBegin(), DestType);1798}17991800// T == T, modulo cv1801if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),1802DestMemPtr->getPointeeType()))1803return TC_NotApplicable;18041805// B base of D1806QualType SrcClass(SrcMemPtr->getClass(), 0);1807QualType DestClass(DestMemPtr->getClass(), 0);1808CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,1809/*DetectVirtual=*/true);1810if (!Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths))1811return TC_NotApplicable;18121813// B is a base of D. But is it an allowed base? If not, it's a hard error.1814if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {1815Paths.clear();1816Paths.setRecordingPaths(true);1817bool StillOkay =1818Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths);1819assert(StillOkay);1820(void)StillOkay;1821std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);1822Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)1823<< 1 << SrcClass << DestClass << PathDisplayStr << OpRange;1824msg = 0;1825return TC_Failed;1826}18271828if (const RecordType *VBase = Paths.getDetectedVirtual()) {1829Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)1830<< SrcClass << DestClass << QualType(VBase, 0) << OpRange;1831msg = 0;1832return TC_Failed;1833}18341835if (!CStyle) {1836switch (Self.CheckBaseClassAccess(OpRange.getBegin(),1837DestClass, SrcClass,1838Paths.front(),1839diag::err_upcast_to_inaccessible_base)) {1840case Sema::AR_accessible:1841case Sema::AR_delayed:1842case Sema::AR_dependent:1843// Optimistically assume that the delayed and dependent cases1844// will work out.1845break;18461847case Sema::AR_inaccessible:1848msg = 0;1849return TC_Failed;1850}1851}18521853if (WasOverloadedFunction) {1854// Resolve the address of the overloaded function again, this time1855// allowing complaints if something goes wrong.1856FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),1857DestType,1858true,1859FoundOverload);1860if (!Fn) {1861msg = 0;1862return TC_Failed;1863}18641865SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);1866if (!SrcExpr.isUsable()) {1867msg = 0;1868return TC_Failed;1869}1870}18711872Self.BuildBasePathArray(Paths, BasePath);1873Kind = CK_DerivedToBaseMemberPointer;1874return TC_Success;1875}18761877/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p21878/// is valid:1879///1880/// An expression e can be explicitly converted to a type T using a1881/// @c static_cast if the declaration "T t(e);" is well-formed [...].1882TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,1883QualType DestType,1884CheckedConversionKind CCK,1885SourceRange OpRange, unsigned &msg,1886CastKind &Kind, bool ListInitialization) {1887if (DestType->isRecordType()) {1888if (Self.RequireCompleteType(OpRange.getBegin(), DestType,1889diag::err_bad_cast_incomplete) ||1890Self.RequireNonAbstractType(OpRange.getBegin(), DestType,1891diag::err_allocation_of_abstract_type)) {1892msg = 0;1893return TC_Failed;1894}1895}18961897InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);1898InitializationKind InitKind =1899(CCK == CheckedConversionKind::CStyleCast)1900? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,1901ListInitialization)1902: (CCK == CheckedConversionKind::FunctionalCast)1903? InitializationKind::CreateFunctionalCast(OpRange,1904ListInitialization)1905: InitializationKind::CreateCast(OpRange);1906Expr *SrcExprRaw = SrcExpr.get();1907// FIXME: Per DR242, we should check for an implicit conversion sequence1908// or for a constructor that could be invoked by direct-initialization1909// here, not for an initialization sequence.1910InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);19111912// At this point of CheckStaticCast, if the destination is a reference,1913// or the expression is an overload expression this has to work.1914// There is no other way that works.1915// On the other hand, if we're checking a C-style cast, we've still got1916// the reinterpret_cast way.1917bool CStyle = (CCK == CheckedConversionKind::CStyleCast ||1918CCK == CheckedConversionKind::FunctionalCast);1919if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))1920return TC_NotApplicable;19211922ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);1923if (Result.isInvalid()) {1924msg = 0;1925return TC_Failed;1926}19271928if (InitSeq.isConstructorInitialization())1929Kind = CK_ConstructorConversion;1930else1931Kind = CK_NoOp;19321933SrcExpr = Result;1934return TC_Success;1935}19361937/// TryConstCast - See if a const_cast from source to destination is allowed,1938/// and perform it if it is.1939static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,1940QualType DestType, bool CStyle,1941unsigned &msg) {1942DestType = Self.Context.getCanonicalType(DestType);1943QualType SrcType = SrcExpr.get()->getType();1944bool NeedToMaterializeTemporary = false;19451946if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {1947// C++11 5.2.11p4:1948// if a pointer to T1 can be explicitly converted to the type "pointer to1949// T2" using a const_cast, then the following conversions can also be1950// made:1951// -- an lvalue of type T1 can be explicitly converted to an lvalue of1952// type T2 using the cast const_cast<T2&>;1953// -- a glvalue of type T1 can be explicitly converted to an xvalue of1954// type T2 using the cast const_cast<T2&&>; and1955// -- if T1 is a class type, a prvalue of type T1 can be explicitly1956// converted to an xvalue of type T2 using the cast const_cast<T2&&>.19571958if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) {1959// Cannot const_cast non-lvalue to lvalue reference type. But if this1960// is C-style, static_cast might find a way, so we simply suggest a1961// message and tell the parent to keep searching.1962msg = diag::err_bad_cxx_cast_rvalue;1963return TC_NotApplicable;1964}19651966if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isPRValue()) {1967if (!SrcType->isRecordType()) {1968// Cannot const_cast non-class prvalue to rvalue reference type. But if1969// this is C-style, static_cast can do this.1970msg = diag::err_bad_cxx_cast_rvalue;1971return TC_NotApplicable;1972}19731974// Materialize the class prvalue so that the const_cast can bind a1975// reference to it.1976NeedToMaterializeTemporary = true;1977}19781979// It's not completely clear under the standard whether we can1980// const_cast bit-field gl-values. Doing so would not be1981// intrinsically complicated, but for now, we say no for1982// consistency with other compilers and await the word of the1983// committee.1984if (SrcExpr.get()->refersToBitField()) {1985msg = diag::err_bad_cxx_cast_bitfield;1986return TC_NotApplicable;1987}19881989DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());1990SrcType = Self.Context.getPointerType(SrcType);1991}19921993// C++ 5.2.11p5: For a const_cast involving pointers to data members [...]1994// the rules for const_cast are the same as those used for pointers.19951996if (!DestType->isPointerType() &&1997!DestType->isMemberPointerType() &&1998!DestType->isObjCObjectPointerType()) {1999// Cannot cast to non-pointer, non-reference type. Note that, if DestType2000// was a reference type, we converted it to a pointer above.2001// The status of rvalue references isn't entirely clear, but it looks like2002// conversion to them is simply invalid.2003// C++ 5.2.11p3: For two pointer types [...]2004if (!CStyle)2005msg = diag::err_bad_const_cast_dest;2006return TC_NotApplicable;2007}2008if (DestType->isFunctionPointerType() ||2009DestType->isMemberFunctionPointerType()) {2010// Cannot cast direct function pointers.2011// C++ 5.2.11p2: [...] where T is any object type or the void type [...]2012// T is the ultimate pointee of source and target type.2013if (!CStyle)2014msg = diag::err_bad_const_cast_dest;2015return TC_NotApplicable;2016}20172018// C++ [expr.const.cast]p3:2019// "For two similar types T1 and T2, [...]"2020//2021// We only allow a const_cast to change cvr-qualifiers, not other kinds of2022// type qualifiers. (Likewise, we ignore other changes when determining2023// whether a cast casts away constness.)2024if (!Self.Context.hasCvrSimilarType(SrcType, DestType))2025return TC_NotApplicable;20262027if (NeedToMaterializeTemporary)2028// This is a const_cast from a class prvalue to an rvalue reference type.2029// Materialize a temporary to store the result of the conversion.2030SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcExpr.get()->getType(),2031SrcExpr.get(),2032/*IsLValueReference*/ false);20332034return TC_Success;2035}20362037// Checks for undefined behavior in reinterpret_cast.2038// The cases that is checked for is:2039// *reinterpret_cast<T*>(&a)2040// reinterpret_cast<T&>(a)2041// where accessing 'a' as type 'T' will result in undefined behavior.2042void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,2043bool IsDereference,2044SourceRange Range) {2045unsigned DiagID = IsDereference ?2046diag::warn_pointer_indirection_from_incompatible_type :2047diag::warn_undefined_reinterpret_cast;20482049if (Diags.isIgnored(DiagID, Range.getBegin()))2050return;20512052QualType SrcTy, DestTy;2053if (IsDereference) {2054if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {2055return;2056}2057SrcTy = SrcType->getPointeeType();2058DestTy = DestType->getPointeeType();2059} else {2060if (!DestType->getAs<ReferenceType>()) {2061return;2062}2063SrcTy = SrcType;2064DestTy = DestType->getPointeeType();2065}20662067// Cast is compatible if the types are the same.2068if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {2069return;2070}2071// or one of the types is a char or void type2072if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||2073SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {2074return;2075}2076// or one of the types is a tag type.2077if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {2078return;2079}20802081// FIXME: Scoped enums?2082if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||2083(SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {2084if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {2085return;2086}2087}20882089Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;2090}20912092static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,2093QualType DestType) {2094QualType SrcType = SrcExpr.get()->getType();2095if (Self.Context.hasSameType(SrcType, DestType))2096return;2097if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())2098if (SrcPtrTy->isObjCSelType()) {2099QualType DT = DestType;2100if (isa<PointerType>(DestType))2101DT = DestType->getPointeeType();2102if (!DT.getUnqualifiedType()->isVoidType())2103Self.Diag(SrcExpr.get()->getExprLoc(),2104diag::warn_cast_pointer_from_sel)2105<< SrcType << DestType << SrcExpr.get()->getSourceRange();2106}2107}21082109/// Diagnose casts that change the calling convention of a pointer to a function2110/// defined in the current TU.2111static void DiagnoseCallingConvCast(Sema &Self, const ExprResult &SrcExpr,2112QualType DstType, SourceRange OpRange) {2113// Check if this cast would change the calling convention of a function2114// pointer type.2115QualType SrcType = SrcExpr.get()->getType();2116if (Self.Context.hasSameType(SrcType, DstType) ||2117!SrcType->isFunctionPointerType() || !DstType->isFunctionPointerType())2118return;2119const auto *SrcFTy =2120SrcType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();2121const auto *DstFTy =2122DstType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();2123CallingConv SrcCC = SrcFTy->getCallConv();2124CallingConv DstCC = DstFTy->getCallConv();2125if (SrcCC == DstCC)2126return;21272128// We have a calling convention cast. Check if the source is a pointer to a2129// known, specific function that has already been defined.2130Expr *Src = SrcExpr.get()->IgnoreParenImpCasts();2131if (auto *UO = dyn_cast<UnaryOperator>(Src))2132if (UO->getOpcode() == UO_AddrOf)2133Src = UO->getSubExpr()->IgnoreParenImpCasts();2134auto *DRE = dyn_cast<DeclRefExpr>(Src);2135if (!DRE)2136return;2137auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());2138if (!FD)2139return;21402141// Only warn if we are casting from the default convention to a non-default2142// convention. This can happen when the programmer forgot to apply the calling2143// convention to the function declaration and then inserted this cast to2144// satisfy the type system.2145CallingConv DefaultCC = Self.getASTContext().getDefaultCallingConvention(2146FD->isVariadic(), FD->isCXXInstanceMember());2147if (DstCC == DefaultCC || SrcCC != DefaultCC)2148return;21492150// Diagnose this cast, as it is probably bad.2151StringRef SrcCCName = FunctionType::getNameForCallConv(SrcCC);2152StringRef DstCCName = FunctionType::getNameForCallConv(DstCC);2153Self.Diag(OpRange.getBegin(), diag::warn_cast_calling_conv)2154<< SrcCCName << DstCCName << OpRange;21552156// The checks above are cheaper than checking if the diagnostic is enabled.2157// However, it's worth checking if the warning is enabled before we construct2158// a fixit.2159if (Self.Diags.isIgnored(diag::warn_cast_calling_conv, OpRange.getBegin()))2160return;21612162// Try to suggest a fixit to change the calling convention of the function2163// whose address was taken. Try to use the latest macro for the convention.2164// For example, users probably want to write "WINAPI" instead of "__stdcall"2165// to match the Windows header declarations.2166SourceLocation NameLoc = FD->getFirstDecl()->getNameInfo().getLoc();2167Preprocessor &PP = Self.getPreprocessor();2168SmallVector<TokenValue, 6> AttrTokens;2169SmallString<64> CCAttrText;2170llvm::raw_svector_ostream OS(CCAttrText);2171if (Self.getLangOpts().MicrosoftExt) {2172// __stdcall or __vectorcall2173OS << "__" << DstCCName;2174IdentifierInfo *II = PP.getIdentifierInfo(OS.str());2175AttrTokens.push_back(II->isKeyword(Self.getLangOpts())2176? TokenValue(II->getTokenID())2177: TokenValue(II));2178} else {2179// __attribute__((stdcall)) or __attribute__((vectorcall))2180OS << "__attribute__((" << DstCCName << "))";2181AttrTokens.push_back(tok::kw___attribute);2182AttrTokens.push_back(tok::l_paren);2183AttrTokens.push_back(tok::l_paren);2184IdentifierInfo *II = PP.getIdentifierInfo(DstCCName);2185AttrTokens.push_back(II->isKeyword(Self.getLangOpts())2186? TokenValue(II->getTokenID())2187: TokenValue(II));2188AttrTokens.push_back(tok::r_paren);2189AttrTokens.push_back(tok::r_paren);2190}2191StringRef AttrSpelling = PP.getLastMacroWithSpelling(NameLoc, AttrTokens);2192if (!AttrSpelling.empty())2193CCAttrText = AttrSpelling;2194OS << ' ';2195Self.Diag(NameLoc, diag::note_change_calling_conv_fixit)2196<< FD << DstCCName << FixItHint::CreateInsertion(NameLoc, CCAttrText);2197}21982199static void checkIntToPointerCast(bool CStyle, const SourceRange &OpRange,2200const Expr *SrcExpr, QualType DestType,2201Sema &Self) {2202QualType SrcType = SrcExpr->getType();22032204// Not warning on reinterpret_cast, boolean, constant expressions, etc2205// are not explicit design choices, but consistent with GCC's behavior.2206// Feel free to modify them if you've reason/evidence for an alternative.2207if (CStyle && SrcType->isIntegralType(Self.Context)2208&& !SrcType->isBooleanType()2209&& !SrcType->isEnumeralType()2210&& !SrcExpr->isIntegerConstantExpr(Self.Context)2211&& Self.Context.getTypeSize(DestType) >2212Self.Context.getTypeSize(SrcType)) {2213// Separate between casts to void* and non-void* pointers.2214// Some APIs use (abuse) void* for something like a user context,2215// and often that value is an integer even if it isn't a pointer itself.2216// Having a separate warning flag allows users to control the warning2217// for their workflow.2218unsigned Diag = DestType->isVoidPointerType() ?2219diag::warn_int_to_void_pointer_cast2220: diag::warn_int_to_pointer_cast;2221Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange;2222}2223}22242225static bool fixOverloadedReinterpretCastExpr(Sema &Self, QualType DestType,2226ExprResult &Result) {2227// We can only fix an overloaded reinterpret_cast if2228// - it is a template with explicit arguments that resolves to an lvalue2229// unambiguously, or2230// - it is the only function in an overload set that may have its address2231// taken.22322233Expr *E = Result.get();2234// TODO: what if this fails because of DiagnoseUseOfDecl or something2235// like it?2236if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(2237Result,2238Expr::getValueKindForType(DestType) ==2239VK_PRValue // Convert Fun to Ptr2240) &&2241Result.isUsable())2242return true;22432244// No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization2245// preserves Result.2246Result = E;2247if (!Self.resolveAndFixAddressOfSingleOverloadCandidate(2248Result, /*DoFunctionPointerConversion=*/true))2249return false;2250return Result.isUsable();2251}22522253static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,2254QualType DestType, bool CStyle,2255SourceRange OpRange,2256unsigned &msg,2257CastKind &Kind) {2258bool IsLValueCast = false;22592260DestType = Self.Context.getCanonicalType(DestType);2261QualType SrcType = SrcExpr.get()->getType();22622263// Is the source an overloaded name? (i.e. &foo)2264// If so, reinterpret_cast generally can not help us here (13.4, p1, bullet 5)2265if (SrcType == Self.Context.OverloadTy) {2266ExprResult FixedExpr = SrcExpr;2267if (!fixOverloadedReinterpretCastExpr(Self, DestType, FixedExpr))2268return TC_NotApplicable;22692270assert(FixedExpr.isUsable() && "Invalid result fixing overloaded expr");2271SrcExpr = FixedExpr;2272SrcType = SrcExpr.get()->getType();2273}22742275if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {2276if (!SrcExpr.get()->isGLValue()) {2277// Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the2278// similar comment in const_cast.2279msg = diag::err_bad_cxx_cast_rvalue;2280return TC_NotApplicable;2281}22822283if (!CStyle) {2284Self.CheckCompatibleReinterpretCast(SrcType, DestType,2285/*IsDereference=*/false, OpRange);2286}22872288// C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the2289// same effect as the conversion *reinterpret_cast<T*>(&x) with the2290// built-in & and * operators.22912292const char *inappropriate = nullptr;2293switch (SrcExpr.get()->getObjectKind()) {2294case OK_Ordinary:2295break;2296case OK_BitField:2297msg = diag::err_bad_cxx_cast_bitfield;2298return TC_NotApplicable;2299// FIXME: Use a specific diagnostic for the rest of these cases.2300case OK_VectorComponent: inappropriate = "vector element"; break;2301case OK_MatrixComponent:2302inappropriate = "matrix element";2303break;2304case OK_ObjCProperty: inappropriate = "property expression"; break;2305case OK_ObjCSubscript: inappropriate = "container subscripting expression";2306break;2307}2308if (inappropriate) {2309Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)2310<< inappropriate << DestType2311<< OpRange << SrcExpr.get()->getSourceRange();2312msg = 0; SrcExpr = ExprError();2313return TC_NotApplicable;2314}23152316// This code does this transformation for the checked types.2317DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());2318SrcType = Self.Context.getPointerType(SrcType);23192320IsLValueCast = true;2321}23222323// Canonicalize source for comparison.2324SrcType = Self.Context.getCanonicalType(SrcType);23252326const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),2327*SrcMemPtr = SrcType->getAs<MemberPointerType>();2328if (DestMemPtr && SrcMemPtr) {2329// C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"2330// can be explicitly converted to an rvalue of type "pointer to member2331// of Y of type T2" if T1 and T2 are both function types or both object2332// types.2333if (DestMemPtr->isMemberFunctionPointer() !=2334SrcMemPtr->isMemberFunctionPointer())2335return TC_NotApplicable;23362337if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {2338// We need to determine the inheritance model that the class will use if2339// haven't yet.2340(void)Self.isCompleteType(OpRange.getBegin(), SrcType);2341(void)Self.isCompleteType(OpRange.getBegin(), DestType);2342}23432344// Don't allow casting between member pointers of different sizes.2345if (Self.Context.getTypeSize(DestMemPtr) !=2346Self.Context.getTypeSize(SrcMemPtr)) {2347msg = diag::err_bad_cxx_cast_member_pointer_size;2348return TC_Failed;2349}23502351// C++ 5.2.10p2: The reinterpret_cast operator shall not cast away2352// constness.2353// A reinterpret_cast followed by a const_cast can, though, so in C-style,2354// we accept it.2355if (auto CACK =2356CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,2357/*CheckObjCLifetime=*/CStyle))2358return getCastAwayConstnessCastKind(CACK, msg);23592360// A valid member pointer cast.2361assert(!IsLValueCast);2362Kind = CK_ReinterpretMemberPointer;2363return TC_Success;2364}23652366// See below for the enumeral issue.2367if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {2368// C++0x 5.2.10p4: A pointer can be explicitly converted to any integral2369// type large enough to hold it. A value of std::nullptr_t can be2370// converted to an integral type; the conversion has the same meaning2371// and validity as a conversion of (void*)0 to the integral type.2372if (Self.Context.getTypeSize(SrcType) >2373Self.Context.getTypeSize(DestType)) {2374msg = diag::err_bad_reinterpret_cast_small_int;2375return TC_Failed;2376}2377Kind = CK_PointerToIntegral;2378return TC_Success;2379}23802381// Allow reinterpret_casts between vectors of the same size and2382// between vectors and integers of the same size.2383bool destIsVector = DestType->isVectorType();2384bool srcIsVector = SrcType->isVectorType();2385if (srcIsVector || destIsVector) {2386// Allow bitcasting between SVE VLATs and VLSTs, and vice-versa.2387if (Self.isValidSveBitcast(SrcType, DestType)) {2388Kind = CK_BitCast;2389return TC_Success;2390}23912392// Allow bitcasting between SVE VLATs and VLSTs, and vice-versa.2393if (Self.RISCV().isValidRVVBitcast(SrcType, DestType)) {2394Kind = CK_BitCast;2395return TC_Success;2396}23972398// The non-vector type, if any, must have integral type. This is2399// the same rule that C vector casts use; note, however, that enum2400// types are not integral in C++.2401if ((!destIsVector && !DestType->isIntegralType(Self.Context)) ||2402(!srcIsVector && !SrcType->isIntegralType(Self.Context)))2403return TC_NotApplicable;24042405// The size we want to consider is eltCount * eltSize.2406// That's exactly what the lax-conversion rules will check.2407if (Self.areLaxCompatibleVectorTypes(SrcType, DestType)) {2408Kind = CK_BitCast;2409return TC_Success;2410}24112412if (Self.LangOpts.OpenCL && !CStyle) {2413if (DestType->isExtVectorType() || SrcType->isExtVectorType()) {2414// FIXME: Allow for reinterpret cast between 3 and 4 element vectors2415if (Self.areVectorTypesSameSize(SrcType, DestType)) {2416Kind = CK_BitCast;2417return TC_Success;2418}2419}2420}24212422// Otherwise, pick a reasonable diagnostic.2423if (!destIsVector)2424msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;2425else if (!srcIsVector)2426msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;2427else2428msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;24292430return TC_Failed;2431}24322433if (SrcType == DestType) {2434// C++ 5.2.10p2 has a note that mentions that, subject to all other2435// restrictions, a cast to the same type is allowed so long as it does not2436// cast away constness. In C++98, the intent was not entirely clear here,2437// since all other paragraphs explicitly forbid casts to the same type.2438// C++11 clarifies this case with p2.2439//2440// The only allowed types are: integral, enumeration, pointer, or2441// pointer-to-member types. We also won't restrict Obj-C pointers either.2442Kind = CK_NoOp;2443TryCastResult Result = TC_NotApplicable;2444if (SrcType->isIntegralOrEnumerationType() ||2445SrcType->isAnyPointerType() ||2446SrcType->isMemberPointerType() ||2447SrcType->isBlockPointerType()) {2448Result = TC_Success;2449}2450return Result;2451}24522453bool destIsPtr = DestType->isAnyPointerType() ||2454DestType->isBlockPointerType();2455bool srcIsPtr = SrcType->isAnyPointerType() ||2456SrcType->isBlockPointerType();2457if (!destIsPtr && !srcIsPtr) {2458// Except for std::nullptr_t->integer and lvalue->reference, which are2459// handled above, at least one of the two arguments must be a pointer.2460return TC_NotApplicable;2461}24622463if (DestType->isIntegralType(Self.Context)) {2464assert(srcIsPtr && "One type must be a pointer");2465// C++ 5.2.10p4: A pointer can be explicitly converted to any integral2466// type large enough to hold it; except in Microsoft mode, where the2467// integral type size doesn't matter (except we don't allow bool).2468if ((Self.Context.getTypeSize(SrcType) >2469Self.Context.getTypeSize(DestType))) {2470bool MicrosoftException =2471Self.getLangOpts().MicrosoftExt && !DestType->isBooleanType();2472if (MicrosoftException) {2473unsigned Diag = SrcType->isVoidPointerType()2474? diag::warn_void_pointer_to_int_cast2475: diag::warn_pointer_to_int_cast;2476Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange;2477} else {2478msg = diag::err_bad_reinterpret_cast_small_int;2479return TC_Failed;2480}2481}2482Kind = CK_PointerToIntegral;2483return TC_Success;2484}24852486if (SrcType->isIntegralOrEnumerationType()) {2487assert(destIsPtr && "One type must be a pointer");2488checkIntToPointerCast(CStyle, OpRange, SrcExpr.get(), DestType, Self);2489// C++ 5.2.10p5: A value of integral or enumeration type can be explicitly2490// converted to a pointer.2491// C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not2492// necessarily converted to a null pointer value.]2493Kind = CK_IntegralToPointer;2494return TC_Success;2495}24962497if (!destIsPtr || !srcIsPtr) {2498// With the valid non-pointer conversions out of the way, we can be even2499// more stringent.2500return TC_NotApplicable;2501}25022503// Cannot convert between block pointers and Objective-C object pointers.2504if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||2505(DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))2506return TC_NotApplicable;25072508// C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.2509// The C-style cast operator can.2510TryCastResult SuccessResult = TC_Success;2511if (auto CACK =2512CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,2513/*CheckObjCLifetime=*/CStyle))2514SuccessResult = getCastAwayConstnessCastKind(CACK, msg);25152516if (IsAddressSpaceConversion(SrcType, DestType)) {2517Kind = CK_AddressSpaceConversion;2518assert(SrcType->isPointerType() && DestType->isPointerType());2519if (!CStyle &&2520!DestType->getPointeeType().getQualifiers().isAddressSpaceSupersetOf(2521SrcType->getPointeeType().getQualifiers())) {2522SuccessResult = TC_Failed;2523}2524} else if (IsLValueCast) {2525Kind = CK_LValueBitCast;2526} else if (DestType->isObjCObjectPointerType()) {2527Kind = Self.ObjC().PrepareCastToObjCObjectPointer(SrcExpr);2528} else if (DestType->isBlockPointerType()) {2529if (!SrcType->isBlockPointerType()) {2530Kind = CK_AnyPointerToBlockPointerCast;2531} else {2532Kind = CK_BitCast;2533}2534} else {2535Kind = CK_BitCast;2536}25372538// Any pointer can be cast to an Objective-C pointer type with a C-style2539// cast.2540if (CStyle && DestType->isObjCObjectPointerType()) {2541return SuccessResult;2542}2543if (CStyle)2544DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);25452546DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);25472548// Not casting away constness, so the only remaining check is for compatible2549// pointer categories.25502551if (SrcType->isFunctionPointerType()) {2552if (DestType->isFunctionPointerType()) {2553// C++ 5.2.10p6: A pointer to a function can be explicitly converted to2554// a pointer to a function of a different type.2555return SuccessResult;2556}25572558// C++0x 5.2.10p8: Converting a pointer to a function into a pointer to2559// an object type or vice versa is conditionally-supported.2560// Compilers support it in C++03 too, though, because it's necessary for2561// casting the return value of dlsym() and GetProcAddress().2562// FIXME: Conditionally-supported behavior should be configurable in the2563// TargetInfo or similar.2564Self.Diag(OpRange.getBegin(),2565Self.getLangOpts().CPlusPlus11 ?2566diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)2567<< OpRange;2568return SuccessResult;2569}25702571if (DestType->isFunctionPointerType()) {2572// See above.2573Self.Diag(OpRange.getBegin(),2574Self.getLangOpts().CPlusPlus11 ?2575diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)2576<< OpRange;2577return SuccessResult;2578}25792580// Diagnose address space conversion in nested pointers.2581QualType DestPtee = DestType->getPointeeType().isNull()2582? DestType->getPointeeType()2583: DestType->getPointeeType()->getPointeeType();2584QualType SrcPtee = SrcType->getPointeeType().isNull()2585? SrcType->getPointeeType()2586: SrcType->getPointeeType()->getPointeeType();2587while (!DestPtee.isNull() && !SrcPtee.isNull()) {2588if (DestPtee.getAddressSpace() != SrcPtee.getAddressSpace()) {2589Self.Diag(OpRange.getBegin(),2590diag::warn_bad_cxx_cast_nested_pointer_addr_space)2591<< CStyle << SrcType << DestType << SrcExpr.get()->getSourceRange();2592break;2593}2594DestPtee = DestPtee->getPointeeType();2595SrcPtee = SrcPtee->getPointeeType();2596}25972598// C++ 5.2.10p7: A pointer to an object can be explicitly converted to2599// a pointer to an object of different type.2600// Void pointers are not specified, but supported by every compiler out there.2601// So we finish by allowing everything that remains - it's got to be two2602// object pointers.2603return SuccessResult;2604}26052606static TryCastResult TryAddressSpaceCast(Sema &Self, ExprResult &SrcExpr,2607QualType DestType, bool CStyle,2608unsigned &msg, CastKind &Kind) {2609if (!Self.getLangOpts().OpenCL && !Self.getLangOpts().SYCLIsDevice)2610// FIXME: As compiler doesn't have any information about overlapping addr2611// spaces at the moment we have to be permissive here.2612return TC_NotApplicable;2613// Even though the logic below is general enough and can be applied to2614// non-OpenCL mode too, we fast-path above because no other languages2615// define overlapping address spaces currently.2616auto SrcType = SrcExpr.get()->getType();2617// FIXME: Should this be generalized to references? The reference parameter2618// however becomes a reference pointee type here and therefore rejected.2619// Perhaps this is the right behavior though according to C++.2620auto SrcPtrType = SrcType->getAs<PointerType>();2621if (!SrcPtrType)2622return TC_NotApplicable;2623auto DestPtrType = DestType->getAs<PointerType>();2624if (!DestPtrType)2625return TC_NotApplicable;2626auto SrcPointeeType = SrcPtrType->getPointeeType();2627auto DestPointeeType = DestPtrType->getPointeeType();2628if (!DestPointeeType.isAddressSpaceOverlapping(SrcPointeeType)) {2629msg = diag::err_bad_cxx_cast_addr_space_mismatch;2630return TC_Failed;2631}2632auto SrcPointeeTypeWithoutAS =2633Self.Context.removeAddrSpaceQualType(SrcPointeeType.getCanonicalType());2634auto DestPointeeTypeWithoutAS =2635Self.Context.removeAddrSpaceQualType(DestPointeeType.getCanonicalType());2636if (Self.Context.hasSameType(SrcPointeeTypeWithoutAS,2637DestPointeeTypeWithoutAS)) {2638Kind = SrcPointeeType.getAddressSpace() == DestPointeeType.getAddressSpace()2639? CK_NoOp2640: CK_AddressSpaceConversion;2641return TC_Success;2642} else {2643return TC_NotApplicable;2644}2645}26462647void CastOperation::checkAddressSpaceCast(QualType SrcType, QualType DestType) {2648// In OpenCL only conversions between pointers to objects in overlapping2649// addr spaces are allowed. v2.0 s6.5.5 - Generic addr space overlaps2650// with any named one, except for constant.26512652// Converting the top level pointee addrspace is permitted for compatible2653// addrspaces (such as 'generic int *' to 'local int *' or vice versa), but2654// if any of the nested pointee addrspaces differ, we emit a warning2655// regardless of addrspace compatibility. This makes2656// local int ** p;2657// return (generic int **) p;2658// warn even though local -> generic is permitted.2659if (Self.getLangOpts().OpenCL) {2660const Type *DestPtr, *SrcPtr;2661bool Nested = false;2662unsigned DiagID = diag::err_typecheck_incompatible_address_space;2663DestPtr = Self.getASTContext().getCanonicalType(DestType.getTypePtr()),2664SrcPtr = Self.getASTContext().getCanonicalType(SrcType.getTypePtr());26652666while (isa<PointerType>(DestPtr) && isa<PointerType>(SrcPtr)) {2667const PointerType *DestPPtr = cast<PointerType>(DestPtr);2668const PointerType *SrcPPtr = cast<PointerType>(SrcPtr);2669QualType DestPPointee = DestPPtr->getPointeeType();2670QualType SrcPPointee = SrcPPtr->getPointeeType();2671if (Nested2672? DestPPointee.getAddressSpace() != SrcPPointee.getAddressSpace()2673: !DestPPointee.isAddressSpaceOverlapping(SrcPPointee)) {2674Self.Diag(OpRange.getBegin(), DiagID)2675<< SrcType << DestType << Sema::AA_Casting2676<< SrcExpr.get()->getSourceRange();2677if (!Nested)2678SrcExpr = ExprError();2679return;2680}26812682DestPtr = DestPPtr->getPointeeType().getTypePtr();2683SrcPtr = SrcPPtr->getPointeeType().getTypePtr();2684Nested = true;2685DiagID = diag::ext_nested_pointer_qualifier_mismatch;2686}2687}2688}26892690bool Sema::ShouldSplatAltivecScalarInCast(const VectorType *VecTy) {2691bool SrcCompatXL = this->getLangOpts().getAltivecSrcCompat() ==2692LangOptions::AltivecSrcCompatKind::XL;2693VectorKind VKind = VecTy->getVectorKind();26942695if ((VKind == VectorKind::AltiVecVector) ||2696(SrcCompatXL && ((VKind == VectorKind::AltiVecBool) ||2697(VKind == VectorKind::AltiVecPixel)))) {2698return true;2699}2700return false;2701}27022703bool Sema::CheckAltivecInitFromScalar(SourceRange R, QualType VecTy,2704QualType SrcTy) {2705bool SrcCompatGCC = this->getLangOpts().getAltivecSrcCompat() ==2706LangOptions::AltivecSrcCompatKind::GCC;2707if (this->getLangOpts().AltiVec && SrcCompatGCC) {2708this->Diag(R.getBegin(),2709diag::err_invalid_conversion_between_vector_and_integer)2710<< VecTy << SrcTy << R;2711return true;2712}2713return false;2714}27152716void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,2717bool ListInitialization) {2718assert(Self.getLangOpts().CPlusPlus);27192720// Handle placeholders.2721if (isPlaceholder()) {2722// C-style casts can resolve __unknown_any types.2723if (claimPlaceholder(BuiltinType::UnknownAny)) {2724SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,2725SrcExpr.get(), Kind,2726ValueKind, BasePath);2727return;2728}27292730checkNonOverloadPlaceholders();2731if (SrcExpr.isInvalid())2732return;2733}27342735// C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".2736// This test is outside everything else because it's the only case where2737// a non-lvalue-reference target type does not lead to decay.2738if (DestType->isVoidType()) {2739Kind = CK_ToVoid;27402741if (claimPlaceholder(BuiltinType::Overload)) {2742Self.ResolveAndFixSingleFunctionTemplateSpecialization(2743SrcExpr, /* Decay Function to ptr */ false,2744/* Complain */ true, DestRange, DestType,2745diag::err_bad_cstyle_cast_overload);2746if (SrcExpr.isInvalid())2747return;2748}27492750SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());2751return;2752}27532754// If the type is dependent, we won't do any other semantic analysis now.2755if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||2756SrcExpr.get()->isValueDependent()) {2757assert(Kind == CK_Dependent);2758return;2759}27602761if (ValueKind == VK_PRValue && !DestType->isRecordType() &&2762!isPlaceholder(BuiltinType::Overload)) {2763SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());2764if (SrcExpr.isInvalid())2765return;2766}27672768// AltiVec vector initialization with a single literal.2769if (const VectorType *vecTy = DestType->getAs<VectorType>()) {2770if (Self.CheckAltivecInitFromScalar(OpRange, DestType,2771SrcExpr.get()->getType())) {2772SrcExpr = ExprError();2773return;2774}2775if (Self.ShouldSplatAltivecScalarInCast(vecTy) &&2776(SrcExpr.get()->getType()->isIntegerType() ||2777SrcExpr.get()->getType()->isFloatingType())) {2778Kind = CK_VectorSplat;2779SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());2780return;2781}2782}27832784// WebAssembly tables cannot be cast.2785QualType SrcType = SrcExpr.get()->getType();2786if (SrcType->isWebAssemblyTableType()) {2787Self.Diag(OpRange.getBegin(), diag::err_wasm_cast_table)2788<< 1 << SrcExpr.get()->getSourceRange();2789SrcExpr = ExprError();2790return;2791}27922793// C++ [expr.cast]p5: The conversions performed by2794// - a const_cast,2795// - a static_cast,2796// - a static_cast followed by a const_cast,2797// - a reinterpret_cast, or2798// - a reinterpret_cast followed by a const_cast,2799// can be performed using the cast notation of explicit type conversion.2800// [...] If a conversion can be interpreted in more than one of the ways2801// listed above, the interpretation that appears first in the list is used,2802// even if a cast resulting from that interpretation is ill-formed.2803// In plain language, this means trying a const_cast ...2804// Note that for address space we check compatibility after const_cast.2805unsigned msg = diag::err_bad_cxx_cast_generic;2806TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,2807/*CStyle*/ true, msg);2808if (SrcExpr.isInvalid())2809return;2810if (isValidCast(tcr))2811Kind = CK_NoOp;28122813CheckedConversionKind CCK = FunctionalStyle2814? CheckedConversionKind::FunctionalCast2815: CheckedConversionKind::CStyleCast;2816if (tcr == TC_NotApplicable) {2817tcr = TryAddressSpaceCast(Self, SrcExpr, DestType, /*CStyle*/ true, msg,2818Kind);2819if (SrcExpr.isInvalid())2820return;28212822if (tcr == TC_NotApplicable) {2823// ... or if that is not possible, a static_cast, ignoring const and2824// addr space, ...2825tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange, msg, Kind,2826BasePath, ListInitialization);2827if (SrcExpr.isInvalid())2828return;28292830if (tcr == TC_NotApplicable) {2831// ... and finally a reinterpret_cast, ignoring const and addr space.2832tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/ true,2833OpRange, msg, Kind);2834if (SrcExpr.isInvalid())2835return;2836}2837}2838}28392840if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&2841isValidCast(tcr))2842checkObjCConversion(CCK);28432844if (tcr != TC_Success && msg != 0) {2845if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {2846DeclAccessPair Found;2847FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),2848DestType,2849/*Complain*/ true,2850Found);2851if (Fn) {2852// If DestType is a function type (not to be confused with the function2853// pointer type), it will be possible to resolve the function address,2854// but the type cast should be considered as failure.2855OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression;2856Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload)2857<< OE->getName() << DestType << OpRange2858<< OE->getQualifierLoc().getSourceRange();2859Self.NoteAllOverloadCandidates(SrcExpr.get());2860}2861} else {2862diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),2863OpRange, SrcExpr.get(), DestType, ListInitialization);2864}2865}28662867if (isValidCast(tcr)) {2868if (Kind == CK_BitCast)2869checkCastAlign();28702871if (unsigned DiagID = checkCastFunctionType(Self, SrcExpr, DestType))2872Self.Diag(OpRange.getBegin(), DiagID)2873<< SrcExpr.get()->getType() << DestType << OpRange;28742875} else {2876SrcExpr = ExprError();2877}2878}28792880/// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a2881/// non-matching type. Such as enum function call to int, int call to2882/// pointer; etc. Cast to 'void' is an exception.2883static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,2884QualType DestType) {2885if (Self.Diags.isIgnored(diag::warn_bad_function_cast,2886SrcExpr.get()->getExprLoc()))2887return;28882889if (!isa<CallExpr>(SrcExpr.get()))2890return;28912892QualType SrcType = SrcExpr.get()->getType();2893if (DestType.getUnqualifiedType()->isVoidType())2894return;2895if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())2896&& (DestType->isAnyPointerType() || DestType->isBlockPointerType()))2897return;2898if (SrcType->isIntegerType() && DestType->isIntegerType() &&2899(SrcType->isBooleanType() == DestType->isBooleanType()) &&2900(SrcType->isEnumeralType() == DestType->isEnumeralType()))2901return;2902if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())2903return;2904if (SrcType->isEnumeralType() && DestType->isEnumeralType())2905return;2906if (SrcType->isComplexType() && DestType->isComplexType())2907return;2908if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())2909return;2910if (SrcType->isFixedPointType() && DestType->isFixedPointType())2911return;29122913Self.Diag(SrcExpr.get()->getExprLoc(),2914diag::warn_bad_function_cast)2915<< SrcType << DestType << SrcExpr.get()->getSourceRange();2916}29172918/// Check the semantics of a C-style cast operation, in C.2919void CastOperation::CheckCStyleCast() {2920assert(!Self.getLangOpts().CPlusPlus);29212922// C-style casts can resolve __unknown_any types.2923if (claimPlaceholder(BuiltinType::UnknownAny)) {2924SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,2925SrcExpr.get(), Kind,2926ValueKind, BasePath);2927return;2928}29292930// C99 6.5.4p2: the cast type needs to be void or scalar and the expression2931// type needs to be scalar.2932if (DestType->isVoidType()) {2933// We don't necessarily do lvalue-to-rvalue conversions on this.2934SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());2935if (SrcExpr.isInvalid())2936return;29372938// Cast to void allows any expr type.2939Kind = CK_ToVoid;2940return;2941}29422943// If the type is dependent, we won't do any other semantic analysis now.2944if (Self.getASTContext().isDependenceAllowed() &&2945(DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||2946SrcExpr.get()->isValueDependent())) {2947assert((DestType->containsErrors() || SrcExpr.get()->containsErrors() ||2948SrcExpr.get()->containsErrors()) &&2949"should only occur in error-recovery path.");2950assert(Kind == CK_Dependent);2951return;2952}29532954// Overloads are allowed with C extensions, so we need to support them.2955if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {2956DeclAccessPair DAP;2957if (FunctionDecl *FD = Self.ResolveAddressOfOverloadedFunction(2958SrcExpr.get(), DestType, /*Complain=*/true, DAP))2959SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr.get(), DAP, FD);2960else2961return;2962assert(SrcExpr.isUsable());2963}2964SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());2965if (SrcExpr.isInvalid())2966return;2967QualType SrcType = SrcExpr.get()->getType();29682969if (SrcType->isWebAssemblyTableType()) {2970Self.Diag(OpRange.getBegin(), diag::err_wasm_cast_table)2971<< 1 << SrcExpr.get()->getSourceRange();2972SrcExpr = ExprError();2973return;2974}29752976assert(!SrcType->isPlaceholderType());29772978checkAddressSpaceCast(SrcType, DestType);2979if (SrcExpr.isInvalid())2980return;29812982if (Self.RequireCompleteType(OpRange.getBegin(), DestType,2983diag::err_typecheck_cast_to_incomplete)) {2984SrcExpr = ExprError();2985return;2986}29872988// Allow casting a sizeless built-in type to itself.2989if (DestType->isSizelessBuiltinType() &&2990Self.Context.hasSameUnqualifiedType(DestType, SrcType)) {2991Kind = CK_NoOp;2992return;2993}29942995// Allow bitcasting between compatible SVE vector types.2996if ((SrcType->isVectorType() || DestType->isVectorType()) &&2997Self.isValidSveBitcast(SrcType, DestType)) {2998Kind = CK_BitCast;2999return;3000}30013002// Allow bitcasting between compatible RVV vector types.3003if ((SrcType->isVectorType() || DestType->isVectorType()) &&3004Self.RISCV().isValidRVVBitcast(SrcType, DestType)) {3005Kind = CK_BitCast;3006return;3007}30083009if (!DestType->isScalarType() && !DestType->isVectorType() &&3010!DestType->isMatrixType()) {3011const RecordType *DestRecordTy = DestType->getAs<RecordType>();30123013if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){3014// GCC struct/union extension: allow cast to self.3015Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)3016<< DestType << SrcExpr.get()->getSourceRange();3017Kind = CK_NoOp;3018return;3019}30203021// GCC's cast to union extension.3022if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {3023RecordDecl *RD = DestRecordTy->getDecl();3024if (CastExpr::getTargetFieldForToUnionCast(RD, SrcType)) {3025Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)3026<< SrcExpr.get()->getSourceRange();3027Kind = CK_ToUnion;3028return;3029} else {3030Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)3031<< SrcType << SrcExpr.get()->getSourceRange();3032SrcExpr = ExprError();3033return;3034}3035}30363037// OpenCL v2.0 s6.13.10 - Allow casts from '0' to event_t type.3038if (Self.getLangOpts().OpenCL && DestType->isEventT()) {3039Expr::EvalResult Result;3040if (SrcExpr.get()->EvaluateAsInt(Result, Self.Context)) {3041llvm::APSInt CastInt = Result.Val.getInt();3042if (0 == CastInt) {3043Kind = CK_ZeroToOCLOpaqueType;3044return;3045}3046Self.Diag(OpRange.getBegin(),3047diag::err_opencl_cast_non_zero_to_event_t)3048<< toString(CastInt, 10) << SrcExpr.get()->getSourceRange();3049SrcExpr = ExprError();3050return;3051}3052}30533054// Reject any other conversions to non-scalar types.3055Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)3056<< DestType << SrcExpr.get()->getSourceRange();3057SrcExpr = ExprError();3058return;3059}30603061// The type we're casting to is known to be a scalar, a vector, or a matrix.30623063// Require the operand to be a scalar, a vector, or a matrix.3064if (!SrcType->isScalarType() && !SrcType->isVectorType() &&3065!SrcType->isMatrixType()) {3066Self.Diag(SrcExpr.get()->getExprLoc(),3067diag::err_typecheck_expect_scalar_operand)3068<< SrcType << SrcExpr.get()->getSourceRange();3069SrcExpr = ExprError();3070return;3071}30723073// C23 6.5.4p4:3074// The type nullptr_t shall not be converted to any type other than void,3075// bool, or a pointer type. No type other than nullptr_t shall be converted3076// to nullptr_t.3077if (SrcType->isNullPtrType()) {3078// FIXME: 6.3.2.4p2 says that nullptr_t can be converted to itself, but3079// 6.5.4p4 is a constraint check and nullptr_t is not void, bool, or a3080// pointer type. We're not going to diagnose that as a constraint violation.3081if (!DestType->isVoidType() && !DestType->isBooleanType() &&3082!DestType->isPointerType() && !DestType->isNullPtrType()) {3083Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_nullptr_cast)3084<< /*nullptr to type*/ 0 << DestType;3085SrcExpr = ExprError();3086return;3087}3088if (!DestType->isNullPtrType()) {3089// Implicitly cast from the null pointer type to the type of the3090// destination.3091CastKind CK = DestType->isPointerType() ? CK_NullToPointer : CK_BitCast;3092SrcExpr = ImplicitCastExpr::Create(Self.Context, DestType, CK,3093SrcExpr.get(), nullptr, VK_PRValue,3094Self.CurFPFeatureOverrides());3095}3096}3097if (DestType->isNullPtrType() && !SrcType->isNullPtrType()) {3098Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_nullptr_cast)3099<< /*type to nullptr*/ 1 << SrcType;3100SrcExpr = ExprError();3101return;3102}31033104if (DestType->isExtVectorType()) {3105SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind);3106return;3107}31083109if (DestType->getAs<MatrixType>() || SrcType->getAs<MatrixType>()) {3110if (Self.CheckMatrixCast(OpRange, DestType, SrcType, Kind))3111SrcExpr = ExprError();3112return;3113}31143115if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {3116if (Self.CheckAltivecInitFromScalar(OpRange, DestType, SrcType)) {3117SrcExpr = ExprError();3118return;3119}3120if (Self.ShouldSplatAltivecScalarInCast(DestVecTy) &&3121(SrcType->isIntegerType() || SrcType->isFloatingType())) {3122Kind = CK_VectorSplat;3123SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());3124} else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {3125SrcExpr = ExprError();3126}3127return;3128}31293130if (SrcType->isVectorType()) {3131if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))3132SrcExpr = ExprError();3133return;3134}31353136// The source and target types are both scalars, i.e.3137// - arithmetic types (fundamental, enum, and complex)3138// - all kinds of pointers3139// Note that member pointers were filtered out with C++, above.31403141if (isa<ObjCSelectorExpr>(SrcExpr.get())) {3142Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);3143SrcExpr = ExprError();3144return;3145}31463147// If either type is a pointer, the other type has to be either an3148// integer or a pointer.3149if (!DestType->isArithmeticType()) {3150if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {3151Self.Diag(SrcExpr.get()->getExprLoc(),3152diag::err_cast_pointer_from_non_pointer_int)3153<< SrcType << SrcExpr.get()->getSourceRange();3154SrcExpr = ExprError();3155return;3156}3157checkIntToPointerCast(/* CStyle */ true, OpRange, SrcExpr.get(), DestType,3158Self);3159} else if (!SrcType->isArithmeticType()) {3160if (!DestType->isIntegralType(Self.Context) &&3161DestType->isArithmeticType()) {3162Self.Diag(SrcExpr.get()->getBeginLoc(),3163diag::err_cast_pointer_to_non_pointer_int)3164<< DestType << SrcExpr.get()->getSourceRange();3165SrcExpr = ExprError();3166return;3167}31683169if ((Self.Context.getTypeSize(SrcType) >3170Self.Context.getTypeSize(DestType)) &&3171!DestType->isBooleanType()) {3172// C 6.3.2.3p6: Any pointer type may be converted to an integer type.3173// Except as previously specified, the result is implementation-defined.3174// If the result cannot be represented in the integer type, the behavior3175// is undefined. The result need not be in the range of values of any3176// integer type.3177unsigned Diag;3178if (SrcType->isVoidPointerType())3179Diag = DestType->isEnumeralType() ? diag::warn_void_pointer_to_enum_cast3180: diag::warn_void_pointer_to_int_cast;3181else if (DestType->isEnumeralType())3182Diag = diag::warn_pointer_to_enum_cast;3183else3184Diag = diag::warn_pointer_to_int_cast;3185Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange;3186}3187}31883189if (Self.getLangOpts().OpenCL && !Self.getOpenCLOptions().isAvailableOption(3190"cl_khr_fp16", Self.getLangOpts())) {3191if (DestType->isHalfType()) {3192Self.Diag(SrcExpr.get()->getBeginLoc(), diag::err_opencl_cast_to_half)3193<< DestType << SrcExpr.get()->getSourceRange();3194SrcExpr = ExprError();3195return;3196}3197}31983199// ARC imposes extra restrictions on casts.3200if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) {3201checkObjCConversion(CheckedConversionKind::CStyleCast);3202if (SrcExpr.isInvalid())3203return;32043205const PointerType *CastPtr = DestType->getAs<PointerType>();3206if (Self.getLangOpts().ObjCAutoRefCount && CastPtr) {3207if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {3208Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();3209Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();3210if (CastPtr->getPointeeType()->isObjCLifetimeType() &&3211ExprPtr->getPointeeType()->isObjCLifetimeType() &&3212!CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {3213Self.Diag(SrcExpr.get()->getBeginLoc(),3214diag::err_typecheck_incompatible_ownership)3215<< SrcType << DestType << Sema::AA_Casting3216<< SrcExpr.get()->getSourceRange();3217return;3218}3219}3220} else if (!Self.ObjC().CheckObjCARCUnavailableWeakConversion(DestType,3221SrcType)) {3222Self.Diag(SrcExpr.get()->getBeginLoc(),3223diag::err_arc_convesion_of_weak_unavailable)3224<< 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();3225SrcExpr = ExprError();3226return;3227}3228}32293230if (unsigned DiagID = checkCastFunctionType(Self, SrcExpr, DestType))3231Self.Diag(OpRange.getBegin(), DiagID) << SrcType << DestType << OpRange;32323233if (isa<PointerType>(SrcType) && isa<PointerType>(DestType)) {3234QualType SrcTy = cast<PointerType>(SrcType)->getPointeeType();3235QualType DestTy = cast<PointerType>(DestType)->getPointeeType();32363237const RecordDecl *SrcRD = SrcTy->getAsRecordDecl();3238const RecordDecl *DestRD = DestTy->getAsRecordDecl();32393240if (SrcRD && DestRD && SrcRD->hasAttr<RandomizeLayoutAttr>() &&3241SrcRD != DestRD) {3242// The struct we are casting the pointer from was randomized.3243Self.Diag(OpRange.getBegin(), diag::err_cast_from_randomized_struct)3244<< SrcType << DestType;3245SrcExpr = ExprError();3246return;3247}3248}32493250DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);3251DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);3252DiagnoseBadFunctionCast(Self, SrcExpr, DestType);3253Kind = Self.PrepareScalarCast(SrcExpr, DestType);3254if (SrcExpr.isInvalid())3255return;32563257if (Kind == CK_BitCast)3258checkCastAlign();3259}32603261void CastOperation::CheckBuiltinBitCast() {3262QualType SrcType = SrcExpr.get()->getType();32633264if (Self.RequireCompleteType(OpRange.getBegin(), DestType,3265diag::err_typecheck_cast_to_incomplete) ||3266Self.RequireCompleteType(OpRange.getBegin(), SrcType,3267diag::err_incomplete_type)) {3268SrcExpr = ExprError();3269return;3270}32713272if (SrcExpr.get()->isPRValue())3273SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcType, SrcExpr.get(),3274/*IsLValueReference=*/false);32753276CharUnits DestSize = Self.Context.getTypeSizeInChars(DestType);3277CharUnits SourceSize = Self.Context.getTypeSizeInChars(SrcType);3278if (DestSize != SourceSize) {3279Self.Diag(OpRange.getBegin(), diag::err_bit_cast_type_size_mismatch)3280<< (int)SourceSize.getQuantity() << (int)DestSize.getQuantity();3281SrcExpr = ExprError();3282return;3283}32843285if (!DestType.isTriviallyCopyableType(Self.Context)) {3286Self.Diag(OpRange.getBegin(), diag::err_bit_cast_non_trivially_copyable)3287<< 1;3288SrcExpr = ExprError();3289return;3290}32913292if (!SrcType.isTriviallyCopyableType(Self.Context)) {3293Self.Diag(OpRange.getBegin(), diag::err_bit_cast_non_trivially_copyable)3294<< 0;3295SrcExpr = ExprError();3296return;3297}32983299Kind = CK_LValueToRValueBitCast;3300}33013302/// DiagnoseCastQual - Warn whenever casts discards a qualifiers, be it either3303/// const, volatile or both.3304static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,3305QualType DestType) {3306if (SrcExpr.isInvalid())3307return;33083309QualType SrcType = SrcExpr.get()->getType();3310if (!((SrcType->isAnyPointerType() && DestType->isAnyPointerType()) ||3311DestType->isLValueReferenceType()))3312return;33133314QualType TheOffendingSrcType, TheOffendingDestType;3315Qualifiers CastAwayQualifiers;3316if (CastsAwayConstness(Self, SrcType, DestType, true, false,3317&TheOffendingSrcType, &TheOffendingDestType,3318&CastAwayQualifiers) !=3319CastAwayConstnessKind::CACK_Similar)3320return;33213322// FIXME: 'restrict' is not properly handled here.3323int qualifiers = -1;3324if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) {3325qualifiers = 0;3326} else if (CastAwayQualifiers.hasConst()) {3327qualifiers = 1;3328} else if (CastAwayQualifiers.hasVolatile()) {3329qualifiers = 2;3330}3331// This is a variant of int **x; const int **y = (const int **)x;3332if (qualifiers == -1)3333Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual2)3334<< SrcType << DestType;3335else3336Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual)3337<< TheOffendingSrcType << TheOffendingDestType << qualifiers;3338}33393340ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,3341TypeSourceInfo *CastTypeInfo,3342SourceLocation RPLoc,3343Expr *CastExpr) {3344CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);3345Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();3346Op.OpRange = SourceRange(LPLoc, CastExpr->getEndLoc());33473348if (getLangOpts().CPlusPlus) {3349Op.CheckCXXCStyleCast(/*FunctionalCast=*/ false,3350isa<InitListExpr>(CastExpr));3351} else {3352Op.CheckCStyleCast();3353}33543355if (Op.SrcExpr.isInvalid())3356return ExprError();33573358// -Wcast-qual3359DiagnoseCastQual(Op.Self, Op.SrcExpr, Op.DestType);33603361return Op.complete(CStyleCastExpr::Create(3362Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(),3363&Op.BasePath, CurFPFeatureOverrides(), CastTypeInfo, LPLoc, RPLoc));3364}33653366ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,3367QualType Type,3368SourceLocation LPLoc,3369Expr *CastExpr,3370SourceLocation RPLoc) {3371assert(LPLoc.isValid() && "List-initialization shouldn't get here.");3372CastOperation Op(*this, Type, CastExpr);3373Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();3374Op.OpRange = SourceRange(Op.DestRange.getBegin(), RPLoc);33753376Op.CheckCXXCStyleCast(/*FunctionalCast=*/true, /*ListInit=*/false);3377if (Op.SrcExpr.isInvalid())3378return ExprError();33793380auto *SubExpr = Op.SrcExpr.get();3381if (auto *BindExpr = dyn_cast<CXXBindTemporaryExpr>(SubExpr))3382SubExpr = BindExpr->getSubExpr();3383if (auto *ConstructExpr = dyn_cast<CXXConstructExpr>(SubExpr))3384ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc));33853386// -Wcast-qual3387DiagnoseCastQual(Op.Self, Op.SrcExpr, Op.DestType);33883389return Op.complete(CXXFunctionalCastExpr::Create(3390Context, Op.ResultType, Op.ValueKind, CastTypeInfo, Op.Kind,3391Op.SrcExpr.get(), &Op.BasePath, CurFPFeatureOverrides(), LPLoc, RPLoc));3392}339333943395