blob: 3f46cd457ad4a6777ba3dfb64bb71bef544a201b [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"
Sebastian Redl26d85b12008-11-05 21:50:06 +000018#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000022#include "clang/Basic/PartialDiagnostic.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000023#include "clang/Sema/Initialization.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,
Fariborz Jahanianf799ae12013-02-22 22:02:53 +0000261 OpLoc, Parens.getEnd(),
262 AngleBrackets));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000263
Anders Carlsson714179b2009-08-02 19:07:59 +0000264 case tok::kw_dynamic_cast: {
John Wiegley429bb272011-04-08 18:41:53 +0000265 if (!TypeDependent) {
John McCallb45ae252011-10-05 07:41:44 +0000266 Op.CheckDynamicCast();
267 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000268 return ExprError();
269 }
John McCall5acb0c92011-10-17 18:40:02 +0000270 return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
271 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
272 &Op.BasePath, DestTInfo,
Fariborz Jahanianf799ae12013-02-22 22:02:53 +0000273 OpLoc, Parens.getEnd(),
274 AngleBrackets));
Anders Carlsson714179b2009-08-02 19:07:59 +0000275 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000276 case tok::kw_reinterpret_cast: {
John Wiegley429bb272011-04-08 18:41:53 +0000277 if (!TypeDependent) {
John McCallb45ae252011-10-05 07:41:44 +0000278 Op.CheckReinterpretCast();
279 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000280 return ExprError();
281 }
John McCall5acb0c92011-10-17 18:40:02 +0000282 return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
283 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
284 0, DestTInfo, OpLoc,
Fariborz Jahanianf799ae12013-02-22 22:02:53 +0000285 Parens.getEnd(),
286 AngleBrackets));
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000287 }
Anders Carlssoncdb61972009-08-07 22:21:05 +0000288 case tok::kw_static_cast: {
John Wiegley429bb272011-04-08 18:41:53 +0000289 if (!TypeDependent) {
Richard Smithc8d7f582011-11-29 22:48:16 +0000290 Op.CheckStaticCast();
John McCallb45ae252011-10-05 07:41:44 +0000291 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000292 return ExprError();
293 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000294
John McCall5acb0c92011-10-17 18:40:02 +0000295 return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
296 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
297 &Op.BasePath, DestTInfo,
Fariborz Jahanianf799ae12013-02-22 22:02:53 +0000298 OpLoc, Parens.getEnd(),
299 AngleBrackets));
Anders Carlssoncdb61972009-08-07 22:21:05 +0000300 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000301 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000302}
303
John McCall79ab2c82011-02-14 18:34:10 +0000304/// Try to diagnose a failed overloaded cast. Returns true if
305/// diagnostics were emitted.
306static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
307 SourceRange range, Expr *src,
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000308 QualType destType,
309 bool listInitialization) {
John McCall79ab2c82011-02-14 18:34:10 +0000310 switch (CT) {
311 // These cast kinds don't consider user-defined conversions.
312 case CT_Const:
313 case CT_Reinterpret:
314 case CT_Dynamic:
315 return false;
316
317 // These do.
318 case CT_Static:
319 case CT_CStyle:
320 case CT_Functional:
321 break;
322 }
323
324 QualType srcType = src->getType();
325 if (!destType->isRecordType() && !srcType->isRecordType())
326 return false;
327
328 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
329 InitializationKind initKind
John McCallf85e1932011-06-15 23:02:42 +0000330 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000331 range, listInitialization)
Sebastian Redl3a45c0e2012-02-12 16:37:36 +0000332 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000333 listInitialization)
Richard Smithc8d7f582011-11-29 22:48:16 +0000334 : InitializationKind::CreateCast(/*type range?*/ range);
John McCall79ab2c82011-02-14 18:34:10 +0000335 InitializationSequence sequence(S, entity, initKind, &src, 1);
336
Sebastian Redl383616c2011-06-05 12:23:28 +0000337 assert(sequence.Failed() && "initialization succeeded on second try?");
John McCall79ab2c82011-02-14 18:34:10 +0000338 switch (sequence.getFailureKind()) {
339 default: return false;
340
341 case InitializationSequence::FK_ConstructorOverloadFailed:
342 case InitializationSequence::FK_UserConversionOverloadFailed:
343 break;
344 }
345
346 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
347
348 unsigned msg = 0;
349 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
350
351 switch (sequence.getFailedOverloadResult()) {
352 case OR_Success: llvm_unreachable("successful failed overload");
John McCall79ab2c82011-02-14 18:34:10 +0000353 case OR_No_Viable_Function:
354 if (candidates.empty())
355 msg = diag::err_ovl_no_conversion_in_cast;
356 else
357 msg = diag::err_ovl_no_viable_conversion_in_cast;
358 howManyCandidates = OCD_AllCandidates;
359 break;
360
361 case OR_Ambiguous:
362 msg = diag::err_ovl_ambiguous_conversion_in_cast;
363 howManyCandidates = OCD_ViableCandidates;
364 break;
365
366 case OR_Deleted:
367 msg = diag::err_ovl_deleted_conversion_in_cast;
368 howManyCandidates = OCD_ViableCandidates;
369 break;
370 }
371
372 S.Diag(range.getBegin(), msg)
373 << CT << srcType << destType
374 << range << src->getSourceRange();
375
Ahmed Charles13a140c2012-02-25 11:00:22 +0000376 candidates.NoteCandidates(S, howManyCandidates, src);
John McCall79ab2c82011-02-14 18:34:10 +0000377
378 return true;
379}
380
381/// Diagnose a failed cast.
382static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000383 SourceRange opRange, Expr *src, QualType destType,
384 bool listInitialization) {
John McCall864c0412011-04-26 20:42:42 +0000385 if (src->getType() == S.Context.BoundMemberTy) {
386 (void) S.CheckPlaceholderExpr(src); // will always fail
387 return;
388 }
389
John McCall79ab2c82011-02-14 18:34:10 +0000390 if (msg == diag::err_bad_cxx_cast_generic &&
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000391 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
392 listInitialization))
John McCall79ab2c82011-02-14 18:34:10 +0000393 return;
394
395 S.Diag(opRange.getBegin(), msg) << castType
396 << src->getType() << destType << opRange << src->getSourceRange();
397}
398
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000399/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
400/// this removes one level of indirection from both types, provided that they're
401/// the same kind of pointer (plain or to-member). Unlike the Sema function,
402/// this one doesn't care if the two pointers-to-member don't point into the
403/// same class. This is because CastsAwayConstness doesn't care.
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000404static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000405 const PointerType *T1PtrType = T1->getAs<PointerType>(),
406 *T2PtrType = T2->getAs<PointerType>();
407 if (T1PtrType && T2PtrType) {
408 T1 = T1PtrType->getPointeeType();
409 T2 = T2PtrType->getPointeeType();
410 return true;
411 }
Fariborz Jahanian72a86592010-02-03 20:32:31 +0000412 const ObjCObjectPointerType *T1ObjCPtrType =
413 T1->getAs<ObjCObjectPointerType>(),
414 *T2ObjCPtrType =
415 T2->getAs<ObjCObjectPointerType>();
416 if (T1ObjCPtrType) {
417 if (T2ObjCPtrType) {
418 T1 = T1ObjCPtrType->getPointeeType();
419 T2 = T2ObjCPtrType->getPointeeType();
420 return true;
421 }
422 else if (T2PtrType) {
423 T1 = T1ObjCPtrType->getPointeeType();
424 T2 = T2PtrType->getPointeeType();
425 return true;
426 }
427 }
428 else if (T2ObjCPtrType) {
429 if (T1PtrType) {
430 T2 = T2ObjCPtrType->getPointeeType();
431 T1 = T1PtrType->getPointeeType();
432 return true;
433 }
434 }
435
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000436 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
437 *T2MPType = T2->getAs<MemberPointerType>();
438 if (T1MPType && T2MPType) {
439 T1 = T1MPType->getPointeeType();
440 T2 = T2MPType->getPointeeType();
441 return true;
442 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000443
444 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
445 *T2BPType = T2->getAs<BlockPointerType>();
446 if (T1BPType && T2BPType) {
447 T1 = T1BPType->getPointeeType();
448 T2 = T2BPType->getPointeeType();
449 return true;
450 }
451
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000452 return false;
453}
454
Sebastian Redldb647282009-01-27 23:18:31 +0000455/// CastsAwayConstness - Check if the pointer conversion from SrcType to
456/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
457/// the cast checkers. Both arguments must denote pointer (possibly to member)
458/// types.
John McCallf85e1932011-06-15 23:02:42 +0000459///
460/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
461///
462/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000463static bool
John McCallf85e1932011-06-15 23:02:42 +0000464CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
465 bool CheckCVR, bool CheckObjCLifetime) {
466 // If the only checking we care about is for Objective-C lifetime qualifiers,
467 // and we're not in ARC mode, there's nothing to check.
468 if (!CheckCVR && CheckObjCLifetime &&
David Blaikie4e4d0842012-03-11 07:00:24 +0000469 !Self.Context.getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +0000470 return false;
471
Sebastian Redldb647282009-01-27 23:18:31 +0000472 // Casting away constness is defined in C++ 5.2.11p8 with reference to
473 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
474 // the rules are non-trivial. So first we construct Tcv *...cv* as described
475 // in C++ 5.2.11p8.
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000476 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
477 SrcType->isBlockPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000478 "Source type is not pointer or pointer to member.");
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000479 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
480 DestType->isBlockPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000481 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000482
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000483 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
484 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000485 SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000486
Douglas Gregord4c5f842011-04-15 17:59:54 +0000487 // Find the qualifiers. We only care about cvr-qualifiers for the
488 // purpose of this check, because other qualifiers (address spaces,
489 // Objective-C GC, etc.) are part of the type's identity.
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000490 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCallf85e1932011-06-15 23:02:42 +0000491 // Determine the relevant qualifiers at this level.
492 Qualifiers SrcQuals, DestQuals;
Anders Carlsson52647c62010-06-04 22:47:55 +0000493 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
Anders Carlsson52647c62010-06-04 22:47:55 +0000494 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
John McCallf85e1932011-06-15 23:02:42 +0000495
496 Qualifiers RetainedSrcQuals, RetainedDestQuals;
497 if (CheckCVR) {
498 RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
499 RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
500 }
501
502 if (CheckObjCLifetime &&
503 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
504 return true;
505
506 cv1.push_back(RetainedSrcQuals);
507 cv2.push_back(RetainedDestQuals);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000508 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000509 if (cv1.empty())
510 return false;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000511
512 // Construct void pointers with those qualifiers (in reverse order of
513 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000514 QualType SrcConstruct = Self.Context.VoidTy;
515 QualType DestConstruct = Self.Context.VoidTy;
John McCall0953e762009-09-24 19:53:00 +0000516 ASTContext &Context = Self.Context;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000517 for (SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
John McCall0953e762009-09-24 19:53:00 +0000518 i2 = cv2.rbegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000519 i1 != cv1.rend(); ++i1, ++i2) {
John McCall0953e762009-09-24 19:53:00 +0000520 SrcConstruct
521 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
522 DestConstruct
523 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000524 }
525
526 // Test if they're compatible.
John McCallf85e1932011-06-15 23:02:42 +0000527 bool ObjCLifetimeConversion;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000528 return SrcConstruct != DestConstruct &&
John McCallf85e1932011-06-15 23:02:42 +0000529 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
530 ObjCLifetimeConversion);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000531}
532
Sebastian Redl26d85b12008-11-05 21:50:06 +0000533/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
534/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
535/// checked downcasts in class hierarchies.
John McCallb45ae252011-10-05 07:41:44 +0000536void CastOperation::CheckDynamicCast() {
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000537 if (ValueKind == VK_RValue)
Eli Friedman7a420df2011-10-31 20:59:03 +0000538 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000539 else if (isPlaceholder())
540 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
541 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
542 return;
Eli Friedman7a420df2011-10-31 20:59:03 +0000543
John McCallb45ae252011-10-05 07:41:44 +0000544 QualType OrigSrcType = SrcExpr.get()->getType();
545 QualType DestType = Self.Context.getCanonicalType(this->DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000546
547 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
548 // or "pointer to cv void".
549
550 QualType DestPointee;
Ted Kremenek6217b802009-07-29 21:53:49 +0000551 const PointerType *DestPointer = DestType->getAs<PointerType>();
John McCallf89e55a2010-11-18 06:31:45 +0000552 const ReferenceType *DestReference = 0;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000553 if (DestPointer) {
554 DestPointee = DestPointer->getPointeeType();
John McCallf89e55a2010-11-18 06:31:45 +0000555 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000556 DestPointee = DestReference->getPointeeType();
557 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000558 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
John McCallb45ae252011-10-05 07:41:44 +0000559 << this->DestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000560 return;
561 }
562
Ted Kremenek6217b802009-07-29 21:53:49 +0000563 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000564 if (DestPointee->isVoidType()) {
565 assert(DestPointer && "Reference to void is not possible");
566 } else if (DestRecord) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000567 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregord10099e2012-05-04 16:32:21 +0000568 diag::err_bad_dynamic_cast_incomplete,
569 DestRange))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000570 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000571 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000572 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000573 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000574 return;
575 }
576
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000577 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
578 // complete class type, [...]. If T is an lvalue reference type, v shall be
Douglas Gregordc843f22011-01-22 00:06:57 +0000579 // an lvalue of a complete class type, [...]. If T is an rvalue reference
580 // type, v shall be an expression having a complete class type, [...]
Sebastian Redl37d6de32008-11-08 13:00:26 +0000581 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000582 QualType SrcPointee;
583 if (DestPointer) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000584 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000585 SrcPointee = SrcPointer->getPointeeType();
586 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000587 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
John Wiegley429bb272011-04-08 18:41:53 +0000588 << OrigSrcType << SrcExpr.get()->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000589 return;
590 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000591 } else if (DestReference->isLValueReferenceType()) {
John Wiegley429bb272011-04-08 18:41:53 +0000592 if (!SrcExpr.get()->isLValue()) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000593 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
John McCallb45ae252011-10-05 07:41:44 +0000594 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000595 }
596 SrcPointee = SrcType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000597 } else {
598 SrcPointee = SrcType;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000599 }
600
Ted Kremenek6217b802009-07-29 21:53:49 +0000601 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000602 if (SrcRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000603 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregord10099e2012-05-04 16:32:21 +0000604 diag::err_bad_dynamic_cast_incomplete,
605 SrcExpr.get()))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000606 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000607 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000608 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
John Wiegley429bb272011-04-08 18:41:53 +0000609 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000610 return;
611 }
612
613 assert((DestPointer || DestReference) &&
614 "Bad destination non-ptr/ref slipped through.");
615 assert((DestRecord || DestPointee->isVoidType()) &&
616 "Bad destination pointee slipped through.");
617 assert(SrcRecord && "Bad source pointee slipped through.");
618
619 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
620 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +0000621 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
John McCallb45ae252011-10-05 07:41:44 +0000622 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000623 return;
624 }
625
626 // C++ 5.2.7p3: If the type of v is the same as the required result type,
627 // [except for cv].
628 if (DestRecord == SrcRecord) {
John McCall2de56d12010-08-25 11:45:40 +0000629 Kind = CK_NoOp;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000630 return;
631 }
632
633 // C++ 5.2.7p5
634 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000635 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000636 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
637 OpRange.getBegin(), OpRange,
638 &BasePath))
639 return;
640
John McCall2de56d12010-08-25 11:45:40 +0000641 Kind = CK_DerivedToBase;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000642
643 // If we are casting to or through a virtual base class, we need a
644 // vtable.
645 if (Self.BasePathInvolvesVirtualBase(BasePath))
646 Self.MarkVTableUsed(OpRange.getBegin(),
647 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000648 return;
649 }
650
651 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor952b0172010-02-11 01:04:33 +0000652 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000653 assert(SrcDecl && "Definition missing");
654 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000655 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
John Wiegley429bb272011-04-08 18:41:53 +0000656 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000657 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000658 Self.MarkVTableUsed(OpRange.getBegin(),
659 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000660
661 // Done. Everything else is run-time checks.
John McCall2de56d12010-08-25 11:45:40 +0000662 Kind = CK_Dynamic;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000663}
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000664
665/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
666/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
667/// like this:
668/// const char *str = "literal";
669/// legacy_function(const_cast\<char*\>(str));
John McCallb45ae252011-10-05 07:41:44 +0000670void CastOperation::CheckConstCast() {
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000671 if (ValueKind == VK_RValue)
John Wiegley429bb272011-04-08 18:41:53 +0000672 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000673 else if (isPlaceholder())
674 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
675 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
676 return;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000677
678 unsigned msg = diag::err_bad_cxx_cast_generic;
John Wiegley429bb272011-04-08 18:41:53 +0000679 if (TryConstCast(Self, SrcExpr.get(), DestType, /*CStyle*/false, msg) != TC_Success
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000680 && msg != 0)
681 Self.Diag(OpRange.getBegin(), msg) << CT_Const
John Wiegley429bb272011-04-08 18:41:53 +0000682 << SrcExpr.get()->getType() << DestType << OpRange;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000683}
684
685/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
686/// valid.
687/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
688/// like this:
689/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
John McCallb45ae252011-10-05 07:41:44 +0000690void CastOperation::CheckReinterpretCast() {
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000691 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
John Wiegley429bb272011-04-08 18:41:53 +0000692 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000693 else
694 checkNonOverloadPlaceholders();
695 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
696 return;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000697
698 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCallf85e1932011-06-15 23:02:42 +0000699 TryCastResult tcr =
700 TryReinterpretCast(Self, SrcExpr, DestType,
701 /*CStyle*/false, OpRange, msg, Kind);
702 if (tcr != TC_Success && msg != 0)
Douglas Gregor8e960432010-11-08 03:40:48 +0000703 {
John Wiegley429bb272011-04-08 18:41:53 +0000704 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
705 return;
706 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor8e960432010-11-08 03:40:48 +0000707 //FIXME: &f<int>; is overloaded and resolvable
708 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
John Wiegley429bb272011-04-08 18:41:53 +0000709 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
Douglas Gregor8e960432010-11-08 03:40:48 +0000710 << DestType << OpRange;
John Wiegley429bb272011-04-08 18:41:53 +0000711 Self.NoteAllOverloadCandidates(SrcExpr.get());
Douglas Gregor8e960432010-11-08 03:40:48 +0000712
John McCall79ab2c82011-02-14 18:34:10 +0000713 } else {
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000714 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
715 DestType, /*listInitialization=*/false);
Douglas Gregor8e960432010-11-08 03:40:48 +0000716 }
David Blaikie4e4d0842012-03-11 07:00:24 +0000717 } else if (tcr == TC_Success && Self.getLangOpts().ObjCAutoRefCount) {
John McCallb45ae252011-10-05 07:41:44 +0000718 checkObjCARCConversion(Sema::CCK_OtherCast);
John McCallf85e1932011-06-15 23:02:42 +0000719 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000720}
721
722
723/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
724/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
725/// implicit conversions explicit and getting rid of data loss warnings.
Richard Smithc8d7f582011-11-29 22:48:16 +0000726void CastOperation::CheckStaticCast() {
John McCalla180f042011-10-06 23:25:11 +0000727 if (isPlaceholder()) {
728 checkNonOverloadPlaceholders();
729 if (SrcExpr.isInvalid())
730 return;
731 }
732
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000733 // This test is outside everything else because it's the only case where
734 // a non-lvalue-reference target type does not lead to decay.
735 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000736 if (DestType->isVoidType()) {
John McCalla180f042011-10-06 23:25:11 +0000737 Kind = CK_ToVoid;
738
739 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall6dbba4f2011-10-11 23:14:30 +0000740 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000741 false, // Decay Function to ptr
742 true, // Complain
743 OpRange, DestType, diag::err_bad_static_cast_overload);
John McCall6dbba4f2011-10-11 23:14:30 +0000744 if (SrcExpr.isInvalid())
745 return;
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000746 }
John McCalla180f042011-10-06 23:25:11 +0000747
748 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000749 return;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000750 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000751
John McCall6dbba4f2011-10-11 23:14:30 +0000752 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
753 !isPlaceholder(BuiltinType::Overload)) {
John Wiegley429bb272011-04-08 18:41:53 +0000754 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
755 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
756 return;
757 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000758
759 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCallf85e1932011-06-15 23:02:42 +0000760 TryCastResult tcr
Richard Smithc8d7f582011-11-29 22:48:16 +0000761 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000762 Kind, BasePath, /*ListInitialization=*/false);
John McCallf85e1932011-06-15 23:02:42 +0000763 if (tcr != TC_Success && msg != 0) {
John Wiegley429bb272011-04-08 18:41:53 +0000764 if (SrcExpr.isInvalid())
765 return;
766 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
767 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
Douglas Gregor8e960432010-11-08 03:40:48 +0000768 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
Douglas Gregor4c9be892011-02-28 20:01:57 +0000769 << oe->getName() << DestType << OpRange
770 << oe->getQualifierLoc().getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +0000771 Self.NoteAllOverloadCandidates(SrcExpr.get());
John McCall79ab2c82011-02-14 18:34:10 +0000772 } else {
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000773 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
774 /*listInitialization=*/false);
Douglas Gregor8e960432010-11-08 03:40:48 +0000775 }
John McCallf85e1932011-06-15 23:02:42 +0000776 } else if (tcr == TC_Success) {
777 if (Kind == CK_BitCast)
John McCallb45ae252011-10-05 07:41:44 +0000778 checkCastAlign();
David Blaikie4e4d0842012-03-11 07:00:24 +0000779 if (Self.getLangOpts().ObjCAutoRefCount)
Richard Smithc8d7f582011-11-29 22:48:16 +0000780 checkObjCARCConversion(Sema::CCK_OtherCast);
John McCallb45ae252011-10-05 07:41:44 +0000781 } else if (Kind == CK_BitCast) {
782 checkCastAlign();
Douglas Gregor8e960432010-11-08 03:40:48 +0000783 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000784}
785
786/// TryStaticCast - Check if a static cast can be performed, and do so if
787/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
788/// and casting away constness.
John Wiegley429bb272011-04-08 18:41:53 +0000789static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCallf85e1932011-06-15 23:02:42 +0000790 QualType DestType,
791 Sema::CheckedConversionKind CCK,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000792 const SourceRange &OpRange, unsigned &msg,
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000793 CastKind &Kind, CXXCastPath &BasePath,
794 bool ListInitialization) {
John McCallf85e1932011-06-15 23:02:42 +0000795 // Determine whether we have the semantics of a C-style cast.
796 bool CStyle
797 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
798
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000799 // The order the tests is not entirely arbitrary. There is one conversion
800 // that can be handled in two different ways. Given:
801 // struct A {};
802 // struct B : public A {
803 // B(); B(const A&);
804 // };
805 // const A &a = B();
806 // the cast static_cast<const B&>(a) could be seen as either a static
807 // reference downcast, or an explicit invocation of the user-defined
808 // conversion using B's conversion constructor.
809 // DR 427 specifies that the downcast is to be applied here.
810
811 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
812 // Done outside this function.
813
814 TryCastResult tcr;
815
816 // C++ 5.2.9p5, reference downcast.
817 // See the function for details.
818 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000819 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
820 OpRange, msg, Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000821 if (tcr != TC_NotApplicable)
822 return tcr;
823
Douglas Gregordc843f22011-01-22 00:06:57 +0000824 // C++0x [expr.static.cast]p3:
825 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
826 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000827 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
828 BasePath, msg);
Douglas Gregor88b22a42011-01-25 16:13:26 +0000829 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000830 return tcr;
831
832 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
833 // [...] if the declaration "T t(e);" is well-formed, [...].
John McCallf85e1932011-06-15 23:02:42 +0000834 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000835 Kind, ListInitialization);
John Wiegley429bb272011-04-08 18:41:53 +0000836 if (SrcExpr.isInvalid())
837 return TC_Failed;
Anders Carlsson3c31a392009-09-26 00:12:34 +0000838 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000839 return tcr;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000840
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000841 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
842 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
843 // conversions, subject to further restrictions.
844 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
845 // of qualification conversions impossible.
846 // In the CStyle case, the earlier attempt to const_cast should have taken
847 // care of reverse qualification conversions.
848
John Wiegley429bb272011-04-08 18:41:53 +0000849 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000850
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000851 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
Douglas Gregor1e856d92011-02-18 03:01:41 +0000852 // converted to an integral type. [...] A value of a scoped enumeration type
853 // can also be explicitly converted to a floating-point type [...].
854 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
855 if (Enum->getDecl()->isScoped()) {
856 if (DestType->isBooleanType()) {
857 Kind = CK_IntegralToBoolean;
858 return TC_Success;
859 } else if (DestType->isIntegralType(Self.Context)) {
860 Kind = CK_IntegralCast;
861 return TC_Success;
862 } else if (DestType->isRealFloatingType()) {
863 Kind = CK_IntegralToFloating;
864 return TC_Success;
865 }
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000866 }
867 }
Douglas Gregor1e856d92011-02-18 03:01:41 +0000868
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000869 // Reverse integral promotion/conversion. All such conversions are themselves
870 // again integral promotions or conversions and are thus already handled by
871 // p2 (TryDirectInitialization above).
872 // (Note: any data loss warnings should be suppressed.)
873 // The exception is the reverse of enum->integer, i.e. integer->enum (and
874 // enum->enum). See also C++ 5.2.9p7.
875 // The same goes for reverse floating point promotion/conversion and
876 // floating-integral conversions. Again, only floating->enum is relevant.
877 if (DestType->isEnumeralType()) {
Eli Friedmancc2fca22011-09-02 17:38:59 +0000878 if (SrcType->isIntegralOrEnumerationType()) {
John McCall2de56d12010-08-25 11:45:40 +0000879 Kind = CK_IntegralCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000880 return TC_Success;
Eli Friedmancc2fca22011-09-02 17:38:59 +0000881 } else if (SrcType->isRealFloatingType()) {
882 Kind = CK_FloatingToIntegral;
883 return TC_Success;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000884 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000885 }
886
887 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
888 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000889 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000890 Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000891 if (tcr != TC_NotApplicable)
892 return tcr;
893
894 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
895 // conversion. C++ 5.2.9p9 has additional information.
896 // DR54's access restrictions apply here also.
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000897 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssoncee22422010-04-24 19:22:20 +0000898 OpRange, msg, Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000899 if (tcr != TC_NotApplicable)
900 return tcr;
901
902 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
903 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
904 // just the usual constness stuff.
Ted Kremenek6217b802009-07-29 21:53:49 +0000905 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000906 QualType SrcPointee = SrcPointer->getPointeeType();
907 if (SrcPointee->isVoidType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000908 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000909 QualType DestPointee = DestPointer->getPointeeType();
910 if (DestPointee->isIncompleteOrObjectType()) {
911 // This is definitely the intended conversion, but it might fail due
John McCallf85e1932011-06-15 23:02:42 +0000912 // to a qualifier violation. Note that we permit Objective-C lifetime
913 // and GC qualifier mismatches here.
914 if (!CStyle) {
915 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
916 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
917 DestPointeeQuals.removeObjCGCAttr();
918 DestPointeeQuals.removeObjCLifetime();
919 SrcPointeeQuals.removeObjCGCAttr();
920 SrcPointeeQuals.removeObjCLifetime();
921 if (DestPointeeQuals != SrcPointeeQuals &&
922 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
923 msg = diag::err_bad_cxx_cast_qualifiers_away;
924 return TC_Failed;
925 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000926 }
John McCall2de56d12010-08-25 11:45:40 +0000927 Kind = CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000928 return TC_Success;
929 }
930 }
Fariborz Jahanian2f6c5502010-05-10 23:46:53 +0000931 else if (DestType->isObjCObjectPointerType()) {
932 // allow both c-style cast and static_cast of objective-c pointers as
933 // they are pervasive.
John McCall1d9b3b22011-09-09 05:25:32 +0000934 Kind = CK_CPointerToObjCPointerCast;
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +0000935 return TC_Success;
936 }
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +0000937 else if (CStyle && DestType->isBlockPointerType()) {
938 // allow c-style cast of void * to block pointers.
John McCall2de56d12010-08-25 11:45:40 +0000939 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +0000940 return TC_Success;
941 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000942 }
943 }
Fariborz Jahanian65267b22010-05-12 18:16:59 +0000944 // Allow arbitray objective-c pointer conversion with static casts.
945 if (SrcType->isObjCObjectPointerType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +0000946 DestType->isObjCObjectPointerType()) {
947 Kind = CK_BitCast;
Fariborz Jahanian65267b22010-05-12 18:16:59 +0000948 return TC_Success;
John McCalldaa8e4e2010-11-15 09:13:47 +0000949 }
Fariborz Jahanian65267b22010-05-12 18:16:59 +0000950
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000951 // We tried everything. Everything! Nothing works! :-(
952 return TC_NotApplicable;
953}
954
955/// Tests whether a conversion according to N2844 is valid.
956TryCastResult
957TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000958 bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
959 unsigned &msg) {
Douglas Gregordc843f22011-01-22 00:06:57 +0000960 // C++0x [expr.static.cast]p3:
961 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
962 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenek6217b802009-07-29 21:53:49 +0000963 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000964 if (!R)
965 return TC_NotApplicable;
966
Douglas Gregordc843f22011-01-22 00:06:57 +0000967 if (!SrcExpr->isGLValue())
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000968 return TC_NotApplicable;
969
970 // Because we try the reference downcast before this function, from now on
971 // this is the only cast possibility, so we issue an error if we fail now.
972 // FIXME: Should allow casting away constness if CStyle.
973 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +0000974 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +0000975 bool ObjCLifetimeConversion;
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000976 QualType FromType = SrcExpr->getType();
977 QualType ToType = R->getPointeeType();
978 if (CStyle) {
979 FromType = FromType.getUnqualifiedType();
980 ToType = ToType.getUnqualifiedType();
981 }
982
Douglas Gregor393896f2009-11-05 13:06:35 +0000983 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000984 ToType, FromType,
John McCallf85e1932011-06-15 23:02:42 +0000985 DerivedToBase, ObjCConversion,
986 ObjCLifetimeConversion)
987 < Sema::Ref_Compatible_With_Added_Qualification) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000988 msg = diag::err_bad_lvalue_to_rvalue_cast;
989 return TC_Failed;
990 }
991
Douglas Gregor88b22a42011-01-25 16:13:26 +0000992 if (DerivedToBase) {
993 Kind = CK_DerivedToBase;
994 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
995 /*DetectVirtual=*/true);
996 if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
997 return TC_NotApplicable;
998
999 Self.BuildBasePathArray(Paths, BasePath);
1000 } else
1001 Kind = CK_NoOp;
1002
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001003 return TC_Success;
1004}
1005
1006/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1007TryCastResult
1008TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
1009 bool CStyle, const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +00001010 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001011 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001012 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1013 // cast to type "reference to cv2 D", where D is a class derived from B,
1014 // if a valid standard conversion from "pointer to D" to "pointer to B"
1015 // exists, cv2 >= cv1, and B is not a virtual base class of D.
1016 // In addition, DR54 clarifies that the base must be accessible in the
1017 // current context. Although the wording of DR54 only applies to the pointer
1018 // variant of this rule, the intent is clearly for it to apply to the this
1019 // conversion as well.
1020
Ted Kremenek6217b802009-07-29 21:53:49 +00001021 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001022 if (!DestReference) {
1023 return TC_NotApplicable;
1024 }
1025 bool RValueRef = DestReference->isRValueReferenceType();
John McCall7eb0a9e2010-11-24 05:12:34 +00001026 if (!RValueRef && !SrcExpr->isLValue()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001027 // We know the left side is an lvalue reference, so we can suggest a reason.
1028 msg = diag::err_bad_cxx_cast_rvalue;
1029 return TC_NotApplicable;
1030 }
1031
1032 QualType DestPointee = DestReference->getPointeeType();
1033
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001034 return TryStaticDowncast(Self,
1035 Self.Context.getCanonicalType(SrcExpr->getType()),
1036 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001037 OpRange, SrcExpr->getType(), DestType, msg, Kind,
1038 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001039}
1040
1041/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1042TryCastResult
1043TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +00001044 bool CStyle, const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +00001045 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001046 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001047 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1048 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1049 // is a class derived from B, if a valid standard conversion from "pointer
1050 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1051 // class of D.
1052 // In addition, DR54 clarifies that the base must be accessible in the
1053 // current context.
1054
Ted Kremenek6217b802009-07-29 21:53:49 +00001055 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001056 if (!DestPointer) {
1057 return TC_NotApplicable;
1058 }
1059
Ted Kremenek6217b802009-07-29 21:53:49 +00001060 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001061 if (!SrcPointer) {
1062 msg = diag::err_bad_static_cast_pointer_nonpointer;
1063 return TC_NotApplicable;
1064 }
1065
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001066 return TryStaticDowncast(Self,
1067 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1068 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001069 CStyle, OpRange, SrcType, DestType, msg, Kind,
1070 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001071}
1072
1073/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1074/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001075/// DestType is possible and allowed.
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001076TryCastResult
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001077TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001078 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +00001079 QualType OrigDestType, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +00001080 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl5ed66f72009-10-22 15:07:22 +00001081 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregord10099e2012-05-04 16:32:21 +00001082 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, 0) ||
1083 Self.RequireCompleteType(OpRange.getBegin(), DestType, 0))
Sebastian Redl5ed66f72009-10-22 15:07:22 +00001084 return TC_NotApplicable;
1085
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001086 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001087 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001088 return TC_NotApplicable;
1089 }
1090
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001091 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001092 /*DetectVirtual=*/true);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001093 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
1094 return TC_NotApplicable;
1095 }
1096
1097 // Target type does derive from source type. Now we're serious. If an error
1098 // appears now, it's not ignored.
1099 // This may not be entirely in line with the standard. Take for example:
1100 // struct A {};
1101 // struct B : virtual A {
1102 // B(A&);
1103 // };
Mike Stump1eb44332009-09-09 15:08:12 +00001104 //
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001105 // void f()
1106 // {
1107 // (void)static_cast<const B&>(*((A*)0));
1108 // }
1109 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1110 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1111 // However, both GCC and Comeau reject this example, and accepting it would
1112 // mean more complex code if we're to preserve the nice error message.
1113 // FIXME: Being 100% compliant here would be nice to have.
1114
1115 // Must preserve cv, as always, unless we're in C-style mode.
1116 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001117 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001118 return TC_Failed;
1119 }
1120
1121 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1122 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1123 // that it builds the paths in reverse order.
1124 // To sum up: record all paths to the base and build a nice string from
1125 // them. Use it to spice up the error message.
1126 if (!Paths.isRecordingPaths()) {
1127 Paths.clear();
1128 Paths.setRecordingPaths(true);
1129 Self.IsDerivedFrom(DestType, SrcType, Paths);
1130 }
1131 std::string PathDisplayStr;
1132 std::set<unsigned> DisplayedPaths;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001133 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001134 PI != PE; ++PI) {
1135 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
1136 // We haven't displayed a path to this particular base
1137 // class subobject yet.
1138 PathDisplayStr += "\n ";
Douglas Gregora8f32e02009-10-06 17:59:45 +00001139 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
1140 EE = PI->rend();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001141 EI != EE; ++EI)
1142 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001143 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001144 }
1145 }
1146
1147 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001148 << QualType(SrcType).getUnqualifiedType()
1149 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001150 << PathDisplayStr << OpRange;
1151 msg = 0;
1152 return TC_Failed;
1153 }
1154
1155 if (Paths.getDetectedVirtual() != 0) {
1156 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1157 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1158 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1159 msg = 0;
1160 return TC_Failed;
1161 }
1162
John McCall417d39f2011-02-14 23:21:33 +00001163 if (!CStyle) {
1164 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1165 SrcType, DestType,
1166 Paths.front(),
John McCall58e6f342010-03-16 05:22:47 +00001167 diag::err_downcast_from_inaccessible_base)) {
John McCall417d39f2011-02-14 23:21:33 +00001168 case Sema::AR_accessible:
1169 case Sema::AR_delayed: // be optimistic
1170 case Sema::AR_dependent: // be optimistic
1171 break;
1172
1173 case Sema::AR_inaccessible:
1174 msg = 0;
1175 return TC_Failed;
1176 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001177 }
1178
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001179 Self.BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00001180 Kind = CK_BaseToDerived;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001181 return TC_Success;
1182}
1183
1184/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1185/// C++ 5.2.9p9 is valid:
1186///
1187/// An rvalue of type "pointer to member of D of type cv1 T" can be
1188/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1189/// where B is a base class of D [...].
1190///
1191TryCastResult
John Wiegley429bb272011-04-08 18:41:53 +00001192TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001193 QualType DestType, bool CStyle,
1194 const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +00001195 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001196 CXXCastPath &BasePath) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001197 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001198 if (!DestMemPtr)
1199 return TC_NotApplicable;
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001200
1201 bool WasOverloadedFunction = false;
John McCall6bb80172010-03-30 21:47:33 +00001202 DeclAccessPair FoundOverload;
John Wiegley429bb272011-04-08 18:41:53 +00001203 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor1a8cf732010-04-14 23:11:21 +00001204 if (FunctionDecl *Fn
John Wiegley429bb272011-04-08 18:41:53 +00001205 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
Douglas Gregor1a8cf732010-04-14 23:11:21 +00001206 FoundOverload)) {
1207 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1208 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1209 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1210 WasOverloadedFunction = true;
1211 }
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001212 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00001213
Ted Kremenek6217b802009-07-29 21:53:49 +00001214 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001215 if (!SrcMemPtr) {
1216 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1217 return TC_NotApplicable;
1218 }
1219
1220 // T == T, modulo cv
Douglas Gregora4923eb2009-11-16 21:35:15 +00001221 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1222 DestMemPtr->getPointeeType()))
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001223 return TC_NotApplicable;
1224
1225 // B base of D
1226 QualType SrcClass(SrcMemPtr->getClass(), 0);
1227 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssoncee22422010-04-24 19:22:20 +00001228 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001229 /*DetectVirtual=*/true);
1230 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
1231 return TC_NotApplicable;
1232 }
1233
1234 // 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 +00001235 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001236 Paths.clear();
1237 Paths.setRecordingPaths(true);
1238 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
1239 assert(StillOkay);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001240 (void)StillOkay;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001241 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1242 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1243 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1244 msg = 0;
1245 return TC_Failed;
1246 }
1247
1248 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1249 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1250 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1251 msg = 0;
1252 return TC_Failed;
1253 }
1254
John McCall417d39f2011-02-14 23:21:33 +00001255 if (!CStyle) {
1256 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1257 DestClass, SrcClass,
1258 Paths.front(),
1259 diag::err_upcast_to_inaccessible_base)) {
1260 case Sema::AR_accessible:
1261 case Sema::AR_delayed:
1262 case Sema::AR_dependent:
1263 // Optimistically assume that the delayed and dependent cases
1264 // will work out.
1265 break;
1266
1267 case Sema::AR_inaccessible:
1268 msg = 0;
1269 return TC_Failed;
1270 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001271 }
1272
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001273 if (WasOverloadedFunction) {
1274 // Resolve the address of the overloaded function again, this time
1275 // allowing complaints if something goes wrong.
John Wiegley429bb272011-04-08 18:41:53 +00001276 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001277 DestType,
John McCall6bb80172010-03-30 21:47:33 +00001278 true,
1279 FoundOverload);
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001280 if (!Fn) {
1281 msg = 0;
1282 return TC_Failed;
1283 }
1284
John McCall6bb80172010-03-30 21:47:33 +00001285 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
John Wiegley429bb272011-04-08 18:41:53 +00001286 if (!SrcExpr.isUsable()) {
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001287 msg = 0;
1288 return TC_Failed;
1289 }
1290 }
1291
Anders Carlssoncee22422010-04-24 19:22:20 +00001292 Self.BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00001293 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001294 return TC_Success;
1295}
1296
1297/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1298/// is valid:
1299///
1300/// An expression e can be explicitly converted to a type T using a
1301/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1302TryCastResult
John Wiegley429bb272011-04-08 18:41:53 +00001303TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCallf85e1932011-06-15 23:02:42 +00001304 Sema::CheckedConversionKind CCK,
1305 const SourceRange &OpRange, unsigned &msg,
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001306 CastKind &Kind, bool ListInitialization) {
Anders Carlssond851b372009-09-07 18:25:47 +00001307 if (DestType->isRecordType()) {
1308 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
Aaron Ballman21eb6d42012-05-07 00:02:00 +00001309 diag::err_bad_dynamic_cast_incomplete) ||
Eli Friedman860a3192012-06-16 02:19:17 +00001310 Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
Aaron Ballman21eb6d42012-05-07 00:02:00 +00001311 diag::err_allocation_of_abstract_type)) {
Anders Carlssond851b372009-09-07 18:25:47 +00001312 msg = 0;
1313 return TC_Failed;
1314 }
1315 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00001316
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001317 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1318 InitializationKind InitKind
John McCallf85e1932011-06-15 23:02:42 +00001319 = (CCK == Sema::CCK_CStyleCast)
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00001320 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001321 ListInitialization)
John McCallf85e1932011-06-15 23:02:42 +00001322 : (CCK == Sema::CCK_FunctionalCast)
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001323 ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
Richard Smithc8d7f582011-11-29 22:48:16 +00001324 : InitializationKind::CreateCast(OpRange);
John Wiegley429bb272011-04-08 18:41:53 +00001325 Expr *SrcExprRaw = SrcExpr.get();
1326 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExprRaw, 1);
Douglas Gregor8e960432010-11-08 03:40:48 +00001327
1328 // At this point of CheckStaticCast, if the destination is a reference,
1329 // or the expression is an overload expression this has to work.
1330 // There is no other way that works.
1331 // On the other hand, if we're checking a C-style cast, we've still got
1332 // the reinterpret_cast way.
John McCallf85e1932011-06-15 23:02:42 +00001333 bool CStyle
1334 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
Sebastian Redl383616c2011-06-05 12:23:28 +00001335 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
Anders Carlsson3c31a392009-09-26 00:12:34 +00001336 return TC_NotApplicable;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001337
Benjamin Kramer5354e772012-08-23 23:38:35 +00001338 ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001339 if (Result.isInvalid()) {
1340 msg = 0;
1341 return TC_Failed;
1342 }
1343
Douglas Gregord6e44a32010-04-16 22:09:46 +00001344 if (InitSeq.isConstructorInitialization())
John McCall2de56d12010-08-25 11:45:40 +00001345 Kind = CK_ConstructorConversion;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001346 else
John McCall2de56d12010-08-25 11:45:40 +00001347 Kind = CK_NoOp;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001348
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001349 SrcExpr = Result;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001350 return TC_Success;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001351}
1352
1353/// TryConstCast - See if a const_cast from source to destination is allowed,
1354/// and perform it if it is.
1355static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
1356 bool CStyle, unsigned &msg) {
1357 DestType = Self.Context.getCanonicalType(DestType);
1358 QualType SrcType = SrcExpr->getType();
Douglas Gregor575d2a32011-01-22 00:19:52 +00001359 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
1360 if (DestTypeTmp->isLValueReferenceType() && !SrcExpr->isLValue()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001361 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1362 // is C-style, static_cast might find a way, so we simply suggest a
1363 // message and tell the parent to keep searching.
1364 msg = diag::err_bad_cxx_cast_rvalue;
1365 return TC_NotApplicable;
1366 }
1367
1368 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
1369 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
1370 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1371 SrcType = Self.Context.getPointerType(SrcType);
1372 }
1373
1374 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1375 // the rules for const_cast are the same as those used for pointers.
1376
John McCalld425d2b2010-05-18 09:35:29 +00001377 if (!DestType->isPointerType() &&
1378 !DestType->isMemberPointerType() &&
1379 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001380 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1381 // was a reference type, we converted it to a pointer above.
1382 // The status of rvalue references isn't entirely clear, but it looks like
1383 // conversion to them is simply invalid.
1384 // C++ 5.2.11p3: For two pointer types [...]
1385 if (!CStyle)
1386 msg = diag::err_bad_const_cast_dest;
1387 return TC_NotApplicable;
1388 }
1389 if (DestType->isFunctionPointerType() ||
1390 DestType->isMemberFunctionPointerType()) {
1391 // Cannot cast direct function pointers.
1392 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1393 // T is the ultimate pointee of source and target type.
1394 if (!CStyle)
1395 msg = diag::err_bad_const_cast_dest;
1396 return TC_NotApplicable;
1397 }
1398 SrcType = Self.Context.getCanonicalType(SrcType);
1399
1400 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1401 // completely equal.
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001402 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1403 // in multi-level pointers may change, but the level count must be the same,
1404 // as must be the final pointee type.
1405 while (SrcType != DestType &&
Douglas Gregor5a57efd2010-06-09 03:53:18 +00001406 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001407 Qualifiers SrcQuals, DestQuals;
1408 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
1409 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
1410
1411 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
1412 // the other qualifiers (e.g., address spaces) are identical.
1413 SrcQuals.removeCVRQualifiers();
1414 DestQuals.removeCVRQualifiers();
1415 if (SrcQuals != DestQuals)
1416 return TC_NotApplicable;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001417 }
1418
1419 // Since we're dealing in canonical types, the remainder must be the same.
1420 if (SrcType != DestType)
1421 return TC_NotApplicable;
1422
1423 return TC_Success;
1424}
1425
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001426// Checks for undefined behavior in reinterpret_cast.
1427// The cases that is checked for is:
1428// *reinterpret_cast<T*>(&a)
1429// reinterpret_cast<T&>(a)
1430// where accessing 'a' as type 'T' will result in undefined behavior.
1431void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1432 bool IsDereference,
1433 SourceRange Range) {
1434 unsigned DiagID = IsDereference ?
1435 diag::warn_pointer_indirection_from_incompatible_type :
1436 diag::warn_undefined_reinterpret_cast;
1437
1438 if (Diags.getDiagnosticLevel(DiagID, Range.getBegin()) ==
David Blaikied6471f72011-09-25 23:23:43 +00001439 DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001440 return;
1441 }
1442
1443 QualType SrcTy, DestTy;
1444 if (IsDereference) {
1445 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1446 return;
1447 }
1448 SrcTy = SrcType->getPointeeType();
1449 DestTy = DestType->getPointeeType();
1450 } else {
1451 if (!DestType->getAs<ReferenceType>()) {
1452 return;
1453 }
1454 SrcTy = SrcType;
1455 DestTy = DestType->getPointeeType();
1456 }
1457
1458 // Cast is compatible if the types are the same.
1459 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1460 return;
1461 }
1462 // or one of the types is a char or void type
1463 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1464 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1465 return;
1466 }
1467 // or one of the types is a tag type.
Chandler Carruth1f8f2d52011-05-24 07:43:19 +00001468 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001469 return;
1470 }
1471
Douglas Gregor575a1c92011-05-20 16:38:50 +00001472 // FIXME: Scoped enums?
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001473 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1474 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1475 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1476 return;
1477 }
1478 }
1479
1480 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1481}
Douglas Gregorfadb53b2011-03-12 01:48:56 +00001482
Fariborz Jahanian91dd9df2012-08-16 18:33:47 +00001483static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
1484 QualType DestType) {
1485 QualType SrcType = SrcExpr.get()->getType();
Fariborz Jahanian0c252fa2012-12-13 00:42:06 +00001486 if (Self.Context.hasSameType(SrcType, DestType))
1487 return;
Fariborz Jahanian91dd9df2012-08-16 18:33:47 +00001488 if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
1489 if (SrcPtrTy->isObjCSelType()) {
1490 QualType DT = DestType;
1491 if (isa<PointerType>(DestType))
1492 DT = DestType->getPointeeType();
1493 if (!DT.getUnqualifiedType()->isVoidType())
1494 Self.Diag(SrcExpr.get()->getExprLoc(),
1495 diag::warn_cast_pointer_from_sel)
1496 << SrcType << DestType << SrcExpr.get()->getSourceRange();
1497 }
1498}
1499
David Blaikie9b29f4f2012-10-16 18:53:14 +00001500static void checkIntToPointerCast(bool CStyle, SourceLocation Loc,
1501 const Expr *SrcExpr, QualType DestType,
1502 Sema &Self) {
1503 QualType SrcType = SrcExpr->getType();
1504
1505 // Not warning on reinterpret_cast, boolean, constant expressions, etc
1506 // are not explicit design choices, but consistent with GCC's behavior.
1507 // Feel free to modify them if you've reason/evidence for an alternative.
1508 if (CStyle && SrcType->isIntegralType(Self.Context)
1509 && !SrcType->isBooleanType()
1510 && !SrcType->isEnumeralType()
1511 && !SrcExpr->isIntegerConstantExpr(Self.Context)
1512 && Self.Context.getTypeSize(DestType) > Self.Context.getTypeSize(SrcType))
1513 Self.Diag(Loc, diag::warn_int_to_pointer_cast) << SrcType << DestType;
1514}
1515
John Wiegley429bb272011-04-08 18:41:53 +00001516static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001517 QualType DestType, bool CStyle,
1518 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +00001519 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +00001520 CastKind &Kind) {
Douglas Gregore39a3892010-07-13 23:17:26 +00001521 bool IsLValueCast = false;
1522
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001523 DestType = Self.Context.getCanonicalType(DestType);
John Wiegley429bb272011-04-08 18:41:53 +00001524 QualType SrcType = SrcExpr.get()->getType();
Douglas Gregor8e960432010-11-08 03:40:48 +00001525
1526 // Is the source an overloaded name? (i.e. &foo)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001527 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ...
1528 if (SrcType == Self.Context.OverloadTy) {
John McCall6dbba4f2011-10-11 23:14:30 +00001529 // ... unless foo<int> resolves to an lvalue unambiguously.
1530 // TODO: what if this fails because of DiagnoseUseOfDecl or something
1531 // like it?
1532 ExprResult SingleFunctionExpr = SrcExpr;
1533 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1534 SingleFunctionExpr,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001535 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
John McCall6dbba4f2011-10-11 23:14:30 +00001536 ) && SingleFunctionExpr.isUsable()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001537 SrcExpr = SingleFunctionExpr;
John Wiegley429bb272011-04-08 18:41:53 +00001538 SrcType = SrcExpr.get()->getType();
John McCall6dbba4f2011-10-11 23:14:30 +00001539 } else {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001540 return TC_NotApplicable;
John McCall6dbba4f2011-10-11 23:14:30 +00001541 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001542 }
Douglas Gregor8e960432010-11-08 03:40:48 +00001543
Ted Kremenek6217b802009-07-29 21:53:49 +00001544 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Richard Smith6850faf2012-04-29 08:24:44 +00001545 if (!SrcExpr.get()->isGLValue()) {
1546 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
1547 // similar comment in const_cast.
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001548 msg = diag::err_bad_cxx_cast_rvalue;
1549 return TC_NotApplicable;
1550 }
1551
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001552 if (!CStyle) {
1553 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
1554 /*isDereference=*/false, OpRange);
1555 }
1556
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001557 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1558 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1559 // built-in & and * operators.
Argyrios Kyrtzidisb464a5b2011-04-22 22:31:13 +00001560
Argyrios Kyrtzidisbb29d1b2011-04-22 23:57:57 +00001561 const char *inappropriate = 0;
1562 switch (SrcExpr.get()->getObjectKind()) {
Argyrios Kyrtzidise5e3d312011-04-23 01:10:24 +00001563 case OK_Ordinary:
1564 break;
Argyrios Kyrtzidisbb29d1b2011-04-22 23:57:57 +00001565 case OK_BitField: inappropriate = "bit-field"; break;
1566 case OK_VectorComponent: inappropriate = "vector element"; break;
1567 case OK_ObjCProperty: inappropriate = "property expression"; break;
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001568 case OK_ObjCSubscript: inappropriate = "container subscripting expression";
1569 break;
Argyrios Kyrtzidisbb29d1b2011-04-22 23:57:57 +00001570 }
1571 if (inappropriate) {
1572 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
1573 << inappropriate << DestType
1574 << OpRange << SrcExpr.get()->getSourceRange();
1575 msg = 0; SrcExpr = ExprError();
Argyrios Kyrtzidisb464a5b2011-04-22 22:31:13 +00001576 return TC_NotApplicable;
1577 }
1578
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001579 // This code does this transformation for the checked types.
1580 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1581 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregor8e960432010-11-08 03:40:48 +00001582
Douglas Gregore39a3892010-07-13 23:17:26 +00001583 IsLValueCast = true;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001584 }
1585
1586 // Canonicalize source for comparison.
1587 SrcType = Self.Context.getCanonicalType(SrcType);
1588
Ted Kremenek6217b802009-07-29 21:53:49 +00001589 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1590 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001591 if (DestMemPtr && SrcMemPtr) {
1592 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1593 // can be explicitly converted to an rvalue of type "pointer to member
1594 // of Y of type T2" if T1 and T2 are both function types or both object
1595 // types.
1596 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1597 SrcMemPtr->getPointeeType()->isFunctionType())
1598 return TC_NotApplicable;
1599
1600 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1601 // constness.
1602 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1603 // we accept it.
John McCallf85e1932011-06-15 23:02:42 +00001604 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1605 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001606 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001607 return TC_Failed;
1608 }
1609
Charles Davisf231df32010-08-16 05:30:44 +00001610 // Don't allow casting between member pointers of different sizes.
1611 if (Self.Context.getTypeSize(DestMemPtr) !=
1612 Self.Context.getTypeSize(SrcMemPtr)) {
1613 msg = diag::err_bad_cxx_cast_member_pointer_size;
1614 return TC_Failed;
1615 }
1616
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001617 // A valid member pointer cast.
John McCall4d4e5c12012-02-15 01:22:51 +00001618 assert(!IsLValueCast);
1619 Kind = CK_ReinterpretMemberPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001620 return TC_Success;
1621 }
1622
1623 // See below for the enumeral issue.
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001624 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001625 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1626 // type large enough to hold it. A value of std::nullptr_t can be
1627 // converted to an integral type; the conversion has the same meaning
1628 // and validity as a conversion of (void*)0 to the integral type.
1629 if (Self.Context.getTypeSize(SrcType) >
1630 Self.Context.getTypeSize(DestType)) {
1631 msg = diag::err_bad_reinterpret_cast_small_int;
1632 return TC_Failed;
1633 }
John McCall2de56d12010-08-25 11:45:40 +00001634 Kind = CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001635 return TC_Success;
1636 }
1637
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001638 bool destIsVector = DestType->isVectorType();
1639 bool srcIsVector = SrcType->isVectorType();
1640 if (srcIsVector || destIsVector) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001641 // FIXME: Should this also apply to floating point types?
1642 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1643 bool destIsScalar = DestType->isIntegralType(Self.Context);
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001644
1645 // Check if this is a cast between a vector and something else.
1646 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1647 !(srcIsVector && destIsVector))
1648 return TC_NotApplicable;
1649
1650 // If both types have the same size, we can successfully cast.
Douglas Gregorf2a55392009-12-22 22:47:22 +00001651 if (Self.Context.getTypeSize(SrcType)
1652 == Self.Context.getTypeSize(DestType)) {
John McCall2de56d12010-08-25 11:45:40 +00001653 Kind = CK_BitCast;
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001654 return TC_Success;
Douglas Gregorf2a55392009-12-22 22:47:22 +00001655 }
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001656
1657 if (destIsScalar)
1658 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1659 else if (srcIsScalar)
1660 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1661 else
1662 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1663
1664 return TC_Failed;
1665 }
Chad Rosier41f44312012-02-03 02:54:37 +00001666
1667 if (SrcType == DestType) {
1668 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1669 // restrictions, a cast to the same type is allowed so long as it does not
1670 // cast away constness. In C++98, the intent was not entirely clear here,
1671 // since all other paragraphs explicitly forbid casts to the same type.
1672 // C++11 clarifies this case with p2.
1673 //
1674 // The only allowed types are: integral, enumeration, pointer, or
1675 // pointer-to-member types. We also won't restrict Obj-C pointers either.
1676 Kind = CK_NoOp;
1677 TryCastResult Result = TC_NotApplicable;
1678 if (SrcType->isIntegralOrEnumerationType() ||
1679 SrcType->isAnyPointerType() ||
1680 SrcType->isMemberPointerType() ||
1681 SrcType->isBlockPointerType()) {
1682 Result = TC_Success;
1683 }
1684 return Result;
1685 }
1686
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001687 bool destIsPtr = DestType->isAnyPointerType() ||
1688 DestType->isBlockPointerType();
1689 bool srcIsPtr = SrcType->isAnyPointerType() ||
1690 SrcType->isBlockPointerType();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001691 if (!destIsPtr && !srcIsPtr) {
1692 // Except for std::nullptr_t->integer and lvalue->reference, which are
1693 // handled above, at least one of the two arguments must be a pointer.
1694 return TC_NotApplicable;
1695 }
1696
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001697 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001698 assert(srcIsPtr && "One type must be a pointer");
1699 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
Francois Pichet30aff5b2011-05-11 22:13:54 +00001700 // type large enough to hold it; except in Microsoft mode, where the
1701 // integral type size doesn't matter.
1702 if ((Self.Context.getTypeSize(SrcType) >
1703 Self.Context.getTypeSize(DestType)) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00001704 !Self.getLangOpts().MicrosoftExt) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001705 msg = diag::err_bad_reinterpret_cast_small_int;
1706 return TC_Failed;
1707 }
John McCall2de56d12010-08-25 11:45:40 +00001708 Kind = CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001709 return TC_Success;
1710 }
1711
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001712 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001713 assert(destIsPtr && "One type must be a pointer");
David Blaikie9b29f4f2012-10-16 18:53:14 +00001714 checkIntToPointerCast(CStyle, OpRange.getBegin(), SrcExpr.get(), DestType,
1715 Self);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001716 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1717 // converted to a pointer.
John McCall404cd162010-11-13 01:35:44 +00001718 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1719 // necessarily converted to a null pointer value.]
John McCall2de56d12010-08-25 11:45:40 +00001720 Kind = CK_IntegralToPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001721 return TC_Success;
1722 }
1723
1724 if (!destIsPtr || !srcIsPtr) {
1725 // With the valid non-pointer conversions out of the way, we can be even
1726 // more stringent.
1727 return TC_NotApplicable;
1728 }
1729
1730 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1731 // The C-style cast operator can.
John McCallf85e1932011-06-15 23:02:42 +00001732 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1733 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001734 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001735 return TC_Failed;
1736 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001737
1738 // Cannot convert between block pointers and Objective-C object pointers.
1739 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1740 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1741 return TC_NotApplicable;
1742
John McCall1d9b3b22011-09-09 05:25:32 +00001743 if (IsLValueCast) {
1744 Kind = CK_LValueBitCast;
1745 } else if (DestType->isObjCObjectPointerType()) {
John McCalldc05b112011-09-10 01:16:55 +00001746 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
John McCall1d9b3b22011-09-09 05:25:32 +00001747 } else if (DestType->isBlockPointerType()) {
1748 if (!SrcType->isBlockPointerType()) {
1749 Kind = CK_AnyPointerToBlockPointerCast;
1750 } else {
1751 Kind = CK_BitCast;
1752 }
1753 } else {
1754 Kind = CK_BitCast;
1755 }
1756
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001757 // Any pointer can be cast to an Objective-C pointer type with a C-style
1758 // cast.
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001759 if (CStyle && DestType->isObjCObjectPointerType()) {
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001760 return TC_Success;
1761 }
Fariborz Jahanian91dd9df2012-08-16 18:33:47 +00001762 if (CStyle)
1763 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
1764
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001765 // Not casting away constness, so the only remaining check is for compatible
1766 // pointer categories.
1767
1768 if (SrcType->isFunctionPointerType()) {
1769 if (DestType->isFunctionPointerType()) {
1770 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1771 // a pointer to a function of a different type.
1772 return TC_Success;
1773 }
1774
1775 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1776 // an object type or vice versa is conditionally-supported.
1777 // Compilers support it in C++03 too, though, because it's necessary for
1778 // casting the return value of dlsym() and GetProcAddress().
1779 // FIXME: Conditionally-supported behavior should be configurable in the
1780 // TargetInfo or similar.
Richard Smithebaf0e62011-10-18 20:49:44 +00001781 Self.Diag(OpRange.getBegin(),
Richard Smith80ad52f2013-01-02 11:42:31 +00001782 Self.getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00001783 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
1784 << OpRange;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001785 return TC_Success;
1786 }
1787
1788 if (DestType->isFunctionPointerType()) {
1789 // See above.
Richard Smithebaf0e62011-10-18 20:49:44 +00001790 Self.Diag(OpRange.getBegin(),
Richard Smith80ad52f2013-01-02 11:42:31 +00001791 Self.getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00001792 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
1793 << OpRange;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001794 return TC_Success;
1795 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001796
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001797 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1798 // a pointer to an object of different type.
1799 // Void pointers are not specified, but supported by every compiler out there.
1800 // So we finish by allowing everything that remains - it's got to be two
1801 // object pointers.
1802 return TC_Success;
John McCall79ab2c82011-02-14 18:34:10 +00001803}
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001804
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001805void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
1806 bool ListInitialization) {
John McCalla180f042011-10-06 23:25:11 +00001807 // Handle placeholders.
1808 if (isPlaceholder()) {
1809 // C-style casts can resolve __unknown_any types.
1810 if (claimPlaceholder(BuiltinType::UnknownAny)) {
1811 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
1812 SrcExpr.get(), Kind,
1813 ValueKind, BasePath);
1814 return;
1815 }
John McCallb45ae252011-10-05 07:41:44 +00001816
John McCalla180f042011-10-06 23:25:11 +00001817 checkNonOverloadPlaceholders();
1818 if (SrcExpr.isInvalid())
1819 return;
John McCall4919dfd2011-10-17 17:42:19 +00001820 }
John McCalla180f042011-10-06 23:25:11 +00001821
1822 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001823 // This test is outside everything else because it's the only case where
1824 // a non-lvalue-reference target type does not lead to decay.
John McCallb45ae252011-10-05 07:41:44 +00001825 if (DestType->isVoidType()) {
John McCallfb8721c2011-04-10 19:13:55 +00001826 Kind = CK_ToVoid;
1827
John McCalla180f042011-10-06 23:25:11 +00001828 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall6dbba4f2011-10-11 23:14:30 +00001829 Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1830 SrcExpr, /* Decay Function to ptr */ false,
John McCallb45ae252011-10-05 07:41:44 +00001831 /* Complain */ true, DestRange, DestType,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00001832 diag::err_bad_cstyle_cast_overload);
John McCallb45ae252011-10-05 07:41:44 +00001833 if (SrcExpr.isInvalid())
1834 return;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001835 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001836
John McCalla180f042011-10-06 23:25:11 +00001837 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
1838 if (SrcExpr.isInvalid())
John McCallb45ae252011-10-05 07:41:44 +00001839 return;
John McCallb45ae252011-10-05 07:41:44 +00001840
1841 return;
Anton Yartsevd06fea82011-03-27 09:32:40 +00001842 }
1843
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001844 // If the type is dependent, we won't do any other semantic analysis now.
John McCallb45ae252011-10-05 07:41:44 +00001845 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent()) {
1846 assert(Kind == CK_Dependent);
1847 return;
John McCalldaa8e4e2010-11-15 09:13:47 +00001848 }
Benjamin Kramer5b4a40a2011-07-08 20:20:17 +00001849
John McCall6dbba4f2011-10-11 23:14:30 +00001850 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
1851 !isPlaceholder(BuiltinType::Overload)) {
John McCallb45ae252011-10-05 07:41:44 +00001852 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
1853 if (SrcExpr.isInvalid())
1854 return;
John Wiegley429bb272011-04-08 18:41:53 +00001855 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001856
John McCallfb8721c2011-04-10 19:13:55 +00001857 // AltiVec vector initialization with a single literal.
John McCallb45ae252011-10-05 07:41:44 +00001858 if (const VectorType *vecTy = DestType->getAs<VectorType>())
John McCallfb8721c2011-04-10 19:13:55 +00001859 if (vecTy->getVectorKind() == VectorType::AltiVecVector
John McCallb45ae252011-10-05 07:41:44 +00001860 && (SrcExpr.get()->getType()->isIntegerType()
1861 || SrcExpr.get()->getType()->isFloatingType())) {
John McCallfb8721c2011-04-10 19:13:55 +00001862 Kind = CK_VectorSplat;
John McCallb45ae252011-10-05 07:41:44 +00001863 return;
John McCallfb8721c2011-04-10 19:13:55 +00001864 }
1865
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001866 // C++ [expr.cast]p5: The conversions performed by
1867 // - a const_cast,
1868 // - a static_cast,
1869 // - a static_cast followed by a const_cast,
1870 // - a reinterpret_cast, or
1871 // - a reinterpret_cast followed by a const_cast,
1872 // can be performed using the cast notation of explicit type conversion.
1873 // [...] If a conversion can be interpreted in more than one of the ways
1874 // listed above, the interpretation that appears first in the list is used,
1875 // even if a cast resulting from that interpretation is ill-formed.
1876 // In plain language, this means trying a const_cast ...
1877 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCallb45ae252011-10-05 07:41:44 +00001878 TryCastResult tcr = TryConstCast(Self, SrcExpr.get(), DestType,
1879 /*CStyle*/true, msg);
Anders Carlssonda921fd2009-10-19 18:14:28 +00001880 if (tcr == TC_Success)
John McCall2de56d12010-08-25 11:45:40 +00001881 Kind = CK_NoOp;
Anders Carlssonda921fd2009-10-19 18:14:28 +00001882
John McCallf85e1932011-06-15 23:02:42 +00001883 Sema::CheckedConversionKind CCK
1884 = FunctionalStyle? Sema::CCK_FunctionalCast
1885 : Sema::CCK_CStyleCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001886 if (tcr == TC_NotApplicable) {
1887 // ... or if that is not possible, a static_cast, ignoring const, ...
John McCallb45ae252011-10-05 07:41:44 +00001888 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001889 msg, Kind, BasePath, ListInitialization);
John McCallb45ae252011-10-05 07:41:44 +00001890 if (SrcExpr.isInvalid())
1891 return;
1892
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001893 if (tcr == TC_NotApplicable) {
1894 // ... and finally a reinterpret_cast, ignoring const.
John McCallb45ae252011-10-05 07:41:44 +00001895 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
1896 OpRange, msg, Kind);
1897 if (SrcExpr.isInvalid())
1898 return;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001899 }
1900 }
1901
David Blaikie4e4d0842012-03-11 07:00:24 +00001902 if (Self.getLangOpts().ObjCAutoRefCount && tcr == TC_Success)
John McCallb45ae252011-10-05 07:41:44 +00001903 checkObjCARCConversion(CCK);
John McCallf85e1932011-06-15 23:02:42 +00001904
Nick Lewycky43328e92010-11-09 00:19:31 +00001905 if (tcr != TC_Success && msg != 0) {
John McCallb45ae252011-10-05 07:41:44 +00001906 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor8e960432010-11-08 03:40:48 +00001907 DeclAccessPair Found;
John McCallb45ae252011-10-05 07:41:44 +00001908 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
1909 DestType,
1910 /*Complain*/ true,
Douglas Gregor8e960432010-11-08 03:40:48 +00001911 Found);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001912
Richard Trieu32ac00d2011-04-16 01:09:30 +00001913 assert(!Fn && "cast failed but able to resolve overload expression!!");
Nick Lewycky43328e92010-11-09 00:19:31 +00001914 (void)Fn;
John McCall79ab2c82011-02-14 18:34:10 +00001915
Nick Lewycky43328e92010-11-09 00:19:31 +00001916 } else {
John McCallb45ae252011-10-05 07:41:44 +00001917 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
Sebastian Redl20ff0e22012-02-13 19:55:43 +00001918 OpRange, SrcExpr.get(), DestType, ListInitialization);
Douglas Gregor8e960432010-11-08 03:40:48 +00001919 }
John McCallb45ae252011-10-05 07:41:44 +00001920 } else if (Kind == CK_BitCast) {
1921 checkCastAlign();
Douglas Gregor8e960432010-11-08 03:40:48 +00001922 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001923
John McCallb45ae252011-10-05 07:41:44 +00001924 // Clear out SrcExpr if there was a fatal error.
John Wiegley429bb272011-04-08 18:41:53 +00001925 if (tcr != TC_Success)
John McCallb45ae252011-10-05 07:41:44 +00001926 SrcExpr = ExprError();
1927}
1928
Fariborz Jahanianbbb8afd2012-08-17 17:22:34 +00001929/// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
1930/// non-matching type. Such as enum function call to int, int call to
1931/// pointer; etc. Cast to 'void' is an exception.
1932static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
1933 QualType DestType) {
1934 if (Self.Diags.getDiagnosticLevel(diag::warn_bad_function_cast,
1935 SrcExpr.get()->getExprLoc())
1936 == DiagnosticsEngine::Ignored)
1937 return;
1938
1939 if (!isa<CallExpr>(SrcExpr.get()))
1940 return;
1941
1942 QualType SrcType = SrcExpr.get()->getType();
1943 if (DestType.getUnqualifiedType()->isVoidType())
1944 return;
1945 if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
1946 && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
1947 return;
1948 if (SrcType->isIntegerType() && DestType->isIntegerType() &&
1949 (SrcType->isBooleanType() == DestType->isBooleanType()) &&
1950 (SrcType->isEnumeralType() == DestType->isEnumeralType()))
1951 return;
1952 if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
1953 return;
1954 if (SrcType->isEnumeralType() && DestType->isEnumeralType())
1955 return;
1956 if (SrcType->isComplexType() && DestType->isComplexType())
1957 return;
1958 if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
1959 return;
1960
1961 Self.Diag(SrcExpr.get()->getExprLoc(),
1962 diag::warn_bad_function_cast)
1963 << SrcType << DestType << SrcExpr.get()->getSourceRange();
1964}
1965
John McCalla180f042011-10-06 23:25:11 +00001966/// Check the semantics of a C-style cast operation, in C.
1967void CastOperation::CheckCStyleCast() {
David Blaikie4e4d0842012-03-11 07:00:24 +00001968 assert(!Self.getLangOpts().CPlusPlus);
John McCalla180f042011-10-06 23:25:11 +00001969
John McCall5acb0c92011-10-17 18:40:02 +00001970 // C-style casts can resolve __unknown_any types.
1971 if (claimPlaceholder(BuiltinType::UnknownAny)) {
1972 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
1973 SrcExpr.get(), Kind,
1974 ValueKind, BasePath);
1975 return;
1976 }
John McCalla180f042011-10-06 23:25:11 +00001977
1978 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1979 // type needs to be scalar.
1980 if (DestType->isVoidType()) {
1981 // We don't necessarily do lvalue-to-rvalue conversions on this.
1982 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
1983 if (SrcExpr.isInvalid())
1984 return;
1985
1986 // Cast to void allows any expr type.
1987 Kind = CK_ToVoid;
1988 return;
1989 }
1990
1991 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
1992 if (SrcExpr.isInvalid())
1993 return;
1994 QualType SrcType = SrcExpr.get()->getType();
David Chisnall7a7ee302012-01-16 17:27:18 +00001995
John McCall5acb0c92011-10-17 18:40:02 +00001996 assert(!SrcType->isPlaceholderType());
John McCalla180f042011-10-06 23:25:11 +00001997
1998 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1999 diag::err_typecheck_cast_to_incomplete)) {
2000 SrcExpr = ExprError();
2001 return;
2002 }
2003
2004 if (!DestType->isScalarType() && !DestType->isVectorType()) {
2005 const RecordType *DestRecordTy = DestType->getAs<RecordType>();
2006
2007 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
2008 // GCC struct/union extension: allow cast to self.
2009 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
2010 << DestType << SrcExpr.get()->getSourceRange();
2011 Kind = CK_NoOp;
2012 return;
2013 }
2014
2015 // GCC's cast to union extension.
2016 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
2017 RecordDecl *RD = DestRecordTy->getDecl();
2018 RecordDecl::field_iterator Field, FieldEnd;
2019 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2020 Field != FieldEnd; ++Field) {
2021 if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) &&
2022 !Field->isUnnamedBitfield()) {
2023 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
2024 << SrcExpr.get()->getSourceRange();
2025 break;
2026 }
2027 }
2028 if (Field == FieldEnd) {
2029 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2030 << SrcType << SrcExpr.get()->getSourceRange();
2031 SrcExpr = ExprError();
2032 return;
2033 }
2034 Kind = CK_ToUnion;
2035 return;
2036 }
2037
2038 // Reject any other conversions to non-scalar types.
2039 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
2040 << DestType << SrcExpr.get()->getSourceRange();
2041 SrcExpr = ExprError();
2042 return;
2043 }
2044
2045 // The type we're casting to is known to be a scalar or vector.
2046
2047 // Require the operand to be a scalar or vector.
2048 if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
2049 Self.Diag(SrcExpr.get()->getExprLoc(),
2050 diag::err_typecheck_expect_scalar_operand)
2051 << SrcType << SrcExpr.get()->getSourceRange();
2052 SrcExpr = ExprError();
2053 return;
2054 }
2055
2056 if (DestType->isExtVectorType()) {
2057 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.take(), Kind);
2058 return;
2059 }
2060
2061 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
2062 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
2063 (SrcType->isIntegerType() || SrcType->isFloatingType())) {
2064 Kind = CK_VectorSplat;
2065 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
2066 SrcExpr = ExprError();
2067 }
2068 return;
2069 }
2070
2071 if (SrcType->isVectorType()) {
2072 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
2073 SrcExpr = ExprError();
2074 return;
2075 }
2076
2077 // The source and target types are both scalars, i.e.
2078 // - arithmetic types (fundamental, enum, and complex)
2079 // - all kinds of pointers
2080 // Note that member pointers were filtered out with C++, above.
2081
2082 if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
2083 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
2084 SrcExpr = ExprError();
2085 return;
2086 }
2087
2088 // If either type is a pointer, the other type has to be either an
2089 // integer or a pointer.
2090 if (!DestType->isArithmeticType()) {
2091 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
2092 Self.Diag(SrcExpr.get()->getExprLoc(),
2093 diag::err_cast_pointer_from_non_pointer_int)
2094 << SrcType << SrcExpr.get()->getSourceRange();
2095 SrcExpr = ExprError();
2096 return;
2097 }
David Blaikie9b29f4f2012-10-16 18:53:14 +00002098 checkIntToPointerCast(/* CStyle */ true, OpRange.getBegin(), SrcExpr.get(),
2099 DestType, Self);
John McCalla180f042011-10-06 23:25:11 +00002100 } else if (!SrcType->isArithmeticType()) {
2101 if (!DestType->isIntegralType(Self.Context) &&
2102 DestType->isArithmeticType()) {
2103 Self.Diag(SrcExpr.get()->getLocStart(),
2104 diag::err_cast_pointer_to_non_pointer_int)
Abramo Bagnaraf7ce1942011-11-15 11:25:38 +00002105 << DestType << SrcExpr.get()->getSourceRange();
John McCalla180f042011-10-06 23:25:11 +00002106 SrcExpr = ExprError();
2107 return;
2108 }
2109 }
2110
Joey Gouly19dbb202013-01-23 11:56:20 +00002111 if (Self.getLangOpts().OpenCL && !Self.getOpenCLOptions().cl_khr_fp16) {
2112 if (DestType->isHalfType()) {
2113 Self.Diag(SrcExpr.get()->getLocStart(), diag::err_opencl_cast_to_half)
2114 << DestType << SrcExpr.get()->getSourceRange();
2115 SrcExpr = ExprError();
2116 return;
2117 }
Joey Gouly19dbb202013-01-23 11:56:20 +00002118 }
2119
John McCalla180f042011-10-06 23:25:11 +00002120 // ARC imposes extra restrictions on casts.
David Blaikie4e4d0842012-03-11 07:00:24 +00002121 if (Self.getLangOpts().ObjCAutoRefCount) {
John McCalla180f042011-10-06 23:25:11 +00002122 checkObjCARCConversion(Sema::CCK_CStyleCast);
2123 if (SrcExpr.isInvalid())
2124 return;
2125
2126 if (const PointerType *CastPtr = DestType->getAs<PointerType>()) {
2127 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
2128 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
2129 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
2130 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
2131 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
2132 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
2133 Self.Diag(SrcExpr.get()->getLocStart(),
2134 diag::err_typecheck_incompatible_ownership)
2135 << SrcType << DestType << Sema::AA_Casting
2136 << SrcExpr.get()->getSourceRange();
2137 return;
2138 }
2139 }
2140 }
2141 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
2142 Self.Diag(SrcExpr.get()->getLocStart(),
2143 diag::err_arc_convesion_of_weak_unavailable)
2144 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2145 SrcExpr = ExprError();
2146 return;
2147 }
2148 }
Fariborz Jahanian91dd9df2012-08-16 18:33:47 +00002149 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
Fariborz Jahanianbbb8afd2012-08-17 17:22:34 +00002150 DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
John McCalla180f042011-10-06 23:25:11 +00002151 Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2152 if (SrcExpr.isInvalid())
2153 return;
2154
2155 if (Kind == CK_BitCast)
2156 checkCastAlign();
2157}
2158
2159ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
2160 TypeSourceInfo *CastTypeInfo,
2161 SourceLocation RPLoc,
2162 Expr *CastExpr) {
John McCallb45ae252011-10-05 07:41:44 +00002163 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2164 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2165 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
2166
David Blaikie4e4d0842012-03-11 07:00:24 +00002167 if (getLangOpts().CPlusPlus) {
Sebastian Redl6dc00f62012-02-12 18:41:05 +00002168 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false,
2169 isa<InitListExpr>(CastExpr));
John McCalla180f042011-10-06 23:25:11 +00002170 } else {
2171 Op.CheckCStyleCast();
2172 }
2173
John McCallb45ae252011-10-05 07:41:44 +00002174 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00002175 return ExprError();
2176
John McCall5acb0c92011-10-17 18:40:02 +00002177 return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
2178 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
2179 &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
John McCallb45ae252011-10-05 07:41:44 +00002180}
2181
2182ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
2183 SourceLocation LPLoc,
2184 Expr *CastExpr,
2185 SourceLocation RPLoc) {
Sebastian Redl20ff0e22012-02-13 19:55:43 +00002186 assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
John McCallb45ae252011-10-05 07:41:44 +00002187 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2188 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2189 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
2190
Sebastian Redl20ff0e22012-02-13 19:55:43 +00002191 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/true, /*ListInit=*/false);
John McCallb45ae252011-10-05 07:41:44 +00002192 if (Op.SrcExpr.isInvalid())
2193 return ExprError();
Daniel Jaspera770a4d2012-07-16 08:05:07 +00002194
2195 if (CXXConstructExpr *ConstructExpr = dyn_cast<CXXConstructExpr>(Op.SrcExpr.get()))
2196 ConstructExpr->setParenRange(SourceRange(LPLoc, RPLoc));
John McCallb45ae252011-10-05 07:41:44 +00002197
John McCall5acb0c92011-10-17 18:40:02 +00002198 return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
2199 Op.ValueKind, CastTypeInfo, Op.DestRange.getBegin(),
2200 Op.Kind, Op.SrcExpr.take(), &Op.BasePath, RPLoc));
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002201}