blob: 1dbc9aaca59b610f5273fd09afa72a13d5042a28 [file] [log] [blame]
John McCalld8d3ced2011-10-11 17:38:55 +00001//===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===//
Sebastian Redl26d85b12008-11-05 21:50:06 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
John McCalld8d3ced2011-10-11 17:38:55 +000010// This file implements semantic analysis for cast expressions, including
11// 1) C-style casts like '(int) x'
12// 2) C++ functional casts like 'int(x)'
13// 3) C++ named casts like 'static_cast<int>(x)'
Sebastian Redl26d85b12008-11-05 21:50:06 +000014//
15//===----------------------------------------------------------------------===//
16
John McCall2d887082010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Sebastian Redl26d85b12008-11-05 21:50:06 +000018#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
John McCall437da052013-03-22 02:58:14 +000022#include "clang/AST/RecordLayout.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000024#include "clang/Sema/Initialization.h"
Sebastian Redl26d85b12008-11-05 21:50:06 +000025#include "llvm/ADT/SmallVector.h"
Sebastian Redle3dc28a2008-11-07 23:29:29 +000026#include <set>
Sebastian Redl26d85b12008-11-05 21:50:06 +000027using namespace clang;
28
Douglas Gregor8e960432010-11-08 03:40:48 +000029
Douglas Gregor8e960432010-11-08 03:40:48 +000030
Sebastian Redl9cc11e72009-07-25 15:41:38 +000031enum TryCastResult {
32 TC_NotApplicable, ///< The cast method is not applicable.
33 TC_Success, ///< The cast method is appropriate and successful.
34 TC_Failed ///< The cast method is appropriate, but failed. A
35 ///< diagnostic has been emitted.
36};
37
38enum CastType {
39 CT_Const, ///< const_cast
40 CT_Static, ///< static_cast
41 CT_Reinterpret, ///< reinterpret_cast
42 CT_Dynamic, ///< dynamic_cast
43 CT_CStyle, ///< (Type)expr
44 CT_Functional ///< Type(expr)
Sebastian Redl37d6de32008-11-08 13:00:26 +000045};
46
John McCallb45ae252011-10-05 07:41:44 +000047namespace {
48 struct CastOperation {
49 CastOperation(Sema &S, QualType destType, ExprResult src)
50 : Self(S), SrcExpr(src), DestType(destType),
51 ResultType(destType.getNonLValueExprType(S.Context)),
52 ValueKind(Expr::getValueKindForType(destType)),
John McCall5acb0c92011-10-17 18:40:02 +000053 Kind(CK_Dependent), IsARCUnbridgedCast(false) {
John McCalla180f042011-10-06 23:25:11 +000054
55 if (const BuiltinType *placeholder =
56 src.get()->getType()->getAsPlaceholderType()) {
57 PlaceholderKind = placeholder->getKind();
58 } else {
59 PlaceholderKind = (BuiltinType::Kind) 0;
60 }
61 }
Douglas Gregor8e960432010-11-08 03:40:48 +000062
John McCallb45ae252011-10-05 07:41:44 +000063 Sema &Self;
64 ExprResult SrcExpr;
65 QualType DestType;
66 QualType ResultType;
67 ExprValueKind ValueKind;
68 CastKind Kind;
John McCalla180f042011-10-06 23:25:11 +000069 BuiltinType::Kind PlaceholderKind;
John McCallb45ae252011-10-05 07:41:44 +000070 CXXCastPath BasePath;
John McCall5acb0c92011-10-17 18:40:02 +000071 bool IsARCUnbridgedCast;
Douglas Gregor8e960432010-11-08 03:40:48 +000072
John McCallb45ae252011-10-05 07:41:44 +000073 SourceRange OpRange;
74 SourceRange DestRange;
Douglas Gregor8e960432010-11-08 03:40:48 +000075
John McCalla180f042011-10-06 23:25:11 +000076 // Top-level semantics-checking routines.
John McCallb45ae252011-10-05 07:41:44 +000077 void CheckConstCast();
78 void CheckReinterpretCast();
Richard Smithc8d7f582011-11-29 22:48:16 +000079 void CheckStaticCast();
John McCallb45ae252011-10-05 07:41:44 +000080 void CheckDynamicCast();
Sebastian Redl6dc00f62012-02-12 18:41:05 +000081 void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
John McCalla180f042011-10-06 23:25:11 +000082 void CheckCStyleCast();
83
John McCall5acb0c92011-10-17 18:40:02 +000084 /// Complete an apparently-successful cast operation that yields
85 /// the given expression.
86 ExprResult complete(CastExpr *castExpr) {
87 // If this is an unbridged cast, wrap the result in an implicit
88 // cast that yields the unbridged-cast placeholder type.
89 if (IsARCUnbridgedCast) {
90 castExpr = ImplicitCastExpr::Create(Self.Context,
91 Self.Context.ARCUnbridgedCastTy,
92 CK_Dependent, castExpr, 0,
93 castExpr->getValueKind());
94 }
95 return Self.Owned(castExpr);
96 }
97
John McCalla180f042011-10-06 23:25:11 +000098 // Internal convenience methods.
99
100 /// Try to handle the given placeholder expression kind. Return
101 /// true if the source expression has the appropriate placeholder
102 /// kind. A placeholder can only be claimed once.
103 bool claimPlaceholder(BuiltinType::Kind K) {
104 if (PlaceholderKind != K) return false;
105
106 PlaceholderKind = (BuiltinType::Kind) 0;
107 return true;
108 }
109
110 bool isPlaceholder() const {
111 return PlaceholderKind != 0;
112 }
113 bool isPlaceholder(BuiltinType::Kind K) const {
114 return PlaceholderKind == K;
115 }
John McCallb45ae252011-10-05 07:41:44 +0000116
117 void checkCastAlign() {
118 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
119 }
120
121 void checkObjCARCConversion(Sema::CheckedConversionKind CCK) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000122 assert(Self.getLangOpts().ObjCAutoRefCount);
John McCall5acb0c92011-10-17 18:40:02 +0000123
John McCallb45ae252011-10-05 07:41:44 +0000124 Expr *src = SrcExpr.get();
John McCall5acb0c92011-10-17 18:40:02 +0000125 if (Self.CheckObjCARCConversion(OpRange, DestType, src, CCK) ==
126 Sema::ACR_unbridged)
127 IsARCUnbridgedCast = true;
John McCallb45ae252011-10-05 07:41:44 +0000128 SrcExpr = src;
129 }
John McCalla180f042011-10-06 23:25:11 +0000130
131 /// Check for and handle non-overload placeholder expressions.
132 void checkNonOverloadPlaceholders() {
133 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
134 return;
135
136 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
137 if (SrcExpr.isInvalid())
138 return;
139 PlaceholderKind = (BuiltinType::Kind) 0;
140 }
John McCallb45ae252011-10-05 07:41:44 +0000141 };
142}
Sebastian Redl37d6de32008-11-08 13:00:26 +0000143
John McCallf85e1932011-06-15 23:02:42 +0000144static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
145 bool CheckCVR, bool CheckObjCLifetime);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000146
147// The Try functions attempt a specific way of casting. If they succeed, they
148// return TC_Success. If their way of casting is not appropriate for the given
149// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
150// to emit if no other way succeeds. If their way of casting is appropriate but
151// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
152// they emit a specialized diagnostic.
153// All diagnostics returned by these functions must expect the same three
154// arguments:
155// %0: Cast Type (a value from the CastType enumeration)
156// %1: Source Type
157// %2: Destination Type
158static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000159 QualType DestType, bool CStyle,
160 CastKind &Kind,
Douglas Gregor88b22a42011-01-25 16:13:26 +0000161 CXXCastPath &BasePath,
162 unsigned &msg);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000163static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000164 QualType DestType, bool CStyle,
165 const SourceRange &OpRange,
166 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000167 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000168 CXXCastPath &BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000169static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
170 QualType DestType, bool CStyle,
171 const SourceRange &OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000172 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000173 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000174 CXXCastPath &BasePath);
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000175static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
176 CanQualType DestType, bool CStyle,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000177 const SourceRange &OpRange,
178 QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000179 QualType OrigDestType, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000180 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000181 CXXCastPath &BasePath);
John Wiegley429bb272011-04-08 18:41:53 +0000182static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
Anders Carlssoncee22422010-04-24 19:22:20 +0000183 QualType SrcType,
184 QualType DestType,bool CStyle,
185 const SourceRange &OpRange,
186 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000187 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000188 CXXCastPath &BasePath);
Anders Carlssoncee22422010-04-24 19:22:20 +0000189
John Wiegley429bb272011-04-08 18:41:53 +0000190static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
John McCallf85e1932011-06-15 23:02:42 +0000191 QualType DestType,
192 Sema::CheckedConversionKind CCK,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000193 const SourceRange &OpRange,
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000194 unsigned &msg, CastKind &Kind,
195 bool ListInitialization);
John Wiegley429bb272011-04-08 18:41:53 +0000196static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCallf85e1932011-06-15 23:02:42 +0000197 QualType DestType,
198 Sema::CheckedConversionKind CCK,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000199 const SourceRange &OpRange,
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000200 unsigned &msg, CastKind &Kind,
201 CXXCastPath &BasePath,
202 bool ListInitialization);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000203static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
204 bool CStyle, unsigned &msg);
John Wiegley429bb272011-04-08 18:41:53 +0000205static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000206 QualType DestType, bool CStyle,
207 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000208 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000209 CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +0000210
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000211
Sebastian Redl26d85b12008-11-05 21:50:06 +0000212/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
John McCall60d7b3a2010-08-24 06:29:42 +0000213ExprResult
Sebastian Redl26d85b12008-11-05 21:50:06 +0000214Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +0000215 SourceLocation LAngleBracketLoc, Declarator &D,
Sebastian Redl26d85b12008-11-05 21:50:06 +0000216 SourceLocation RAngleBracketLoc,
John McCallf312b1e2010-08-26 23:41:50 +0000217 SourceLocation LParenLoc, Expr *E,
Sebastian Redl26d85b12008-11-05 21:50:06 +0000218 SourceLocation RParenLoc) {
John McCallc89724c2010-01-15 19:13:16 +0000219
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +0000220 assert(!D.isInvalidType());
221
222 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
223 if (D.isInvalidType())
224 return ExprError();
225
David Blaikie4e4d0842012-03-11 07:00:24 +0000226 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +0000227 // Check that there are no default arguments (C++ only).
228 CheckExtraCXXDefaultArguments(D);
229 }
230
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000231 return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
John McCallc89724c2010-01-15 19:13:16 +0000232 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
233 SourceRange(LParenLoc, RParenLoc));
234}
235
John McCall60d7b3a2010-08-24 06:29:42 +0000236ExprResult
John McCallc89724c2010-01-15 19:13:16 +0000237Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John Wiegley429bb272011-04-08 18:41:53 +0000238 TypeSourceInfo *DestTInfo, Expr *E,
John McCallc89724c2010-01-15 19:13:16 +0000239 SourceRange AngleBrackets, SourceRange Parens) {
John Wiegley429bb272011-04-08 18:41:53 +0000240 ExprResult Ex = Owned(E);
John McCallc89724c2010-01-15 19:13:16 +0000241 QualType DestType = DestTInfo->getType();
242
Douglas Gregor9103bb22008-12-17 22:52:20 +0000243 // If the type is dependent, we won't do the semantic analysis now.
244 // FIXME: should we check this in a more fine-grained manner?
John Wiegley429bb272011-04-08 18:41:53 +0000245 bool TypeDependent = DestType->isDependentType() || Ex.get()->isTypeDependent();
Douglas Gregor9103bb22008-12-17 22:52:20 +0000246
John McCallb45ae252011-10-05 07:41:44 +0000247 CastOperation Op(*this, DestType, E);
248 Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
249 Op.DestRange = AngleBrackets;
John McCalla21e06c2010-11-26 10:57:22 +0000250
Sebastian Redl26d85b12008-11-05 21:50:06 +0000251 switch (Kind) {
John McCalldaa8e4e2010-11-15 09:13:47 +0000252 default: llvm_unreachable("Unknown C++ cast!");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000253
254 case tok::kw_const_cast:
John Wiegley429bb272011-04-08 18:41:53 +0000255 if (!TypeDependent) {
John McCallb45ae252011-10-05 07:41:44 +0000256 Op.CheckConstCast();
257 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000258 return ExprError();
259 }
John McCall5acb0c92011-10-17 18:40:02 +0000260 return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
261 Op.ValueKind, Op.SrcExpr.take(), DestTInfo,
Fariborz Jahanianf799ae12013-02-22 22:02:53 +0000262 OpLoc, Parens.getEnd(),
263 AngleBrackets));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000264
Anders Carlsson714179b2009-08-02 19:07:59 +0000265 case tok::kw_dynamic_cast: {
John Wiegley429bb272011-04-08 18:41:53 +0000266 if (!TypeDependent) {
John McCallb45ae252011-10-05 07:41:44 +0000267 Op.CheckDynamicCast();
268 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000269 return ExprError();
270 }
John McCall5acb0c92011-10-17 18:40:02 +0000271 return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
272 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
273 &Op.BasePath, DestTInfo,
Fariborz Jahanianf799ae12013-02-22 22:02:53 +0000274 OpLoc, Parens.getEnd(),
275 AngleBrackets));
Anders Carlsson714179b2009-08-02 19:07:59 +0000276 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000277 case tok::kw_reinterpret_cast: {
John Wiegley429bb272011-04-08 18:41:53 +0000278 if (!TypeDependent) {
John McCallb45ae252011-10-05 07:41:44 +0000279 Op.CheckReinterpretCast();
280 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000281 return ExprError();
282 }
John McCall5acb0c92011-10-17 18:40:02 +0000283 return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
284 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
285 0, DestTInfo, OpLoc,
Fariborz Jahanianf799ae12013-02-22 22:02:53 +0000286 Parens.getEnd(),
287 AngleBrackets));
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000288 }
Anders Carlssoncdb61972009-08-07 22:21:05 +0000289 case tok::kw_static_cast: {
John Wiegley429bb272011-04-08 18:41:53 +0000290 if (!TypeDependent) {
Richard Smithc8d7f582011-11-29 22:48:16 +0000291 Op.CheckStaticCast();
John McCallb45ae252011-10-05 07:41:44 +0000292 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000293 return ExprError();
294 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000295
John McCall5acb0c92011-10-17 18:40:02 +0000296 return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
297 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
298 &Op.BasePath, DestTInfo,
Fariborz Jahanianf799ae12013-02-22 22:02:53 +0000299 OpLoc, Parens.getEnd(),
300 AngleBrackets));
Anders Carlssoncdb61972009-08-07 22:21:05 +0000301 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000302 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000303}
304
John McCall79ab2c82011-02-14 18:34:10 +0000305/// Try to diagnose a failed overloaded cast. Returns true if
306/// diagnostics were emitted.
307static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
308 SourceRange range, Expr *src,
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000309 QualType destType,
310 bool listInitialization) {
John McCall79ab2c82011-02-14 18:34:10 +0000311 switch (CT) {
312 // These cast kinds don't consider user-defined conversions.
313 case CT_Const:
314 case CT_Reinterpret:
315 case CT_Dynamic:
316 return false;
317
318 // These do.
319 case CT_Static:
320 case CT_CStyle:
321 case CT_Functional:
322 break;
323 }
324
325 QualType srcType = src->getType();
326 if (!destType->isRecordType() && !srcType->isRecordType())
327 return false;
328
329 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
330 InitializationKind initKind
John McCallf85e1932011-06-15 23:02:42 +0000331 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000332 range, listInitialization)
Sebastian Redl3a45c0e2012-02-12 16:37:36 +0000333 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000334 listInitialization)
Richard Smithc8d7f582011-11-29 22:48:16 +0000335 : InitializationKind::CreateCast(/*type range?*/ range);
John McCall79ab2c82011-02-14 18:34:10 +0000336 InitializationSequence sequence(S, entity, initKind, &src, 1);
337
Sebastian Redl383616c2011-06-05 12:23:28 +0000338 assert(sequence.Failed() && "initialization succeeded on second try?");
John McCall79ab2c82011-02-14 18:34:10 +0000339 switch (sequence.getFailureKind()) {
340 default: return false;
341
342 case InitializationSequence::FK_ConstructorOverloadFailed:
343 case InitializationSequence::FK_UserConversionOverloadFailed:
344 break;
345 }
346
347 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
348
349 unsigned msg = 0;
350 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
351
352 switch (sequence.getFailedOverloadResult()) {
353 case OR_Success: llvm_unreachable("successful failed overload");
John McCall79ab2c82011-02-14 18:34:10 +0000354 case OR_No_Viable_Function:
355 if (candidates.empty())
356 msg = diag::err_ovl_no_conversion_in_cast;
357 else
358 msg = diag::err_ovl_no_viable_conversion_in_cast;
359 howManyCandidates = OCD_AllCandidates;
360 break;
361
362 case OR_Ambiguous:
363 msg = diag::err_ovl_ambiguous_conversion_in_cast;
364 howManyCandidates = OCD_ViableCandidates;
365 break;
366
367 case OR_Deleted:
368 msg = diag::err_ovl_deleted_conversion_in_cast;
369 howManyCandidates = OCD_ViableCandidates;
370 break;
371 }
372
373 S.Diag(range.getBegin(), msg)
374 << CT << srcType << destType
375 << range << src->getSourceRange();
376
Ahmed Charles13a140c2012-02-25 11:00:22 +0000377 candidates.NoteCandidates(S, howManyCandidates, src);
John McCall79ab2c82011-02-14 18:34:10 +0000378
379 return true;
380}
381
382/// Diagnose a failed cast.
383static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000384 SourceRange opRange, Expr *src, QualType destType,
385 bool listInitialization) {
John McCall864c0412011-04-26 20:42:42 +0000386 if (src->getType() == S.Context.BoundMemberTy) {
387 (void) S.CheckPlaceholderExpr(src); // will always fail
388 return;
389 }
390
John McCall79ab2c82011-02-14 18:34:10 +0000391 if (msg == diag::err_bad_cxx_cast_generic &&
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000392 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
393 listInitialization))
John McCall79ab2c82011-02-14 18:34:10 +0000394 return;
395
396 S.Diag(opRange.getBegin(), msg) << castType
397 << src->getType() << destType << opRange << src->getSourceRange();
398}
399
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000400/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
401/// this removes one level of indirection from both types, provided that they're
402/// the same kind of pointer (plain or to-member). Unlike the Sema function,
403/// this one doesn't care if the two pointers-to-member don't point into the
404/// same class. This is because CastsAwayConstness doesn't care.
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000405static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000406 const PointerType *T1PtrType = T1->getAs<PointerType>(),
407 *T2PtrType = T2->getAs<PointerType>();
408 if (T1PtrType && T2PtrType) {
409 T1 = T1PtrType->getPointeeType();
410 T2 = T2PtrType->getPointeeType();
411 return true;
412 }
Fariborz Jahanian72a86592010-02-03 20:32:31 +0000413 const ObjCObjectPointerType *T1ObjCPtrType =
414 T1->getAs<ObjCObjectPointerType>(),
415 *T2ObjCPtrType =
416 T2->getAs<ObjCObjectPointerType>();
417 if (T1ObjCPtrType) {
418 if (T2ObjCPtrType) {
419 T1 = T1ObjCPtrType->getPointeeType();
420 T2 = T2ObjCPtrType->getPointeeType();
421 return true;
422 }
423 else if (T2PtrType) {
424 T1 = T1ObjCPtrType->getPointeeType();
425 T2 = T2PtrType->getPointeeType();
426 return true;
427 }
428 }
429 else if (T2ObjCPtrType) {
430 if (T1PtrType) {
431 T2 = T2ObjCPtrType->getPointeeType();
432 T1 = T1PtrType->getPointeeType();
433 return true;
434 }
435 }
436
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000437 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
438 *T2MPType = T2->getAs<MemberPointerType>();
439 if (T1MPType && T2MPType) {
440 T1 = T1MPType->getPointeeType();
441 T2 = T2MPType->getPointeeType();
442 return true;
443 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000444
445 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
446 *T2BPType = T2->getAs<BlockPointerType>();
447 if (T1BPType && T2BPType) {
448 T1 = T1BPType->getPointeeType();
449 T2 = T2BPType->getPointeeType();
450 return true;
451 }
452
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000453 return false;
454}
455
Sebastian Redldb647282009-01-27 23:18:31 +0000456/// CastsAwayConstness - Check if the pointer conversion from SrcType to
457/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
458/// the cast checkers. Both arguments must denote pointer (possibly to member)
459/// types.
John McCallf85e1932011-06-15 23:02:42 +0000460///
461/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
462///
463/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000464static bool
John McCallf85e1932011-06-15 23:02:42 +0000465CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
466 bool CheckCVR, bool CheckObjCLifetime) {
467 // If the only checking we care about is for Objective-C lifetime qualifiers,
468 // and we're not in ARC mode, there's nothing to check.
469 if (!CheckCVR && CheckObjCLifetime &&
David Blaikie4e4d0842012-03-11 07:00:24 +0000470 !Self.Context.getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +0000471 return false;
472
Sebastian Redldb647282009-01-27 23:18:31 +0000473 // Casting away constness is defined in C++ 5.2.11p8 with reference to
474 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
475 // the rules are non-trivial. So first we construct Tcv *...cv* as described
476 // in C++ 5.2.11p8.
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000477 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
478 SrcType->isBlockPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000479 "Source type is not pointer or pointer to member.");
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000480 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
481 DestType->isBlockPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000482 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000483
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000484 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
485 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000486 SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000487
Douglas Gregord4c5f842011-04-15 17:59:54 +0000488 // Find the qualifiers. We only care about cvr-qualifiers for the
489 // purpose of this check, because other qualifiers (address spaces,
490 // Objective-C GC, etc.) are part of the type's identity.
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000491 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCallf85e1932011-06-15 23:02:42 +0000492 // Determine the relevant qualifiers at this level.
493 Qualifiers SrcQuals, DestQuals;
Anders Carlsson52647c62010-06-04 22:47:55 +0000494 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
Anders Carlsson52647c62010-06-04 22:47:55 +0000495 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
John McCallf85e1932011-06-15 23:02:42 +0000496
497 Qualifiers RetainedSrcQuals, RetainedDestQuals;
498 if (CheckCVR) {
499 RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
500 RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
501 }
502
503 if (CheckObjCLifetime &&
504 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
505 return true;
506
507 cv1.push_back(RetainedSrcQuals);
508 cv2.push_back(RetainedDestQuals);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000509 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000510 if (cv1.empty())
511 return false;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000512
513 // Construct void pointers with those qualifiers (in reverse order of
514 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000515 QualType SrcConstruct = Self.Context.VoidTy;
516 QualType DestConstruct = Self.Context.VoidTy;
John McCall0953e762009-09-24 19:53:00 +0000517 ASTContext &Context = Self.Context;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000518 for (SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
John McCall0953e762009-09-24 19:53:00 +0000519 i2 = cv2.rbegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000520 i1 != cv1.rend(); ++i1, ++i2) {
John McCall0953e762009-09-24 19:53:00 +0000521 SrcConstruct
522 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
523 DestConstruct
524 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000525 }
526
527 // Test if they're compatible.
John McCallf85e1932011-06-15 23:02:42 +0000528 bool ObjCLifetimeConversion;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000529 return SrcConstruct != DestConstruct &&
John McCallf85e1932011-06-15 23:02:42 +0000530 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
531 ObjCLifetimeConversion);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000532}
533
Sebastian Redl26d85b12008-11-05 21:50:06 +0000534/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
535/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
536/// checked downcasts in class hierarchies.
John McCallb45ae252011-10-05 07:41:44 +0000537void CastOperation::CheckDynamicCast() {
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000538 if (ValueKind == VK_RValue)
Eli Friedman7a420df2011-10-31 20:59:03 +0000539 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000540 else if (isPlaceholder())
541 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
542 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
543 return;
Eli Friedman7a420df2011-10-31 20:59:03 +0000544
John McCallb45ae252011-10-05 07:41:44 +0000545 QualType OrigSrcType = SrcExpr.get()->getType();
546 QualType DestType = Self.Context.getCanonicalType(this->DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000547
548 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
549 // or "pointer to cv void".
550
551 QualType DestPointee;
Ted Kremenek6217b802009-07-29 21:53:49 +0000552 const PointerType *DestPointer = DestType->getAs<PointerType>();
John McCallf89e55a2010-11-18 06:31:45 +0000553 const ReferenceType *DestReference = 0;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000554 if (DestPointer) {
555 DestPointee = DestPointer->getPointeeType();
John McCallf89e55a2010-11-18 06:31:45 +0000556 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000557 DestPointee = DestReference->getPointeeType();
558 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000559 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
John McCallb45ae252011-10-05 07:41:44 +0000560 << this->DestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000561 return;
562 }
563
Ted Kremenek6217b802009-07-29 21:53:49 +0000564 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000565 if (DestPointee->isVoidType()) {
566 assert(DestPointer && "Reference to void is not possible");
567 } else if (DestRecord) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000568 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregord10099e2012-05-04 16:32:21 +0000569 diag::err_bad_dynamic_cast_incomplete,
570 DestRange))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000571 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000572 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000573 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000574 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000575 return;
576 }
577
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000578 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
579 // complete class type, [...]. If T is an lvalue reference type, v shall be
Douglas Gregordc843f22011-01-22 00:06:57 +0000580 // an lvalue of a complete class type, [...]. If T is an rvalue reference
581 // type, v shall be an expression having a complete class type, [...]
Sebastian Redl37d6de32008-11-08 13:00:26 +0000582 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000583 QualType SrcPointee;
584 if (DestPointer) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000585 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000586 SrcPointee = SrcPointer->getPointeeType();
587 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000588 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
John Wiegley429bb272011-04-08 18:41:53 +0000589 << OrigSrcType << SrcExpr.get()->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000590 return;
591 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000592 } else if (DestReference->isLValueReferenceType()) {
John Wiegley429bb272011-04-08 18:41:53 +0000593 if (!SrcExpr.get()->isLValue()) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000594 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
John McCallb45ae252011-10-05 07:41:44 +0000595 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000596 }
597 SrcPointee = SrcType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000598 } else {
599 SrcPointee = SrcType;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000600 }
601
Ted Kremenek6217b802009-07-29 21:53:49 +0000602 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000603 if (SrcRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000604 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregord10099e2012-05-04 16:32:21 +0000605 diag::err_bad_dynamic_cast_incomplete,
606 SrcExpr.get()))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000607 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000608 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000609 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
John Wiegley429bb272011-04-08 18:41:53 +0000610 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000611 return;
612 }
613
614 assert((DestPointer || DestReference) &&
615 "Bad destination non-ptr/ref slipped through.");
616 assert((DestRecord || DestPointee->isVoidType()) &&
617 "Bad destination pointee slipped through.");
618 assert(SrcRecord && "Bad source pointee slipped through.");
619
620 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
621 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +0000622 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
John McCallb45ae252011-10-05 07:41:44 +0000623 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000624 return;
625 }
626
627 // C++ 5.2.7p3: If the type of v is the same as the required result type,
628 // [except for cv].
629 if (DestRecord == SrcRecord) {
John McCall2de56d12010-08-25 11:45:40 +0000630 Kind = CK_NoOp;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000631 return;
632 }
633
634 // C++ 5.2.7p5
635 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000636 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000637 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
638 OpRange.getBegin(), OpRange,
639 &BasePath))
640 return;
641
John McCall2de56d12010-08-25 11:45:40 +0000642 Kind = CK_DerivedToBase;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000643
644 // If we are casting to or through a virtual base class, we need a
645 // vtable.
646 if (Self.BasePathInvolvesVirtualBase(BasePath))
647 Self.MarkVTableUsed(OpRange.getBegin(),
648 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000649 return;
650 }
651
652 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor952b0172010-02-11 01:04:33 +0000653 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000654 assert(SrcDecl && "Definition missing");
655 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000656 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
John Wiegley429bb272011-04-08 18:41:53 +0000657 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000658 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000659 Self.MarkVTableUsed(OpRange.getBegin(),
660 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000661
662 // Done. Everything else is run-time checks.
John McCall2de56d12010-08-25 11:45:40 +0000663 Kind = CK_Dynamic;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000664}
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000665
666/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
667/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
668/// like this:
669/// const char *str = "literal";
670/// legacy_function(const_cast\<char*\>(str));
John McCallb45ae252011-10-05 07:41:44 +0000671void CastOperation::CheckConstCast() {
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000672 if (ValueKind == VK_RValue)
John Wiegley429bb272011-04-08 18:41:53 +0000673 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000674 else if (isPlaceholder())
675 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
676 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
677 return;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000678
679 unsigned msg = diag::err_bad_cxx_cast_generic;
John Wiegley429bb272011-04-08 18:41:53 +0000680 if (TryConstCast(Self, SrcExpr.get(), DestType, /*CStyle*/false, msg) != TC_Success
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000681 && msg != 0)
682 Self.Diag(OpRange.getBegin(), msg) << CT_Const
John Wiegley429bb272011-04-08 18:41:53 +0000683 << SrcExpr.get()->getType() << DestType << OpRange;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000684}
685
John McCall437da052013-03-22 02:58:14 +0000686/// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
687/// or downcast between respective pointers or references.
688static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
689 QualType DestType,
690 SourceRange OpRange) {
691 QualType SrcType = SrcExpr->getType();
692 // When casting from pointer or reference, get pointee type; use original
693 // type otherwise.
694 const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
695 const CXXRecordDecl *SrcRD =
696 SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
697
698 // Examining subobjects for records is only possible if the complete
699 // definition is available. Also, template instantiation is not allowed here.
700 if(!SrcRD || !SrcRD->isCompleteDefinition())
701 return;
702
703 const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
704
705 if(!DestRD || !DestRD->isCompleteDefinition())
706 return;
707
708 enum {
709 ReinterpretUpcast,
710 ReinterpretDowncast
711 } ReinterpretKind;
712
713 CXXBasePaths BasePaths;
714
715 if (SrcRD->isDerivedFrom(DestRD, BasePaths))
716 ReinterpretKind = ReinterpretUpcast;
717 else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
718 ReinterpretKind = ReinterpretDowncast;
719 else
720 return;
721
722 bool VirtualBase = true;
723 bool NonZeroOffset = false;
724 for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
725 E = BasePaths.end();
726 I != E; ++I) {
727 const CXXBasePath &Path = *I;
728 CharUnits Offset = CharUnits::Zero();
729 bool IsVirtual = false;
730 for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
731 IElem != EElem; ++IElem) {
732 IsVirtual = IElem->Base->isVirtual();
733 if (IsVirtual)
734 break;
735 const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
736 assert(BaseRD && "Base type should be a valid unqualified class type");
737 const ASTRecordLayout &DerivedLayout =
738 Self.Context.getASTRecordLayout(IElem->Class);
739 Offset += DerivedLayout.getBaseClassOffset(BaseRD);
740 }
741 if (!IsVirtual) {
742 // Don't warn if any path is a non-virtually derived base at offset zero.
743 if (Offset.isZero())
744 return;
745 // Offset makes sense only for non-virtual bases.
746 else
747 NonZeroOffset = true;
748 }
749 VirtualBase = VirtualBase && IsVirtual;
750 }
751
752 assert((VirtualBase || NonZeroOffset) &&
753 "Should have returned if has non-virtual base with zero offset");
754
755 QualType BaseType =
756 ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
757 QualType DerivedType =
758 ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
759
760 Self.Diag(OpRange.getBegin(), diag::warn_reinterpret_different_from_static)
761 << DerivedType << BaseType << !VirtualBase << ReinterpretKind;
762 Self.Diag(OpRange.getBegin(), diag::note_reinterpret_updowncast_use_static)
763 << ReinterpretKind;
764
765 // TODO: emit fixits. This requires passing operator SourceRange from Parser.
766}
767
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000768/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
769/// valid.
770/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
771/// like this:
772/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
John McCallb45ae252011-10-05 07:41:44 +0000773void CastOperation::CheckReinterpretCast() {
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000774 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
John Wiegley429bb272011-04-08 18:41:53 +0000775 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000776 else
777 checkNonOverloadPlaceholders();
778 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
779 return;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000780
781 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCallf85e1932011-06-15 23:02:42 +0000782 TryCastResult tcr =
783 TryReinterpretCast(Self, SrcExpr, DestType,
784 /*CStyle*/false, OpRange, msg, Kind);
785 if (tcr != TC_Success && msg != 0)
Douglas Gregor8e960432010-11-08 03:40:48 +0000786 {
John Wiegley429bb272011-04-08 18:41:53 +0000787 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
788 return;
789 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor8e960432010-11-08 03:40:48 +0000790 //FIXME: &f<int>; is overloaded and resolvable
791 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
John Wiegley429bb272011-04-08 18:41:53 +0000792 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
Douglas Gregor8e960432010-11-08 03:40:48 +0000793 << DestType << OpRange;
John Wiegley429bb272011-04-08 18:41:53 +0000794 Self.NoteAllOverloadCandidates(SrcExpr.get());
Douglas Gregor8e960432010-11-08 03:40:48 +0000795
John McCall79ab2c82011-02-14 18:34:10 +0000796 } else {
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000797 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
798 DestType, /*listInitialization=*/false);
Douglas Gregor8e960432010-11-08 03:40:48 +0000799 }
John McCall437da052013-03-22 02:58:14 +0000800 } else if (tcr == TC_Success) {
801 if (Self.getLangOpts().ObjCAutoRefCount)
802 checkObjCARCConversion(Sema::CCK_OtherCast);
803 DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
John McCallf85e1932011-06-15 23:02:42 +0000804 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000805}
806
807
808/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
809/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
810/// implicit conversions explicit and getting rid of data loss warnings.
Richard Smithc8d7f582011-11-29 22:48:16 +0000811void CastOperation::CheckStaticCast() {
John McCalla180f042011-10-06 23:25:11 +0000812 if (isPlaceholder()) {
813 checkNonOverloadPlaceholders();
814 if (SrcExpr.isInvalid())
815 return;
816 }
817
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000818 // This test is outside everything else because it's the only case where
819 // a non-lvalue-reference target type does not lead to decay.
820 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000821 if (DestType->isVoidType()) {
John McCalla180f042011-10-06 23:25:11 +0000822 Kind = CK_ToVoid;
823
824 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall6dbba4f2011-10-11 23:14:30 +0000825 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000826 false, // Decay Function to ptr
827 true, // Complain
828 OpRange, DestType, diag::err_bad_static_cast_overload);
John McCall6dbba4f2011-10-11 23:14:30 +0000829 if (SrcExpr.isInvalid())
830 return;
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000831 }
John McCalla180f042011-10-06 23:25:11 +0000832
833 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000834 return;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000835 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000836
John McCall6dbba4f2011-10-11 23:14:30 +0000837 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
838 !isPlaceholder(BuiltinType::Overload)) {
John Wiegley429bb272011-04-08 18:41:53 +0000839 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
840 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
841 return;
842 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000843
844 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCallf85e1932011-06-15 23:02:42 +0000845 TryCastResult tcr
Richard Smithc8d7f582011-11-29 22:48:16 +0000846 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000847 Kind, BasePath, /*ListInitialization=*/false);
John McCallf85e1932011-06-15 23:02:42 +0000848 if (tcr != TC_Success && msg != 0) {
John Wiegley429bb272011-04-08 18:41:53 +0000849 if (SrcExpr.isInvalid())
850 return;
851 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
852 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
Douglas Gregor8e960432010-11-08 03:40:48 +0000853 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
Douglas Gregor4c9be892011-02-28 20:01:57 +0000854 << oe->getName() << DestType << OpRange
855 << oe->getQualifierLoc().getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +0000856 Self.NoteAllOverloadCandidates(SrcExpr.get());
John McCall79ab2c82011-02-14 18:34:10 +0000857 } else {
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000858 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
859 /*listInitialization=*/false);
Douglas Gregor8e960432010-11-08 03:40:48 +0000860 }
John McCallf85e1932011-06-15 23:02:42 +0000861 } else if (tcr == TC_Success) {
862 if (Kind == CK_BitCast)
John McCallb45ae252011-10-05 07:41:44 +0000863 checkCastAlign();
David Blaikie4e4d0842012-03-11 07:00:24 +0000864 if (Self.getLangOpts().ObjCAutoRefCount)
Richard Smithc8d7f582011-11-29 22:48:16 +0000865 checkObjCARCConversion(Sema::CCK_OtherCast);
John McCallb45ae252011-10-05 07:41:44 +0000866 } else if (Kind == CK_BitCast) {
867 checkCastAlign();
Douglas Gregor8e960432010-11-08 03:40:48 +0000868 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000869}
870
871/// TryStaticCast - Check if a static cast can be performed, and do so if
872/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
873/// and casting away constness.
John Wiegley429bb272011-04-08 18:41:53 +0000874static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCallf85e1932011-06-15 23:02:42 +0000875 QualType DestType,
876 Sema::CheckedConversionKind CCK,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000877 const SourceRange &OpRange, unsigned &msg,
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000878 CastKind &Kind, CXXCastPath &BasePath,
879 bool ListInitialization) {
John McCallf85e1932011-06-15 23:02:42 +0000880 // Determine whether we have the semantics of a C-style cast.
881 bool CStyle
882 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
883
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000884 // The order the tests is not entirely arbitrary. There is one conversion
885 // that can be handled in two different ways. Given:
886 // struct A {};
887 // struct B : public A {
888 // B(); B(const A&);
889 // };
890 // const A &a = B();
891 // the cast static_cast<const B&>(a) could be seen as either a static
892 // reference downcast, or an explicit invocation of the user-defined
893 // conversion using B's conversion constructor.
894 // DR 427 specifies that the downcast is to be applied here.
895
896 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
897 // Done outside this function.
898
899 TryCastResult tcr;
900
901 // C++ 5.2.9p5, reference downcast.
902 // See the function for details.
903 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000904 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
905 OpRange, msg, Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000906 if (tcr != TC_NotApplicable)
907 return tcr;
908
Douglas Gregordc843f22011-01-22 00:06:57 +0000909 // C++0x [expr.static.cast]p3:
910 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
911 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000912 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
913 BasePath, msg);
Douglas Gregor88b22a42011-01-25 16:13:26 +0000914 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000915 return tcr;
916
917 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
918 // [...] if the declaration "T t(e);" is well-formed, [...].
John McCallf85e1932011-06-15 23:02:42 +0000919 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000920 Kind, ListInitialization);
John Wiegley429bb272011-04-08 18:41:53 +0000921 if (SrcExpr.isInvalid())
922 return TC_Failed;
Anders Carlsson3c31a392009-09-26 00:12:34 +0000923 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000924 return tcr;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000925
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000926 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
927 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
928 // conversions, subject to further restrictions.
929 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
930 // of qualification conversions impossible.
931 // In the CStyle case, the earlier attempt to const_cast should have taken
932 // care of reverse qualification conversions.
933
John Wiegley429bb272011-04-08 18:41:53 +0000934 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000935
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000936 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
Douglas Gregor1e856d92011-02-18 03:01:41 +0000937 // converted to an integral type. [...] A value of a scoped enumeration type
938 // can also be explicitly converted to a floating-point type [...].
939 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
940 if (Enum->getDecl()->isScoped()) {
941 if (DestType->isBooleanType()) {
942 Kind = CK_IntegralToBoolean;
943 return TC_Success;
944 } else if (DestType->isIntegralType(Self.Context)) {
945 Kind = CK_IntegralCast;
946 return TC_Success;
947 } else if (DestType->isRealFloatingType()) {
948 Kind = CK_IntegralToFloating;
949 return TC_Success;
950 }
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000951 }
952 }
Douglas Gregor1e856d92011-02-18 03:01:41 +0000953
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000954 // Reverse integral promotion/conversion. All such conversions are themselves
955 // again integral promotions or conversions and are thus already handled by
956 // p2 (TryDirectInitialization above).
957 // (Note: any data loss warnings should be suppressed.)
958 // The exception is the reverse of enum->integer, i.e. integer->enum (and
959 // enum->enum). See also C++ 5.2.9p7.
960 // The same goes for reverse floating point promotion/conversion and
961 // floating-integral conversions. Again, only floating->enum is relevant.
962 if (DestType->isEnumeralType()) {
Eli Friedmancc2fca22011-09-02 17:38:59 +0000963 if (SrcType->isIntegralOrEnumerationType()) {
John McCall2de56d12010-08-25 11:45:40 +0000964 Kind = CK_IntegralCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000965 return TC_Success;
Eli Friedmancc2fca22011-09-02 17:38:59 +0000966 } else if (SrcType->isRealFloatingType()) {
967 Kind = CK_FloatingToIntegral;
968 return TC_Success;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000969 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000970 }
971
972 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
973 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000974 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000975 Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000976 if (tcr != TC_NotApplicable)
977 return tcr;
978
979 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
980 // conversion. C++ 5.2.9p9 has additional information.
981 // DR54's access restrictions apply here also.
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000982 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssoncee22422010-04-24 19:22:20 +0000983 OpRange, msg, Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000984 if (tcr != TC_NotApplicable)
985 return tcr;
986
987 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
988 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
989 // just the usual constness stuff.
Ted Kremenek6217b802009-07-29 21:53:49 +0000990 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000991 QualType SrcPointee = SrcPointer->getPointeeType();
992 if (SrcPointee->isVoidType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000993 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000994 QualType DestPointee = DestPointer->getPointeeType();
995 if (DestPointee->isIncompleteOrObjectType()) {
996 // This is definitely the intended conversion, but it might fail due
John McCallf85e1932011-06-15 23:02:42 +0000997 // to a qualifier violation. Note that we permit Objective-C lifetime
998 // and GC qualifier mismatches here.
999 if (!CStyle) {
1000 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
1001 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
1002 DestPointeeQuals.removeObjCGCAttr();
1003 DestPointeeQuals.removeObjCLifetime();
1004 SrcPointeeQuals.removeObjCGCAttr();
1005 SrcPointeeQuals.removeObjCLifetime();
1006 if (DestPointeeQuals != SrcPointeeQuals &&
1007 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
1008 msg = diag::err_bad_cxx_cast_qualifiers_away;
1009 return TC_Failed;
1010 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001011 }
John McCall2de56d12010-08-25 11:45:40 +00001012 Kind = CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001013 return TC_Success;
1014 }
1015 }
Fariborz Jahanian2f6c5502010-05-10 23:46:53 +00001016 else if (DestType->isObjCObjectPointerType()) {
1017 // allow both c-style cast and static_cast of objective-c pointers as
1018 // they are pervasive.
John McCall1d9b3b22011-09-09 05:25:32 +00001019 Kind = CK_CPointerToObjCPointerCast;
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001020 return TC_Success;
1021 }
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +00001022 else if (CStyle && DestType->isBlockPointerType()) {
1023 // allow c-style cast of void * to block pointers.
John McCall2de56d12010-08-25 11:45:40 +00001024 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +00001025 return TC_Success;
1026 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001027 }
1028 }
Fariborz Jahanian65267b22010-05-12 18:16:59 +00001029 // Allow arbitray objective-c pointer conversion with static casts.
1030 if (SrcType->isObjCObjectPointerType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001031 DestType->isObjCObjectPointerType()) {
1032 Kind = CK_BitCast;
Fariborz Jahanian65267b22010-05-12 18:16:59 +00001033 return TC_Success;
John McCalldaa8e4e2010-11-15 09:13:47 +00001034 }
Fariborz Jahanian65267b22010-05-12 18:16:59 +00001035
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001036 // We tried everything. Everything! Nothing works! :-(
1037 return TC_NotApplicable;
1038}
1039
1040/// Tests whether a conversion according to N2844 is valid.
1041TryCastResult
1042TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Douglas Gregor8ec14e62011-01-26 21:04:06 +00001043 bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
1044 unsigned &msg) {
Douglas Gregordc843f22011-01-22 00:06:57 +00001045 // C++0x [expr.static.cast]p3:
1046 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
1047 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenek6217b802009-07-29 21:53:49 +00001048 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001049 if (!R)
1050 return TC_NotApplicable;
1051
Douglas Gregordc843f22011-01-22 00:06:57 +00001052 if (!SrcExpr->isGLValue())
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001053 return TC_NotApplicable;
1054
1055 // Because we try the reference downcast before this function, from now on
1056 // this is the only cast possibility, so we issue an error if we fail now.
1057 // FIXME: Should allow casting away constness if CStyle.
1058 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00001059 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00001060 bool ObjCLifetimeConversion;
Douglas Gregor8ec14e62011-01-26 21:04:06 +00001061 QualType FromType = SrcExpr->getType();
1062 QualType ToType = R->getPointeeType();
1063 if (CStyle) {
1064 FromType = FromType.getUnqualifiedType();
1065 ToType = ToType.getUnqualifiedType();
1066 }
1067
Douglas Gregor393896f2009-11-05 13:06:35 +00001068 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
Douglas Gregor8ec14e62011-01-26 21:04:06 +00001069 ToType, FromType,
John McCallf85e1932011-06-15 23:02:42 +00001070 DerivedToBase, ObjCConversion,
1071 ObjCLifetimeConversion)
1072 < Sema::Ref_Compatible_With_Added_Qualification) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001073 msg = diag::err_bad_lvalue_to_rvalue_cast;
1074 return TC_Failed;
1075 }
1076
Douglas Gregor88b22a42011-01-25 16:13:26 +00001077 if (DerivedToBase) {
1078 Kind = CK_DerivedToBase;
1079 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1080 /*DetectVirtual=*/true);
1081 if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
1082 return TC_NotApplicable;
1083
1084 Self.BuildBasePathArray(Paths, BasePath);
1085 } else
1086 Kind = CK_NoOp;
1087
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001088 return TC_Success;
1089}
1090
1091/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1092TryCastResult
1093TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
1094 bool CStyle, const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +00001095 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001096 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001097 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1098 // cast to type "reference to cv2 D", where D is a class derived from B,
1099 // if a valid standard conversion from "pointer to D" to "pointer to B"
1100 // exists, cv2 >= cv1, and B is not a virtual base class of D.
1101 // In addition, DR54 clarifies that the base must be accessible in the
1102 // current context. Although the wording of DR54 only applies to the pointer
1103 // variant of this rule, the intent is clearly for it to apply to the this
1104 // conversion as well.
1105
Ted Kremenek6217b802009-07-29 21:53:49 +00001106 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001107 if (!DestReference) {
1108 return TC_NotApplicable;
1109 }
1110 bool RValueRef = DestReference->isRValueReferenceType();
John McCall7eb0a9e2010-11-24 05:12:34 +00001111 if (!RValueRef && !SrcExpr->isLValue()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001112 // We know the left side is an lvalue reference, so we can suggest a reason.
1113 msg = diag::err_bad_cxx_cast_rvalue;
1114 return TC_NotApplicable;
1115 }
1116
1117 QualType DestPointee = DestReference->getPointeeType();
1118
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001119 return TryStaticDowncast(Self,
1120 Self.Context.getCanonicalType(SrcExpr->getType()),
1121 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001122 OpRange, SrcExpr->getType(), DestType, msg, Kind,
1123 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001124}
1125
1126/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1127TryCastResult
1128TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +00001129 bool CStyle, const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +00001130 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001131 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001132 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1133 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1134 // is a class derived from B, if a valid standard conversion from "pointer
1135 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1136 // class of D.
1137 // In addition, DR54 clarifies that the base must be accessible in the
1138 // current context.
1139
Ted Kremenek6217b802009-07-29 21:53:49 +00001140 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001141 if (!DestPointer) {
1142 return TC_NotApplicable;
1143 }
1144
Ted Kremenek6217b802009-07-29 21:53:49 +00001145 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001146 if (!SrcPointer) {
1147 msg = diag::err_bad_static_cast_pointer_nonpointer;
1148 return TC_NotApplicable;
1149 }
1150
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001151 return TryStaticDowncast(Self,
1152 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1153 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001154 CStyle, OpRange, SrcType, DestType, msg, Kind,
1155 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001156}
1157
1158/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1159/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001160/// DestType is possible and allowed.
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001161TryCastResult
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001162TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001163 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +00001164 QualType OrigDestType, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +00001165 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl5ed66f72009-10-22 15:07:22 +00001166 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregord10099e2012-05-04 16:32:21 +00001167 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, 0) ||
1168 Self.RequireCompleteType(OpRange.getBegin(), DestType, 0))
Sebastian Redl5ed66f72009-10-22 15:07:22 +00001169 return TC_NotApplicable;
1170
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001171 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001172 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001173 return TC_NotApplicable;
1174 }
1175
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001176 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001177 /*DetectVirtual=*/true);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001178 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
1179 return TC_NotApplicable;
1180 }
1181
1182 // Target type does derive from source type. Now we're serious. If an error
1183 // appears now, it's not ignored.
1184 // This may not be entirely in line with the standard. Take for example:
1185 // struct A {};
1186 // struct B : virtual A {
1187 // B(A&);
1188 // };
Mike Stump1eb44332009-09-09 15:08:12 +00001189 //
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001190 // void f()
1191 // {
1192 // (void)static_cast<const B&>(*((A*)0));
1193 // }
1194 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1195 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1196 // However, both GCC and Comeau reject this example, and accepting it would
1197 // mean more complex code if we're to preserve the nice error message.
1198 // FIXME: Being 100% compliant here would be nice to have.
1199
1200 // Must preserve cv, as always, unless we're in C-style mode.
1201 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001202 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001203 return TC_Failed;
1204 }
1205
1206 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1207 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1208 // that it builds the paths in reverse order.
1209 // To sum up: record all paths to the base and build a nice string from
1210 // them. Use it to spice up the error message.
1211 if (!Paths.isRecordingPaths()) {
1212 Paths.clear();
1213 Paths.setRecordingPaths(true);
1214 Self.IsDerivedFrom(DestType, SrcType, Paths);
1215 }
1216 std::string PathDisplayStr;
1217 std::set<unsigned> DisplayedPaths;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001218 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001219 PI != PE; ++PI) {
1220 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
1221 // We haven't displayed a path to this particular base
1222 // class subobject yet.
1223 PathDisplayStr += "\n ";
Douglas Gregora8f32e02009-10-06 17:59:45 +00001224 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
1225 EE = PI->rend();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001226 EI != EE; ++EI)
1227 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001228 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001229 }
1230 }
1231
1232 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001233 << QualType(SrcType).getUnqualifiedType()
1234 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001235 << PathDisplayStr << OpRange;
1236 msg = 0;
1237 return TC_Failed;
1238 }
1239
1240 if (Paths.getDetectedVirtual() != 0) {
1241 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1242 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1243 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1244 msg = 0;
1245 return TC_Failed;
1246 }
1247
John McCall417d39f2011-02-14 23:21:33 +00001248 if (!CStyle) {
1249 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1250 SrcType, DestType,
1251 Paths.front(),
John McCall58e6f342010-03-16 05:22:47 +00001252 diag::err_downcast_from_inaccessible_base)) {
John McCall417d39f2011-02-14 23:21:33 +00001253 case Sema::AR_accessible:
1254 case Sema::AR_delayed: // be optimistic
1255 case Sema::AR_dependent: // be optimistic
1256 break;
1257
1258 case Sema::AR_inaccessible:
1259 msg = 0;
1260 return TC_Failed;
1261 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001262 }
1263
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001264 Self.BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00001265 Kind = CK_BaseToDerived;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001266 return TC_Success;
1267}
1268
1269/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1270/// C++ 5.2.9p9 is valid:
1271///
1272/// An rvalue of type "pointer to member of D of type cv1 T" can be
1273/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1274/// where B is a base class of D [...].
1275///
1276TryCastResult
John Wiegley429bb272011-04-08 18:41:53 +00001277TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001278 QualType DestType, bool CStyle,
1279 const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +00001280 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001281 CXXCastPath &BasePath) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001282 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001283 if (!DestMemPtr)
1284 return TC_NotApplicable;
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001285
1286 bool WasOverloadedFunction = false;
John McCall6bb80172010-03-30 21:47:33 +00001287 DeclAccessPair FoundOverload;
John Wiegley429bb272011-04-08 18:41:53 +00001288 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor1a8cf732010-04-14 23:11:21 +00001289 if (FunctionDecl *Fn
John Wiegley429bb272011-04-08 18:41:53 +00001290 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
Douglas Gregor1a8cf732010-04-14 23:11:21 +00001291 FoundOverload)) {
1292 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1293 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1294 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1295 WasOverloadedFunction = true;
1296 }
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001297 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00001298
Ted Kremenek6217b802009-07-29 21:53:49 +00001299 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001300 if (!SrcMemPtr) {
1301 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1302 return TC_NotApplicable;
1303 }
1304
1305 // T == T, modulo cv
Douglas Gregora4923eb2009-11-16 21:35:15 +00001306 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1307 DestMemPtr->getPointeeType()))
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001308 return TC_NotApplicable;
1309
1310 // B base of D
1311 QualType SrcClass(SrcMemPtr->getClass(), 0);
1312 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssoncee22422010-04-24 19:22:20 +00001313 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001314 /*DetectVirtual=*/true);
1315 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
1316 return TC_NotApplicable;
1317 }
1318
1319 // 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 +00001320 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001321 Paths.clear();
1322 Paths.setRecordingPaths(true);
1323 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
1324 assert(StillOkay);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001325 (void)StillOkay;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001326 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1327 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1328 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1329 msg = 0;
1330 return TC_Failed;
1331 }
1332
1333 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1334 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1335 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1336 msg = 0;
1337 return TC_Failed;
1338 }
1339
John McCall417d39f2011-02-14 23:21:33 +00001340 if (!CStyle) {
1341 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1342 DestClass, SrcClass,
1343 Paths.front(),
1344 diag::err_upcast_to_inaccessible_base)) {
1345 case Sema::AR_accessible:
1346 case Sema::AR_delayed:
1347 case Sema::AR_dependent:
1348 // Optimistically assume that the delayed and dependent cases
1349 // will work out.
1350 break;
1351
1352 case Sema::AR_inaccessible:
1353 msg = 0;
1354 return TC_Failed;
1355 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001356 }
1357
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001358 if (WasOverloadedFunction) {
1359 // Resolve the address of the overloaded function again, this time
1360 // allowing complaints if something goes wrong.
John Wiegley429bb272011-04-08 18:41:53 +00001361 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001362 DestType,
John McCall6bb80172010-03-30 21:47:33 +00001363 true,
1364 FoundOverload);
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001365 if (!Fn) {
1366 msg = 0;
1367 return TC_Failed;
1368 }
1369
John McCall6bb80172010-03-30 21:47:33 +00001370 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
John Wiegley429bb272011-04-08 18:41:53 +00001371 if (!SrcExpr.isUsable()) {
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001372 msg = 0;
1373 return TC_Failed;
1374 }
1375 }
1376
Anders Carlssoncee22422010-04-24 19:22:20 +00001377 Self.BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00001378 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001379 return TC_Success;
1380}
1381
1382/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1383/// is valid:
1384///
1385/// An expression e can be explicitly converted to a type T using a
1386/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1387TryCastResult
John Wiegley429bb272011-04-08 18:41:53 +00001388TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCallf85e1932011-06-15 23:02:42 +00001389 Sema::CheckedConversionKind CCK,
1390 const SourceRange &OpRange, unsigned &msg,
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001391 CastKind &Kind, bool ListInitialization) {
Anders Carlssond851b372009-09-07 18:25:47 +00001392 if (DestType->isRecordType()) {
1393 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
Aaron Ballman21eb6d42012-05-07 00:02:00 +00001394 diag::err_bad_dynamic_cast_incomplete) ||
Eli Friedman860a3192012-06-16 02:19:17 +00001395 Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
Aaron Ballman21eb6d42012-05-07 00:02:00 +00001396 diag::err_allocation_of_abstract_type)) {
Anders Carlssond851b372009-09-07 18:25:47 +00001397 msg = 0;
1398 return TC_Failed;
1399 }
1400 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00001401
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001402 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1403 InitializationKind InitKind
John McCallf85e1932011-06-15 23:02:42 +00001404 = (CCK == Sema::CCK_CStyleCast)
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00001405 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001406 ListInitialization)
John McCallf85e1932011-06-15 23:02:42 +00001407 : (CCK == Sema::CCK_FunctionalCast)
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001408 ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
Richard Smithc8d7f582011-11-29 22:48:16 +00001409 : InitializationKind::CreateCast(OpRange);
John Wiegley429bb272011-04-08 18:41:53 +00001410 Expr *SrcExprRaw = SrcExpr.get();
1411 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExprRaw, 1);
Douglas Gregor8e960432010-11-08 03:40:48 +00001412
1413 // At this point of CheckStaticCast, if the destination is a reference,
1414 // or the expression is an overload expression this has to work.
1415 // There is no other way that works.
1416 // On the other hand, if we're checking a C-style cast, we've still got
1417 // the reinterpret_cast way.
John McCallf85e1932011-06-15 23:02:42 +00001418 bool CStyle
1419 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
Sebastian Redl383616c2011-06-05 12:23:28 +00001420 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
Anders Carlsson3c31a392009-09-26 00:12:34 +00001421 return TC_NotApplicable;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001422
Benjamin Kramer5354e772012-08-23 23:38:35 +00001423 ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001424 if (Result.isInvalid()) {
1425 msg = 0;
1426 return TC_Failed;
1427 }
1428
Douglas Gregord6e44a32010-04-16 22:09:46 +00001429 if (InitSeq.isConstructorInitialization())
John McCall2de56d12010-08-25 11:45:40 +00001430 Kind = CK_ConstructorConversion;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001431 else
John McCall2de56d12010-08-25 11:45:40 +00001432 Kind = CK_NoOp;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001433
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001434 SrcExpr = Result;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001435 return TC_Success;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001436}
1437
1438/// TryConstCast - See if a const_cast from source to destination is allowed,
1439/// and perform it if it is.
1440static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
1441 bool CStyle, unsigned &msg) {
1442 DestType = Self.Context.getCanonicalType(DestType);
1443 QualType SrcType = SrcExpr->getType();
Douglas Gregor575d2a32011-01-22 00:19:52 +00001444 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
1445 if (DestTypeTmp->isLValueReferenceType() && !SrcExpr->isLValue()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001446 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1447 // is C-style, static_cast might find a way, so we simply suggest a
1448 // message and tell the parent to keep searching.
1449 msg = diag::err_bad_cxx_cast_rvalue;
1450 return TC_NotApplicable;
1451 }
1452
1453 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
1454 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
1455 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1456 SrcType = Self.Context.getPointerType(SrcType);
1457 }
1458
1459 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1460 // the rules for const_cast are the same as those used for pointers.
1461
John McCalld425d2b2010-05-18 09:35:29 +00001462 if (!DestType->isPointerType() &&
1463 !DestType->isMemberPointerType() &&
1464 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001465 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1466 // was a reference type, we converted it to a pointer above.
1467 // The status of rvalue references isn't entirely clear, but it looks like
1468 // conversion to them is simply invalid.
1469 // C++ 5.2.11p3: For two pointer types [...]
1470 if (!CStyle)
1471 msg = diag::err_bad_const_cast_dest;
1472 return TC_NotApplicable;
1473 }
1474 if (DestType->isFunctionPointerType() ||
1475 DestType->isMemberFunctionPointerType()) {
1476 // Cannot cast direct function pointers.
1477 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1478 // T is the ultimate pointee of source and target type.
1479 if (!CStyle)
1480 msg = diag::err_bad_const_cast_dest;
1481 return TC_NotApplicable;
1482 }
1483 SrcType = Self.Context.getCanonicalType(SrcType);
1484
1485 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1486 // completely equal.
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001487 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1488 // in multi-level pointers may change, but the level count must be the same,
1489 // as must be the final pointee type.
1490 while (SrcType != DestType &&
Douglas Gregor5a57efd2010-06-09 03:53:18 +00001491 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001492 Qualifiers SrcQuals, DestQuals;
1493 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
1494 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
1495
1496 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
1497 // the other qualifiers (e.g., address spaces) are identical.
1498 SrcQuals.removeCVRQualifiers();
1499 DestQuals.removeCVRQualifiers();
1500 if (SrcQuals != DestQuals)
1501 return TC_NotApplicable;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001502 }
1503
1504 // Since we're dealing in canonical types, the remainder must be the same.
1505 if (SrcType != DestType)
1506 return TC_NotApplicable;
1507
1508 return TC_Success;
1509}
1510
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001511// Checks for undefined behavior in reinterpret_cast.
1512// The cases that is checked for is:
1513// *reinterpret_cast<T*>(&a)
1514// reinterpret_cast<T&>(a)
1515// where accessing 'a' as type 'T' will result in undefined behavior.
1516void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1517 bool IsDereference,
1518 SourceRange Range) {
1519 unsigned DiagID = IsDereference ?
1520 diag::warn_pointer_indirection_from_incompatible_type :
1521 diag::warn_undefined_reinterpret_cast;
1522
1523 if (Diags.getDiagnosticLevel(DiagID, Range.getBegin()) ==
David Blaikied6471f72011-09-25 23:23:43 +00001524 DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001525 return;
1526 }
1527
1528 QualType SrcTy, DestTy;
1529 if (IsDereference) {
1530 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1531 return;
1532 }
1533 SrcTy = SrcType->getPointeeType();
1534 DestTy = DestType->getPointeeType();
1535 } else {
1536 if (!DestType->getAs<ReferenceType>()) {
1537 return;
1538 }
1539 SrcTy = SrcType;
1540 DestTy = DestType->getPointeeType();
1541 }
1542
1543 // Cast is compatible if the types are the same.
1544 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1545 return;
1546 }
1547 // or one of the types is a char or void type
1548 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1549 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1550 return;
1551 }
1552 // or one of the types is a tag type.
Chandler Carruth1f8f2d52011-05-24 07:43:19 +00001553 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001554 return;
1555 }
1556
Douglas Gregor575a1c92011-05-20 16:38:50 +00001557 // FIXME: Scoped enums?
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001558 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1559 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1560 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1561 return;
1562 }
1563 }
1564
1565 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1566}
Douglas Gregorfadb53b2011-03-12 01:48:56 +00001567
Fariborz Jahanian91dd9df2012-08-16 18:33:47 +00001568static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
1569 QualType DestType) {
1570 QualType SrcType = SrcExpr.get()->getType();
Fariborz Jahanian0c252fa2012-12-13 00:42:06 +00001571 if (Self.Context.hasSameType(SrcType, DestType))
1572 return;
Fariborz Jahanian91dd9df2012-08-16 18:33:47 +00001573 if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
1574 if (SrcPtrTy->isObjCSelType()) {
1575 QualType DT = DestType;
1576 if (isa<PointerType>(DestType))
1577 DT = DestType->getPointeeType();
1578 if (!DT.getUnqualifiedType()->isVoidType())
1579 Self.Diag(SrcExpr.get()->getExprLoc(),
1580 diag::warn_cast_pointer_from_sel)
1581 << SrcType << DestType << SrcExpr.get()->getSourceRange();
1582 }
1583}
1584
David Blaikie9b29f4f2012-10-16 18:53:14 +00001585static void checkIntToPointerCast(bool CStyle, SourceLocation Loc,
1586 const Expr *SrcExpr, QualType DestType,
1587 Sema &Self) {
1588 QualType SrcType = SrcExpr->getType();
1589
1590 // Not warning on reinterpret_cast, boolean, constant expressions, etc
1591 // are not explicit design choices, but consistent with GCC's behavior.
1592 // Feel free to modify them if you've reason/evidence for an alternative.
1593 if (CStyle && SrcType->isIntegralType(Self.Context)
1594 && !SrcType->isBooleanType()
1595 && !SrcType->isEnumeralType()
1596 && !SrcExpr->isIntegerConstantExpr(Self.Context)
1597 && Self.Context.getTypeSize(DestType) > Self.Context.getTypeSize(SrcType))
1598 Self.Diag(Loc, diag::warn_int_to_pointer_cast) << SrcType << DestType;
1599}
1600
John Wiegley429bb272011-04-08 18:41:53 +00001601static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001602 QualType DestType, bool CStyle,
1603 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +00001604 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +00001605 CastKind &Kind) {
Douglas Gregore39a3892010-07-13 23:17:26 +00001606 bool IsLValueCast = false;
1607
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001608 DestType = Self.Context.getCanonicalType(DestType);
John Wiegley429bb272011-04-08 18:41:53 +00001609 QualType SrcType = SrcExpr.get()->getType();
Douglas Gregor8e960432010-11-08 03:40:48 +00001610
1611 // Is the source an overloaded name? (i.e. &foo)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001612 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ...
1613 if (SrcType == Self.Context.OverloadTy) {
John McCall6dbba4f2011-10-11 23:14:30 +00001614 // ... unless foo<int> resolves to an lvalue unambiguously.
1615 // TODO: what if this fails because of DiagnoseUseOfDecl or something
1616 // like it?
1617 ExprResult SingleFunctionExpr = SrcExpr;
1618 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1619 SingleFunctionExpr,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001620 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
John McCall6dbba4f2011-10-11 23:14:30 +00001621 ) && SingleFunctionExpr.isUsable()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001622 SrcExpr = SingleFunctionExpr;
John Wiegley429bb272011-04-08 18:41:53 +00001623 SrcType = SrcExpr.get()->getType();
John McCall6dbba4f2011-10-11 23:14:30 +00001624 } else {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001625 return TC_NotApplicable;
John McCall6dbba4f2011-10-11 23:14:30 +00001626 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001627 }
Douglas Gregor8e960432010-11-08 03:40:48 +00001628
Ted Kremenek6217b802009-07-29 21:53:49 +00001629 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Richard Smith6850faf2012-04-29 08:24:44 +00001630 if (!SrcExpr.get()->isGLValue()) {
1631 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
1632 // similar comment in const_cast.
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001633 msg = diag::err_bad_cxx_cast_rvalue;
1634 return TC_NotApplicable;
1635 }
1636
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001637 if (!CStyle) {
1638 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
1639 /*isDereference=*/false, OpRange);
1640 }
1641
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001642 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1643 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1644 // built-in & and * operators.
Argyrios Kyrtzidisb464a5b2011-04-22 22:31:13 +00001645
Argyrios Kyrtzidisbb29d1b2011-04-22 23:57:57 +00001646 const char *inappropriate = 0;
1647 switch (SrcExpr.get()->getObjectKind()) {
Argyrios Kyrtzidise5e3d312011-04-23 01:10:24 +00001648 case OK_Ordinary:
1649 break;
Argyrios Kyrtzidisbb29d1b2011-04-22 23:57:57 +00001650 case OK_BitField: inappropriate = "bit-field"; break;
1651 case OK_VectorComponent: inappropriate = "vector element"; break;
1652 case OK_ObjCProperty: inappropriate = "property expression"; break;
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001653 case OK_ObjCSubscript: inappropriate = "container subscripting expression";
1654 break;
Argyrios Kyrtzidisbb29d1b2011-04-22 23:57:57 +00001655 }
1656 if (inappropriate) {
1657 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
1658 << inappropriate << DestType
1659 << OpRange << SrcExpr.get()->getSourceRange();
1660 msg = 0; SrcExpr = ExprError();
Argyrios Kyrtzidisb464a5b2011-04-22 22:31:13 +00001661 return TC_NotApplicable;
1662 }
1663
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001664 // This code does this transformation for the checked types.
1665 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1666 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregor8e960432010-11-08 03:40:48 +00001667
Douglas Gregore39a3892010-07-13 23:17:26 +00001668 IsLValueCast = true;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001669 }
1670
1671 // Canonicalize source for comparison.
1672 SrcType = Self.Context.getCanonicalType(SrcType);
1673
Ted Kremenek6217b802009-07-29 21:53:49 +00001674 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1675 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001676 if (DestMemPtr && SrcMemPtr) {
1677 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1678 // can be explicitly converted to an rvalue of type "pointer to member
1679 // of Y of type T2" if T1 and T2 are both function types or both object
1680 // types.
1681 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1682 SrcMemPtr->getPointeeType()->isFunctionType())
1683 return TC_NotApplicable;
1684
1685 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1686 // constness.
1687 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1688 // we accept it.
John McCallf85e1932011-06-15 23:02:42 +00001689 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1690 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001691 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001692 return TC_Failed;
1693 }
1694
Charles Davisf231df32010-08-16 05:30:44 +00001695 // Don't allow casting between member pointers of different sizes.
1696 if (Self.Context.getTypeSize(DestMemPtr) !=
1697 Self.Context.getTypeSize(SrcMemPtr)) {
1698 msg = diag::err_bad_cxx_cast_member_pointer_size;
1699 return TC_Failed;
1700 }
1701
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001702 // A valid member pointer cast.
John McCall4d4e5c12012-02-15 01:22:51 +00001703 assert(!IsLValueCast);
1704 Kind = CK_ReinterpretMemberPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001705 return TC_Success;
1706 }
1707
1708 // See below for the enumeral issue.
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001709 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001710 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1711 // type large enough to hold it. A value of std::nullptr_t can be
1712 // converted to an integral type; the conversion has the same meaning
1713 // and validity as a conversion of (void*)0 to the integral type.
1714 if (Self.Context.getTypeSize(SrcType) >
1715 Self.Context.getTypeSize(DestType)) {
1716 msg = diag::err_bad_reinterpret_cast_small_int;
1717 return TC_Failed;
1718 }
John McCall2de56d12010-08-25 11:45:40 +00001719 Kind = CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001720 return TC_Success;
1721 }
1722
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001723 bool destIsVector = DestType->isVectorType();
1724 bool srcIsVector = SrcType->isVectorType();
1725 if (srcIsVector || destIsVector) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001726 // FIXME: Should this also apply to floating point types?
1727 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1728 bool destIsScalar = DestType->isIntegralType(Self.Context);
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001729
1730 // Check if this is a cast between a vector and something else.
1731 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1732 !(srcIsVector && destIsVector))
1733 return TC_NotApplicable;
1734
1735 // If both types have the same size, we can successfully cast.
Douglas Gregorf2a55392009-12-22 22:47:22 +00001736 if (Self.Context.getTypeSize(SrcType)
1737 == Self.Context.getTypeSize(DestType)) {
John McCall2de56d12010-08-25 11:45:40 +00001738 Kind = CK_BitCast;
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001739 return TC_Success;
Douglas Gregorf2a55392009-12-22 22:47:22 +00001740 }
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001741
1742 if (destIsScalar)
1743 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1744 else if (srcIsScalar)
1745 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1746 else
1747 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1748
1749 return TC_Failed;
1750 }
Chad Rosier41f44312012-02-03 02:54:37 +00001751
1752 if (SrcType == DestType) {
1753 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1754 // restrictions, a cast to the same type is allowed so long as it does not
1755 // cast away constness. In C++98, the intent was not entirely clear here,
1756 // since all other paragraphs explicitly forbid casts to the same type.
1757 // C++11 clarifies this case with p2.
1758 //
1759 // The only allowed types are: integral, enumeration, pointer, or
1760 // pointer-to-member types. We also won't restrict Obj-C pointers either.
1761 Kind = CK_NoOp;
1762 TryCastResult Result = TC_NotApplicable;
1763 if (SrcType->isIntegralOrEnumerationType() ||
1764 SrcType->isAnyPointerType() ||
1765 SrcType->isMemberPointerType() ||
1766 SrcType->isBlockPointerType()) {
1767 Result = TC_Success;
1768 }
1769 return Result;
1770 }
1771
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001772 bool destIsPtr = DestType->isAnyPointerType() ||
1773 DestType->isBlockPointerType();
1774 bool srcIsPtr = SrcType->isAnyPointerType() ||
1775 SrcType->isBlockPointerType();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001776 if (!destIsPtr && !srcIsPtr) {
1777 // Except for std::nullptr_t->integer and lvalue->reference, which are
1778 // handled above, at least one of the two arguments must be a pointer.
1779 return TC_NotApplicable;
1780 }
1781
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001782 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001783 assert(srcIsPtr && "One type must be a pointer");
1784 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
Francois Pichet30aff5b2011-05-11 22:13:54 +00001785 // type large enough to hold it; except in Microsoft mode, where the
1786 // integral type size doesn't matter.
1787 if ((Self.Context.getTypeSize(SrcType) >
1788 Self.Context.getTypeSize(DestType)) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00001789 !Self.getLangOpts().MicrosoftExt) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001790 msg = diag::err_bad_reinterpret_cast_small_int;
1791 return TC_Failed;
1792 }
John McCall2de56d12010-08-25 11:45:40 +00001793 Kind = CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001794 return TC_Success;
1795 }
1796
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001797 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001798 assert(destIsPtr && "One type must be a pointer");
David Blaikie9b29f4f2012-10-16 18:53:14 +00001799 checkIntToPointerCast(CStyle, OpRange.getBegin(), SrcExpr.get(), DestType,
1800 Self);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001801 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1802 // converted to a pointer.
John McCall404cd162010-11-13 01:35:44 +00001803 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1804 // necessarily converted to a null pointer value.]
John McCall2de56d12010-08-25 11:45:40 +00001805 Kind = CK_IntegralToPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001806 return TC_Success;
1807 }
1808
1809 if (!destIsPtr || !srcIsPtr) {
1810 // With the valid non-pointer conversions out of the way, we can be even
1811 // more stringent.
1812 return TC_NotApplicable;
1813 }
1814
1815 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1816 // The C-style cast operator can.
John McCallf85e1932011-06-15 23:02:42 +00001817 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1818 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001819 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001820 return TC_Failed;
1821 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001822
1823 // Cannot convert between block pointers and Objective-C object pointers.
1824 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1825 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1826 return TC_NotApplicable;
1827
John McCall1d9b3b22011-09-09 05:25:32 +00001828 if (IsLValueCast) {
1829 Kind = CK_LValueBitCast;
1830 } else if (DestType->isObjCObjectPointerType()) {
John McCalldc05b112011-09-10 01:16:55 +00001831 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
John McCall1d9b3b22011-09-09 05:25:32 +00001832 } else if (DestType->isBlockPointerType()) {
1833 if (!SrcType->isBlockPointerType()) {
1834 Kind = CK_AnyPointerToBlockPointerCast;
1835 } else {
1836 Kind = CK_BitCast;
1837 }
1838 } else {
1839 Kind = CK_BitCast;
1840 }
1841
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001842 // Any pointer can be cast to an Objective-C pointer type with a C-style
1843 // cast.
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001844 if (CStyle && DestType->isObjCObjectPointerType()) {
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001845 return TC_Success;
1846 }
Fariborz Jahanian91dd9df2012-08-16 18:33:47 +00001847 if (CStyle)
1848 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
1849
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001850 // Not casting away constness, so the only remaining check is for compatible
1851 // pointer categories.
1852
1853 if (SrcType->isFunctionPointerType()) {
1854 if (DestType->isFunctionPointerType()) {
1855 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1856 // a pointer to a function of a different type.
1857 return TC_Success;
1858 }
1859
1860 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1861 // an object type or vice versa is conditionally-supported.
1862 // Compilers support it in C++03 too, though, because it's necessary for
1863 // casting the return value of dlsym() and GetProcAddress().
1864 // FIXME: Conditionally-supported behavior should be configurable in the
1865 // TargetInfo or similar.
Richard Smithebaf0e62011-10-18 20:49:44 +00001866 Self.Diag(OpRange.getBegin(),
Richard Smith80ad52f2013-01-02 11:42:31 +00001867 Self.getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00001868 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
1869 << OpRange;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001870 return TC_Success;
1871 }
1872
1873 if (DestType->isFunctionPointerType()) {
1874 // See above.
Richard Smithebaf0e62011-10-18 20:49:44 +00001875 Self.Diag(OpRange.getBegin(),
Richard Smith80ad52f2013-01-02 11:42:31 +00001876 Self.getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00001877 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
1878 << OpRange;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001879 return TC_Success;
1880 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001881
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001882 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1883 // a pointer to an object of different type.
1884 // Void pointers are not specified, but supported by every compiler out there.
1885 // So we finish by allowing everything that remains - it's got to be two
1886 // object pointers.
1887 return TC_Success;
John McCall79ab2c82011-02-14 18:34:10 +00001888}
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001889
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001890void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
1891 bool ListInitialization) {
John McCalla180f042011-10-06 23:25:11 +00001892 // Handle placeholders.
1893 if (isPlaceholder()) {
1894 // C-style casts can resolve __unknown_any types.
1895 if (claimPlaceholder(BuiltinType::UnknownAny)) {
1896 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
1897 SrcExpr.get(), Kind,
1898 ValueKind, BasePath);
1899 return;
1900 }
John McCallb45ae252011-10-05 07:41:44 +00001901
John McCalla180f042011-10-06 23:25:11 +00001902 checkNonOverloadPlaceholders();
1903 if (SrcExpr.isInvalid())
1904 return;
John McCall4919dfd2011-10-17 17:42:19 +00001905 }
John McCalla180f042011-10-06 23:25:11 +00001906
1907 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001908 // This test is outside everything else because it's the only case where
1909 // a non-lvalue-reference target type does not lead to decay.
John McCallb45ae252011-10-05 07:41:44 +00001910 if (DestType->isVoidType()) {
John McCallfb8721c2011-04-10 19:13:55 +00001911 Kind = CK_ToVoid;
1912
John McCalla180f042011-10-06 23:25:11 +00001913 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall6dbba4f2011-10-11 23:14:30 +00001914 Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1915 SrcExpr, /* Decay Function to ptr */ false,
John McCallb45ae252011-10-05 07:41:44 +00001916 /* Complain */ true, DestRange, DestType,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00001917 diag::err_bad_cstyle_cast_overload);
John McCallb45ae252011-10-05 07:41:44 +00001918 if (SrcExpr.isInvalid())
1919 return;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001920 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001921
John McCalla180f042011-10-06 23:25:11 +00001922 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
1923 if (SrcExpr.isInvalid())
John McCallb45ae252011-10-05 07:41:44 +00001924 return;
John McCallb45ae252011-10-05 07:41:44 +00001925
1926 return;
Anton Yartsevd06fea82011-03-27 09:32:40 +00001927 }
1928
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001929 // If the type is dependent, we won't do any other semantic analysis now.
John McCallb45ae252011-10-05 07:41:44 +00001930 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent()) {
1931 assert(Kind == CK_Dependent);
1932 return;
John McCalldaa8e4e2010-11-15 09:13:47 +00001933 }
Benjamin Kramer5b4a40a2011-07-08 20:20:17 +00001934
John McCall6dbba4f2011-10-11 23:14:30 +00001935 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
1936 !isPlaceholder(BuiltinType::Overload)) {
John McCallb45ae252011-10-05 07:41:44 +00001937 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
1938 if (SrcExpr.isInvalid())
1939 return;
John Wiegley429bb272011-04-08 18:41:53 +00001940 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001941
John McCallfb8721c2011-04-10 19:13:55 +00001942 // AltiVec vector initialization with a single literal.
John McCallb45ae252011-10-05 07:41:44 +00001943 if (const VectorType *vecTy = DestType->getAs<VectorType>())
John McCallfb8721c2011-04-10 19:13:55 +00001944 if (vecTy->getVectorKind() == VectorType::AltiVecVector
John McCallb45ae252011-10-05 07:41:44 +00001945 && (SrcExpr.get()->getType()->isIntegerType()
1946 || SrcExpr.get()->getType()->isFloatingType())) {
John McCallfb8721c2011-04-10 19:13:55 +00001947 Kind = CK_VectorSplat;
John McCallb45ae252011-10-05 07:41:44 +00001948 return;
John McCallfb8721c2011-04-10 19:13:55 +00001949 }
1950
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001951 // C++ [expr.cast]p5: The conversions performed by
1952 // - a const_cast,
1953 // - a static_cast,
1954 // - a static_cast followed by a const_cast,
1955 // - a reinterpret_cast, or
1956 // - a reinterpret_cast followed by a const_cast,
1957 // can be performed using the cast notation of explicit type conversion.
1958 // [...] If a conversion can be interpreted in more than one of the ways
1959 // listed above, the interpretation that appears first in the list is used,
1960 // even if a cast resulting from that interpretation is ill-formed.
1961 // In plain language, this means trying a const_cast ...
1962 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCallb45ae252011-10-05 07:41:44 +00001963 TryCastResult tcr = TryConstCast(Self, SrcExpr.get(), DestType,
1964 /*CStyle*/true, msg);
Anders Carlssonda921fd2009-10-19 18:14:28 +00001965 if (tcr == TC_Success)
John McCall2de56d12010-08-25 11:45:40 +00001966 Kind = CK_NoOp;
Anders Carlssonda921fd2009-10-19 18:14:28 +00001967
John McCallf85e1932011-06-15 23:02:42 +00001968 Sema::CheckedConversionKind CCK
1969 = FunctionalStyle? Sema::CCK_FunctionalCast
1970 : Sema::CCK_CStyleCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001971 if (tcr == TC_NotApplicable) {
1972 // ... or if that is not possible, a static_cast, ignoring const, ...
John McCallb45ae252011-10-05 07:41:44 +00001973 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001974 msg, Kind, BasePath, ListInitialization);
John McCallb45ae252011-10-05 07:41:44 +00001975 if (SrcExpr.isInvalid())
1976 return;
1977
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001978 if (tcr == TC_NotApplicable) {
1979 // ... and finally a reinterpret_cast, ignoring const.
John McCallb45ae252011-10-05 07:41:44 +00001980 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
1981 OpRange, msg, Kind);
1982 if (SrcExpr.isInvalid())
1983 return;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001984 }
1985 }
1986
David Blaikie4e4d0842012-03-11 07:00:24 +00001987 if (Self.getLangOpts().ObjCAutoRefCount && tcr == TC_Success)
John McCallb45ae252011-10-05 07:41:44 +00001988 checkObjCARCConversion(CCK);
John McCallf85e1932011-06-15 23:02:42 +00001989
Nick Lewycky43328e92010-11-09 00:19:31 +00001990 if (tcr != TC_Success && msg != 0) {
John McCallb45ae252011-10-05 07:41:44 +00001991 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor8e960432010-11-08 03:40:48 +00001992 DeclAccessPair Found;
John McCallb45ae252011-10-05 07:41:44 +00001993 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
1994 DestType,
1995 /*Complain*/ true,
Douglas Gregor8e960432010-11-08 03:40:48 +00001996 Found);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001997
Richard Trieu32ac00d2011-04-16 01:09:30 +00001998 assert(!Fn && "cast failed but able to resolve overload expression!!");
Nick Lewycky43328e92010-11-09 00:19:31 +00001999 (void)Fn;
John McCall79ab2c82011-02-14 18:34:10 +00002000
Nick Lewycky43328e92010-11-09 00:19:31 +00002001 } else {
John McCallb45ae252011-10-05 07:41:44 +00002002 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
Sebastian Redl20ff0e22012-02-13 19:55:43 +00002003 OpRange, SrcExpr.get(), DestType, ListInitialization);
Douglas Gregor8e960432010-11-08 03:40:48 +00002004 }
John McCallb45ae252011-10-05 07:41:44 +00002005 } else if (Kind == CK_BitCast) {
2006 checkCastAlign();
Douglas Gregor8e960432010-11-08 03:40:48 +00002007 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002008
John McCallb45ae252011-10-05 07:41:44 +00002009 // Clear out SrcExpr if there was a fatal error.
John Wiegley429bb272011-04-08 18:41:53 +00002010 if (tcr != TC_Success)
John McCallb45ae252011-10-05 07:41:44 +00002011 SrcExpr = ExprError();
2012}
2013
Fariborz Jahanianbbb8afd2012-08-17 17:22:34 +00002014/// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
2015/// non-matching type. Such as enum function call to int, int call to
2016/// pointer; etc. Cast to 'void' is an exception.
2017static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
2018 QualType DestType) {
2019 if (Self.Diags.getDiagnosticLevel(diag::warn_bad_function_cast,
2020 SrcExpr.get()->getExprLoc())
2021 == DiagnosticsEngine::Ignored)
2022 return;
2023
2024 if (!isa<CallExpr>(SrcExpr.get()))
2025 return;
2026
2027 QualType SrcType = SrcExpr.get()->getType();
2028 if (DestType.getUnqualifiedType()->isVoidType())
2029 return;
2030 if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
2031 && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
2032 return;
2033 if (SrcType->isIntegerType() && DestType->isIntegerType() &&
2034 (SrcType->isBooleanType() == DestType->isBooleanType()) &&
2035 (SrcType->isEnumeralType() == DestType->isEnumeralType()))
2036 return;
2037 if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
2038 return;
2039 if (SrcType->isEnumeralType() && DestType->isEnumeralType())
2040 return;
2041 if (SrcType->isComplexType() && DestType->isComplexType())
2042 return;
2043 if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
2044 return;
2045
2046 Self.Diag(SrcExpr.get()->getExprLoc(),
2047 diag::warn_bad_function_cast)
2048 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2049}
2050
John McCalla180f042011-10-06 23:25:11 +00002051/// Check the semantics of a C-style cast operation, in C.
2052void CastOperation::CheckCStyleCast() {
David Blaikie4e4d0842012-03-11 07:00:24 +00002053 assert(!Self.getLangOpts().CPlusPlus);
John McCalla180f042011-10-06 23:25:11 +00002054
John McCall5acb0c92011-10-17 18:40:02 +00002055 // C-style casts can resolve __unknown_any types.
2056 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2057 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2058 SrcExpr.get(), Kind,
2059 ValueKind, BasePath);
2060 return;
2061 }
John McCalla180f042011-10-06 23:25:11 +00002062
2063 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2064 // type needs to be scalar.
2065 if (DestType->isVoidType()) {
2066 // We don't necessarily do lvalue-to-rvalue conversions on this.
2067 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
2068 if (SrcExpr.isInvalid())
2069 return;
2070
2071 // Cast to void allows any expr type.
2072 Kind = CK_ToVoid;
2073 return;
2074 }
2075
2076 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
2077 if (SrcExpr.isInvalid())
2078 return;
2079 QualType SrcType = SrcExpr.get()->getType();
David Chisnall7a7ee302012-01-16 17:27:18 +00002080
John McCall5acb0c92011-10-17 18:40:02 +00002081 assert(!SrcType->isPlaceholderType());
John McCalla180f042011-10-06 23:25:11 +00002082
2083 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
2084 diag::err_typecheck_cast_to_incomplete)) {
2085 SrcExpr = ExprError();
2086 return;
2087 }
2088
2089 if (!DestType->isScalarType() && !DestType->isVectorType()) {
2090 const RecordType *DestRecordTy = DestType->getAs<RecordType>();
2091
2092 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
2093 // GCC struct/union extension: allow cast to self.
2094 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
2095 << DestType << SrcExpr.get()->getSourceRange();
2096 Kind = CK_NoOp;
2097 return;
2098 }
2099
2100 // GCC's cast to union extension.
2101 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
2102 RecordDecl *RD = DestRecordTy->getDecl();
2103 RecordDecl::field_iterator Field, FieldEnd;
2104 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2105 Field != FieldEnd; ++Field) {
2106 if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) &&
2107 !Field->isUnnamedBitfield()) {
2108 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
2109 << SrcExpr.get()->getSourceRange();
2110 break;
2111 }
2112 }
2113 if (Field == FieldEnd) {
2114 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2115 << SrcType << SrcExpr.get()->getSourceRange();
2116 SrcExpr = ExprError();
2117 return;
2118 }
2119 Kind = CK_ToUnion;
2120 return;
2121 }
2122
2123 // Reject any other conversions to non-scalar types.
2124 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
2125 << DestType << SrcExpr.get()->getSourceRange();
2126 SrcExpr = ExprError();
2127 return;
2128 }
2129
2130 // The type we're casting to is known to be a scalar or vector.
2131
2132 // Require the operand to be a scalar or vector.
2133 if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
2134 Self.Diag(SrcExpr.get()->getExprLoc(),
2135 diag::err_typecheck_expect_scalar_operand)
2136 << SrcType << SrcExpr.get()->getSourceRange();
2137 SrcExpr = ExprError();
2138 return;
2139 }
2140
2141 if (DestType->isExtVectorType()) {
2142 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.take(), Kind);
2143 return;
2144 }
2145
2146 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
2147 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
2148 (SrcType->isIntegerType() || SrcType->isFloatingType())) {
2149 Kind = CK_VectorSplat;
2150 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
2151 SrcExpr = ExprError();
2152 }
2153 return;
2154 }
2155
2156 if (SrcType->isVectorType()) {
2157 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
2158 SrcExpr = ExprError();
2159 return;
2160 }
2161
2162 // The source and target types are both scalars, i.e.
2163 // - arithmetic types (fundamental, enum, and complex)
2164 // - all kinds of pointers
2165 // Note that member pointers were filtered out with C++, above.
2166
2167 if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
2168 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
2169 SrcExpr = ExprError();
2170 return;
2171 }
2172
2173 // If either type is a pointer, the other type has to be either an
2174 // integer or a pointer.
2175 if (!DestType->isArithmeticType()) {
2176 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
2177 Self.Diag(SrcExpr.get()->getExprLoc(),
2178 diag::err_cast_pointer_from_non_pointer_int)
2179 << SrcType << SrcExpr.get()->getSourceRange();
2180 SrcExpr = ExprError();
2181 return;
2182 }
David Blaikie9b29f4f2012-10-16 18:53:14 +00002183 checkIntToPointerCast(/* CStyle */ true, OpRange.getBegin(), SrcExpr.get(),
2184 DestType, Self);
John McCalla180f042011-10-06 23:25:11 +00002185 } else if (!SrcType->isArithmeticType()) {
2186 if (!DestType->isIntegralType(Self.Context) &&
2187 DestType->isArithmeticType()) {
2188 Self.Diag(SrcExpr.get()->getLocStart(),
2189 diag::err_cast_pointer_to_non_pointer_int)
Abramo Bagnaraf7ce1942011-11-15 11:25:38 +00002190 << DestType << SrcExpr.get()->getSourceRange();
John McCalla180f042011-10-06 23:25:11 +00002191 SrcExpr = ExprError();
2192 return;
2193 }
2194 }
2195
Joey Gouly19dbb202013-01-23 11:56:20 +00002196 if (Self.getLangOpts().OpenCL && !Self.getOpenCLOptions().cl_khr_fp16) {
2197 if (DestType->isHalfType()) {
2198 Self.Diag(SrcExpr.get()->getLocStart(), diag::err_opencl_cast_to_half)
2199 << DestType << SrcExpr.get()->getSourceRange();
2200 SrcExpr = ExprError();
2201 return;
2202 }
Joey Gouly19dbb202013-01-23 11:56:20 +00002203 }
2204
John McCalla180f042011-10-06 23:25:11 +00002205 // ARC imposes extra restrictions on casts.
David Blaikie4e4d0842012-03-11 07:00:24 +00002206 if (Self.getLangOpts().ObjCAutoRefCount) {
John McCalla180f042011-10-06 23:25:11 +00002207 checkObjCARCConversion(Sema::CCK_CStyleCast);
2208 if (SrcExpr.isInvalid())
2209 return;
2210
2211 if (const PointerType *CastPtr = DestType->getAs<PointerType>()) {
2212 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
2213 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
2214 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
2215 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
2216 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
2217 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
2218 Self.Diag(SrcExpr.get()->getLocStart(),
2219 diag::err_typecheck_incompatible_ownership)
2220 << SrcType << DestType << Sema::AA_Casting
2221 << SrcExpr.get()->getSourceRange();
2222 return;
2223 }
2224 }
2225 }
2226 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
2227 Self.Diag(SrcExpr.get()->getLocStart(),
2228 diag::err_arc_convesion_of_weak_unavailable)
2229 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2230 SrcExpr = ExprError();
2231 return;
2232 }
2233 }
Fariborz Jahanian91dd9df2012-08-16 18:33:47 +00002234 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
Fariborz Jahanianbbb8afd2012-08-17 17:22:34 +00002235 DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
John McCalla180f042011-10-06 23:25:11 +00002236 Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2237 if (SrcExpr.isInvalid())
2238 return;
2239
2240 if (Kind == CK_BitCast)
2241 checkCastAlign();
2242}
2243
2244ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
2245 TypeSourceInfo *CastTypeInfo,
2246 SourceLocation RPLoc,
2247 Expr *CastExpr) {
John McCallb45ae252011-10-05 07:41:44 +00002248 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2249 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2250 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
2251
David Blaikie4e4d0842012-03-11 07:00:24 +00002252 if (getLangOpts().CPlusPlus) {
Sebastian Redl6dc00f62012-02-12 18:41:05 +00002253 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false,
2254 isa<InitListExpr>(CastExpr));
John McCalla180f042011-10-06 23:25:11 +00002255 } else {
2256 Op.CheckCStyleCast();
2257 }
2258
John McCallb45ae252011-10-05 07:41:44 +00002259 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00002260 return ExprError();
2261
John McCall5acb0c92011-10-17 18:40:02 +00002262 return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
2263 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
2264 &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
John McCallb45ae252011-10-05 07:41:44 +00002265}
2266
2267ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
2268 SourceLocation LPLoc,
2269 Expr *CastExpr,
2270 SourceLocation RPLoc) {
Sebastian Redl20ff0e22012-02-13 19:55:43 +00002271 assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
John McCallb45ae252011-10-05 07:41:44 +00002272 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2273 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2274 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
2275
Sebastian Redl20ff0e22012-02-13 19:55:43 +00002276 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/true, /*ListInit=*/false);
John McCallb45ae252011-10-05 07:41:44 +00002277 if (Op.SrcExpr.isInvalid())
2278 return ExprError();
Daniel Jaspera770a4d2012-07-16 08:05:07 +00002279
2280 if (CXXConstructExpr *ConstructExpr = dyn_cast<CXXConstructExpr>(Op.SrcExpr.get()))
2281 ConstructExpr->setParenRange(SourceRange(LPLoc, RPLoc));
John McCallb45ae252011-10-05 07:41:44 +00002282
John McCall5acb0c92011-10-17 18:40:02 +00002283 return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
2284 Op.ValueKind, CastTypeInfo, Op.DestRange.getBegin(),
2285 Op.Kind, Op.SrcExpr.take(), &Op.BasePath, RPLoc));
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002286}