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