blob: 586d3cbae66be0341b91d8d0d7ddf0a25f9f04c7 [file] [log] [blame]
John McCalld8d3ced2011-10-11 17:38:55 +00001//===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===//
Sebastian Redl26d85b12008-11-05 21:50:06 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
John McCalld8d3ced2011-10-11 17:38:55 +000010// This file implements semantic analysis for cast expressions, including
11// 1) C-style casts like '(int) x'
12// 2) C++ functional casts like 'int(x)'
13// 3) C++ named casts like 'static_cast<int>(x)'
Sebastian Redl26d85b12008-11-05 21:50:06 +000014//
15//===----------------------------------------------------------------------===//
16
John McCall2d887082010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000018#include "clang/Sema/Initialization.h"
Sebastian Redl26d85b12008-11-05 21:50:06 +000019#include "clang/AST/ExprCXX.h"
John McCalla180f042011-10-06 23:25:11 +000020#include "clang/AST/ExprObjC.h"
Sebastian Redl26d85b12008-11-05 21:50:06 +000021#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redl26d85b12008-11-05 21:50:06 +000024#include "llvm/ADT/SmallVector.h"
Sebastian Redle3dc28a2008-11-07 23:29:29 +000025#include <set>
Sebastian Redl26d85b12008-11-05 21:50:06 +000026using namespace clang;
27
Douglas Gregor8e960432010-11-08 03:40:48 +000028
Douglas Gregor8e960432010-11-08 03:40:48 +000029
Sebastian Redl9cc11e72009-07-25 15:41:38 +000030enum TryCastResult {
31 TC_NotApplicable, ///< The cast method is not applicable.
32 TC_Success, ///< The cast method is appropriate and successful.
33 TC_Failed ///< The cast method is appropriate, but failed. A
34 ///< diagnostic has been emitted.
35};
36
37enum CastType {
38 CT_Const, ///< const_cast
39 CT_Static, ///< static_cast
40 CT_Reinterpret, ///< reinterpret_cast
41 CT_Dynamic, ///< dynamic_cast
42 CT_CStyle, ///< (Type)expr
43 CT_Functional ///< Type(expr)
Sebastian Redl37d6de32008-11-08 13:00:26 +000044};
45
John McCallb45ae252011-10-05 07:41:44 +000046namespace {
47 struct CastOperation {
48 CastOperation(Sema &S, QualType destType, ExprResult src)
49 : Self(S), SrcExpr(src), DestType(destType),
50 ResultType(destType.getNonLValueExprType(S.Context)),
51 ValueKind(Expr::getValueKindForType(destType)),
John McCall5acb0c92011-10-17 18:40:02 +000052 Kind(CK_Dependent), IsARCUnbridgedCast(false) {
John McCalla180f042011-10-06 23:25:11 +000053
54 if (const BuiltinType *placeholder =
55 src.get()->getType()->getAsPlaceholderType()) {
56 PlaceholderKind = placeholder->getKind();
57 } else {
58 PlaceholderKind = (BuiltinType::Kind) 0;
59 }
60 }
Douglas Gregor8e960432010-11-08 03:40:48 +000061
John McCallb45ae252011-10-05 07:41:44 +000062 Sema &Self;
63 ExprResult SrcExpr;
64 QualType DestType;
65 QualType ResultType;
66 ExprValueKind ValueKind;
67 CastKind Kind;
John McCalla180f042011-10-06 23:25:11 +000068 BuiltinType::Kind PlaceholderKind;
John McCallb45ae252011-10-05 07:41:44 +000069 CXXCastPath BasePath;
John McCall5acb0c92011-10-17 18:40:02 +000070 bool IsARCUnbridgedCast;
Douglas Gregor8e960432010-11-08 03:40:48 +000071
John McCallb45ae252011-10-05 07:41:44 +000072 SourceRange OpRange;
73 SourceRange DestRange;
Douglas Gregor8e960432010-11-08 03:40:48 +000074
John McCalla180f042011-10-06 23:25:11 +000075 // Top-level semantics-checking routines.
John McCallb45ae252011-10-05 07:41:44 +000076 void CheckConstCast();
77 void CheckReinterpretCast();
Nicola Gigante56f5d362011-11-28 12:21:57 +000078 void CheckStaticCast(bool &CastNodesCreated);
John McCallb45ae252011-10-05 07:41:44 +000079 void CheckDynamicCast();
Nicola Gigante56f5d362011-11-28 12:21:57 +000080 void CheckCXXCStyleCast(bool FunctionalCast, bool &CastNodesCreated);
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) {
John McCall5acb0c92011-10-17 18:40:02 +0000121 assert(Self.getLangOptions().ObjCAutoRefCount);
122
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,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000193 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000194 CastKind &Kind);
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,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000199 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000200 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000201 CXXCastPath &BasePath);
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
225 if (getLangOptions().CPlusPlus) {
226 // Check that there are no default arguments (C++ only).
227 CheckExtraCXXDefaultArguments(D);
228 }
229
230 return BuildCXXNamedCast(OpLoc, Kind, TInfo, move(E),
John McCallc89724c2010-01-15 19:13:16 +0000231 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
232 SourceRange(LParenLoc, RParenLoc));
233}
234
John McCall60d7b3a2010-08-24 06:29:42 +0000235ExprResult
John McCallc89724c2010-01-15 19:13:16 +0000236Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John Wiegley429bb272011-04-08 18:41:53 +0000237 TypeSourceInfo *DestTInfo, Expr *E,
John McCallc89724c2010-01-15 19:13:16 +0000238 SourceRange AngleBrackets, SourceRange Parens) {
John Wiegley429bb272011-04-08 18:41:53 +0000239 ExprResult Ex = Owned(E);
John McCallc89724c2010-01-15 19:13:16 +0000240 QualType DestType = DestTInfo->getType();
241
Douglas Gregor9103bb22008-12-17 22:52:20 +0000242 // If the type is dependent, we won't do the semantic analysis now.
243 // FIXME: should we check this in a more fine-grained manner?
John Wiegley429bb272011-04-08 18:41:53 +0000244 bool TypeDependent = DestType->isDependentType() || Ex.get()->isTypeDependent();
Douglas Gregor9103bb22008-12-17 22:52:20 +0000245
John McCallb45ae252011-10-05 07:41:44 +0000246 CastOperation Op(*this, DestType, E);
247 Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
248 Op.DestRange = AngleBrackets;
John McCalla21e06c2010-11-26 10:57:22 +0000249
Sebastian Redl26d85b12008-11-05 21:50:06 +0000250 switch (Kind) {
John McCalldaa8e4e2010-11-15 09:13:47 +0000251 default: llvm_unreachable("Unknown C++ cast!");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000252
253 case tok::kw_const_cast:
John Wiegley429bb272011-04-08 18:41:53 +0000254 if (!TypeDependent) {
John McCallb45ae252011-10-05 07:41:44 +0000255 Op.CheckConstCast();
256 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000257 return ExprError();
258 }
John McCall5acb0c92011-10-17 18:40:02 +0000259 return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
260 Op.ValueKind, Op.SrcExpr.take(), DestTInfo,
261 OpLoc, Parens.getEnd()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000262
Anders Carlsson714179b2009-08-02 19:07:59 +0000263 case tok::kw_dynamic_cast: {
John Wiegley429bb272011-04-08 18:41:53 +0000264 if (!TypeDependent) {
John McCallb45ae252011-10-05 07:41:44 +0000265 Op.CheckDynamicCast();
266 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000267 return ExprError();
268 }
John McCall5acb0c92011-10-17 18:40:02 +0000269 return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
270 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
271 &Op.BasePath, DestTInfo,
272 OpLoc, Parens.getEnd()));
Anders Carlsson714179b2009-08-02 19:07:59 +0000273 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000274 case tok::kw_reinterpret_cast: {
John Wiegley429bb272011-04-08 18:41:53 +0000275 if (!TypeDependent) {
John McCallb45ae252011-10-05 07:41:44 +0000276 Op.CheckReinterpretCast();
277 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000278 return ExprError();
279 }
John McCall5acb0c92011-10-17 18:40:02 +0000280 return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
281 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
282 0, DestTInfo, OpLoc,
283 Parens.getEnd()));
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000284 }
Anders Carlssoncdb61972009-08-07 22:21:05 +0000285 case tok::kw_static_cast: {
Nicola Gigante56f5d362011-11-28 12:21:57 +0000286 bool CastNodesCreated = false;
John Wiegley429bb272011-04-08 18:41:53 +0000287 if (!TypeDependent) {
Nicola Gigante56f5d362011-11-28 12:21:57 +0000288 Op.CheckStaticCast(CastNodesCreated);
John McCallb45ae252011-10-05 07:41:44 +0000289 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000290 return ExprError();
291 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000292
Nicola Gigante56f5d362011-11-28 12:21:57 +0000293 // CheckStaticCast _may_ have already created the cast node. Let's check
294 if (CastNodesCreated) {
295 if (CXXStaticCastExpr *Cast =
296 dyn_cast<CXXStaticCastExpr>(Op.SrcExpr.get())) {
297 assert(!Cast->getTypeInfoAsWritten() &&
298 "The explicit cast node created by CheckStaticCast "
299 "has source type infos!");
300
301 Cast->setTypeInfoAsWritten(DestTInfo);
302 Cast->setOperatorLoc(OpLoc);
303 Cast->setRParenLoc(Parens.getEnd());
304
305 return Op.complete(Cast);
306 }
307 }
John McCall5acb0c92011-10-17 18:40:02 +0000308 return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
309 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
310 &Op.BasePath, DestTInfo,
311 OpLoc, Parens.getEnd()));
Anders Carlssoncdb61972009-08-07 22:21:05 +0000312 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000313 }
314
Sebastian Redlf53597f2009-03-15 17:47:39 +0000315 return ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000316}
317
John McCall79ab2c82011-02-14 18:34:10 +0000318/// Try to diagnose a failed overloaded cast. Returns true if
319/// diagnostics were emitted.
320static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
321 SourceRange range, Expr *src,
322 QualType destType) {
323 switch (CT) {
324 // These cast kinds don't consider user-defined conversions.
325 case CT_Const:
326 case CT_Reinterpret:
327 case CT_Dynamic:
328 return false;
329
330 // These do.
331 case CT_Static:
332 case CT_CStyle:
333 case CT_Functional:
334 break;
335 }
336
337 QualType srcType = src->getType();
338 if (!destType->isRecordType() && !srcType->isRecordType())
339 return false;
340
341 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
342 InitializationKind initKind
John McCallf85e1932011-06-15 23:02:42 +0000343 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
344 range)
345 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range)
Nicola Gigante56f5d362011-11-28 12:21:57 +0000346 : InitializationKind::CreateStaticCast(/*type range?*/ range);
John McCall79ab2c82011-02-14 18:34:10 +0000347 InitializationSequence sequence(S, entity, initKind, &src, 1);
348
Sebastian Redl383616c2011-06-05 12:23:28 +0000349 assert(sequence.Failed() && "initialization succeeded on second try?");
John McCall79ab2c82011-02-14 18:34:10 +0000350 switch (sequence.getFailureKind()) {
351 default: return false;
352
353 case InitializationSequence::FK_ConstructorOverloadFailed:
354 case InitializationSequence::FK_UserConversionOverloadFailed:
355 break;
356 }
357
358 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
359
360 unsigned msg = 0;
361 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
362
363 switch (sequence.getFailedOverloadResult()) {
364 case OR_Success: llvm_unreachable("successful failed overload");
365 return false;
366 case OR_No_Viable_Function:
367 if (candidates.empty())
368 msg = diag::err_ovl_no_conversion_in_cast;
369 else
370 msg = diag::err_ovl_no_viable_conversion_in_cast;
371 howManyCandidates = OCD_AllCandidates;
372 break;
373
374 case OR_Ambiguous:
375 msg = diag::err_ovl_ambiguous_conversion_in_cast;
376 howManyCandidates = OCD_ViableCandidates;
377 break;
378
379 case OR_Deleted:
380 msg = diag::err_ovl_deleted_conversion_in_cast;
381 howManyCandidates = OCD_ViableCandidates;
382 break;
383 }
384
385 S.Diag(range.getBegin(), msg)
386 << CT << srcType << destType
387 << range << src->getSourceRange();
388
389 candidates.NoteCandidates(S, howManyCandidates, &src, 1);
390
391 return true;
392}
393
394/// Diagnose a failed cast.
395static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
396 SourceRange opRange, Expr *src, QualType destType) {
John McCall864c0412011-04-26 20:42:42 +0000397 if (src->getType() == S.Context.BoundMemberTy) {
398 (void) S.CheckPlaceholderExpr(src); // will always fail
399 return;
400 }
401
John McCall79ab2c82011-02-14 18:34:10 +0000402 if (msg == diag::err_bad_cxx_cast_generic &&
403 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType))
404 return;
405
406 S.Diag(opRange.getBegin(), msg) << castType
407 << src->getType() << destType << opRange << src->getSourceRange();
408}
409
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000410/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
411/// this removes one level of indirection from both types, provided that they're
412/// the same kind of pointer (plain or to-member). Unlike the Sema function,
413/// this one doesn't care if the two pointers-to-member don't point into the
414/// same class. This is because CastsAwayConstness doesn't care.
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000415static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000416 const PointerType *T1PtrType = T1->getAs<PointerType>(),
417 *T2PtrType = T2->getAs<PointerType>();
418 if (T1PtrType && T2PtrType) {
419 T1 = T1PtrType->getPointeeType();
420 T2 = T2PtrType->getPointeeType();
421 return true;
422 }
Fariborz Jahanian72a86592010-02-03 20:32:31 +0000423 const ObjCObjectPointerType *T1ObjCPtrType =
424 T1->getAs<ObjCObjectPointerType>(),
425 *T2ObjCPtrType =
426 T2->getAs<ObjCObjectPointerType>();
427 if (T1ObjCPtrType) {
428 if (T2ObjCPtrType) {
429 T1 = T1ObjCPtrType->getPointeeType();
430 T2 = T2ObjCPtrType->getPointeeType();
431 return true;
432 }
433 else if (T2PtrType) {
434 T1 = T1ObjCPtrType->getPointeeType();
435 T2 = T2PtrType->getPointeeType();
436 return true;
437 }
438 }
439 else if (T2ObjCPtrType) {
440 if (T1PtrType) {
441 T2 = T2ObjCPtrType->getPointeeType();
442 T1 = T1PtrType->getPointeeType();
443 return true;
444 }
445 }
446
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000447 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
448 *T2MPType = T2->getAs<MemberPointerType>();
449 if (T1MPType && T2MPType) {
450 T1 = T1MPType->getPointeeType();
451 T2 = T2MPType->getPointeeType();
452 return true;
453 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000454
455 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
456 *T2BPType = T2->getAs<BlockPointerType>();
457 if (T1BPType && T2BPType) {
458 T1 = T1BPType->getPointeeType();
459 T2 = T2BPType->getPointeeType();
460 return true;
461 }
462
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000463 return false;
464}
465
Sebastian Redldb647282009-01-27 23:18:31 +0000466/// CastsAwayConstness - Check if the pointer conversion from SrcType to
467/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
468/// the cast checkers. Both arguments must denote pointer (possibly to member)
469/// types.
John McCallf85e1932011-06-15 23:02:42 +0000470///
471/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
472///
473/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000474static bool
John McCallf85e1932011-06-15 23:02:42 +0000475CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
476 bool CheckCVR, bool CheckObjCLifetime) {
477 // If the only checking we care about is for Objective-C lifetime qualifiers,
478 // and we're not in ARC mode, there's nothing to check.
479 if (!CheckCVR && CheckObjCLifetime &&
480 !Self.Context.getLangOptions().ObjCAutoRefCount)
481 return false;
482
Sebastian Redldb647282009-01-27 23:18:31 +0000483 // Casting away constness is defined in C++ 5.2.11p8 with reference to
484 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
485 // the rules are non-trivial. So first we construct Tcv *...cv* as described
486 // in C++ 5.2.11p8.
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000487 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
488 SrcType->isBlockPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000489 "Source type is not pointer or pointer to member.");
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000490 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
491 DestType->isBlockPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000492 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000493
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000494 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
495 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000496 SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000497
Douglas Gregord4c5f842011-04-15 17:59:54 +0000498 // Find the qualifiers. We only care about cvr-qualifiers for the
499 // purpose of this check, because other qualifiers (address spaces,
500 // Objective-C GC, etc.) are part of the type's identity.
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000501 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCallf85e1932011-06-15 23:02:42 +0000502 // Determine the relevant qualifiers at this level.
503 Qualifiers SrcQuals, DestQuals;
Anders Carlsson52647c62010-06-04 22:47:55 +0000504 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
Anders Carlsson52647c62010-06-04 22:47:55 +0000505 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
John McCallf85e1932011-06-15 23:02:42 +0000506
507 Qualifiers RetainedSrcQuals, RetainedDestQuals;
508 if (CheckCVR) {
509 RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
510 RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
511 }
512
513 if (CheckObjCLifetime &&
514 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
515 return true;
516
517 cv1.push_back(RetainedSrcQuals);
518 cv2.push_back(RetainedDestQuals);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000519 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000520 if (cv1.empty())
521 return false;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000522
523 // Construct void pointers with those qualifiers (in reverse order of
524 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000525 QualType SrcConstruct = Self.Context.VoidTy;
526 QualType DestConstruct = Self.Context.VoidTy;
John McCall0953e762009-09-24 19:53:00 +0000527 ASTContext &Context = Self.Context;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000528 for (SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
John McCall0953e762009-09-24 19:53:00 +0000529 i2 = cv2.rbegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000530 i1 != cv1.rend(); ++i1, ++i2) {
John McCall0953e762009-09-24 19:53:00 +0000531 SrcConstruct
532 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
533 DestConstruct
534 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000535 }
536
537 // Test if they're compatible.
John McCallf85e1932011-06-15 23:02:42 +0000538 bool ObjCLifetimeConversion;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000539 return SrcConstruct != DestConstruct &&
John McCallf85e1932011-06-15 23:02:42 +0000540 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
541 ObjCLifetimeConversion);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000542}
543
Sebastian Redl26d85b12008-11-05 21:50:06 +0000544/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
545/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
546/// checked downcasts in class hierarchies.
John McCallb45ae252011-10-05 07:41:44 +0000547void CastOperation::CheckDynamicCast() {
Eli Friedman7a420df2011-10-31 20:59:03 +0000548 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload)) {
549 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
550 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
551 return;
552 }
553
John McCallb45ae252011-10-05 07:41:44 +0000554 QualType OrigSrcType = SrcExpr.get()->getType();
555 QualType DestType = Self.Context.getCanonicalType(this->DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000556
557 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
558 // or "pointer to cv void".
559
560 QualType DestPointee;
Ted Kremenek6217b802009-07-29 21:53:49 +0000561 const PointerType *DestPointer = DestType->getAs<PointerType>();
John McCallf89e55a2010-11-18 06:31:45 +0000562 const ReferenceType *DestReference = 0;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000563 if (DestPointer) {
564 DestPointee = DestPointer->getPointeeType();
John McCallf89e55a2010-11-18 06:31:45 +0000565 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000566 DestPointee = DestReference->getPointeeType();
567 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000568 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
John McCallb45ae252011-10-05 07:41:44 +0000569 << this->DestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000570 return;
571 }
572
Ted Kremenek6217b802009-07-29 21:53:49 +0000573 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000574 if (DestPointee->isVoidType()) {
575 assert(DestPointer && "Reference to void is not possible");
576 } else if (DestRecord) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000577 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000578 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssonb7906612009-08-26 23:45:07 +0000579 << DestRange))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000580 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000581 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000582 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000583 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000584 return;
585 }
586
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000587 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
588 // complete class type, [...]. If T is an lvalue reference type, v shall be
Douglas Gregordc843f22011-01-22 00:06:57 +0000589 // an lvalue of a complete class type, [...]. If T is an rvalue reference
590 // type, v shall be an expression having a complete class type, [...]
Sebastian Redl37d6de32008-11-08 13:00:26 +0000591 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000592 QualType SrcPointee;
593 if (DestPointer) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000594 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000595 SrcPointee = SrcPointer->getPointeeType();
596 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000597 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
John Wiegley429bb272011-04-08 18:41:53 +0000598 << OrigSrcType << SrcExpr.get()->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000599 return;
600 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000601 } else if (DestReference->isLValueReferenceType()) {
John Wiegley429bb272011-04-08 18:41:53 +0000602 if (!SrcExpr.get()->isLValue()) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000603 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
John McCallb45ae252011-10-05 07:41:44 +0000604 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000605 }
606 SrcPointee = SrcType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000607 } else {
608 SrcPointee = SrcType;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000609 }
610
Ted Kremenek6217b802009-07-29 21:53:49 +0000611 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000612 if (SrcRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000613 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000614 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
John Wiegley429bb272011-04-08 18:41:53 +0000615 << SrcExpr.get()->getSourceRange()))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000616 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000617 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000618 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
John Wiegley429bb272011-04-08 18:41:53 +0000619 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000620 return;
621 }
622
623 assert((DestPointer || DestReference) &&
624 "Bad destination non-ptr/ref slipped through.");
625 assert((DestRecord || DestPointee->isVoidType()) &&
626 "Bad destination pointee slipped through.");
627 assert(SrcRecord && "Bad source pointee slipped through.");
628
629 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
630 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +0000631 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
John McCallb45ae252011-10-05 07:41:44 +0000632 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000633 return;
634 }
635
636 // C++ 5.2.7p3: If the type of v is the same as the required result type,
637 // [except for cv].
638 if (DestRecord == SrcRecord) {
John McCall2de56d12010-08-25 11:45:40 +0000639 Kind = CK_NoOp;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000640 return;
641 }
642
643 // C++ 5.2.7p5
644 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000645 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000646 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
647 OpRange.getBegin(), OpRange,
648 &BasePath))
649 return;
650
John McCall2de56d12010-08-25 11:45:40 +0000651 Kind = CK_DerivedToBase;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000652
653 // If we are casting to or through a virtual base class, we need a
654 // vtable.
655 if (Self.BasePathInvolvesVirtualBase(BasePath))
656 Self.MarkVTableUsed(OpRange.getBegin(),
657 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000658 return;
659 }
660
661 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor952b0172010-02-11 01:04:33 +0000662 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000663 assert(SrcDecl && "Definition missing");
664 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000665 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
John Wiegley429bb272011-04-08 18:41:53 +0000666 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000667 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000668 Self.MarkVTableUsed(OpRange.getBegin(),
669 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000670
671 // Done. Everything else is run-time checks.
John McCall2de56d12010-08-25 11:45:40 +0000672 Kind = CK_Dynamic;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000673}
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000674
675/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
676/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
677/// like this:
678/// const char *str = "literal";
679/// legacy_function(const_cast\<char*\>(str));
John McCallb45ae252011-10-05 07:41:44 +0000680void CastOperation::CheckConstCast() {
John McCall6dbba4f2011-10-11 23:14:30 +0000681 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload)) {
John Wiegley429bb272011-04-08 18:41:53 +0000682 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
683 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
684 return;
685 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000686
687 unsigned msg = diag::err_bad_cxx_cast_generic;
John Wiegley429bb272011-04-08 18:41:53 +0000688 if (TryConstCast(Self, SrcExpr.get(), DestType, /*CStyle*/false, msg) != TC_Success
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000689 && msg != 0)
690 Self.Diag(OpRange.getBegin(), msg) << CT_Const
John Wiegley429bb272011-04-08 18:41:53 +0000691 << SrcExpr.get()->getType() << DestType << OpRange;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000692}
693
694/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
695/// valid.
696/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
697/// like this:
698/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
John McCallb45ae252011-10-05 07:41:44 +0000699void CastOperation::CheckReinterpretCast() {
John McCall6dbba4f2011-10-11 23:14:30 +0000700 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload)) {
John Wiegley429bb272011-04-08 18:41:53 +0000701 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
702 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
703 return;
704 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000705
706 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCallf85e1932011-06-15 23:02:42 +0000707 TryCastResult tcr =
708 TryReinterpretCast(Self, SrcExpr, DestType,
709 /*CStyle*/false, OpRange, msg, Kind);
710 if (tcr != TC_Success && msg != 0)
Douglas Gregor8e960432010-11-08 03:40:48 +0000711 {
John Wiegley429bb272011-04-08 18:41:53 +0000712 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
713 return;
714 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor8e960432010-11-08 03:40:48 +0000715 //FIXME: &f<int>; is overloaded and resolvable
716 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
John Wiegley429bb272011-04-08 18:41:53 +0000717 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
Douglas Gregor8e960432010-11-08 03:40:48 +0000718 << DestType << OpRange;
John Wiegley429bb272011-04-08 18:41:53 +0000719 Self.NoteAllOverloadCandidates(SrcExpr.get());
Douglas Gregor8e960432010-11-08 03:40:48 +0000720
John McCall79ab2c82011-02-14 18:34:10 +0000721 } else {
John Wiegley429bb272011-04-08 18:41:53 +0000722 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(), DestType);
Douglas Gregor8e960432010-11-08 03:40:48 +0000723 }
John McCallf85e1932011-06-15 23:02:42 +0000724 } else if (tcr == TC_Success && Self.getLangOptions().ObjCAutoRefCount) {
John McCallb45ae252011-10-05 07:41:44 +0000725 checkObjCARCConversion(Sema::CCK_OtherCast);
John McCallf85e1932011-06-15 23:02:42 +0000726 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000727}
728
729
730/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
731/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
732/// implicit conversions explicit and getting rid of data loss warnings.
Nicola Gigante56f5d362011-11-28 12:21:57 +0000733void CastOperation::CheckStaticCast(bool &CastNodesCreated) {
John McCalla180f042011-10-06 23:25:11 +0000734 if (isPlaceholder()) {
735 checkNonOverloadPlaceholders();
736 if (SrcExpr.isInvalid())
737 return;
738 }
739
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000740 // This test is outside everything else because it's the only case where
741 // a non-lvalue-reference target type does not lead to decay.
742 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000743 if (DestType->isVoidType()) {
John McCalla180f042011-10-06 23:25:11 +0000744 Kind = CK_ToVoid;
745
746 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall6dbba4f2011-10-11 23:14:30 +0000747 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000748 false, // Decay Function to ptr
749 true, // Complain
750 OpRange, DestType, diag::err_bad_static_cast_overload);
John McCall6dbba4f2011-10-11 23:14:30 +0000751 if (SrcExpr.isInvalid())
752 return;
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000753 }
John McCalla180f042011-10-06 23:25:11 +0000754
755 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000756 return;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000757 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000758
John McCall6dbba4f2011-10-11 23:14:30 +0000759 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
760 !isPlaceholder(BuiltinType::Overload)) {
John Wiegley429bb272011-04-08 18:41:53 +0000761 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
762 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
763 return;
764 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000765
Nicola Gigante56f5d362011-11-28 12:21:57 +0000766 Expr *SrcExprOrig = SrcExpr.get();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000767 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCallf85e1932011-06-15 23:02:42 +0000768 TryCastResult tcr
Nicola Gigante56f5d362011-11-28 12:21:57 +0000769 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_StaticCast, OpRange, msg,
John McCallf85e1932011-06-15 23:02:42 +0000770 Kind, BasePath);
771 if (tcr != TC_Success && msg != 0) {
John Wiegley429bb272011-04-08 18:41:53 +0000772 if (SrcExpr.isInvalid())
773 return;
774 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
775 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
Douglas Gregor8e960432010-11-08 03:40:48 +0000776 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
Douglas Gregor4c9be892011-02-28 20:01:57 +0000777 << oe->getName() << DestType << OpRange
778 << oe->getQualifierLoc().getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +0000779 Self.NoteAllOverloadCandidates(SrcExpr.get());
John McCall79ab2c82011-02-14 18:34:10 +0000780 } else {
John Wiegley429bb272011-04-08 18:41:53 +0000781 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType);
Douglas Gregor8e960432010-11-08 03:40:48 +0000782 }
John McCallf85e1932011-06-15 23:02:42 +0000783 } else if (tcr == TC_Success) {
784 if (Kind == CK_BitCast)
John McCallb45ae252011-10-05 07:41:44 +0000785 checkCastAlign();
786 if (Self.getLangOptions().ObjCAutoRefCount)
Nicola Gigante56f5d362011-11-28 12:21:57 +0000787 checkObjCARCConversion(Sema::CCK_StaticCast);
John McCallb45ae252011-10-05 07:41:44 +0000788 } else if (Kind == CK_BitCast) {
789 checkCastAlign();
Douglas Gregor8e960432010-11-08 03:40:48 +0000790 }
Nicola Gigante56f5d362011-11-28 12:21:57 +0000791
792 CastNodesCreated = (SrcExpr.get() != SrcExprOrig);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000793}
794
795/// TryStaticCast - Check if a static cast can be performed, and do so if
796/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
797/// and casting away constness.
John Wiegley429bb272011-04-08 18:41:53 +0000798static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCallf85e1932011-06-15 23:02:42 +0000799 QualType DestType,
800 Sema::CheckedConversionKind CCK,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000801 const SourceRange &OpRange, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000802 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000803 CXXCastPath &BasePath) {
John McCallf85e1932011-06-15 23:02:42 +0000804 // Determine whether we have the semantics of a C-style cast.
805 bool CStyle
806 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
807
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000808 // The order the tests is not entirely arbitrary. There is one conversion
809 // that can be handled in two different ways. Given:
810 // struct A {};
811 // struct B : public A {
812 // B(); B(const A&);
813 // };
814 // const A &a = B();
815 // the cast static_cast<const B&>(a) could be seen as either a static
816 // reference downcast, or an explicit invocation of the user-defined
817 // conversion using B's conversion constructor.
818 // DR 427 specifies that the downcast is to be applied here.
819
820 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
821 // Done outside this function.
822
823 TryCastResult tcr;
824
825 // C++ 5.2.9p5, reference downcast.
826 // See the function for details.
827 // DR 427 specifies that this is to be applied before paragraph 2.
John Wiegley429bb272011-04-08 18:41:53 +0000828 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle, OpRange,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000829 msg, Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000830 if (tcr != TC_NotApplicable)
831 return tcr;
832
Douglas Gregordc843f22011-01-22 00:06:57 +0000833 // C++0x [expr.static.cast]p3:
834 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
835 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
John Wiegley429bb272011-04-08 18:41:53 +0000836 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind, BasePath,
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000837 msg);
Douglas Gregor88b22a42011-01-25 16:13:26 +0000838 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000839 return tcr;
840
841 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
842 // [...] if the declaration "T t(e);" is well-formed, [...].
John McCallf85e1932011-06-15 23:02:42 +0000843 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
Douglas Gregord6e44a32010-04-16 22:09:46 +0000844 Kind);
John Wiegley429bb272011-04-08 18:41:53 +0000845 if (SrcExpr.isInvalid())
846 return TC_Failed;
Anders Carlsson3c31a392009-09-26 00:12:34 +0000847 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000848 return tcr;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000849
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000850 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
851 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
852 // conversions, subject to further restrictions.
853 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
854 // of qualification conversions impossible.
855 // In the CStyle case, the earlier attempt to const_cast should have taken
856 // care of reverse qualification conversions.
857
John Wiegley429bb272011-04-08 18:41:53 +0000858 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000859
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000860 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
Douglas Gregor1e856d92011-02-18 03:01:41 +0000861 // converted to an integral type. [...] A value of a scoped enumeration type
862 // can also be explicitly converted to a floating-point type [...].
863 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
864 if (Enum->getDecl()->isScoped()) {
865 if (DestType->isBooleanType()) {
866 Kind = CK_IntegralToBoolean;
867 return TC_Success;
868 } else if (DestType->isIntegralType(Self.Context)) {
869 Kind = CK_IntegralCast;
870 return TC_Success;
871 } else if (DestType->isRealFloatingType()) {
872 Kind = CK_IntegralToFloating;
873 return TC_Success;
874 }
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000875 }
876 }
Douglas Gregor1e856d92011-02-18 03:01:41 +0000877
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000878 // Reverse integral promotion/conversion. All such conversions are themselves
879 // again integral promotions or conversions and are thus already handled by
880 // p2 (TryDirectInitialization above).
881 // (Note: any data loss warnings should be suppressed.)
882 // The exception is the reverse of enum->integer, i.e. integer->enum (and
883 // enum->enum). See also C++ 5.2.9p7.
884 // The same goes for reverse floating point promotion/conversion and
885 // floating-integral conversions. Again, only floating->enum is relevant.
886 if (DestType->isEnumeralType()) {
Eli Friedmancc2fca22011-09-02 17:38:59 +0000887 if (SrcType->isIntegralOrEnumerationType()) {
John McCall2de56d12010-08-25 11:45:40 +0000888 Kind = CK_IntegralCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000889 return TC_Success;
Eli Friedmancc2fca22011-09-02 17:38:59 +0000890 } else if (SrcType->isRealFloatingType()) {
891 Kind = CK_FloatingToIntegral;
892 return TC_Success;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000893 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000894 }
895
896 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
897 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000898 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000899 Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000900 if (tcr != TC_NotApplicable)
901 return tcr;
902
903 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
904 // conversion. C++ 5.2.9p9 has additional information.
905 // DR54's access restrictions apply here also.
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000906 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssoncee22422010-04-24 19:22:20 +0000907 OpRange, msg, Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000908 if (tcr != TC_NotApplicable)
909 return tcr;
910
911 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
912 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
913 // just the usual constness stuff.
Ted Kremenek6217b802009-07-29 21:53:49 +0000914 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000915 QualType SrcPointee = SrcPointer->getPointeeType();
916 if (SrcPointee->isVoidType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000917 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000918 QualType DestPointee = DestPointer->getPointeeType();
919 if (DestPointee->isIncompleteOrObjectType()) {
920 // This is definitely the intended conversion, but it might fail due
John McCallf85e1932011-06-15 23:02:42 +0000921 // to a qualifier violation. Note that we permit Objective-C lifetime
922 // and GC qualifier mismatches here.
923 if (!CStyle) {
924 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
925 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
926 DestPointeeQuals.removeObjCGCAttr();
927 DestPointeeQuals.removeObjCLifetime();
928 SrcPointeeQuals.removeObjCGCAttr();
929 SrcPointeeQuals.removeObjCLifetime();
930 if (DestPointeeQuals != SrcPointeeQuals &&
931 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
932 msg = diag::err_bad_cxx_cast_qualifiers_away;
933 return TC_Failed;
934 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000935 }
John McCall2de56d12010-08-25 11:45:40 +0000936 Kind = CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000937 return TC_Success;
938 }
939 }
Fariborz Jahanian2f6c5502010-05-10 23:46:53 +0000940 else if (DestType->isObjCObjectPointerType()) {
941 // allow both c-style cast and static_cast of objective-c pointers as
942 // they are pervasive.
John McCall1d9b3b22011-09-09 05:25:32 +0000943 Kind = CK_CPointerToObjCPointerCast;
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +0000944 return TC_Success;
945 }
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +0000946 else if (CStyle && DestType->isBlockPointerType()) {
947 // allow c-style cast of void * to block pointers.
John McCall2de56d12010-08-25 11:45:40 +0000948 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +0000949 return TC_Success;
950 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000951 }
952 }
Fariborz Jahanian65267b22010-05-12 18:16:59 +0000953 // Allow arbitray objective-c pointer conversion with static casts.
954 if (SrcType->isObjCObjectPointerType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +0000955 DestType->isObjCObjectPointerType()) {
956 Kind = CK_BitCast;
Fariborz Jahanian65267b22010-05-12 18:16:59 +0000957 return TC_Success;
John McCalldaa8e4e2010-11-15 09:13:47 +0000958 }
Fariborz Jahanian65267b22010-05-12 18:16:59 +0000959
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000960 // We tried everything. Everything! Nothing works! :-(
961 return TC_NotApplicable;
962}
963
964/// Tests whether a conversion according to N2844 is valid.
965TryCastResult
966TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000967 bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
968 unsigned &msg) {
Douglas Gregordc843f22011-01-22 00:06:57 +0000969 // C++0x [expr.static.cast]p3:
970 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
971 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenek6217b802009-07-29 21:53:49 +0000972 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000973 if (!R)
974 return TC_NotApplicable;
975
Douglas Gregordc843f22011-01-22 00:06:57 +0000976 if (!SrcExpr->isGLValue())
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000977 return TC_NotApplicable;
978
979 // Because we try the reference downcast before this function, from now on
980 // this is the only cast possibility, so we issue an error if we fail now.
981 // FIXME: Should allow casting away constness if CStyle.
982 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +0000983 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +0000984 bool ObjCLifetimeConversion;
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000985 QualType FromType = SrcExpr->getType();
986 QualType ToType = R->getPointeeType();
987 if (CStyle) {
988 FromType = FromType.getUnqualifiedType();
989 ToType = ToType.getUnqualifiedType();
990 }
991
Douglas Gregor393896f2009-11-05 13:06:35 +0000992 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000993 ToType, FromType,
John McCallf85e1932011-06-15 23:02:42 +0000994 DerivedToBase, ObjCConversion,
995 ObjCLifetimeConversion)
996 < Sema::Ref_Compatible_With_Added_Qualification) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000997 msg = diag::err_bad_lvalue_to_rvalue_cast;
998 return TC_Failed;
999 }
1000
Douglas Gregor88b22a42011-01-25 16:13:26 +00001001 if (DerivedToBase) {
1002 Kind = CK_DerivedToBase;
1003 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1004 /*DetectVirtual=*/true);
1005 if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
1006 return TC_NotApplicable;
1007
1008 Self.BuildBasePathArray(Paths, BasePath);
1009 } else
1010 Kind = CK_NoOp;
1011
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001012 return TC_Success;
1013}
1014
1015/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1016TryCastResult
1017TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
1018 bool CStyle, const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +00001019 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001020 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001021 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1022 // cast to type "reference to cv2 D", where D is a class derived from B,
1023 // if a valid standard conversion from "pointer to D" to "pointer to B"
1024 // exists, cv2 >= cv1, and B is not a virtual base class of D.
1025 // In addition, DR54 clarifies that the base must be accessible in the
1026 // current context. Although the wording of DR54 only applies to the pointer
1027 // variant of this rule, the intent is clearly for it to apply to the this
1028 // conversion as well.
1029
Ted Kremenek6217b802009-07-29 21:53:49 +00001030 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001031 if (!DestReference) {
1032 return TC_NotApplicable;
1033 }
1034 bool RValueRef = DestReference->isRValueReferenceType();
John McCall7eb0a9e2010-11-24 05:12:34 +00001035 if (!RValueRef && !SrcExpr->isLValue()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001036 // We know the left side is an lvalue reference, so we can suggest a reason.
1037 msg = diag::err_bad_cxx_cast_rvalue;
1038 return TC_NotApplicable;
1039 }
1040
1041 QualType DestPointee = DestReference->getPointeeType();
1042
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001043 return TryStaticDowncast(Self,
1044 Self.Context.getCanonicalType(SrcExpr->getType()),
1045 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001046 OpRange, SrcExpr->getType(), DestType, msg, Kind,
1047 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001048}
1049
1050/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1051TryCastResult
1052TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +00001053 bool CStyle, const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +00001054 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001055 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001056 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1057 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1058 // is a class derived from B, if a valid standard conversion from "pointer
1059 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1060 // class of D.
1061 // In addition, DR54 clarifies that the base must be accessible in the
1062 // current context.
1063
Ted Kremenek6217b802009-07-29 21:53:49 +00001064 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001065 if (!DestPointer) {
1066 return TC_NotApplicable;
1067 }
1068
Ted Kremenek6217b802009-07-29 21:53:49 +00001069 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001070 if (!SrcPointer) {
1071 msg = diag::err_bad_static_cast_pointer_nonpointer;
1072 return TC_NotApplicable;
1073 }
1074
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001075 return TryStaticDowncast(Self,
1076 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1077 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001078 CStyle, OpRange, SrcType, DestType, msg, Kind,
1079 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001080}
1081
1082/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1083/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001084/// DestType is possible and allowed.
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001085TryCastResult
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001086TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001087 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +00001088 QualType OrigDestType, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +00001089 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl5ed66f72009-10-22 15:07:22 +00001090 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00001091 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, Self.PDiag(0)) ||
1092 Self.RequireCompleteType(OpRange.getBegin(), DestType, Self.PDiag(0)))
Sebastian Redl5ed66f72009-10-22 15:07:22 +00001093 return TC_NotApplicable;
1094
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001095 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001096 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001097 return TC_NotApplicable;
1098 }
1099
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001100 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001101 /*DetectVirtual=*/true);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001102 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
1103 return TC_NotApplicable;
1104 }
1105
1106 // Target type does derive from source type. Now we're serious. If an error
1107 // appears now, it's not ignored.
1108 // This may not be entirely in line with the standard. Take for example:
1109 // struct A {};
1110 // struct B : virtual A {
1111 // B(A&);
1112 // };
Mike Stump1eb44332009-09-09 15:08:12 +00001113 //
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001114 // void f()
1115 // {
1116 // (void)static_cast<const B&>(*((A*)0));
1117 // }
1118 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1119 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1120 // However, both GCC and Comeau reject this example, and accepting it would
1121 // mean more complex code if we're to preserve the nice error message.
1122 // FIXME: Being 100% compliant here would be nice to have.
1123
1124 // Must preserve cv, as always, unless we're in C-style mode.
1125 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001126 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001127 return TC_Failed;
1128 }
1129
1130 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1131 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1132 // that it builds the paths in reverse order.
1133 // To sum up: record all paths to the base and build a nice string from
1134 // them. Use it to spice up the error message.
1135 if (!Paths.isRecordingPaths()) {
1136 Paths.clear();
1137 Paths.setRecordingPaths(true);
1138 Self.IsDerivedFrom(DestType, SrcType, Paths);
1139 }
1140 std::string PathDisplayStr;
1141 std::set<unsigned> DisplayedPaths;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001142 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001143 PI != PE; ++PI) {
1144 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
1145 // We haven't displayed a path to this particular base
1146 // class subobject yet.
1147 PathDisplayStr += "\n ";
Douglas Gregora8f32e02009-10-06 17:59:45 +00001148 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
1149 EE = PI->rend();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001150 EI != EE; ++EI)
1151 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001152 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001153 }
1154 }
1155
1156 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001157 << QualType(SrcType).getUnqualifiedType()
1158 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001159 << PathDisplayStr << OpRange;
1160 msg = 0;
1161 return TC_Failed;
1162 }
1163
1164 if (Paths.getDetectedVirtual() != 0) {
1165 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1166 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1167 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1168 msg = 0;
1169 return TC_Failed;
1170 }
1171
John McCall417d39f2011-02-14 23:21:33 +00001172 if (!CStyle) {
1173 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1174 SrcType, DestType,
1175 Paths.front(),
John McCall58e6f342010-03-16 05:22:47 +00001176 diag::err_downcast_from_inaccessible_base)) {
John McCall417d39f2011-02-14 23:21:33 +00001177 case Sema::AR_accessible:
1178 case Sema::AR_delayed: // be optimistic
1179 case Sema::AR_dependent: // be optimistic
1180 break;
1181
1182 case Sema::AR_inaccessible:
1183 msg = 0;
1184 return TC_Failed;
1185 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001186 }
1187
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001188 Self.BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00001189 Kind = CK_BaseToDerived;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001190 return TC_Success;
1191}
1192
1193/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1194/// C++ 5.2.9p9 is valid:
1195///
1196/// An rvalue of type "pointer to member of D of type cv1 T" can be
1197/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1198/// where B is a base class of D [...].
1199///
1200TryCastResult
John Wiegley429bb272011-04-08 18:41:53 +00001201TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001202 QualType DestType, bool CStyle,
1203 const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +00001204 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001205 CXXCastPath &BasePath) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001206 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001207 if (!DestMemPtr)
1208 return TC_NotApplicable;
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001209
1210 bool WasOverloadedFunction = false;
John McCall6bb80172010-03-30 21:47:33 +00001211 DeclAccessPair FoundOverload;
John Wiegley429bb272011-04-08 18:41:53 +00001212 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor1a8cf732010-04-14 23:11:21 +00001213 if (FunctionDecl *Fn
John Wiegley429bb272011-04-08 18:41:53 +00001214 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
Douglas Gregor1a8cf732010-04-14 23:11:21 +00001215 FoundOverload)) {
1216 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1217 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1218 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1219 WasOverloadedFunction = true;
1220 }
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001221 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00001222
Ted Kremenek6217b802009-07-29 21:53:49 +00001223 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001224 if (!SrcMemPtr) {
1225 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1226 return TC_NotApplicable;
1227 }
1228
1229 // T == T, modulo cv
Douglas Gregora4923eb2009-11-16 21:35:15 +00001230 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1231 DestMemPtr->getPointeeType()))
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001232 return TC_NotApplicable;
1233
1234 // B base of D
1235 QualType SrcClass(SrcMemPtr->getClass(), 0);
1236 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssoncee22422010-04-24 19:22:20 +00001237 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001238 /*DetectVirtual=*/true);
1239 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
1240 return TC_NotApplicable;
1241 }
1242
1243 // 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 +00001244 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001245 Paths.clear();
1246 Paths.setRecordingPaths(true);
1247 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
1248 assert(StillOkay);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001249 (void)StillOkay;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001250 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1251 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1252 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1253 msg = 0;
1254 return TC_Failed;
1255 }
1256
1257 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1258 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1259 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1260 msg = 0;
1261 return TC_Failed;
1262 }
1263
John McCall417d39f2011-02-14 23:21:33 +00001264 if (!CStyle) {
1265 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1266 DestClass, SrcClass,
1267 Paths.front(),
1268 diag::err_upcast_to_inaccessible_base)) {
1269 case Sema::AR_accessible:
1270 case Sema::AR_delayed:
1271 case Sema::AR_dependent:
1272 // Optimistically assume that the delayed and dependent cases
1273 // will work out.
1274 break;
1275
1276 case Sema::AR_inaccessible:
1277 msg = 0;
1278 return TC_Failed;
1279 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001280 }
1281
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001282 if (WasOverloadedFunction) {
1283 // Resolve the address of the overloaded function again, this time
1284 // allowing complaints if something goes wrong.
John Wiegley429bb272011-04-08 18:41:53 +00001285 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001286 DestType,
John McCall6bb80172010-03-30 21:47:33 +00001287 true,
1288 FoundOverload);
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001289 if (!Fn) {
1290 msg = 0;
1291 return TC_Failed;
1292 }
1293
John McCall6bb80172010-03-30 21:47:33 +00001294 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
John Wiegley429bb272011-04-08 18:41:53 +00001295 if (!SrcExpr.isUsable()) {
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001296 msg = 0;
1297 return TC_Failed;
1298 }
1299 }
1300
Anders Carlssoncee22422010-04-24 19:22:20 +00001301 Self.BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00001302 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001303 return TC_Success;
1304}
1305
1306/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1307/// is valid:
1308///
1309/// An expression e can be explicitly converted to a type T using a
1310/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1311TryCastResult
John Wiegley429bb272011-04-08 18:41:53 +00001312TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCallf85e1932011-06-15 23:02:42 +00001313 Sema::CheckedConversionKind CCK,
1314 const SourceRange &OpRange, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +00001315 CastKind &Kind) {
Anders Carlssond851b372009-09-07 18:25:47 +00001316 if (DestType->isRecordType()) {
1317 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1318 diag::err_bad_dynamic_cast_incomplete)) {
1319 msg = 0;
1320 return TC_Failed;
1321 }
1322 }
Douglas Gregord6e44a32010-04-16 22:09:46 +00001323
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001324 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1325 InitializationKind InitKind
John McCallf85e1932011-06-15 23:02:42 +00001326 = (CCK == Sema::CCK_CStyleCast)
1327 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange)
1328 : (CCK == Sema::CCK_FunctionalCast)
1329 ? InitializationKind::CreateFunctionalCast(OpRange)
Nicola Gigante56f5d362011-11-28 12:21:57 +00001330 : InitializationKind::CreateStaticCast(OpRange);
John Wiegley429bb272011-04-08 18:41:53 +00001331 Expr *SrcExprRaw = SrcExpr.get();
1332 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExprRaw, 1);
Douglas Gregor8e960432010-11-08 03:40:48 +00001333
1334 // At this point of CheckStaticCast, if the destination is a reference,
1335 // or the expression is an overload expression this has to work.
1336 // There is no other way that works.
1337 // On the other hand, if we're checking a C-style cast, we've still got
1338 // the reinterpret_cast way.
John McCallf85e1932011-06-15 23:02:42 +00001339 bool CStyle
1340 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
Sebastian Redl383616c2011-06-05 12:23:28 +00001341 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
Anders Carlsson3c31a392009-09-26 00:12:34 +00001342 return TC_NotApplicable;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001343
John McCall60d7b3a2010-08-24 06:29:42 +00001344 ExprResult Result
John Wiegley429bb272011-04-08 18:41:53 +00001345 = InitSeq.Perform(Self, Entity, InitKind, MultiExprArg(Self, &SrcExprRaw, 1));
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001346 if (Result.isInvalid()) {
1347 msg = 0;
1348 return TC_Failed;
1349 }
1350
Douglas Gregord6e44a32010-04-16 22:09:46 +00001351 if (InitSeq.isConstructorInitialization())
John McCall2de56d12010-08-25 11:45:40 +00001352 Kind = CK_ConstructorConversion;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001353 else
John McCall2de56d12010-08-25 11:45:40 +00001354 Kind = CK_NoOp;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001355
John Wiegley429bb272011-04-08 18:41:53 +00001356 SrcExpr = move(Result);
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001357 return TC_Success;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001358}
1359
1360/// TryConstCast - See if a const_cast from source to destination is allowed,
1361/// and perform it if it is.
1362static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
1363 bool CStyle, unsigned &msg) {
1364 DestType = Self.Context.getCanonicalType(DestType);
1365 QualType SrcType = SrcExpr->getType();
Douglas Gregor575d2a32011-01-22 00:19:52 +00001366 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
1367 if (DestTypeTmp->isLValueReferenceType() && !SrcExpr->isLValue()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001368 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1369 // is C-style, static_cast might find a way, so we simply suggest a
1370 // message and tell the parent to keep searching.
1371 msg = diag::err_bad_cxx_cast_rvalue;
1372 return TC_NotApplicable;
1373 }
1374
1375 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
1376 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
1377 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1378 SrcType = Self.Context.getPointerType(SrcType);
1379 }
1380
1381 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1382 // the rules for const_cast are the same as those used for pointers.
1383
John McCalld425d2b2010-05-18 09:35:29 +00001384 if (!DestType->isPointerType() &&
1385 !DestType->isMemberPointerType() &&
1386 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001387 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1388 // was a reference type, we converted it to a pointer above.
1389 // The status of rvalue references isn't entirely clear, but it looks like
1390 // conversion to them is simply invalid.
1391 // C++ 5.2.11p3: For two pointer types [...]
1392 if (!CStyle)
1393 msg = diag::err_bad_const_cast_dest;
1394 return TC_NotApplicable;
1395 }
1396 if (DestType->isFunctionPointerType() ||
1397 DestType->isMemberFunctionPointerType()) {
1398 // Cannot cast direct function pointers.
1399 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1400 // T is the ultimate pointee of source and target type.
1401 if (!CStyle)
1402 msg = diag::err_bad_const_cast_dest;
1403 return TC_NotApplicable;
1404 }
1405 SrcType = Self.Context.getCanonicalType(SrcType);
1406
1407 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1408 // completely equal.
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001409 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1410 // in multi-level pointers may change, but the level count must be the same,
1411 // as must be the final pointee type.
1412 while (SrcType != DestType &&
Douglas Gregor5a57efd2010-06-09 03:53:18 +00001413 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001414 Qualifiers SrcQuals, DestQuals;
1415 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
1416 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
1417
1418 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
1419 // the other qualifiers (e.g., address spaces) are identical.
1420 SrcQuals.removeCVRQualifiers();
1421 DestQuals.removeCVRQualifiers();
1422 if (SrcQuals != DestQuals)
1423 return TC_NotApplicable;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001424 }
1425
1426 // Since we're dealing in canonical types, the remainder must be the same.
1427 if (SrcType != DestType)
1428 return TC_NotApplicable;
1429
1430 return TC_Success;
1431}
1432
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001433// Checks for undefined behavior in reinterpret_cast.
1434// The cases that is checked for is:
1435// *reinterpret_cast<T*>(&a)
1436// reinterpret_cast<T&>(a)
1437// where accessing 'a' as type 'T' will result in undefined behavior.
1438void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1439 bool IsDereference,
1440 SourceRange Range) {
1441 unsigned DiagID = IsDereference ?
1442 diag::warn_pointer_indirection_from_incompatible_type :
1443 diag::warn_undefined_reinterpret_cast;
1444
1445 if (Diags.getDiagnosticLevel(DiagID, Range.getBegin()) ==
David Blaikied6471f72011-09-25 23:23:43 +00001446 DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001447 return;
1448 }
1449
1450 QualType SrcTy, DestTy;
1451 if (IsDereference) {
1452 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1453 return;
1454 }
1455 SrcTy = SrcType->getPointeeType();
1456 DestTy = DestType->getPointeeType();
1457 } else {
1458 if (!DestType->getAs<ReferenceType>()) {
1459 return;
1460 }
1461 SrcTy = SrcType;
1462 DestTy = DestType->getPointeeType();
1463 }
1464
1465 // Cast is compatible if the types are the same.
1466 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1467 return;
1468 }
1469 // or one of the types is a char or void type
1470 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1471 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1472 return;
1473 }
1474 // or one of the types is a tag type.
Chandler Carruth1f8f2d52011-05-24 07:43:19 +00001475 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001476 return;
1477 }
1478
Douglas Gregor575a1c92011-05-20 16:38:50 +00001479 // FIXME: Scoped enums?
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001480 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1481 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1482 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1483 return;
1484 }
1485 }
1486
1487 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1488}
Douglas Gregorfadb53b2011-03-12 01:48:56 +00001489
John Wiegley429bb272011-04-08 18:41:53 +00001490static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001491 QualType DestType, bool CStyle,
1492 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +00001493 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +00001494 CastKind &Kind) {
Douglas Gregore39a3892010-07-13 23:17:26 +00001495 bool IsLValueCast = false;
1496
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001497 DestType = Self.Context.getCanonicalType(DestType);
John Wiegley429bb272011-04-08 18:41:53 +00001498 QualType SrcType = SrcExpr.get()->getType();
Douglas Gregor8e960432010-11-08 03:40:48 +00001499
1500 // Is the source an overloaded name? (i.e. &foo)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001501 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ...
1502 if (SrcType == Self.Context.OverloadTy) {
John McCall6dbba4f2011-10-11 23:14:30 +00001503 // ... unless foo<int> resolves to an lvalue unambiguously.
1504 // TODO: what if this fails because of DiagnoseUseOfDecl or something
1505 // like it?
1506 ExprResult SingleFunctionExpr = SrcExpr;
1507 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1508 SingleFunctionExpr,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001509 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
John McCall6dbba4f2011-10-11 23:14:30 +00001510 ) && SingleFunctionExpr.isUsable()) {
John Wiegley429bb272011-04-08 18:41:53 +00001511 SrcExpr = move(SingleFunctionExpr);
1512 SrcType = SrcExpr.get()->getType();
John McCall6dbba4f2011-10-11 23:14:30 +00001513 } else {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001514 return TC_NotApplicable;
John McCall6dbba4f2011-10-11 23:14:30 +00001515 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001516 }
Douglas Gregor8e960432010-11-08 03:40:48 +00001517
Ted Kremenek6217b802009-07-29 21:53:49 +00001518 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001519 bool LValue = DestTypeTmp->isLValueReferenceType();
John Wiegley429bb272011-04-08 18:41:53 +00001520 if (LValue && !SrcExpr.get()->isLValue()) {
Douglas Gregor575d2a32011-01-22 00:19:52 +00001521 // Cannot cast non-lvalue to lvalue reference type. See the similar
1522 // comment in const_cast.
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001523 msg = diag::err_bad_cxx_cast_rvalue;
1524 return TC_NotApplicable;
1525 }
1526
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001527 if (!CStyle) {
1528 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
1529 /*isDereference=*/false, OpRange);
1530 }
1531
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001532 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1533 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1534 // built-in & and * operators.
Argyrios Kyrtzidisb464a5b2011-04-22 22:31:13 +00001535
Argyrios Kyrtzidisbb29d1b2011-04-22 23:57:57 +00001536 const char *inappropriate = 0;
1537 switch (SrcExpr.get()->getObjectKind()) {
Argyrios Kyrtzidise5e3d312011-04-23 01:10:24 +00001538 case OK_Ordinary:
1539 break;
Argyrios Kyrtzidisbb29d1b2011-04-22 23:57:57 +00001540 case OK_BitField: inappropriate = "bit-field"; break;
1541 case OK_VectorComponent: inappropriate = "vector element"; break;
1542 case OK_ObjCProperty: inappropriate = "property expression"; break;
1543 }
1544 if (inappropriate) {
1545 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
1546 << inappropriate << DestType
1547 << OpRange << SrcExpr.get()->getSourceRange();
1548 msg = 0; SrcExpr = ExprError();
Argyrios Kyrtzidisb464a5b2011-04-22 22:31:13 +00001549 return TC_NotApplicable;
1550 }
1551
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001552 // This code does this transformation for the checked types.
1553 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1554 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregor8e960432010-11-08 03:40:48 +00001555
Douglas Gregore39a3892010-07-13 23:17:26 +00001556 IsLValueCast = true;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001557 }
1558
1559 // Canonicalize source for comparison.
1560 SrcType = Self.Context.getCanonicalType(SrcType);
1561
Ted Kremenek6217b802009-07-29 21:53:49 +00001562 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1563 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001564 if (DestMemPtr && SrcMemPtr) {
1565 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1566 // can be explicitly converted to an rvalue of type "pointer to member
1567 // of Y of type T2" if T1 and T2 are both function types or both object
1568 // types.
1569 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1570 SrcMemPtr->getPointeeType()->isFunctionType())
1571 return TC_NotApplicable;
1572
1573 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1574 // constness.
1575 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1576 // we accept it.
John McCallf85e1932011-06-15 23:02:42 +00001577 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1578 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001579 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001580 return TC_Failed;
1581 }
1582
Charles Davisf231df32010-08-16 05:30:44 +00001583 // Don't allow casting between member pointers of different sizes.
1584 if (Self.Context.getTypeSize(DestMemPtr) !=
1585 Self.Context.getTypeSize(SrcMemPtr)) {
1586 msg = diag::err_bad_cxx_cast_member_pointer_size;
1587 return TC_Failed;
1588 }
1589
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001590 // A valid member pointer cast.
John McCall2de56d12010-08-25 11:45:40 +00001591 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001592 return TC_Success;
1593 }
1594
1595 // See below for the enumeral issue.
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001596 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001597 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1598 // type large enough to hold it. A value of std::nullptr_t can be
1599 // converted to an integral type; the conversion has the same meaning
1600 // and validity as a conversion of (void*)0 to the integral type.
1601 if (Self.Context.getTypeSize(SrcType) >
1602 Self.Context.getTypeSize(DestType)) {
1603 msg = diag::err_bad_reinterpret_cast_small_int;
1604 return TC_Failed;
1605 }
John McCall2de56d12010-08-25 11:45:40 +00001606 Kind = CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001607 return TC_Success;
1608 }
1609
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001610 bool destIsVector = DestType->isVectorType();
1611 bool srcIsVector = SrcType->isVectorType();
1612 if (srcIsVector || destIsVector) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001613 // FIXME: Should this also apply to floating point types?
1614 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1615 bool destIsScalar = DestType->isIntegralType(Self.Context);
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001616
1617 // Check if this is a cast between a vector and something else.
1618 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1619 !(srcIsVector && destIsVector))
1620 return TC_NotApplicable;
1621
1622 // If both types have the same size, we can successfully cast.
Douglas Gregorf2a55392009-12-22 22:47:22 +00001623 if (Self.Context.getTypeSize(SrcType)
1624 == Self.Context.getTypeSize(DestType)) {
John McCall2de56d12010-08-25 11:45:40 +00001625 Kind = CK_BitCast;
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001626 return TC_Success;
Douglas Gregorf2a55392009-12-22 22:47:22 +00001627 }
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001628
1629 if (destIsScalar)
1630 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1631 else if (srcIsScalar)
1632 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1633 else
1634 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1635
1636 return TC_Failed;
1637 }
1638
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001639 bool destIsPtr = DestType->isAnyPointerType() ||
1640 DestType->isBlockPointerType();
1641 bool srcIsPtr = SrcType->isAnyPointerType() ||
1642 SrcType->isBlockPointerType();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001643 if (!destIsPtr && !srcIsPtr) {
1644 // Except for std::nullptr_t->integer and lvalue->reference, which are
1645 // handled above, at least one of the two arguments must be a pointer.
1646 return TC_NotApplicable;
1647 }
1648
1649 if (SrcType == DestType) {
1650 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1651 // restrictions, a cast to the same type is allowed. The intent is not
1652 // entirely clear here, since all other paragraphs explicitly forbid casts
1653 // to the same type. However, the behavior of compilers is pretty consistent
1654 // on this point: allow same-type conversion if the involved types are
1655 // pointers, disallow otherwise.
John McCall2de56d12010-08-25 11:45:40 +00001656 Kind = CK_NoOp;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001657 return TC_Success;
1658 }
1659
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001660 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001661 assert(srcIsPtr && "One type must be a pointer");
1662 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
Francois Pichet30aff5b2011-05-11 22:13:54 +00001663 // type large enough to hold it; except in Microsoft mode, where the
1664 // integral type size doesn't matter.
1665 if ((Self.Context.getTypeSize(SrcType) >
1666 Self.Context.getTypeSize(DestType)) &&
Francois Pichet62ec1f22011-09-17 17:15:52 +00001667 !Self.getLangOptions().MicrosoftExt) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001668 msg = diag::err_bad_reinterpret_cast_small_int;
1669 return TC_Failed;
1670 }
John McCall2de56d12010-08-25 11:45:40 +00001671 Kind = CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001672 return TC_Success;
1673 }
1674
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001675 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001676 assert(destIsPtr && "One type must be a pointer");
1677 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1678 // converted to a pointer.
John McCall404cd162010-11-13 01:35:44 +00001679 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1680 // necessarily converted to a null pointer value.]
John McCall2de56d12010-08-25 11:45:40 +00001681 Kind = CK_IntegralToPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001682 return TC_Success;
1683 }
1684
1685 if (!destIsPtr || !srcIsPtr) {
1686 // With the valid non-pointer conversions out of the way, we can be even
1687 // more stringent.
1688 return TC_NotApplicable;
1689 }
1690
1691 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1692 // The C-style cast operator can.
John McCallf85e1932011-06-15 23:02:42 +00001693 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1694 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001695 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001696 return TC_Failed;
1697 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001698
1699 // Cannot convert between block pointers and Objective-C object pointers.
1700 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1701 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1702 return TC_NotApplicable;
1703
John McCall1d9b3b22011-09-09 05:25:32 +00001704 if (IsLValueCast) {
1705 Kind = CK_LValueBitCast;
1706 } else if (DestType->isObjCObjectPointerType()) {
John McCalldc05b112011-09-10 01:16:55 +00001707 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
John McCall1d9b3b22011-09-09 05:25:32 +00001708 } else if (DestType->isBlockPointerType()) {
1709 if (!SrcType->isBlockPointerType()) {
1710 Kind = CK_AnyPointerToBlockPointerCast;
1711 } else {
1712 Kind = CK_BitCast;
1713 }
1714 } else {
1715 Kind = CK_BitCast;
1716 }
1717
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001718 // Any pointer can be cast to an Objective-C pointer type with a C-style
1719 // cast.
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001720 if (CStyle && DestType->isObjCObjectPointerType()) {
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001721 return TC_Success;
1722 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001723
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001724 // Not casting away constness, so the only remaining check is for compatible
1725 // pointer categories.
1726
1727 if (SrcType->isFunctionPointerType()) {
1728 if (DestType->isFunctionPointerType()) {
1729 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1730 // a pointer to a function of a different type.
1731 return TC_Success;
1732 }
1733
1734 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1735 // an object type or vice versa is conditionally-supported.
1736 // Compilers support it in C++03 too, though, because it's necessary for
1737 // casting the return value of dlsym() and GetProcAddress().
1738 // FIXME: Conditionally-supported behavior should be configurable in the
1739 // TargetInfo or similar.
Richard Smithebaf0e62011-10-18 20:49:44 +00001740 Self.Diag(OpRange.getBegin(),
1741 Self.getLangOptions().CPlusPlus0x ?
1742 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
1743 << OpRange;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001744 return TC_Success;
1745 }
1746
1747 if (DestType->isFunctionPointerType()) {
1748 // See above.
Richard Smithebaf0e62011-10-18 20:49:44 +00001749 Self.Diag(OpRange.getBegin(),
1750 Self.getLangOptions().CPlusPlus0x ?
1751 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
1752 << OpRange;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001753 return TC_Success;
1754 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001755
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001756 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1757 // a pointer to an object of different type.
1758 // Void pointers are not specified, but supported by every compiler out there.
1759 // So we finish by allowing everything that remains - it's got to be two
1760 // object pointers.
1761 return TC_Success;
John McCall79ab2c82011-02-14 18:34:10 +00001762}
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001763
Nicola Gigante56f5d362011-11-28 12:21:57 +00001764void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
1765 bool &CastNodesCreated) {
1766 CastNodesCreated = false;
John McCalla180f042011-10-06 23:25:11 +00001767 // Handle placeholders.
1768 if (isPlaceholder()) {
1769 // C-style casts can resolve __unknown_any types.
1770 if (claimPlaceholder(BuiltinType::UnknownAny)) {
1771 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
1772 SrcExpr.get(), Kind,
1773 ValueKind, BasePath);
1774 return;
1775 }
John McCallb45ae252011-10-05 07:41:44 +00001776
John McCalla180f042011-10-06 23:25:11 +00001777 checkNonOverloadPlaceholders();
1778 if (SrcExpr.isInvalid())
1779 return;
John McCall4919dfd2011-10-17 17:42:19 +00001780 }
John McCalla180f042011-10-06 23:25:11 +00001781
1782 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001783 // This test is outside everything else because it's the only case where
1784 // a non-lvalue-reference target type does not lead to decay.
John McCallb45ae252011-10-05 07:41:44 +00001785 if (DestType->isVoidType()) {
John McCallfb8721c2011-04-10 19:13:55 +00001786 Kind = CK_ToVoid;
1787
John McCalla180f042011-10-06 23:25:11 +00001788 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall6dbba4f2011-10-11 23:14:30 +00001789 Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1790 SrcExpr, /* Decay Function to ptr */ false,
John McCallb45ae252011-10-05 07:41:44 +00001791 /* Complain */ true, DestRange, DestType,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00001792 diag::err_bad_cstyle_cast_overload);
John McCallb45ae252011-10-05 07:41:44 +00001793 if (SrcExpr.isInvalid())
1794 return;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001795 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001796
John McCalla180f042011-10-06 23:25:11 +00001797 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
1798 if (SrcExpr.isInvalid())
John McCallb45ae252011-10-05 07:41:44 +00001799 return;
John McCallb45ae252011-10-05 07:41:44 +00001800
1801 return;
Anton Yartsevd06fea82011-03-27 09:32:40 +00001802 }
1803
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001804 // If the type is dependent, we won't do any other semantic analysis now.
John McCallb45ae252011-10-05 07:41:44 +00001805 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent()) {
1806 assert(Kind == CK_Dependent);
1807 return;
John McCalldaa8e4e2010-11-15 09:13:47 +00001808 }
Benjamin Kramer5b4a40a2011-07-08 20:20:17 +00001809
John McCall6dbba4f2011-10-11 23:14:30 +00001810 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
1811 !isPlaceholder(BuiltinType::Overload)) {
John McCallb45ae252011-10-05 07:41:44 +00001812 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
1813 if (SrcExpr.isInvalid())
1814 return;
John Wiegley429bb272011-04-08 18:41:53 +00001815 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001816
John McCallfb8721c2011-04-10 19:13:55 +00001817 // AltiVec vector initialization with a single literal.
John McCallb45ae252011-10-05 07:41:44 +00001818 if (const VectorType *vecTy = DestType->getAs<VectorType>())
John McCallfb8721c2011-04-10 19:13:55 +00001819 if (vecTy->getVectorKind() == VectorType::AltiVecVector
John McCallb45ae252011-10-05 07:41:44 +00001820 && (SrcExpr.get()->getType()->isIntegerType()
1821 || SrcExpr.get()->getType()->isFloatingType())) {
John McCallfb8721c2011-04-10 19:13:55 +00001822 Kind = CK_VectorSplat;
John McCallb45ae252011-10-05 07:41:44 +00001823 return;
John McCallfb8721c2011-04-10 19:13:55 +00001824 }
1825
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001826 // C++ [expr.cast]p5: The conversions performed by
1827 // - a const_cast,
1828 // - a static_cast,
1829 // - a static_cast followed by a const_cast,
1830 // - a reinterpret_cast, or
1831 // - a reinterpret_cast followed by a const_cast,
1832 // can be performed using the cast notation of explicit type conversion.
1833 // [...] If a conversion can be interpreted in more than one of the ways
1834 // listed above, the interpretation that appears first in the list is used,
1835 // even if a cast resulting from that interpretation is ill-formed.
1836 // In plain language, this means trying a const_cast ...
1837 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCallb45ae252011-10-05 07:41:44 +00001838 TryCastResult tcr = TryConstCast(Self, SrcExpr.get(), DestType,
1839 /*CStyle*/true, msg);
Anders Carlssonda921fd2009-10-19 18:14:28 +00001840 if (tcr == TC_Success)
John McCall2de56d12010-08-25 11:45:40 +00001841 Kind = CK_NoOp;
Anders Carlssonda921fd2009-10-19 18:14:28 +00001842
John McCallf85e1932011-06-15 23:02:42 +00001843 Sema::CheckedConversionKind CCK
1844 = FunctionalStyle? Sema::CCK_FunctionalCast
1845 : Sema::CCK_CStyleCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001846 if (tcr == TC_NotApplicable) {
Nicola Gigante56f5d362011-11-28 12:21:57 +00001847 Expr *SrcExprOrig = SrcExpr.get();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001848 // ... or if that is not possible, a static_cast, ignoring const, ...
John McCallb45ae252011-10-05 07:41:44 +00001849 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
1850 msg, Kind, BasePath);
1851 if (SrcExpr.isInvalid())
1852 return;
1853
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001854 if (tcr == TC_NotApplicable) {
1855 // ... and finally a reinterpret_cast, ignoring const.
John McCallb45ae252011-10-05 07:41:44 +00001856 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
1857 OpRange, msg, Kind);
1858 if (SrcExpr.isInvalid())
1859 return;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001860 }
Nicola Gigante56f5d362011-11-28 12:21:57 +00001861
1862 CastNodesCreated = (SrcExpr.get() != SrcExprOrig);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001863 }
1864
John McCallb45ae252011-10-05 07:41:44 +00001865 if (Self.getLangOptions().ObjCAutoRefCount && tcr == TC_Success)
1866 checkObjCARCConversion(CCK);
John McCallf85e1932011-06-15 23:02:42 +00001867
Nick Lewycky43328e92010-11-09 00:19:31 +00001868 if (tcr != TC_Success && msg != 0) {
John McCallb45ae252011-10-05 07:41:44 +00001869 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor8e960432010-11-08 03:40:48 +00001870 DeclAccessPair Found;
John McCallb45ae252011-10-05 07:41:44 +00001871 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
1872 DestType,
1873 /*Complain*/ true,
Douglas Gregor8e960432010-11-08 03:40:48 +00001874 Found);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001875
Richard Trieu32ac00d2011-04-16 01:09:30 +00001876 assert(!Fn && "cast failed but able to resolve overload expression!!");
Nick Lewycky43328e92010-11-09 00:19:31 +00001877 (void)Fn;
John McCall79ab2c82011-02-14 18:34:10 +00001878
Nick Lewycky43328e92010-11-09 00:19:31 +00001879 } else {
John McCallb45ae252011-10-05 07:41:44 +00001880 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
1881 OpRange, SrcExpr.get(), DestType);
Douglas Gregor8e960432010-11-08 03:40:48 +00001882 }
John McCallb45ae252011-10-05 07:41:44 +00001883 } else if (Kind == CK_BitCast) {
1884 checkCastAlign();
Douglas Gregor8e960432010-11-08 03:40:48 +00001885 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001886
John McCallb45ae252011-10-05 07:41:44 +00001887 // Clear out SrcExpr if there was a fatal error.
John Wiegley429bb272011-04-08 18:41:53 +00001888 if (tcr != TC_Success)
John McCallb45ae252011-10-05 07:41:44 +00001889 SrcExpr = ExprError();
1890}
1891
John McCalla180f042011-10-06 23:25:11 +00001892/// Check the semantics of a C-style cast operation, in C.
1893void CastOperation::CheckCStyleCast() {
1894 assert(!Self.getLangOptions().CPlusPlus);
1895
John McCall5acb0c92011-10-17 18:40:02 +00001896 // C-style casts can resolve __unknown_any types.
1897 if (claimPlaceholder(BuiltinType::UnknownAny)) {
1898 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
1899 SrcExpr.get(), Kind,
1900 ValueKind, BasePath);
1901 return;
1902 }
John McCalla180f042011-10-06 23:25:11 +00001903
1904 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1905 // type needs to be scalar.
1906 if (DestType->isVoidType()) {
1907 // We don't necessarily do lvalue-to-rvalue conversions on this.
1908 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
1909 if (SrcExpr.isInvalid())
1910 return;
1911
1912 // Cast to void allows any expr type.
1913 Kind = CK_ToVoid;
1914 return;
1915 }
1916
1917 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
1918 if (SrcExpr.isInvalid())
1919 return;
1920 QualType SrcType = SrcExpr.get()->getType();
John McCall5acb0c92011-10-17 18:40:02 +00001921 assert(!SrcType->isPlaceholderType());
John McCalla180f042011-10-06 23:25:11 +00001922
1923 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1924 diag::err_typecheck_cast_to_incomplete)) {
1925 SrcExpr = ExprError();
1926 return;
1927 }
1928
1929 if (!DestType->isScalarType() && !DestType->isVectorType()) {
1930 const RecordType *DestRecordTy = DestType->getAs<RecordType>();
1931
1932 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
1933 // GCC struct/union extension: allow cast to self.
1934 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
1935 << DestType << SrcExpr.get()->getSourceRange();
1936 Kind = CK_NoOp;
1937 return;
1938 }
1939
1940 // GCC's cast to union extension.
1941 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
1942 RecordDecl *RD = DestRecordTy->getDecl();
1943 RecordDecl::field_iterator Field, FieldEnd;
1944 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
1945 Field != FieldEnd; ++Field) {
1946 if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) &&
1947 !Field->isUnnamedBitfield()) {
1948 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
1949 << SrcExpr.get()->getSourceRange();
1950 break;
1951 }
1952 }
1953 if (Field == FieldEnd) {
1954 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
1955 << SrcType << SrcExpr.get()->getSourceRange();
1956 SrcExpr = ExprError();
1957 return;
1958 }
1959 Kind = CK_ToUnion;
1960 return;
1961 }
1962
1963 // Reject any other conversions to non-scalar types.
1964 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
1965 << DestType << SrcExpr.get()->getSourceRange();
1966 SrcExpr = ExprError();
1967 return;
1968 }
1969
1970 // The type we're casting to is known to be a scalar or vector.
1971
1972 // Require the operand to be a scalar or vector.
1973 if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
1974 Self.Diag(SrcExpr.get()->getExprLoc(),
1975 diag::err_typecheck_expect_scalar_operand)
1976 << SrcType << SrcExpr.get()->getSourceRange();
1977 SrcExpr = ExprError();
1978 return;
1979 }
1980
1981 if (DestType->isExtVectorType()) {
1982 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.take(), Kind);
1983 return;
1984 }
1985
1986 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
1987 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
1988 (SrcType->isIntegerType() || SrcType->isFloatingType())) {
1989 Kind = CK_VectorSplat;
1990 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
1991 SrcExpr = ExprError();
1992 }
1993 return;
1994 }
1995
1996 if (SrcType->isVectorType()) {
1997 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
1998 SrcExpr = ExprError();
1999 return;
2000 }
2001
2002 // The source and target types are both scalars, i.e.
2003 // - arithmetic types (fundamental, enum, and complex)
2004 // - all kinds of pointers
2005 // Note that member pointers were filtered out with C++, above.
2006
2007 if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
2008 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
2009 SrcExpr = ExprError();
2010 return;
2011 }
2012
2013 // If either type is a pointer, the other type has to be either an
2014 // integer or a pointer.
2015 if (!DestType->isArithmeticType()) {
2016 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
2017 Self.Diag(SrcExpr.get()->getExprLoc(),
2018 diag::err_cast_pointer_from_non_pointer_int)
2019 << SrcType << SrcExpr.get()->getSourceRange();
2020 SrcExpr = ExprError();
2021 return;
2022 }
2023 } else if (!SrcType->isArithmeticType()) {
2024 if (!DestType->isIntegralType(Self.Context) &&
2025 DestType->isArithmeticType()) {
2026 Self.Diag(SrcExpr.get()->getLocStart(),
2027 diag::err_cast_pointer_to_non_pointer_int)
Abramo Bagnaraf7ce1942011-11-15 11:25:38 +00002028 << DestType << SrcExpr.get()->getSourceRange();
John McCalla180f042011-10-06 23:25:11 +00002029 SrcExpr = ExprError();
2030 return;
2031 }
2032 }
2033
2034 // ARC imposes extra restrictions on casts.
2035 if (Self.getLangOptions().ObjCAutoRefCount) {
2036 checkObjCARCConversion(Sema::CCK_CStyleCast);
2037 if (SrcExpr.isInvalid())
2038 return;
2039
2040 if (const PointerType *CastPtr = DestType->getAs<PointerType>()) {
2041 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
2042 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
2043 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
2044 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
2045 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
2046 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
2047 Self.Diag(SrcExpr.get()->getLocStart(),
2048 diag::err_typecheck_incompatible_ownership)
2049 << SrcType << DestType << Sema::AA_Casting
2050 << SrcExpr.get()->getSourceRange();
2051 return;
2052 }
2053 }
2054 }
2055 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
2056 Self.Diag(SrcExpr.get()->getLocStart(),
2057 diag::err_arc_convesion_of_weak_unavailable)
2058 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2059 SrcExpr = ExprError();
2060 return;
2061 }
2062 }
2063
2064 Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2065 if (SrcExpr.isInvalid())
2066 return;
2067
2068 if (Kind == CK_BitCast)
2069 checkCastAlign();
2070}
2071
2072ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
2073 TypeSourceInfo *CastTypeInfo,
2074 SourceLocation RPLoc,
2075 Expr *CastExpr) {
John McCallb45ae252011-10-05 07:41:44 +00002076 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2077 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2078 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
2079
Nicola Gigante56f5d362011-11-28 12:21:57 +00002080 bool CastNodesCreated = false;
John McCalla180f042011-10-06 23:25:11 +00002081 if (getLangOptions().CPlusPlus) {
Nicola Gigante56f5d362011-11-28 12:21:57 +00002082 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false, CastNodesCreated);
John McCalla180f042011-10-06 23:25:11 +00002083 } else {
2084 Op.CheckCStyleCast();
2085 }
2086
John McCallb45ae252011-10-05 07:41:44 +00002087 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00002088 return ExprError();
2089
Nicola Gigante56f5d362011-11-28 12:21:57 +00002090 // CheckCXXCStyleCast _may_ have already created the CStyleCastExpr
2091 // node. Let's check.
2092 if (CastNodesCreated) {
2093 if (CStyleCastExpr *Cast = dyn_cast<CStyleCastExpr>(Op.SrcExpr.get())){
2094 assert(!Cast->getTypeInfoAsWritten() &&
2095 "The explicit cast node created by CheckStaticCast "
2096 "has source type infos!");
2097 Cast->setTypeInfoAsWritten(CastTypeInfo);
2098 Cast->setLParenLoc(LPLoc);
2099 Cast->setRParenLoc(RPLoc);
2100 return Op.complete(Cast);
2101 }
2102 }
2103
John McCall5acb0c92011-10-17 18:40:02 +00002104 return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
2105 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
2106 &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
John McCallb45ae252011-10-05 07:41:44 +00002107}
2108
2109ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
2110 SourceLocation LPLoc,
2111 Expr *CastExpr,
2112 SourceLocation RPLoc) {
2113 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2114 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2115 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
2116
Nicola Gigante56f5d362011-11-28 12:21:57 +00002117 bool CastNodesCreated = false;
2118 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ true, CastNodesCreated);
John McCallb45ae252011-10-05 07:41:44 +00002119 if (Op.SrcExpr.isInvalid())
2120 return ExprError();
2121
Nicola Gigante56f5d362011-11-28 12:21:57 +00002122 // CheckCXXCStyleCast _may_ have already created the CXXFunctionalCastExpr
2123 // node. Let's check.
2124 if (CastNodesCreated) {
2125 if (CXXFunctionalCastExpr *Cast =
2126 dyn_cast<CXXFunctionalCastExpr>(Op.SrcExpr.get())){
2127 assert(!Cast->getTypeInfoAsWritten() &&
2128 "The explicit cast node created by CheckStaticCast "
2129 "has source type infos!");
2130 Cast->setTypeInfoAsWritten(CastTypeInfo);
2131 Cast->setTypeBeginLoc(Op.DestRange.getBegin());
2132 Cast->setRParenLoc(RPLoc);
2133 return Op.complete(Cast);
2134 }
2135 }
2136
John McCall5acb0c92011-10-17 18:40:02 +00002137 return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
2138 Op.ValueKind, CastTypeInfo, Op.DestRange.getBegin(),
2139 Op.Kind, Op.SrcExpr.take(), &Op.BasePath, RPLoc));
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002140}
Nicola Gigante56f5d362011-11-28 12:21:57 +00002141