blob: 0c3757821eb06c1be8b4c1fb87a3d29ec66d4c13 [file] [log] [blame]
John McCalld8d3ced2011-10-11 17:38:55 +00001//===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===//
Sebastian Redl26d85b12008-11-05 21:50:06 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
John McCalld8d3ced2011-10-11 17:38:55 +000010// This file implements semantic analysis for cast expressions, including
11// 1) C-style casts like '(int) x'
12// 2) C++ functional casts like 'int(x)'
13// 3) C++ named casts like 'static_cast<int>(x)'
Sebastian Redl26d85b12008-11-05 21:50:06 +000014//
15//===----------------------------------------------------------------------===//
16
John McCall2d887082010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000018#include "clang/Sema/Initialization.h"
Sebastian Redl26d85b12008-11-05 21:50:06 +000019#include "clang/AST/ExprCXX.h"
John McCalla180f042011-10-06 23:25:11 +000020#include "clang/AST/ExprObjC.h"
Sebastian Redl26d85b12008-11-05 21:50:06 +000021#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redl26d85b12008-11-05 21:50:06 +000024#include "llvm/ADT/SmallVector.h"
Sebastian Redle3dc28a2008-11-07 23:29:29 +000025#include <set>
Sebastian Redl26d85b12008-11-05 21:50:06 +000026using namespace clang;
27
Douglas Gregor8e960432010-11-08 03:40:48 +000028
Douglas Gregor8e960432010-11-08 03:40:48 +000029
Sebastian Redl9cc11e72009-07-25 15:41:38 +000030enum TryCastResult {
31 TC_NotApplicable, ///< The cast method is not applicable.
32 TC_Success, ///< The cast method is appropriate and successful.
33 TC_Failed ///< The cast method is appropriate, but failed. A
34 ///< diagnostic has been emitted.
35};
36
37enum CastType {
38 CT_Const, ///< const_cast
39 CT_Static, ///< static_cast
40 CT_Reinterpret, ///< reinterpret_cast
41 CT_Dynamic, ///< dynamic_cast
42 CT_CStyle, ///< (Type)expr
43 CT_Functional ///< Type(expr)
Sebastian Redl37d6de32008-11-08 13:00:26 +000044};
45
John McCallb45ae252011-10-05 07:41:44 +000046namespace {
47 struct CastOperation {
48 CastOperation(Sema &S, QualType destType, ExprResult src)
49 : Self(S), SrcExpr(src), DestType(destType),
50 ResultType(destType.getNonLValueExprType(S.Context)),
51 ValueKind(Expr::getValueKindForType(destType)),
John McCall5acb0c92011-10-17 18:40:02 +000052 Kind(CK_Dependent), IsARCUnbridgedCast(false) {
John McCalla180f042011-10-06 23:25:11 +000053
54 if (const BuiltinType *placeholder =
55 src.get()->getType()->getAsPlaceholderType()) {
56 PlaceholderKind = placeholder->getKind();
57 } else {
58 PlaceholderKind = (BuiltinType::Kind) 0;
59 }
60 }
Douglas Gregor8e960432010-11-08 03:40:48 +000061
John McCallb45ae252011-10-05 07:41:44 +000062 Sema &Self;
63 ExprResult SrcExpr;
64 QualType DestType;
65 QualType ResultType;
66 ExprValueKind ValueKind;
67 CastKind Kind;
John McCalla180f042011-10-06 23:25:11 +000068 BuiltinType::Kind PlaceholderKind;
John McCallb45ae252011-10-05 07:41:44 +000069 CXXCastPath BasePath;
John McCall5acb0c92011-10-17 18:40:02 +000070 bool IsARCUnbridgedCast;
Douglas Gregor8e960432010-11-08 03:40:48 +000071
John McCallb45ae252011-10-05 07:41:44 +000072 SourceRange OpRange;
73 SourceRange DestRange;
Douglas Gregor8e960432010-11-08 03:40:48 +000074
John McCalla180f042011-10-06 23:25:11 +000075 // Top-level semantics-checking routines.
John McCallb45ae252011-10-05 07:41:44 +000076 void CheckConstCast();
77 void CheckReinterpretCast();
Richard Smithc8d7f582011-11-29 22:48:16 +000078 void CheckStaticCast();
John McCallb45ae252011-10-05 07:41:44 +000079 void CheckDynamicCast();
Sebastian Redl6dc00f62012-02-12 18:41:05 +000080 void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
John McCalla180f042011-10-06 23:25:11 +000081 void CheckCStyleCast();
82
John McCall5acb0c92011-10-17 18:40:02 +000083 /// Complete an apparently-successful cast operation that yields
84 /// the given expression.
85 ExprResult complete(CastExpr *castExpr) {
86 // If this is an unbridged cast, wrap the result in an implicit
87 // cast that yields the unbridged-cast placeholder type.
88 if (IsARCUnbridgedCast) {
89 castExpr = ImplicitCastExpr::Create(Self.Context,
90 Self.Context.ARCUnbridgedCastTy,
91 CK_Dependent, castExpr, 0,
92 castExpr->getValueKind());
93 }
94 return Self.Owned(castExpr);
95 }
96
John McCalla180f042011-10-06 23:25:11 +000097 // Internal convenience methods.
98
99 /// Try to handle the given placeholder expression kind. Return
100 /// true if the source expression has the appropriate placeholder
101 /// kind. A placeholder can only be claimed once.
102 bool claimPlaceholder(BuiltinType::Kind K) {
103 if (PlaceholderKind != K) return false;
104
105 PlaceholderKind = (BuiltinType::Kind) 0;
106 return true;
107 }
108
109 bool isPlaceholder() const {
110 return PlaceholderKind != 0;
111 }
112 bool isPlaceholder(BuiltinType::Kind K) const {
113 return PlaceholderKind == K;
114 }
John McCallb45ae252011-10-05 07:41:44 +0000115
116 void checkCastAlign() {
117 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
118 }
119
120 void checkObjCARCConversion(Sema::CheckedConversionKind CCK) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000121 assert(Self.getLangOpts().ObjCAutoRefCount);
John McCall5acb0c92011-10-17 18:40:02 +0000122
John McCallb45ae252011-10-05 07:41:44 +0000123 Expr *src = SrcExpr.get();
John McCall5acb0c92011-10-17 18:40:02 +0000124 if (Self.CheckObjCARCConversion(OpRange, DestType, src, CCK) ==
125 Sema::ACR_unbridged)
126 IsARCUnbridgedCast = true;
John McCallb45ae252011-10-05 07:41:44 +0000127 SrcExpr = src;
128 }
John McCalla180f042011-10-06 23:25:11 +0000129
130 /// Check for and handle non-overload placeholder expressions.
131 void checkNonOverloadPlaceholders() {
132 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
133 return;
134
135 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
136 if (SrcExpr.isInvalid())
137 return;
138 PlaceholderKind = (BuiltinType::Kind) 0;
139 }
John McCallb45ae252011-10-05 07:41:44 +0000140 };
141}
Sebastian Redl37d6de32008-11-08 13:00:26 +0000142
John McCallf85e1932011-06-15 23:02:42 +0000143static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
144 bool CheckCVR, bool CheckObjCLifetime);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000145
146// The Try functions attempt a specific way of casting. If they succeed, they
147// return TC_Success. If their way of casting is not appropriate for the given
148// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
149// to emit if no other way succeeds. If their way of casting is appropriate but
150// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
151// they emit a specialized diagnostic.
152// All diagnostics returned by these functions must expect the same three
153// arguments:
154// %0: Cast Type (a value from the CastType enumeration)
155// %1: Source Type
156// %2: Destination Type
157static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000158 QualType DestType, bool CStyle,
159 CastKind &Kind,
Douglas Gregor88b22a42011-01-25 16:13:26 +0000160 CXXCastPath &BasePath,
161 unsigned &msg);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000162static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000163 QualType DestType, bool CStyle,
164 const SourceRange &OpRange,
165 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000166 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000167 CXXCastPath &BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000168static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
169 QualType DestType, bool CStyle,
170 const SourceRange &OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000171 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000172 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000173 CXXCastPath &BasePath);
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000174static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
175 CanQualType DestType, bool CStyle,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000176 const SourceRange &OpRange,
177 QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000178 QualType OrigDestType, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000179 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000180 CXXCastPath &BasePath);
John Wiegley429bb272011-04-08 18:41:53 +0000181static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
Anders Carlssoncee22422010-04-24 19:22:20 +0000182 QualType SrcType,
183 QualType DestType,bool CStyle,
184 const SourceRange &OpRange,
185 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000186 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000187 CXXCastPath &BasePath);
Anders Carlssoncee22422010-04-24 19:22:20 +0000188
John Wiegley429bb272011-04-08 18:41:53 +0000189static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
John McCallf85e1932011-06-15 23:02:42 +0000190 QualType DestType,
191 Sema::CheckedConversionKind CCK,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000192 const SourceRange &OpRange,
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000193 unsigned &msg, CastKind &Kind,
194 bool ListInitialization);
John Wiegley429bb272011-04-08 18:41:53 +0000195static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCallf85e1932011-06-15 23:02:42 +0000196 QualType DestType,
197 Sema::CheckedConversionKind CCK,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000198 const SourceRange &OpRange,
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000199 unsigned &msg, CastKind &Kind,
200 CXXCastPath &BasePath,
201 bool ListInitialization);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000202static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
203 bool CStyle, unsigned &msg);
John Wiegley429bb272011-04-08 18:41:53 +0000204static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000205 QualType DestType, bool CStyle,
206 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000207 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000208 CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +0000209
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000210
Sebastian Redl26d85b12008-11-05 21:50:06 +0000211/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
John McCall60d7b3a2010-08-24 06:29:42 +0000212ExprResult
Sebastian Redl26d85b12008-11-05 21:50:06 +0000213Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +0000214 SourceLocation LAngleBracketLoc, Declarator &D,
Sebastian Redl26d85b12008-11-05 21:50:06 +0000215 SourceLocation RAngleBracketLoc,
John McCallf312b1e2010-08-26 23:41:50 +0000216 SourceLocation LParenLoc, Expr *E,
Sebastian Redl26d85b12008-11-05 21:50:06 +0000217 SourceLocation RParenLoc) {
John McCallc89724c2010-01-15 19:13:16 +0000218
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +0000219 assert(!D.isInvalidType());
220
221 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
222 if (D.isInvalidType())
223 return ExprError();
224
David Blaikie4e4d0842012-03-11 07:00:24 +0000225 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +0000226 // Check that there are no default arguments (C++ only).
227 CheckExtraCXXDefaultArguments(D);
228 }
229
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000230 return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
John McCallc89724c2010-01-15 19:13:16 +0000231 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
232 SourceRange(LParenLoc, RParenLoc));
233}
234
John McCall60d7b3a2010-08-24 06:29:42 +0000235ExprResult
John McCallc89724c2010-01-15 19:13:16 +0000236Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John Wiegley429bb272011-04-08 18:41:53 +0000237 TypeSourceInfo *DestTInfo, Expr *E,
John McCallc89724c2010-01-15 19:13:16 +0000238 SourceRange AngleBrackets, SourceRange Parens) {
John Wiegley429bb272011-04-08 18:41:53 +0000239 ExprResult Ex = Owned(E);
John McCallc89724c2010-01-15 19:13:16 +0000240 QualType DestType = DestTInfo->getType();
241
Douglas Gregor9103bb22008-12-17 22:52:20 +0000242 // If the type is dependent, we won't do the semantic analysis now.
243 // FIXME: should we check this in a more fine-grained manner?
John Wiegley429bb272011-04-08 18:41:53 +0000244 bool TypeDependent = DestType->isDependentType() || Ex.get()->isTypeDependent();
Douglas Gregor9103bb22008-12-17 22:52:20 +0000245
John McCallb45ae252011-10-05 07:41:44 +0000246 CastOperation Op(*this, DestType, E);
247 Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
248 Op.DestRange = AngleBrackets;
John McCalla21e06c2010-11-26 10:57:22 +0000249
Sebastian Redl26d85b12008-11-05 21:50:06 +0000250 switch (Kind) {
John McCalldaa8e4e2010-11-15 09:13:47 +0000251 default: llvm_unreachable("Unknown C++ cast!");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000252
253 case tok::kw_const_cast:
John Wiegley429bb272011-04-08 18:41:53 +0000254 if (!TypeDependent) {
John McCallb45ae252011-10-05 07:41:44 +0000255 Op.CheckConstCast();
256 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000257 return ExprError();
258 }
John McCall5acb0c92011-10-17 18:40:02 +0000259 return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
260 Op.ValueKind, Op.SrcExpr.take(), DestTInfo,
261 OpLoc, Parens.getEnd()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000262
Anders Carlsson714179b2009-08-02 19:07:59 +0000263 case tok::kw_dynamic_cast: {
John Wiegley429bb272011-04-08 18:41:53 +0000264 if (!TypeDependent) {
John McCallb45ae252011-10-05 07:41:44 +0000265 Op.CheckDynamicCast();
266 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000267 return ExprError();
268 }
John McCall5acb0c92011-10-17 18:40:02 +0000269 return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
270 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
271 &Op.BasePath, DestTInfo,
272 OpLoc, Parens.getEnd()));
Anders Carlsson714179b2009-08-02 19:07:59 +0000273 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000274 case tok::kw_reinterpret_cast: {
John Wiegley429bb272011-04-08 18:41:53 +0000275 if (!TypeDependent) {
John McCallb45ae252011-10-05 07:41:44 +0000276 Op.CheckReinterpretCast();
277 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000278 return ExprError();
279 }
John McCall5acb0c92011-10-17 18:40:02 +0000280 return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
281 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
282 0, DestTInfo, OpLoc,
283 Parens.getEnd()));
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000284 }
Anders Carlssoncdb61972009-08-07 22:21:05 +0000285 case tok::kw_static_cast: {
John Wiegley429bb272011-04-08 18:41:53 +0000286 if (!TypeDependent) {
Richard Smithc8d7f582011-11-29 22:48:16 +0000287 Op.CheckStaticCast();
John McCallb45ae252011-10-05 07:41:44 +0000288 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000289 return ExprError();
290 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000291
John McCall5acb0c92011-10-17 18:40:02 +0000292 return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
293 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
294 &Op.BasePath, DestTInfo,
295 OpLoc, Parens.getEnd()));
Anders Carlssoncdb61972009-08-07 22:21:05 +0000296 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000297 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000298}
299
John McCall79ab2c82011-02-14 18:34:10 +0000300/// Try to diagnose a failed overloaded cast. Returns true if
301/// diagnostics were emitted.
302static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
303 SourceRange range, Expr *src,
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000304 QualType destType,
305 bool listInitialization) {
John McCall79ab2c82011-02-14 18:34:10 +0000306 switch (CT) {
307 // These cast kinds don't consider user-defined conversions.
308 case CT_Const:
309 case CT_Reinterpret:
310 case CT_Dynamic:
311 return false;
312
313 // These do.
314 case CT_Static:
315 case CT_CStyle:
316 case CT_Functional:
317 break;
318 }
319
320 QualType srcType = src->getType();
321 if (!destType->isRecordType() && !srcType->isRecordType())
322 return false;
323
324 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
325 InitializationKind initKind
John McCallf85e1932011-06-15 23:02:42 +0000326 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000327 range, listInitialization)
Sebastian Redl3a45c0e2012-02-12 16:37:36 +0000328 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000329 listInitialization)
Richard Smithc8d7f582011-11-29 22:48:16 +0000330 : InitializationKind::CreateCast(/*type range?*/ range);
John McCall79ab2c82011-02-14 18:34:10 +0000331 InitializationSequence sequence(S, entity, initKind, &src, 1);
332
Sebastian Redl383616c2011-06-05 12:23:28 +0000333 assert(sequence.Failed() && "initialization succeeded on second try?");
John McCall79ab2c82011-02-14 18:34:10 +0000334 switch (sequence.getFailureKind()) {
335 default: return false;
336
337 case InitializationSequence::FK_ConstructorOverloadFailed:
338 case InitializationSequence::FK_UserConversionOverloadFailed:
339 break;
340 }
341
342 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
343
344 unsigned msg = 0;
345 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
346
347 switch (sequence.getFailedOverloadResult()) {
348 case OR_Success: llvm_unreachable("successful failed overload");
John McCall79ab2c82011-02-14 18:34:10 +0000349 case OR_No_Viable_Function:
350 if (candidates.empty())
351 msg = diag::err_ovl_no_conversion_in_cast;
352 else
353 msg = diag::err_ovl_no_viable_conversion_in_cast;
354 howManyCandidates = OCD_AllCandidates;
355 break;
356
357 case OR_Ambiguous:
358 msg = diag::err_ovl_ambiguous_conversion_in_cast;
359 howManyCandidates = OCD_ViableCandidates;
360 break;
361
362 case OR_Deleted:
363 msg = diag::err_ovl_deleted_conversion_in_cast;
364 howManyCandidates = OCD_ViableCandidates;
365 break;
366 }
367
368 S.Diag(range.getBegin(), msg)
369 << CT << srcType << destType
370 << range << src->getSourceRange();
371
Ahmed Charles13a140c2012-02-25 11:00:22 +0000372 candidates.NoteCandidates(S, howManyCandidates, src);
John McCall79ab2c82011-02-14 18:34:10 +0000373
374 return true;
375}
376
377/// Diagnose a failed cast.
378static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000379 SourceRange opRange, Expr *src, QualType destType,
380 bool listInitialization) {
John McCall864c0412011-04-26 20:42:42 +0000381 if (src->getType() == S.Context.BoundMemberTy) {
382 (void) S.CheckPlaceholderExpr(src); // will always fail
383 return;
384 }
385
John McCall79ab2c82011-02-14 18:34:10 +0000386 if (msg == diag::err_bad_cxx_cast_generic &&
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000387 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
388 listInitialization))
John McCall79ab2c82011-02-14 18:34:10 +0000389 return;
390
391 S.Diag(opRange.getBegin(), msg) << castType
392 << src->getType() << destType << opRange << src->getSourceRange();
393}
394
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000395/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
396/// this removes one level of indirection from both types, provided that they're
397/// the same kind of pointer (plain or to-member). Unlike the Sema function,
398/// this one doesn't care if the two pointers-to-member don't point into the
399/// same class. This is because CastsAwayConstness doesn't care.
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000400static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000401 const PointerType *T1PtrType = T1->getAs<PointerType>(),
402 *T2PtrType = T2->getAs<PointerType>();
403 if (T1PtrType && T2PtrType) {
404 T1 = T1PtrType->getPointeeType();
405 T2 = T2PtrType->getPointeeType();
406 return true;
407 }
Fariborz Jahanian72a86592010-02-03 20:32:31 +0000408 const ObjCObjectPointerType *T1ObjCPtrType =
409 T1->getAs<ObjCObjectPointerType>(),
410 *T2ObjCPtrType =
411 T2->getAs<ObjCObjectPointerType>();
412 if (T1ObjCPtrType) {
413 if (T2ObjCPtrType) {
414 T1 = T1ObjCPtrType->getPointeeType();
415 T2 = T2ObjCPtrType->getPointeeType();
416 return true;
417 }
418 else if (T2PtrType) {
419 T1 = T1ObjCPtrType->getPointeeType();
420 T2 = T2PtrType->getPointeeType();
421 return true;
422 }
423 }
424 else if (T2ObjCPtrType) {
425 if (T1PtrType) {
426 T2 = T2ObjCPtrType->getPointeeType();
427 T1 = T1PtrType->getPointeeType();
428 return true;
429 }
430 }
431
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000432 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
433 *T2MPType = T2->getAs<MemberPointerType>();
434 if (T1MPType && T2MPType) {
435 T1 = T1MPType->getPointeeType();
436 T2 = T2MPType->getPointeeType();
437 return true;
438 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000439
440 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
441 *T2BPType = T2->getAs<BlockPointerType>();
442 if (T1BPType && T2BPType) {
443 T1 = T1BPType->getPointeeType();
444 T2 = T2BPType->getPointeeType();
445 return true;
446 }
447
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000448 return false;
449}
450
Sebastian Redldb647282009-01-27 23:18:31 +0000451/// CastsAwayConstness - Check if the pointer conversion from SrcType to
452/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
453/// the cast checkers. Both arguments must denote pointer (possibly to member)
454/// types.
John McCallf85e1932011-06-15 23:02:42 +0000455///
456/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
457///
458/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000459static bool
John McCallf85e1932011-06-15 23:02:42 +0000460CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
461 bool CheckCVR, bool CheckObjCLifetime) {
462 // If the only checking we care about is for Objective-C lifetime qualifiers,
463 // and we're not in ARC mode, there's nothing to check.
464 if (!CheckCVR && CheckObjCLifetime &&
David Blaikie4e4d0842012-03-11 07:00:24 +0000465 !Self.Context.getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +0000466 return false;
467
Sebastian Redldb647282009-01-27 23:18:31 +0000468 // Casting away constness is defined in C++ 5.2.11p8 with reference to
469 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
470 // the rules are non-trivial. So first we construct Tcv *...cv* as described
471 // in C++ 5.2.11p8.
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000472 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
473 SrcType->isBlockPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000474 "Source type is not pointer or pointer to member.");
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000475 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
476 DestType->isBlockPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000477 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000478
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000479 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
480 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000481 SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000482
Douglas Gregord4c5f842011-04-15 17:59:54 +0000483 // Find the qualifiers. We only care about cvr-qualifiers for the
484 // purpose of this check, because other qualifiers (address spaces,
485 // Objective-C GC, etc.) are part of the type's identity.
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000486 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCallf85e1932011-06-15 23:02:42 +0000487 // Determine the relevant qualifiers at this level.
488 Qualifiers SrcQuals, DestQuals;
Anders Carlsson52647c62010-06-04 22:47:55 +0000489 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
Anders Carlsson52647c62010-06-04 22:47:55 +0000490 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
John McCallf85e1932011-06-15 23:02:42 +0000491
492 Qualifiers RetainedSrcQuals, RetainedDestQuals;
493 if (CheckCVR) {
494 RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
495 RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
496 }
497
498 if (CheckObjCLifetime &&
499 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
500 return true;
501
502 cv1.push_back(RetainedSrcQuals);
503 cv2.push_back(RetainedDestQuals);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000504 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000505 if (cv1.empty())
506 return false;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000507
508 // Construct void pointers with those qualifiers (in reverse order of
509 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000510 QualType SrcConstruct = Self.Context.VoidTy;
511 QualType DestConstruct = Self.Context.VoidTy;
John McCall0953e762009-09-24 19:53:00 +0000512 ASTContext &Context = Self.Context;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000513 for (SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
John McCall0953e762009-09-24 19:53:00 +0000514 i2 = cv2.rbegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000515 i1 != cv1.rend(); ++i1, ++i2) {
John McCall0953e762009-09-24 19:53:00 +0000516 SrcConstruct
517 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
518 DestConstruct
519 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000520 }
521
522 // Test if they're compatible.
John McCallf85e1932011-06-15 23:02:42 +0000523 bool ObjCLifetimeConversion;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000524 return SrcConstruct != DestConstruct &&
John McCallf85e1932011-06-15 23:02:42 +0000525 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
526 ObjCLifetimeConversion);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000527}
528
Sebastian Redl26d85b12008-11-05 21:50:06 +0000529/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
530/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
531/// checked downcasts in class hierarchies.
John McCallb45ae252011-10-05 07:41:44 +0000532void CastOperation::CheckDynamicCast() {
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000533 if (ValueKind == VK_RValue)
Eli Friedman7a420df2011-10-31 20:59:03 +0000534 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000535 else if (isPlaceholder())
536 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
537 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
538 return;
Eli Friedman7a420df2011-10-31 20:59:03 +0000539
John McCallb45ae252011-10-05 07:41:44 +0000540 QualType OrigSrcType = SrcExpr.get()->getType();
541 QualType DestType = Self.Context.getCanonicalType(this->DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000542
543 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
544 // or "pointer to cv void".
545
546 QualType DestPointee;
Ted Kremenek6217b802009-07-29 21:53:49 +0000547 const PointerType *DestPointer = DestType->getAs<PointerType>();
John McCallf89e55a2010-11-18 06:31:45 +0000548 const ReferenceType *DestReference = 0;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000549 if (DestPointer) {
550 DestPointee = DestPointer->getPointeeType();
John McCallf89e55a2010-11-18 06:31:45 +0000551 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000552 DestPointee = DestReference->getPointeeType();
553 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000554 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
John McCallb45ae252011-10-05 07:41:44 +0000555 << this->DestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000556 return;
557 }
558
Ted Kremenek6217b802009-07-29 21:53:49 +0000559 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000560 if (DestPointee->isVoidType()) {
561 assert(DestPointer && "Reference to void is not possible");
562 } else if (DestRecord) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000563 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregord10099e2012-05-04 16:32:21 +0000564 diag::err_bad_dynamic_cast_incomplete,
565 DestRange))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000566 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000567 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000568 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000569 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000570 return;
571 }
572
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000573 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
574 // complete class type, [...]. If T is an lvalue reference type, v shall be
Douglas Gregordc843f22011-01-22 00:06:57 +0000575 // an lvalue of a complete class type, [...]. If T is an rvalue reference
576 // type, v shall be an expression having a complete class type, [...]
Sebastian Redl37d6de32008-11-08 13:00:26 +0000577 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000578 QualType SrcPointee;
579 if (DestPointer) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000580 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000581 SrcPointee = SrcPointer->getPointeeType();
582 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000583 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
John Wiegley429bb272011-04-08 18:41:53 +0000584 << OrigSrcType << SrcExpr.get()->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000585 return;
586 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000587 } else if (DestReference->isLValueReferenceType()) {
John Wiegley429bb272011-04-08 18:41:53 +0000588 if (!SrcExpr.get()->isLValue()) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000589 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
John McCallb45ae252011-10-05 07:41:44 +0000590 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000591 }
592 SrcPointee = SrcType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000593 } else {
594 SrcPointee = SrcType;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000595 }
596
Ted Kremenek6217b802009-07-29 21:53:49 +0000597 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000598 if (SrcRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000599 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregord10099e2012-05-04 16:32:21 +0000600 diag::err_bad_dynamic_cast_incomplete,
601 SrcExpr.get()))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000602 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000603 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000604 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
John Wiegley429bb272011-04-08 18:41:53 +0000605 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000606 return;
607 }
608
609 assert((DestPointer || DestReference) &&
610 "Bad destination non-ptr/ref slipped through.");
611 assert((DestRecord || DestPointee->isVoidType()) &&
612 "Bad destination pointee slipped through.");
613 assert(SrcRecord && "Bad source pointee slipped through.");
614
615 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
616 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +0000617 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
John McCallb45ae252011-10-05 07:41:44 +0000618 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000619 return;
620 }
621
622 // C++ 5.2.7p3: If the type of v is the same as the required result type,
623 // [except for cv].
624 if (DestRecord == SrcRecord) {
John McCall2de56d12010-08-25 11:45:40 +0000625 Kind = CK_NoOp;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000626 return;
627 }
628
629 // C++ 5.2.7p5
630 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000631 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000632 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
633 OpRange.getBegin(), OpRange,
634 &BasePath))
635 return;
636
John McCall2de56d12010-08-25 11:45:40 +0000637 Kind = CK_DerivedToBase;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000638
639 // If we are casting to or through a virtual base class, we need a
640 // vtable.
641 if (Self.BasePathInvolvesVirtualBase(BasePath))
642 Self.MarkVTableUsed(OpRange.getBegin(),
643 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000644 return;
645 }
646
647 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor952b0172010-02-11 01:04:33 +0000648 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000649 assert(SrcDecl && "Definition missing");
650 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000651 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
John Wiegley429bb272011-04-08 18:41:53 +0000652 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000653 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000654 Self.MarkVTableUsed(OpRange.getBegin(),
655 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000656
657 // Done. Everything else is run-time checks.
John McCall2de56d12010-08-25 11:45:40 +0000658 Kind = CK_Dynamic;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000659}
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000660
661/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
662/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
663/// like this:
664/// const char *str = "literal";
665/// legacy_function(const_cast\<char*\>(str));
John McCallb45ae252011-10-05 07:41:44 +0000666void CastOperation::CheckConstCast() {
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000667 if (ValueKind == VK_RValue)
John Wiegley429bb272011-04-08 18:41:53 +0000668 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000669 else if (isPlaceholder())
670 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
671 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
672 return;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000673
674 unsigned msg = diag::err_bad_cxx_cast_generic;
John Wiegley429bb272011-04-08 18:41:53 +0000675 if (TryConstCast(Self, SrcExpr.get(), DestType, /*CStyle*/false, msg) != TC_Success
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000676 && msg != 0)
677 Self.Diag(OpRange.getBegin(), msg) << CT_Const
John Wiegley429bb272011-04-08 18:41:53 +0000678 << SrcExpr.get()->getType() << DestType << OpRange;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000679}
680
681/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
682/// valid.
683/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
684/// like this:
685/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
John McCallb45ae252011-10-05 07:41:44 +0000686void CastOperation::CheckReinterpretCast() {
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000687 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
John Wiegley429bb272011-04-08 18:41:53 +0000688 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000689 else
690 checkNonOverloadPlaceholders();
691 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
692 return;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000693
694 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCallf85e1932011-06-15 23:02:42 +0000695 TryCastResult tcr =
696 TryReinterpretCast(Self, SrcExpr, DestType,
697 /*CStyle*/false, OpRange, msg, Kind);
698 if (tcr != TC_Success && msg != 0)
Douglas Gregor8e960432010-11-08 03:40:48 +0000699 {
John Wiegley429bb272011-04-08 18:41:53 +0000700 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
701 return;
702 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor8e960432010-11-08 03:40:48 +0000703 //FIXME: &f<int>; is overloaded and resolvable
704 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
John Wiegley429bb272011-04-08 18:41:53 +0000705 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
Douglas Gregor8e960432010-11-08 03:40:48 +0000706 << DestType << OpRange;
John Wiegley429bb272011-04-08 18:41:53 +0000707 Self.NoteAllOverloadCandidates(SrcExpr.get());
Douglas Gregor8e960432010-11-08 03:40:48 +0000708
John McCall79ab2c82011-02-14 18:34:10 +0000709 } else {
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000710 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
711 DestType, /*listInitialization=*/false);
Douglas Gregor8e960432010-11-08 03:40:48 +0000712 }
David Blaikie4e4d0842012-03-11 07:00:24 +0000713 } else if (tcr == TC_Success && Self.getLangOpts().ObjCAutoRefCount) {
John McCallb45ae252011-10-05 07:41:44 +0000714 checkObjCARCConversion(Sema::CCK_OtherCast);
John McCallf85e1932011-06-15 23:02:42 +0000715 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000716}
717
718
719/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
720/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
721/// implicit conversions explicit and getting rid of data loss warnings.
Richard Smithc8d7f582011-11-29 22:48:16 +0000722void CastOperation::CheckStaticCast() {
John McCalla180f042011-10-06 23:25:11 +0000723 if (isPlaceholder()) {
724 checkNonOverloadPlaceholders();
725 if (SrcExpr.isInvalid())
726 return;
727 }
728
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000729 // This test is outside everything else because it's the only case where
730 // a non-lvalue-reference target type does not lead to decay.
731 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000732 if (DestType->isVoidType()) {
John McCalla180f042011-10-06 23:25:11 +0000733 Kind = CK_ToVoid;
734
735 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall6dbba4f2011-10-11 23:14:30 +0000736 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000737 false, // Decay Function to ptr
738 true, // Complain
739 OpRange, DestType, diag::err_bad_static_cast_overload);
John McCall6dbba4f2011-10-11 23:14:30 +0000740 if (SrcExpr.isInvalid())
741 return;
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000742 }
John McCalla180f042011-10-06 23:25:11 +0000743
744 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000745 return;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000746 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000747
John McCall6dbba4f2011-10-11 23:14:30 +0000748 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
749 !isPlaceholder(BuiltinType::Overload)) {
John Wiegley429bb272011-04-08 18:41:53 +0000750 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
751 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
752 return;
753 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000754
755 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCallf85e1932011-06-15 23:02:42 +0000756 TryCastResult tcr
Richard Smithc8d7f582011-11-29 22:48:16 +0000757 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000758 Kind, BasePath, /*ListInitialization=*/false);
John McCallf85e1932011-06-15 23:02:42 +0000759 if (tcr != TC_Success && msg != 0) {
John Wiegley429bb272011-04-08 18:41:53 +0000760 if (SrcExpr.isInvalid())
761 return;
762 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
763 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
Douglas Gregor8e960432010-11-08 03:40:48 +0000764 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
Douglas Gregor4c9be892011-02-28 20:01:57 +0000765 << oe->getName() << DestType << OpRange
766 << oe->getQualifierLoc().getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +0000767 Self.NoteAllOverloadCandidates(SrcExpr.get());
John McCall79ab2c82011-02-14 18:34:10 +0000768 } else {
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000769 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
770 /*listInitialization=*/false);
Douglas Gregor8e960432010-11-08 03:40:48 +0000771 }
John McCallf85e1932011-06-15 23:02:42 +0000772 } else if (tcr == TC_Success) {
773 if (Kind == CK_BitCast)
John McCallb45ae252011-10-05 07:41:44 +0000774 checkCastAlign();
David Blaikie4e4d0842012-03-11 07:00:24 +0000775 if (Self.getLangOpts().ObjCAutoRefCount)
Richard Smithc8d7f582011-11-29 22:48:16 +0000776 checkObjCARCConversion(Sema::CCK_OtherCast);
John McCallb45ae252011-10-05 07:41:44 +0000777 } else if (Kind == CK_BitCast) {
778 checkCastAlign();
Douglas Gregor8e960432010-11-08 03:40:48 +0000779 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000780}
781
782/// TryStaticCast - Check if a static cast can be performed, and do so if
783/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
784/// and casting away constness.
John Wiegley429bb272011-04-08 18:41:53 +0000785static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCallf85e1932011-06-15 23:02:42 +0000786 QualType DestType,
787 Sema::CheckedConversionKind CCK,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000788 const SourceRange &OpRange, unsigned &msg,
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000789 CastKind &Kind, CXXCastPath &BasePath,
790 bool ListInitialization) {
John McCallf85e1932011-06-15 23:02:42 +0000791 // Determine whether we have the semantics of a C-style cast.
792 bool CStyle
793 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
794
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000795 // The order the tests is not entirely arbitrary. There is one conversion
796 // that can be handled in two different ways. Given:
797 // struct A {};
798 // struct B : public A {
799 // B(); B(const A&);
800 // };
801 // const A &a = B();
802 // the cast static_cast<const B&>(a) could be seen as either a static
803 // reference downcast, or an explicit invocation of the user-defined
804 // conversion using B's conversion constructor.
805 // DR 427 specifies that the downcast is to be applied here.
806
807 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
808 // Done outside this function.
809
810 TryCastResult tcr;
811
812 // C++ 5.2.9p5, reference downcast.
813 // See the function for details.
814 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000815 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
816 OpRange, msg, Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000817 if (tcr != TC_NotApplicable)
818 return tcr;
819
Douglas Gregordc843f22011-01-22 00:06:57 +0000820 // C++0x [expr.static.cast]p3:
821 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
822 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000823 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
824 BasePath, msg);
Douglas Gregor88b22a42011-01-25 16:13:26 +0000825 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000826 return tcr;
827
828 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
829 // [...] if the declaration "T t(e);" is well-formed, [...].
John McCallf85e1932011-06-15 23:02:42 +0000830 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000831 Kind, ListInitialization);
John Wiegley429bb272011-04-08 18:41:53 +0000832 if (SrcExpr.isInvalid())
833 return TC_Failed;
Anders Carlsson3c31a392009-09-26 00:12:34 +0000834 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000835 return tcr;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000836
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000837 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
838 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
839 // conversions, subject to further restrictions.
840 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
841 // of qualification conversions impossible.
842 // In the CStyle case, the earlier attempt to const_cast should have taken
843 // care of reverse qualification conversions.
844
John Wiegley429bb272011-04-08 18:41:53 +0000845 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000846
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000847 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
Douglas Gregor1e856d92011-02-18 03:01:41 +0000848 // converted to an integral type. [...] A value of a scoped enumeration type
849 // can also be explicitly converted to a floating-point type [...].
850 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
851 if (Enum->getDecl()->isScoped()) {
852 if (DestType->isBooleanType()) {
853 Kind = CK_IntegralToBoolean;
854 return TC_Success;
855 } else if (DestType->isIntegralType(Self.Context)) {
856 Kind = CK_IntegralCast;
857 return TC_Success;
858 } else if (DestType->isRealFloatingType()) {
859 Kind = CK_IntegralToFloating;
860 return TC_Success;
861 }
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000862 }
863 }
Douglas Gregor1e856d92011-02-18 03:01:41 +0000864
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000865 // Reverse integral promotion/conversion. All such conversions are themselves
866 // again integral promotions or conversions and are thus already handled by
867 // p2 (TryDirectInitialization above).
868 // (Note: any data loss warnings should be suppressed.)
869 // The exception is the reverse of enum->integer, i.e. integer->enum (and
870 // enum->enum). See also C++ 5.2.9p7.
871 // The same goes for reverse floating point promotion/conversion and
872 // floating-integral conversions. Again, only floating->enum is relevant.
873 if (DestType->isEnumeralType()) {
Eli Friedmancc2fca22011-09-02 17:38:59 +0000874 if (SrcType->isIntegralOrEnumerationType()) {
John McCall2de56d12010-08-25 11:45:40 +0000875 Kind = CK_IntegralCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000876 return TC_Success;
Eli Friedmancc2fca22011-09-02 17:38:59 +0000877 } else if (SrcType->isRealFloatingType()) {
878 Kind = CK_FloatingToIntegral;
879 return TC_Success;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000880 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000881 }
882
883 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
884 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000885 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000886 Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000887 if (tcr != TC_NotApplicable)
888 return tcr;
889
890 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
891 // conversion. C++ 5.2.9p9 has additional information.
892 // DR54's access restrictions apply here also.
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000893 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssoncee22422010-04-24 19:22:20 +0000894 OpRange, msg, Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000895 if (tcr != TC_NotApplicable)
896 return tcr;
897
898 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
899 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
900 // just the usual constness stuff.
Ted Kremenek6217b802009-07-29 21:53:49 +0000901 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000902 QualType SrcPointee = SrcPointer->getPointeeType();
903 if (SrcPointee->isVoidType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000904 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000905 QualType DestPointee = DestPointer->getPointeeType();
906 if (DestPointee->isIncompleteOrObjectType()) {
907 // This is definitely the intended conversion, but it might fail due
John McCallf85e1932011-06-15 23:02:42 +0000908 // to a qualifier violation. Note that we permit Objective-C lifetime
909 // and GC qualifier mismatches here.
910 if (!CStyle) {
911 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
912 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
913 DestPointeeQuals.removeObjCGCAttr();
914 DestPointeeQuals.removeObjCLifetime();
915 SrcPointeeQuals.removeObjCGCAttr();
916 SrcPointeeQuals.removeObjCLifetime();
917 if (DestPointeeQuals != SrcPointeeQuals &&
918 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
919 msg = diag::err_bad_cxx_cast_qualifiers_away;
920 return TC_Failed;
921 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000922 }
John McCall2de56d12010-08-25 11:45:40 +0000923 Kind = CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000924 return TC_Success;
925 }
926 }
Fariborz Jahanian2f6c5502010-05-10 23:46:53 +0000927 else if (DestType->isObjCObjectPointerType()) {
928 // allow both c-style cast and static_cast of objective-c pointers as
929 // they are pervasive.
John McCall1d9b3b22011-09-09 05:25:32 +0000930 Kind = CK_CPointerToObjCPointerCast;
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +0000931 return TC_Success;
932 }
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +0000933 else if (CStyle && DestType->isBlockPointerType()) {
934 // allow c-style cast of void * to block pointers.
John McCall2de56d12010-08-25 11:45:40 +0000935 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +0000936 return TC_Success;
937 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000938 }
939 }
Fariborz Jahanian65267b22010-05-12 18:16:59 +0000940 // Allow arbitray objective-c pointer conversion with static casts.
941 if (SrcType->isObjCObjectPointerType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +0000942 DestType->isObjCObjectPointerType()) {
943 Kind = CK_BitCast;
Fariborz Jahanian65267b22010-05-12 18:16:59 +0000944 return TC_Success;
John McCalldaa8e4e2010-11-15 09:13:47 +0000945 }
Fariborz Jahanian65267b22010-05-12 18:16:59 +0000946
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000947 // We tried everything. Everything! Nothing works! :-(
948 return TC_NotApplicable;
949}
950
951/// Tests whether a conversion according to N2844 is valid.
952TryCastResult
953TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000954 bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
955 unsigned &msg) {
Douglas Gregordc843f22011-01-22 00:06:57 +0000956 // C++0x [expr.static.cast]p3:
957 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
958 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenek6217b802009-07-29 21:53:49 +0000959 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000960 if (!R)
961 return TC_NotApplicable;
962
Douglas Gregordc843f22011-01-22 00:06:57 +0000963 if (!SrcExpr->isGLValue())
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000964 return TC_NotApplicable;
965
966 // Because we try the reference downcast before this function, from now on
967 // this is the only cast possibility, so we issue an error if we fail now.
968 // FIXME: Should allow casting away constness if CStyle.
969 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +0000970 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +0000971 bool ObjCLifetimeConversion;
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000972 QualType FromType = SrcExpr->getType();
973 QualType ToType = R->getPointeeType();
974 if (CStyle) {
975 FromType = FromType.getUnqualifiedType();
976 ToType = ToType.getUnqualifiedType();
977 }
978
Douglas Gregor393896f2009-11-05 13:06:35 +0000979 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000980 ToType, FromType,
John McCallf85e1932011-06-15 23:02:42 +0000981 DerivedToBase, ObjCConversion,
982 ObjCLifetimeConversion)
983 < Sema::Ref_Compatible_With_Added_Qualification) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000984 msg = diag::err_bad_lvalue_to_rvalue_cast;
985 return TC_Failed;
986 }
987
Douglas Gregor88b22a42011-01-25 16:13:26 +0000988 if (DerivedToBase) {
989 Kind = CK_DerivedToBase;
990 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
991 /*DetectVirtual=*/true);
992 if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
993 return TC_NotApplicable;
994
995 Self.BuildBasePathArray(Paths, BasePath);
996 } else
997 Kind = CK_NoOp;
998
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000999 return TC_Success;
1000}
1001
1002/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1003TryCastResult
1004TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
1005 bool CStyle, const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +00001006 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001007 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001008 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1009 // cast to type "reference to cv2 D", where D is a class derived from B,
1010 // if a valid standard conversion from "pointer to D" to "pointer to B"
1011 // exists, cv2 >= cv1, and B is not a virtual base class of D.
1012 // In addition, DR54 clarifies that the base must be accessible in the
1013 // current context. Although the wording of DR54 only applies to the pointer
1014 // variant of this rule, the intent is clearly for it to apply to the this
1015 // conversion as well.
1016
Ted Kremenek6217b802009-07-29 21:53:49 +00001017 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001018 if (!DestReference) {
1019 return TC_NotApplicable;
1020 }
1021 bool RValueRef = DestReference->isRValueReferenceType();
John McCall7eb0a9e2010-11-24 05:12:34 +00001022 if (!RValueRef && !SrcExpr->isLValue()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001023 // We know the left side is an lvalue reference, so we can suggest a reason.
1024 msg = diag::err_bad_cxx_cast_rvalue;
1025 return TC_NotApplicable;
1026 }
1027
1028 QualType DestPointee = DestReference->getPointeeType();
1029
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001030 return TryStaticDowncast(Self,
1031 Self.Context.getCanonicalType(SrcExpr->getType()),
1032 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001033 OpRange, SrcExpr->getType(), DestType, msg, Kind,
1034 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001035}
1036
1037/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1038TryCastResult
1039TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +00001040 bool CStyle, const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +00001041 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001042 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001043 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1044 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1045 // is a class derived from B, if a valid standard conversion from "pointer
1046 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1047 // class of D.
1048 // In addition, DR54 clarifies that the base must be accessible in the
1049 // current context.
1050
Ted Kremenek6217b802009-07-29 21:53:49 +00001051 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001052 if (!DestPointer) {
1053 return TC_NotApplicable;
1054 }
1055
Ted Kremenek6217b802009-07-29 21:53:49 +00001056 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001057 if (!SrcPointer) {
1058 msg = diag::err_bad_static_cast_pointer_nonpointer;
1059 return TC_NotApplicable;
1060 }
1061
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001062 return TryStaticDowncast(Self,
1063 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1064 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001065 CStyle, OpRange, SrcType, DestType, msg, Kind,
1066 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001067}
1068
1069/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1070/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001071/// DestType is possible and allowed.
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001072TryCastResult
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001073TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001074 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +00001075 QualType OrigDestType, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +00001076 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl5ed66f72009-10-22 15:07:22 +00001077 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregord10099e2012-05-04 16:32:21 +00001078 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, 0) ||
1079 Self.RequireCompleteType(OpRange.getBegin(), DestType, 0))
Sebastian Redl5ed66f72009-10-22 15:07:22 +00001080 return TC_NotApplicable;
1081
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001082 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001083 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001084 return TC_NotApplicable;
1085 }
1086
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001087 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001088 /*DetectVirtual=*/true);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001089 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
1090 return TC_NotApplicable;
1091 }
1092
1093 // Target type does derive from source type. Now we're serious. If an error
1094 // appears now, it's not ignored.
1095 // This may not be entirely in line with the standard. Take for example:
1096 // struct A {};
1097 // struct B : virtual A {
1098 // B(A&);
1099 // };
Mike Stump1eb44332009-09-09 15:08:12 +00001100 //
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001101 // void f()
1102 // {
1103 // (void)static_cast<const B&>(*((A*)0));
1104 // }
1105 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1106 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1107 // However, both GCC and Comeau reject this example, and accepting it would
1108 // mean more complex code if we're to preserve the nice error message.
1109 // FIXME: Being 100% compliant here would be nice to have.
1110
1111 // Must preserve cv, as always, unless we're in C-style mode.
1112 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001113 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001114 return TC_Failed;
1115 }
1116
1117 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1118 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1119 // that it builds the paths in reverse order.
1120 // To sum up: record all paths to the base and build a nice string from
1121 // them. Use it to spice up the error message.
1122 if (!Paths.isRecordingPaths()) {
1123 Paths.clear();
1124 Paths.setRecordingPaths(true);
1125 Self.IsDerivedFrom(DestType, SrcType, Paths);
1126 }
1127 std::string PathDisplayStr;
1128 std::set<unsigned> DisplayedPaths;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001129 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001130 PI != PE; ++PI) {
1131 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
1132 // We haven't displayed a path to this particular base
1133 // class subobject yet.
1134 PathDisplayStr += "\n ";
Douglas Gregora8f32e02009-10-06 17:59:45 +00001135 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
1136 EE = PI->rend();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001137 EI != EE; ++EI)
1138 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001139 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001140 }
1141 }
1142
1143 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001144 << QualType(SrcType).getUnqualifiedType()
1145 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001146 << PathDisplayStr << OpRange;
1147 msg = 0;
1148 return TC_Failed;
1149 }
1150
1151 if (Paths.getDetectedVirtual() != 0) {
1152 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1153 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1154 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1155 msg = 0;
1156 return TC_Failed;
1157 }
1158
John McCall417d39f2011-02-14 23:21:33 +00001159 if (!CStyle) {
1160 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1161 SrcType, DestType,
1162 Paths.front(),
John McCall58e6f342010-03-16 05:22:47 +00001163 diag::err_downcast_from_inaccessible_base)) {
John McCall417d39f2011-02-14 23:21:33 +00001164 case Sema::AR_accessible:
1165 case Sema::AR_delayed: // be optimistic
1166 case Sema::AR_dependent: // be optimistic
1167 break;
1168
1169 case Sema::AR_inaccessible:
1170 msg = 0;
1171 return TC_Failed;
1172 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001173 }
1174
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001175 Self.BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00001176 Kind = CK_BaseToDerived;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001177 return TC_Success;
1178}
1179
1180/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1181/// C++ 5.2.9p9 is valid:
1182///
1183/// An rvalue of type "pointer to member of D of type cv1 T" can be
1184/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1185/// where B is a base class of D [...].
1186///
1187TryCastResult
John Wiegley429bb272011-04-08 18:41:53 +00001188TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001189 QualType DestType, bool CStyle,
1190 const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +00001191 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001192 CXXCastPath &BasePath) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001193 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001194 if (!DestMemPtr)
1195 return TC_NotApplicable;
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001196
1197 bool WasOverloadedFunction = false;
John McCall6bb80172010-03-30 21:47:33 +00001198 DeclAccessPair FoundOverload;
John Wiegley429bb272011-04-08 18:41:53 +00001199 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor1a8cf732010-04-14 23:11:21 +00001200 if (FunctionDecl *Fn
John Wiegley429bb272011-04-08 18:41:53 +00001201 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
Douglas Gregor1a8cf732010-04-14 23:11:21 +00001202 FoundOverload)) {
1203 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1204 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1205 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1206 WasOverloadedFunction = true;
1207 }
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001208 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00001209
Ted Kremenek6217b802009-07-29 21:53:49 +00001210 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001211 if (!SrcMemPtr) {
1212 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1213 return TC_NotApplicable;
1214 }
1215
1216 // T == T, modulo cv
Douglas Gregora4923eb2009-11-16 21:35:15 +00001217 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1218 DestMemPtr->getPointeeType()))
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001219 return TC_NotApplicable;
1220
1221 // B base of D
1222 QualType SrcClass(SrcMemPtr->getClass(), 0);
1223 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssoncee22422010-04-24 19:22:20 +00001224 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001225 /*DetectVirtual=*/true);
1226 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
1227 return TC_NotApplicable;
1228 }
1229
1230 // B is a base of D. But is it an allowed base? If not, it's a hard error.
Douglas Gregore0d5fe22010-05-21 20:29:55 +00001231 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001232 Paths.clear();
1233 Paths.setRecordingPaths(true);
1234 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
1235 assert(StillOkay);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001236 (void)StillOkay;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001237 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1238 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1239 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1240 msg = 0;
1241 return TC_Failed;
1242 }
1243
1244 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1245 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1246 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1247 msg = 0;
1248 return TC_Failed;
1249 }
1250
John McCall417d39f2011-02-14 23:21:33 +00001251 if (!CStyle) {
1252 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1253 DestClass, SrcClass,
1254 Paths.front(),
1255 diag::err_upcast_to_inaccessible_base)) {
1256 case Sema::AR_accessible:
1257 case Sema::AR_delayed:
1258 case Sema::AR_dependent:
1259 // Optimistically assume that the delayed and dependent cases
1260 // will work out.
1261 break;
1262
1263 case Sema::AR_inaccessible:
1264 msg = 0;
1265 return TC_Failed;
1266 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001267 }
1268
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001269 if (WasOverloadedFunction) {
1270 // Resolve the address of the overloaded function again, this time
1271 // allowing complaints if something goes wrong.
John Wiegley429bb272011-04-08 18:41:53 +00001272 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001273 DestType,
John McCall6bb80172010-03-30 21:47:33 +00001274 true,
1275 FoundOverload);
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001276 if (!Fn) {
1277 msg = 0;
1278 return TC_Failed;
1279 }
1280
John McCall6bb80172010-03-30 21:47:33 +00001281 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
John Wiegley429bb272011-04-08 18:41:53 +00001282 if (!SrcExpr.isUsable()) {
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001283 msg = 0;
1284 return TC_Failed;
1285 }
1286 }
1287
Anders Carlssoncee22422010-04-24 19:22:20 +00001288 Self.BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00001289 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001290 return TC_Success;
1291}
1292
1293/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1294/// is valid:
1295///
1296/// An expression e can be explicitly converted to a type T using a
1297/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1298TryCastResult
John Wiegley429bb272011-04-08 18:41:53 +00001299TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCallf85e1932011-06-15 23:02:42 +00001300 Sema::CheckedConversionKind CCK,
1301 const SourceRange &OpRange, unsigned &msg,
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001302 CastKind &Kind, bool ListInitialization) {
Anders Carlssond851b372009-09-07 18:25:47 +00001303 if (DestType->isRecordType()) {
1304 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
Aaron Ballman21eb6d42012-05-07 00:02:00 +00001305 diag::err_bad_dynamic_cast_incomplete) ||
Eli Friedman860a3192012-06-16 02:19:17 +00001306 Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
Aaron Ballman21eb6d42012-05-07 00:02:00 +00001307 diag::err_allocation_of_abstract_type)) {
Anders Carlssond851b372009-09-07 18:25:47 +00001308 msg = 0;
1309 return TC_Failed;
1310 }
1311 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00001312
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001313 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1314 InitializationKind InitKind
John McCallf85e1932011-06-15 23:02:42 +00001315 = (CCK == Sema::CCK_CStyleCast)
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00001316 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001317 ListInitialization)
John McCallf85e1932011-06-15 23:02:42 +00001318 : (CCK == Sema::CCK_FunctionalCast)
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001319 ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
Richard Smithc8d7f582011-11-29 22:48:16 +00001320 : InitializationKind::CreateCast(OpRange);
John Wiegley429bb272011-04-08 18:41:53 +00001321 Expr *SrcExprRaw = SrcExpr.get();
1322 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExprRaw, 1);
Douglas Gregor8e960432010-11-08 03:40:48 +00001323
1324 // At this point of CheckStaticCast, if the destination is a reference,
1325 // or the expression is an overload expression this has to work.
1326 // There is no other way that works.
1327 // On the other hand, if we're checking a C-style cast, we've still got
1328 // the reinterpret_cast way.
John McCallf85e1932011-06-15 23:02:42 +00001329 bool CStyle
1330 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
Sebastian Redl383616c2011-06-05 12:23:28 +00001331 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
Anders Carlsson3c31a392009-09-26 00:12:34 +00001332 return TC_NotApplicable;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001333
Benjamin Kramer5354e772012-08-23 23:38:35 +00001334 ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001335 if (Result.isInvalid()) {
1336 msg = 0;
1337 return TC_Failed;
1338 }
1339
Douglas Gregord6e44a32010-04-16 22:09:46 +00001340 if (InitSeq.isConstructorInitialization())
John McCall2de56d12010-08-25 11:45:40 +00001341 Kind = CK_ConstructorConversion;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001342 else
John McCall2de56d12010-08-25 11:45:40 +00001343 Kind = CK_NoOp;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001344
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001345 SrcExpr = Result;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001346 return TC_Success;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001347}
1348
1349/// TryConstCast - See if a const_cast from source to destination is allowed,
1350/// and perform it if it is.
1351static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
1352 bool CStyle, unsigned &msg) {
1353 DestType = Self.Context.getCanonicalType(DestType);
1354 QualType SrcType = SrcExpr->getType();
Douglas Gregor575d2a32011-01-22 00:19:52 +00001355 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
1356 if (DestTypeTmp->isLValueReferenceType() && !SrcExpr->isLValue()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001357 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1358 // is C-style, static_cast might find a way, so we simply suggest a
1359 // message and tell the parent to keep searching.
1360 msg = diag::err_bad_cxx_cast_rvalue;
1361 return TC_NotApplicable;
1362 }
1363
1364 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
1365 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
1366 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1367 SrcType = Self.Context.getPointerType(SrcType);
1368 }
1369
1370 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1371 // the rules for const_cast are the same as those used for pointers.
1372
John McCalld425d2b2010-05-18 09:35:29 +00001373 if (!DestType->isPointerType() &&
1374 !DestType->isMemberPointerType() &&
1375 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001376 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1377 // was a reference type, we converted it to a pointer above.
1378 // The status of rvalue references isn't entirely clear, but it looks like
1379 // conversion to them is simply invalid.
1380 // C++ 5.2.11p3: For two pointer types [...]
1381 if (!CStyle)
1382 msg = diag::err_bad_const_cast_dest;
1383 return TC_NotApplicable;
1384 }
1385 if (DestType->isFunctionPointerType() ||
1386 DestType->isMemberFunctionPointerType()) {
1387 // Cannot cast direct function pointers.
1388 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1389 // T is the ultimate pointee of source and target type.
1390 if (!CStyle)
1391 msg = diag::err_bad_const_cast_dest;
1392 return TC_NotApplicable;
1393 }
1394 SrcType = Self.Context.getCanonicalType(SrcType);
1395
1396 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1397 // completely equal.
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001398 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1399 // in multi-level pointers may change, but the level count must be the same,
1400 // as must be the final pointee type.
1401 while (SrcType != DestType &&
Douglas Gregor5a57efd2010-06-09 03:53:18 +00001402 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001403 Qualifiers SrcQuals, DestQuals;
1404 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
1405 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
1406
1407 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
1408 // the other qualifiers (e.g., address spaces) are identical.
1409 SrcQuals.removeCVRQualifiers();
1410 DestQuals.removeCVRQualifiers();
1411 if (SrcQuals != DestQuals)
1412 return TC_NotApplicable;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001413 }
1414
1415 // Since we're dealing in canonical types, the remainder must be the same.
1416 if (SrcType != DestType)
1417 return TC_NotApplicable;
1418
1419 return TC_Success;
1420}
1421
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001422// Checks for undefined behavior in reinterpret_cast.
1423// The cases that is checked for is:
1424// *reinterpret_cast<T*>(&a)
1425// reinterpret_cast<T&>(a)
1426// where accessing 'a' as type 'T' will result in undefined behavior.
1427void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1428 bool IsDereference,
1429 SourceRange Range) {
1430 unsigned DiagID = IsDereference ?
1431 diag::warn_pointer_indirection_from_incompatible_type :
1432 diag::warn_undefined_reinterpret_cast;
1433
1434 if (Diags.getDiagnosticLevel(DiagID, Range.getBegin()) ==
David Blaikied6471f72011-09-25 23:23:43 +00001435 DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001436 return;
1437 }
1438
1439 QualType SrcTy, DestTy;
1440 if (IsDereference) {
1441 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1442 return;
1443 }
1444 SrcTy = SrcType->getPointeeType();
1445 DestTy = DestType->getPointeeType();
1446 } else {
1447 if (!DestType->getAs<ReferenceType>()) {
1448 return;
1449 }
1450 SrcTy = SrcType;
1451 DestTy = DestType->getPointeeType();
1452 }
1453
1454 // Cast is compatible if the types are the same.
1455 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1456 return;
1457 }
1458 // or one of the types is a char or void type
1459 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1460 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1461 return;
1462 }
1463 // or one of the types is a tag type.
Chandler Carruth1f8f2d52011-05-24 07:43:19 +00001464 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001465 return;
1466 }
1467
Douglas Gregor575a1c92011-05-20 16:38:50 +00001468 // FIXME: Scoped enums?
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001469 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1470 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1471 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1472 return;
1473 }
1474 }
1475
1476 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1477}
Douglas Gregorfadb53b2011-03-12 01:48:56 +00001478
Fariborz Jahanian91dd9df2012-08-16 18:33:47 +00001479static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
1480 QualType DestType) {
1481 QualType SrcType = SrcExpr.get()->getType();
1482 if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
1483 if (SrcPtrTy->isObjCSelType()) {
1484 QualType DT = DestType;
1485 if (isa<PointerType>(DestType))
1486 DT = DestType->getPointeeType();
1487 if (!DT.getUnqualifiedType()->isVoidType())
1488 Self.Diag(SrcExpr.get()->getExprLoc(),
1489 diag::warn_cast_pointer_from_sel)
1490 << SrcType << DestType << SrcExpr.get()->getSourceRange();
1491 }
1492}
1493
John Wiegley429bb272011-04-08 18:41:53 +00001494static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001495 QualType DestType, bool CStyle,
1496 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +00001497 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +00001498 CastKind &Kind) {
Douglas Gregore39a3892010-07-13 23:17:26 +00001499 bool IsLValueCast = false;
1500
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001501 DestType = Self.Context.getCanonicalType(DestType);
John Wiegley429bb272011-04-08 18:41:53 +00001502 QualType SrcType = SrcExpr.get()->getType();
Douglas Gregor8e960432010-11-08 03:40:48 +00001503
1504 // Is the source an overloaded name? (i.e. &foo)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001505 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ...
1506 if (SrcType == Self.Context.OverloadTy) {
John McCall6dbba4f2011-10-11 23:14:30 +00001507 // ... unless foo<int> resolves to an lvalue unambiguously.
1508 // TODO: what if this fails because of DiagnoseUseOfDecl or something
1509 // like it?
1510 ExprResult SingleFunctionExpr = SrcExpr;
1511 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1512 SingleFunctionExpr,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001513 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
John McCall6dbba4f2011-10-11 23:14:30 +00001514 ) && SingleFunctionExpr.isUsable()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001515 SrcExpr = SingleFunctionExpr;
John Wiegley429bb272011-04-08 18:41:53 +00001516 SrcType = SrcExpr.get()->getType();
John McCall6dbba4f2011-10-11 23:14:30 +00001517 } else {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001518 return TC_NotApplicable;
John McCall6dbba4f2011-10-11 23:14:30 +00001519 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001520 }
Douglas Gregor8e960432010-11-08 03:40:48 +00001521
Ted Kremenek6217b802009-07-29 21:53:49 +00001522 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Richard Smith6850faf2012-04-29 08:24:44 +00001523 if (!SrcExpr.get()->isGLValue()) {
1524 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
1525 // similar comment in const_cast.
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001526 msg = diag::err_bad_cxx_cast_rvalue;
1527 return TC_NotApplicable;
1528 }
1529
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001530 if (!CStyle) {
1531 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
1532 /*isDereference=*/false, OpRange);
1533 }
1534
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001535 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1536 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1537 // built-in & and * operators.
Argyrios Kyrtzidisb464a5b2011-04-22 22:31:13 +00001538
Argyrios Kyrtzidisbb29d1b2011-04-22 23:57:57 +00001539 const char *inappropriate = 0;
1540 switch (SrcExpr.get()->getObjectKind()) {
Argyrios Kyrtzidise5e3d312011-04-23 01:10:24 +00001541 case OK_Ordinary:
1542 break;
Argyrios Kyrtzidisbb29d1b2011-04-22 23:57:57 +00001543 case OK_BitField: inappropriate = "bit-field"; break;
1544 case OK_VectorComponent: inappropriate = "vector element"; break;
1545 case OK_ObjCProperty: inappropriate = "property expression"; break;
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001546 case OK_ObjCSubscript: inappropriate = "container subscripting expression";
1547 break;
Argyrios Kyrtzidisbb29d1b2011-04-22 23:57:57 +00001548 }
1549 if (inappropriate) {
1550 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
1551 << inappropriate << DestType
1552 << OpRange << SrcExpr.get()->getSourceRange();
1553 msg = 0; SrcExpr = ExprError();
Argyrios Kyrtzidisb464a5b2011-04-22 22:31:13 +00001554 return TC_NotApplicable;
1555 }
1556
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001557 // This code does this transformation for the checked types.
1558 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1559 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregor8e960432010-11-08 03:40:48 +00001560
Douglas Gregore39a3892010-07-13 23:17:26 +00001561 IsLValueCast = true;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001562 }
1563
1564 // Canonicalize source for comparison.
1565 SrcType = Self.Context.getCanonicalType(SrcType);
1566
Ted Kremenek6217b802009-07-29 21:53:49 +00001567 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1568 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001569 if (DestMemPtr && SrcMemPtr) {
1570 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1571 // can be explicitly converted to an rvalue of type "pointer to member
1572 // of Y of type T2" if T1 and T2 are both function types or both object
1573 // types.
1574 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1575 SrcMemPtr->getPointeeType()->isFunctionType())
1576 return TC_NotApplicable;
1577
1578 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1579 // constness.
1580 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1581 // we accept it.
John McCallf85e1932011-06-15 23:02:42 +00001582 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1583 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001584 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001585 return TC_Failed;
1586 }
1587
Charles Davisf231df32010-08-16 05:30:44 +00001588 // Don't allow casting between member pointers of different sizes.
1589 if (Self.Context.getTypeSize(DestMemPtr) !=
1590 Self.Context.getTypeSize(SrcMemPtr)) {
1591 msg = diag::err_bad_cxx_cast_member_pointer_size;
1592 return TC_Failed;
1593 }
1594
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001595 // A valid member pointer cast.
John McCall4d4e5c12012-02-15 01:22:51 +00001596 assert(!IsLValueCast);
1597 Kind = CK_ReinterpretMemberPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001598 return TC_Success;
1599 }
1600
1601 // See below for the enumeral issue.
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001602 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001603 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1604 // type large enough to hold it. A value of std::nullptr_t can be
1605 // converted to an integral type; the conversion has the same meaning
1606 // and validity as a conversion of (void*)0 to the integral type.
1607 if (Self.Context.getTypeSize(SrcType) >
1608 Self.Context.getTypeSize(DestType)) {
1609 msg = diag::err_bad_reinterpret_cast_small_int;
1610 return TC_Failed;
1611 }
John McCall2de56d12010-08-25 11:45:40 +00001612 Kind = CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001613 return TC_Success;
1614 }
1615
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001616 bool destIsVector = DestType->isVectorType();
1617 bool srcIsVector = SrcType->isVectorType();
1618 if (srcIsVector || destIsVector) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001619 // FIXME: Should this also apply to floating point types?
1620 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1621 bool destIsScalar = DestType->isIntegralType(Self.Context);
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001622
1623 // Check if this is a cast between a vector and something else.
1624 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1625 !(srcIsVector && destIsVector))
1626 return TC_NotApplicable;
1627
1628 // If both types have the same size, we can successfully cast.
Douglas Gregorf2a55392009-12-22 22:47:22 +00001629 if (Self.Context.getTypeSize(SrcType)
1630 == Self.Context.getTypeSize(DestType)) {
John McCall2de56d12010-08-25 11:45:40 +00001631 Kind = CK_BitCast;
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001632 return TC_Success;
Douglas Gregorf2a55392009-12-22 22:47:22 +00001633 }
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001634
1635 if (destIsScalar)
1636 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1637 else if (srcIsScalar)
1638 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1639 else
1640 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1641
1642 return TC_Failed;
1643 }
Chad Rosier41f44312012-02-03 02:54:37 +00001644
1645 if (SrcType == DestType) {
1646 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1647 // restrictions, a cast to the same type is allowed so long as it does not
1648 // cast away constness. In C++98, the intent was not entirely clear here,
1649 // since all other paragraphs explicitly forbid casts to the same type.
1650 // C++11 clarifies this case with p2.
1651 //
1652 // The only allowed types are: integral, enumeration, pointer, or
1653 // pointer-to-member types. We also won't restrict Obj-C pointers either.
1654 Kind = CK_NoOp;
1655 TryCastResult Result = TC_NotApplicable;
1656 if (SrcType->isIntegralOrEnumerationType() ||
1657 SrcType->isAnyPointerType() ||
1658 SrcType->isMemberPointerType() ||
1659 SrcType->isBlockPointerType()) {
1660 Result = TC_Success;
1661 }
1662 return Result;
1663 }
1664
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001665 bool destIsPtr = DestType->isAnyPointerType() ||
1666 DestType->isBlockPointerType();
1667 bool srcIsPtr = SrcType->isAnyPointerType() ||
1668 SrcType->isBlockPointerType();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001669 if (!destIsPtr && !srcIsPtr) {
1670 // Except for std::nullptr_t->integer and lvalue->reference, which are
1671 // handled above, at least one of the two arguments must be a pointer.
1672 return TC_NotApplicable;
1673 }
1674
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001675 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001676 assert(srcIsPtr && "One type must be a pointer");
1677 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
Francois Pichet30aff5b2011-05-11 22:13:54 +00001678 // type large enough to hold it; except in Microsoft mode, where the
1679 // integral type size doesn't matter.
1680 if ((Self.Context.getTypeSize(SrcType) >
1681 Self.Context.getTypeSize(DestType)) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00001682 !Self.getLangOpts().MicrosoftExt) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001683 msg = diag::err_bad_reinterpret_cast_small_int;
1684 return TC_Failed;
1685 }
John McCall2de56d12010-08-25 11:45:40 +00001686 Kind = CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001687 return TC_Success;
1688 }
1689
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001690 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001691 assert(destIsPtr && "One type must be a pointer");
1692 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1693 // converted to a pointer.
John McCall404cd162010-11-13 01:35:44 +00001694 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1695 // necessarily converted to a null pointer value.]
John McCall2de56d12010-08-25 11:45:40 +00001696 Kind = CK_IntegralToPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001697 return TC_Success;
1698 }
1699
1700 if (!destIsPtr || !srcIsPtr) {
1701 // With the valid non-pointer conversions out of the way, we can be even
1702 // more stringent.
1703 return TC_NotApplicable;
1704 }
1705
1706 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1707 // The C-style cast operator can.
John McCallf85e1932011-06-15 23:02:42 +00001708 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1709 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001710 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001711 return TC_Failed;
1712 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001713
1714 // Cannot convert between block pointers and Objective-C object pointers.
1715 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1716 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1717 return TC_NotApplicable;
1718
John McCall1d9b3b22011-09-09 05:25:32 +00001719 if (IsLValueCast) {
1720 Kind = CK_LValueBitCast;
1721 } else if (DestType->isObjCObjectPointerType()) {
John McCalldc05b112011-09-10 01:16:55 +00001722 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
John McCall1d9b3b22011-09-09 05:25:32 +00001723 } else if (DestType->isBlockPointerType()) {
1724 if (!SrcType->isBlockPointerType()) {
1725 Kind = CK_AnyPointerToBlockPointerCast;
1726 } else {
1727 Kind = CK_BitCast;
1728 }
1729 } else {
1730 Kind = CK_BitCast;
1731 }
1732
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001733 // Any pointer can be cast to an Objective-C pointer type with a C-style
1734 // cast.
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001735 if (CStyle && DestType->isObjCObjectPointerType()) {
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001736 return TC_Success;
1737 }
Fariborz Jahanian91dd9df2012-08-16 18:33:47 +00001738 if (CStyle)
1739 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
1740
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001741 // Not casting away constness, so the only remaining check is for compatible
1742 // pointer categories.
1743
1744 if (SrcType->isFunctionPointerType()) {
1745 if (DestType->isFunctionPointerType()) {
1746 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1747 // a pointer to a function of a different type.
1748 return TC_Success;
1749 }
1750
1751 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1752 // an object type or vice versa is conditionally-supported.
1753 // Compilers support it in C++03 too, though, because it's necessary for
1754 // casting the return value of dlsym() and GetProcAddress().
1755 // FIXME: Conditionally-supported behavior should be configurable in the
1756 // TargetInfo or similar.
Richard Smithebaf0e62011-10-18 20:49:44 +00001757 Self.Diag(OpRange.getBegin(),
David Blaikie4e4d0842012-03-11 07:00:24 +00001758 Self.getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00001759 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
1760 << OpRange;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001761 return TC_Success;
1762 }
1763
1764 if (DestType->isFunctionPointerType()) {
1765 // See above.
Richard Smithebaf0e62011-10-18 20:49:44 +00001766 Self.Diag(OpRange.getBegin(),
David Blaikie4e4d0842012-03-11 07:00:24 +00001767 Self.getLangOpts().CPlusPlus0x ?
Richard Smithebaf0e62011-10-18 20:49:44 +00001768 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
1769 << OpRange;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001770 return TC_Success;
1771 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001772
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001773 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1774 // a pointer to an object of different type.
1775 // Void pointers are not specified, but supported by every compiler out there.
1776 // So we finish by allowing everything that remains - it's got to be two
1777 // object pointers.
1778 return TC_Success;
John McCall79ab2c82011-02-14 18:34:10 +00001779}
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001780
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001781void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
1782 bool ListInitialization) {
John McCalla180f042011-10-06 23:25:11 +00001783 // Handle placeholders.
1784 if (isPlaceholder()) {
1785 // C-style casts can resolve __unknown_any types.
1786 if (claimPlaceholder(BuiltinType::UnknownAny)) {
1787 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
1788 SrcExpr.get(), Kind,
1789 ValueKind, BasePath);
1790 return;
1791 }
John McCallb45ae252011-10-05 07:41:44 +00001792
John McCalla180f042011-10-06 23:25:11 +00001793 checkNonOverloadPlaceholders();
1794 if (SrcExpr.isInvalid())
1795 return;
John McCall4919dfd2011-10-17 17:42:19 +00001796 }
John McCalla180f042011-10-06 23:25:11 +00001797
1798 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001799 // This test is outside everything else because it's the only case where
1800 // a non-lvalue-reference target type does not lead to decay.
John McCallb45ae252011-10-05 07:41:44 +00001801 if (DestType->isVoidType()) {
John McCallfb8721c2011-04-10 19:13:55 +00001802 Kind = CK_ToVoid;
1803
John McCalla180f042011-10-06 23:25:11 +00001804 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall6dbba4f2011-10-11 23:14:30 +00001805 Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1806 SrcExpr, /* Decay Function to ptr */ false,
John McCallb45ae252011-10-05 07:41:44 +00001807 /* Complain */ true, DestRange, DestType,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00001808 diag::err_bad_cstyle_cast_overload);
John McCallb45ae252011-10-05 07:41:44 +00001809 if (SrcExpr.isInvalid())
1810 return;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001811 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001812
John McCalla180f042011-10-06 23:25:11 +00001813 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
1814 if (SrcExpr.isInvalid())
John McCallb45ae252011-10-05 07:41:44 +00001815 return;
John McCallb45ae252011-10-05 07:41:44 +00001816
1817 return;
Anton Yartsevd06fea82011-03-27 09:32:40 +00001818 }
1819
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001820 // If the type is dependent, we won't do any other semantic analysis now.
John McCallb45ae252011-10-05 07:41:44 +00001821 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent()) {
1822 assert(Kind == CK_Dependent);
1823 return;
John McCalldaa8e4e2010-11-15 09:13:47 +00001824 }
Benjamin Kramer5b4a40a2011-07-08 20:20:17 +00001825
John McCall6dbba4f2011-10-11 23:14:30 +00001826 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
1827 !isPlaceholder(BuiltinType::Overload)) {
John McCallb45ae252011-10-05 07:41:44 +00001828 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
1829 if (SrcExpr.isInvalid())
1830 return;
John Wiegley429bb272011-04-08 18:41:53 +00001831 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001832
John McCallfb8721c2011-04-10 19:13:55 +00001833 // AltiVec vector initialization with a single literal.
John McCallb45ae252011-10-05 07:41:44 +00001834 if (const VectorType *vecTy = DestType->getAs<VectorType>())
John McCallfb8721c2011-04-10 19:13:55 +00001835 if (vecTy->getVectorKind() == VectorType::AltiVecVector
John McCallb45ae252011-10-05 07:41:44 +00001836 && (SrcExpr.get()->getType()->isIntegerType()
1837 || SrcExpr.get()->getType()->isFloatingType())) {
John McCallfb8721c2011-04-10 19:13:55 +00001838 Kind = CK_VectorSplat;
John McCallb45ae252011-10-05 07:41:44 +00001839 return;
John McCallfb8721c2011-04-10 19:13:55 +00001840 }
1841
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001842 // C++ [expr.cast]p5: The conversions performed by
1843 // - a const_cast,
1844 // - a static_cast,
1845 // - a static_cast followed by a const_cast,
1846 // - a reinterpret_cast, or
1847 // - a reinterpret_cast followed by a const_cast,
1848 // can be performed using the cast notation of explicit type conversion.
1849 // [...] If a conversion can be interpreted in more than one of the ways
1850 // listed above, the interpretation that appears first in the list is used,
1851 // even if a cast resulting from that interpretation is ill-formed.
1852 // In plain language, this means trying a const_cast ...
1853 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCallb45ae252011-10-05 07:41:44 +00001854 TryCastResult tcr = TryConstCast(Self, SrcExpr.get(), DestType,
1855 /*CStyle*/true, msg);
Anders Carlssonda921fd2009-10-19 18:14:28 +00001856 if (tcr == TC_Success)
John McCall2de56d12010-08-25 11:45:40 +00001857 Kind = CK_NoOp;
Anders Carlssonda921fd2009-10-19 18:14:28 +00001858
John McCallf85e1932011-06-15 23:02:42 +00001859 Sema::CheckedConversionKind CCK
1860 = FunctionalStyle? Sema::CCK_FunctionalCast
1861 : Sema::CCK_CStyleCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001862 if (tcr == TC_NotApplicable) {
1863 // ... or if that is not possible, a static_cast, ignoring const, ...
John McCallb45ae252011-10-05 07:41:44 +00001864 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001865 msg, Kind, BasePath, ListInitialization);
John McCallb45ae252011-10-05 07:41:44 +00001866 if (SrcExpr.isInvalid())
1867 return;
1868
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001869 if (tcr == TC_NotApplicable) {
1870 // ... and finally a reinterpret_cast, ignoring const.
John McCallb45ae252011-10-05 07:41:44 +00001871 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
1872 OpRange, msg, Kind);
1873 if (SrcExpr.isInvalid())
1874 return;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001875 }
1876 }
1877
David Blaikie4e4d0842012-03-11 07:00:24 +00001878 if (Self.getLangOpts().ObjCAutoRefCount && tcr == TC_Success)
John McCallb45ae252011-10-05 07:41:44 +00001879 checkObjCARCConversion(CCK);
John McCallf85e1932011-06-15 23:02:42 +00001880
Nick Lewycky43328e92010-11-09 00:19:31 +00001881 if (tcr != TC_Success && msg != 0) {
John McCallb45ae252011-10-05 07:41:44 +00001882 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor8e960432010-11-08 03:40:48 +00001883 DeclAccessPair Found;
John McCallb45ae252011-10-05 07:41:44 +00001884 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
1885 DestType,
1886 /*Complain*/ true,
Douglas Gregor8e960432010-11-08 03:40:48 +00001887 Found);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001888
Richard Trieu32ac00d2011-04-16 01:09:30 +00001889 assert(!Fn && "cast failed but able to resolve overload expression!!");
Nick Lewycky43328e92010-11-09 00:19:31 +00001890 (void)Fn;
John McCall79ab2c82011-02-14 18:34:10 +00001891
Nick Lewycky43328e92010-11-09 00:19:31 +00001892 } else {
John McCallb45ae252011-10-05 07:41:44 +00001893 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
Sebastian Redl20ff0e22012-02-13 19:55:43 +00001894 OpRange, SrcExpr.get(), DestType, ListInitialization);
Douglas Gregor8e960432010-11-08 03:40:48 +00001895 }
John McCallb45ae252011-10-05 07:41:44 +00001896 } else if (Kind == CK_BitCast) {
1897 checkCastAlign();
Douglas Gregor8e960432010-11-08 03:40:48 +00001898 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001899
John McCallb45ae252011-10-05 07:41:44 +00001900 // Clear out SrcExpr if there was a fatal error.
John Wiegley429bb272011-04-08 18:41:53 +00001901 if (tcr != TC_Success)
John McCallb45ae252011-10-05 07:41:44 +00001902 SrcExpr = ExprError();
1903}
1904
Fariborz Jahanianbbb8afd2012-08-17 17:22:34 +00001905/// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
1906/// non-matching type. Such as enum function call to int, int call to
1907/// pointer; etc. Cast to 'void' is an exception.
1908static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
1909 QualType DestType) {
1910 if (Self.Diags.getDiagnosticLevel(diag::warn_bad_function_cast,
1911 SrcExpr.get()->getExprLoc())
1912 == DiagnosticsEngine::Ignored)
1913 return;
1914
1915 if (!isa<CallExpr>(SrcExpr.get()))
1916 return;
1917
1918 QualType SrcType = SrcExpr.get()->getType();
1919 if (DestType.getUnqualifiedType()->isVoidType())
1920 return;
1921 if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
1922 && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
1923 return;
1924 if (SrcType->isIntegerType() && DestType->isIntegerType() &&
1925 (SrcType->isBooleanType() == DestType->isBooleanType()) &&
1926 (SrcType->isEnumeralType() == DestType->isEnumeralType()))
1927 return;
1928 if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
1929 return;
1930 if (SrcType->isEnumeralType() && DestType->isEnumeralType())
1931 return;
1932 if (SrcType->isComplexType() && DestType->isComplexType())
1933 return;
1934 if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
1935 return;
1936
1937 Self.Diag(SrcExpr.get()->getExprLoc(),
1938 diag::warn_bad_function_cast)
1939 << SrcType << DestType << SrcExpr.get()->getSourceRange();
1940}
1941
John McCalla180f042011-10-06 23:25:11 +00001942/// Check the semantics of a C-style cast operation, in C.
1943void CastOperation::CheckCStyleCast() {
David Blaikie4e4d0842012-03-11 07:00:24 +00001944 assert(!Self.getLangOpts().CPlusPlus);
John McCalla180f042011-10-06 23:25:11 +00001945
John McCall5acb0c92011-10-17 18:40:02 +00001946 // C-style casts can resolve __unknown_any types.
1947 if (claimPlaceholder(BuiltinType::UnknownAny)) {
1948 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
1949 SrcExpr.get(), Kind,
1950 ValueKind, BasePath);
1951 return;
1952 }
John McCalla180f042011-10-06 23:25:11 +00001953
1954 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1955 // type needs to be scalar.
1956 if (DestType->isVoidType()) {
1957 // We don't necessarily do lvalue-to-rvalue conversions on this.
1958 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
1959 if (SrcExpr.isInvalid())
1960 return;
1961
1962 // Cast to void allows any expr type.
1963 Kind = CK_ToVoid;
1964 return;
1965 }
1966
1967 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
1968 if (SrcExpr.isInvalid())
1969 return;
1970 QualType SrcType = SrcExpr.get()->getType();
David Chisnall7a7ee302012-01-16 17:27:18 +00001971
John McCall5acb0c92011-10-17 18:40:02 +00001972 assert(!SrcType->isPlaceholderType());
John McCalla180f042011-10-06 23:25:11 +00001973
1974 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1975 diag::err_typecheck_cast_to_incomplete)) {
1976 SrcExpr = ExprError();
1977 return;
1978 }
1979
1980 if (!DestType->isScalarType() && !DestType->isVectorType()) {
1981 const RecordType *DestRecordTy = DestType->getAs<RecordType>();
1982
1983 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
1984 // GCC struct/union extension: allow cast to self.
1985 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
1986 << DestType << SrcExpr.get()->getSourceRange();
1987 Kind = CK_NoOp;
1988 return;
1989 }
1990
1991 // GCC's cast to union extension.
1992 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
1993 RecordDecl *RD = DestRecordTy->getDecl();
1994 RecordDecl::field_iterator Field, FieldEnd;
1995 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1996 Field != FieldEnd; ++Field) {
1997 if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) &&
1998 !Field->isUnnamedBitfield()) {
1999 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
2000 << SrcExpr.get()->getSourceRange();
2001 break;
2002 }
2003 }
2004 if (Field == FieldEnd) {
2005 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2006 << SrcType << SrcExpr.get()->getSourceRange();
2007 SrcExpr = ExprError();
2008 return;
2009 }
2010 Kind = CK_ToUnion;
2011 return;
2012 }
2013
2014 // Reject any other conversions to non-scalar types.
2015 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
2016 << DestType << SrcExpr.get()->getSourceRange();
2017 SrcExpr = ExprError();
2018 return;
2019 }
2020
2021 // The type we're casting to is known to be a scalar or vector.
2022
2023 // Require the operand to be a scalar or vector.
2024 if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
2025 Self.Diag(SrcExpr.get()->getExprLoc(),
2026 diag::err_typecheck_expect_scalar_operand)
2027 << SrcType << SrcExpr.get()->getSourceRange();
2028 SrcExpr = ExprError();
2029 return;
2030 }
2031
2032 if (DestType->isExtVectorType()) {
2033 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.take(), Kind);
2034 return;
2035 }
2036
2037 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
2038 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
2039 (SrcType->isIntegerType() || SrcType->isFloatingType())) {
2040 Kind = CK_VectorSplat;
2041 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
2042 SrcExpr = ExprError();
2043 }
2044 return;
2045 }
2046
2047 if (SrcType->isVectorType()) {
2048 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
2049 SrcExpr = ExprError();
2050 return;
2051 }
2052
2053 // The source and target types are both scalars, i.e.
2054 // - arithmetic types (fundamental, enum, and complex)
2055 // - all kinds of pointers
2056 // Note that member pointers were filtered out with C++, above.
2057
2058 if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
2059 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
2060 SrcExpr = ExprError();
2061 return;
2062 }
2063
2064 // If either type is a pointer, the other type has to be either an
2065 // integer or a pointer.
2066 if (!DestType->isArithmeticType()) {
2067 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
2068 Self.Diag(SrcExpr.get()->getExprLoc(),
2069 diag::err_cast_pointer_from_non_pointer_int)
2070 << SrcType << SrcExpr.get()->getSourceRange();
2071 SrcExpr = ExprError();
2072 return;
2073 }
2074 } else if (!SrcType->isArithmeticType()) {
2075 if (!DestType->isIntegralType(Self.Context) &&
2076 DestType->isArithmeticType()) {
2077 Self.Diag(SrcExpr.get()->getLocStart(),
2078 diag::err_cast_pointer_to_non_pointer_int)
Abramo Bagnaraf7ce1942011-11-15 11:25:38 +00002079 << DestType << SrcExpr.get()->getSourceRange();
John McCalla180f042011-10-06 23:25:11 +00002080 SrcExpr = ExprError();
2081 return;
2082 }
2083 }
2084
2085 // ARC imposes extra restrictions on casts.
David Blaikie4e4d0842012-03-11 07:00:24 +00002086 if (Self.getLangOpts().ObjCAutoRefCount) {
John McCalla180f042011-10-06 23:25:11 +00002087 checkObjCARCConversion(Sema::CCK_CStyleCast);
2088 if (SrcExpr.isInvalid())
2089 return;
2090
2091 if (const PointerType *CastPtr = DestType->getAs<PointerType>()) {
2092 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
2093 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
2094 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
2095 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
2096 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
2097 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
2098 Self.Diag(SrcExpr.get()->getLocStart(),
2099 diag::err_typecheck_incompatible_ownership)
2100 << SrcType << DestType << Sema::AA_Casting
2101 << SrcExpr.get()->getSourceRange();
2102 return;
2103 }
2104 }
2105 }
2106 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
2107 Self.Diag(SrcExpr.get()->getLocStart(),
2108 diag::err_arc_convesion_of_weak_unavailable)
2109 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2110 SrcExpr = ExprError();
2111 return;
2112 }
2113 }
Fariborz Jahanian91dd9df2012-08-16 18:33:47 +00002114 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
Fariborz Jahanianbbb8afd2012-08-17 17:22:34 +00002115 DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
John McCalla180f042011-10-06 23:25:11 +00002116 Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2117 if (SrcExpr.isInvalid())
2118 return;
2119
2120 if (Kind == CK_BitCast)
2121 checkCastAlign();
2122}
2123
2124ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
2125 TypeSourceInfo *CastTypeInfo,
2126 SourceLocation RPLoc,
2127 Expr *CastExpr) {
John McCallb45ae252011-10-05 07:41:44 +00002128 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2129 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2130 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
2131
David Blaikie4e4d0842012-03-11 07:00:24 +00002132 if (getLangOpts().CPlusPlus) {
Sebastian Redl6dc00f62012-02-12 18:41:05 +00002133 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false,
2134 isa<InitListExpr>(CastExpr));
John McCalla180f042011-10-06 23:25:11 +00002135 } else {
2136 Op.CheckCStyleCast();
2137 }
2138
John McCallb45ae252011-10-05 07:41:44 +00002139 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00002140 return ExprError();
2141
John McCall5acb0c92011-10-17 18:40:02 +00002142 return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
2143 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
2144 &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
John McCallb45ae252011-10-05 07:41:44 +00002145}
2146
2147ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
2148 SourceLocation LPLoc,
2149 Expr *CastExpr,
2150 SourceLocation RPLoc) {
Sebastian Redl20ff0e22012-02-13 19:55:43 +00002151 assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
John McCallb45ae252011-10-05 07:41:44 +00002152 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2153 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2154 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
2155
Sebastian Redl20ff0e22012-02-13 19:55:43 +00002156 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/true, /*ListInit=*/false);
John McCallb45ae252011-10-05 07:41:44 +00002157 if (Op.SrcExpr.isInvalid())
2158 return ExprError();
Daniel Jaspera770a4d2012-07-16 08:05:07 +00002159
2160 if (CXXConstructExpr *ConstructExpr = dyn_cast<CXXConstructExpr>(Op.SrcExpr.get()))
2161 ConstructExpr->setParenRange(SourceRange(LPLoc, RPLoc));
John McCallb45ae252011-10-05 07:41:44 +00002162
John McCall5acb0c92011-10-17 18:40:02 +00002163 return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
2164 Op.ValueKind, CastTypeInfo, Op.DestRange.getBegin(),
2165 Op.Kind, Op.SrcExpr.take(), &Op.BasePath, RPLoc));
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002166}