blob: 32cb307c8647ce8878e1239fcced51e4f4872c2e [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"
Reid Kleckner9f497332016-05-10 21:00:03 +000025#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Sema/Initialization.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000027#include "llvm/ADT/SmallVector.h"
Sebastian Redl015085f2008-11-07 23:29:29 +000028#include <set>
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000029using namespace clang;
30
Douglas Gregore81f58e2010-11-08 03:40:48 +000031
Douglas Gregore81f58e2010-11-08 03:40:48 +000032
Sebastian Redl9f831db2009-07-25 15:41:38 +000033enum TryCastResult {
34 TC_NotApplicable, ///< The cast method is not applicable.
35 TC_Success, ///< The cast method is appropriate and successful.
36 TC_Failed ///< The cast method is appropriate, but failed. A
37 ///< diagnostic has been emitted.
38};
39
40enum CastType {
41 CT_Const, ///< const_cast
42 CT_Static, ///< static_cast
43 CT_Reinterpret, ///< reinterpret_cast
44 CT_Dynamic, ///< dynamic_cast
45 CT_CStyle, ///< (Type)expr
46 CT_Functional ///< Type(expr)
Sebastian Redl842ef522008-11-08 13:00:26 +000047};
48
John McCallb50451a2011-10-05 07:41:44 +000049namespace {
50 struct CastOperation {
51 CastOperation(Sema &S, QualType destType, ExprResult src)
52 : Self(S), SrcExpr(src), DestType(destType),
53 ResultType(destType.getNonLValueExprType(S.Context)),
54 ValueKind(Expr::getValueKindForType(destType)),
John McCall4124c492011-10-17 18:40:02 +000055 Kind(CK_Dependent), IsARCUnbridgedCast(false) {
John McCall9776e432011-10-06 23:25:11 +000056
57 if (const BuiltinType *placeholder =
58 src.get()->getType()->getAsPlaceholderType()) {
59 PlaceholderKind = placeholder->getKind();
60 } else {
61 PlaceholderKind = (BuiltinType::Kind) 0;
62 }
63 }
Douglas Gregore81f58e2010-11-08 03:40:48 +000064
John McCallb50451a2011-10-05 07:41:44 +000065 Sema &Self;
66 ExprResult SrcExpr;
67 QualType DestType;
68 QualType ResultType;
69 ExprValueKind ValueKind;
70 CastKind Kind;
John McCall9776e432011-10-06 23:25:11 +000071 BuiltinType::Kind PlaceholderKind;
John McCallb50451a2011-10-05 07:41:44 +000072 CXXCastPath BasePath;
John McCall4124c492011-10-17 18:40:02 +000073 bool IsARCUnbridgedCast;
Douglas Gregore81f58e2010-11-08 03:40:48 +000074
John McCallb50451a2011-10-05 07:41:44 +000075 SourceRange OpRange;
76 SourceRange DestRange;
Douglas Gregore81f58e2010-11-08 03:40:48 +000077
John McCall9776e432011-10-06 23:25:11 +000078 // Top-level semantics-checking routines.
John McCallb50451a2011-10-05 07:41:44 +000079 void CheckConstCast();
80 void CheckReinterpretCast();
Richard Smith507840d2011-11-29 22:48:16 +000081 void CheckStaticCast();
John McCallb50451a2011-10-05 07:41:44 +000082 void CheckDynamicCast();
Sebastian Redld74dd492012-02-12 18:41:05 +000083 void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
John McCall9776e432011-10-06 23:25:11 +000084 void CheckCStyleCast();
85
John McCall4124c492011-10-17 18:40:02 +000086 /// Complete an apparently-successful cast operation that yields
87 /// the given expression.
88 ExprResult complete(CastExpr *castExpr) {
89 // If this is an unbridged cast, wrap the result in an implicit
90 // cast that yields the unbridged-cast placeholder type.
91 if (IsARCUnbridgedCast) {
92 castExpr = ImplicitCastExpr::Create(Self.Context,
93 Self.Context.ARCUnbridgedCastTy,
Craig Topperc3ec1492014-05-26 06:22:03 +000094 CK_Dependent, castExpr, nullptr,
John McCall4124c492011-10-17 18:40:02 +000095 castExpr->getValueKind());
96 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000097 return castExpr;
John McCall4124c492011-10-17 18:40:02 +000098 }
99
John McCall9776e432011-10-06 23:25:11 +0000100 // Internal convenience methods.
101
102 /// Try to handle the given placeholder expression kind. Return
103 /// true if the source expression has the appropriate placeholder
104 /// kind. A placeholder can only be claimed once.
105 bool claimPlaceholder(BuiltinType::Kind K) {
106 if (PlaceholderKind != K) return false;
107
108 PlaceholderKind = (BuiltinType::Kind) 0;
109 return true;
110 }
111
112 bool isPlaceholder() const {
113 return PlaceholderKind != 0;
114 }
115 bool isPlaceholder(BuiltinType::Kind K) const {
116 return PlaceholderKind == K;
117 }
John McCallb50451a2011-10-05 07:41:44 +0000118
119 void checkCastAlign() {
120 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
121 }
122
Brian Kelley11352a82017-03-29 18:09:02 +0000123 void checkObjCConversion(Sema::CheckedConversionKind CCK) {
124 assert(Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers());
John McCall4124c492011-10-17 18:40:02 +0000125
John McCallb50451a2011-10-05 07:41:44 +0000126 Expr *src = SrcExpr.get();
Brian Kelley11352a82017-03-29 18:09:02 +0000127 if (Self.CheckObjCConversion(OpRange, DestType, src, CCK) ==
128 Sema::ACR_unbridged)
John McCall4124c492011-10-17 18:40:02 +0000129 IsARCUnbridgedCast = true;
John McCallb50451a2011-10-05 07:41:44 +0000130 SrcExpr = src;
131 }
John McCall9776e432011-10-06 23:25:11 +0000132
133 /// Check for and handle non-overload placeholder expressions.
134 void checkNonOverloadPlaceholders() {
135 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
136 return;
137
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000138 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +0000139 if (SrcExpr.isInvalid())
140 return;
141 PlaceholderKind = (BuiltinType::Kind) 0;
142 }
John McCallb50451a2011-10-05 07:41:44 +0000143 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000144}
Sebastian Redl842ef522008-11-08 13:00:26 +0000145
Roman Lebedevba80b8d2017-07-03 17:59:22 +0000146static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
147 QualType DestType);
148
Sebastian Redl9f831db2009-07-25 15:41:38 +0000149// The Try functions attempt a specific way of casting. If they succeed, they
150// return TC_Success. If their way of casting is not appropriate for the given
151// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
152// to emit if no other way succeeds. If their way of casting is appropriate but
153// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
154// they emit a specialized diagnostic.
155// All diagnostics returned by these functions must expect the same three
156// arguments:
157// %0: Cast Type (a value from the CastType enumeration)
158// %1: Source Type
159// %2: Destination Type
160static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
Douglas Gregorce950842011-01-26 21:04:06 +0000161 QualType DestType, bool CStyle,
162 CastKind &Kind,
Douglas Gregorba278e22011-01-25 16:13:26 +0000163 CXXCastPath &BasePath,
164 unsigned &msg);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000165static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000166 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000167 SourceRange OpRange,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000168 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000169 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000170 CXXCastPath &BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000171static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
172 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000173 SourceRange OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000174 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000175 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000176 CXXCastPath &BasePath);
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000177static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
178 CanQualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000179 SourceRange OpRange,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000180 QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000181 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000182 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000183 CXXCastPath &BasePath);
John Wiegley01296292011-04-08 18:41:53 +0000184static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000185 QualType SrcType,
186 QualType DestType,bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000187 SourceRange OpRange,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000188 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000189 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000190 CXXCastPath &BasePath);
Anders Carlssonb78feca2010-04-24 19:22:20 +0000191
John Wiegley01296292011-04-08 18:41:53 +0000192static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000193 QualType DestType,
194 Sema::CheckedConversionKind CCK,
Craig Toppere335f252015-10-04 04:53:55 +0000195 SourceRange OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +0000196 unsigned &msg, CastKind &Kind,
197 bool ListInitialization);
John Wiegley01296292011-04-08 18:41:53 +0000198static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000199 QualType DestType,
200 Sema::CheckedConversionKind CCK,
Craig Toppere335f252015-10-04 04:53:55 +0000201 SourceRange OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +0000202 unsigned &msg, CastKind &Kind,
203 CXXCastPath &BasePath,
204 bool ListInitialization);
Richard Smith82c9b512013-06-14 22:27:52 +0000205static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
206 QualType DestType, bool CStyle,
207 unsigned &msg);
John Wiegley01296292011-04-08 18:41:53 +0000208static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000209 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +0000210 SourceRange OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000211 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000212 CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +0000213
Douglas Gregorb491ed32011-02-19 21:32:49 +0000214
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000215/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
John McCalldadc5752010-08-24 06:29:42 +0000216ExprResult
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000217Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000218 SourceLocation LAngleBracketLoc, Declarator &D,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000219 SourceLocation RAngleBracketLoc,
John McCallfaf5fb42010-08-26 23:41:50 +0000220 SourceLocation LParenLoc, Expr *E,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000221 SourceLocation RParenLoc) {
John McCalld377e042010-01-15 19:13:16 +0000222
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000223 assert(!D.isInvalidType());
224
225 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
226 if (D.isInvalidType())
227 return ExprError();
228
David Blaikiebbafb8a2012-03-11 07:00:24 +0000229 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +0000230 // Check that there are no default arguments (C++ only).
231 CheckExtraCXXDefaultArguments(D);
232 }
233
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000234 return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
John McCalld377e042010-01-15 19:13:16 +0000235 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
236 SourceRange(LParenLoc, RParenLoc));
237}
238
John McCalldadc5752010-08-24 06:29:42 +0000239ExprResult
John McCalld377e042010-01-15 19:13:16 +0000240Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John Wiegley01296292011-04-08 18:41:53 +0000241 TypeSourceInfo *DestTInfo, Expr *E,
John McCalld377e042010-01-15 19:13:16 +0000242 SourceRange AngleBrackets, SourceRange Parens) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000243 ExprResult Ex = E;
John McCalld377e042010-01-15 19:13:16 +0000244 QualType DestType = DestTInfo->getType();
245
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000246 // If the type is dependent, we won't do the semantic analysis now.
David Majnemere64941f2014-12-16 00:46:30 +0000247 bool TypeDependent =
248 DestType->isDependentType() || Ex.get()->isTypeDependent();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000249
John McCallb50451a2011-10-05 07:41:44 +0000250 CastOperation Op(*this, DestType, E);
251 Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
252 Op.DestRange = AngleBrackets;
John McCall29ac8e22010-11-26 10:57:22 +0000253
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000254 switch (Kind) {
John McCall8cb679e2010-11-15 09:13:47 +0000255 default: llvm_unreachable("Unknown C++ cast!");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000256
257 case tok::kw_const_cast:
John Wiegley01296292011-04-08 18:41:53 +0000258 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000259 Op.CheckConstCast();
260 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000261 return ExprError();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +0000262 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
John Wiegley01296292011-04-08 18:41:53 +0000263 }
John McCall4124c492011-10-17 18:40:02 +0000264 return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000265 Op.ValueKind, Op.SrcExpr.get(), DestTInfo,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000266 OpLoc, Parens.getEnd(),
267 AngleBrackets));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000268
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000269 case tok::kw_dynamic_cast: {
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +0000270 // OpenCL C++ 1.0 s2.9: dynamic_cast is not supported.
271 if (getLangOpts().OpenCLCPlusPlus) {
272 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
273 << "dynamic_cast");
274 }
275
John Wiegley01296292011-04-08 18:41:53 +0000276 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000277 Op.CheckDynamicCast();
278 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000279 return ExprError();
280 }
John McCall4124c492011-10-17 18:40:02 +0000281 return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000282 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
John McCall4124c492011-10-17 18:40:02 +0000283 &Op.BasePath, DestTInfo,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000284 OpLoc, Parens.getEnd(),
285 AngleBrackets));
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000286 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000287 case tok::kw_reinterpret_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000288 if (!TypeDependent) {
John McCallb50451a2011-10-05 07:41:44 +0000289 Op.CheckReinterpretCast();
290 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000291 return ExprError();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +0000292 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
John Wiegley01296292011-04-08 18:41:53 +0000293 }
John McCall4124c492011-10-17 18:40:02 +0000294 return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000295 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
Craig Topperc3ec1492014-05-26 06:22:03 +0000296 nullptr, DestTInfo, OpLoc,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000297 Parens.getEnd(),
298 AngleBrackets));
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000299 }
Anders Carlssonf10e4142009-08-07 22:21:05 +0000300 case tok::kw_static_cast: {
John Wiegley01296292011-04-08 18:41:53 +0000301 if (!TypeDependent) {
Richard Smith507840d2011-11-29 22:48:16 +0000302 Op.CheckStaticCast();
John McCallb50451a2011-10-05 07:41:44 +0000303 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000304 return ExprError();
Roger Ferrer Ibanez722a4db2016-08-12 08:04:13 +0000305 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
John Wiegley01296292011-04-08 18:41:53 +0000306 }
Anders Carlssone9766d52009-09-09 21:33:21 +0000307
John McCall4124c492011-10-17 18:40:02 +0000308 return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000309 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
John McCall4124c492011-10-17 18:40:02 +0000310 &Op.BasePath, DestTInfo,
Fariborz Jahanianf0738712013-02-22 22:02:53 +0000311 OpLoc, Parens.getEnd(),
312 AngleBrackets));
Anders Carlssonf10e4142009-08-07 22:21:05 +0000313 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000314 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000315}
316
John McCall909acf82011-02-14 18:34:10 +0000317/// Try to diagnose a failed overloaded cast. Returns true if
318/// diagnostics were emitted.
319static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
320 SourceRange range, Expr *src,
Sebastian Redl2b80af42012-02-13 19:55:43 +0000321 QualType destType,
322 bool listInitialization) {
John McCall909acf82011-02-14 18:34:10 +0000323 switch (CT) {
324 // These cast kinds don't consider user-defined conversions.
325 case CT_Const:
326 case CT_Reinterpret:
327 case CT_Dynamic:
328 return false;
329
330 // These do.
331 case CT_Static:
332 case CT_CStyle:
333 case CT_Functional:
334 break;
335 }
336
337 QualType srcType = src->getType();
338 if (!destType->isRecordType() && !srcType->isRecordType())
339 return false;
340
341 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
342 InitializationKind initKind
John McCall31168b02011-06-15 23:02:42 +0000343 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
Sebastian Redl2b80af42012-02-13 19:55:43 +0000344 range, listInitialization)
Sebastian Redl0501c632012-02-12 16:37:36 +0000345 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
Sebastian Redl2b80af42012-02-13 19:55:43 +0000346 listInitialization)
Richard Smith507840d2011-11-29 22:48:16 +0000347 : InitializationKind::CreateCast(/*type range?*/ range);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000348 InitializationSequence sequence(S, entity, initKind, src);
John McCall909acf82011-02-14 18:34:10 +0000349
Sebastian Redlc7ca5872011-06-05 12:23:28 +0000350 assert(sequence.Failed() && "initialization succeeded on second try?");
John McCall909acf82011-02-14 18:34:10 +0000351 switch (sequence.getFailureKind()) {
352 default: return false;
353
354 case InitializationSequence::FK_ConstructorOverloadFailed:
355 case InitializationSequence::FK_UserConversionOverloadFailed:
356 break;
357 }
358
359 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
360
361 unsigned msg = 0;
362 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
363
364 switch (sequence.getFailedOverloadResult()) {
365 case OR_Success: llvm_unreachable("successful failed overload");
John McCall909acf82011-02-14 18:34:10 +0000366 case OR_No_Viable_Function:
367 if (candidates.empty())
368 msg = diag::err_ovl_no_conversion_in_cast;
369 else
370 msg = diag::err_ovl_no_viable_conversion_in_cast;
371 howManyCandidates = OCD_AllCandidates;
372 break;
373
374 case OR_Ambiguous:
375 msg = diag::err_ovl_ambiguous_conversion_in_cast;
376 howManyCandidates = OCD_ViableCandidates;
377 break;
378
379 case OR_Deleted:
380 msg = diag::err_ovl_deleted_conversion_in_cast;
381 howManyCandidates = OCD_ViableCandidates;
382 break;
383 }
384
385 S.Diag(range.getBegin(), msg)
386 << CT << srcType << destType
387 << range << src->getSourceRange();
388
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +0000389 candidates.NoteCandidates(S, howManyCandidates, src);
John McCall909acf82011-02-14 18:34:10 +0000390
391 return true;
392}
393
394/// Diagnose a failed cast.
395static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
Sebastian Redl2b80af42012-02-13 19:55:43 +0000396 SourceRange opRange, Expr *src, QualType destType,
397 bool listInitialization) {
John McCall909acf82011-02-14 18:34:10 +0000398 if (msg == diag::err_bad_cxx_cast_generic &&
Sebastian Redl2b80af42012-02-13 19:55:43 +0000399 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
400 listInitialization))
John McCall909acf82011-02-14 18:34:10 +0000401 return;
402
403 S.Diag(opRange.getBegin(), msg) << castType
404 << src->getType() << destType << opRange << src->getSourceRange();
Nathan Sidwellffa7dc32015-01-28 21:31:26 +0000405
406 // Detect if both types are (ptr to) class, and note any incompleteness.
407 int DifferentPtrness = 0;
408 QualType From = destType;
409 if (auto Ptr = From->getAs<PointerType>()) {
410 From = Ptr->getPointeeType();
411 DifferentPtrness++;
412 }
413 QualType To = src->getType();
414 if (auto Ptr = To->getAs<PointerType>()) {
415 To = Ptr->getPointeeType();
416 DifferentPtrness--;
417 }
418 if (!DifferentPtrness) {
419 auto RecFrom = From->getAs<RecordType>();
420 auto RecTo = To->getAs<RecordType>();
421 if (RecFrom && RecTo) {
422 auto DeclFrom = RecFrom->getAsCXXRecordDecl();
423 if (!DeclFrom->isCompleteDefinition())
424 S.Diag(DeclFrom->getLocation(), diag::note_type_incomplete)
425 << DeclFrom->getDeclName();
426 auto DeclTo = RecTo->getAsCXXRecordDecl();
427 if (!DeclTo->isCompleteDefinition())
428 S.Diag(DeclTo->getLocation(), diag::note_type_incomplete)
429 << DeclTo->getDeclName();
430 }
431 }
John McCall909acf82011-02-14 18:34:10 +0000432}
433
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000434/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
435/// this removes one level of indirection from both types, provided that they're
436/// the same kind of pointer (plain or to-member). Unlike the Sema function,
437/// this one doesn't care if the two pointers-to-member don't point into the
438/// same class. This is because CastsAwayConstness doesn't care.
Roman Lebedevba80b8d2017-07-03 17:59:22 +0000439/// And additionally, it handles C++ references. If both the types are
440/// references, then their pointee types are returned,
441/// else if only one of them is reference, it's pointee type is returned,
442/// and the other type is returned as-is.
Dan Gohman28ade552010-07-26 21:25:24 +0000443static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000444 const PointerType *T1PtrType = T1->getAs<PointerType>(),
445 *T2PtrType = T2->getAs<PointerType>();
446 if (T1PtrType && T2PtrType) {
447 T1 = T1PtrType->getPointeeType();
448 T2 = T2PtrType->getPointeeType();
449 return true;
450 }
Fariborz Jahanian8c3f06d2010-02-03 20:32:31 +0000451 const ObjCObjectPointerType *T1ObjCPtrType =
452 T1->getAs<ObjCObjectPointerType>(),
453 *T2ObjCPtrType =
454 T2->getAs<ObjCObjectPointerType>();
455 if (T1ObjCPtrType) {
456 if (T2ObjCPtrType) {
457 T1 = T1ObjCPtrType->getPointeeType();
458 T2 = T2ObjCPtrType->getPointeeType();
459 return true;
460 }
461 else if (T2PtrType) {
462 T1 = T1ObjCPtrType->getPointeeType();
463 T2 = T2PtrType->getPointeeType();
464 return true;
465 }
466 }
467 else if (T2ObjCPtrType) {
468 if (T1PtrType) {
469 T2 = T2ObjCPtrType->getPointeeType();
470 T1 = T1PtrType->getPointeeType();
471 return true;
472 }
473 }
474
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000475 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
476 *T2MPType = T2->getAs<MemberPointerType>();
477 if (T1MPType && T2MPType) {
478 T1 = T1MPType->getPointeeType();
479 T2 = T2MPType->getPointeeType();
480 return true;
481 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000482
483 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
484 *T2BPType = T2->getAs<BlockPointerType>();
485 if (T1BPType && T2BPType) {
486 T1 = T1BPType->getPointeeType();
487 T2 = T2BPType->getPointeeType();
488 return true;
489 }
490
Roman Lebedevba80b8d2017-07-03 17:59:22 +0000491 const LValueReferenceType *T1RefType = T1->getAs<LValueReferenceType>(),
492 *T2RefType = T2->getAs<LValueReferenceType>();
493 if (T1RefType && T2RefType) {
494 T1 = T1RefType->getPointeeType();
495 T2 = T2RefType->getPointeeType();
496 return true;
497 }
498
499 if (T1RefType) {
500 T1 = T1RefType->getPointeeType();
501 // T2 = T2;
502 return true;
503 }
504
505 if (T2RefType) {
506 // T1 = T1;
507 T2 = T2RefType->getPointeeType();
508 return true;
509 }
510
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000511 return false;
512}
513
Sebastian Redla5a77a62009-01-27 23:18:31 +0000514/// CastsAwayConstness - Check if the pointer conversion from SrcType to
515/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
516/// the cast checkers. Both arguments must denote pointer (possibly to member)
517/// types.
John McCall31168b02011-06-15 23:02:42 +0000518///
519/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
520///
521/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
Sebastian Redl802f14c2009-10-22 15:07:22 +0000522static bool
John McCall31168b02011-06-15 23:02:42 +0000523CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
Roman Divackyd5178012014-11-21 21:03:10 +0000524 bool CheckCVR, bool CheckObjCLifetime,
525 QualType *TheOffendingSrcType = nullptr,
526 QualType *TheOffendingDestType = nullptr,
527 Qualifiers *CastAwayQualifiers = nullptr) {
John McCall31168b02011-06-15 23:02:42 +0000528 // If the only checking we care about is for Objective-C lifetime qualifiers,
John McCall460ce582015-10-22 18:38:17 +0000529 // and we're not in ObjC mode, there's nothing to check.
John McCall31168b02011-06-15 23:02:42 +0000530 if (!CheckCVR && CheckObjCLifetime &&
John McCall460ce582015-10-22 18:38:17 +0000531 !Self.Context.getLangOpts().ObjC1)
John McCall31168b02011-06-15 23:02:42 +0000532 return false;
533
Sebastian Redla5a77a62009-01-27 23:18:31 +0000534 // Casting away constness is defined in C++ 5.2.11p8 with reference to
535 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
536 // the rules are non-trivial. So first we construct Tcv *...cv* as described
537 // in C++ 5.2.11p8.
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000538 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
Roman Lebedevba80b8d2017-07-03 17:59:22 +0000539 SrcType->isBlockPointerType() ||
540 DestType->isLValueReferenceType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000541 "Source type is not pointer or pointer to member.");
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000542 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
Roman Lebedevba80b8d2017-07-03 17:59:22 +0000543 DestType->isBlockPointerType() ||
544 DestType->isLValueReferenceType()) &&
545 "Destination type is not pointer or pointer to member, or reference.");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000546
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000547 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
548 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000549 SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000550
Douglas Gregorb472e932011-04-15 17:59:54 +0000551 // Find the qualifiers. We only care about cvr-qualifiers for the
552 // purpose of this check, because other qualifiers (address spaces,
553 // Objective-C GC, etc.) are part of the type's identity.
Roman Divackyd5178012014-11-21 21:03:10 +0000554 QualType PrevUnwrappedSrcType = UnwrappedSrcType;
555 QualType PrevUnwrappedDestType = UnwrappedDestType;
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000556 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCall31168b02011-06-15 23:02:42 +0000557 // Determine the relevant qualifiers at this level.
558 Qualifiers SrcQuals, DestQuals;
Anders Carlsson76f513f2010-06-04 22:47:55 +0000559 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
Anders Carlsson76f513f2010-06-04 22:47:55 +0000560 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
Akira Hatanaka8d7bdf62017-08-11 00:06:49 +0000561
562 // We do not meaningfully track object const-ness of Objective-C object
563 // types. Remove const from the source type if either the source or
564 // the destination is an Objective-C object type.
565 if (UnwrappedSrcType->isObjCObjectType() ||
566 UnwrappedDestType->isObjCObjectType())
567 SrcQuals.removeConst();
568
John McCall31168b02011-06-15 23:02:42 +0000569 Qualifiers RetainedSrcQuals, RetainedDestQuals;
570 if (CheckCVR) {
571 RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
572 RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
Roman Divackyd5178012014-11-21 21:03:10 +0000573
574 if (RetainedSrcQuals != RetainedDestQuals && TheOffendingSrcType &&
575 TheOffendingDestType && CastAwayQualifiers) {
576 *TheOffendingSrcType = PrevUnwrappedSrcType;
577 *TheOffendingDestType = PrevUnwrappedDestType;
578 *CastAwayQualifiers = RetainedSrcQuals - RetainedDestQuals;
579 }
John McCall31168b02011-06-15 23:02:42 +0000580 }
581
582 if (CheckObjCLifetime &&
583 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
584 return true;
585
586 cv1.push_back(RetainedSrcQuals);
587 cv2.push_back(RetainedDestQuals);
Roman Divackyd5178012014-11-21 21:03:10 +0000588
589 PrevUnwrappedSrcType = UnwrappedSrcType;
590 PrevUnwrappedDestType = UnwrappedDestType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000591 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000592 if (cv1.empty())
593 return false;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000594
595 // Construct void pointers with those qualifiers (in reverse order of
596 // unwrapping, of course).
Sebastian Redl842ef522008-11-08 13:00:26 +0000597 QualType SrcConstruct = Self.Context.VoidTy;
598 QualType DestConstruct = Self.Context.VoidTy;
John McCall8ccfcb52009-09-24 19:53:00 +0000599 ASTContext &Context = Self.Context;
Craig Topper61ac9062013-07-08 03:55:09 +0000600 for (SmallVectorImpl<Qualifiers>::reverse_iterator i1 = cv1.rbegin(),
601 i2 = cv2.rbegin();
Mike Stump11289f42009-09-09 15:08:12 +0000602 i1 != cv1.rend(); ++i1, ++i2) {
John McCall8ccfcb52009-09-24 19:53:00 +0000603 SrcConstruct
604 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
605 DestConstruct
606 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000607 }
608
609 // Test if they're compatible.
John McCall31168b02011-06-15 23:02:42 +0000610 bool ObjCLifetimeConversion;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000611 return SrcConstruct != DestConstruct &&
John McCall31168b02011-06-15 23:02:42 +0000612 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
613 ObjCLifetimeConversion);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000614}
615
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000616/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
617/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
618/// checked downcasts in class hierarchies.
John McCallb50451a2011-10-05 07:41:44 +0000619void CastOperation::CheckDynamicCast() {
Eli Friedman42b199c2012-01-12 00:44:34 +0000620 if (ValueKind == VK_RValue)
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000621 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000622 else if (isPlaceholder())
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000623 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000624 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
625 return;
Eli Friedman90a2cdf2011-10-31 20:59:03 +0000626
John McCallb50451a2011-10-05 07:41:44 +0000627 QualType OrigSrcType = SrcExpr.get()->getType();
628 QualType DestType = Self.Context.getCanonicalType(this->DestType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000629
630 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
631 // or "pointer to cv void".
632
633 QualType DestPointee;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000634 const PointerType *DestPointer = DestType->getAs<PointerType>();
Craig Topperc3ec1492014-05-26 06:22:03 +0000635 const ReferenceType *DestReference = nullptr;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000636 if (DestPointer) {
637 DestPointee = DestPointer->getPointeeType();
John McCall7decc9e2010-11-18 06:31:45 +0000638 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000639 DestPointee = DestReference->getPointeeType();
640 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000641 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
John McCallb50451a2011-10-05 07:41:44 +0000642 << this->DestType << DestRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000643 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000644 return;
645 }
646
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000647 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000648 if (DestPointee->isVoidType()) {
649 assert(DestPointer && "Reference to void is not possible");
650 } else if (DestRecord) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000651 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000652 diag::err_bad_dynamic_cast_incomplete,
Eli Friedman3fd26b82013-07-26 23:47:47 +0000653 DestRange)) {
654 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000655 return;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000656 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000657 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000658 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000659 << DestPointee.getUnqualifiedType() << DestRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000660 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000661 return;
662 }
663
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000664 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
665 // complete class type, [...]. If T is an lvalue reference type, v shall be
Douglas Gregor465184a2011-01-22 00:06:57 +0000666 // an lvalue of a complete class type, [...]. If T is an rvalue reference
667 // type, v shall be an expression having a complete class type, [...]
Sebastian Redl842ef522008-11-08 13:00:26 +0000668 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000669 QualType SrcPointee;
670 if (DestPointer) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000671 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000672 SrcPointee = SrcPointer->getPointeeType();
673 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000674 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
John Wiegley01296292011-04-08 18:41:53 +0000675 << OrigSrcType << SrcExpr.get()->getSourceRange();
Eli Friedman3fd26b82013-07-26 23:47:47 +0000676 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000677 return;
678 }
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000679 } else if (DestReference->isLValueReferenceType()) {
John Wiegley01296292011-04-08 18:41:53 +0000680 if (!SrcExpr.get()->isLValue()) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000681 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
John McCallb50451a2011-10-05 07:41:44 +0000682 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000683 }
684 SrcPointee = SrcType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000685 } else {
Richard Smith11330852014-07-08 17:25:14 +0000686 // If we're dynamic_casting from a prvalue to an rvalue reference, we need
687 // to materialize the prvalue before we bind the reference to it.
688 if (SrcExpr.get()->isRValue())
Tim Shen4a05bb82016-06-21 20:29:17 +0000689 SrcExpr = Self.CreateMaterializeTemporaryExpr(
690 SrcType, SrcExpr.get(), /*IsLValueReference*/ false);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000691 SrcPointee = SrcType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000692 }
693
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000694 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000695 if (SrcRecord) {
Douglas Gregored0cfbd2009-03-09 16:13:40 +0000696 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000697 diag::err_bad_dynamic_cast_incomplete,
Eli Friedman3fd26b82013-07-26 23:47:47 +0000698 SrcExpr.get())) {
699 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000700 return;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000701 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000702 } else {
Chris Lattner29e812b2008-11-20 06:06:08 +0000703 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
John Wiegley01296292011-04-08 18:41:53 +0000704 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Eli Friedman3fd26b82013-07-26 23:47:47 +0000705 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000706 return;
707 }
708
709 assert((DestPointer || DestReference) &&
710 "Bad destination non-ptr/ref slipped through.");
711 assert((DestRecord || DestPointee->isVoidType()) &&
712 "Bad destination pointee slipped through.");
713 assert(SrcRecord && "Bad source pointee slipped through.");
714
715 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
716 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Douglas Gregorb472e932011-04-15 17:59:54 +0000717 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
John McCallb50451a2011-10-05 07:41:44 +0000718 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000719 SrcExpr = ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000720 return;
721 }
722
723 // C++ 5.2.7p3: If the type of v is the same as the required result type,
724 // [except for cv].
725 if (DestRecord == SrcRecord) {
John McCalle3027922010-08-25 11:45:40 +0000726 Kind = CK_NoOp;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000727 return;
728 }
729
730 // C++ 5.2.7p5
731 // Upcasts are resolved statically.
Richard Smith0f59cb32015-12-18 21:45:41 +0000732 if (DestRecord &&
733 Self.IsDerivedFrom(OpRange.getBegin(), SrcPointee, DestPointee)) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000734 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
735 OpRange.getBegin(), OpRange,
Eli Friedman3fd26b82013-07-26 23:47:47 +0000736 &BasePath)) {
737 SrcExpr = ExprError();
738 return;
739 }
Richard Smith11330852014-07-08 17:25:14 +0000740
John McCalle3027922010-08-25 11:45:40 +0000741 Kind = CK_DerivedToBase;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000742 return;
743 }
744
745 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000746 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000747 assert(SrcDecl && "Definition missing");
748 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner29e812b2008-11-20 06:06:08 +0000749 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
John Wiegley01296292011-04-08 18:41:53 +0000750 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Eli Friedman3fd26b82013-07-26 23:47:47 +0000751 SrcExpr = ExprError();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000752 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000753
Eli Friedman3ce27102013-09-24 23:21:41 +0000754 // dynamic_cast is not available with -fno-rtti.
755 // As an exception, dynamic_cast to void* is available because it doesn't
756 // use RTTI.
757 if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) {
Arnaud A. de Grandmaisoncb6f9432013-08-01 08:28:32 +0000758 Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti);
759 SrcExpr = ExprError();
760 return;
761 }
762
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000763 // Done. Everything else is run-time checks.
John McCalle3027922010-08-25 11:45:40 +0000764 Kind = CK_Dynamic;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000765}
Sebastian Redl9f831db2009-07-25 15:41:38 +0000766
767/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
768/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
769/// like this:
770/// const char *str = "literal";
771/// legacy_function(const_cast\<char*\>(str));
John McCallb50451a2011-10-05 07:41:44 +0000772void CastOperation::CheckConstCast() {
Eli Friedman42b199c2012-01-12 00:44:34 +0000773 if (ValueKind == VK_RValue)
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000774 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000775 else if (isPlaceholder())
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000776 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000777 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
778 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000779
780 unsigned msg = diag::err_bad_cxx_cast_generic;
Richard Smith82c9b512013-06-14 22:27:52 +0000781 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
Eli Friedman3fd26b82013-07-26 23:47:47 +0000782 && msg != 0) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000783 Self.Diag(OpRange.getBegin(), msg) << CT_Const
John Wiegley01296292011-04-08 18:41:53 +0000784 << SrcExpr.get()->getType() << DestType << OpRange;
Eli Friedman3fd26b82013-07-26 23:47:47 +0000785 SrcExpr = ExprError();
786 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000787}
788
John McCallcda80832013-03-22 02:58:14 +0000789/// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
790/// or downcast between respective pointers or references.
791static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
792 QualType DestType,
793 SourceRange OpRange) {
794 QualType SrcType = SrcExpr->getType();
795 // When casting from pointer or reference, get pointee type; use original
796 // type otherwise.
797 const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
798 const CXXRecordDecl *SrcRD =
799 SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
800
John McCallf2abe192013-03-27 00:03:48 +0000801 // Examining subobjects for records is only possible if the complete and
802 // valid definition is available. Also, template instantiation is not
803 // allowed here.
804 if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
John McCallcda80832013-03-22 02:58:14 +0000805 return;
806
807 const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
808
John McCallf2abe192013-03-27 00:03:48 +0000809 if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
John McCallcda80832013-03-22 02:58:14 +0000810 return;
811
812 enum {
813 ReinterpretUpcast,
814 ReinterpretDowncast
815 } ReinterpretKind;
816
817 CXXBasePaths BasePaths;
818
819 if (SrcRD->isDerivedFrom(DestRD, BasePaths))
820 ReinterpretKind = ReinterpretUpcast;
821 else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
822 ReinterpretKind = ReinterpretDowncast;
823 else
824 return;
825
826 bool VirtualBase = true;
827 bool NonZeroOffset = false;
John McCallf2abe192013-03-27 00:03:48 +0000828 for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
John McCallcda80832013-03-22 02:58:14 +0000829 E = BasePaths.end();
830 I != E; ++I) {
831 const CXXBasePath &Path = *I;
832 CharUnits Offset = CharUnits::Zero();
833 bool IsVirtual = false;
834 for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
835 IElem != EElem; ++IElem) {
836 IsVirtual = IElem->Base->isVirtual();
837 if (IsVirtual)
838 break;
839 const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
840 assert(BaseRD && "Base type should be a valid unqualified class type");
John McCallf2abe192013-03-27 00:03:48 +0000841 // Don't check if any base has invalid declaration or has no definition
842 // since it has no layout info.
843 const CXXRecordDecl *Class = IElem->Class,
844 *ClassDefinition = Class->getDefinition();
845 if (Class->isInvalidDecl() || !ClassDefinition ||
846 !ClassDefinition->isCompleteDefinition())
847 return;
848
John McCallcda80832013-03-22 02:58:14 +0000849 const ASTRecordLayout &DerivedLayout =
John McCallf2abe192013-03-27 00:03:48 +0000850 Self.Context.getASTRecordLayout(Class);
John McCallcda80832013-03-22 02:58:14 +0000851 Offset += DerivedLayout.getBaseClassOffset(BaseRD);
852 }
853 if (!IsVirtual) {
854 // Don't warn if any path is a non-virtually derived base at offset zero.
855 if (Offset.isZero())
856 return;
857 // Offset makes sense only for non-virtual bases.
858 else
859 NonZeroOffset = true;
860 }
861 VirtualBase = VirtualBase && IsVirtual;
862 }
863
Andy Gibbsfa5026d2013-06-19 13:33:37 +0000864 (void) NonZeroOffset; // Silence set but not used warning.
John McCallcda80832013-03-22 02:58:14 +0000865 assert((VirtualBase || NonZeroOffset) &&
866 "Should have returned if has non-virtual base with zero offset");
867
868 QualType BaseType =
869 ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
870 QualType DerivedType =
871 ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
872
Jordan Rose04a94d12013-03-28 19:09:40 +0000873 SourceLocation BeginLoc = OpRange.getBegin();
874 Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000875 << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind)
Jordan Rose04a94d12013-03-28 19:09:40 +0000876 << OpRange;
877 Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +0000878 << int(ReinterpretKind)
Jordan Rose04a94d12013-03-28 19:09:40 +0000879 << FixItHint::CreateReplacement(BeginLoc, "static_cast");
John McCallcda80832013-03-22 02:58:14 +0000880}
881
Sebastian Redl9f831db2009-07-25 15:41:38 +0000882/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
883/// valid.
884/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
885/// like this:
886/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
John McCallb50451a2011-10-05 07:41:44 +0000887void CastOperation::CheckReinterpretCast() {
Eli Friedman42b199c2012-01-12 00:44:34 +0000888 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000889 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
Eli Friedman42b199c2012-01-12 00:44:34 +0000890 else
891 checkNonOverloadPlaceholders();
892 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
893 return;
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 =
897 TryReinterpretCast(Self, SrcExpr, DestType,
898 /*CStyle*/false, OpRange, msg, Kind);
899 if (tcr != TC_Success && msg != 0)
Douglas Gregore81f58e2010-11-08 03:40:48 +0000900 {
John Wiegley01296292011-04-08 18:41:53 +0000901 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
902 return;
903 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +0000904 //FIXME: &f<int>; is overloaded and resolvable
905 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
John Wiegley01296292011-04-08 18:41:53 +0000906 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
Douglas Gregore81f58e2010-11-08 03:40:48 +0000907 << DestType << OpRange;
John Wiegley01296292011-04-08 18:41:53 +0000908 Self.NoteAllOverloadCandidates(SrcExpr.get());
Douglas Gregore81f58e2010-11-08 03:40:48 +0000909
John McCall909acf82011-02-14 18:34:10 +0000910 } else {
Sebastian Redl2b80af42012-02-13 19:55:43 +0000911 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
912 DestType, /*listInitialization=*/false);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000913 }
Eli Friedman3fd26b82013-07-26 23:47:47 +0000914 SrcExpr = ExprError();
John McCallcda80832013-03-22 02:58:14 +0000915 } else if (tcr == TC_Success) {
Brian Kelley762f9282017-03-29 18:16:38 +0000916 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
Brian Kelley11352a82017-03-29 18:09:02 +0000917 checkObjCConversion(Sema::CCK_OtherCast);
John McCallcda80832013-03-22 02:58:14 +0000918 DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
John McCall31168b02011-06-15 23:02:42 +0000919 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000920}
921
922
923/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
924/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
925/// implicit conversions explicit and getting rid of data loss warnings.
Richard Smith507840d2011-11-29 22:48:16 +0000926void CastOperation::CheckStaticCast() {
John McCall9776e432011-10-06 23:25:11 +0000927 if (isPlaceholder()) {
928 checkNonOverloadPlaceholders();
929 if (SrcExpr.isInvalid())
930 return;
931 }
932
Sebastian Redl9f831db2009-07-25 15:41:38 +0000933 // This test is outside everything else because it's the only case where
934 // a non-lvalue-reference target type does not lead to decay.
935 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman03bf60a2009-11-16 05:44:20 +0000936 if (DestType->isVoidType()) {
John McCall9776e432011-10-06 23:25:11 +0000937 Kind = CK_ToVoid;
938
939 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall50a2c2c2011-10-11 23:14:30 +0000940 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
Douglas Gregorb491ed32011-02-19 21:32:49 +0000941 false, // Decay Function to ptr
942 true, // Complain
943 OpRange, DestType, diag::err_bad_static_cast_overload);
John McCall50a2c2c2011-10-11 23:14:30 +0000944 if (SrcExpr.isInvalid())
945 return;
Douglas Gregorb491ed32011-02-19 21:32:49 +0000946 }
John McCall9776e432011-10-06 23:25:11 +0000947
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000948 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
Sebastian Redl9f831db2009-07-25 15:41:38 +0000949 return;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000950 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000951
John McCall50a2c2c2011-10-11 23:14:30 +0000952 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
953 !isPlaceholder(BuiltinType::Overload)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000954 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
John Wiegley01296292011-04-08 18:41:53 +0000955 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
956 return;
957 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000958
959 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCall31168b02011-06-15 23:02:42 +0000960 TryCastResult tcr
Richard Smith507840d2011-11-29 22:48:16 +0000961 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
Sebastian Redld74dd492012-02-12 18:41:05 +0000962 Kind, BasePath, /*ListInitialization=*/false);
John McCall31168b02011-06-15 23:02:42 +0000963 if (tcr != TC_Success && msg != 0) {
John Wiegley01296292011-04-08 18:41:53 +0000964 if (SrcExpr.isInvalid())
965 return;
966 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
967 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
Douglas Gregore81f58e2010-11-08 03:40:48 +0000968 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
Douglas Gregor0da1d432011-02-28 20:01:57 +0000969 << oe->getName() << DestType << OpRange
970 << oe->getQualifierLoc().getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +0000971 Self.NoteAllOverloadCandidates(SrcExpr.get());
John McCall909acf82011-02-14 18:34:10 +0000972 } else {
Sebastian Redl2b80af42012-02-13 19:55:43 +0000973 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
974 /*listInitialization=*/false);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000975 }
Eli Friedman3fd26b82013-07-26 23:47:47 +0000976 SrcExpr = ExprError();
John McCall31168b02011-06-15 23:02:42 +0000977 } else if (tcr == TC_Success) {
978 if (Kind == CK_BitCast)
John McCallb50451a2011-10-05 07:41:44 +0000979 checkCastAlign();
Brian Kelley762f9282017-03-29 18:16:38 +0000980 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
Brian Kelley11352a82017-03-29 18:09:02 +0000981 checkObjCConversion(Sema::CCK_OtherCast);
John McCallb50451a2011-10-05 07:41:44 +0000982 } else if (Kind == CK_BitCast) {
983 checkCastAlign();
Douglas Gregore81f58e2010-11-08 03:40:48 +0000984 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000985}
986
987/// TryStaticCast - Check if a static cast can be performed, and do so if
988/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
989/// and casting away constness.
John Wiegley01296292011-04-08 18:41:53 +0000990static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCall31168b02011-06-15 23:02:42 +0000991 QualType DestType,
992 Sema::CheckedConversionKind CCK,
Craig Toppere335f252015-10-04 04:53:55 +0000993 SourceRange OpRange, unsigned &msg,
Sebastian Redld74dd492012-02-12 18:41:05 +0000994 CastKind &Kind, CXXCastPath &BasePath,
995 bool ListInitialization) {
John McCall31168b02011-06-15 23:02:42 +0000996 // Determine whether we have the semantics of a C-style cast.
997 bool CStyle
998 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
999
Sebastian Redl9f831db2009-07-25 15:41:38 +00001000 // The order the tests is not entirely arbitrary. There is one conversion
1001 // that can be handled in two different ways. Given:
1002 // struct A {};
1003 // struct B : public A {
1004 // B(); B(const A&);
1005 // };
1006 // const A &a = B();
1007 // the cast static_cast<const B&>(a) could be seen as either a static
1008 // reference downcast, or an explicit invocation of the user-defined
1009 // conversion using B's conversion constructor.
1010 // DR 427 specifies that the downcast is to be applied here.
1011
1012 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1013 // Done outside this function.
1014
1015 TryCastResult tcr;
1016
1017 // C++ 5.2.9p5, reference downcast.
1018 // See the function for details.
1019 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redld74dd492012-02-12 18:41:05 +00001020 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
1021 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001022 if (tcr != TC_NotApplicable)
1023 return tcr;
1024
Davide Italianoa2275912015-07-12 22:10:56 +00001025 // C++11 [expr.static.cast]p3:
Douglas Gregor465184a2011-01-22 00:06:57 +00001026 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
1027 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Eric Fiseliere4e9e282016-11-03 02:13:17 +00001028 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
Sebastian Redld74dd492012-02-12 18:41:05 +00001029 BasePath, msg);
Douglas Gregorba278e22011-01-25 16:13:26 +00001030 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +00001031 return tcr;
1032
1033 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
1034 // [...] if the declaration "T t(e);" is well-formed, [...].
John McCall31168b02011-06-15 23:02:42 +00001035 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
Sebastian Redld74dd492012-02-12 18:41:05 +00001036 Kind, ListInitialization);
John Wiegley01296292011-04-08 18:41:53 +00001037 if (SrcExpr.isInvalid())
1038 return TC_Failed;
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001039 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +00001040 return tcr;
Anders Carlssone9766d52009-09-09 21:33:21 +00001041
Sebastian Redl9f831db2009-07-25 15:41:38 +00001042 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
1043 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
1044 // conversions, subject to further restrictions.
1045 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
1046 // of qualification conversions impossible.
1047 // In the CStyle case, the earlier attempt to const_cast should have taken
1048 // care of reverse qualification conversions.
1049
John Wiegley01296292011-04-08 18:41:53 +00001050 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
Sebastian Redl9f831db2009-07-25 15:41:38 +00001051
Douglas Gregor0bf31402010-10-08 23:50:27 +00001052 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
Douglas Gregorb327eac2011-02-18 03:01:41 +00001053 // converted to an integral type. [...] A value of a scoped enumeration type
1054 // can also be explicitly converted to a floating-point type [...].
1055 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
1056 if (Enum->getDecl()->isScoped()) {
1057 if (DestType->isBooleanType()) {
1058 Kind = CK_IntegralToBoolean;
1059 return TC_Success;
1060 } else if (DestType->isIntegralType(Self.Context)) {
1061 Kind = CK_IntegralCast;
1062 return TC_Success;
1063 } else if (DestType->isRealFloatingType()) {
1064 Kind = CK_IntegralToFloating;
1065 return TC_Success;
1066 }
Douglas Gregor0bf31402010-10-08 23:50:27 +00001067 }
1068 }
Douglas Gregorb327eac2011-02-18 03:01:41 +00001069
Sebastian Redl9f831db2009-07-25 15:41:38 +00001070 // Reverse integral promotion/conversion. All such conversions are themselves
1071 // again integral promotions or conversions and are thus already handled by
1072 // p2 (TryDirectInitialization above).
1073 // (Note: any data loss warnings should be suppressed.)
1074 // The exception is the reverse of enum->integer, i.e. integer->enum (and
1075 // enum->enum). See also C++ 5.2.9p7.
1076 // The same goes for reverse floating point promotion/conversion and
1077 // floating-integral conversions. Again, only floating->enum is relevant.
1078 if (DestType->isEnumeralType()) {
Eli Friedman29538892011-09-02 17:38:59 +00001079 if (SrcType->isIntegralOrEnumerationType()) {
John McCalle3027922010-08-25 11:45:40 +00001080 Kind = CK_IntegralCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001081 return TC_Success;
Eli Friedman29538892011-09-02 17:38:59 +00001082 } else if (SrcType->isRealFloatingType()) {
1083 Kind = CK_FloatingToIntegral;
1084 return TC_Success;
Eli Friedman03bf60a2009-11-16 05:44:20 +00001085 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001086 }
1087
1088 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
1089 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson9a1cd872009-11-12 16:53:16 +00001090 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001091 Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001092 if (tcr != TC_NotApplicable)
1093 return tcr;
1094
1095 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
1096 // conversion. C++ 5.2.9p9 has additional information.
1097 // DR54's access restrictions apply here also.
Douglas Gregorc934bc82010-03-07 23:24:59 +00001098 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001099 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001100 if (tcr != TC_NotApplicable)
1101 return tcr;
1102
1103 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
1104 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
1105 // just the usual constness stuff.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001106 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001107 QualType SrcPointee = SrcPointer->getPointeeType();
1108 if (SrcPointee->isVoidType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001109 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001110 QualType DestPointee = DestPointer->getPointeeType();
1111 if (DestPointee->isIncompleteOrObjectType()) {
1112 // This is definitely the intended conversion, but it might fail due
John McCall31168b02011-06-15 23:02:42 +00001113 // to a qualifier violation. Note that we permit Objective-C lifetime
1114 // and GC qualifier mismatches here.
1115 if (!CStyle) {
1116 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
1117 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
1118 DestPointeeQuals.removeObjCGCAttr();
1119 DestPointeeQuals.removeObjCLifetime();
1120 SrcPointeeQuals.removeObjCGCAttr();
1121 SrcPointeeQuals.removeObjCLifetime();
1122 if (DestPointeeQuals != SrcPointeeQuals &&
1123 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
1124 msg = diag::err_bad_cxx_cast_qualifiers_away;
1125 return TC_Failed;
1126 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001127 }
John McCalle3027922010-08-25 11:45:40 +00001128 Kind = CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001129 return TC_Success;
1130 }
David Majnemer85bd1202015-06-02 22:15:12 +00001131
1132 // Microsoft permits static_cast from 'pointer-to-void' to
1133 // 'pointer-to-function'.
David Majnemer78324f22015-06-09 02:41:08 +00001134 if (!CStyle && Self.getLangOpts().MSVCCompat &&
1135 DestPointee->isFunctionType()) {
David Majnemer85bd1202015-06-02 22:15:12 +00001136 Self.Diag(OpRange.getBegin(), diag::ext_ms_cast_fn_obj) << OpRange;
1137 Kind = CK_BitCast;
1138 return TC_Success;
1139 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001140 }
Fariborz Jahanianeee16692010-05-10 23:46:53 +00001141 else if (DestType->isObjCObjectPointerType()) {
1142 // allow both c-style cast and static_cast of objective-c pointers as
1143 // they are pervasive.
John McCall9320b872011-09-09 05:25:32 +00001144 Kind = CK_CPointerToObjCPointerCast;
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001145 return TC_Success;
1146 }
Fariborz Jahanianffe912c2009-12-11 22:40:48 +00001147 else if (CStyle && DestType->isBlockPointerType()) {
1148 // allow c-style cast of void * to block pointers.
John McCalle3027922010-08-25 11:45:40 +00001149 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanianffe912c2009-12-11 22:40:48 +00001150 return TC_Success;
1151 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001152 }
1153 }
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001154 // Allow arbitrary objective-c pointer conversion with static casts.
Fariborz Jahanianb0901b72010-05-12 18:16:59 +00001155 if (SrcType->isObjCObjectPointerType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001156 DestType->isObjCObjectPointerType()) {
1157 Kind = CK_BitCast;
Fariborz Jahanianb0901b72010-05-12 18:16:59 +00001158 return TC_Success;
John McCall8cb679e2010-11-15 09:13:47 +00001159 }
Fariborz Jahanianc70a5432014-05-10 17:40:11 +00001160 // Allow ns-pointer to cf-pointer conversion in either direction
1161 // with static casts.
1162 if (!CStyle &&
1163 Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind))
1164 return TC_Success;
Nathan Sidwellffa7dc32015-01-28 21:31:26 +00001165
1166 // See if it looks like the user is trying to convert between
1167 // related record types, and select a better diagnostic if so.
1168 if (auto SrcPointer = SrcType->getAs<PointerType>())
1169 if (auto DestPointer = DestType->getAs<PointerType>())
1170 if (SrcPointer->getPointeeType()->getAs<RecordType>() &&
1171 DestPointer->getPointeeType()->getAs<RecordType>())
1172 msg = diag::err_bad_cxx_cast_unrelated_class;
Fariborz Jahanianb0901b72010-05-12 18:16:59 +00001173
Sebastian Redl9f831db2009-07-25 15:41:38 +00001174 // We tried everything. Everything! Nothing works! :-(
1175 return TC_NotApplicable;
1176}
1177
1178/// Tests whether a conversion according to N2844 is valid.
Eric Fiseliere4e9e282016-11-03 02:13:17 +00001179TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
1180 QualType DestType, bool CStyle,
1181 CastKind &Kind, CXXCastPath &BasePath,
1182 unsigned &msg) {
Davide Italianoa2275912015-07-12 22:10:56 +00001183 // C++11 [expr.static.cast]p3:
Eric Fiseliere4e9e282016-11-03 02:13:17 +00001184 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
Douglas Gregor465184a2011-01-22 00:06:57 +00001185 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001186 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001187 if (!R)
1188 return TC_NotApplicable;
1189
Douglas Gregor465184a2011-01-22 00:06:57 +00001190 if (!SrcExpr->isGLValue())
Sebastian Redl9f831db2009-07-25 15:41:38 +00001191 return TC_NotApplicable;
1192
1193 // Because we try the reference downcast before this function, from now on
1194 // this is the only cast possibility, so we issue an error if we fail now.
1195 // FIXME: Should allow casting away constness if CStyle.
1196 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00001197 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00001198 bool ObjCLifetimeConversion;
Douglas Gregorce950842011-01-26 21:04:06 +00001199 QualType FromType = SrcExpr->getType();
1200 QualType ToType = R->getPointeeType();
1201 if (CStyle) {
1202 FromType = FromType.getUnqualifiedType();
1203 ToType = ToType.getUnqualifiedType();
1204 }
Eric Fiseliere4e9e282016-11-03 02:13:17 +00001205
1206 Sema::ReferenceCompareResult RefResult = Self.CompareReferenceRelationship(
1207 SrcExpr->getLocStart(), ToType, FromType, DerivedToBase, ObjCConversion,
1208 ObjCLifetimeConversion);
1209 if (RefResult != Sema::Ref_Compatible) {
1210 if (CStyle || RefResult == Sema::Ref_Incompatible)
Davide Italianoa2275912015-07-12 22:10:56 +00001211 return TC_NotApplicable;
Eric Fiseliere4e9e282016-11-03 02:13:17 +00001212 // Diagnose types which are reference-related but not compatible here since
1213 // we can provide better diagnostics. In these cases forwarding to
1214 // [expr.static.cast]p4 should never result in a well-formed cast.
1215 msg = SrcExpr->isLValue() ? diag::err_bad_lvalue_to_rvalue_cast
1216 : diag::err_bad_rvalue_to_rvalue_cast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001217 return TC_Failed;
1218 }
1219
Douglas Gregorba278e22011-01-25 16:13:26 +00001220 if (DerivedToBase) {
1221 Kind = CK_DerivedToBase;
1222 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1223 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001224 if (!Self.IsDerivedFrom(SrcExpr->getLocStart(), SrcExpr->getType(),
1225 R->getPointeeType(), Paths))
Douglas Gregorba278e22011-01-25 16:13:26 +00001226 return TC_NotApplicable;
1227
1228 Self.BuildBasePathArray(Paths, BasePath);
1229 } else
1230 Kind = CK_NoOp;
1231
Sebastian Redl9f831db2009-07-25 15:41:38 +00001232 return TC_Success;
1233}
1234
1235/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1236TryCastResult
1237TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
Craig Toppere335f252015-10-04 04:53:55 +00001238 bool CStyle, SourceRange OpRange,
John McCalle3027922010-08-25 11:45:40 +00001239 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001240 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001241 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1242 // cast to type "reference to cv2 D", where D is a class derived from B,
1243 // if a valid standard conversion from "pointer to D" to "pointer to B"
1244 // exists, cv2 >= cv1, and B is not a virtual base class of D.
1245 // In addition, DR54 clarifies that the base must be accessible in the
1246 // current context. Although the wording of DR54 only applies to the pointer
1247 // variant of this rule, the intent is clearly for it to apply to the this
1248 // conversion as well.
1249
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001250 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001251 if (!DestReference) {
1252 return TC_NotApplicable;
1253 }
1254 bool RValueRef = DestReference->isRValueReferenceType();
John McCall086a4642010-11-24 05:12:34 +00001255 if (!RValueRef && !SrcExpr->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001256 // We know the left side is an lvalue reference, so we can suggest a reason.
1257 msg = diag::err_bad_cxx_cast_rvalue;
1258 return TC_NotApplicable;
1259 }
1260
1261 QualType DestPointee = DestReference->getPointeeType();
1262
Richard Smith11330852014-07-08 17:25:14 +00001263 // FIXME: If the source is a prvalue, we should issue a warning (because the
1264 // cast always has undefined behavior), and for AST consistency, we should
1265 // materialize a temporary.
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001266 return TryStaticDowncast(Self,
1267 Self.Context.getCanonicalType(SrcExpr->getType()),
1268 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001269 OpRange, SrcExpr->getType(), DestType, msg, Kind,
1270 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001271}
1272
1273/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1274TryCastResult
1275TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Craig Toppere335f252015-10-04 04:53:55 +00001276 bool CStyle, SourceRange OpRange,
John McCalle3027922010-08-25 11:45:40 +00001277 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001278 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001279 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1280 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1281 // is a class derived from B, if a valid standard conversion from "pointer
1282 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1283 // class of D.
1284 // In addition, DR54 clarifies that the base must be accessible in the
1285 // current context.
1286
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001287 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001288 if (!DestPointer) {
1289 return TC_NotApplicable;
1290 }
1291
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001292 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001293 if (!SrcPointer) {
1294 msg = diag::err_bad_static_cast_pointer_nonpointer;
1295 return TC_NotApplicable;
1296 }
1297
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001298 return TryStaticDowncast(Self,
1299 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1300 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001301 CStyle, OpRange, SrcType, DestType, msg, Kind,
1302 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001303}
1304
1305/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1306/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001307/// DestType is possible and allowed.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001308TryCastResult
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001309TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Craig Toppere335f252015-10-04 04:53:55 +00001310 bool CStyle, SourceRange OpRange, QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +00001311 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001312 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl802f14c2009-10-22 15:07:22 +00001313 // We can only work with complete types. But don't complain if it doesn't work
Richard Smithdb0ac552015-12-18 22:40:25 +00001314 if (!Self.isCompleteType(OpRange.getBegin(), SrcType) ||
1315 !Self.isCompleteType(OpRange.getBegin(), DestType))
Sebastian Redl802f14c2009-10-22 15:07:22 +00001316 return TC_NotApplicable;
1317
Sebastian Redl9f831db2009-07-25 15:41:38 +00001318 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001319 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001320 return TC_NotApplicable;
1321 }
1322
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001323 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001324 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001325 if (!Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001326 return TC_NotApplicable;
1327 }
1328
1329 // Target type does derive from source type. Now we're serious. If an error
1330 // appears now, it's not ignored.
1331 // This may not be entirely in line with the standard. Take for example:
1332 // struct A {};
1333 // struct B : virtual A {
1334 // B(A&);
1335 // };
Mike Stump11289f42009-09-09 15:08:12 +00001336 //
Sebastian Redl9f831db2009-07-25 15:41:38 +00001337 // void f()
1338 // {
1339 // (void)static_cast<const B&>(*((A*)0));
1340 // }
1341 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1342 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1343 // However, both GCC and Comeau reject this example, and accepting it would
1344 // mean more complex code if we're to preserve the nice error message.
1345 // FIXME: Being 100% compliant here would be nice to have.
1346
1347 // Must preserve cv, as always, unless we're in C-style mode.
1348 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001349 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001350 return TC_Failed;
1351 }
1352
1353 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1354 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1355 // that it builds the paths in reverse order.
1356 // To sum up: record all paths to the base and build a nice string from
1357 // them. Use it to spice up the error message.
1358 if (!Paths.isRecordingPaths()) {
1359 Paths.clear();
1360 Paths.setRecordingPaths(true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001361 Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001362 }
1363 std::string PathDisplayStr;
1364 std::set<unsigned> DisplayedPaths;
David Majnemerf7e36092016-06-23 00:15:04 +00001365 for (clang::CXXBasePath &Path : Paths) {
1366 if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001367 // We haven't displayed a path to this particular base
1368 // class subobject yet.
1369 PathDisplayStr += "\n ";
David Majnemerf7e36092016-06-23 00:15:04 +00001370 for (CXXBasePathElement &PE : llvm::reverse(Path))
1371 PathDisplayStr += PE.Base->getType().getAsString() + " -> ";
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001372 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001373 }
1374 }
1375
1376 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregor8f3952c2009-11-15 09:20:52 +00001377 << QualType(SrcType).getUnqualifiedType()
1378 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9f831db2009-07-25 15:41:38 +00001379 << PathDisplayStr << OpRange;
1380 msg = 0;
1381 return TC_Failed;
1382 }
1383
Craig Topperc3ec1492014-05-26 06:22:03 +00001384 if (Paths.getDetectedVirtual() != nullptr) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001385 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1386 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1387 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1388 msg = 0;
1389 return TC_Failed;
1390 }
1391
John McCallfe9cf0a2011-02-14 23:21:33 +00001392 if (!CStyle) {
Dmitry Polukhin5b4faee2016-04-28 09:56:22 +00001393 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1394 SrcType, DestType,
1395 Paths.front(),
1396 diag::err_downcast_from_inaccessible_base)) {
John McCallfe9cf0a2011-02-14 23:21:33 +00001397 case Sema::AR_accessible:
1398 case Sema::AR_delayed: // be optimistic
1399 case Sema::AR_dependent: // be optimistic
1400 break;
1401
1402 case Sema::AR_inaccessible:
1403 msg = 0;
1404 return TC_Failed;
1405 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001406 }
1407
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001408 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001409 Kind = CK_BaseToDerived;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001410 return TC_Success;
1411}
1412
1413/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1414/// C++ 5.2.9p9 is valid:
1415///
1416/// An rvalue of type "pointer to member of D of type cv1 T" can be
1417/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1418/// where B is a base class of D [...].
1419///
1420TryCastResult
John Wiegley01296292011-04-08 18:41:53 +00001421TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
Douglas Gregorc934bc82010-03-07 23:24:59 +00001422 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +00001423 SourceRange OpRange,
John McCalle3027922010-08-25 11:45:40 +00001424 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001425 CXXCastPath &BasePath) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001426 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001427 if (!DestMemPtr)
1428 return TC_NotApplicable;
Douglas Gregorc934bc82010-03-07 23:24:59 +00001429
1430 bool WasOverloadedFunction = false;
John McCall16df1e52010-03-30 21:47:33 +00001431 DeclAccessPair FoundOverload;
John Wiegley01296292011-04-08 18:41:53 +00001432 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00001433 if (FunctionDecl *Fn
John Wiegley01296292011-04-08 18:41:53 +00001434 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
Douglas Gregor064fdb22010-04-14 23:11:21 +00001435 FoundOverload)) {
1436 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1437 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1438 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1439 WasOverloadedFunction = true;
1440 }
Douglas Gregorc934bc82010-03-07 23:24:59 +00001441 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00001442
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001443 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001444 if (!SrcMemPtr) {
1445 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1446 return TC_NotApplicable;
1447 }
Richard Smithdb0ac552015-12-18 22:40:25 +00001448
1449 // Lock down the inheritance model right now in MS ABI, whether or not the
1450 // pointee types are the same.
David Majnemeraf382652016-03-22 16:44:39 +00001451 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00001452 (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
David Majnemeraf382652016-03-22 16:44:39 +00001453 (void)Self.isCompleteType(OpRange.getBegin(), DestType);
1454 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001455
1456 // T == T, modulo cv
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001457 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1458 DestMemPtr->getPointeeType()))
Sebastian Redl9f831db2009-07-25 15:41:38 +00001459 return TC_NotApplicable;
1460
1461 // B base of D
1462 QualType SrcClass(SrcMemPtr->getClass(), 0);
1463 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssonb78feca2010-04-24 19:22:20 +00001464 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001465 /*DetectVirtual=*/true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001466 if (!Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths))
Sebastian Redl9f831db2009-07-25 15:41:38 +00001467 return TC_NotApplicable;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001468
1469 // 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 +00001470 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001471 Paths.clear();
1472 Paths.setRecordingPaths(true);
Richard Smith0f59cb32015-12-18 21:45:41 +00001473 bool StillOkay =
1474 Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001475 assert(StillOkay);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001476 (void)StillOkay;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001477 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1478 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1479 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1480 msg = 0;
1481 return TC_Failed;
1482 }
1483
1484 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1485 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1486 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1487 msg = 0;
1488 return TC_Failed;
1489 }
1490
John McCallfe9cf0a2011-02-14 23:21:33 +00001491 if (!CStyle) {
1492 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1493 DestClass, SrcClass,
1494 Paths.front(),
1495 diag::err_upcast_to_inaccessible_base)) {
1496 case Sema::AR_accessible:
1497 case Sema::AR_delayed:
1498 case Sema::AR_dependent:
1499 // Optimistically assume that the delayed and dependent cases
1500 // will work out.
1501 break;
1502
1503 case Sema::AR_inaccessible:
1504 msg = 0;
1505 return TC_Failed;
1506 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001507 }
1508
Douglas Gregorc934bc82010-03-07 23:24:59 +00001509 if (WasOverloadedFunction) {
1510 // Resolve the address of the overloaded function again, this time
1511 // allowing complaints if something goes wrong.
John Wiegley01296292011-04-08 18:41:53 +00001512 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
Douglas Gregorc934bc82010-03-07 23:24:59 +00001513 DestType,
John McCall16df1e52010-03-30 21:47:33 +00001514 true,
1515 FoundOverload);
Douglas Gregorc934bc82010-03-07 23:24:59 +00001516 if (!Fn) {
1517 msg = 0;
1518 return TC_Failed;
1519 }
1520
John McCall16df1e52010-03-30 21:47:33 +00001521 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
John Wiegley01296292011-04-08 18:41:53 +00001522 if (!SrcExpr.isUsable()) {
Douglas Gregorc934bc82010-03-07 23:24:59 +00001523 msg = 0;
1524 return TC_Failed;
1525 }
1526 }
1527
Anders Carlssonb78feca2010-04-24 19:22:20 +00001528 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001529 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001530 return TC_Success;
1531}
1532
1533/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1534/// is valid:
1535///
1536/// An expression e can be explicitly converted to a type T using a
1537/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1538TryCastResult
John Wiegley01296292011-04-08 18:41:53 +00001539TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCall31168b02011-06-15 23:02:42 +00001540 Sema::CheckedConversionKind CCK,
Craig Toppere335f252015-10-04 04:53:55 +00001541 SourceRange OpRange, unsigned &msg,
Sebastian Redld74dd492012-02-12 18:41:05 +00001542 CastKind &Kind, bool ListInitialization) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +00001543 if (DestType->isRecordType()) {
1544 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
Aaron Ballmanea032142012-05-07 00:02:00 +00001545 diag::err_bad_dynamic_cast_incomplete) ||
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001546 Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
Aaron Ballmanea032142012-05-07 00:02:00 +00001547 diag::err_allocation_of_abstract_type)) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +00001548 msg = 0;
1549 return TC_Failed;
1550 }
1551 }
Sebastian Redl0501c632012-02-12 16:37:36 +00001552
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001553 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1554 InitializationKind InitKind
John McCall31168b02011-06-15 23:02:42 +00001555 = (CCK == Sema::CCK_CStyleCast)
Sebastian Redl0501c632012-02-12 16:37:36 +00001556 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +00001557 ListInitialization)
John McCall31168b02011-06-15 23:02:42 +00001558 : (CCK == Sema::CCK_FunctionalCast)
Sebastian Redld74dd492012-02-12 18:41:05 +00001559 ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
Richard Smith507840d2011-11-29 22:48:16 +00001560 : InitializationKind::CreateCast(OpRange);
John Wiegley01296292011-04-08 18:41:53 +00001561 Expr *SrcExprRaw = SrcExpr.get();
Richard Smithb8c0f552016-12-09 18:49:13 +00001562 // FIXME: Per DR242, we should check for an implicit conversion sequence
1563 // or for a constructor that could be invoked by direct-initialization
1564 // here, not for an initialization sequence.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001565 InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001566
1567 // At this point of CheckStaticCast, if the destination is a reference,
1568 // or the expression is an overload expression this has to work.
1569 // There is no other way that works.
1570 // On the other hand, if we're checking a C-style cast, we've still got
1571 // the reinterpret_cast way.
John McCall31168b02011-06-15 23:02:42 +00001572 bool CStyle
1573 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00001574 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001575 return TC_NotApplicable;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001576
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001577 ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001578 if (Result.isInvalid()) {
1579 msg = 0;
1580 return TC_Failed;
1581 }
1582
Douglas Gregorb33eed02010-04-16 22:09:46 +00001583 if (InitSeq.isConstructorInitialization())
John McCalle3027922010-08-25 11:45:40 +00001584 Kind = CK_ConstructorConversion;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001585 else
John McCalle3027922010-08-25 11:45:40 +00001586 Kind = CK_NoOp;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001587
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001588 SrcExpr = Result;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001589 return TC_Success;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001590}
1591
1592/// TryConstCast - See if a const_cast from source to destination is allowed,
1593/// and perform it if it is.
Richard Smith82c9b512013-06-14 22:27:52 +00001594static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
1595 QualType DestType, bool CStyle,
1596 unsigned &msg) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001597 DestType = Self.Context.getCanonicalType(DestType);
Richard Smith82c9b512013-06-14 22:27:52 +00001598 QualType SrcType = SrcExpr.get()->getType();
1599 bool NeedToMaterializeTemporary = false;
1600
Douglas Gregorc1ed20c2011-01-22 00:19:52 +00001601 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
Richard Smith82c9b512013-06-14 22:27:52 +00001602 // C++11 5.2.11p4:
1603 // if a pointer to T1 can be explicitly converted to the type "pointer to
1604 // T2" using a const_cast, then the following conversions can also be
1605 // made:
1606 // -- an lvalue of type T1 can be explicitly converted to an lvalue of
1607 // type T2 using the cast const_cast<T2&>;
1608 // -- a glvalue of type T1 can be explicitly converted to an xvalue of
1609 // type T2 using the cast const_cast<T2&&>; and
1610 // -- if T1 is a class type, a prvalue of type T1 can be explicitly
1611 // converted to an xvalue of type T2 using the cast const_cast<T2&&>.
1612
1613 if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001614 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1615 // is C-style, static_cast might find a way, so we simply suggest a
1616 // message and tell the parent to keep searching.
1617 msg = diag::err_bad_cxx_cast_rvalue;
1618 return TC_NotApplicable;
1619 }
1620
Richard Smith82c9b512013-06-14 22:27:52 +00001621 if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) {
1622 if (!SrcType->isRecordType()) {
1623 // Cannot const_cast non-class prvalue to rvalue reference type. But if
1624 // this is C-style, static_cast can do this.
1625 msg = diag::err_bad_cxx_cast_rvalue;
1626 return TC_NotApplicable;
1627 }
1628
1629 // Materialize the class prvalue so that the const_cast can bind a
1630 // reference to it.
1631 NeedToMaterializeTemporary = true;
1632 }
1633
John McCalld25db7e2013-05-06 21:39:12 +00001634 // It's not completely clear under the standard whether we can
1635 // const_cast bit-field gl-values. Doing so would not be
1636 // intrinsically complicated, but for now, we say no for
1637 // consistency with other compilers and await the word of the
1638 // committee.
Richard Smith82c9b512013-06-14 22:27:52 +00001639 if (SrcExpr.get()->refersToBitField()) {
John McCalld25db7e2013-05-06 21:39:12 +00001640 msg = diag::err_bad_cxx_cast_bitfield;
1641 return TC_NotApplicable;
1642 }
1643
Sebastian Redl9f831db2009-07-25 15:41:38 +00001644 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1645 SrcType = Self.Context.getPointerType(SrcType);
1646 }
1647
1648 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1649 // the rules for const_cast are the same as those used for pointers.
1650
John McCall0e704f72010-05-18 09:35:29 +00001651 if (!DestType->isPointerType() &&
1652 !DestType->isMemberPointerType() &&
1653 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001654 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1655 // was a reference type, we converted it to a pointer above.
1656 // The status of rvalue references isn't entirely clear, but it looks like
1657 // conversion to them is simply invalid.
1658 // C++ 5.2.11p3: For two pointer types [...]
1659 if (!CStyle)
1660 msg = diag::err_bad_const_cast_dest;
1661 return TC_NotApplicable;
1662 }
1663 if (DestType->isFunctionPointerType() ||
1664 DestType->isMemberFunctionPointerType()) {
1665 // Cannot cast direct function pointers.
1666 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1667 // T is the ultimate pointee of source and target type.
1668 if (!CStyle)
1669 msg = diag::err_bad_const_cast_dest;
1670 return TC_NotApplicable;
1671 }
1672 SrcType = Self.Context.getCanonicalType(SrcType);
1673
1674 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1675 // completely equal.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001676 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1677 // in multi-level pointers may change, but the level count must be the same,
1678 // as must be the final pointee type.
1679 while (SrcType != DestType &&
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001680 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00001681 Qualifiers SrcQuals, DestQuals;
1682 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
1683 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
1684
1685 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
1686 // the other qualifiers (e.g., address spaces) are identical.
1687 SrcQuals.removeCVRQualifiers();
1688 DestQuals.removeCVRQualifiers();
1689 if (SrcQuals != DestQuals)
1690 return TC_NotApplicable;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001691 }
1692
1693 // Since we're dealing in canonical types, the remainder must be the same.
1694 if (SrcType != DestType)
1695 return TC_NotApplicable;
1696
Richard Smith82c9b512013-06-14 22:27:52 +00001697 if (NeedToMaterializeTemporary)
1698 // This is a const_cast from a class prvalue to an rvalue reference type.
1699 // Materialize a temporary to store the result of the conversion.
Richard Smithb8c0f552016-12-09 18:49:13 +00001700 SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcExpr.get()->getType(),
1701 SrcExpr.get(),
Tim Shen4a05bb82016-06-21 20:29:17 +00001702 /*IsLValueReference*/ false);
Richard Smith82c9b512013-06-14 22:27:52 +00001703
Sebastian Redl9f831db2009-07-25 15:41:38 +00001704 return TC_Success;
1705}
1706
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001707// Checks for undefined behavior in reinterpret_cast.
1708// The cases that is checked for is:
1709// *reinterpret_cast<T*>(&a)
1710// reinterpret_cast<T&>(a)
1711// where accessing 'a' as type 'T' will result in undefined behavior.
1712void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1713 bool IsDereference,
1714 SourceRange Range) {
1715 unsigned DiagID = IsDereference ?
1716 diag::warn_pointer_indirection_from_incompatible_type :
1717 diag::warn_undefined_reinterpret_cast;
1718
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001719 if (Diags.isIgnored(DiagID, Range.getBegin()))
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001720 return;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001721
1722 QualType SrcTy, DestTy;
1723 if (IsDereference) {
1724 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1725 return;
1726 }
1727 SrcTy = SrcType->getPointeeType();
1728 DestTy = DestType->getPointeeType();
1729 } else {
1730 if (!DestType->getAs<ReferenceType>()) {
1731 return;
1732 }
1733 SrcTy = SrcType;
1734 DestTy = DestType->getPointeeType();
1735 }
1736
1737 // Cast is compatible if the types are the same.
1738 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1739 return;
1740 }
1741 // or one of the types is a char or void type
1742 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1743 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1744 return;
1745 }
1746 // or one of the types is a tag type.
Chandler Carruth0dc3f8d2011-05-24 07:43:19 +00001747 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001748 return;
1749 }
1750
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001751 // FIXME: Scoped enums?
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001752 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1753 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1754 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1755 return;
1756 }
1757 }
1758
1759 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1760}
Douglas Gregor1beec452011-03-12 01:48:56 +00001761
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00001762static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
1763 QualType DestType) {
1764 QualType SrcType = SrcExpr.get()->getType();
Fariborz Jahanianb4873882012-12-13 00:42:06 +00001765 if (Self.Context.hasSameType(SrcType, DestType))
1766 return;
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00001767 if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
1768 if (SrcPtrTy->isObjCSelType()) {
1769 QualType DT = DestType;
1770 if (isa<PointerType>(DestType))
1771 DT = DestType->getPointeeType();
1772 if (!DT.getUnqualifiedType()->isVoidType())
1773 Self.Diag(SrcExpr.get()->getExprLoc(),
1774 diag::warn_cast_pointer_from_sel)
1775 << SrcType << DestType << SrcExpr.get()->getSourceRange();
1776 }
1777}
1778
Reid Kleckner9f497332016-05-10 21:00:03 +00001779/// Diagnose casts that change the calling convention of a pointer to a function
1780/// defined in the current TU.
1781static void DiagnoseCallingConvCast(Sema &Self, const ExprResult &SrcExpr,
1782 QualType DstType, SourceRange OpRange) {
1783 // Check if this cast would change the calling convention of a function
1784 // pointer type.
1785 QualType SrcType = SrcExpr.get()->getType();
1786 if (Self.Context.hasSameType(SrcType, DstType) ||
1787 !SrcType->isFunctionPointerType() || !DstType->isFunctionPointerType())
1788 return;
1789 const auto *SrcFTy =
1790 SrcType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
1791 const auto *DstFTy =
1792 DstType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
1793 CallingConv SrcCC = SrcFTy->getCallConv();
1794 CallingConv DstCC = DstFTy->getCallConv();
1795 if (SrcCC == DstCC)
1796 return;
1797
1798 // We have a calling convention cast. Check if the source is a pointer to a
1799 // known, specific function that has already been defined.
1800 Expr *Src = SrcExpr.get()->IgnoreParenImpCasts();
1801 if (auto *UO = dyn_cast<UnaryOperator>(Src))
1802 if (UO->getOpcode() == UO_AddrOf)
1803 Src = UO->getSubExpr()->IgnoreParenImpCasts();
1804 auto *DRE = dyn_cast<DeclRefExpr>(Src);
1805 if (!DRE)
1806 return;
1807 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
Reid Kleckner0b009e82017-01-31 19:37:45 +00001808 if (!FD)
Reid Kleckner9f497332016-05-10 21:00:03 +00001809 return;
1810
Reid Kleckner43be52a2016-05-11 17:43:13 +00001811 // Only warn if we are casting from the default convention to a non-default
1812 // convention. This can happen when the programmer forgot to apply the calling
Reid Kleckner0b009e82017-01-31 19:37:45 +00001813 // convention to the function declaration and then inserted this cast to
Reid Kleckner43be52a2016-05-11 17:43:13 +00001814 // satisfy the type system.
1815 CallingConv DefaultCC = Self.getASTContext().getDefaultCallingConvention(
1816 FD->isVariadic(), FD->isCXXInstanceMember());
1817 if (DstCC == DefaultCC || SrcCC != DefaultCC)
1818 return;
1819
Reid Kleckner9f497332016-05-10 21:00:03 +00001820 // Diagnose this cast, as it is probably bad.
1821 StringRef SrcCCName = FunctionType::getNameForCallConv(SrcCC);
1822 StringRef DstCCName = FunctionType::getNameForCallConv(DstCC);
1823 Self.Diag(OpRange.getBegin(), diag::warn_cast_calling_conv)
1824 << SrcCCName << DstCCName << OpRange;
1825
1826 // The checks above are cheaper than checking if the diagnostic is enabled.
1827 // However, it's worth checking if the warning is enabled before we construct
1828 // a fixit.
1829 if (Self.Diags.isIgnored(diag::warn_cast_calling_conv, OpRange.getBegin()))
1830 return;
1831
1832 // Try to suggest a fixit to change the calling convention of the function
1833 // whose address was taken. Try to use the latest macro for the convention.
1834 // For example, users probably want to write "WINAPI" instead of "__stdcall"
1835 // to match the Windows header declarations.
Reid Kleckner0b009e82017-01-31 19:37:45 +00001836 SourceLocation NameLoc = FD->getFirstDecl()->getNameInfo().getLoc();
Reid Kleckner9f497332016-05-10 21:00:03 +00001837 Preprocessor &PP = Self.getPreprocessor();
1838 SmallVector<TokenValue, 6> AttrTokens;
1839 SmallString<64> CCAttrText;
1840 llvm::raw_svector_ostream OS(CCAttrText);
1841 if (Self.getLangOpts().MicrosoftExt) {
1842 // __stdcall or __vectorcall
1843 OS << "__" << DstCCName;
1844 IdentifierInfo *II = PP.getIdentifierInfo(OS.str());
1845 AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
1846 ? TokenValue(II->getTokenID())
1847 : TokenValue(II));
1848 } else {
1849 // __attribute__((stdcall)) or __attribute__((vectorcall))
1850 OS << "__attribute__((" << DstCCName << "))";
1851 AttrTokens.push_back(tok::kw___attribute);
1852 AttrTokens.push_back(tok::l_paren);
1853 AttrTokens.push_back(tok::l_paren);
1854 IdentifierInfo *II = PP.getIdentifierInfo(DstCCName);
1855 AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
1856 ? TokenValue(II->getTokenID())
1857 : TokenValue(II));
1858 AttrTokens.push_back(tok::r_paren);
1859 AttrTokens.push_back(tok::r_paren);
1860 }
1861 StringRef AttrSpelling = PP.getLastMacroWithSpelling(NameLoc, AttrTokens);
1862 if (!AttrSpelling.empty())
1863 CCAttrText = AttrSpelling;
1864 OS << ' ';
1865 Self.Diag(NameLoc, diag::note_change_calling_conv_fixit)
1866 << FD << DstCCName << FixItHint::CreateInsertion(NameLoc, CCAttrText);
1867}
1868
David Blaikie282ad872012-10-16 18:53:14 +00001869static void checkIntToPointerCast(bool CStyle, SourceLocation Loc,
1870 const Expr *SrcExpr, QualType DestType,
1871 Sema &Self) {
1872 QualType SrcType = SrcExpr->getType();
1873
1874 // Not warning on reinterpret_cast, boolean, constant expressions, etc
1875 // are not explicit design choices, but consistent with GCC's behavior.
1876 // Feel free to modify them if you've reason/evidence for an alternative.
1877 if (CStyle && SrcType->isIntegralType(Self.Context)
1878 && !SrcType->isBooleanType()
1879 && !SrcType->isEnumeralType()
1880 && !SrcExpr->isIntegerConstantExpr(Self.Context)
Ted Kremeneke3dc7f72013-05-29 21:50:46 +00001881 && Self.Context.getTypeSize(DestType) >
1882 Self.Context.getTypeSize(SrcType)) {
1883 // Separate between casts to void* and non-void* pointers.
1884 // Some APIs use (abuse) void* for something like a user context,
1885 // and often that value is an integer even if it isn't a pointer itself.
1886 // Having a separate warning flag allows users to control the warning
1887 // for their workflow.
1888 unsigned Diag = DestType->isVoidPointerType() ?
1889 diag::warn_int_to_void_pointer_cast
1890 : diag::warn_int_to_pointer_cast;
1891 Self.Diag(Loc, Diag) << SrcType << DestType;
1892 }
David Blaikie282ad872012-10-16 18:53:14 +00001893}
1894
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001895static bool fixOverloadedReinterpretCastExpr(Sema &Self, QualType DestType,
1896 ExprResult &Result) {
1897 // We can only fix an overloaded reinterpret_cast if
1898 // - it is a template with explicit arguments that resolves to an lvalue
1899 // unambiguously, or
1900 // - it is the only function in an overload set that may have its address
1901 // taken.
1902
1903 Expr *E = Result.get();
1904 // TODO: what if this fails because of DiagnoseUseOfDecl or something
1905 // like it?
1906 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1907 Result,
1908 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
1909 ) &&
1910 Result.isUsable())
1911 return true;
1912
George Burgess IVbeca4a32016-06-08 00:34:22 +00001913 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
1914 // preserves Result.
1915 Result = E;
George Burgess IV1dbfa852017-05-09 04:06:24 +00001916 if (!Self.resolveAndFixAddressOfOnlyViableOverloadCandidate(
1917 Result, /*DoFunctionPointerConversion=*/true))
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001918 return false;
George Burgess IVbeca4a32016-06-08 00:34:22 +00001919 return Result.isUsable();
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001920}
1921
John Wiegley01296292011-04-08 18:41:53 +00001922static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001923 QualType DestType, bool CStyle,
Craig Toppere335f252015-10-04 04:53:55 +00001924 SourceRange OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001925 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001926 CastKind &Kind) {
Douglas Gregor51954272010-07-13 23:17:26 +00001927 bool IsLValueCast = false;
1928
Sebastian Redl9f831db2009-07-25 15:41:38 +00001929 DestType = Self.Context.getCanonicalType(DestType);
John Wiegley01296292011-04-08 18:41:53 +00001930 QualType SrcType = SrcExpr.get()->getType();
Douglas Gregore81f58e2010-11-08 03:40:48 +00001931
1932 // Is the source an overloaded name? (i.e. &foo)
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001933 // If so, reinterpret_cast generally can not help us here (13.4, p1, bullet 5)
Douglas Gregorb491ed32011-02-19 21:32:49 +00001934 if (SrcType == Self.Context.OverloadTy) {
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001935 ExprResult FixedExpr = SrcExpr;
1936 if (!fixOverloadedReinterpretCastExpr(Self, DestType, FixedExpr))
Douglas Gregorb491ed32011-02-19 21:32:49 +00001937 return TC_NotApplicable;
George Burgess IV3cde9bf2016-03-19 21:36:10 +00001938
1939 assert(FixedExpr.isUsable() && "Invalid result fixing overloaded expr");
1940 SrcExpr = FixedExpr;
1941 SrcType = SrcExpr.get()->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001942 }
Douglas Gregore81f58e2010-11-08 03:40:48 +00001943
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001944 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Richard Smithdb05f1f2012-04-29 08:24:44 +00001945 if (!SrcExpr.get()->isGLValue()) {
1946 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
1947 // similar comment in const_cast.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001948 msg = diag::err_bad_cxx_cast_rvalue;
1949 return TC_NotApplicable;
1950 }
1951
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00001952 if (!CStyle) {
1953 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
1954 /*isDereference=*/false, OpRange);
1955 }
1956
Sebastian Redl9f831db2009-07-25 15:41:38 +00001957 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1958 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1959 // built-in & and * operators.
Argyrios Kyrtzidis47a12852011-04-22 22:31:13 +00001960
Craig Topperc3ec1492014-05-26 06:22:03 +00001961 const char *inappropriate = nullptr;
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00001962 switch (SrcExpr.get()->getObjectKind()) {
Argyrios Kyrtzidis3d2185b2011-04-23 01:10:24 +00001963 case OK_Ordinary:
1964 break;
Richard Smithb8c0f552016-12-09 18:49:13 +00001965 case OK_BitField:
1966 msg = diag::err_bad_cxx_cast_bitfield;
1967 return TC_NotApplicable;
1968 // FIXME: Use a specific diagnostic for the rest of these cases.
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00001969 case OK_VectorComponent: inappropriate = "vector element"; break;
1970 case OK_ObjCProperty: inappropriate = "property expression"; break;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001971 case OK_ObjCSubscript: inappropriate = "container subscripting expression";
1972 break;
Argyrios Kyrtzidisbf042312011-04-22 23:57:57 +00001973 }
1974 if (inappropriate) {
1975 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
1976 << inappropriate << DestType
1977 << OpRange << SrcExpr.get()->getSourceRange();
1978 msg = 0; SrcExpr = ExprError();
Argyrios Kyrtzidis47a12852011-04-22 22:31:13 +00001979 return TC_NotApplicable;
1980 }
1981
Sebastian Redl9f831db2009-07-25 15:41:38 +00001982 // This code does this transformation for the checked types.
1983 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1984 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001985
Douglas Gregor51954272010-07-13 23:17:26 +00001986 IsLValueCast = true;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001987 }
1988
1989 // Canonicalize source for comparison.
1990 SrcType = Self.Context.getCanonicalType(SrcType);
1991
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001992 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1993 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001994 if (DestMemPtr && SrcMemPtr) {
1995 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1996 // can be explicitly converted to an rvalue of type "pointer to member
1997 // of Y of type T2" if T1 and T2 are both function types or both object
1998 // types.
David Majnemer5fd33e02015-04-24 01:25:08 +00001999 if (DestMemPtr->isMemberFunctionPointer() !=
2000 SrcMemPtr->isMemberFunctionPointer())
Sebastian Redl9f831db2009-07-25 15:41:38 +00002001 return TC_NotApplicable;
2002
2003 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
2004 // constness.
2005 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
2006 // we accept it.
John McCall31168b02011-06-15 23:02:42 +00002007 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
2008 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00002009 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002010 return TC_Failed;
2011 }
2012
David Majnemer1cdd96d2014-01-17 09:01:00 +00002013 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2014 // We need to determine the inheritance model that the class will use if
2015 // haven't yet.
Richard Smithdb0ac552015-12-18 22:40:25 +00002016 (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
2017 (void)Self.isCompleteType(OpRange.getBegin(), DestType);
David Majnemer1cdd96d2014-01-17 09:01:00 +00002018 }
2019
Charles Davisebab1ed2010-08-16 05:30:44 +00002020 // Don't allow casting between member pointers of different sizes.
2021 if (Self.Context.getTypeSize(DestMemPtr) !=
2022 Self.Context.getTypeSize(SrcMemPtr)) {
2023 msg = diag::err_bad_cxx_cast_member_pointer_size;
2024 return TC_Failed;
2025 }
2026
Sebastian Redl9f831db2009-07-25 15:41:38 +00002027 // A valid member pointer cast.
John McCallc62bb392012-02-15 01:22:51 +00002028 assert(!IsLValueCast);
2029 Kind = CK_ReinterpretMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002030 return TC_Success;
2031 }
2032
2033 // See below for the enumeral issue.
Douglas Gregor6972a622010-06-16 00:35:25 +00002034 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00002035 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
2036 // type large enough to hold it. A value of std::nullptr_t can be
2037 // converted to an integral type; the conversion has the same meaning
2038 // and validity as a conversion of (void*)0 to the integral type.
2039 if (Self.Context.getTypeSize(SrcType) >
2040 Self.Context.getTypeSize(DestType)) {
2041 msg = diag::err_bad_reinterpret_cast_small_int;
2042 return TC_Failed;
2043 }
John McCalle3027922010-08-25 11:45:40 +00002044 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002045 return TC_Success;
2046 }
2047
John McCall1c78f082015-07-23 23:54:07 +00002048 // Allow reinterpret_casts between vectors of the same size and
2049 // between vectors and integers of the same size.
Anders Carlsson570af5d2009-09-16 19:19:43 +00002050 bool destIsVector = DestType->isVectorType();
2051 bool srcIsVector = SrcType->isVectorType();
2052 if (srcIsVector || destIsVector) {
John McCall1c78f082015-07-23 23:54:07 +00002053 // The non-vector type, if any, must have integral type. This is
2054 // the same rule that C vector casts use; note, however, that enum
2055 // types are not integral in C++.
2056 if ((!destIsVector && !DestType->isIntegralType(Self.Context)) ||
2057 (!srcIsVector && !SrcType->isIntegralType(Self.Context)))
Anders Carlsson570af5d2009-09-16 19:19:43 +00002058 return TC_NotApplicable;
2059
John McCall1c78f082015-07-23 23:54:07 +00002060 // The size we want to consider is eltCount * eltSize.
2061 // That's exactly what the lax-conversion rules will check.
2062 if (Self.areLaxCompatibleVectorTypes(SrcType, DestType)) {
John McCalle3027922010-08-25 11:45:40 +00002063 Kind = CK_BitCast;
Anders Carlsson570af5d2009-09-16 19:19:43 +00002064 return TC_Success;
Douglas Gregor19fc0b72009-12-22 22:47:22 +00002065 }
John McCall1c78f082015-07-23 23:54:07 +00002066
2067 // Otherwise, pick a reasonable diagnostic.
2068 if (!destIsVector)
Anders Carlsson570af5d2009-09-16 19:19:43 +00002069 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
John McCall1c78f082015-07-23 23:54:07 +00002070 else if (!srcIsVector)
Anders Carlsson570af5d2009-09-16 19:19:43 +00002071 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
2072 else
2073 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
2074
2075 return TC_Failed;
2076 }
Chad Rosier96c755d12012-02-03 02:54:37 +00002077
2078 if (SrcType == DestType) {
2079 // C++ 5.2.10p2 has a note that mentions that, subject to all other
2080 // restrictions, a cast to the same type is allowed so long as it does not
2081 // cast away constness. In C++98, the intent was not entirely clear here,
2082 // since all other paragraphs explicitly forbid casts to the same type.
2083 // C++11 clarifies this case with p2.
2084 //
2085 // The only allowed types are: integral, enumeration, pointer, or
2086 // pointer-to-member types. We also won't restrict Obj-C pointers either.
2087 Kind = CK_NoOp;
2088 TryCastResult Result = TC_NotApplicable;
2089 if (SrcType->isIntegralOrEnumerationType() ||
2090 SrcType->isAnyPointerType() ||
2091 SrcType->isMemberPointerType() ||
2092 SrcType->isBlockPointerType()) {
2093 Result = TC_Success;
2094 }
2095 return Result;
2096 }
2097
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00002098 bool destIsPtr = DestType->isAnyPointerType() ||
2099 DestType->isBlockPointerType();
2100 bool srcIsPtr = SrcType->isAnyPointerType() ||
2101 SrcType->isBlockPointerType();
Sebastian Redl9f831db2009-07-25 15:41:38 +00002102 if (!destIsPtr && !srcIsPtr) {
2103 // Except for std::nullptr_t->integer and lvalue->reference, which are
2104 // handled above, at least one of the two arguments must be a pointer.
2105 return TC_NotApplicable;
2106 }
2107
Douglas Gregor6972a622010-06-16 00:35:25 +00002108 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00002109 assert(srcIsPtr && "One type must be a pointer");
2110 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
Francois Pichetb796b632011-05-11 22:13:54 +00002111 // type large enough to hold it; except in Microsoft mode, where the
Hans Wennborg15439bc2013-06-06 09:16:36 +00002112 // integral type size doesn't matter (except we don't allow bool).
2113 bool MicrosoftException = Self.getLangOpts().MicrosoftExt &&
2114 !DestType->isBooleanType();
Francois Pichetb796b632011-05-11 22:13:54 +00002115 if ((Self.Context.getTypeSize(SrcType) >
2116 Self.Context.getTypeSize(DestType)) &&
Hans Wennborg15439bc2013-06-06 09:16:36 +00002117 !MicrosoftException) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00002118 msg = diag::err_bad_reinterpret_cast_small_int;
2119 return TC_Failed;
2120 }
John McCalle3027922010-08-25 11:45:40 +00002121 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002122 return TC_Success;
2123 }
2124
Douglas Gregorb90df602010-06-16 00:17:44 +00002125 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00002126 assert(destIsPtr && "One type must be a pointer");
David Blaikie282ad872012-10-16 18:53:14 +00002127 checkIntToPointerCast(CStyle, OpRange.getBegin(), SrcExpr.get(), DestType,
2128 Self);
Sebastian Redl9f831db2009-07-25 15:41:38 +00002129 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
2130 // converted to a pointer.
John McCalle84af4e2010-11-13 01:35:44 +00002131 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
2132 // necessarily converted to a null pointer value.]
John McCalle3027922010-08-25 11:45:40 +00002133 Kind = CK_IntegralToPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002134 return TC_Success;
2135 }
2136
2137 if (!destIsPtr || !srcIsPtr) {
2138 // With the valid non-pointer conversions out of the way, we can be even
2139 // more stringent.
2140 return TC_NotApplicable;
2141 }
2142
2143 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
2144 // The C-style cast operator can.
John McCall31168b02011-06-15 23:02:42 +00002145 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
2146 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregorb472e932011-04-15 17:59:54 +00002147 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002148 return TC_Failed;
2149 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00002150
2151 // Cannot convert between block pointers and Objective-C object pointers.
2152 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
2153 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
2154 return TC_NotApplicable;
2155
John McCall9320b872011-09-09 05:25:32 +00002156 if (IsLValueCast) {
2157 Kind = CK_LValueBitCast;
2158 } else if (DestType->isObjCObjectPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00002159 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
John McCall9320b872011-09-09 05:25:32 +00002160 } else if (DestType->isBlockPointerType()) {
2161 if (!SrcType->isBlockPointerType()) {
2162 Kind = CK_AnyPointerToBlockPointerCast;
2163 } else {
2164 Kind = CK_BitCast;
2165 }
2166 } else {
2167 Kind = CK_BitCast;
2168 }
2169
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00002170 // Any pointer can be cast to an Objective-C pointer type with a C-style
2171 // cast.
Fariborz Jahanian859c4152009-12-08 23:09:15 +00002172 if (CStyle && DestType->isObjCObjectPointerType()) {
Fariborz Jahanian859c4152009-12-08 23:09:15 +00002173 return TC_Success;
2174 }
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00002175 if (CStyle)
2176 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
Reid Kleckner9f497332016-05-10 21:00:03 +00002177
2178 DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
2179
Sebastian Redl9f831db2009-07-25 15:41:38 +00002180 // Not casting away constness, so the only remaining check is for compatible
2181 // pointer categories.
2182
2183 if (SrcType->isFunctionPointerType()) {
2184 if (DestType->isFunctionPointerType()) {
2185 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
2186 // a pointer to a function of a different type.
2187 return TC_Success;
2188 }
2189
2190 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
2191 // an object type or vice versa is conditionally-supported.
2192 // Compilers support it in C++03 too, though, because it's necessary for
2193 // casting the return value of dlsym() and GetProcAddress().
2194 // FIXME: Conditionally-supported behavior should be configurable in the
2195 // TargetInfo or similar.
Richard Smith0bf8a4922011-10-18 20:49:44 +00002196 Self.Diag(OpRange.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002197 Self.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002198 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2199 << OpRange;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002200 return TC_Success;
2201 }
2202
2203 if (DestType->isFunctionPointerType()) {
2204 // See above.
Richard Smith0bf8a4922011-10-18 20:49:44 +00002205 Self.Diag(OpRange.getBegin(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002206 Self.getLangOpts().CPlusPlus11 ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002207 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2208 << OpRange;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002209 return TC_Success;
2210 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00002211
Sebastian Redl9f831db2009-07-25 15:41:38 +00002212 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
2213 // a pointer to an object of different type.
2214 // Void pointers are not specified, but supported by every compiler out there.
2215 // So we finish by allowing everything that remains - it's got to be two
2216 // object pointers.
2217 return TC_Success;
John McCall909acf82011-02-14 18:34:10 +00002218}
Sebastian Redl9f831db2009-07-25 15:41:38 +00002219
Sebastian Redld74dd492012-02-12 18:41:05 +00002220void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
2221 bool ListInitialization) {
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002222 assert(Self.getLangOpts().CPlusPlus);
2223
John McCall9776e432011-10-06 23:25:11 +00002224 // Handle placeholders.
2225 if (isPlaceholder()) {
2226 // C-style casts can resolve __unknown_any types.
2227 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2228 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2229 SrcExpr.get(), Kind,
2230 ValueKind, BasePath);
2231 return;
2232 }
John McCallb50451a2011-10-05 07:41:44 +00002233
John McCall9776e432011-10-06 23:25:11 +00002234 checkNonOverloadPlaceholders();
2235 if (SrcExpr.isInvalid())
2236 return;
John McCalla072f5d2011-10-17 17:42:19 +00002237 }
John McCall9776e432011-10-06 23:25:11 +00002238
2239 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Sebastian Redl9f831db2009-07-25 15:41:38 +00002240 // This test is outside everything else because it's the only case where
2241 // a non-lvalue-reference target type does not lead to decay.
John McCallb50451a2011-10-05 07:41:44 +00002242 if (DestType->isVoidType()) {
John McCall3aef3d82011-04-10 19:13:55 +00002243 Kind = CK_ToVoid;
2244
John McCall9776e432011-10-06 23:25:11 +00002245 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall50a2c2c2011-10-11 23:14:30 +00002246 Self.ResolveAndFixSingleFunctionTemplateSpecialization(
2247 SrcExpr, /* Decay Function to ptr */ false,
John McCallb50451a2011-10-05 07:41:44 +00002248 /* Complain */ true, DestRange, DestType,
Douglas Gregor1beec452011-03-12 01:48:56 +00002249 diag::err_bad_cstyle_cast_overload);
John McCallb50451a2011-10-05 07:41:44 +00002250 if (SrcExpr.isInvalid())
2251 return;
Douglas Gregorb491ed32011-02-19 21:32:49 +00002252 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002253
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002254 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
John McCallb50451a2011-10-05 07:41:44 +00002255 return;
Anton Yartsev28ccef72011-03-27 09:32:40 +00002256 }
2257
Sebastian Redl9f831db2009-07-25 15:41:38 +00002258 // If the type is dependent, we won't do any other semantic analysis now.
Eli Friedman71271082013-09-19 01:12:33 +00002259 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
2260 SrcExpr.get()->isValueDependent()) {
John McCallb50451a2011-10-05 07:41:44 +00002261 assert(Kind == CK_Dependent);
2262 return;
John McCall8cb679e2010-11-15 09:13:47 +00002263 }
Benjamin Kramer65cc1072011-07-08 20:20:17 +00002264
John McCall50a2c2c2011-10-11 23:14:30 +00002265 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
2266 !isPlaceholder(BuiltinType::Overload)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002267 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
John McCallb50451a2011-10-05 07:41:44 +00002268 if (SrcExpr.isInvalid())
2269 return;
John Wiegley01296292011-04-08 18:41:53 +00002270 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002271
John McCall3aef3d82011-04-10 19:13:55 +00002272 // AltiVec vector initialization with a single literal.
John McCallb50451a2011-10-05 07:41:44 +00002273 if (const VectorType *vecTy = DestType->getAs<VectorType>())
John McCall3aef3d82011-04-10 19:13:55 +00002274 if (vecTy->getVectorKind() == VectorType::AltiVecVector
John McCallb50451a2011-10-05 07:41:44 +00002275 && (SrcExpr.get()->getType()->isIntegerType()
2276 || SrcExpr.get()->getType()->isFloatingType())) {
John McCall3aef3d82011-04-10 19:13:55 +00002277 Kind = CK_VectorSplat;
George Burgess IVdf1ed002016-01-13 01:52:39 +00002278 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
John McCallb50451a2011-10-05 07:41:44 +00002279 return;
John McCall3aef3d82011-04-10 19:13:55 +00002280 }
2281
Sebastian Redl9f831db2009-07-25 15:41:38 +00002282 // C++ [expr.cast]p5: The conversions performed by
2283 // - a const_cast,
2284 // - a static_cast,
2285 // - a static_cast followed by a const_cast,
2286 // - a reinterpret_cast, or
2287 // - a reinterpret_cast followed by a const_cast,
2288 // can be performed using the cast notation of explicit type conversion.
2289 // [...] If a conversion can be interpreted in more than one of the ways
2290 // listed above, the interpretation that appears first in the list is used,
2291 // even if a cast resulting from that interpretation is ill-formed.
2292 // In plain language, this means trying a const_cast ...
2293 unsigned msg = diag::err_bad_cxx_cast_generic;
Richard Smith82c9b512013-06-14 22:27:52 +00002294 TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
John McCallb50451a2011-10-05 07:41:44 +00002295 /*CStyle*/true, msg);
Richard Smith82c9b512013-06-14 22:27:52 +00002296 if (SrcExpr.isInvalid())
2297 return;
Anders Carlsson027732b2009-10-19 18:14:28 +00002298 if (tcr == TC_Success)
John McCalle3027922010-08-25 11:45:40 +00002299 Kind = CK_NoOp;
Anders Carlsson027732b2009-10-19 18:14:28 +00002300
John McCall31168b02011-06-15 23:02:42 +00002301 Sema::CheckedConversionKind CCK
2302 = FunctionalStyle? Sema::CCK_FunctionalCast
2303 : Sema::CCK_CStyleCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002304 if (tcr == TC_NotApplicable) {
2305 // ... or if that is not possible, a static_cast, ignoring const, ...
John McCallb50451a2011-10-05 07:41:44 +00002306 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
Sebastian Redld74dd492012-02-12 18:41:05 +00002307 msg, Kind, BasePath, ListInitialization);
John McCallb50451a2011-10-05 07:41:44 +00002308 if (SrcExpr.isInvalid())
2309 return;
2310
Sebastian Redl9f831db2009-07-25 15:41:38 +00002311 if (tcr == TC_NotApplicable) {
2312 // ... and finally a reinterpret_cast, ignoring const.
John McCallb50451a2011-10-05 07:41:44 +00002313 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
2314 OpRange, msg, Kind);
2315 if (SrcExpr.isInvalid())
2316 return;
Sebastian Redl9f831db2009-07-25 15:41:38 +00002317 }
2318 }
2319
Brian Kelley11352a82017-03-29 18:09:02 +00002320 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
2321 tcr == TC_Success)
2322 checkObjCConversion(CCK);
John McCall31168b02011-06-15 23:02:42 +00002323
Nick Lewycky14d88eb2010-11-09 00:19:31 +00002324 if (tcr != TC_Success && msg != 0) {
John McCallb50451a2011-10-05 07:41:44 +00002325 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +00002326 DeclAccessPair Found;
John McCallb50451a2011-10-05 07:41:44 +00002327 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
2328 DestType,
2329 /*Complain*/ true,
Douglas Gregore81f58e2010-11-08 03:40:48 +00002330 Found);
Logan Chienaf24ad92014-04-13 16:08:24 +00002331 if (Fn) {
2332 // If DestType is a function type (not to be confused with the function
2333 // pointer type), it will be possible to resolve the function address,
2334 // but the type cast should be considered as failure.
2335 OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression;
2336 Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload)
2337 << OE->getName() << DestType << OpRange
2338 << OE->getQualifierLoc().getSourceRange();
2339 Self.NoteAllOverloadCandidates(SrcExpr.get());
2340 }
Nick Lewycky14d88eb2010-11-09 00:19:31 +00002341 } else {
John McCallb50451a2011-10-05 07:41:44 +00002342 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
Sebastian Redl2b80af42012-02-13 19:55:43 +00002343 OpRange, SrcExpr.get(), DestType, ListInitialization);
Douglas Gregore81f58e2010-11-08 03:40:48 +00002344 }
John McCallb50451a2011-10-05 07:41:44 +00002345 } else if (Kind == CK_BitCast) {
2346 checkCastAlign();
Douglas Gregore81f58e2010-11-08 03:40:48 +00002347 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00002348
John McCallb50451a2011-10-05 07:41:44 +00002349 // Clear out SrcExpr if there was a fatal error.
John Wiegley01296292011-04-08 18:41:53 +00002350 if (tcr != TC_Success)
John McCallb50451a2011-10-05 07:41:44 +00002351 SrcExpr = ExprError();
2352}
2353
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002354/// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
2355/// non-matching type. Such as enum function call to int, int call to
2356/// pointer; etc. Cast to 'void' is an exception.
2357static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
2358 QualType DestType) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002359 if (Self.Diags.isIgnored(diag::warn_bad_function_cast,
2360 SrcExpr.get()->getExprLoc()))
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002361 return;
2362
2363 if (!isa<CallExpr>(SrcExpr.get()))
2364 return;
2365
2366 QualType SrcType = SrcExpr.get()->getType();
2367 if (DestType.getUnqualifiedType()->isVoidType())
2368 return;
2369 if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
2370 && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
2371 return;
2372 if (SrcType->isIntegerType() && DestType->isIntegerType() &&
2373 (SrcType->isBooleanType() == DestType->isBooleanType()) &&
2374 (SrcType->isEnumeralType() == DestType->isEnumeralType()))
2375 return;
2376 if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
2377 return;
2378 if (SrcType->isEnumeralType() && DestType->isEnumeralType())
2379 return;
2380 if (SrcType->isComplexType() && DestType->isComplexType())
2381 return;
2382 if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
2383 return;
2384
2385 Self.Diag(SrcExpr.get()->getExprLoc(),
2386 diag::warn_bad_function_cast)
2387 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2388}
2389
John McCall9776e432011-10-06 23:25:11 +00002390/// Check the semantics of a C-style cast operation, in C.
2391void CastOperation::CheckCStyleCast() {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002392 assert(!Self.getLangOpts().CPlusPlus);
John McCall9776e432011-10-06 23:25:11 +00002393
John McCall4124c492011-10-17 18:40:02 +00002394 // C-style casts can resolve __unknown_any types.
2395 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2396 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2397 SrcExpr.get(), Kind,
2398 ValueKind, BasePath);
2399 return;
2400 }
John McCall9776e432011-10-06 23:25:11 +00002401
2402 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2403 // type needs to be scalar.
2404 if (DestType->isVoidType()) {
2405 // We don't necessarily do lvalue-to-rvalue conversions on this.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002406 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +00002407 if (SrcExpr.isInvalid())
2408 return;
2409
2410 // Cast to void allows any expr type.
2411 Kind = CK_ToVoid;
2412 return;
2413 }
2414
George Burgess IV5f21c712015-10-12 19:57:04 +00002415 // Overloads are allowed with C extensions, so we need to support them.
2416 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
2417 DeclAccessPair DAP;
2418 if (FunctionDecl *FD = Self.ResolveAddressOfOverloadedFunction(
2419 SrcExpr.get(), DestType, /*Complain=*/true, DAP))
2420 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr.get(), DAP, FD);
2421 else
2422 return;
2423 assert(SrcExpr.isUsable());
2424 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002425 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +00002426 if (SrcExpr.isInvalid())
2427 return;
2428 QualType SrcType = SrcExpr.get()->getType();
David Chisnallfa35df62012-01-16 17:27:18 +00002429
John McCall4124c492011-10-17 18:40:02 +00002430 assert(!SrcType->isPlaceholderType());
John McCall9776e432011-10-06 23:25:11 +00002431
Joey Gouly8fc32f02014-01-14 12:47:29 +00002432 // OpenCL v1 s6.5: Casting a pointer to address space A to a pointer to
2433 // address space B is illegal.
2434 if (Self.getLangOpts().OpenCL && DestType->isPointerType() &&
2435 SrcType->isPointerType()) {
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00002436 const PointerType *DestPtr = DestType->getAs<PointerType>();
2437 if (!DestPtr->isAddressSpaceOverlapping(*SrcType->getAs<PointerType>())) {
Joey Gouly8fc32f02014-01-14 12:47:29 +00002438 Self.Diag(OpRange.getBegin(),
2439 diag::err_typecheck_incompatible_address_space)
2440 << SrcType << DestType << Sema::AA_Casting
2441 << SrcExpr.get()->getSourceRange();
2442 SrcExpr = ExprError();
2443 return;
2444 }
2445 }
2446
John McCall9776e432011-10-06 23:25:11 +00002447 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
2448 diag::err_typecheck_cast_to_incomplete)) {
2449 SrcExpr = ExprError();
2450 return;
2451 }
2452
2453 if (!DestType->isScalarType() && !DestType->isVectorType()) {
2454 const RecordType *DestRecordTy = DestType->getAs<RecordType>();
2455
2456 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
2457 // GCC struct/union extension: allow cast to self.
2458 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
2459 << DestType << SrcExpr.get()->getSourceRange();
2460 Kind = CK_NoOp;
2461 return;
2462 }
2463
2464 // GCC's cast to union extension.
2465 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
2466 RecordDecl *RD = DestRecordTy->getDecl();
John McCallf1ef7962017-08-15 21:42:47 +00002467 if (CastExpr::getTargetFieldForToUnionCast(RD, SrcType)) {
2468 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
2469 << SrcExpr.get()->getSourceRange();
2470 Kind = CK_ToUnion;
2471 return;
2472 } else {
John McCall9776e432011-10-06 23:25:11 +00002473 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2474 << SrcType << SrcExpr.get()->getSourceRange();
2475 SrcExpr = ExprError();
2476 return;
2477 }
John McCall9776e432011-10-06 23:25:11 +00002478 }
2479
Yaxun Liuc537c8a2016-05-20 17:18:16 +00002480 // OpenCL v2.0 s6.13.10 - Allow casts from '0' to event_t type.
2481 if (Self.getLangOpts().OpenCL && DestType->isEventT()) {
2482 llvm::APSInt CastInt;
2483 if (SrcExpr.get()->EvaluateAsInt(CastInt, Self.Context)) {
2484 if (0 == CastInt) {
2485 Kind = CK_ZeroToOCLEvent;
2486 return;
2487 }
2488 Self.Diag(OpRange.getBegin(),
Richard Smithf8812672016-12-02 22:38:31 +00002489 diag::err_opencl_cast_non_zero_to_event_t)
Yaxun Liuc537c8a2016-05-20 17:18:16 +00002490 << CastInt.toString(10) << SrcExpr.get()->getSourceRange();
2491 SrcExpr = ExprError();
2492 return;
2493 }
2494 }
2495
John McCall9776e432011-10-06 23:25:11 +00002496 // Reject any other conversions to non-scalar types.
2497 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
2498 << DestType << SrcExpr.get()->getSourceRange();
2499 SrcExpr = ExprError();
2500 return;
2501 }
2502
2503 // The type we're casting to is known to be a scalar or vector.
2504
2505 // Require the operand to be a scalar or vector.
2506 if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
2507 Self.Diag(SrcExpr.get()->getExprLoc(),
2508 diag::err_typecheck_expect_scalar_operand)
2509 << SrcType << SrcExpr.get()->getSourceRange();
2510 SrcExpr = ExprError();
2511 return;
2512 }
2513
2514 if (DestType->isExtVectorType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002515 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind);
John McCall9776e432011-10-06 23:25:11 +00002516 return;
2517 }
2518
2519 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
2520 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
2521 (SrcType->isIntegerType() || SrcType->isFloatingType())) {
2522 Kind = CK_VectorSplat;
George Burgess IVdf1ed002016-01-13 01:52:39 +00002523 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
John McCall9776e432011-10-06 23:25:11 +00002524 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
2525 SrcExpr = ExprError();
2526 }
2527 return;
2528 }
2529
2530 if (SrcType->isVectorType()) {
2531 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
2532 SrcExpr = ExprError();
2533 return;
2534 }
2535
2536 // The source and target types are both scalars, i.e.
2537 // - arithmetic types (fundamental, enum, and complex)
2538 // - all kinds of pointers
2539 // Note that member pointers were filtered out with C++, above.
2540
2541 if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
2542 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
2543 SrcExpr = ExprError();
2544 return;
2545 }
2546
2547 // If either type is a pointer, the other type has to be either an
2548 // integer or a pointer.
2549 if (!DestType->isArithmeticType()) {
2550 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
2551 Self.Diag(SrcExpr.get()->getExprLoc(),
2552 diag::err_cast_pointer_from_non_pointer_int)
2553 << SrcType << SrcExpr.get()->getSourceRange();
2554 SrcExpr = ExprError();
2555 return;
2556 }
David Blaikie282ad872012-10-16 18:53:14 +00002557 checkIntToPointerCast(/* CStyle */ true, OpRange.getBegin(), SrcExpr.get(),
2558 DestType, Self);
John McCall9776e432011-10-06 23:25:11 +00002559 } else if (!SrcType->isArithmeticType()) {
2560 if (!DestType->isIntegralType(Self.Context) &&
2561 DestType->isArithmeticType()) {
2562 Self.Diag(SrcExpr.get()->getLocStart(),
2563 diag::err_cast_pointer_to_non_pointer_int)
Abramo Bagnara9847e742011-11-15 11:25:38 +00002564 << DestType << SrcExpr.get()->getSourceRange();
John McCall9776e432011-10-06 23:25:11 +00002565 SrcExpr = ExprError();
2566 return;
2567 }
2568 }
2569
Yaxun Liu5b746652016-12-18 05:18:55 +00002570 if (Self.getLangOpts().OpenCL &&
2571 !Self.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
Joey Goulydd7f4562013-01-23 11:56:20 +00002572 if (DestType->isHalfType()) {
2573 Self.Diag(SrcExpr.get()->getLocStart(), diag::err_opencl_cast_to_half)
2574 << DestType << SrcExpr.get()->getSourceRange();
2575 SrcExpr = ExprError();
2576 return;
2577 }
Joey Goulydd7f4562013-01-23 11:56:20 +00002578 }
2579
John McCall9776e432011-10-06 23:25:11 +00002580 // ARC imposes extra restrictions on casts.
Brian Kelley11352a82017-03-29 18:09:02 +00002581 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) {
2582 checkObjCConversion(Sema::CCK_CStyleCast);
John McCall9776e432011-10-06 23:25:11 +00002583 if (SrcExpr.isInvalid())
2584 return;
Brian Kelley11352a82017-03-29 18:09:02 +00002585
2586 const PointerType *CastPtr = DestType->getAs<PointerType>();
2587 if (Self.getLangOpts().ObjCAutoRefCount && CastPtr) {
John McCall9776e432011-10-06 23:25:11 +00002588 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
2589 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
2590 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
2591 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
2592 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
2593 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
2594 Self.Diag(SrcExpr.get()->getLocStart(),
2595 diag::err_typecheck_incompatible_ownership)
2596 << SrcType << DestType << Sema::AA_Casting
2597 << SrcExpr.get()->getSourceRange();
2598 return;
2599 }
2600 }
2601 }
2602 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
2603 Self.Diag(SrcExpr.get()->getLocStart(),
2604 diag::err_arc_convesion_of_weak_unavailable)
2605 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2606 SrcExpr = ExprError();
2607 return;
2608 }
2609 }
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00002610
Fariborz Jahanian5ad96592012-08-16 18:33:47 +00002611 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
Reid Kleckner9f497332016-05-10 21:00:03 +00002612 DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
Fariborz Jahanian91f548b2012-08-17 17:22:34 +00002613 DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
John McCall9776e432011-10-06 23:25:11 +00002614 Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2615 if (SrcExpr.isInvalid())
2616 return;
2617
2618 if (Kind == CK_BitCast)
2619 checkCastAlign();
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002620}
Roman Divackyd5178012014-11-21 21:03:10 +00002621
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002622/// DiagnoseCastQual - Warn whenever casts discards a qualifiers, be it either
2623/// const, volatile or both.
2624static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
2625 QualType DestType) {
2626 if (SrcExpr.isInvalid())
2627 return;
2628
2629 QualType SrcType = SrcExpr.get()->getType();
2630 if (!((SrcType->isAnyPointerType() && DestType->isAnyPointerType()) ||
2631 DestType->isLValueReferenceType()))
2632 return;
2633
Roman Divackyd5178012014-11-21 21:03:10 +00002634 QualType TheOffendingSrcType, TheOffendingDestType;
2635 Qualifiers CastAwayQualifiers;
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002636 if (!CastsAwayConstness(Self, SrcType, DestType, true, false,
2637 &TheOffendingSrcType, &TheOffendingDestType,
2638 &CastAwayQualifiers))
2639 return;
2640
2641 int qualifiers = -1;
2642 if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) {
2643 qualifiers = 0;
2644 } else if (CastAwayQualifiers.hasConst()) {
2645 qualifiers = 1;
2646 } else if (CastAwayQualifiers.hasVolatile()) {
2647 qualifiers = 2;
Roman Divackyd5178012014-11-21 21:03:10 +00002648 }
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002649 // This is a variant of int **x; const int **y = (const int **)x;
2650 if (qualifiers == -1)
2651 Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual2)
2652 << SrcType << DestType;
2653 else
2654 Self.Diag(SrcExpr.get()->getLocStart(), diag::warn_cast_qual)
2655 << TheOffendingSrcType << TheOffendingDestType << qualifiers;
John McCall9776e432011-10-06 23:25:11 +00002656}
2657
2658ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
2659 TypeSourceInfo *CastTypeInfo,
2660 SourceLocation RPLoc,
2661 Expr *CastExpr) {
John McCallb50451a2011-10-05 07:41:44 +00002662 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2663 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2664 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
2665
David Blaikiebbafb8a2012-03-11 07:00:24 +00002666 if (getLangOpts().CPlusPlus) {
Sebastian Redld74dd492012-02-12 18:41:05 +00002667 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false,
2668 isa<InitListExpr>(CastExpr));
John McCall9776e432011-10-06 23:25:11 +00002669 } else {
2670 Op.CheckCStyleCast();
2671 }
2672
John McCallb50451a2011-10-05 07:41:44 +00002673 if (Op.SrcExpr.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00002674 return ExprError();
2675
Roman Lebedevba80b8d2017-07-03 17:59:22 +00002676 // -Wcast-qual
2677 DiagnoseCastQual(Op.Self, Op.SrcExpr, Op.DestType);
2678
John McCall4124c492011-10-17 18:40:02 +00002679 return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002680 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
John McCall4124c492011-10-17 18:40:02 +00002681 &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
John McCallb50451a2011-10-05 07:41:44 +00002682}
2683
2684ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
Richard Smith60437622017-02-09 19:17:44 +00002685 QualType Type,
John McCallb50451a2011-10-05 07:41:44 +00002686 SourceLocation LPLoc,
2687 Expr *CastExpr,
2688 SourceLocation RPLoc) {
Sebastian Redl2b80af42012-02-13 19:55:43 +00002689 assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
Richard Smith60437622017-02-09 19:17:44 +00002690 CastOperation Op(*this, Type, CastExpr);
John McCallb50451a2011-10-05 07:41:44 +00002691 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2692 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
2693
Sebastian Redl2b80af42012-02-13 19:55:43 +00002694 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/true, /*ListInit=*/false);
John McCallb50451a2011-10-05 07:41:44 +00002695 if (Op.SrcExpr.isInvalid())
2696 return ExprError();
Olivier Goffart1ba7dc32015-09-04 10:17:10 +00002697
2698 auto *SubExpr = Op.SrcExpr.get();
2699 if (auto *BindExpr = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
2700 SubExpr = BindExpr->getSubExpr();
2701 if (auto *ConstructExpr = dyn_cast<CXXConstructExpr>(SubExpr))
Enea Zaffanella76e98fe2013-09-07 05:49:53 +00002702 ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc));
John McCallb50451a2011-10-05 07:41:44 +00002703
John McCall4124c492011-10-17 18:40:02 +00002704 return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
Eli Friedman89fe0d52013-08-15 22:02:56 +00002705 Op.ValueKind, CastTypeInfo, Op.Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002706 Op.SrcExpr.get(), &Op.BasePath, LPLoc, RPLoc));
Sebastian Redl9f831db2009-07-25 15:41:38 +00002707}