blob: d38db87fa5c3957703ab218e3a3501cebfd939b7 [file] [log] [blame]
John McCall3cec19f2011-10-11 17:38:55 +00001//===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===//
Sebastian Redl3c5aa4d2008-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 McCall3cec19f2011-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 Redl3c5aa4d2008-11-05 21:50:06 +000014//
15//===----------------------------------------------------------------------===//
16
John McCall83024632010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
John McCallcda80832013-03-22 02:58:14 +000022#include "clang/AST/RecordLayout.h"
Anders Carlssond624e162009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
David Majnemer1cdd96d2014-01-17 09:01:00 +000024#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Sema/Initialization.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000026#include "llvm/ADT/SmallVector.h"
Sebastian Redl015085f2008-11-07 23:29:29 +000027#include <set>
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000028using namespace clang;
29
Douglas Gregore81f58e2010-11-08 03:40:48 +000030
Douglas Gregore81f58e2010-11-08 03:40:48 +000031
Sebastian Redl9f831db2009-07-25 15:41:38 +000032enum TryCastResult {
33 TC_NotApplicable, ///< The cast method is not applicable.
34 TC_Success, ///< The cast method is appropriate and successful.
35 TC_Failed ///< The cast method is appropriate, but failed. A
36 ///< diagnostic has been emitted.
37};
38
39enum CastType {
40 CT_Const, ///< const_cast
41 CT_Static, ///< static_cast
42 CT_Reinterpret, ///< reinterpret_cast
43 CT_Dynamic, ///< dynamic_cast
44 CT_CStyle, ///< (Type)expr
45 CT_Functional ///< Type(expr)
Sebastian Redl842ef522008-11-08 13:00:26 +000046};
47
John McCallb50451a2011-10-05 07:41:44 +000048namespace {
49 struct CastOperation {
50 CastOperation(Sema &S, QualType destType, ExprResult src)
51 : Self(S), SrcExpr(src), DestType(destType),
52 ResultType(destType.getNonLValueExprType(S.Context)),
53 ValueKind(Expr::getValueKindForType(destType)),
John McCall4124c492011-10-17 18:40:02 +000054 Kind(CK_Dependent), IsARCUnbridgedCast(false) {
John McCall9776e432011-10-06 23:25:11 +000055
56 if (const BuiltinType *placeholder =
57 src.get()->getType()->getAsPlaceholderType()) {
58 PlaceholderKind = placeholder->getKind();
59 } else {
60 PlaceholderKind = (BuiltinType::Kind) 0;
61 }
62 }
Douglas Gregore81f58e2010-11-08 03:40:48 +000063
John McCallb50451a2011-10-05 07:41:44 +000064 Sema &Self;
65 ExprResult SrcExpr;
66 QualType DestType;
67 QualType ResultType;
68 ExprValueKind ValueKind;
69 CastKind Kind;
John McCall9776e432011-10-06 23:25:11 +000070 BuiltinType::Kind PlaceholderKind;
John McCallb50451a2011-10-05 07:41:44 +000071 CXXCastPath BasePath;
John McCall4124c492011-10-17 18:40:02 +000072 bool IsARCUnbridgedCast;
Douglas Gregore81f58e2010-11-08 03:40:48 +000073
John McCallb50451a2011-10-05 07:41:44 +000074 SourceRange OpRange;
75 SourceRange DestRange;
Douglas Gregore81f58e2010-11-08 03:40:48 +000076
John McCall9776e432011-10-06 23:25:11 +000077 // Top-level semantics-checking routines.
John McCallb50451a2011-10-05 07:41:44 +000078 void CheckConstCast();
79 void CheckReinterpretCast();
Richard Smith507840d2011-11-29 22:48:16 +000080 void CheckStaticCast();
John McCallb50451a2011-10-05 07:41:44 +000081 void CheckDynamicCast();
Sebastian Redld74dd492012-02-12 18:41:05 +000082 void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
John McCall9776e432011-10-06 23:25:11 +000083 void CheckCStyleCast();
84
John McCall4124c492011-10-17 18:40:02 +000085 /// Complete an apparently-successful cast operation that yields
86 /// the given expression.
87 ExprResult complete(CastExpr *castExpr) {
88 // If this is an unbridged cast, wrap the result in an implicit
89 // cast that yields the unbridged-cast placeholder type.
90 if (IsARCUnbridgedCast) {
91 castExpr = ImplicitCastExpr::Create(Self.Context,
92 Self.Context.ARCUnbridgedCastTy,
Craig Topperc3ec1492014-05-26 06:22:03 +000093 CK_Dependent, castExpr, nullptr,
John McCall4124c492011-10-17 18:40:02 +000094 castExpr->getValueKind());
95 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000096 return castExpr;
John McCall4124c492011-10-17 18:40:02 +000097 }
98
John McCall9776e432011-10-06 23:25:11 +000099 // Internal convenience methods.
100
101 /// Try to handle the given placeholder expression kind. Return
102 /// true if the source expression has the appropriate placeholder
103 /// kind. A placeholder can only be claimed once.
104 bool claimPlaceholder(BuiltinType::Kind K) {
105 if (PlaceholderKind != K) return false;
106
107 PlaceholderKind = (BuiltinType::Kind) 0;
108 return true;
109 }
110
111 bool isPlaceholder() const {
112 return PlaceholderKind != 0;
113 }
114 bool isPlaceholder(BuiltinType::Kind K) const {
115 return PlaceholderKind == K;
116 }
John McCallb50451a2011-10-05 07:41:44 +0000117
118 void checkCastAlign() {
119 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
120 }
121
122 void checkObjCARCConversion(Sema::CheckedConversionKind CCK) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000123 assert(Self.getLangOpts().ObjCAutoRefCount);
John McCall4124c492011-10-17 18:40:02 +0000124
John McCallb50451a2011-10-05 07:41:44 +0000125 Expr *src = SrcExpr.get();
John McCall4124c492011-10-17 18:40:02 +0000126 if (Self.CheckObjCARCConversion(OpRange, DestType, src, CCK) ==
127 Sema::ACR_unbridged)
128 IsARCUnbridgedCast = true;
John McCallb50451a2011-10-05 07:41:44 +0000129 SrcExpr = src;
130 }
John McCall9776e432011-10-06 23:25:11 +0000131
132 /// Check for and handle non-overload placeholder expressions.
133 void checkNonOverloadPlaceholders() {
134 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
135 return;
136
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000137 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +0000138 if (SrcExpr.isInvalid())
139 return;
140 PlaceholderKind = (BuiltinType::Kind) 0;
141 }
John McCallb50451a2011-10-05 07:41:44 +0000142 };
143}
Sebastian Redl842ef522008-11-08 13:00:26 +0000144
Sebastian Redl9f831db2009-07-25 15:41:38 +0000145// The Try functions attempt a specific way of casting. If they succeed, they
146// return TC_Success. If their way of casting is not appropriate for the given
147// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
148// to emit if no other way succeeds. If their way of casting is appropriate but
149// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
150// they emit a specialized diagnostic.
151// All diagnostics returned by these functions must expect the same three
152// arguments:
153// %0: Cast Type (a value from the CastType enumeration)
154// %1: Source Type
155// %2: Destination Type
156static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
Douglas Gregorce950842011-01-26 21:04:06 +0000157 QualType DestType, bool CStyle,
158 CastKind &Kind,
Douglas Gregorba278e22011-01-25 16:13:26 +0000159 CXXCastPath &BasePath,
160 unsigned &msg);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000161static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000162 QualType DestType, bool CStyle,
163 const SourceRange &OpRange,
164 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000165 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000166 CXXCastPath &BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000167static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
168 QualType DestType, bool CStyle,
169 const SourceRange &OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000170 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000171 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000172 CXXCastPath &BasePath);
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000173static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
174 CanQualType DestType, bool CStyle,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000175 const SourceRange &OpRange,
176 QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000177 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000178 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000179 CXXCastPath &BasePath);
John Wiegley01296292011-04-08 18:41:53 +0000180static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000181 QualType SrcType,
182 QualType DestType,bool CStyle,
183 const SourceRange &OpRange,
184 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000185 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000186 CXXCastPath &BasePath);
Anders Carlssonb78feca2010-04-24 19:22:20 +0000187
John Wiegley01296292011-04-08 18:41:53 +0000188static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000189 QualType DestType,
190 Sema::CheckedConversionKind CCK,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000191 const SourceRange &OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +0000192 unsigned &msg, CastKind &Kind,
193 bool ListInitialization);
John Wiegley01296292011-04-08 18:41:53 +0000194static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000195 QualType DestType,
196 Sema::CheckedConversionKind CCK,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000197 const SourceRange &OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +0000198 unsigned &msg, CastKind &Kind,
199 CXXCastPath &BasePath,
200 bool ListInitialization);
Richard Smith82c9b512013-06-14 22:27:52 +0000201static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
202 QualType DestType, bool CStyle,
203 unsigned &msg);
John Wiegley01296292011-04-08 18:41:53 +0000204static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000205 QualType DestType, bool CStyle,
206 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000207 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000208 CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +0000209
Douglas Gregorb491ed32011-02-19 21:32:49 +0000210
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000211/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
John McCalldadc5752010-08-24 06:29:42 +0000212ExprResult
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000213Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000214 SourceLocation LAngleBracketLoc, Declarator &D,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000215 SourceLocation RAngleBracketLoc,
John McCallfaf5fb42010-08-26 23:41:50 +0000216 SourceLocation LParenLoc, Expr *E,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000217 SourceLocation RParenLoc) {
John McCalld377e042010-01-15 19:13:16 +0000218
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000219 assert(!D.isInvalidType());
220
221 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
222 if (D.isInvalidType())
223 return ExprError();
224
David Blaikiebbafb8a2012-03-11 07:00:24 +0000225 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000226 // Check that there are no default arguments (C++ only).
227 CheckExtraCXXDefaultArguments(D);
228 }
229
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000230 return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
John McCalld377e042010-01-15 19:13:16 +0000231 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
232 SourceRange(LParenLoc, RParenLoc));
233}
234
John McCalldadc5752010-08-24 06:29:42 +0000235ExprResult
John McCalld377e042010-01-15 19:13:16 +0000236Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John Wiegley01296292011-04-08 18:41:53 +0000237 TypeSourceInfo *DestTInfo, Expr *E,
John McCalld377e042010-01-15 19:13:16 +0000238 SourceRange AngleBrackets, SourceRange Parens) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000239 ExprResult Ex = E;
John McCalld377e042010-01-15 19:13:16 +0000240 QualType DestType = DestTInfo->getType();
241
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000242 // If the type is dependent, we won't do the semantic analysis now.
243 // FIXME: should we check this in a more fine-grained manner?
Eli Friedman71271082013-09-19 01:12:33 +0000244 bool TypeDependent = DestType->isDependentType() ||
245 Ex.get()->isTypeDependent() ||
246 Ex.get()->isValueDependent();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000247
John McCallb50451a2011-10-05 07:41:44 +0000248 CastOperation Op(*this, DestType, E);
249 Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
250 Op.DestRange = AngleBrackets;
John McCall29ac8e22010-11-26 10:57:22 +0000251
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000252 switch (Kind) {
John McCall8cb679e2010-11-15 09:13:47 +0000253 default: llvm_unreachable("Unknown C++ cast!");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000254
255 case tok::kw_const_cast:
John Wiegley01296292011-04-08 18:41:53 +0000256 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000257 Op.CheckConstCast();
258 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000259 return ExprError();
260 }
John McCall4124c492011-10-17 18:40:02 +0000261 return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000262 Op.ValueKind, Op.SrcExpr.get(), DestTInfo,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000263 OpLoc, Parens.getEnd(),
264 AngleBrackets));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000265
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000266 case tok::kw_dynamic_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000267 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000268 Op.CheckDynamicCast();
269 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000270 return ExprError();
271 }
John McCall4124c492011-10-17 18:40:02 +0000272 return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000273 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
John McCall4124c492011-10-17 18:40:02 +0000274 &Op.BasePath, DestTInfo,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000275 OpLoc, Parens.getEnd(),
276 AngleBrackets));
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000277 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000278 case tok::kw_reinterpret_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000279 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000280 Op.CheckReinterpretCast();
281 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000282 return ExprError();
283 }
John McCall4124c492011-10-17 18:40:02 +0000284 return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000285 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +0000286 nullptr, DestTInfo, OpLoc,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000287 Parens.getEnd(),
288 AngleBrackets));
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000289 }
Anders Carlssonf10e4142009-08-07 22:21:05 +0000290 case tok::kw_static_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000291 if (!TypeDependent) {
Richard Smith507840d2011-11-29 22:48:16 +0000292 Op.CheckStaticCast();
John McCallb50451a2011-10-05 07:41:44 +0000293 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000294 return ExprError();
295 }
Anders Carlssone9766d52009-09-09 21:33:21 +0000296
John McCall4124c492011-10-17 18:40:02 +0000297 return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000298 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
John McCall4124c492011-10-17 18:40:02 +0000299 &Op.BasePath, DestTInfo,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000300 OpLoc, Parens.getEnd(),
301 AngleBrackets));
Anders Carlssonf10e4142009-08-07 22:21:05 +0000302 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000303 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000304}
305
John McCall909acf82011-02-14 18:34:10 +0000306/// Try to diagnose a failed overloaded cast. Returns true if
307/// diagnostics were emitted.
308static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
309 SourceRange range, Expr *src,
Sebastian Redl2b80af42012-02-13 19:55:43 +0000310 QualType destType,
311 bool listInitialization) {
John McCall909acf82011-02-14 18:34:10 +0000312 switch (CT) {
313 // These cast kinds don't consider user-defined conversions.
314 case CT_Const:
315 case CT_Reinterpret:
316 case CT_Dynamic:
317 return false;
318
319 // These do.
320 case CT_Static:
321 case CT_CStyle:
322 case CT_Functional:
323 break;
324 }
325
326 QualType srcType = src->getType();
327 if (!destType->isRecordType() && !srcType->isRecordType())
328 return false;
329
330 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
331 InitializationKind initKind
John McCall31168b02011-06-15 23:02:42 +0000332 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
Sebastian Redl2b80af42012-02-13 19:55:43 +0000333 range, listInitialization)
Sebastian Redl0501c632012-02-12 16:37:36 +0000334 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
Sebastian Redl2b80af42012-02-13 19:55:43 +0000335 listInitialization)
Richard Smith507840d2011-11-29 22:48:16 +0000336 : InitializationKind::CreateCast(/*type range?*/ range);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000337 InitializationSequence sequence(S, entity, initKind, src);
John McCall909acf82011-02-14 18:34:10 +0000338
Sebastian Redlc7ca5872011-06-05 12:23:28 +0000339 assert(sequence.Failed() && "initialization succeeded on second try?");
John McCall909acf82011-02-14 18:34:10 +0000340 switch (sequence.getFailureKind()) {
341 default: return false;
342
343 case InitializationSequence::FK_ConstructorOverloadFailed:
344 case InitializationSequence::FK_UserConversionOverloadFailed:
345 break;
346 }
347
348 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
349
350 unsigned msg = 0;
351 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
352
353 switch (sequence.getFailedOverloadResult()) {
354 case OR_Success: llvm_unreachable("successful failed overload");
John McCall909acf82011-02-14 18:34:10 +0000355 case OR_No_Viable_Function:
356 if (candidates.empty())
357 msg = diag::err_ovl_no_conversion_in_cast;
358 else
359 msg = diag::err_ovl_no_viable_conversion_in_cast;
360 howManyCandidates = OCD_AllCandidates;
361 break;
362
363 case OR_Ambiguous:
364 msg = diag::err_ovl_ambiguous_conversion_in_cast;
365 howManyCandidates = OCD_ViableCandidates;
366 break;
367
368 case OR_Deleted:
369 msg = diag::err_ovl_deleted_conversion_in_cast;
370 howManyCandidates = OCD_ViableCandidates;
371 break;
372 }
373
374 S.Diag(range.getBegin(), msg)
375 << CT << srcType << destType
376 << range << src->getSourceRange();
377
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +0000378 candidates.NoteCandidates(S, howManyCandidates, src);
John McCall909acf82011-02-14 18:34:10 +0000379
380 return true;
381}
382
383/// Diagnose a failed cast.
384static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
Sebastian Redl2b80af42012-02-13 19:55:43 +0000385 SourceRange opRange, Expr *src, QualType destType,
386 bool listInitialization) {
John McCall909acf82011-02-14 18:34:10 +0000387 if (msg == diag::err_bad_cxx_cast_generic &&
Sebastian Redl2b80af42012-02-13 19:55:43 +0000388 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
389 listInitialization))
John McCall909acf82011-02-14 18:34:10 +0000390 return;
391
392 S.Diag(opRange.getBegin(), msg) << castType
393 << src->getType() << destType << opRange << src->getSourceRange();
394}
395
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000396/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
397/// this removes one level of indirection from both types, provided that they're
398/// the same kind of pointer (plain or to-member). Unlike the Sema function,
399/// this one doesn't care if the two pointers-to-member don't point into the
400/// same class. This is because CastsAwayConstness doesn't care.
Dan Gohman28ade552010-07-26 21:25:24 +0000401static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000402 const PointerType *T1PtrType = T1->getAs<PointerType>(),
403 *T2PtrType = T2->getAs<PointerType>();
404 if (T1PtrType && T2PtrType) {
405 T1 = T1PtrType->getPointeeType();
406 T2 = T2PtrType->getPointeeType();
407 return true;
408 }
Fariborz Jahanian8c3f06d2010-02-03 20:32:31 +0000409 const ObjCObjectPointerType *T1ObjCPtrType =
410 T1->getAs<ObjCObjectPointerType>(),
411 *T2ObjCPtrType =
412 T2->getAs<ObjCObjectPointerType>();
413 if (T1ObjCPtrType) {
414 if (T2ObjCPtrType) {
415 T1 = T1ObjCPtrType->getPointeeType();
416 T2 = T2ObjCPtrType->getPointeeType();
417 return true;
418 }
419 else if (T2PtrType) {
420 T1 = T1ObjCPtrType->getPointeeType();
421 T2 = T2PtrType->getPointeeType();
422 return true;
423 }
424 }
425 else if (T2ObjCPtrType) {
426 if (T1PtrType) {
427 T2 = T2ObjCPtrType->getPointeeType();
428 T1 = T1PtrType->getPointeeType();
429 return true;
430 }
431 }
432
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000433 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
434 *T2MPType = T2->getAs<MemberPointerType>();
435 if (T1MPType && T2MPType) {
436 T1 = T1MPType->getPointeeType();
437 T2 = T2MPType->getPointeeType();
438 return true;
439 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000440
441 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
442 *T2BPType = T2->getAs<BlockPointerType>();
443 if (T1BPType && T2BPType) {
444 T1 = T1BPType->getPointeeType();
445 T2 = T2BPType->getPointeeType();
446 return true;
447 }
448
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000449 return false;
450}
451
Sebastian Redla5a77a62009-01-27 23:18:31 +0000452/// CastsAwayConstness - Check if the pointer conversion from SrcType to
453/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
454/// the cast checkers. Both arguments must denote pointer (possibly to member)
455/// types.
John McCall31168b02011-06-15 23:02:42 +0000456///
457/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
458///
459/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
Sebastian Redl802f14c2009-10-22 15:07:22 +0000460static bool
John McCall31168b02011-06-15 23:02:42 +0000461CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
Roman Divackyd5178012014-11-21 21:03:10 +0000462 bool CheckCVR, bool CheckObjCLifetime,
463 QualType *TheOffendingSrcType = nullptr,
464 QualType *TheOffendingDestType = nullptr,
465 Qualifiers *CastAwayQualifiers = nullptr) {
John McCall31168b02011-06-15 23:02:42 +0000466 // If the only checking we care about is for Objective-C lifetime qualifiers,
467 // and we're not in ARC mode, there's nothing to check.
468 if (!CheckCVR && CheckObjCLifetime &&
David Blaikiebbafb8a2012-03-11 07:00:24 +0000469 !Self.Context.getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +0000470 return false;
471
Sebastian Redla5a77a62009-01-27 23:18:31 +0000472 // Casting away constness is defined in C++ 5.2.11p8 with reference to
473 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
474 // the rules are non-trivial. So first we construct Tcv *...cv* as described
475 // in C++ 5.2.11p8.
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000476 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
477 SrcType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000478 "Source type is not pointer or pointer to member.");
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000479 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
480 DestType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000481 "Destination type is not pointer or pointer to member.");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000482
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000483 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
484 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000485 SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000486
Douglas Gregorb472e932011-04-15 17:59:54 +0000487 // Find the qualifiers. We only care about cvr-qualifiers for the
488 // purpose of this check, because other qualifiers (address spaces,
489 // Objective-C GC, etc.) are part of the type's identity.
Roman Divackyd5178012014-11-21 21:03:10 +0000490 QualType PrevUnwrappedSrcType = UnwrappedSrcType;
491 QualType PrevUnwrappedDestType = UnwrappedDestType;
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000492 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCall31168b02011-06-15 23:02:42 +0000493 // Determine the relevant qualifiers at this level.
494 Qualifiers SrcQuals, DestQuals;
Anders Carlsson76f513f2010-06-04 22:47:55 +0000495 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
Anders Carlsson76f513f2010-06-04 22:47:55 +0000496 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
John McCall31168b02011-06-15 23:02:42 +0000497
498 Qualifiers RetainedSrcQuals, RetainedDestQuals;
499 if (CheckCVR) {
500 RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
501 RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
Roman Divackyd5178012014-11-21 21:03:10 +0000502
503 if (RetainedSrcQuals != RetainedDestQuals && TheOffendingSrcType &&
504 TheOffendingDestType && CastAwayQualifiers) {
505 *TheOffendingSrcType = PrevUnwrappedSrcType;
506 *TheOffendingDestType = PrevUnwrappedDestType;
507 *CastAwayQualifiers = RetainedSrcQuals - RetainedDestQuals;
508 }
John McCall31168b02011-06-15 23:02:42 +0000509 }
510
511 if (CheckObjCLifetime &&
512 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
513 return true;
514
515 cv1.push_back(RetainedSrcQuals);
516 cv2.push_back(RetainedDestQuals);
Roman Divackyd5178012014-11-21 21:03:10 +0000517
518 PrevUnwrappedSrcType = UnwrappedSrcType;
519 PrevUnwrappedDestType = UnwrappedDestType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000520 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000521 if (cv1.empty())
522 return false;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000523
524 // Construct void pointers with those qualifiers (in reverse order of
525 // unwrapping, of course).
Sebastian Redl842ef522008-11-08 13:00:26 +0000526 QualType SrcConstruct = Self.Context.VoidTy;
527 QualType DestConstruct = Self.Context.VoidTy;
John McCall8ccfcb52009-09-24 19:53:00 +0000528 ASTContext &Context = Self.Context;
Craig Topper61ac9062013-07-08 03:55:09 +0000529 for (SmallVectorImpl<Qualifiers>::reverse_iterator i1 = cv1.rbegin(),
530 i2 = cv2.rbegin();
Mike Stump11289f42009-09-09 15:08:12 +0000531 i1 != cv1.rend(); ++i1, ++i2) {
John McCall8ccfcb52009-09-24 19:53:00 +0000532 SrcConstruct
533 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
534 DestConstruct
535 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000536 }
537
538 // Test if they're compatible.
John McCall31168b02011-06-15 23:02:42 +0000539 bool ObjCLifetimeConversion;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000540 return SrcConstruct != DestConstruct &&
John McCall31168b02011-06-15 23:02:42 +0000541 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
542 ObjCLifetimeConversion);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000543}
544
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000545/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
546/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
547/// checked downcasts in class hierarchies.
John McCallb50451a2011-10-05 07:41:44 +0000548void CastOperation::CheckDynamicCast() {
Eli Friedman42b199c2012-01-12 00:44:34 +0000549 if (ValueKind == VK_RValue)
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000550 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000551 else if (isPlaceholder())
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000552 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000553 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
554 return;
Eli Friedman90a2cdf2011-10-31 20:59:03 +0000555
John McCallb50451a2011-10-05 07:41:44 +0000556 QualType OrigSrcType = SrcExpr.get()->getType();
557 QualType DestType = Self.Context.getCanonicalType(this->DestType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000558
559 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
560 // or "pointer to cv void".
561
562 QualType DestPointee;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000563 const PointerType *DestPointer = DestType->getAs<PointerType>();
Craig Topperc3ec1492014-05-26 06:22:03 +0000564 const ReferenceType *DestReference = nullptr;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000565 if (DestPointer) {
566 DestPointee = DestPointer->getPointeeType();
John McCall7decc9e2010-11-18 06:31:45 +0000567 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000568 DestPointee = DestReference->getPointeeType();
569 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000570 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
John McCallb50451a2011-10-05 07:41:44 +0000571 << this->DestType << DestRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000572 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000573 return;
574 }
575
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000576 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000577 if (DestPointee->isVoidType()) {
578 assert(DestPointer && "Reference to void is not possible");
579 } else if (DestRecord) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000580 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000581 diag::err_bad_dynamic_cast_incomplete,
Eli Friedman3fd26b82013-07-26 23:47:47 +0000582 DestRange)) {
583 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000584 return;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000585 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000586 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000587 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000588 << DestPointee.getUnqualifiedType() << DestRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000589 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000590 return;
591 }
592
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000593 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
594 // complete class type, [...]. If T is an lvalue reference type, v shall be
Douglas Gregor465184a2011-01-22 00:06:57 +0000595 // an lvalue of a complete class type, [...]. If T is an rvalue reference
596 // type, v shall be an expression having a complete class type, [...]
Sebastian Redl842ef522008-11-08 13:00:26 +0000597 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000598 QualType SrcPointee;
599 if (DestPointer) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000600 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000601 SrcPointee = SrcPointer->getPointeeType();
602 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000603 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
John Wiegley01296292011-04-08 18:41:53 +0000604 << OrigSrcType << SrcExpr.get()->getSourceRange();
Eli Friedman3fd26b82013-07-26 23:47:47 +0000605 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000606 return;
607 }
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000608 } else if (DestReference->isLValueReferenceType()) {
John Wiegley01296292011-04-08 18:41:53 +0000609 if (!SrcExpr.get()->isLValue()) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000610 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
John McCallb50451a2011-10-05 07:41:44 +0000611 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000612 }
613 SrcPointee = SrcType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000614 } else {
Richard Smith11330852014-07-08 17:25:14 +0000615 // If we're dynamic_casting from a prvalue to an rvalue reference, we need
616 // to materialize the prvalue before we bind the reference to it.
617 if (SrcExpr.get()->isRValue())
618 SrcExpr = new (Self.Context) MaterializeTemporaryExpr(
619 SrcType, SrcExpr.get(), /*IsLValueReference*/false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000620 SrcPointee = SrcType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000621 }
622
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000623 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000624 if (SrcRecord) {
Douglas Gregored0cfbd2009-03-09 16:13:40 +0000625 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000626 diag::err_bad_dynamic_cast_incomplete,
Eli Friedman3fd26b82013-07-26 23:47:47 +0000627 SrcExpr.get())) {
628 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000629 return;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000630 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000631 } else {
Chris Lattner29e812b2008-11-20 06:06:08 +0000632 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
John Wiegley01296292011-04-08 18:41:53 +0000633 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Eli Friedman3fd26b82013-07-26 23:47:47 +0000634 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000635 return;
636 }
637
638 assert((DestPointer || DestReference) &&
639 "Bad destination non-ptr/ref slipped through.");
640 assert((DestRecord || DestPointee->isVoidType()) &&
641 "Bad destination pointee slipped through.");
642 assert(SrcRecord && "Bad source pointee slipped through.");
643
644 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
645 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Douglas Gregorb472e932011-04-15 17:59:54 +0000646 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
John McCallb50451a2011-10-05 07:41:44 +0000647 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000648 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000649 return;
650 }
651
652 // C++ 5.2.7p3: If the type of v is the same as the required result type,
653 // [except for cv].
654 if (DestRecord == SrcRecord) {
John McCalle3027922010-08-25 11:45:40 +0000655 Kind = CK_NoOp;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000656 return;
657 }
658
659 // C++ 5.2.7p5
660 // Upcasts are resolved statically.
Sebastian Redl842ef522008-11-08 13:00:26 +0000661 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000662 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
663 OpRange.getBegin(), OpRange,
Eli Friedman3fd26b82013-07-26 23:47:47 +0000664 &BasePath)) {
665 SrcExpr = ExprError();
666 return;
667 }
Richard Smith11330852014-07-08 17:25:14 +0000668
John McCalle3027922010-08-25 11:45:40 +0000669 Kind = CK_DerivedToBase;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000670
671 // If we are casting to or through a virtual base class, we need a
672 // vtable.
673 if (Self.BasePathInvolvesVirtualBase(BasePath))
674 Self.MarkVTableUsed(OpRange.getBegin(),
675 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000676 return;
677 }
678
679 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000680 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000681 assert(SrcDecl && "Definition missing");
682 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner29e812b2008-11-20 06:06:08 +0000683 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
John Wiegley01296292011-04-08 18:41:53 +0000684 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Eli Friedman3fd26b82013-07-26 23:47:47 +0000685 SrcExpr = ExprError();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000686 }
Douglas Gregor88d292c2010-05-13 16:44:06 +0000687 Self.MarkVTableUsed(OpRange.getBegin(),
688 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000689
Eli Friedman3ce27102013-09-24 23:21:41 +0000690 // dynamic_cast is not available with -fno-rtti.
691 // As an exception, dynamic_cast to void* is available because it doesn't
692 // use RTTI.
693 if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) {
Arnaud A. de Grandmaisoncb6f9432013-08-01 08:28:32 +0000694 Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti);
695 SrcExpr = ExprError();
696 return;
697 }
698
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000699 // Done. Everything else is run-time checks.
John McCalle3027922010-08-25 11:45:40 +0000700 Kind = CK_Dynamic;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000701}
Sebastian Redl9f831db2009-07-25 15:41:38 +0000702
703/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
704/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
705/// like this:
706/// const char *str = "literal";
707/// legacy_function(const_cast\<char*\>(str));
John McCallb50451a2011-10-05 07:41:44 +0000708void CastOperation::CheckConstCast() {
Eli Friedman42b199c2012-01-12 00:44:34 +0000709 if (ValueKind == VK_RValue)
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000710 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000711 else if (isPlaceholder())
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000712 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000713 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
714 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000715
716 unsigned msg = diag::err_bad_cxx_cast_generic;
Richard Smith82c9b512013-06-14 22:27:52 +0000717 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
Eli Friedman3fd26b82013-07-26 23:47:47 +0000718 && msg != 0) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000719 Self.Diag(OpRange.getBegin(), msg) << CT_Const
John Wiegley01296292011-04-08 18:41:53 +0000720 << SrcExpr.get()->getType() << DestType << OpRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000721 SrcExpr = ExprError();
722 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000723}
724
John McCallcda80832013-03-22 02:58:14 +0000725/// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
726/// or downcast between respective pointers or references.
727static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
728 QualType DestType,
729 SourceRange OpRange) {
730 QualType SrcType = SrcExpr->getType();
731 // When casting from pointer or reference, get pointee type; use original
732 // type otherwise.
733 const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
734 const CXXRecordDecl *SrcRD =
735 SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
736
John McCallf2abe192013-03-27 00:03:48 +0000737 // Examining subobjects for records is only possible if the complete and
738 // valid definition is available. Also, template instantiation is not
739 // allowed here.
740 if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
John McCallcda80832013-03-22 02:58:14 +0000741 return;
742
743 const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
744
John McCallf2abe192013-03-27 00:03:48 +0000745 if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
John McCallcda80832013-03-22 02:58:14 +0000746 return;
747
748 enum {
749 ReinterpretUpcast,
750 ReinterpretDowncast
751 } ReinterpretKind;
752
753 CXXBasePaths BasePaths;
754
755 if (SrcRD->isDerivedFrom(DestRD, BasePaths))
756 ReinterpretKind = ReinterpretUpcast;
757 else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
758 ReinterpretKind = ReinterpretDowncast;
759 else
760 return;
761
762 bool VirtualBase = true;
763 bool NonZeroOffset = false;
John McCallf2abe192013-03-27 00:03:48 +0000764 for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
John McCallcda80832013-03-22 02:58:14 +0000765 E = BasePaths.end();
766 I != E; ++I) {
767 const CXXBasePath &Path = *I;
768 CharUnits Offset = CharUnits::Zero();
769 bool IsVirtual = false;
770 for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
771 IElem != EElem; ++IElem) {
772 IsVirtual = IElem->Base->isVirtual();
773 if (IsVirtual)
774 break;
775 const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
776 assert(BaseRD && "Base type should be a valid unqualified class type");
John McCallf2abe192013-03-27 00:03:48 +0000777 // Don't check if any base has invalid declaration or has no definition
778 // since it has no layout info.
779 const CXXRecordDecl *Class = IElem->Class,
780 *ClassDefinition = Class->getDefinition();
781 if (Class->isInvalidDecl() || !ClassDefinition ||
782 !ClassDefinition->isCompleteDefinition())
783 return;
784
John McCallcda80832013-03-22 02:58:14 +0000785 const ASTRecordLayout &DerivedLayout =
John McCallf2abe192013-03-27 00:03:48 +0000786 Self.Context.getASTRecordLayout(Class);
John McCallcda80832013-03-22 02:58:14 +0000787 Offset += DerivedLayout.getBaseClassOffset(BaseRD);
788 }
789 if (!IsVirtual) {
790 // Don't warn if any path is a non-virtually derived base at offset zero.
791 if (Offset.isZero())
792 return;
793 // Offset makes sense only for non-virtual bases.
794 else
795 NonZeroOffset = true;
796 }
797 VirtualBase = VirtualBase && IsVirtual;
798 }
799
Andy Gibbsfa5026d2013-06-19 13:33:37 +0000800 (void) NonZeroOffset; // Silence set but not used warning.
John McCallcda80832013-03-22 02:58:14 +0000801 assert((VirtualBase || NonZeroOffset) &&
802 "Should have returned if has non-virtual base with zero offset");
803
804 QualType BaseType =
805 ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
806 QualType DerivedType =
807 ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
808
Jordan Rose04a94d12013-03-28 19:09:40 +0000809 SourceLocation BeginLoc = OpRange.getBegin();
810 Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000811 << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind)
Jordan Rose04a94d12013-03-28 19:09:40 +0000812 << OpRange;
813 Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000814 << int(ReinterpretKind)
Jordan Rose04a94d12013-03-28 19:09:40 +0000815 << FixItHint::CreateReplacement(BeginLoc, "static_cast");
John McCallcda80832013-03-22 02:58:14 +0000816}
817
Sebastian Redl9f831db2009-07-25 15:41:38 +0000818/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
819/// valid.
820/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
821/// like this:
822/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
John McCallb50451a2011-10-05 07:41:44 +0000823void CastOperation::CheckReinterpretCast() {
Eli Friedman42b199c2012-01-12 00:44:34 +0000824 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000825 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000826 else
827 checkNonOverloadPlaceholders();
828 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
829 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000830
831 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCall31168b02011-06-15 23:02:42 +0000832 TryCastResult tcr =
833 TryReinterpretCast(Self, SrcExpr, DestType,
834 /*CStyle*/false, OpRange, msg, Kind);
835 if (tcr != TC_Success && msg != 0)
Douglas Gregore81f58e2010-11-08 03:40:48 +0000836 {
John Wiegley01296292011-04-08 18:41:53 +0000837 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
838 return;
839 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +0000840 //FIXME: &f<int>; is overloaded and resolvable
841 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
John Wiegley01296292011-04-08 18:41:53 +0000842 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
Douglas Gregore81f58e2010-11-08 03:40:48 +0000843 << DestType << OpRange;
John Wiegley01296292011-04-08 18:41:53 +0000844 Self.NoteAllOverloadCandidates(SrcExpr.get());
Douglas Gregore81f58e2010-11-08 03:40:48 +0000845
John McCall909acf82011-02-14 18:34:10 +0000846 } else {
Sebastian Redl2b80af42012-02-13 19:55:43 +0000847 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
848 DestType, /*listInitialization=*/false);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000849 }
Eli Friedman3fd26b82013-07-26 23:47:47 +0000850 SrcExpr = ExprError();
John McCallcda80832013-03-22 02:58:14 +0000851 } else if (tcr == TC_Success) {
852 if (Self.getLangOpts().ObjCAutoRefCount)
853 checkObjCARCConversion(Sema::CCK_OtherCast);
854 DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
John McCall31168b02011-06-15 23:02:42 +0000855 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000856}
857
858
859/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
860/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
861/// implicit conversions explicit and getting rid of data loss warnings.
Richard Smith507840d2011-11-29 22:48:16 +0000862void CastOperation::CheckStaticCast() {
John McCall9776e432011-10-06 23:25:11 +0000863 if (isPlaceholder()) {
864 checkNonOverloadPlaceholders();
865 if (SrcExpr.isInvalid())
866 return;
867 }
868
Sebastian Redl9f831db2009-07-25 15:41:38 +0000869 // This test is outside everything else because it's the only case where
870 // a non-lvalue-reference target type does not lead to decay.
871 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman03bf60a2009-11-16 05:44:20 +0000872 if (DestType->isVoidType()) {
John McCall9776e432011-10-06 23:25:11 +0000873 Kind = CK_ToVoid;
874
875 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall50a2c2c2011-10-11 23:14:30 +0000876 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
Douglas Gregorb491ed32011-02-19 21:32:49 +0000877 false, // Decay Function to ptr
878 true, // Complain
879 OpRange, DestType, diag::err_bad_static_cast_overload);
John McCall50a2c2c2011-10-11 23:14:30 +0000880 if (SrcExpr.isInvalid())
881 return;
Douglas Gregorb491ed32011-02-19 21:32:49 +0000882 }
John McCall9776e432011-10-06 23:25:11 +0000883
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000884 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
Sebastian Redl9f831db2009-07-25 15:41:38 +0000885 return;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000886 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000887
John McCall50a2c2c2011-10-11 23:14:30 +0000888 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
889 !isPlaceholder(BuiltinType::Overload)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000890 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
John Wiegley01296292011-04-08 18:41:53 +0000891 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
892 return;
893 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000894
895 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCall31168b02011-06-15 23:02:42 +0000896 TryCastResult tcr
Richard Smith507840d2011-11-29 22:48:16 +0000897 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
Sebastian Redld74dd492012-02-12 18:41:05 +0000898 Kind, BasePath, /*ListInitialization=*/false);
John McCall31168b02011-06-15 23:02:42 +0000899 if (tcr != TC_Success && msg != 0) {
John Wiegley01296292011-04-08 18:41:53 +0000900 if (SrcExpr.isInvalid())
901 return;
902 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
903 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
Douglas Gregore81f58e2010-11-08 03:40:48 +0000904 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
Douglas Gregor0da1d432011-02-28 20:01:57 +0000905 << oe->getName() << DestType << OpRange
906 << oe->getQualifierLoc().getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +0000907 Self.NoteAllOverloadCandidates(SrcExpr.get());
John McCall909acf82011-02-14 18:34:10 +0000908 } else {
Sebastian Redl2b80af42012-02-13 19:55:43 +0000909 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
910 /*listInitialization=*/false);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000911 }
Eli Friedman3fd26b82013-07-26 23:47:47 +0000912 SrcExpr = ExprError();
John McCall31168b02011-06-15 23:02:42 +0000913 } else if (tcr == TC_Success) {
914 if (Kind == CK_BitCast)
John McCallb50451a2011-10-05 07:41:44 +0000915 checkCastAlign();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000916 if (Self.getLangOpts().ObjCAutoRefCount)
Richard Smith507840d2011-11-29 22:48:16 +0000917 checkObjCARCConversion(Sema::CCK_OtherCast);
John McCallb50451a2011-10-05 07:41:44 +0000918 } else if (Kind == CK_BitCast) {
919 checkCastAlign();
Douglas Gregore81f58e2010-11-08 03:40:48 +0000920 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000921}
922
923/// TryStaticCast - Check if a static cast can be performed, and do so if
924/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
925/// and casting away constness.
John Wiegley01296292011-04-08 18:41:53 +0000926static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000927 QualType DestType,
928 Sema::CheckedConversionKind CCK,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000929 const SourceRange &OpRange, unsigned &msg,
Sebastian Redld74dd492012-02-12 18:41:05 +0000930 CastKind &Kind, CXXCastPath &BasePath,
931 bool ListInitialization) {
John McCall31168b02011-06-15 23:02:42 +0000932 // Determine whether we have the semantics of a C-style cast.
933 bool CStyle
934 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
935
Sebastian Redl9f831db2009-07-25 15:41:38 +0000936 // The order the tests is not entirely arbitrary. There is one conversion
937 // that can be handled in two different ways. Given:
938 // struct A {};
939 // struct B : public A {
940 // B(); B(const A&);
941 // };
942 // const A &a = B();
943 // the cast static_cast<const B&>(a) could be seen as either a static
944 // reference downcast, or an explicit invocation of the user-defined
945 // conversion using B's conversion constructor.
946 // DR 427 specifies that the downcast is to be applied here.
947
948 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
949 // Done outside this function.
950
951 TryCastResult tcr;
952
953 // C++ 5.2.9p5, reference downcast.
954 // See the function for details.
955 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redld74dd492012-02-12 18:41:05 +0000956 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
957 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000958 if (tcr != TC_NotApplicable)
959 return tcr;
960
Douglas Gregor465184a2011-01-22 00:06:57 +0000961 // C++0x [expr.static.cast]p3:
962 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
963 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Sebastian Redld74dd492012-02-12 18:41:05 +0000964 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
965 BasePath, msg);
Douglas Gregorba278e22011-01-25 16:13:26 +0000966 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000967 return tcr;
968
969 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
970 // [...] if the declaration "T t(e);" is well-formed, [...].
John McCall31168b02011-06-15 23:02:42 +0000971 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
Sebastian Redld74dd492012-02-12 18:41:05 +0000972 Kind, ListInitialization);
John Wiegley01296292011-04-08 18:41:53 +0000973 if (SrcExpr.isInvalid())
974 return TC_Failed;
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000975 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000976 return tcr;
Anders Carlssone9766d52009-09-09 21:33:21 +0000977
Sebastian Redl9f831db2009-07-25 15:41:38 +0000978 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
979 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
980 // conversions, subject to further restrictions.
981 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
982 // of qualification conversions impossible.
983 // In the CStyle case, the earlier attempt to const_cast should have taken
984 // care of reverse qualification conversions.
985
John Wiegley01296292011-04-08 18:41:53 +0000986 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
Sebastian Redl9f831db2009-07-25 15:41:38 +0000987
Douglas Gregor0bf31402010-10-08 23:50:27 +0000988 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
Douglas Gregorb327eac2011-02-18 03:01:41 +0000989 // converted to an integral type. [...] A value of a scoped enumeration type
990 // can also be explicitly converted to a floating-point type [...].
991 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
992 if (Enum->getDecl()->isScoped()) {
993 if (DestType->isBooleanType()) {
994 Kind = CK_IntegralToBoolean;
995 return TC_Success;
996 } else if (DestType->isIntegralType(Self.Context)) {
997 Kind = CK_IntegralCast;
998 return TC_Success;
999 } else if (DestType->isRealFloatingType()) {
1000 Kind = CK_IntegralToFloating;
1001 return TC_Success;
1002 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00001003 }
1004 }
Douglas Gregorb327eac2011-02-18 03:01:41 +00001005
Sebastian Redl9f831db2009-07-25 15:41:38 +00001006 // Reverse integral promotion/conversion. All such conversions are themselves
1007 // again integral promotions or conversions and are thus already handled by
1008 // p2 (TryDirectInitialization above).
1009 // (Note: any data loss warnings should be suppressed.)
1010 // The exception is the reverse of enum->integer, i.e. integer->enum (and
1011 // enum->enum). See also C++ 5.2.9p7.
1012 // The same goes for reverse floating point promotion/conversion and
1013 // floating-integral conversions. Again, only floating->enum is relevant.
1014 if (DestType->isEnumeralType()) {
Eli Friedman29538892011-09-02 17:38:59 +00001015 if (SrcType->isIntegralOrEnumerationType()) {
John McCalle3027922010-08-25 11:45:40 +00001016 Kind = CK_IntegralCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001017 return TC_Success;
Eli Friedman29538892011-09-02 17:38:59 +00001018 } else if (SrcType->isRealFloatingType()) {
1019 Kind = CK_FloatingToIntegral;
1020 return TC_Success;
Eli Friedman03bf60a2009-11-16 05:44:20 +00001021 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001022 }
1023
1024 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
1025 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson9a1cd872009-11-12 16:53:16 +00001026 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001027 Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001028 if (tcr != TC_NotApplicable)
1029 return tcr;
1030
1031 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
1032 // conversion. C++ 5.2.9p9 has additional information.
1033 // DR54's access restrictions apply here also.
Douglas Gregorc934bc82010-03-07 23:24:59 +00001034 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001035 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001036 if (tcr != TC_NotApplicable)
1037 return tcr;
1038
1039 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
1040 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
1041 // just the usual constness stuff.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001042 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001043 QualType SrcPointee = SrcPointer->getPointeeType();
1044 if (SrcPointee->isVoidType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001045 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001046 QualType DestPointee = DestPointer->getPointeeType();
1047 if (DestPointee->isIncompleteOrObjectType()) {
1048 // This is definitely the intended conversion, but it might fail due
John McCall31168b02011-06-15 23:02:42 +00001049 // to a qualifier violation. Note that we permit Objective-C lifetime
1050 // and GC qualifier mismatches here.
1051 if (!CStyle) {
1052 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
1053 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
1054 DestPointeeQuals.removeObjCGCAttr();
1055 DestPointeeQuals.removeObjCLifetime();
1056 SrcPointeeQuals.removeObjCGCAttr();
1057 SrcPointeeQuals.removeObjCLifetime();
1058 if (DestPointeeQuals != SrcPointeeQuals &&
1059 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
1060 msg = diag::err_bad_cxx_cast_qualifiers_away;
1061 return TC_Failed;
1062 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001063 }
John McCalle3027922010-08-25 11:45:40 +00001064 Kind = CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001065 return TC_Success;
1066 }
1067 }
Fariborz Jahanianeee16692010-05-10 23:46:53 +00001068 else if (DestType->isObjCObjectPointerType()) {
1069 // allow both c-style cast and static_cast of objective-c pointers as
1070 // they are pervasive.
John McCall9320b872011-09-09 05:25:32 +00001071 Kind = CK_CPointerToObjCPointerCast;
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001072 return TC_Success;
1073 }
Fariborz Jahanianffe912c2009-12-11 22:40:48 +00001074 else if (CStyle && DestType->isBlockPointerType()) {
1075 // allow c-style cast of void * to block pointers.
John McCalle3027922010-08-25 11:45:40 +00001076 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanianffe912c2009-12-11 22:40:48 +00001077 return TC_Success;
1078 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001079 }
1080 }
Fariborz Jahanianb0901b72010-05-12 18:16:59 +00001081 // Allow arbitray objective-c pointer conversion with static casts.
1082 if (SrcType->isObjCObjectPointerType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001083 DestType->isObjCObjectPointerType()) {
1084 Kind = CK_BitCast;
Fariborz Jahanianb0901b72010-05-12 18:16:59 +00001085 return TC_Success;
John McCall8cb679e2010-11-15 09:13:47 +00001086 }
Fariborz Jahanianc70a5432014-05-10 17:40:11 +00001087 // Allow ns-pointer to cf-pointer conversion in either direction
1088 // with static casts.
1089 if (!CStyle &&
1090 Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind))
1091 return TC_Success;
Fariborz Jahanianb0901b72010-05-12 18:16:59 +00001092
Sebastian Redl9f831db2009-07-25 15:41:38 +00001093 // We tried everything. Everything! Nothing works! :-(
1094 return TC_NotApplicable;
1095}
1096
1097/// Tests whether a conversion according to N2844 is valid.
1098TryCastResult
1099TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Douglas Gregorce950842011-01-26 21:04:06 +00001100 bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
1101 unsigned &msg) {
Douglas Gregor465184a2011-01-22 00:06:57 +00001102 // C++0x [expr.static.cast]p3:
1103 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
1104 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001105 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001106 if (!R)
1107 return TC_NotApplicable;
1108
Douglas Gregor465184a2011-01-22 00:06:57 +00001109 if (!SrcExpr->isGLValue())
Sebastian Redl9f831db2009-07-25 15:41:38 +00001110 return TC_NotApplicable;
1111
1112 // Because we try the reference downcast before this function, from now on
1113 // this is the only cast possibility, so we issue an error if we fail now.
1114 // FIXME: Should allow casting away constness if CStyle.
1115 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00001116 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00001117 bool ObjCLifetimeConversion;
Douglas Gregorce950842011-01-26 21:04:06 +00001118 QualType FromType = SrcExpr->getType();
1119 QualType ToType = R->getPointeeType();
1120 if (CStyle) {
1121 FromType = FromType.getUnqualifiedType();
1122 ToType = ToType.getUnqualifiedType();
1123 }
1124
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001125 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
Douglas Gregorce950842011-01-26 21:04:06 +00001126 ToType, FromType,
John McCall31168b02011-06-15 23:02:42 +00001127 DerivedToBase, ObjCConversion,
1128 ObjCLifetimeConversion)
1129 < Sema::Ref_Compatible_With_Added_Qualification) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001130 msg = diag::err_bad_lvalue_to_rvalue_cast;
1131 return TC_Failed;
1132 }
1133
Douglas Gregorba278e22011-01-25 16:13:26 +00001134 if (DerivedToBase) {
1135 Kind = CK_DerivedToBase;
1136 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1137 /*DetectVirtual=*/true);
1138 if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
1139 return TC_NotApplicable;
1140
1141 Self.BuildBasePathArray(Paths, BasePath);
1142 } else
1143 Kind = CK_NoOp;
1144
Sebastian Redl9f831db2009-07-25 15:41:38 +00001145 return TC_Success;
1146}
1147
1148/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1149TryCastResult
1150TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
1151 bool CStyle, const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +00001152 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001153 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001154 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1155 // cast to type "reference to cv2 D", where D is a class derived from B,
1156 // if a valid standard conversion from "pointer to D" to "pointer to B"
1157 // exists, cv2 >= cv1, and B is not a virtual base class of D.
1158 // In addition, DR54 clarifies that the base must be accessible in the
1159 // current context. Although the wording of DR54 only applies to the pointer
1160 // variant of this rule, the intent is clearly for it to apply to the this
1161 // conversion as well.
1162
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001163 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001164 if (!DestReference) {
1165 return TC_NotApplicable;
1166 }
1167 bool RValueRef = DestReference->isRValueReferenceType();
John McCall086a4642010-11-24 05:12:34 +00001168 if (!RValueRef && !SrcExpr->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001169 // We know the left side is an lvalue reference, so we can suggest a reason.
1170 msg = diag::err_bad_cxx_cast_rvalue;
1171 return TC_NotApplicable;
1172 }
1173
1174 QualType DestPointee = DestReference->getPointeeType();
1175
Richard Smith11330852014-07-08 17:25:14 +00001176 // FIXME: If the source is a prvalue, we should issue a warning (because the
1177 // cast always has undefined behavior), and for AST consistency, we should
1178 // materialize a temporary.
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001179 return TryStaticDowncast(Self,
1180 Self.Context.getCanonicalType(SrcExpr->getType()),
1181 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001182 OpRange, SrcExpr->getType(), DestType, msg, Kind,
1183 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001184}
1185
1186/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1187TryCastResult
1188TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +00001189 bool CStyle, const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +00001190 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001191 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001192 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1193 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1194 // is a class derived from B, if a valid standard conversion from "pointer
1195 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1196 // class of D.
1197 // In addition, DR54 clarifies that the base must be accessible in the
1198 // current context.
1199
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001200 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001201 if (!DestPointer) {
1202 return TC_NotApplicable;
1203 }
1204
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001205 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001206 if (!SrcPointer) {
1207 msg = diag::err_bad_static_cast_pointer_nonpointer;
1208 return TC_NotApplicable;
1209 }
1210
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001211 return TryStaticDowncast(Self,
1212 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1213 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001214 CStyle, OpRange, SrcType, DestType, msg, Kind,
1215 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001216}
1217
1218/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1219/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001220/// DestType is possible and allowed.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001221TryCastResult
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001222TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001223 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +00001224 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001225 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl802f14c2009-10-22 15:07:22 +00001226 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001227 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, 0) ||
1228 Self.RequireCompleteType(OpRange.getBegin(), DestType, 0))
Sebastian Redl802f14c2009-10-22 15:07:22 +00001229 return TC_NotApplicable;
1230
Sebastian Redl9f831db2009-07-25 15:41:38 +00001231 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001232 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001233 return TC_NotApplicable;
1234 }
1235
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001236 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001237 /*DetectVirtual=*/true);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001238 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
1239 return TC_NotApplicable;
1240 }
1241
1242 // Target type does derive from source type. Now we're serious. If an error
1243 // appears now, it's not ignored.
1244 // This may not be entirely in line with the standard. Take for example:
1245 // struct A {};
1246 // struct B : virtual A {
1247 // B(A&);
1248 // };
Mike Stump11289f42009-09-09 15:08:12 +00001249 //
Sebastian Redl9f831db2009-07-25 15:41:38 +00001250 // void f()
1251 // {
1252 // (void)static_cast<const B&>(*((A*)0));
1253 // }
1254 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1255 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1256 // However, both GCC and Comeau reject this example, and accepting it would
1257 // mean more complex code if we're to preserve the nice error message.
1258 // FIXME: Being 100% compliant here would be nice to have.
1259
1260 // Must preserve cv, as always, unless we're in C-style mode.
1261 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001262 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001263 return TC_Failed;
1264 }
1265
1266 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1267 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1268 // that it builds the paths in reverse order.
1269 // To sum up: record all paths to the base and build a nice string from
1270 // them. Use it to spice up the error message.
1271 if (!Paths.isRecordingPaths()) {
1272 Paths.clear();
1273 Paths.setRecordingPaths(true);
1274 Self.IsDerivedFrom(DestType, SrcType, Paths);
1275 }
1276 std::string PathDisplayStr;
1277 std::set<unsigned> DisplayedPaths;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001278 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001279 PI != PE; ++PI) {
1280 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
1281 // We haven't displayed a path to this particular base
1282 // class subobject yet.
1283 PathDisplayStr += "\n ";
Douglas Gregor36d1b142009-10-06 17:59:45 +00001284 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
1285 EE = PI->rend();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001286 EI != EE; ++EI)
1287 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001288 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001289 }
1290 }
1291
1292 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001293 << QualType(SrcType).getUnqualifiedType()
1294 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9f831db2009-07-25 15:41:38 +00001295 << PathDisplayStr << OpRange;
1296 msg = 0;
1297 return TC_Failed;
1298 }
1299
Craig Topperc3ec1492014-05-26 06:22:03 +00001300 if (Paths.getDetectedVirtual() != nullptr) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001301 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1302 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1303 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1304 msg = 0;
1305 return TC_Failed;
1306 }
1307
John McCallfe9cf0a2011-02-14 23:21:33 +00001308 if (!CStyle) {
1309 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1310 SrcType, DestType,
1311 Paths.front(),
John McCall1064d7e2010-03-16 05:22:47 +00001312 diag::err_downcast_from_inaccessible_base)) {
John McCallfe9cf0a2011-02-14 23:21:33 +00001313 case Sema::AR_accessible:
1314 case Sema::AR_delayed: // be optimistic
1315 case Sema::AR_dependent: // be optimistic
1316 break;
1317
1318 case Sema::AR_inaccessible:
1319 msg = 0;
1320 return TC_Failed;
1321 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001322 }
1323
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001324 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001325 Kind = CK_BaseToDerived;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001326 return TC_Success;
1327}
1328
1329/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1330/// C++ 5.2.9p9 is valid:
1331///
1332/// An rvalue of type "pointer to member of D of type cv1 T" can be
1333/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1334/// where B is a base class of D [...].
1335///
1336TryCastResult
John Wiegley01296292011-04-08 18:41:53 +00001337TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
Douglas Gregorc934bc82010-03-07 23:24:59 +00001338 QualType DestType, bool CStyle,
1339 const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +00001340 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001341 CXXCastPath &BasePath) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001342 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001343 if (!DestMemPtr)
1344 return TC_NotApplicable;
Douglas Gregorc934bc82010-03-07 23:24:59 +00001345
1346 bool WasOverloadedFunction = false;
John McCall16df1e52010-03-30 21:47:33 +00001347 DeclAccessPair FoundOverload;
John Wiegley01296292011-04-08 18:41:53 +00001348 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00001349 if (FunctionDecl *Fn
John Wiegley01296292011-04-08 18:41:53 +00001350 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
Douglas Gregor064fdb22010-04-14 23:11:21 +00001351 FoundOverload)) {
1352 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1353 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1354 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1355 WasOverloadedFunction = true;
1356 }
Douglas Gregorc934bc82010-03-07 23:24:59 +00001357 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00001358
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001359 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001360 if (!SrcMemPtr) {
1361 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1362 return TC_NotApplicable;
1363 }
1364
1365 // T == T, modulo cv
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001366 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1367 DestMemPtr->getPointeeType()))
Sebastian Redl9f831db2009-07-25 15:41:38 +00001368 return TC_NotApplicable;
1369
1370 // B base of D
1371 QualType SrcClass(SrcMemPtr->getClass(), 0);
1372 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssonb78feca2010-04-24 19:22:20 +00001373 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001374 /*DetectVirtual=*/true);
David Majnemerf5b93792014-01-16 12:02:55 +00001375 if (Self.RequireCompleteType(OpRange.getBegin(), SrcClass, 0) ||
1376 !Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001377 return TC_NotApplicable;
1378 }
1379
1380 // B is a base of D. But is it an allowed base? If not, it's a hard error.
Douglas Gregor27ac4292010-05-21 20:29:55 +00001381 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001382 Paths.clear();
1383 Paths.setRecordingPaths(true);
1384 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
1385 assert(StillOkay);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001386 (void)StillOkay;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001387 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1388 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1389 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1390 msg = 0;
1391 return TC_Failed;
1392 }
1393
1394 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1395 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1396 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1397 msg = 0;
1398 return TC_Failed;
1399 }
1400
John McCallfe9cf0a2011-02-14 23:21:33 +00001401 if (!CStyle) {
1402 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1403 DestClass, SrcClass,
1404 Paths.front(),
1405 diag::err_upcast_to_inaccessible_base)) {
1406 case Sema::AR_accessible:
1407 case Sema::AR_delayed:
1408 case Sema::AR_dependent:
1409 // Optimistically assume that the delayed and dependent cases
1410 // will work out.
1411 break;
1412
1413 case Sema::AR_inaccessible:
1414 msg = 0;
1415 return TC_Failed;
1416 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001417 }
1418
Douglas Gregorc934bc82010-03-07 23:24:59 +00001419 if (WasOverloadedFunction) {
1420 // Resolve the address of the overloaded function again, this time
1421 // allowing complaints if something goes wrong.
John Wiegley01296292011-04-08 18:41:53 +00001422 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
Douglas Gregorc934bc82010-03-07 23:24:59 +00001423 DestType,
John McCall16df1e52010-03-30 21:47:33 +00001424 true,
1425 FoundOverload);
Douglas Gregorc934bc82010-03-07 23:24:59 +00001426 if (!Fn) {
1427 msg = 0;
1428 return TC_Failed;
1429 }
1430
John McCall16df1e52010-03-30 21:47:33 +00001431 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
John Wiegley01296292011-04-08 18:41:53 +00001432 if (!SrcExpr.isUsable()) {
Douglas Gregorc934bc82010-03-07 23:24:59 +00001433 msg = 0;
1434 return TC_Failed;
1435 }
1436 }
1437
Anders Carlssonb78feca2010-04-24 19:22:20 +00001438 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001439 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001440 return TC_Success;
1441}
1442
1443/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1444/// is valid:
1445///
1446/// An expression e can be explicitly converted to a type T using a
1447/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1448TryCastResult
John Wiegley01296292011-04-08 18:41:53 +00001449TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCall31168b02011-06-15 23:02:42 +00001450 Sema::CheckedConversionKind CCK,
1451 const SourceRange &OpRange, unsigned &msg,
Sebastian Redld74dd492012-02-12 18:41:05 +00001452 CastKind &Kind, bool ListInitialization) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +00001453 if (DestType->isRecordType()) {
1454 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
Aaron Ballmanea032142012-05-07 00:02:00 +00001455 diag::err_bad_dynamic_cast_incomplete) ||
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001456 Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
Aaron Ballmanea032142012-05-07 00:02:00 +00001457 diag::err_allocation_of_abstract_type)) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +00001458 msg = 0;
1459 return TC_Failed;
1460 }
David Majnemer763584d2014-02-06 10:59:19 +00001461 } else if (DestType->isMemberPointerType()) {
1462 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1463 Self.RequireCompleteType(OpRange.getBegin(), DestType, 0);
1464 }
Anders Carlsson85ec4ff2009-09-07 18:25:47 +00001465 }
Sebastian Redl0501c632012-02-12 16:37:36 +00001466
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001467 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1468 InitializationKind InitKind
John McCall31168b02011-06-15 23:02:42 +00001469 = (CCK == Sema::CCK_CStyleCast)
Sebastian Redl0501c632012-02-12 16:37:36 +00001470 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +00001471 ListInitialization)
John McCall31168b02011-06-15 23:02:42 +00001472 : (CCK == Sema::CCK_FunctionalCast)
Sebastian Redld74dd492012-02-12 18:41:05 +00001473 ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
Richard Smith507840d2011-11-29 22:48:16 +00001474 : InitializationKind::CreateCast(OpRange);
John Wiegley01296292011-04-08 18:41:53 +00001475 Expr *SrcExprRaw = SrcExpr.get();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001476 InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001477
1478 // At this point of CheckStaticCast, if the destination is a reference,
1479 // or the expression is an overload expression this has to work.
1480 // There is no other way that works.
1481 // On the other hand, if we're checking a C-style cast, we've still got
1482 // the reinterpret_cast way.
John McCall31168b02011-06-15 23:02:42 +00001483 bool CStyle
1484 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00001485 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001486 return TC_NotApplicable;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001487
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001488 ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001489 if (Result.isInvalid()) {
1490 msg = 0;
1491 return TC_Failed;
1492 }
1493
Douglas Gregorb33eed02010-04-16 22:09:46 +00001494 if (InitSeq.isConstructorInitialization())
John McCalle3027922010-08-25 11:45:40 +00001495 Kind = CK_ConstructorConversion;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001496 else
John McCalle3027922010-08-25 11:45:40 +00001497 Kind = CK_NoOp;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001498
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001499 SrcExpr = Result;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001500 return TC_Success;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001501}
1502
1503/// TryConstCast - See if a const_cast from source to destination is allowed,
1504/// and perform it if it is.
Richard Smith82c9b512013-06-14 22:27:52 +00001505static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
1506 QualType DestType, bool CStyle,
1507 unsigned &msg) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001508 DestType = Self.Context.getCanonicalType(DestType);
Richard Smith82c9b512013-06-14 22:27:52 +00001509 QualType SrcType = SrcExpr.get()->getType();
1510 bool NeedToMaterializeTemporary = false;
1511
Douglas Gregorc1ed20c2011-01-22 00:19:52 +00001512 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
Richard Smith82c9b512013-06-14 22:27:52 +00001513 // C++11 5.2.11p4:
1514 // if a pointer to T1 can be explicitly converted to the type "pointer to
1515 // T2" using a const_cast, then the following conversions can also be
1516 // made:
1517 // -- an lvalue of type T1 can be explicitly converted to an lvalue of
1518 // type T2 using the cast const_cast<T2&>;
1519 // -- a glvalue of type T1 can be explicitly converted to an xvalue of
1520 // type T2 using the cast const_cast<T2&&>; and
1521 // -- if T1 is a class type, a prvalue of type T1 can be explicitly
1522 // converted to an xvalue of type T2 using the cast const_cast<T2&&>.
1523
1524 if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001525 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1526 // is C-style, static_cast might find a way, so we simply suggest a
1527 // message and tell the parent to keep searching.
1528 msg = diag::err_bad_cxx_cast_rvalue;
1529 return TC_NotApplicable;
1530 }
1531
Richard Smith82c9b512013-06-14 22:27:52 +00001532 if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) {
1533 if (!SrcType->isRecordType()) {
1534 // Cannot const_cast non-class prvalue to rvalue reference type. But if
1535 // this is C-style, static_cast can do this.
1536 msg = diag::err_bad_cxx_cast_rvalue;
1537 return TC_NotApplicable;
1538 }
1539
1540 // Materialize the class prvalue so that the const_cast can bind a
1541 // reference to it.
1542 NeedToMaterializeTemporary = true;
1543 }
1544
John McCalld25db7e2013-05-06 21:39:12 +00001545 // It's not completely clear under the standard whether we can
1546 // const_cast bit-field gl-values. Doing so would not be
1547 // intrinsically complicated, but for now, we say no for
1548 // consistency with other compilers and await the word of the
1549 // committee.
Richard Smith82c9b512013-06-14 22:27:52 +00001550 if (SrcExpr.get()->refersToBitField()) {
John McCalld25db7e2013-05-06 21:39:12 +00001551 msg = diag::err_bad_cxx_cast_bitfield;
1552 return TC_NotApplicable;
1553 }
1554
Sebastian Redl9f831db2009-07-25 15:41:38 +00001555 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1556 SrcType = Self.Context.getPointerType(SrcType);
1557 }
1558
1559 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1560 // the rules for const_cast are the same as those used for pointers.
1561
John McCall0e704f72010-05-18 09:35:29 +00001562 if (!DestType->isPointerType() &&
1563 !DestType->isMemberPointerType() &&
1564 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001565 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1566 // was a reference type, we converted it to a pointer above.
1567 // The status of rvalue references isn't entirely clear, but it looks like
1568 // conversion to them is simply invalid.
1569 // C++ 5.2.11p3: For two pointer types [...]
1570 if (!CStyle)
1571 msg = diag::err_bad_const_cast_dest;
1572 return TC_NotApplicable;
1573 }
1574 if (DestType->isFunctionPointerType() ||
1575 DestType->isMemberFunctionPointerType()) {
1576 // Cannot cast direct function pointers.
1577 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1578 // T is the ultimate pointee of source and target type.
1579 if (!CStyle)
1580 msg = diag::err_bad_const_cast_dest;
1581 return TC_NotApplicable;
1582 }
1583 SrcType = Self.Context.getCanonicalType(SrcType);
1584
1585 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1586 // completely equal.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001587 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1588 // in multi-level pointers may change, but the level count must be the same,
1589 // as must be the final pointee type.
1590 while (SrcType != DestType &&
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001591 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001592 Qualifiers SrcQuals, DestQuals;
1593 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
1594 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
1595
1596 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
1597 // the other qualifiers (e.g., address spaces) are identical.
1598 SrcQuals.removeCVRQualifiers();
1599 DestQuals.removeCVRQualifiers();
1600 if (SrcQuals != DestQuals)
1601 return TC_NotApplicable;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001602 }
1603
1604 // Since we're dealing in canonical types, the remainder must be the same.
1605 if (SrcType != DestType)
1606 return TC_NotApplicable;
1607
Richard Smith82c9b512013-06-14 22:27:52 +00001608 if (NeedToMaterializeTemporary)
1609 // This is a const_cast from a class prvalue to an rvalue reference type.
1610 // Materialize a temporary to store the result of the conversion.
1611 SrcExpr = new (Self.Context) MaterializeTemporaryExpr(
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001612 SrcType, SrcExpr.get(), /*IsLValueReference*/ false);
Richard Smith82c9b512013-06-14 22:27:52 +00001613
Sebastian Redl9f831db2009-07-25 15:41:38 +00001614 return TC_Success;
1615}
1616
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001617// Checks for undefined behavior in reinterpret_cast.
1618// The cases that is checked for is:
1619// *reinterpret_cast<T*>(&a)
1620// reinterpret_cast<T&>(a)
1621// where accessing 'a' as type 'T' will result in undefined behavior.
1622void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1623 bool IsDereference,
1624 SourceRange Range) {
1625 unsigned DiagID = IsDereference ?
1626 diag::warn_pointer_indirection_from_incompatible_type :
1627 diag::warn_undefined_reinterpret_cast;
1628
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001629 if (Diags.isIgnored(DiagID, Range.getBegin()))
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001630 return;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001631
1632 QualType SrcTy, DestTy;
1633 if (IsDereference) {
1634 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1635 return;
1636 }
1637 SrcTy = SrcType->getPointeeType();
1638 DestTy = DestType->getPointeeType();
1639 } else {
1640 if (!DestType->getAs<ReferenceType>()) {
1641 return;
1642 }
1643 SrcTy = SrcType;
1644 DestTy = DestType->getPointeeType();
1645 }
1646
1647 // Cast is compatible if the types are the same.
1648 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1649 return;
1650 }
1651 // or one of the types is a char or void type
1652 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1653 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1654 return;
1655 }
1656 // or one of the types is a tag type.
Chandler Carruth0dc3f8d2011-05-24 07:43:19 +00001657 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001658 return;
1659 }
1660
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001661 // FIXME: Scoped enums?
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001662 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1663 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1664 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1665 return;
1666 }
1667 }
1668
1669 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1670}
Douglas Gregor1beec452011-03-12 01:48:56 +00001671
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00001672static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
1673 QualType DestType) {
1674 QualType SrcType = SrcExpr.get()->getType();
Fariborz Jahanianb4873882012-12-13 00:42:06 +00001675 if (Self.Context.hasSameType(SrcType, DestType))
1676 return;
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00001677 if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
1678 if (SrcPtrTy->isObjCSelType()) {
1679 QualType DT = DestType;
1680 if (isa<PointerType>(DestType))
1681 DT = DestType->getPointeeType();
1682 if (!DT.getUnqualifiedType()->isVoidType())
1683 Self.Diag(SrcExpr.get()->getExprLoc(),
1684 diag::warn_cast_pointer_from_sel)
1685 << SrcType << DestType << SrcExpr.get()->getSourceRange();
1686 }
1687}
1688
David Blaikie282ad872012-10-16 18:53:14 +00001689static void checkIntToPointerCast(bool CStyle, SourceLocation Loc,
1690 const Expr *SrcExpr, QualType DestType,
1691 Sema &Self) {
1692 QualType SrcType = SrcExpr->getType();
1693
1694 // Not warning on reinterpret_cast, boolean, constant expressions, etc
1695 // are not explicit design choices, but consistent with GCC's behavior.
1696 // Feel free to modify them if you've reason/evidence for an alternative.
1697 if (CStyle && SrcType->isIntegralType(Self.Context)
1698 && !SrcType->isBooleanType()
1699 && !SrcType->isEnumeralType()
1700 && !SrcExpr->isIntegerConstantExpr(Self.Context)
Ted Kremeneke3dc7f72013-05-29 21:50:46 +00001701 && Self.Context.getTypeSize(DestType) >
1702 Self.Context.getTypeSize(SrcType)) {
1703 // Separate between casts to void* and non-void* pointers.
1704 // Some APIs use (abuse) void* for something like a user context,
1705 // and often that value is an integer even if it isn't a pointer itself.
1706 // Having a separate warning flag allows users to control the warning
1707 // for their workflow.
1708 unsigned Diag = DestType->isVoidPointerType() ?
1709 diag::warn_int_to_void_pointer_cast
1710 : diag::warn_int_to_pointer_cast;
1711 Self.Diag(Loc, Diag) << SrcType << DestType;
1712 }
David Blaikie282ad872012-10-16 18:53:14 +00001713}
1714
John Wiegley01296292011-04-08 18:41:53 +00001715static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001716 QualType DestType, bool CStyle,
1717 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001718 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001719 CastKind &Kind) {
Douglas Gregor51954272010-07-13 23:17:26 +00001720 bool IsLValueCast = false;
1721
Sebastian Redl9f831db2009-07-25 15:41:38 +00001722 DestType = Self.Context.getCanonicalType(DestType);
John Wiegley01296292011-04-08 18:41:53 +00001723 QualType SrcType = SrcExpr.get()->getType();
Douglas Gregore81f58e2010-11-08 03:40:48 +00001724
1725 // Is the source an overloaded name? (i.e. &foo)
Douglas Gregorb491ed32011-02-19 21:32:49 +00001726 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ...
1727 if (SrcType == Self.Context.OverloadTy) {
John McCall50a2c2c2011-10-11 23:14:30 +00001728 // ... unless foo<int> resolves to an lvalue unambiguously.
1729 // TODO: what if this fails because of DiagnoseUseOfDecl or something
1730 // like it?
1731 ExprResult SingleFunctionExpr = SrcExpr;
1732 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1733 SingleFunctionExpr,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001734 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
John McCall50a2c2c2011-10-11 23:14:30 +00001735 ) && SingleFunctionExpr.isUsable()) {
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001736 SrcExpr = SingleFunctionExpr;
John Wiegley01296292011-04-08 18:41:53 +00001737 SrcType = SrcExpr.get()->getType();
John McCall50a2c2c2011-10-11 23:14:30 +00001738 } else {
Douglas Gregorb491ed32011-02-19 21:32:49 +00001739 return TC_NotApplicable;
John McCall50a2c2c2011-10-11 23:14:30 +00001740 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00001741 }
Douglas Gregore81f58e2010-11-08 03:40:48 +00001742
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001743 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Richard Smithdb05f1f2012-04-29 08:24:44 +00001744 if (!SrcExpr.get()->isGLValue()) {
1745 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
1746 // similar comment in const_cast.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001747 msg = diag::err_bad_cxx_cast_rvalue;
1748 return TC_NotApplicable;
1749 }
1750
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001751 if (!CStyle) {
1752 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
1753 /*isDereference=*/false, OpRange);
1754 }
1755
Sebastian Redl9f831db2009-07-25 15:41:38 +00001756 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1757 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1758 // built-in & and * operators.
Argyrios Kyrtzidis47a12852011-04-22 22:31:13 +00001759
Craig Topperc3ec1492014-05-26 06:22:03 +00001760 const char *inappropriate = nullptr;
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00001761 switch (SrcExpr.get()->getObjectKind()) {
Argyrios Kyrtzidis3d2185b2011-04-23 01:10:24 +00001762 case OK_Ordinary:
1763 break;
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00001764 case OK_BitField: inappropriate = "bit-field"; break;
1765 case OK_VectorComponent: inappropriate = "vector element"; break;
1766 case OK_ObjCProperty: inappropriate = "property expression"; break;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001767 case OK_ObjCSubscript: inappropriate = "container subscripting expression";
1768 break;
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00001769 }
1770 if (inappropriate) {
1771 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
1772 << inappropriate << DestType
1773 << OpRange << SrcExpr.get()->getSourceRange();
1774 msg = 0; SrcExpr = ExprError();
Argyrios Kyrtzidis47a12852011-04-22 22:31:13 +00001775 return TC_NotApplicable;
1776 }
1777
Sebastian Redl9f831db2009-07-25 15:41:38 +00001778 // This code does this transformation for the checked types.
1779 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1780 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001781
Douglas Gregor51954272010-07-13 23:17:26 +00001782 IsLValueCast = true;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001783 }
1784
1785 // Canonicalize source for comparison.
1786 SrcType = Self.Context.getCanonicalType(SrcType);
1787
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001788 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1789 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001790 if (DestMemPtr && SrcMemPtr) {
1791 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1792 // can be explicitly converted to an rvalue of type "pointer to member
1793 // of Y of type T2" if T1 and T2 are both function types or both object
1794 // types.
1795 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1796 SrcMemPtr->getPointeeType()->isFunctionType())
1797 return TC_NotApplicable;
1798
1799 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1800 // constness.
1801 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1802 // we accept it.
John McCall31168b02011-06-15 23:02:42 +00001803 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1804 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001805 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001806 return TC_Failed;
1807 }
1808
David Majnemer1cdd96d2014-01-17 09:01:00 +00001809 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1810 // We need to determine the inheritance model that the class will use if
1811 // haven't yet.
1812 Self.RequireCompleteType(OpRange.getBegin(), SrcType, 0);
1813 Self.RequireCompleteType(OpRange.getBegin(), DestType, 0);
1814 }
1815
Charles Davisebab1ed2010-08-16 05:30:44 +00001816 // Don't allow casting between member pointers of different sizes.
1817 if (Self.Context.getTypeSize(DestMemPtr) !=
1818 Self.Context.getTypeSize(SrcMemPtr)) {
1819 msg = diag::err_bad_cxx_cast_member_pointer_size;
1820 return TC_Failed;
1821 }
1822
Sebastian Redl9f831db2009-07-25 15:41:38 +00001823 // A valid member pointer cast.
John McCallc62bb392012-02-15 01:22:51 +00001824 assert(!IsLValueCast);
1825 Kind = CK_ReinterpretMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001826 return TC_Success;
1827 }
1828
1829 // See below for the enumeral issue.
Douglas Gregor6972a622010-06-16 00:35:25 +00001830 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001831 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1832 // type large enough to hold it. A value of std::nullptr_t can be
1833 // converted to an integral type; the conversion has the same meaning
1834 // and validity as a conversion of (void*)0 to the integral type.
1835 if (Self.Context.getTypeSize(SrcType) >
1836 Self.Context.getTypeSize(DestType)) {
1837 msg = diag::err_bad_reinterpret_cast_small_int;
1838 return TC_Failed;
1839 }
John McCalle3027922010-08-25 11:45:40 +00001840 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001841 return TC_Success;
1842 }
1843
Anders Carlsson570af5d2009-09-16 19:19:43 +00001844 bool destIsVector = DestType->isVectorType();
1845 bool srcIsVector = SrcType->isVectorType();
1846 if (srcIsVector || destIsVector) {
Douglas Gregor6972a622010-06-16 00:35:25 +00001847 // FIXME: Should this also apply to floating point types?
1848 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1849 bool destIsScalar = DestType->isIntegralType(Self.Context);
Anders Carlsson570af5d2009-09-16 19:19:43 +00001850
1851 // Check if this is a cast between a vector and something else.
1852 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1853 !(srcIsVector && destIsVector))
1854 return TC_NotApplicable;
1855
1856 // If both types have the same size, we can successfully cast.
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001857 if (Self.Context.getTypeSize(SrcType)
1858 == Self.Context.getTypeSize(DestType)) {
John McCalle3027922010-08-25 11:45:40 +00001859 Kind = CK_BitCast;
Anders Carlsson570af5d2009-09-16 19:19:43 +00001860 return TC_Success;
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001861 }
Anders Carlsson570af5d2009-09-16 19:19:43 +00001862
1863 if (destIsScalar)
1864 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1865 else if (srcIsScalar)
1866 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1867 else
1868 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1869
1870 return TC_Failed;
1871 }
Chad Rosier96c755d12012-02-03 02:54:37 +00001872
1873 if (SrcType == DestType) {
1874 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1875 // restrictions, a cast to the same type is allowed so long as it does not
1876 // cast away constness. In C++98, the intent was not entirely clear here,
1877 // since all other paragraphs explicitly forbid casts to the same type.
1878 // C++11 clarifies this case with p2.
1879 //
1880 // The only allowed types are: integral, enumeration, pointer, or
1881 // pointer-to-member types. We also won't restrict Obj-C pointers either.
1882 Kind = CK_NoOp;
1883 TryCastResult Result = TC_NotApplicable;
1884 if (SrcType->isIntegralOrEnumerationType() ||
1885 SrcType->isAnyPointerType() ||
1886 SrcType->isMemberPointerType() ||
1887 SrcType->isBlockPointerType()) {
1888 Result = TC_Success;
1889 }
1890 return Result;
1891 }
1892
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001893 bool destIsPtr = DestType->isAnyPointerType() ||
1894 DestType->isBlockPointerType();
1895 bool srcIsPtr = SrcType->isAnyPointerType() ||
1896 SrcType->isBlockPointerType();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001897 if (!destIsPtr && !srcIsPtr) {
1898 // Except for std::nullptr_t->integer and lvalue->reference, which are
1899 // handled above, at least one of the two arguments must be a pointer.
1900 return TC_NotApplicable;
1901 }
1902
Douglas Gregor6972a622010-06-16 00:35:25 +00001903 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001904 assert(srcIsPtr && "One type must be a pointer");
1905 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
Francois Pichetb796b632011-05-11 22:13:54 +00001906 // type large enough to hold it; except in Microsoft mode, where the
Hans Wennborg15439bc2013-06-06 09:16:36 +00001907 // integral type size doesn't matter (except we don't allow bool).
1908 bool MicrosoftException = Self.getLangOpts().MicrosoftExt &&
1909 !DestType->isBooleanType();
Francois Pichetb796b632011-05-11 22:13:54 +00001910 if ((Self.Context.getTypeSize(SrcType) >
1911 Self.Context.getTypeSize(DestType)) &&
Hans Wennborg15439bc2013-06-06 09:16:36 +00001912 !MicrosoftException) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001913 msg = diag::err_bad_reinterpret_cast_small_int;
1914 return TC_Failed;
1915 }
John McCalle3027922010-08-25 11:45:40 +00001916 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001917 return TC_Success;
1918 }
1919
Douglas Gregorb90df602010-06-16 00:17:44 +00001920 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001921 assert(destIsPtr && "One type must be a pointer");
David Blaikie282ad872012-10-16 18:53:14 +00001922 checkIntToPointerCast(CStyle, OpRange.getBegin(), SrcExpr.get(), DestType,
1923 Self);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001924 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1925 // converted to a pointer.
John McCalle84af4e2010-11-13 01:35:44 +00001926 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1927 // necessarily converted to a null pointer value.]
John McCalle3027922010-08-25 11:45:40 +00001928 Kind = CK_IntegralToPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001929 return TC_Success;
1930 }
1931
1932 if (!destIsPtr || !srcIsPtr) {
1933 // With the valid non-pointer conversions out of the way, we can be even
1934 // more stringent.
1935 return TC_NotApplicable;
1936 }
1937
1938 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1939 // The C-style cast operator can.
John McCall31168b02011-06-15 23:02:42 +00001940 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1941 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001942 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001943 return TC_Failed;
1944 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001945
1946 // Cannot convert between block pointers and Objective-C object pointers.
1947 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1948 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1949 return TC_NotApplicable;
1950
John McCall9320b872011-09-09 05:25:32 +00001951 if (IsLValueCast) {
1952 Kind = CK_LValueBitCast;
1953 } else if (DestType->isObjCObjectPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00001954 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
John McCall9320b872011-09-09 05:25:32 +00001955 } else if (DestType->isBlockPointerType()) {
1956 if (!SrcType->isBlockPointerType()) {
1957 Kind = CK_AnyPointerToBlockPointerCast;
1958 } else {
1959 Kind = CK_BitCast;
1960 }
1961 } else {
1962 Kind = CK_BitCast;
1963 }
1964
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001965 // Any pointer can be cast to an Objective-C pointer type with a C-style
1966 // cast.
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001967 if (CStyle && DestType->isObjCObjectPointerType()) {
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001968 return TC_Success;
1969 }
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00001970 if (CStyle)
1971 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
1972
Sebastian Redl9f831db2009-07-25 15:41:38 +00001973 // Not casting away constness, so the only remaining check is for compatible
1974 // pointer categories.
1975
1976 if (SrcType->isFunctionPointerType()) {
1977 if (DestType->isFunctionPointerType()) {
1978 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1979 // a pointer to a function of a different type.
1980 return TC_Success;
1981 }
1982
1983 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1984 // an object type or vice versa is conditionally-supported.
1985 // Compilers support it in C++03 too, though, because it's necessary for
1986 // casting the return value of dlsym() and GetProcAddress().
1987 // FIXME: Conditionally-supported behavior should be configurable in the
1988 // TargetInfo or similar.
Richard Smith0bf8a4922011-10-18 20:49:44 +00001989 Self.Diag(OpRange.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001990 Self.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001991 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
1992 << OpRange;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001993 return TC_Success;
1994 }
1995
1996 if (DestType->isFunctionPointerType()) {
1997 // See above.
Richard Smith0bf8a4922011-10-18 20:49:44 +00001998 Self.Diag(OpRange.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001999 Self.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002000 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2001 << OpRange;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002002 return TC_Success;
2003 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00002004
Sebastian Redl9f831db2009-07-25 15:41:38 +00002005 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
2006 // a pointer to an object of different type.
2007 // Void pointers are not specified, but supported by every compiler out there.
2008 // So we finish by allowing everything that remains - it's got to be two
2009 // object pointers.
2010 return TC_Success;
John McCall909acf82011-02-14 18:34:10 +00002011}
Sebastian Redl9f831db2009-07-25 15:41:38 +00002012
Sebastian Redld74dd492012-02-12 18:41:05 +00002013void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
2014 bool ListInitialization) {
John McCall9776e432011-10-06 23:25:11 +00002015 // Handle placeholders.
2016 if (isPlaceholder()) {
2017 // C-style casts can resolve __unknown_any types.
2018 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2019 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2020 SrcExpr.get(), Kind,
2021 ValueKind, BasePath);
2022 return;
2023 }
John McCallb50451a2011-10-05 07:41:44 +00002024
John McCall9776e432011-10-06 23:25:11 +00002025 checkNonOverloadPlaceholders();
2026 if (SrcExpr.isInvalid())
2027 return;
John McCalla072f5d2011-10-17 17:42:19 +00002028 }
John McCall9776e432011-10-06 23:25:11 +00002029
2030 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Sebastian Redl9f831db2009-07-25 15:41:38 +00002031 // This test is outside everything else because it's the only case where
2032 // a non-lvalue-reference target type does not lead to decay.
John McCallb50451a2011-10-05 07:41:44 +00002033 if (DestType->isVoidType()) {
John McCall3aef3d82011-04-10 19:13:55 +00002034 Kind = CK_ToVoid;
2035
John McCall9776e432011-10-06 23:25:11 +00002036 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall50a2c2c2011-10-11 23:14:30 +00002037 Self.ResolveAndFixSingleFunctionTemplateSpecialization(
2038 SrcExpr, /* Decay Function to ptr */ false,
John McCallb50451a2011-10-05 07:41:44 +00002039 /* Complain */ true, DestRange, DestType,
Douglas Gregor1beec452011-03-12 01:48:56 +00002040 diag::err_bad_cstyle_cast_overload);
John McCallb50451a2011-10-05 07:41:44 +00002041 if (SrcExpr.isInvalid())
2042 return;
Douglas Gregorb491ed32011-02-19 21:32:49 +00002043 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002044
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002045 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
John McCallb50451a2011-10-05 07:41:44 +00002046 return;
Anton Yartsev28ccef72011-03-27 09:32:40 +00002047 }
2048
Sebastian Redl9f831db2009-07-25 15:41:38 +00002049 // If the type is dependent, we won't do any other semantic analysis now.
Eli Friedman71271082013-09-19 01:12:33 +00002050 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
2051 SrcExpr.get()->isValueDependent()) {
John McCallb50451a2011-10-05 07:41:44 +00002052 assert(Kind == CK_Dependent);
2053 return;
John McCall8cb679e2010-11-15 09:13:47 +00002054 }
Benjamin Kramer65cc1072011-07-08 20:20:17 +00002055
John McCall50a2c2c2011-10-11 23:14:30 +00002056 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
2057 !isPlaceholder(BuiltinType::Overload)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002058 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
John McCallb50451a2011-10-05 07:41:44 +00002059 if (SrcExpr.isInvalid())
2060 return;
John Wiegley01296292011-04-08 18:41:53 +00002061 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002062
John McCall3aef3d82011-04-10 19:13:55 +00002063 // AltiVec vector initialization with a single literal.
John McCallb50451a2011-10-05 07:41:44 +00002064 if (const VectorType *vecTy = DestType->getAs<VectorType>())
John McCall3aef3d82011-04-10 19:13:55 +00002065 if (vecTy->getVectorKind() == VectorType::AltiVecVector
John McCallb50451a2011-10-05 07:41:44 +00002066 && (SrcExpr.get()->getType()->isIntegerType()
2067 || SrcExpr.get()->getType()->isFloatingType())) {
John McCall3aef3d82011-04-10 19:13:55 +00002068 Kind = CK_VectorSplat;
John McCallb50451a2011-10-05 07:41:44 +00002069 return;
John McCall3aef3d82011-04-10 19:13:55 +00002070 }
2071
Sebastian Redl9f831db2009-07-25 15:41:38 +00002072 // C++ [expr.cast]p5: The conversions performed by
2073 // - a const_cast,
2074 // - a static_cast,
2075 // - a static_cast followed by a const_cast,
2076 // - a reinterpret_cast, or
2077 // - a reinterpret_cast followed by a const_cast,
2078 // can be performed using the cast notation of explicit type conversion.
2079 // [...] If a conversion can be interpreted in more than one of the ways
2080 // listed above, the interpretation that appears first in the list is used,
2081 // even if a cast resulting from that interpretation is ill-formed.
2082 // In plain language, this means trying a const_cast ...
2083 unsigned msg = diag::err_bad_cxx_cast_generic;
Richard Smith82c9b512013-06-14 22:27:52 +00002084 TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
John McCallb50451a2011-10-05 07:41:44 +00002085 /*CStyle*/true, msg);
Richard Smith82c9b512013-06-14 22:27:52 +00002086 if (SrcExpr.isInvalid())
2087 return;
Anders Carlsson027732b2009-10-19 18:14:28 +00002088 if (tcr == TC_Success)
John McCalle3027922010-08-25 11:45:40 +00002089 Kind = CK_NoOp;
Anders Carlsson027732b2009-10-19 18:14:28 +00002090
John McCall31168b02011-06-15 23:02:42 +00002091 Sema::CheckedConversionKind CCK
2092 = FunctionalStyle? Sema::CCK_FunctionalCast
2093 : Sema::CCK_CStyleCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002094 if (tcr == TC_NotApplicable) {
2095 // ... or if that is not possible, a static_cast, ignoring const, ...
John McCallb50451a2011-10-05 07:41:44 +00002096 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +00002097 msg, Kind, BasePath, ListInitialization);
John McCallb50451a2011-10-05 07:41:44 +00002098 if (SrcExpr.isInvalid())
2099 return;
2100
Sebastian Redl9f831db2009-07-25 15:41:38 +00002101 if (tcr == TC_NotApplicable) {
2102 // ... and finally a reinterpret_cast, ignoring const.
John McCallb50451a2011-10-05 07:41:44 +00002103 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
2104 OpRange, msg, Kind);
2105 if (SrcExpr.isInvalid())
2106 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002107 }
2108 }
2109
David Blaikiebbafb8a2012-03-11 07:00:24 +00002110 if (Self.getLangOpts().ObjCAutoRefCount && tcr == TC_Success)
John McCallb50451a2011-10-05 07:41:44 +00002111 checkObjCARCConversion(CCK);
John McCall31168b02011-06-15 23:02:42 +00002112
Nick Lewycky14d88eb2010-11-09 00:19:31 +00002113 if (tcr != TC_Success && msg != 0) {
John McCallb50451a2011-10-05 07:41:44 +00002114 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +00002115 DeclAccessPair Found;
John McCallb50451a2011-10-05 07:41:44 +00002116 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
2117 DestType,
2118 /*Complain*/ true,
Douglas Gregore81f58e2010-11-08 03:40:48 +00002119 Found);
Logan Chienaf24ad92014-04-13 16:08:24 +00002120 if (Fn) {
2121 // If DestType is a function type (not to be confused with the function
2122 // pointer type), it will be possible to resolve the function address,
2123 // but the type cast should be considered as failure.
2124 OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression;
2125 Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload)
2126 << OE->getName() << DestType << OpRange
2127 << OE->getQualifierLoc().getSourceRange();
2128 Self.NoteAllOverloadCandidates(SrcExpr.get());
2129 }
Nick Lewycky14d88eb2010-11-09 00:19:31 +00002130 } else {
John McCallb50451a2011-10-05 07:41:44 +00002131 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
Sebastian Redl2b80af42012-02-13 19:55:43 +00002132 OpRange, SrcExpr.get(), DestType, ListInitialization);
Douglas Gregore81f58e2010-11-08 03:40:48 +00002133 }
John McCallb50451a2011-10-05 07:41:44 +00002134 } else if (Kind == CK_BitCast) {
2135 checkCastAlign();
Douglas Gregore81f58e2010-11-08 03:40:48 +00002136 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002137
John McCallb50451a2011-10-05 07:41:44 +00002138 // Clear out SrcExpr if there was a fatal error.
John Wiegley01296292011-04-08 18:41:53 +00002139 if (tcr != TC_Success)
John McCallb50451a2011-10-05 07:41:44 +00002140 SrcExpr = ExprError();
2141}
2142
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002143/// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
2144/// non-matching type. Such as enum function call to int, int call to
2145/// pointer; etc. Cast to 'void' is an exception.
2146static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
2147 QualType DestType) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002148 if (Self.Diags.isIgnored(diag::warn_bad_function_cast,
2149 SrcExpr.get()->getExprLoc()))
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002150 return;
2151
2152 if (!isa<CallExpr>(SrcExpr.get()))
2153 return;
2154
2155 QualType SrcType = SrcExpr.get()->getType();
2156 if (DestType.getUnqualifiedType()->isVoidType())
2157 return;
2158 if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
2159 && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
2160 return;
2161 if (SrcType->isIntegerType() && DestType->isIntegerType() &&
2162 (SrcType->isBooleanType() == DestType->isBooleanType()) &&
2163 (SrcType->isEnumeralType() == DestType->isEnumeralType()))
2164 return;
2165 if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
2166 return;
2167 if (SrcType->isEnumeralType() && DestType->isEnumeralType())
2168 return;
2169 if (SrcType->isComplexType() && DestType->isComplexType())
2170 return;
2171 if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
2172 return;
2173
2174 Self.Diag(SrcExpr.get()->getExprLoc(),
2175 diag::warn_bad_function_cast)
2176 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2177}
2178
John McCall9776e432011-10-06 23:25:11 +00002179/// Check the semantics of a C-style cast operation, in C.
2180void CastOperation::CheckCStyleCast() {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002181 assert(!Self.getLangOpts().CPlusPlus);
John McCall9776e432011-10-06 23:25:11 +00002182
John McCall4124c492011-10-17 18:40:02 +00002183 // C-style casts can resolve __unknown_any types.
2184 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2185 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2186 SrcExpr.get(), Kind,
2187 ValueKind, BasePath);
2188 return;
2189 }
John McCall9776e432011-10-06 23:25:11 +00002190
2191 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2192 // type needs to be scalar.
2193 if (DestType->isVoidType()) {
2194 // We don't necessarily do lvalue-to-rvalue conversions on this.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002195 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +00002196 if (SrcExpr.isInvalid())
2197 return;
2198
2199 // Cast to void allows any expr type.
2200 Kind = CK_ToVoid;
2201 return;
2202 }
2203
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002204 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +00002205 if (SrcExpr.isInvalid())
2206 return;
2207 QualType SrcType = SrcExpr.get()->getType();
David Chisnallfa35df62012-01-16 17:27:18 +00002208
John McCall4124c492011-10-17 18:40:02 +00002209 assert(!SrcType->isPlaceholderType());
John McCall9776e432011-10-06 23:25:11 +00002210
Joey Gouly8fc32f02014-01-14 12:47:29 +00002211 // OpenCL v1 s6.5: Casting a pointer to address space A to a pointer to
2212 // address space B is illegal.
2213 if (Self.getLangOpts().OpenCL && DestType->isPointerType() &&
2214 SrcType->isPointerType()) {
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00002215 const PointerType *DestPtr = DestType->getAs<PointerType>();
2216 if (!DestPtr->isAddressSpaceOverlapping(*SrcType->getAs<PointerType>())) {
Joey Gouly8fc32f02014-01-14 12:47:29 +00002217 Self.Diag(OpRange.getBegin(),
2218 diag::err_typecheck_incompatible_address_space)
2219 << SrcType << DestType << Sema::AA_Casting
2220 << SrcExpr.get()->getSourceRange();
2221 SrcExpr = ExprError();
2222 return;
2223 }
2224 }
2225
John McCall9776e432011-10-06 23:25:11 +00002226 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
2227 diag::err_typecheck_cast_to_incomplete)) {
2228 SrcExpr = ExprError();
2229 return;
2230 }
2231
2232 if (!DestType->isScalarType() && !DestType->isVectorType()) {
2233 const RecordType *DestRecordTy = DestType->getAs<RecordType>();
2234
2235 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
2236 // GCC struct/union extension: allow cast to self.
2237 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
2238 << DestType << SrcExpr.get()->getSourceRange();
2239 Kind = CK_NoOp;
2240 return;
2241 }
2242
2243 // GCC's cast to union extension.
2244 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
2245 RecordDecl *RD = DestRecordTy->getDecl();
2246 RecordDecl::field_iterator Field, FieldEnd;
2247 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2248 Field != FieldEnd; ++Field) {
2249 if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) &&
2250 !Field->isUnnamedBitfield()) {
2251 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
2252 << SrcExpr.get()->getSourceRange();
2253 break;
2254 }
2255 }
2256 if (Field == FieldEnd) {
2257 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2258 << SrcType << SrcExpr.get()->getSourceRange();
2259 SrcExpr = ExprError();
2260 return;
2261 }
2262 Kind = CK_ToUnion;
2263 return;
2264 }
2265
2266 // Reject any other conversions to non-scalar types.
2267 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
2268 << DestType << SrcExpr.get()->getSourceRange();
2269 SrcExpr = ExprError();
2270 return;
2271 }
2272
2273 // The type we're casting to is known to be a scalar or vector.
2274
2275 // Require the operand to be a scalar or vector.
2276 if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
2277 Self.Diag(SrcExpr.get()->getExprLoc(),
2278 diag::err_typecheck_expect_scalar_operand)
2279 << SrcType << SrcExpr.get()->getSourceRange();
2280 SrcExpr = ExprError();
2281 return;
2282 }
2283
2284 if (DestType->isExtVectorType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002285 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind);
John McCall9776e432011-10-06 23:25:11 +00002286 return;
2287 }
2288
2289 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
2290 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
2291 (SrcType->isIntegerType() || SrcType->isFloatingType())) {
2292 Kind = CK_VectorSplat;
2293 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
2294 SrcExpr = ExprError();
2295 }
2296 return;
2297 }
2298
2299 if (SrcType->isVectorType()) {
2300 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
2301 SrcExpr = ExprError();
2302 return;
2303 }
2304
2305 // The source and target types are both scalars, i.e.
2306 // - arithmetic types (fundamental, enum, and complex)
2307 // - all kinds of pointers
2308 // Note that member pointers were filtered out with C++, above.
2309
2310 if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
2311 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
2312 SrcExpr = ExprError();
2313 return;
2314 }
2315
2316 // If either type is a pointer, the other type has to be either an
2317 // integer or a pointer.
2318 if (!DestType->isArithmeticType()) {
2319 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
2320 Self.Diag(SrcExpr.get()->getExprLoc(),
2321 diag::err_cast_pointer_from_non_pointer_int)
2322 << SrcType << SrcExpr.get()->getSourceRange();
2323 SrcExpr = ExprError();
2324 return;
2325 }
David Blaikie282ad872012-10-16 18:53:14 +00002326 checkIntToPointerCast(/* CStyle */ true, OpRange.getBegin(), SrcExpr.get(),
2327 DestType, Self);
John McCall9776e432011-10-06 23:25:11 +00002328 } else if (!SrcType->isArithmeticType()) {
2329 if (!DestType->isIntegralType(Self.Context) &&
2330 DestType->isArithmeticType()) {
2331 Self.Diag(SrcExpr.get()->getLocStart(),
2332 diag::err_cast_pointer_to_non_pointer_int)
Abramo Bagnara9847e742011-11-15 11:25:38 +00002333 << DestType << SrcExpr.get()->getSourceRange();
John McCall9776e432011-10-06 23:25:11 +00002334 SrcExpr = ExprError();
2335 return;
2336 }
2337 }
2338
Joey Goulydd7f4562013-01-23 11:56:20 +00002339 if (Self.getLangOpts().OpenCL && !Self.getOpenCLOptions().cl_khr_fp16) {
2340 if (DestType->isHalfType()) {
2341 Self.Diag(SrcExpr.get()->getLocStart(), diag::err_opencl_cast_to_half)
2342 << DestType << SrcExpr.get()->getSourceRange();
2343 SrcExpr = ExprError();
2344 return;
2345 }
Joey Goulydd7f4562013-01-23 11:56:20 +00002346 }
2347
John McCall9776e432011-10-06 23:25:11 +00002348 // ARC imposes extra restrictions on casts.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002349 if (Self.getLangOpts().ObjCAutoRefCount) {
John McCall9776e432011-10-06 23:25:11 +00002350 checkObjCARCConversion(Sema::CCK_CStyleCast);
2351 if (SrcExpr.isInvalid())
2352 return;
2353
2354 if (const PointerType *CastPtr = DestType->getAs<PointerType>()) {
2355 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
2356 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
2357 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
2358 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
2359 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
2360 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
2361 Self.Diag(SrcExpr.get()->getLocStart(),
2362 diag::err_typecheck_incompatible_ownership)
2363 << SrcType << DestType << Sema::AA_Casting
2364 << SrcExpr.get()->getSourceRange();
2365 return;
2366 }
2367 }
2368 }
2369 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
2370 Self.Diag(SrcExpr.get()->getLocStart(),
2371 diag::err_arc_convesion_of_weak_unavailable)
2372 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2373 SrcExpr = ExprError();
2374 return;
2375 }
2376 }
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00002377
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00002378 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002379 DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
John McCall9776e432011-10-06 23:25:11 +00002380 Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2381 if (SrcExpr.isInvalid())
2382 return;
2383
2384 if (Kind == CK_BitCast)
2385 checkCastAlign();
Roman Divackyd5178012014-11-21 21:03:10 +00002386
2387 // -Wcast-qual
2388 QualType TheOffendingSrcType, TheOffendingDestType;
2389 Qualifiers CastAwayQualifiers;
2390 if (SrcType->isAnyPointerType() && DestType->isAnyPointerType() &&
2391 CastsAwayConstness(Self, SrcType, DestType, true, false,
2392 &TheOffendingSrcType, &TheOffendingDestType,
2393 &CastAwayQualifiers)) {
2394 int qualifiers = -1;
2395 if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) {
2396 qualifiers = 0;
2397 } else if (CastAwayQualifiers.hasConst()) {
2398 qualifiers = 1;
2399 } else if (CastAwayQualifiers.hasVolatile()) {
2400 qualifiers = 2;
2401 }
2402 // This is a variant of int **x; const int **y = (const int **)x;
2403 if (qualifiers == -1)
2404 Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual2) <<
2405 SrcType << DestType;
2406 else
2407 Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual) <<
2408 TheOffendingSrcType << TheOffendingDestType << qualifiers;
2409 }
John McCall9776e432011-10-06 23:25:11 +00002410}
2411
2412ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
2413 TypeSourceInfo *CastTypeInfo,
2414 SourceLocation RPLoc,
2415 Expr *CastExpr) {
John McCallb50451a2011-10-05 07:41:44 +00002416 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2417 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2418 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
2419
David Blaikiebbafb8a2012-03-11 07:00:24 +00002420 if (getLangOpts().CPlusPlus) {
Sebastian Redld74dd492012-02-12 18:41:05 +00002421 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false,
2422 isa<InitListExpr>(CastExpr));
John McCall9776e432011-10-06 23:25:11 +00002423 } else {
2424 Op.CheckCStyleCast();
2425 }
2426
John McCallb50451a2011-10-05 07:41:44 +00002427 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00002428 return ExprError();
2429
John McCall4124c492011-10-17 18:40:02 +00002430 return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002431 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
John McCall4124c492011-10-17 18:40:02 +00002432 &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
John McCallb50451a2011-10-05 07:41:44 +00002433}
2434
2435ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
2436 SourceLocation LPLoc,
2437 Expr *CastExpr,
2438 SourceLocation RPLoc) {
Sebastian Redl2b80af42012-02-13 19:55:43 +00002439 assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
John McCallb50451a2011-10-05 07:41:44 +00002440 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2441 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2442 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
2443
Sebastian Redl2b80af42012-02-13 19:55:43 +00002444 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/true, /*ListInit=*/false);
John McCallb50451a2011-10-05 07:41:44 +00002445 if (Op.SrcExpr.isInvalid())
2446 return ExprError();
Daniel Jasper3e1a9cf2012-07-16 08:05:07 +00002447
2448 if (CXXConstructExpr *ConstructExpr = dyn_cast<CXXConstructExpr>(Op.SrcExpr.get()))
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00002449 ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc));
John McCallb50451a2011-10-05 07:41:44 +00002450
John McCall4124c492011-10-17 18:40:02 +00002451 return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
Eli Friedman89fe0d52013-08-15 22:02:56 +00002452 Op.ValueKind, CastTypeInfo, Op.Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002453 Op.SrcExpr.get(), &Op.BasePath, LPLoc, RPLoc));
Sebastian Redl9f831db2009-07-25 15:41:38 +00002454}