blob: 5d49225ac4c96ef73c78c0c4e61f8176e9235be7 [file] [log] [blame]
John McCalld8d3ced2011-10-11 17:38:55 +00001//===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===//
Sebastian Redl26d85b12008-11-05 21:50:06 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
John McCalld8d3ced2011-10-11 17:38:55 +000010// This file implements semantic analysis for cast expressions, including
11// 1) C-style casts like '(int) x'
12// 2) C++ functional casts like 'int(x)'
13// 3) C++ named casts like 'static_cast<int>(x)'
Sebastian Redl26d85b12008-11-05 21:50:06 +000014//
15//===----------------------------------------------------------------------===//
16
John McCall2d887082010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Sebastian Redl26d85b12008-11-05 21:50:06 +000018#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
John McCall437da052013-03-22 02:58:14 +000022#include "clang/AST/RecordLayout.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070024#include "clang/Basic/TargetInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000025#include "clang/Sema/Initialization.h"
Sebastian Redl26d85b12008-11-05 21:50:06 +000026#include "llvm/ADT/SmallVector.h"
Sebastian Redle3dc28a2008-11-07 23:29:29 +000027#include <set>
Sebastian Redl26d85b12008-11-05 21:50:06 +000028using namespace clang;
29
Douglas Gregor8e960432010-11-08 03:40:48 +000030
Douglas Gregor8e960432010-11-08 03:40:48 +000031
Sebastian Redl9cc11e72009-07-25 15:41:38 +000032enum TryCastResult {
33 TC_NotApplicable, ///< The cast method is not applicable.
34 TC_Success, ///< The cast method is appropriate and successful.
35 TC_Failed ///< The cast method is appropriate, but failed. A
36 ///< diagnostic has been emitted.
37};
38
39enum CastType {
40 CT_Const, ///< const_cast
41 CT_Static, ///< static_cast
42 CT_Reinterpret, ///< reinterpret_cast
43 CT_Dynamic, ///< dynamic_cast
44 CT_CStyle, ///< (Type)expr
45 CT_Functional ///< Type(expr)
Sebastian Redl37d6de32008-11-08 13:00:26 +000046};
47
John McCallb45ae252011-10-05 07:41:44 +000048namespace {
49 struct CastOperation {
50 CastOperation(Sema &S, QualType destType, ExprResult src)
51 : Self(S), SrcExpr(src), DestType(destType),
52 ResultType(destType.getNonLValueExprType(S.Context)),
53 ValueKind(Expr::getValueKindForType(destType)),
John McCall5acb0c92011-10-17 18:40:02 +000054 Kind(CK_Dependent), IsARCUnbridgedCast(false) {
John McCalla180f042011-10-06 23:25:11 +000055
56 if (const BuiltinType *placeholder =
57 src.get()->getType()->getAsPlaceholderType()) {
58 PlaceholderKind = placeholder->getKind();
59 } else {
60 PlaceholderKind = (BuiltinType::Kind) 0;
61 }
62 }
Douglas Gregor8e960432010-11-08 03:40:48 +000063
John McCallb45ae252011-10-05 07:41:44 +000064 Sema &Self;
65 ExprResult SrcExpr;
66 QualType DestType;
67 QualType ResultType;
68 ExprValueKind ValueKind;
69 CastKind Kind;
John McCalla180f042011-10-06 23:25:11 +000070 BuiltinType::Kind PlaceholderKind;
John McCallb45ae252011-10-05 07:41:44 +000071 CXXCastPath BasePath;
John McCall5acb0c92011-10-17 18:40:02 +000072 bool IsARCUnbridgedCast;
Douglas Gregor8e960432010-11-08 03:40:48 +000073
John McCallb45ae252011-10-05 07:41:44 +000074 SourceRange OpRange;
75 SourceRange DestRange;
Douglas Gregor8e960432010-11-08 03:40:48 +000076
John McCalla180f042011-10-06 23:25:11 +000077 // Top-level semantics-checking routines.
John McCallb45ae252011-10-05 07:41:44 +000078 void CheckConstCast();
79 void CheckReinterpretCast();
Richard Smithc8d7f582011-11-29 22:48:16 +000080 void CheckStaticCast();
John McCallb45ae252011-10-05 07:41:44 +000081 void CheckDynamicCast();
Sebastian Redl6dc00f62012-02-12 18:41:05 +000082 void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
John McCalla180f042011-10-06 23:25:11 +000083 void CheckCStyleCast();
84
John McCall5acb0c92011-10-17 18:40:02 +000085 /// Complete an apparently-successful cast operation that yields
86 /// the given expression.
87 ExprResult complete(CastExpr *castExpr) {
88 // If this is an unbridged cast, wrap the result in an implicit
89 // cast that yields the unbridged-cast placeholder type.
90 if (IsARCUnbridgedCast) {
91 castExpr = ImplicitCastExpr::Create(Self.Context,
92 Self.Context.ARCUnbridgedCastTy,
93 CK_Dependent, castExpr, 0,
94 castExpr->getValueKind());
95 }
96 return Self.Owned(castExpr);
97 }
98
John McCalla180f042011-10-06 23:25:11 +000099 // Internal convenience methods.
100
101 /// Try to handle the given placeholder expression kind. Return
102 /// true if the source expression has the appropriate placeholder
103 /// kind. A placeholder can only be claimed once.
104 bool claimPlaceholder(BuiltinType::Kind K) {
105 if (PlaceholderKind != K) return false;
106
107 PlaceholderKind = (BuiltinType::Kind) 0;
108 return true;
109 }
110
111 bool isPlaceholder() const {
112 return PlaceholderKind != 0;
113 }
114 bool isPlaceholder(BuiltinType::Kind K) const {
115 return PlaceholderKind == K;
116 }
John McCallb45ae252011-10-05 07:41:44 +0000117
118 void checkCastAlign() {
119 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
120 }
121
122 void checkObjCARCConversion(Sema::CheckedConversionKind CCK) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000123 assert(Self.getLangOpts().ObjCAutoRefCount);
John McCall5acb0c92011-10-17 18:40:02 +0000124
John McCallb45ae252011-10-05 07:41:44 +0000125 Expr *src = SrcExpr.get();
John McCall5acb0c92011-10-17 18:40:02 +0000126 if (Self.CheckObjCARCConversion(OpRange, DestType, src, CCK) ==
127 Sema::ACR_unbridged)
128 IsARCUnbridgedCast = true;
John McCallb45ae252011-10-05 07:41:44 +0000129 SrcExpr = src;
130 }
John McCalla180f042011-10-06 23:25:11 +0000131
132 /// Check for and handle non-overload placeholder expressions.
133 void checkNonOverloadPlaceholders() {
134 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
135 return;
136
137 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
138 if (SrcExpr.isInvalid())
139 return;
140 PlaceholderKind = (BuiltinType::Kind) 0;
141 }
John McCallb45ae252011-10-05 07:41:44 +0000142 };
143}
Sebastian Redl37d6de32008-11-08 13:00:26 +0000144
John McCallf85e1932011-06-15 23:02:42 +0000145static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
146 bool CheckCVR, bool CheckObjCLifetime);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000147
148// The Try functions attempt a specific way of casting. If they succeed, they
149// return TC_Success. If their way of casting is not appropriate for the given
150// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
151// to emit if no other way succeeds. If their way of casting is appropriate but
152// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
153// they emit a specialized diagnostic.
154// All diagnostics returned by these functions must expect the same three
155// arguments:
156// %0: Cast Type (a value from the CastType enumeration)
157// %1: Source Type
158// %2: Destination Type
159static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000160 QualType DestType, bool CStyle,
161 CastKind &Kind,
Douglas Gregor88b22a42011-01-25 16:13:26 +0000162 CXXCastPath &BasePath,
163 unsigned &msg);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000164static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000165 QualType DestType, bool CStyle,
166 const SourceRange &OpRange,
167 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000168 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000169 CXXCastPath &BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000170static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
171 QualType DestType, bool CStyle,
172 const SourceRange &OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000173 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000174 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000175 CXXCastPath &BasePath);
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000176static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
177 CanQualType DestType, bool CStyle,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000178 const SourceRange &OpRange,
179 QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000180 QualType OrigDestType, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000181 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000182 CXXCastPath &BasePath);
John Wiegley429bb272011-04-08 18:41:53 +0000183static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
Anders Carlssoncee22422010-04-24 19:22:20 +0000184 QualType SrcType,
185 QualType DestType,bool CStyle,
186 const SourceRange &OpRange,
187 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000188 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000189 CXXCastPath &BasePath);
Anders Carlssoncee22422010-04-24 19:22:20 +0000190
John Wiegley429bb272011-04-08 18:41:53 +0000191static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
John McCallf85e1932011-06-15 23:02:42 +0000192 QualType DestType,
193 Sema::CheckedConversionKind CCK,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000194 const SourceRange &OpRange,
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000195 unsigned &msg, CastKind &Kind,
196 bool ListInitialization);
John Wiegley429bb272011-04-08 18:41:53 +0000197static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCallf85e1932011-06-15 23:02:42 +0000198 QualType DestType,
199 Sema::CheckedConversionKind CCK,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000200 const SourceRange &OpRange,
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000201 unsigned &msg, CastKind &Kind,
202 CXXCastPath &BasePath,
203 bool ListInitialization);
Richard Smith41cb3d92013-06-14 22:27:52 +0000204static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
205 QualType DestType, bool CStyle,
206 unsigned &msg);
John Wiegley429bb272011-04-08 18:41:53 +0000207static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000208 QualType DestType, bool CStyle,
209 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000210 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000211 CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +0000212
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000213
Sebastian Redl26d85b12008-11-05 21:50:06 +0000214/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
John McCall60d7b3a2010-08-24 06:29:42 +0000215ExprResult
Sebastian Redl26d85b12008-11-05 21:50:06 +0000216Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +0000217 SourceLocation LAngleBracketLoc, Declarator &D,
Sebastian Redl26d85b12008-11-05 21:50:06 +0000218 SourceLocation RAngleBracketLoc,
John McCallf312b1e2010-08-26 23:41:50 +0000219 SourceLocation LParenLoc, Expr *E,
Sebastian Redl26d85b12008-11-05 21:50:06 +0000220 SourceLocation RParenLoc) {
John McCallc89724c2010-01-15 19:13:16 +0000221
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +0000222 assert(!D.isInvalidType());
223
224 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
225 if (D.isInvalidType())
226 return ExprError();
227
David Blaikie4e4d0842012-03-11 07:00:24 +0000228 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +0000229 // Check that there are no default arguments (C++ only).
230 CheckExtraCXXDefaultArguments(D);
231 }
232
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000233 return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
John McCallc89724c2010-01-15 19:13:16 +0000234 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
235 SourceRange(LParenLoc, RParenLoc));
236}
237
John McCall60d7b3a2010-08-24 06:29:42 +0000238ExprResult
John McCallc89724c2010-01-15 19:13:16 +0000239Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John Wiegley429bb272011-04-08 18:41:53 +0000240 TypeSourceInfo *DestTInfo, Expr *E,
John McCallc89724c2010-01-15 19:13:16 +0000241 SourceRange AngleBrackets, SourceRange Parens) {
John Wiegley429bb272011-04-08 18:41:53 +0000242 ExprResult Ex = Owned(E);
John McCallc89724c2010-01-15 19:13:16 +0000243 QualType DestType = DestTInfo->getType();
244
Douglas Gregor9103bb22008-12-17 22:52:20 +0000245 // If the type is dependent, we won't do the semantic analysis now.
246 // FIXME: should we check this in a more fine-grained manner?
Eli Friedmanf91e86c2013-09-19 01:12:33 +0000247 bool TypeDependent = DestType->isDependentType() ||
248 Ex.get()->isTypeDependent() ||
249 Ex.get()->isValueDependent();
Douglas Gregor9103bb22008-12-17 22:52:20 +0000250
John McCallb45ae252011-10-05 07:41:44 +0000251 CastOperation Op(*this, DestType, E);
252 Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
253 Op.DestRange = AngleBrackets;
John McCalla21e06c2010-11-26 10:57:22 +0000254
Sebastian Redl26d85b12008-11-05 21:50:06 +0000255 switch (Kind) {
John McCalldaa8e4e2010-11-15 09:13:47 +0000256 default: llvm_unreachable("Unknown C++ cast!");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000257
258 case tok::kw_const_cast:
John Wiegley429bb272011-04-08 18:41:53 +0000259 if (!TypeDependent) {
John McCallb45ae252011-10-05 07:41:44 +0000260 Op.CheckConstCast();
261 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000262 return ExprError();
263 }
John McCall5acb0c92011-10-17 18:40:02 +0000264 return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
265 Op.ValueKind, Op.SrcExpr.take(), DestTInfo,
Fariborz Jahanianf799ae12013-02-22 22:02:53 +0000266 OpLoc, Parens.getEnd(),
267 AngleBrackets));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000268
Anders Carlsson714179b2009-08-02 19:07:59 +0000269 case tok::kw_dynamic_cast: {
John Wiegley429bb272011-04-08 18:41:53 +0000270 if (!TypeDependent) {
John McCallb45ae252011-10-05 07:41:44 +0000271 Op.CheckDynamicCast();
272 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000273 return ExprError();
274 }
John McCall5acb0c92011-10-17 18:40:02 +0000275 return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
276 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
277 &Op.BasePath, DestTInfo,
Fariborz Jahanianf799ae12013-02-22 22:02:53 +0000278 OpLoc, Parens.getEnd(),
279 AngleBrackets));
Anders Carlsson714179b2009-08-02 19:07:59 +0000280 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000281 case tok::kw_reinterpret_cast: {
John Wiegley429bb272011-04-08 18:41:53 +0000282 if (!TypeDependent) {
John McCallb45ae252011-10-05 07:41:44 +0000283 Op.CheckReinterpretCast();
284 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000285 return ExprError();
286 }
John McCall5acb0c92011-10-17 18:40:02 +0000287 return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
288 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
289 0, DestTInfo, OpLoc,
Fariborz Jahanianf799ae12013-02-22 22:02:53 +0000290 Parens.getEnd(),
291 AngleBrackets));
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000292 }
Anders Carlssoncdb61972009-08-07 22:21:05 +0000293 case tok::kw_static_cast: {
John Wiegley429bb272011-04-08 18:41:53 +0000294 if (!TypeDependent) {
Richard Smithc8d7f582011-11-29 22:48:16 +0000295 Op.CheckStaticCast();
John McCallb45ae252011-10-05 07:41:44 +0000296 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +0000297 return ExprError();
298 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000299
John McCall5acb0c92011-10-17 18:40:02 +0000300 return Op.complete(CXXStaticCastExpr::Create(Context, Op.ResultType,
301 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
302 &Op.BasePath, DestTInfo,
Fariborz Jahanianf799ae12013-02-22 22:02:53 +0000303 OpLoc, Parens.getEnd(),
304 AngleBrackets));
Anders Carlssoncdb61972009-08-07 22:21:05 +0000305 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000306 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000307}
308
John McCall79ab2c82011-02-14 18:34:10 +0000309/// Try to diagnose a failed overloaded cast. Returns true if
310/// diagnostics were emitted.
311static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
312 SourceRange range, Expr *src,
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000313 QualType destType,
314 bool listInitialization) {
John McCall79ab2c82011-02-14 18:34:10 +0000315 switch (CT) {
316 // These cast kinds don't consider user-defined conversions.
317 case CT_Const:
318 case CT_Reinterpret:
319 case CT_Dynamic:
320 return false;
321
322 // These do.
323 case CT_Static:
324 case CT_CStyle:
325 case CT_Functional:
326 break;
327 }
328
329 QualType srcType = src->getType();
330 if (!destType->isRecordType() && !srcType->isRecordType())
331 return false;
332
333 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
334 InitializationKind initKind
John McCallf85e1932011-06-15 23:02:42 +0000335 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000336 range, listInitialization)
Sebastian Redl3a45c0e2012-02-12 16:37:36 +0000337 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000338 listInitialization)
Richard Smithc8d7f582011-11-29 22:48:16 +0000339 : InitializationKind::CreateCast(/*type range?*/ range);
Dmitri Gribenko1f78a502013-05-03 15:05:50 +0000340 InitializationSequence sequence(S, entity, initKind, src);
John McCall79ab2c82011-02-14 18:34:10 +0000341
Sebastian Redl383616c2011-06-05 12:23:28 +0000342 assert(sequence.Failed() && "initialization succeeded on second try?");
John McCall79ab2c82011-02-14 18:34:10 +0000343 switch (sequence.getFailureKind()) {
344 default: return false;
345
346 case InitializationSequence::FK_ConstructorOverloadFailed:
347 case InitializationSequence::FK_UserConversionOverloadFailed:
348 break;
349 }
350
351 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
352
353 unsigned msg = 0;
354 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
355
356 switch (sequence.getFailedOverloadResult()) {
357 case OR_Success: llvm_unreachable("successful failed overload");
John McCall79ab2c82011-02-14 18:34:10 +0000358 case OR_No_Viable_Function:
359 if (candidates.empty())
360 msg = diag::err_ovl_no_conversion_in_cast;
361 else
362 msg = diag::err_ovl_no_viable_conversion_in_cast;
363 howManyCandidates = OCD_AllCandidates;
364 break;
365
366 case OR_Ambiguous:
367 msg = diag::err_ovl_ambiguous_conversion_in_cast;
368 howManyCandidates = OCD_ViableCandidates;
369 break;
370
371 case OR_Deleted:
372 msg = diag::err_ovl_deleted_conversion_in_cast;
373 howManyCandidates = OCD_ViableCandidates;
374 break;
375 }
376
377 S.Diag(range.getBegin(), msg)
378 << CT << srcType << destType
379 << range << src->getSourceRange();
380
Ahmed Charles13a140c2012-02-25 11:00:22 +0000381 candidates.NoteCandidates(S, howManyCandidates, src);
John McCall79ab2c82011-02-14 18:34:10 +0000382
383 return true;
384}
385
386/// Diagnose a failed cast.
387static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000388 SourceRange opRange, Expr *src, QualType destType,
389 bool listInitialization) {
John McCall79ab2c82011-02-14 18:34:10 +0000390 if (msg == diag::err_bad_cxx_cast_generic &&
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000391 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
392 listInitialization))
John McCall79ab2c82011-02-14 18:34:10 +0000393 return;
394
395 S.Diag(opRange.getBegin(), msg) << castType
396 << src->getType() << destType << opRange << src->getSourceRange();
397}
398
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000399/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
400/// this removes one level of indirection from both types, provided that they're
401/// the same kind of pointer (plain or to-member). Unlike the Sema function,
402/// this one doesn't care if the two pointers-to-member don't point into the
403/// same class. This is because CastsAwayConstness doesn't care.
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000404static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000405 const PointerType *T1PtrType = T1->getAs<PointerType>(),
406 *T2PtrType = T2->getAs<PointerType>();
407 if (T1PtrType && T2PtrType) {
408 T1 = T1PtrType->getPointeeType();
409 T2 = T2PtrType->getPointeeType();
410 return true;
411 }
Fariborz Jahanian72a86592010-02-03 20:32:31 +0000412 const ObjCObjectPointerType *T1ObjCPtrType =
413 T1->getAs<ObjCObjectPointerType>(),
414 *T2ObjCPtrType =
415 T2->getAs<ObjCObjectPointerType>();
416 if (T1ObjCPtrType) {
417 if (T2ObjCPtrType) {
418 T1 = T1ObjCPtrType->getPointeeType();
419 T2 = T2ObjCPtrType->getPointeeType();
420 return true;
421 }
422 else if (T2PtrType) {
423 T1 = T1ObjCPtrType->getPointeeType();
424 T2 = T2PtrType->getPointeeType();
425 return true;
426 }
427 }
428 else if (T2ObjCPtrType) {
429 if (T1PtrType) {
430 T2 = T2ObjCPtrType->getPointeeType();
431 T1 = T1PtrType->getPointeeType();
432 return true;
433 }
434 }
435
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000436 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
437 *T2MPType = T2->getAs<MemberPointerType>();
438 if (T1MPType && T2MPType) {
439 T1 = T1MPType->getPointeeType();
440 T2 = T2MPType->getPointeeType();
441 return true;
442 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000443
444 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
445 *T2BPType = T2->getAs<BlockPointerType>();
446 if (T1BPType && T2BPType) {
447 T1 = T1BPType->getPointeeType();
448 T2 = T2BPType->getPointeeType();
449 return true;
450 }
451
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000452 return false;
453}
454
Sebastian Redldb647282009-01-27 23:18:31 +0000455/// CastsAwayConstness - Check if the pointer conversion from SrcType to
456/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
457/// the cast checkers. Both arguments must denote pointer (possibly to member)
458/// types.
John McCallf85e1932011-06-15 23:02:42 +0000459///
460/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
461///
462/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000463static bool
John McCallf85e1932011-06-15 23:02:42 +0000464CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
465 bool CheckCVR, bool CheckObjCLifetime) {
466 // If the only checking we care about is for Objective-C lifetime qualifiers,
467 // and we're not in ARC mode, there's nothing to check.
468 if (!CheckCVR && CheckObjCLifetime &&
David Blaikie4e4d0842012-03-11 07:00:24 +0000469 !Self.Context.getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +0000470 return false;
471
Sebastian Redldb647282009-01-27 23:18:31 +0000472 // Casting away constness is defined in C++ 5.2.11p8 with reference to
473 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
474 // the rules are non-trivial. So first we construct Tcv *...cv* as described
475 // in C++ 5.2.11p8.
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000476 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
477 SrcType->isBlockPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000478 "Source type is not pointer or pointer to member.");
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000479 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
480 DestType->isBlockPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000481 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000482
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000483 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
484 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000485 SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000486
Douglas Gregord4c5f842011-04-15 17:59:54 +0000487 // Find the qualifiers. We only care about cvr-qualifiers for the
488 // purpose of this check, because other qualifiers (address spaces,
489 // Objective-C GC, etc.) are part of the type's identity.
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000490 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCallf85e1932011-06-15 23:02:42 +0000491 // Determine the relevant qualifiers at this level.
492 Qualifiers SrcQuals, DestQuals;
Anders Carlsson52647c62010-06-04 22:47:55 +0000493 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
Anders Carlsson52647c62010-06-04 22:47:55 +0000494 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
John McCallf85e1932011-06-15 23:02:42 +0000495
496 Qualifiers RetainedSrcQuals, RetainedDestQuals;
497 if (CheckCVR) {
498 RetainedSrcQuals.setCVRQualifiers(SrcQuals.getCVRQualifiers());
499 RetainedDestQuals.setCVRQualifiers(DestQuals.getCVRQualifiers());
500 }
501
502 if (CheckObjCLifetime &&
503 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
504 return true;
505
506 cv1.push_back(RetainedSrcQuals);
507 cv2.push_back(RetainedDestQuals);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000508 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000509 if (cv1.empty())
510 return false;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000511
512 // Construct void pointers with those qualifiers (in reverse order of
513 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000514 QualType SrcConstruct = Self.Context.VoidTy;
515 QualType DestConstruct = Self.Context.VoidTy;
John McCall0953e762009-09-24 19:53:00 +0000516 ASTContext &Context = Self.Context;
Craig Topper163fbf82013-07-08 03:55:09 +0000517 for (SmallVectorImpl<Qualifiers>::reverse_iterator i1 = cv1.rbegin(),
518 i2 = cv2.rbegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000519 i1 != cv1.rend(); ++i1, ++i2) {
John McCall0953e762009-09-24 19:53:00 +0000520 SrcConstruct
521 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
522 DestConstruct
523 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000524 }
525
526 // Test if they're compatible.
John McCallf85e1932011-06-15 23:02:42 +0000527 bool ObjCLifetimeConversion;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000528 return SrcConstruct != DestConstruct &&
John McCallf85e1932011-06-15 23:02:42 +0000529 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false,
530 ObjCLifetimeConversion);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000531}
532
Sebastian Redl26d85b12008-11-05 21:50:06 +0000533/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
534/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
535/// checked downcasts in class hierarchies.
John McCallb45ae252011-10-05 07:41:44 +0000536void CastOperation::CheckDynamicCast() {
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000537 if (ValueKind == VK_RValue)
Eli Friedman7a420df2011-10-31 20:59:03 +0000538 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000539 else if (isPlaceholder())
540 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
541 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
542 return;
Eli Friedman7a420df2011-10-31 20:59:03 +0000543
John McCallb45ae252011-10-05 07:41:44 +0000544 QualType OrigSrcType = SrcExpr.get()->getType();
545 QualType DestType = Self.Context.getCanonicalType(this->DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000546
547 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
548 // or "pointer to cv void".
549
550 QualType DestPointee;
Ted Kremenek6217b802009-07-29 21:53:49 +0000551 const PointerType *DestPointer = DestType->getAs<PointerType>();
John McCallf89e55a2010-11-18 06:31:45 +0000552 const ReferenceType *DestReference = 0;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000553 if (DestPointer) {
554 DestPointee = DestPointer->getPointeeType();
John McCallf89e55a2010-11-18 06:31:45 +0000555 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000556 DestPointee = DestReference->getPointeeType();
557 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000558 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
John McCallb45ae252011-10-05 07:41:44 +0000559 << this->DestType << DestRange;
Eli Friedman2437c862013-07-26 23:47:47 +0000560 SrcExpr = ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000561 return;
562 }
563
Ted Kremenek6217b802009-07-29 21:53:49 +0000564 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000565 if (DestPointee->isVoidType()) {
566 assert(DestPointer && "Reference to void is not possible");
567 } else if (DestRecord) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000568 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregord10099e2012-05-04 16:32:21 +0000569 diag::err_bad_dynamic_cast_incomplete,
Eli Friedman2437c862013-07-26 23:47:47 +0000570 DestRange)) {
571 SrcExpr = ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000572 return;
Eli Friedman2437c862013-07-26 23:47:47 +0000573 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000574 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000575 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000576 << DestPointee.getUnqualifiedType() << DestRange;
Eli Friedman2437c862013-07-26 23:47:47 +0000577 SrcExpr = ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000578 return;
579 }
580
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000581 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
582 // complete class type, [...]. If T is an lvalue reference type, v shall be
Douglas Gregordc843f22011-01-22 00:06:57 +0000583 // an lvalue of a complete class type, [...]. If T is an rvalue reference
584 // type, v shall be an expression having a complete class type, [...]
Sebastian Redl37d6de32008-11-08 13:00:26 +0000585 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000586 QualType SrcPointee;
587 if (DestPointer) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000588 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000589 SrcPointee = SrcPointer->getPointeeType();
590 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000591 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
John Wiegley429bb272011-04-08 18:41:53 +0000592 << OrigSrcType << SrcExpr.get()->getSourceRange();
Eli Friedman2437c862013-07-26 23:47:47 +0000593 SrcExpr = ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000594 return;
595 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000596 } else if (DestReference->isLValueReferenceType()) {
John Wiegley429bb272011-04-08 18:41:53 +0000597 if (!SrcExpr.get()->isLValue()) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000598 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
John McCallb45ae252011-10-05 07:41:44 +0000599 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000600 }
601 SrcPointee = SrcType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000602 } else {
603 SrcPointee = SrcType;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000604 }
605
Ted Kremenek6217b802009-07-29 21:53:49 +0000606 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000607 if (SrcRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000608 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregord10099e2012-05-04 16:32:21 +0000609 diag::err_bad_dynamic_cast_incomplete,
Eli Friedman2437c862013-07-26 23:47:47 +0000610 SrcExpr.get())) {
611 SrcExpr = ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000612 return;
Eli Friedman2437c862013-07-26 23:47:47 +0000613 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000614 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000615 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
John Wiegley429bb272011-04-08 18:41:53 +0000616 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Eli Friedman2437c862013-07-26 23:47:47 +0000617 SrcExpr = ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000618 return;
619 }
620
621 assert((DestPointer || DestReference) &&
622 "Bad destination non-ptr/ref slipped through.");
623 assert((DestRecord || DestPointee->isVoidType()) &&
624 "Bad destination pointee slipped through.");
625 assert(SrcRecord && "Bad source pointee slipped through.");
626
627 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
628 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +0000629 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
John McCallb45ae252011-10-05 07:41:44 +0000630 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
Eli Friedman2437c862013-07-26 23:47:47 +0000631 SrcExpr = ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000632 return;
633 }
634
635 // C++ 5.2.7p3: If the type of v is the same as the required result type,
636 // [except for cv].
637 if (DestRecord == SrcRecord) {
John McCall2de56d12010-08-25 11:45:40 +0000638 Kind = CK_NoOp;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000639 return;
640 }
641
642 // C++ 5.2.7p5
643 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000644 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000645 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
646 OpRange.getBegin(), OpRange,
Eli Friedman2437c862013-07-26 23:47:47 +0000647 &BasePath)) {
648 SrcExpr = ExprError();
649 return;
650 }
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000651
John McCall2de56d12010-08-25 11:45:40 +0000652 Kind = CK_DerivedToBase;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000653
654 // If we are casting to or through a virtual base class, we need a
655 // vtable.
656 if (Self.BasePathInvolvesVirtualBase(BasePath))
657 Self.MarkVTableUsed(OpRange.getBegin(),
658 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000659 return;
660 }
661
662 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor952b0172010-02-11 01:04:33 +0000663 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000664 assert(SrcDecl && "Definition missing");
665 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000666 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
John Wiegley429bb272011-04-08 18:41:53 +0000667 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Eli Friedman2437c862013-07-26 23:47:47 +0000668 SrcExpr = ExprError();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000669 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000670 Self.MarkVTableUsed(OpRange.getBegin(),
671 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000672
Eli Friedman01ae0932013-09-24 23:21:41 +0000673 // dynamic_cast is not available with -fno-rtti.
674 // As an exception, dynamic_cast to void* is available because it doesn't
675 // use RTTI.
676 if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) {
Arnaud A. de Grandmaison789d82a2013-08-01 08:28:32 +0000677 Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti);
678 SrcExpr = ExprError();
679 return;
680 }
681
Sebastian Redl26d85b12008-11-05 21:50:06 +0000682 // Done. Everything else is run-time checks.
John McCall2de56d12010-08-25 11:45:40 +0000683 Kind = CK_Dynamic;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000684}
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000685
686/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
687/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
688/// like this:
689/// const char *str = "literal";
690/// legacy_function(const_cast\<char*\>(str));
John McCallb45ae252011-10-05 07:41:44 +0000691void CastOperation::CheckConstCast() {
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000692 if (ValueKind == VK_RValue)
John Wiegley429bb272011-04-08 18:41:53 +0000693 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000694 else if (isPlaceholder())
695 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.take());
696 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
697 return;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000698
699 unsigned msg = diag::err_bad_cxx_cast_generic;
Richard Smith41cb3d92013-06-14 22:27:52 +0000700 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
Eli Friedman2437c862013-07-26 23:47:47 +0000701 && msg != 0) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000702 Self.Diag(OpRange.getBegin(), msg) << CT_Const
John Wiegley429bb272011-04-08 18:41:53 +0000703 << SrcExpr.get()->getType() << DestType << OpRange;
Eli Friedman2437c862013-07-26 23:47:47 +0000704 SrcExpr = ExprError();
705 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000706}
707
John McCall437da052013-03-22 02:58:14 +0000708/// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
709/// or downcast between respective pointers or references.
710static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
711 QualType DestType,
712 SourceRange OpRange) {
713 QualType SrcType = SrcExpr->getType();
714 // When casting from pointer or reference, get pointee type; use original
715 // type otherwise.
716 const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
717 const CXXRecordDecl *SrcRD =
718 SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
719
John McCallfdb468f2013-03-27 00:03:48 +0000720 // Examining subobjects for records is only possible if the complete and
721 // valid definition is available. Also, template instantiation is not
722 // allowed here.
723 if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
John McCall437da052013-03-22 02:58:14 +0000724 return;
725
726 const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
727
John McCallfdb468f2013-03-27 00:03:48 +0000728 if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
John McCall437da052013-03-22 02:58:14 +0000729 return;
730
731 enum {
732 ReinterpretUpcast,
733 ReinterpretDowncast
734 } ReinterpretKind;
735
736 CXXBasePaths BasePaths;
737
738 if (SrcRD->isDerivedFrom(DestRD, BasePaths))
739 ReinterpretKind = ReinterpretUpcast;
740 else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
741 ReinterpretKind = ReinterpretDowncast;
742 else
743 return;
744
745 bool VirtualBase = true;
746 bool NonZeroOffset = false;
John McCallfdb468f2013-03-27 00:03:48 +0000747 for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
John McCall437da052013-03-22 02:58:14 +0000748 E = BasePaths.end();
749 I != E; ++I) {
750 const CXXBasePath &Path = *I;
751 CharUnits Offset = CharUnits::Zero();
752 bool IsVirtual = false;
753 for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
754 IElem != EElem; ++IElem) {
755 IsVirtual = IElem->Base->isVirtual();
756 if (IsVirtual)
757 break;
758 const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
759 assert(BaseRD && "Base type should be a valid unqualified class type");
John McCallfdb468f2013-03-27 00:03:48 +0000760 // Don't check if any base has invalid declaration or has no definition
761 // since it has no layout info.
762 const CXXRecordDecl *Class = IElem->Class,
763 *ClassDefinition = Class->getDefinition();
764 if (Class->isInvalidDecl() || !ClassDefinition ||
765 !ClassDefinition->isCompleteDefinition())
766 return;
767
John McCall437da052013-03-22 02:58:14 +0000768 const ASTRecordLayout &DerivedLayout =
John McCallfdb468f2013-03-27 00:03:48 +0000769 Self.Context.getASTRecordLayout(Class);
John McCall437da052013-03-22 02:58:14 +0000770 Offset += DerivedLayout.getBaseClassOffset(BaseRD);
771 }
772 if (!IsVirtual) {
773 // Don't warn if any path is a non-virtually derived base at offset zero.
774 if (Offset.isZero())
775 return;
776 // Offset makes sense only for non-virtual bases.
777 else
778 NonZeroOffset = true;
779 }
780 VirtualBase = VirtualBase && IsVirtual;
781 }
782
Andy Gibbsde7afe02013-06-19 13:33:37 +0000783 (void) NonZeroOffset; // Silence set but not used warning.
John McCall437da052013-03-22 02:58:14 +0000784 assert((VirtualBase || NonZeroOffset) &&
785 "Should have returned if has non-virtual base with zero offset");
786
787 QualType BaseType =
788 ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
789 QualType DerivedType =
790 ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
791
Jordan Rose5fd1fac2013-03-28 19:09:40 +0000792 SourceLocation BeginLoc = OpRange.getBegin();
793 Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
Joerg Sonnenberger73484542013-06-26 21:31:47 +0000794 << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind)
Jordan Rose5fd1fac2013-03-28 19:09:40 +0000795 << OpRange;
796 Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
Joerg Sonnenberger73484542013-06-26 21:31:47 +0000797 << int(ReinterpretKind)
Jordan Rose5fd1fac2013-03-28 19:09:40 +0000798 << FixItHint::CreateReplacement(BeginLoc, "static_cast");
John McCall437da052013-03-22 02:58:14 +0000799}
800
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000801/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
802/// valid.
803/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
804/// like this:
805/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
John McCallb45ae252011-10-05 07:41:44 +0000806void CastOperation::CheckReinterpretCast() {
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000807 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
John Wiegley429bb272011-04-08 18:41:53 +0000808 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
Eli Friedmaned0b31f2012-01-12 00:44:34 +0000809 else
810 checkNonOverloadPlaceholders();
811 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
812 return;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000813
814 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCallf85e1932011-06-15 23:02:42 +0000815 TryCastResult tcr =
816 TryReinterpretCast(Self, SrcExpr, DestType,
817 /*CStyle*/false, OpRange, msg, Kind);
818 if (tcr != TC_Success && msg != 0)
Douglas Gregor8e960432010-11-08 03:40:48 +0000819 {
John Wiegley429bb272011-04-08 18:41:53 +0000820 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
821 return;
822 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor8e960432010-11-08 03:40:48 +0000823 //FIXME: &f<int>; is overloaded and resolvable
824 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
John Wiegley429bb272011-04-08 18:41:53 +0000825 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
Douglas Gregor8e960432010-11-08 03:40:48 +0000826 << DestType << OpRange;
John Wiegley429bb272011-04-08 18:41:53 +0000827 Self.NoteAllOverloadCandidates(SrcExpr.get());
Douglas Gregor8e960432010-11-08 03:40:48 +0000828
John McCall79ab2c82011-02-14 18:34:10 +0000829 } else {
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000830 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
831 DestType, /*listInitialization=*/false);
Douglas Gregor8e960432010-11-08 03:40:48 +0000832 }
Eli Friedman2437c862013-07-26 23:47:47 +0000833 SrcExpr = ExprError();
John McCall437da052013-03-22 02:58:14 +0000834 } else if (tcr == TC_Success) {
835 if (Self.getLangOpts().ObjCAutoRefCount)
836 checkObjCARCConversion(Sema::CCK_OtherCast);
837 DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
John McCallf85e1932011-06-15 23:02:42 +0000838 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000839}
840
841
842/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
843/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
844/// implicit conversions explicit and getting rid of data loss warnings.
Richard Smithc8d7f582011-11-29 22:48:16 +0000845void CastOperation::CheckStaticCast() {
John McCalla180f042011-10-06 23:25:11 +0000846 if (isPlaceholder()) {
847 checkNonOverloadPlaceholders();
848 if (SrcExpr.isInvalid())
849 return;
850 }
851
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000852 // This test is outside everything else because it's the only case where
853 // a non-lvalue-reference target type does not lead to decay.
854 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000855 if (DestType->isVoidType()) {
John McCalla180f042011-10-06 23:25:11 +0000856 Kind = CK_ToVoid;
857
858 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall6dbba4f2011-10-11 23:14:30 +0000859 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000860 false, // Decay Function to ptr
861 true, // Complain
862 OpRange, DestType, diag::err_bad_static_cast_overload);
John McCall6dbba4f2011-10-11 23:14:30 +0000863 if (SrcExpr.isInvalid())
864 return;
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000865 }
John McCalla180f042011-10-06 23:25:11 +0000866
867 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000868 return;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000869 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000870
John McCall6dbba4f2011-10-11 23:14:30 +0000871 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
872 !isPlaceholder(BuiltinType::Overload)) {
John Wiegley429bb272011-04-08 18:41:53 +0000873 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
874 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
875 return;
876 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000877
878 unsigned msg = diag::err_bad_cxx_cast_generic;
John McCallf85e1932011-06-15 23:02:42 +0000879 TryCastResult tcr
Richard Smithc8d7f582011-11-29 22:48:16 +0000880 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000881 Kind, BasePath, /*ListInitialization=*/false);
John McCallf85e1932011-06-15 23:02:42 +0000882 if (tcr != TC_Success && msg != 0) {
John Wiegley429bb272011-04-08 18:41:53 +0000883 if (SrcExpr.isInvalid())
884 return;
885 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
886 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
Douglas Gregor8e960432010-11-08 03:40:48 +0000887 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
Douglas Gregor4c9be892011-02-28 20:01:57 +0000888 << oe->getName() << DestType << OpRange
889 << oe->getQualifierLoc().getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +0000890 Self.NoteAllOverloadCandidates(SrcExpr.get());
John McCall79ab2c82011-02-14 18:34:10 +0000891 } else {
Sebastian Redl20ff0e22012-02-13 19:55:43 +0000892 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
893 /*listInitialization=*/false);
Douglas Gregor8e960432010-11-08 03:40:48 +0000894 }
Eli Friedman2437c862013-07-26 23:47:47 +0000895 SrcExpr = ExprError();
John McCallf85e1932011-06-15 23:02:42 +0000896 } else if (tcr == TC_Success) {
897 if (Kind == CK_BitCast)
John McCallb45ae252011-10-05 07:41:44 +0000898 checkCastAlign();
David Blaikie4e4d0842012-03-11 07:00:24 +0000899 if (Self.getLangOpts().ObjCAutoRefCount)
Richard Smithc8d7f582011-11-29 22:48:16 +0000900 checkObjCARCConversion(Sema::CCK_OtherCast);
John McCallb45ae252011-10-05 07:41:44 +0000901 } else if (Kind == CK_BitCast) {
902 checkCastAlign();
Douglas Gregor8e960432010-11-08 03:40:48 +0000903 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000904}
905
906/// TryStaticCast - Check if a static cast can be performed, and do so if
907/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
908/// and casting away constness.
John Wiegley429bb272011-04-08 18:41:53 +0000909static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
John McCallf85e1932011-06-15 23:02:42 +0000910 QualType DestType,
911 Sema::CheckedConversionKind CCK,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000912 const SourceRange &OpRange, unsigned &msg,
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000913 CastKind &Kind, CXXCastPath &BasePath,
914 bool ListInitialization) {
John McCallf85e1932011-06-15 23:02:42 +0000915 // Determine whether we have the semantics of a C-style cast.
916 bool CStyle
917 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
918
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000919 // The order the tests is not entirely arbitrary. There is one conversion
920 // that can be handled in two different ways. Given:
921 // struct A {};
922 // struct B : public A {
923 // B(); B(const A&);
924 // };
925 // const A &a = B();
926 // the cast static_cast<const B&>(a) could be seen as either a static
927 // reference downcast, or an explicit invocation of the user-defined
928 // conversion using B's conversion constructor.
929 // DR 427 specifies that the downcast is to be applied here.
930
931 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
932 // Done outside this function.
933
934 TryCastResult tcr;
935
936 // C++ 5.2.9p5, reference downcast.
937 // See the function for details.
938 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000939 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
940 OpRange, msg, Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000941 if (tcr != TC_NotApplicable)
942 return tcr;
943
Douglas Gregordc843f22011-01-22 00:06:57 +0000944 // C++0x [expr.static.cast]p3:
945 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
946 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000947 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
948 BasePath, msg);
Douglas Gregor88b22a42011-01-25 16:13:26 +0000949 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000950 return tcr;
951
952 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
953 // [...] if the declaration "T t(e);" is well-formed, [...].
John McCallf85e1932011-06-15 23:02:42 +0000954 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
Sebastian Redl6dc00f62012-02-12 18:41:05 +0000955 Kind, ListInitialization);
John Wiegley429bb272011-04-08 18:41:53 +0000956 if (SrcExpr.isInvalid())
957 return TC_Failed;
Anders Carlsson3c31a392009-09-26 00:12:34 +0000958 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000959 return tcr;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000960
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000961 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
962 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
963 // conversions, subject to further restrictions.
964 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
965 // of qualification conversions impossible.
966 // In the CStyle case, the earlier attempt to const_cast should have taken
967 // care of reverse qualification conversions.
968
John Wiegley429bb272011-04-08 18:41:53 +0000969 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000970
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000971 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
Douglas Gregor1e856d92011-02-18 03:01:41 +0000972 // converted to an integral type. [...] A value of a scoped enumeration type
973 // can also be explicitly converted to a floating-point type [...].
974 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
975 if (Enum->getDecl()->isScoped()) {
976 if (DestType->isBooleanType()) {
977 Kind = CK_IntegralToBoolean;
978 return TC_Success;
979 } else if (DestType->isIntegralType(Self.Context)) {
980 Kind = CK_IntegralCast;
981 return TC_Success;
982 } else if (DestType->isRealFloatingType()) {
983 Kind = CK_IntegralToFloating;
984 return TC_Success;
985 }
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000986 }
987 }
Douglas Gregor1e856d92011-02-18 03:01:41 +0000988
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000989 // Reverse integral promotion/conversion. All such conversions are themselves
990 // again integral promotions or conversions and are thus already handled by
991 // p2 (TryDirectInitialization above).
992 // (Note: any data loss warnings should be suppressed.)
993 // The exception is the reverse of enum->integer, i.e. integer->enum (and
994 // enum->enum). See also C++ 5.2.9p7.
995 // The same goes for reverse floating point promotion/conversion and
996 // floating-integral conversions. Again, only floating->enum is relevant.
997 if (DestType->isEnumeralType()) {
Eli Friedmancc2fca22011-09-02 17:38:59 +0000998 if (SrcType->isIntegralOrEnumerationType()) {
John McCall2de56d12010-08-25 11:45:40 +0000999 Kind = CK_IntegralCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001000 return TC_Success;
Eli Friedmancc2fca22011-09-02 17:38:59 +00001001 } else if (SrcType->isRealFloatingType()) {
1002 Kind = CK_FloatingToIntegral;
1003 return TC_Success;
Eli Friedman05d9d7a2009-11-16 05:44:20 +00001004 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001005 }
1006
1007 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
1008 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson95c5d8a2009-11-12 16:53:16 +00001009 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001010 Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001011 if (tcr != TC_NotApplicable)
1012 return tcr;
1013
1014 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
1015 // conversion. C++ 5.2.9p9 has additional information.
1016 // DR54's access restrictions apply here also.
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001017 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssoncee22422010-04-24 19:22:20 +00001018 OpRange, msg, Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001019 if (tcr != TC_NotApplicable)
1020 return tcr;
1021
1022 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
1023 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
1024 // just the usual constness stuff.
Ted Kremenek6217b802009-07-29 21:53:49 +00001025 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001026 QualType SrcPointee = SrcPointer->getPointeeType();
1027 if (SrcPointee->isVoidType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001028 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001029 QualType DestPointee = DestPointer->getPointeeType();
1030 if (DestPointee->isIncompleteOrObjectType()) {
1031 // This is definitely the intended conversion, but it might fail due
John McCallf85e1932011-06-15 23:02:42 +00001032 // to a qualifier violation. Note that we permit Objective-C lifetime
1033 // and GC qualifier mismatches here.
1034 if (!CStyle) {
1035 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
1036 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
1037 DestPointeeQuals.removeObjCGCAttr();
1038 DestPointeeQuals.removeObjCLifetime();
1039 SrcPointeeQuals.removeObjCGCAttr();
1040 SrcPointeeQuals.removeObjCLifetime();
1041 if (DestPointeeQuals != SrcPointeeQuals &&
1042 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
1043 msg = diag::err_bad_cxx_cast_qualifiers_away;
1044 return TC_Failed;
1045 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001046 }
John McCall2de56d12010-08-25 11:45:40 +00001047 Kind = CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001048 return TC_Success;
1049 }
1050 }
Fariborz Jahanian2f6c5502010-05-10 23:46:53 +00001051 else if (DestType->isObjCObjectPointerType()) {
1052 // allow both c-style cast and static_cast of objective-c pointers as
1053 // they are pervasive.
John McCall1d9b3b22011-09-09 05:25:32 +00001054 Kind = CK_CPointerToObjCPointerCast;
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001055 return TC_Success;
1056 }
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +00001057 else if (CStyle && DestType->isBlockPointerType()) {
1058 // allow c-style cast of void * to block pointers.
John McCall2de56d12010-08-25 11:45:40 +00001059 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +00001060 return TC_Success;
1061 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001062 }
1063 }
Fariborz Jahanian65267b22010-05-12 18:16:59 +00001064 // Allow arbitray objective-c pointer conversion with static casts.
1065 if (SrcType->isObjCObjectPointerType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001066 DestType->isObjCObjectPointerType()) {
1067 Kind = CK_BitCast;
Fariborz Jahanian65267b22010-05-12 18:16:59 +00001068 return TC_Success;
John McCalldaa8e4e2010-11-15 09:13:47 +00001069 }
Fariborz Jahanian65267b22010-05-12 18:16:59 +00001070
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001071 // We tried everything. Everything! Nothing works! :-(
1072 return TC_NotApplicable;
1073}
1074
1075/// Tests whether a conversion according to N2844 is valid.
1076TryCastResult
1077TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Douglas Gregor8ec14e62011-01-26 21:04:06 +00001078 bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
1079 unsigned &msg) {
Douglas Gregordc843f22011-01-22 00:06:57 +00001080 // C++0x [expr.static.cast]p3:
1081 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
1082 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenek6217b802009-07-29 21:53:49 +00001083 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001084 if (!R)
1085 return TC_NotApplicable;
1086
Douglas Gregordc843f22011-01-22 00:06:57 +00001087 if (!SrcExpr->isGLValue())
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001088 return TC_NotApplicable;
1089
1090 // Because we try the reference downcast before this function, from now on
1091 // this is the only cast possibility, so we issue an error if we fail now.
1092 // FIXME: Should allow casting away constness if CStyle.
1093 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00001094 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00001095 bool ObjCLifetimeConversion;
Douglas Gregor8ec14e62011-01-26 21:04:06 +00001096 QualType FromType = SrcExpr->getType();
1097 QualType ToType = R->getPointeeType();
1098 if (CStyle) {
1099 FromType = FromType.getUnqualifiedType();
1100 ToType = ToType.getUnqualifiedType();
1101 }
1102
Douglas Gregor393896f2009-11-05 13:06:35 +00001103 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
Douglas Gregor8ec14e62011-01-26 21:04:06 +00001104 ToType, FromType,
John McCallf85e1932011-06-15 23:02:42 +00001105 DerivedToBase, ObjCConversion,
1106 ObjCLifetimeConversion)
1107 < Sema::Ref_Compatible_With_Added_Qualification) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001108 msg = diag::err_bad_lvalue_to_rvalue_cast;
1109 return TC_Failed;
1110 }
1111
Douglas Gregor88b22a42011-01-25 16:13:26 +00001112 if (DerivedToBase) {
1113 Kind = CK_DerivedToBase;
1114 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1115 /*DetectVirtual=*/true);
1116 if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
1117 return TC_NotApplicable;
1118
1119 Self.BuildBasePathArray(Paths, BasePath);
1120 } else
1121 Kind = CK_NoOp;
1122
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001123 return TC_Success;
1124}
1125
1126/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1127TryCastResult
1128TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
1129 bool CStyle, const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +00001130 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001131 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001132 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1133 // cast to type "reference to cv2 D", where D is a class derived from B,
1134 // if a valid standard conversion from "pointer to D" to "pointer to B"
1135 // exists, cv2 >= cv1, and B is not a virtual base class of D.
1136 // In addition, DR54 clarifies that the base must be accessible in the
1137 // current context. Although the wording of DR54 only applies to the pointer
1138 // variant of this rule, the intent is clearly for it to apply to the this
1139 // conversion as well.
1140
Ted Kremenek6217b802009-07-29 21:53:49 +00001141 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001142 if (!DestReference) {
1143 return TC_NotApplicable;
1144 }
1145 bool RValueRef = DestReference->isRValueReferenceType();
John McCall7eb0a9e2010-11-24 05:12:34 +00001146 if (!RValueRef && !SrcExpr->isLValue()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001147 // We know the left side is an lvalue reference, so we can suggest a reason.
1148 msg = diag::err_bad_cxx_cast_rvalue;
1149 return TC_NotApplicable;
1150 }
1151
1152 QualType DestPointee = DestReference->getPointeeType();
1153
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001154 return TryStaticDowncast(Self,
1155 Self.Context.getCanonicalType(SrcExpr->getType()),
1156 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001157 OpRange, SrcExpr->getType(), DestType, msg, Kind,
1158 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001159}
1160
1161/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1162TryCastResult
1163TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +00001164 bool CStyle, const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +00001165 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001166 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001167 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1168 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1169 // is a class derived from B, if a valid standard conversion from "pointer
1170 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1171 // class of D.
1172 // In addition, DR54 clarifies that the base must be accessible in the
1173 // current context.
1174
Ted Kremenek6217b802009-07-29 21:53:49 +00001175 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001176 if (!DestPointer) {
1177 return TC_NotApplicable;
1178 }
1179
Ted Kremenek6217b802009-07-29 21:53:49 +00001180 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001181 if (!SrcPointer) {
1182 msg = diag::err_bad_static_cast_pointer_nonpointer;
1183 return TC_NotApplicable;
1184 }
1185
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001186 return TryStaticDowncast(Self,
1187 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1188 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001189 CStyle, OpRange, SrcType, DestType, msg, Kind,
1190 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001191}
1192
1193/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1194/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001195/// DestType is possible and allowed.
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001196TryCastResult
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001197TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001198 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +00001199 QualType OrigDestType, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +00001200 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl5ed66f72009-10-22 15:07:22 +00001201 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregord10099e2012-05-04 16:32:21 +00001202 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, 0) ||
1203 Self.RequireCompleteType(OpRange.getBegin(), DestType, 0))
Sebastian Redl5ed66f72009-10-22 15:07:22 +00001204 return TC_NotApplicable;
1205
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001206 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001207 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001208 return TC_NotApplicable;
1209 }
1210
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001211 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001212 /*DetectVirtual=*/true);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001213 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
1214 return TC_NotApplicable;
1215 }
1216
1217 // Target type does derive from source type. Now we're serious. If an error
1218 // appears now, it's not ignored.
1219 // This may not be entirely in line with the standard. Take for example:
1220 // struct A {};
1221 // struct B : virtual A {
1222 // B(A&);
1223 // };
Mike Stump1eb44332009-09-09 15:08:12 +00001224 //
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001225 // void f()
1226 // {
1227 // (void)static_cast<const B&>(*((A*)0));
1228 // }
1229 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1230 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1231 // However, both GCC and Comeau reject this example, and accepting it would
1232 // mean more complex code if we're to preserve the nice error message.
1233 // FIXME: Being 100% compliant here would be nice to have.
1234
1235 // Must preserve cv, as always, unless we're in C-style mode.
1236 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001237 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001238 return TC_Failed;
1239 }
1240
1241 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1242 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1243 // that it builds the paths in reverse order.
1244 // To sum up: record all paths to the base and build a nice string from
1245 // them. Use it to spice up the error message.
1246 if (!Paths.isRecordingPaths()) {
1247 Paths.clear();
1248 Paths.setRecordingPaths(true);
1249 Self.IsDerivedFrom(DestType, SrcType, Paths);
1250 }
1251 std::string PathDisplayStr;
1252 std::set<unsigned> DisplayedPaths;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001253 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001254 PI != PE; ++PI) {
1255 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
1256 // We haven't displayed a path to this particular base
1257 // class subobject yet.
1258 PathDisplayStr += "\n ";
Douglas Gregora8f32e02009-10-06 17:59:45 +00001259 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
1260 EE = PI->rend();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001261 EI != EE; ++EI)
1262 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001263 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001264 }
1265 }
1266
1267 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001268 << QualType(SrcType).getUnqualifiedType()
1269 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001270 << PathDisplayStr << OpRange;
1271 msg = 0;
1272 return TC_Failed;
1273 }
1274
1275 if (Paths.getDetectedVirtual() != 0) {
1276 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1277 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1278 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1279 msg = 0;
1280 return TC_Failed;
1281 }
1282
John McCall417d39f2011-02-14 23:21:33 +00001283 if (!CStyle) {
1284 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1285 SrcType, DestType,
1286 Paths.front(),
John McCall58e6f342010-03-16 05:22:47 +00001287 diag::err_downcast_from_inaccessible_base)) {
John McCall417d39f2011-02-14 23:21:33 +00001288 case Sema::AR_accessible:
1289 case Sema::AR_delayed: // be optimistic
1290 case Sema::AR_dependent: // be optimistic
1291 break;
1292
1293 case Sema::AR_inaccessible:
1294 msg = 0;
1295 return TC_Failed;
1296 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001297 }
1298
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001299 Self.BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00001300 Kind = CK_BaseToDerived;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001301 return TC_Success;
1302}
1303
1304/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1305/// C++ 5.2.9p9 is valid:
1306///
1307/// An rvalue of type "pointer to member of D of type cv1 T" can be
1308/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1309/// where B is a base class of D [...].
1310///
1311TryCastResult
John Wiegley429bb272011-04-08 18:41:53 +00001312TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001313 QualType DestType, bool CStyle,
1314 const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +00001315 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001316 CXXCastPath &BasePath) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001317 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001318 if (!DestMemPtr)
1319 return TC_NotApplicable;
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001320
1321 bool WasOverloadedFunction = false;
John McCall6bb80172010-03-30 21:47:33 +00001322 DeclAccessPair FoundOverload;
John Wiegley429bb272011-04-08 18:41:53 +00001323 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor1a8cf732010-04-14 23:11:21 +00001324 if (FunctionDecl *Fn
John Wiegley429bb272011-04-08 18:41:53 +00001325 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
Douglas Gregor1a8cf732010-04-14 23:11:21 +00001326 FoundOverload)) {
1327 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1328 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1329 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1330 WasOverloadedFunction = true;
1331 }
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001332 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00001333
Ted Kremenek6217b802009-07-29 21:53:49 +00001334 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001335 if (!SrcMemPtr) {
1336 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1337 return TC_NotApplicable;
1338 }
1339
1340 // T == T, modulo cv
Douglas Gregora4923eb2009-11-16 21:35:15 +00001341 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1342 DestMemPtr->getPointeeType()))
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001343 return TC_NotApplicable;
1344
1345 // B base of D
1346 QualType SrcClass(SrcMemPtr->getClass(), 0);
1347 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssoncee22422010-04-24 19:22:20 +00001348 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001349 /*DetectVirtual=*/true);
Stephen Hines651f13c2014-04-23 16:59:28 -07001350 if (Self.RequireCompleteType(OpRange.getBegin(), SrcClass, 0) ||
1351 !Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001352 return TC_NotApplicable;
1353 }
1354
1355 // B is a base of D. But is it an allowed base? If not, it's a hard error.
Douglas Gregore0d5fe22010-05-21 20:29:55 +00001356 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001357 Paths.clear();
1358 Paths.setRecordingPaths(true);
1359 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
1360 assert(StillOkay);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001361 (void)StillOkay;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001362 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1363 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1364 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1365 msg = 0;
1366 return TC_Failed;
1367 }
1368
1369 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1370 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1371 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1372 msg = 0;
1373 return TC_Failed;
1374 }
1375
John McCall417d39f2011-02-14 23:21:33 +00001376 if (!CStyle) {
1377 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1378 DestClass, SrcClass,
1379 Paths.front(),
1380 diag::err_upcast_to_inaccessible_base)) {
1381 case Sema::AR_accessible:
1382 case Sema::AR_delayed:
1383 case Sema::AR_dependent:
1384 // Optimistically assume that the delayed and dependent cases
1385 // will work out.
1386 break;
1387
1388 case Sema::AR_inaccessible:
1389 msg = 0;
1390 return TC_Failed;
1391 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001392 }
1393
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001394 if (WasOverloadedFunction) {
1395 // Resolve the address of the overloaded function again, this time
1396 // allowing complaints if something goes wrong.
John Wiegley429bb272011-04-08 18:41:53 +00001397 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001398 DestType,
John McCall6bb80172010-03-30 21:47:33 +00001399 true,
1400 FoundOverload);
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001401 if (!Fn) {
1402 msg = 0;
1403 return TC_Failed;
1404 }
1405
John McCall6bb80172010-03-30 21:47:33 +00001406 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
John Wiegley429bb272011-04-08 18:41:53 +00001407 if (!SrcExpr.isUsable()) {
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001408 msg = 0;
1409 return TC_Failed;
1410 }
1411 }
1412
Anders Carlssoncee22422010-04-24 19:22:20 +00001413 Self.BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00001414 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001415 return TC_Success;
1416}
1417
1418/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1419/// is valid:
1420///
1421/// An expression e can be explicitly converted to a type T using a
1422/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1423TryCastResult
John Wiegley429bb272011-04-08 18:41:53 +00001424TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCallf85e1932011-06-15 23:02:42 +00001425 Sema::CheckedConversionKind CCK,
1426 const SourceRange &OpRange, unsigned &msg,
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001427 CastKind &Kind, bool ListInitialization) {
Anders Carlssond851b372009-09-07 18:25:47 +00001428 if (DestType->isRecordType()) {
1429 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
Aaron Ballman21eb6d42012-05-07 00:02:00 +00001430 diag::err_bad_dynamic_cast_incomplete) ||
Eli Friedman860a3192012-06-16 02:19:17 +00001431 Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
Aaron Ballman21eb6d42012-05-07 00:02:00 +00001432 diag::err_allocation_of_abstract_type)) {
Anders Carlssond851b372009-09-07 18:25:47 +00001433 msg = 0;
1434 return TC_Failed;
1435 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001436 } else if (DestType->isMemberPointerType()) {
1437 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1438 Self.RequireCompleteType(OpRange.getBegin(), DestType, 0);
1439 }
Anders Carlssond851b372009-09-07 18:25:47 +00001440 }
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00001441
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001442 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1443 InitializationKind InitKind
John McCallf85e1932011-06-15 23:02:42 +00001444 = (CCK == Sema::CCK_CStyleCast)
Sebastian Redl3a45c0e2012-02-12 16:37:36 +00001445 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001446 ListInitialization)
John McCallf85e1932011-06-15 23:02:42 +00001447 : (CCK == Sema::CCK_FunctionalCast)
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001448 ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
Richard Smithc8d7f582011-11-29 22:48:16 +00001449 : InitializationKind::CreateCast(OpRange);
John Wiegley429bb272011-04-08 18:41:53 +00001450 Expr *SrcExprRaw = SrcExpr.get();
Dmitri Gribenko1f78a502013-05-03 15:05:50 +00001451 InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
Douglas Gregor8e960432010-11-08 03:40:48 +00001452
1453 // At this point of CheckStaticCast, if the destination is a reference,
1454 // or the expression is an overload expression this has to work.
1455 // There is no other way that works.
1456 // On the other hand, if we're checking a C-style cast, we've still got
1457 // the reinterpret_cast way.
John McCallf85e1932011-06-15 23:02:42 +00001458 bool CStyle
1459 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
Sebastian Redl383616c2011-06-05 12:23:28 +00001460 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
Anders Carlsson3c31a392009-09-26 00:12:34 +00001461 return TC_NotApplicable;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001462
Benjamin Kramer5354e772012-08-23 23:38:35 +00001463 ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001464 if (Result.isInvalid()) {
1465 msg = 0;
1466 return TC_Failed;
1467 }
1468
Douglas Gregord6e44a32010-04-16 22:09:46 +00001469 if (InitSeq.isConstructorInitialization())
John McCall2de56d12010-08-25 11:45:40 +00001470 Kind = CK_ConstructorConversion;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001471 else
John McCall2de56d12010-08-25 11:45:40 +00001472 Kind = CK_NoOp;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001473
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001474 SrcExpr = Result;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001475 return TC_Success;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001476}
1477
1478/// TryConstCast - See if a const_cast from source to destination is allowed,
1479/// and perform it if it is.
Richard Smith41cb3d92013-06-14 22:27:52 +00001480static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
1481 QualType DestType, bool CStyle,
1482 unsigned &msg) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001483 DestType = Self.Context.getCanonicalType(DestType);
Richard Smith41cb3d92013-06-14 22:27:52 +00001484 QualType SrcType = SrcExpr.get()->getType();
1485 bool NeedToMaterializeTemporary = false;
1486
Douglas Gregor575d2a32011-01-22 00:19:52 +00001487 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
Richard Smith41cb3d92013-06-14 22:27:52 +00001488 // C++11 5.2.11p4:
1489 // if a pointer to T1 can be explicitly converted to the type "pointer to
1490 // T2" using a const_cast, then the following conversions can also be
1491 // made:
1492 // -- an lvalue of type T1 can be explicitly converted to an lvalue of
1493 // type T2 using the cast const_cast<T2&>;
1494 // -- a glvalue of type T1 can be explicitly converted to an xvalue of
1495 // type T2 using the cast const_cast<T2&&>; and
1496 // -- if T1 is a class type, a prvalue of type T1 can be explicitly
1497 // converted to an xvalue of type T2 using the cast const_cast<T2&&>.
1498
1499 if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001500 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1501 // is C-style, static_cast might find a way, so we simply suggest a
1502 // message and tell the parent to keep searching.
1503 msg = diag::err_bad_cxx_cast_rvalue;
1504 return TC_NotApplicable;
1505 }
1506
Richard Smith41cb3d92013-06-14 22:27:52 +00001507 if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) {
1508 if (!SrcType->isRecordType()) {
1509 // Cannot const_cast non-class prvalue to rvalue reference type. But if
1510 // this is C-style, static_cast can do this.
1511 msg = diag::err_bad_cxx_cast_rvalue;
1512 return TC_NotApplicable;
1513 }
1514
1515 // Materialize the class prvalue so that the const_cast can bind a
1516 // reference to it.
1517 NeedToMaterializeTemporary = true;
1518 }
1519
John McCall993f43f2013-05-06 21:39:12 +00001520 // It's not completely clear under the standard whether we can
1521 // const_cast bit-field gl-values. Doing so would not be
1522 // intrinsically complicated, but for now, we say no for
1523 // consistency with other compilers and await the word of the
1524 // committee.
Richard Smith41cb3d92013-06-14 22:27:52 +00001525 if (SrcExpr.get()->refersToBitField()) {
John McCall993f43f2013-05-06 21:39:12 +00001526 msg = diag::err_bad_cxx_cast_bitfield;
1527 return TC_NotApplicable;
1528 }
1529
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001530 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1531 SrcType = Self.Context.getPointerType(SrcType);
1532 }
1533
1534 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1535 // the rules for const_cast are the same as those used for pointers.
1536
John McCalld425d2b2010-05-18 09:35:29 +00001537 if (!DestType->isPointerType() &&
1538 !DestType->isMemberPointerType() &&
1539 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001540 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1541 // was a reference type, we converted it to a pointer above.
1542 // The status of rvalue references isn't entirely clear, but it looks like
1543 // conversion to them is simply invalid.
1544 // C++ 5.2.11p3: For two pointer types [...]
1545 if (!CStyle)
1546 msg = diag::err_bad_const_cast_dest;
1547 return TC_NotApplicable;
1548 }
1549 if (DestType->isFunctionPointerType() ||
1550 DestType->isMemberFunctionPointerType()) {
1551 // Cannot cast direct function pointers.
1552 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1553 // T is the ultimate pointee of source and target type.
1554 if (!CStyle)
1555 msg = diag::err_bad_const_cast_dest;
1556 return TC_NotApplicable;
1557 }
1558 SrcType = Self.Context.getCanonicalType(SrcType);
1559
1560 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1561 // completely equal.
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001562 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1563 // in multi-level pointers may change, but the level count must be the same,
1564 // as must be the final pointee type.
1565 while (SrcType != DestType &&
Douglas Gregor5a57efd2010-06-09 03:53:18 +00001566 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001567 Qualifiers SrcQuals, DestQuals;
1568 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
1569 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
1570
1571 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
1572 // the other qualifiers (e.g., address spaces) are identical.
1573 SrcQuals.removeCVRQualifiers();
1574 DestQuals.removeCVRQualifiers();
1575 if (SrcQuals != DestQuals)
1576 return TC_NotApplicable;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001577 }
1578
1579 // Since we're dealing in canonical types, the remainder must be the same.
1580 if (SrcType != DestType)
1581 return TC_NotApplicable;
1582
Richard Smith41cb3d92013-06-14 22:27:52 +00001583 if (NeedToMaterializeTemporary)
1584 // This is a const_cast from a class prvalue to an rvalue reference type.
1585 // Materialize a temporary to store the result of the conversion.
1586 SrcExpr = new (Self.Context) MaterializeTemporaryExpr(
1587 SrcType, SrcExpr.take(), /*IsLValueReference*/ false,
1588 /*ExtendingDecl*/ 0);
1589
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001590 return TC_Success;
1591}
1592
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001593// Checks for undefined behavior in reinterpret_cast.
1594// The cases that is checked for is:
1595// *reinterpret_cast<T*>(&a)
1596// reinterpret_cast<T&>(a)
1597// where accessing 'a' as type 'T' will result in undefined behavior.
1598void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1599 bool IsDereference,
1600 SourceRange Range) {
1601 unsigned DiagID = IsDereference ?
1602 diag::warn_pointer_indirection_from_incompatible_type :
1603 diag::warn_undefined_reinterpret_cast;
1604
1605 if (Diags.getDiagnosticLevel(DiagID, Range.getBegin()) ==
David Blaikied6471f72011-09-25 23:23:43 +00001606 DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001607 return;
1608 }
1609
1610 QualType SrcTy, DestTy;
1611 if (IsDereference) {
1612 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1613 return;
1614 }
1615 SrcTy = SrcType->getPointeeType();
1616 DestTy = DestType->getPointeeType();
1617 } else {
1618 if (!DestType->getAs<ReferenceType>()) {
1619 return;
1620 }
1621 SrcTy = SrcType;
1622 DestTy = DestType->getPointeeType();
1623 }
1624
1625 // Cast is compatible if the types are the same.
1626 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1627 return;
1628 }
1629 // or one of the types is a char or void type
1630 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1631 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1632 return;
1633 }
1634 // or one of the types is a tag type.
Chandler Carruth1f8f2d52011-05-24 07:43:19 +00001635 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001636 return;
1637 }
1638
Douglas Gregor575a1c92011-05-20 16:38:50 +00001639 // FIXME: Scoped enums?
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001640 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1641 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1642 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1643 return;
1644 }
1645 }
1646
1647 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1648}
Douglas Gregorfadb53b2011-03-12 01:48:56 +00001649
Fariborz Jahanian91dd9df2012-08-16 18:33:47 +00001650static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
1651 QualType DestType) {
1652 QualType SrcType = SrcExpr.get()->getType();
Fariborz Jahanian0c252fa2012-12-13 00:42:06 +00001653 if (Self.Context.hasSameType(SrcType, DestType))
1654 return;
Fariborz Jahanian91dd9df2012-08-16 18:33:47 +00001655 if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
1656 if (SrcPtrTy->isObjCSelType()) {
1657 QualType DT = DestType;
1658 if (isa<PointerType>(DestType))
1659 DT = DestType->getPointeeType();
1660 if (!DT.getUnqualifiedType()->isVoidType())
1661 Self.Diag(SrcExpr.get()->getExprLoc(),
1662 diag::warn_cast_pointer_from_sel)
1663 << SrcType << DestType << SrcExpr.get()->getSourceRange();
1664 }
1665}
1666
David Blaikie9b29f4f2012-10-16 18:53:14 +00001667static void checkIntToPointerCast(bool CStyle, SourceLocation Loc,
1668 const Expr *SrcExpr, QualType DestType,
1669 Sema &Self) {
1670 QualType SrcType = SrcExpr->getType();
1671
1672 // Not warning on reinterpret_cast, boolean, constant expressions, etc
1673 // are not explicit design choices, but consistent with GCC's behavior.
1674 // Feel free to modify them if you've reason/evidence for an alternative.
1675 if (CStyle && SrcType->isIntegralType(Self.Context)
1676 && !SrcType->isBooleanType()
1677 && !SrcType->isEnumeralType()
1678 && !SrcExpr->isIntegerConstantExpr(Self.Context)
Ted Kremenek2628b442013-05-29 21:50:46 +00001679 && Self.Context.getTypeSize(DestType) >
1680 Self.Context.getTypeSize(SrcType)) {
1681 // Separate between casts to void* and non-void* pointers.
1682 // Some APIs use (abuse) void* for something like a user context,
1683 // and often that value is an integer even if it isn't a pointer itself.
1684 // Having a separate warning flag allows users to control the warning
1685 // for their workflow.
1686 unsigned Diag = DestType->isVoidPointerType() ?
1687 diag::warn_int_to_void_pointer_cast
1688 : diag::warn_int_to_pointer_cast;
1689 Self.Diag(Loc, Diag) << SrcType << DestType;
1690 }
David Blaikie9b29f4f2012-10-16 18:53:14 +00001691}
1692
John Wiegley429bb272011-04-08 18:41:53 +00001693static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001694 QualType DestType, bool CStyle,
1695 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +00001696 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +00001697 CastKind &Kind) {
Douglas Gregore39a3892010-07-13 23:17:26 +00001698 bool IsLValueCast = false;
1699
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001700 DestType = Self.Context.getCanonicalType(DestType);
John Wiegley429bb272011-04-08 18:41:53 +00001701 QualType SrcType = SrcExpr.get()->getType();
Douglas Gregor8e960432010-11-08 03:40:48 +00001702
1703 // Is the source an overloaded name? (i.e. &foo)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001704 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ...
1705 if (SrcType == Self.Context.OverloadTy) {
John McCall6dbba4f2011-10-11 23:14:30 +00001706 // ... unless foo<int> resolves to an lvalue unambiguously.
1707 // TODO: what if this fails because of DiagnoseUseOfDecl or something
1708 // like it?
1709 ExprResult SingleFunctionExpr = SrcExpr;
1710 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
1711 SingleFunctionExpr,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001712 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
John McCall6dbba4f2011-10-11 23:14:30 +00001713 ) && SingleFunctionExpr.isUsable()) {
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001714 SrcExpr = SingleFunctionExpr;
John Wiegley429bb272011-04-08 18:41:53 +00001715 SrcType = SrcExpr.get()->getType();
John McCall6dbba4f2011-10-11 23:14:30 +00001716 } else {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001717 return TC_NotApplicable;
John McCall6dbba4f2011-10-11 23:14:30 +00001718 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001719 }
Douglas Gregor8e960432010-11-08 03:40:48 +00001720
Ted Kremenek6217b802009-07-29 21:53:49 +00001721 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Richard Smith6850faf2012-04-29 08:24:44 +00001722 if (!SrcExpr.get()->isGLValue()) {
1723 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
1724 // similar comment in const_cast.
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001725 msg = diag::err_bad_cxx_cast_rvalue;
1726 return TC_NotApplicable;
1727 }
1728
Argyrios Kyrtzidisf4bbbf02011-05-02 18:21:19 +00001729 if (!CStyle) {
1730 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
1731 /*isDereference=*/false, OpRange);
1732 }
1733
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001734 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1735 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1736 // built-in & and * operators.
Argyrios Kyrtzidisb464a5b2011-04-22 22:31:13 +00001737
Argyrios Kyrtzidisbb29d1b2011-04-22 23:57:57 +00001738 const char *inappropriate = 0;
1739 switch (SrcExpr.get()->getObjectKind()) {
Argyrios Kyrtzidise5e3d312011-04-23 01:10:24 +00001740 case OK_Ordinary:
1741 break;
Argyrios Kyrtzidisbb29d1b2011-04-22 23:57:57 +00001742 case OK_BitField: inappropriate = "bit-field"; break;
1743 case OK_VectorComponent: inappropriate = "vector element"; break;
1744 case OK_ObjCProperty: inappropriate = "property expression"; break;
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001745 case OK_ObjCSubscript: inappropriate = "container subscripting expression";
1746 break;
Argyrios Kyrtzidisbb29d1b2011-04-22 23:57:57 +00001747 }
1748 if (inappropriate) {
1749 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
1750 << inappropriate << DestType
1751 << OpRange << SrcExpr.get()->getSourceRange();
1752 msg = 0; SrcExpr = ExprError();
Argyrios Kyrtzidisb464a5b2011-04-22 22:31:13 +00001753 return TC_NotApplicable;
1754 }
1755
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001756 // This code does this transformation for the checked types.
1757 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1758 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregor8e960432010-11-08 03:40:48 +00001759
Douglas Gregore39a3892010-07-13 23:17:26 +00001760 IsLValueCast = true;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001761 }
1762
1763 // Canonicalize source for comparison.
1764 SrcType = Self.Context.getCanonicalType(SrcType);
1765
Ted Kremenek6217b802009-07-29 21:53:49 +00001766 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1767 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001768 if (DestMemPtr && SrcMemPtr) {
1769 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1770 // can be explicitly converted to an rvalue of type "pointer to member
1771 // of Y of type T2" if T1 and T2 are both function types or both object
1772 // types.
1773 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1774 SrcMemPtr->getPointeeType()->isFunctionType())
1775 return TC_NotApplicable;
1776
1777 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1778 // constness.
1779 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1780 // we accept it.
John McCallf85e1932011-06-15 23:02:42 +00001781 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1782 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001783 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001784 return TC_Failed;
1785 }
1786
Stephen Hines651f13c2014-04-23 16:59:28 -07001787 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1788 // We need to determine the inheritance model that the class will use if
1789 // haven't yet.
1790 Self.RequireCompleteType(OpRange.getBegin(), SrcType, 0);
1791 Self.RequireCompleteType(OpRange.getBegin(), DestType, 0);
1792 }
1793
Charles Davisf231df32010-08-16 05:30:44 +00001794 // Don't allow casting between member pointers of different sizes.
1795 if (Self.Context.getTypeSize(DestMemPtr) !=
1796 Self.Context.getTypeSize(SrcMemPtr)) {
1797 msg = diag::err_bad_cxx_cast_member_pointer_size;
1798 return TC_Failed;
1799 }
1800
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001801 // A valid member pointer cast.
John McCall4d4e5c12012-02-15 01:22:51 +00001802 assert(!IsLValueCast);
1803 Kind = CK_ReinterpretMemberPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001804 return TC_Success;
1805 }
1806
1807 // See below for the enumeral issue.
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001808 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001809 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1810 // type large enough to hold it. A value of std::nullptr_t can be
1811 // converted to an integral type; the conversion has the same meaning
1812 // and validity as a conversion of (void*)0 to the integral type.
1813 if (Self.Context.getTypeSize(SrcType) >
1814 Self.Context.getTypeSize(DestType)) {
1815 msg = diag::err_bad_reinterpret_cast_small_int;
1816 return TC_Failed;
1817 }
John McCall2de56d12010-08-25 11:45:40 +00001818 Kind = CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001819 return TC_Success;
1820 }
1821
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001822 bool destIsVector = DestType->isVectorType();
1823 bool srcIsVector = SrcType->isVectorType();
1824 if (srcIsVector || destIsVector) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001825 // FIXME: Should this also apply to floating point types?
1826 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1827 bool destIsScalar = DestType->isIntegralType(Self.Context);
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001828
1829 // Check if this is a cast between a vector and something else.
1830 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1831 !(srcIsVector && destIsVector))
1832 return TC_NotApplicable;
1833
1834 // If both types have the same size, we can successfully cast.
Douglas Gregorf2a55392009-12-22 22:47:22 +00001835 if (Self.Context.getTypeSize(SrcType)
1836 == Self.Context.getTypeSize(DestType)) {
John McCall2de56d12010-08-25 11:45:40 +00001837 Kind = CK_BitCast;
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001838 return TC_Success;
Douglas Gregorf2a55392009-12-22 22:47:22 +00001839 }
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001840
1841 if (destIsScalar)
1842 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1843 else if (srcIsScalar)
1844 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1845 else
1846 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1847
1848 return TC_Failed;
1849 }
Chad Rosier41f44312012-02-03 02:54:37 +00001850
1851 if (SrcType == DestType) {
1852 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1853 // restrictions, a cast to the same type is allowed so long as it does not
1854 // cast away constness. In C++98, the intent was not entirely clear here,
1855 // since all other paragraphs explicitly forbid casts to the same type.
1856 // C++11 clarifies this case with p2.
1857 //
1858 // The only allowed types are: integral, enumeration, pointer, or
1859 // pointer-to-member types. We also won't restrict Obj-C pointers either.
1860 Kind = CK_NoOp;
1861 TryCastResult Result = TC_NotApplicable;
1862 if (SrcType->isIntegralOrEnumerationType() ||
1863 SrcType->isAnyPointerType() ||
1864 SrcType->isMemberPointerType() ||
1865 SrcType->isBlockPointerType()) {
1866 Result = TC_Success;
1867 }
1868 return Result;
1869 }
1870
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001871 bool destIsPtr = DestType->isAnyPointerType() ||
1872 DestType->isBlockPointerType();
1873 bool srcIsPtr = SrcType->isAnyPointerType() ||
1874 SrcType->isBlockPointerType();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001875 if (!destIsPtr && !srcIsPtr) {
1876 // Except for std::nullptr_t->integer and lvalue->reference, which are
1877 // handled above, at least one of the two arguments must be a pointer.
1878 return TC_NotApplicable;
1879 }
1880
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001881 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001882 assert(srcIsPtr && "One type must be a pointer");
1883 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
Francois Pichet30aff5b2011-05-11 22:13:54 +00001884 // type large enough to hold it; except in Microsoft mode, where the
Hans Wennborg649c6c52013-06-06 09:16:36 +00001885 // integral type size doesn't matter (except we don't allow bool).
1886 bool MicrosoftException = Self.getLangOpts().MicrosoftExt &&
1887 !DestType->isBooleanType();
Francois Pichet30aff5b2011-05-11 22:13:54 +00001888 if ((Self.Context.getTypeSize(SrcType) >
1889 Self.Context.getTypeSize(DestType)) &&
Hans Wennborg649c6c52013-06-06 09:16:36 +00001890 !MicrosoftException) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001891 msg = diag::err_bad_reinterpret_cast_small_int;
1892 return TC_Failed;
1893 }
John McCall2de56d12010-08-25 11:45:40 +00001894 Kind = CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001895 return TC_Success;
1896 }
1897
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001898 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001899 assert(destIsPtr && "One type must be a pointer");
David Blaikie9b29f4f2012-10-16 18:53:14 +00001900 checkIntToPointerCast(CStyle, OpRange.getBegin(), SrcExpr.get(), DestType,
1901 Self);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001902 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1903 // converted to a pointer.
John McCall404cd162010-11-13 01:35:44 +00001904 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1905 // necessarily converted to a null pointer value.]
John McCall2de56d12010-08-25 11:45:40 +00001906 Kind = CK_IntegralToPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001907 return TC_Success;
1908 }
1909
1910 if (!destIsPtr || !srcIsPtr) {
1911 // With the valid non-pointer conversions out of the way, we can be even
1912 // more stringent.
1913 return TC_NotApplicable;
1914 }
1915
1916 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1917 // The C-style cast operator can.
John McCallf85e1932011-06-15 23:02:42 +00001918 if (CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
1919 /*CheckObjCLifetime=*/CStyle)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001920 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001921 return TC_Failed;
1922 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001923
1924 // Cannot convert between block pointers and Objective-C object pointers.
1925 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1926 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1927 return TC_NotApplicable;
1928
John McCall1d9b3b22011-09-09 05:25:32 +00001929 if (IsLValueCast) {
1930 Kind = CK_LValueBitCast;
1931 } else if (DestType->isObjCObjectPointerType()) {
John McCalldc05b112011-09-10 01:16:55 +00001932 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
John McCall1d9b3b22011-09-09 05:25:32 +00001933 } else if (DestType->isBlockPointerType()) {
1934 if (!SrcType->isBlockPointerType()) {
1935 Kind = CK_AnyPointerToBlockPointerCast;
1936 } else {
1937 Kind = CK_BitCast;
1938 }
1939 } else {
1940 Kind = CK_BitCast;
1941 }
1942
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001943 // Any pointer can be cast to an Objective-C pointer type with a C-style
1944 // cast.
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001945 if (CStyle && DestType->isObjCObjectPointerType()) {
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001946 return TC_Success;
1947 }
Fariborz Jahanian91dd9df2012-08-16 18:33:47 +00001948 if (CStyle)
1949 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
1950
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001951 // Not casting away constness, so the only remaining check is for compatible
1952 // pointer categories.
1953
1954 if (SrcType->isFunctionPointerType()) {
1955 if (DestType->isFunctionPointerType()) {
1956 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1957 // a pointer to a function of a different type.
1958 return TC_Success;
1959 }
1960
1961 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1962 // an object type or vice versa is conditionally-supported.
1963 // Compilers support it in C++03 too, though, because it's necessary for
1964 // casting the return value of dlsym() and GetProcAddress().
1965 // FIXME: Conditionally-supported behavior should be configurable in the
1966 // TargetInfo or similar.
Richard Smithebaf0e62011-10-18 20:49:44 +00001967 Self.Diag(OpRange.getBegin(),
Richard Smith80ad52f2013-01-02 11:42:31 +00001968 Self.getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00001969 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
1970 << OpRange;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001971 return TC_Success;
1972 }
1973
1974 if (DestType->isFunctionPointerType()) {
1975 // See above.
Richard Smithebaf0e62011-10-18 20:49:44 +00001976 Self.Diag(OpRange.getBegin(),
Richard Smith80ad52f2013-01-02 11:42:31 +00001977 Self.getLangOpts().CPlusPlus11 ?
Richard Smithebaf0e62011-10-18 20:49:44 +00001978 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
1979 << OpRange;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001980 return TC_Success;
1981 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001982
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001983 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1984 // a pointer to an object of different type.
1985 // Void pointers are not specified, but supported by every compiler out there.
1986 // So we finish by allowing everything that remains - it's got to be two
1987 // object pointers.
1988 return TC_Success;
John McCall79ab2c82011-02-14 18:34:10 +00001989}
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001990
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001991void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
1992 bool ListInitialization) {
John McCalla180f042011-10-06 23:25:11 +00001993 // Handle placeholders.
1994 if (isPlaceholder()) {
1995 // C-style casts can resolve __unknown_any types.
1996 if (claimPlaceholder(BuiltinType::UnknownAny)) {
1997 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
1998 SrcExpr.get(), Kind,
1999 ValueKind, BasePath);
2000 return;
2001 }
John McCallb45ae252011-10-05 07:41:44 +00002002
John McCalla180f042011-10-06 23:25:11 +00002003 checkNonOverloadPlaceholders();
2004 if (SrcExpr.isInvalid())
2005 return;
John McCall4919dfd2011-10-17 17:42:19 +00002006 }
John McCalla180f042011-10-06 23:25:11 +00002007
2008 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002009 // This test is outside everything else because it's the only case where
2010 // a non-lvalue-reference target type does not lead to decay.
John McCallb45ae252011-10-05 07:41:44 +00002011 if (DestType->isVoidType()) {
John McCallfb8721c2011-04-10 19:13:55 +00002012 Kind = CK_ToVoid;
2013
John McCalla180f042011-10-06 23:25:11 +00002014 if (claimPlaceholder(BuiltinType::Overload)) {
John McCall6dbba4f2011-10-11 23:14:30 +00002015 Self.ResolveAndFixSingleFunctionTemplateSpecialization(
2016 SrcExpr, /* Decay Function to ptr */ false,
John McCallb45ae252011-10-05 07:41:44 +00002017 /* Complain */ true, DestRange, DestType,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00002018 diag::err_bad_cstyle_cast_overload);
John McCallb45ae252011-10-05 07:41:44 +00002019 if (SrcExpr.isInvalid())
2020 return;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00002021 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002022
John McCalla180f042011-10-06 23:25:11 +00002023 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
John McCallb45ae252011-10-05 07:41:44 +00002024 return;
Anton Yartsevd06fea82011-03-27 09:32:40 +00002025 }
2026
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002027 // If the type is dependent, we won't do any other semantic analysis now.
Eli Friedmanf91e86c2013-09-19 01:12:33 +00002028 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
2029 SrcExpr.get()->isValueDependent()) {
John McCallb45ae252011-10-05 07:41:44 +00002030 assert(Kind == CK_Dependent);
2031 return;
John McCalldaa8e4e2010-11-15 09:13:47 +00002032 }
Benjamin Kramer5b4a40a2011-07-08 20:20:17 +00002033
John McCall6dbba4f2011-10-11 23:14:30 +00002034 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
2035 !isPlaceholder(BuiltinType::Overload)) {
John McCallb45ae252011-10-05 07:41:44 +00002036 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
2037 if (SrcExpr.isInvalid())
2038 return;
John Wiegley429bb272011-04-08 18:41:53 +00002039 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002040
John McCallfb8721c2011-04-10 19:13:55 +00002041 // AltiVec vector initialization with a single literal.
John McCallb45ae252011-10-05 07:41:44 +00002042 if (const VectorType *vecTy = DestType->getAs<VectorType>())
John McCallfb8721c2011-04-10 19:13:55 +00002043 if (vecTy->getVectorKind() == VectorType::AltiVecVector
John McCallb45ae252011-10-05 07:41:44 +00002044 && (SrcExpr.get()->getType()->isIntegerType()
2045 || SrcExpr.get()->getType()->isFloatingType())) {
John McCallfb8721c2011-04-10 19:13:55 +00002046 Kind = CK_VectorSplat;
John McCallb45ae252011-10-05 07:41:44 +00002047 return;
John McCallfb8721c2011-04-10 19:13:55 +00002048 }
2049
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002050 // C++ [expr.cast]p5: The conversions performed by
2051 // - a const_cast,
2052 // - a static_cast,
2053 // - a static_cast followed by a const_cast,
2054 // - a reinterpret_cast, or
2055 // - a reinterpret_cast followed by a const_cast,
2056 // can be performed using the cast notation of explicit type conversion.
2057 // [...] If a conversion can be interpreted in more than one of the ways
2058 // listed above, the interpretation that appears first in the list is used,
2059 // even if a cast resulting from that interpretation is ill-formed.
2060 // In plain language, this means trying a const_cast ...
2061 unsigned msg = diag::err_bad_cxx_cast_generic;
Richard Smith41cb3d92013-06-14 22:27:52 +00002062 TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
John McCallb45ae252011-10-05 07:41:44 +00002063 /*CStyle*/true, msg);
Richard Smith41cb3d92013-06-14 22:27:52 +00002064 if (SrcExpr.isInvalid())
2065 return;
Anders Carlssonda921fd2009-10-19 18:14:28 +00002066 if (tcr == TC_Success)
John McCall2de56d12010-08-25 11:45:40 +00002067 Kind = CK_NoOp;
Anders Carlssonda921fd2009-10-19 18:14:28 +00002068
John McCallf85e1932011-06-15 23:02:42 +00002069 Sema::CheckedConversionKind CCK
2070 = FunctionalStyle? Sema::CCK_FunctionalCast
2071 : Sema::CCK_CStyleCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002072 if (tcr == TC_NotApplicable) {
2073 // ... or if that is not possible, a static_cast, ignoring const, ...
John McCallb45ae252011-10-05 07:41:44 +00002074 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange,
Sebastian Redl6dc00f62012-02-12 18:41:05 +00002075 msg, Kind, BasePath, ListInitialization);
John McCallb45ae252011-10-05 07:41:44 +00002076 if (SrcExpr.isInvalid())
2077 return;
2078
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002079 if (tcr == TC_NotApplicable) {
2080 // ... and finally a reinterpret_cast, ignoring const.
John McCallb45ae252011-10-05 07:41:44 +00002081 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/true,
2082 OpRange, msg, Kind);
2083 if (SrcExpr.isInvalid())
2084 return;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002085 }
2086 }
2087
David Blaikie4e4d0842012-03-11 07:00:24 +00002088 if (Self.getLangOpts().ObjCAutoRefCount && tcr == TC_Success)
John McCallb45ae252011-10-05 07:41:44 +00002089 checkObjCARCConversion(CCK);
Stephen Hines651f13c2014-04-23 16:59:28 -07002090 else if (Self.getLangOpts().ObjC1 && tcr == TC_Success)
2091 Self.CheckTollFreeBridgeCast(DestType, SrcExpr.get());
John McCallf85e1932011-06-15 23:02:42 +00002092
Nick Lewycky43328e92010-11-09 00:19:31 +00002093 if (tcr != TC_Success && msg != 0) {
John McCallb45ae252011-10-05 07:41:44 +00002094 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor8e960432010-11-08 03:40:48 +00002095 DeclAccessPair Found;
John McCallb45ae252011-10-05 07:41:44 +00002096 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
2097 DestType,
2098 /*Complain*/ true,
Douglas Gregor8e960432010-11-08 03:40:48 +00002099 Found);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00002100
Richard Trieu32ac00d2011-04-16 01:09:30 +00002101 assert(!Fn && "cast failed but able to resolve overload expression!!");
Nick Lewycky43328e92010-11-09 00:19:31 +00002102 (void)Fn;
John McCall79ab2c82011-02-14 18:34:10 +00002103
Nick Lewycky43328e92010-11-09 00:19:31 +00002104 } else {
John McCallb45ae252011-10-05 07:41:44 +00002105 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
Sebastian Redl20ff0e22012-02-13 19:55:43 +00002106 OpRange, SrcExpr.get(), DestType, ListInitialization);
Douglas Gregor8e960432010-11-08 03:40:48 +00002107 }
John McCallb45ae252011-10-05 07:41:44 +00002108 } else if (Kind == CK_BitCast) {
2109 checkCastAlign();
Douglas Gregor8e960432010-11-08 03:40:48 +00002110 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002111
John McCallb45ae252011-10-05 07:41:44 +00002112 // Clear out SrcExpr if there was a fatal error.
John Wiegley429bb272011-04-08 18:41:53 +00002113 if (tcr != TC_Success)
John McCallb45ae252011-10-05 07:41:44 +00002114 SrcExpr = ExprError();
2115}
2116
Fariborz Jahanianbbb8afd2012-08-17 17:22:34 +00002117/// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
2118/// non-matching type. Such as enum function call to int, int call to
2119/// pointer; etc. Cast to 'void' is an exception.
2120static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
2121 QualType DestType) {
2122 if (Self.Diags.getDiagnosticLevel(diag::warn_bad_function_cast,
2123 SrcExpr.get()->getExprLoc())
2124 == DiagnosticsEngine::Ignored)
2125 return;
2126
2127 if (!isa<CallExpr>(SrcExpr.get()))
2128 return;
2129
2130 QualType SrcType = SrcExpr.get()->getType();
2131 if (DestType.getUnqualifiedType()->isVoidType())
2132 return;
2133 if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
2134 && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
2135 return;
2136 if (SrcType->isIntegerType() && DestType->isIntegerType() &&
2137 (SrcType->isBooleanType() == DestType->isBooleanType()) &&
2138 (SrcType->isEnumeralType() == DestType->isEnumeralType()))
2139 return;
2140 if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
2141 return;
2142 if (SrcType->isEnumeralType() && DestType->isEnumeralType())
2143 return;
2144 if (SrcType->isComplexType() && DestType->isComplexType())
2145 return;
2146 if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
2147 return;
2148
2149 Self.Diag(SrcExpr.get()->getExprLoc(),
2150 diag::warn_bad_function_cast)
2151 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2152}
2153
John McCalla180f042011-10-06 23:25:11 +00002154/// Check the semantics of a C-style cast operation, in C.
2155void CastOperation::CheckCStyleCast() {
David Blaikie4e4d0842012-03-11 07:00:24 +00002156 assert(!Self.getLangOpts().CPlusPlus);
John McCalla180f042011-10-06 23:25:11 +00002157
John McCall5acb0c92011-10-17 18:40:02 +00002158 // C-style casts can resolve __unknown_any types.
2159 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2160 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2161 SrcExpr.get(), Kind,
2162 ValueKind, BasePath);
2163 return;
2164 }
John McCalla180f042011-10-06 23:25:11 +00002165
2166 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2167 // type needs to be scalar.
2168 if (DestType->isVoidType()) {
2169 // We don't necessarily do lvalue-to-rvalue conversions on this.
2170 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
2171 if (SrcExpr.isInvalid())
2172 return;
2173
2174 // Cast to void allows any expr type.
2175 Kind = CK_ToVoid;
2176 return;
2177 }
2178
2179 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
2180 if (SrcExpr.isInvalid())
2181 return;
2182 QualType SrcType = SrcExpr.get()->getType();
David Chisnall7a7ee302012-01-16 17:27:18 +00002183
John McCall5acb0c92011-10-17 18:40:02 +00002184 assert(!SrcType->isPlaceholderType());
John McCalla180f042011-10-06 23:25:11 +00002185
Stephen Hines651f13c2014-04-23 16:59:28 -07002186 // OpenCL v1 s6.5: Casting a pointer to address space A to a pointer to
2187 // address space B is illegal.
2188 if (Self.getLangOpts().OpenCL && DestType->isPointerType() &&
2189 SrcType->isPointerType()) {
2190 if (DestType->getPointeeType().getAddressSpace() !=
2191 SrcType->getPointeeType().getAddressSpace()) {
2192 Self.Diag(OpRange.getBegin(),
2193 diag::err_typecheck_incompatible_address_space)
2194 << SrcType << DestType << Sema::AA_Casting
2195 << SrcExpr.get()->getSourceRange();
2196 SrcExpr = ExprError();
2197 return;
2198 }
2199 }
2200
John McCalla180f042011-10-06 23:25:11 +00002201 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
2202 diag::err_typecheck_cast_to_incomplete)) {
2203 SrcExpr = ExprError();
2204 return;
2205 }
2206
2207 if (!DestType->isScalarType() && !DestType->isVectorType()) {
2208 const RecordType *DestRecordTy = DestType->getAs<RecordType>();
2209
2210 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
2211 // GCC struct/union extension: allow cast to self.
2212 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
2213 << DestType << SrcExpr.get()->getSourceRange();
2214 Kind = CK_NoOp;
2215 return;
2216 }
2217
2218 // GCC's cast to union extension.
2219 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
2220 RecordDecl *RD = DestRecordTy->getDecl();
2221 RecordDecl::field_iterator Field, FieldEnd;
2222 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2223 Field != FieldEnd; ++Field) {
2224 if (Self.Context.hasSameUnqualifiedType(Field->getType(), SrcType) &&
2225 !Field->isUnnamedBitfield()) {
2226 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
2227 << SrcExpr.get()->getSourceRange();
2228 break;
2229 }
2230 }
2231 if (Field == FieldEnd) {
2232 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2233 << SrcType << SrcExpr.get()->getSourceRange();
2234 SrcExpr = ExprError();
2235 return;
2236 }
2237 Kind = CK_ToUnion;
2238 return;
2239 }
2240
2241 // Reject any other conversions to non-scalar types.
2242 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
2243 << DestType << SrcExpr.get()->getSourceRange();
2244 SrcExpr = ExprError();
2245 return;
2246 }
2247
2248 // The type we're casting to is known to be a scalar or vector.
2249
2250 // Require the operand to be a scalar or vector.
2251 if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
2252 Self.Diag(SrcExpr.get()->getExprLoc(),
2253 diag::err_typecheck_expect_scalar_operand)
2254 << SrcType << SrcExpr.get()->getSourceRange();
2255 SrcExpr = ExprError();
2256 return;
2257 }
2258
2259 if (DestType->isExtVectorType()) {
2260 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.take(), Kind);
2261 return;
2262 }
2263
2264 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
2265 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
2266 (SrcType->isIntegerType() || SrcType->isFloatingType())) {
2267 Kind = CK_VectorSplat;
2268 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
2269 SrcExpr = ExprError();
2270 }
2271 return;
2272 }
2273
2274 if (SrcType->isVectorType()) {
2275 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
2276 SrcExpr = ExprError();
2277 return;
2278 }
2279
2280 // The source and target types are both scalars, i.e.
2281 // - arithmetic types (fundamental, enum, and complex)
2282 // - all kinds of pointers
2283 // Note that member pointers were filtered out with C++, above.
2284
2285 if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
2286 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
2287 SrcExpr = ExprError();
2288 return;
2289 }
2290
2291 // If either type is a pointer, the other type has to be either an
2292 // integer or a pointer.
2293 if (!DestType->isArithmeticType()) {
2294 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
2295 Self.Diag(SrcExpr.get()->getExprLoc(),
2296 diag::err_cast_pointer_from_non_pointer_int)
2297 << SrcType << SrcExpr.get()->getSourceRange();
2298 SrcExpr = ExprError();
2299 return;
2300 }
David Blaikie9b29f4f2012-10-16 18:53:14 +00002301 checkIntToPointerCast(/* CStyle */ true, OpRange.getBegin(), SrcExpr.get(),
2302 DestType, Self);
John McCalla180f042011-10-06 23:25:11 +00002303 } else if (!SrcType->isArithmeticType()) {
2304 if (!DestType->isIntegralType(Self.Context) &&
2305 DestType->isArithmeticType()) {
2306 Self.Diag(SrcExpr.get()->getLocStart(),
2307 diag::err_cast_pointer_to_non_pointer_int)
Abramo Bagnaraf7ce1942011-11-15 11:25:38 +00002308 << DestType << SrcExpr.get()->getSourceRange();
John McCalla180f042011-10-06 23:25:11 +00002309 SrcExpr = ExprError();
2310 return;
2311 }
2312 }
2313
Joey Gouly19dbb202013-01-23 11:56:20 +00002314 if (Self.getLangOpts().OpenCL && !Self.getOpenCLOptions().cl_khr_fp16) {
2315 if (DestType->isHalfType()) {
2316 Self.Diag(SrcExpr.get()->getLocStart(), diag::err_opencl_cast_to_half)
2317 << DestType << SrcExpr.get()->getSourceRange();
2318 SrcExpr = ExprError();
2319 return;
2320 }
Joey Gouly19dbb202013-01-23 11:56:20 +00002321 }
2322
John McCalla180f042011-10-06 23:25:11 +00002323 // ARC imposes extra restrictions on casts.
David Blaikie4e4d0842012-03-11 07:00:24 +00002324 if (Self.getLangOpts().ObjCAutoRefCount) {
John McCalla180f042011-10-06 23:25:11 +00002325 checkObjCARCConversion(Sema::CCK_CStyleCast);
2326 if (SrcExpr.isInvalid())
2327 return;
2328
2329 if (const PointerType *CastPtr = DestType->getAs<PointerType>()) {
2330 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
2331 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
2332 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
2333 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
2334 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
2335 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
2336 Self.Diag(SrcExpr.get()->getLocStart(),
2337 diag::err_typecheck_incompatible_ownership)
2338 << SrcType << DestType << Sema::AA_Casting
2339 << SrcExpr.get()->getSourceRange();
2340 return;
2341 }
2342 }
2343 }
2344 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
2345 Self.Diag(SrcExpr.get()->getLocStart(),
2346 diag::err_arc_convesion_of_weak_unavailable)
2347 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2348 SrcExpr = ExprError();
2349 return;
2350 }
2351 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002352 else if (Self.getLangOpts().ObjC1)
2353 Self.CheckTollFreeBridgeCast(DestType, SrcExpr.get());
2354
Fariborz Jahanian91dd9df2012-08-16 18:33:47 +00002355 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
Fariborz Jahanianbbb8afd2012-08-17 17:22:34 +00002356 DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
John McCalla180f042011-10-06 23:25:11 +00002357 Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2358 if (SrcExpr.isInvalid())
2359 return;
2360
2361 if (Kind == CK_BitCast)
2362 checkCastAlign();
2363}
2364
2365ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
2366 TypeSourceInfo *CastTypeInfo,
2367 SourceLocation RPLoc,
2368 Expr *CastExpr) {
John McCallb45ae252011-10-05 07:41:44 +00002369 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2370 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2371 Op.OpRange = SourceRange(LPLoc, CastExpr->getLocEnd());
2372
David Blaikie4e4d0842012-03-11 07:00:24 +00002373 if (getLangOpts().CPlusPlus) {
Sebastian Redl6dc00f62012-02-12 18:41:05 +00002374 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/ false,
2375 isa<InitListExpr>(CastExpr));
John McCalla180f042011-10-06 23:25:11 +00002376 } else {
2377 Op.CheckCStyleCast();
2378 }
2379
John McCallb45ae252011-10-05 07:41:44 +00002380 if (Op.SrcExpr.isInvalid())
John Wiegley429bb272011-04-08 18:41:53 +00002381 return ExprError();
2382
John McCall5acb0c92011-10-17 18:40:02 +00002383 return Op.complete(CStyleCastExpr::Create(Context, Op.ResultType,
2384 Op.ValueKind, Op.Kind, Op.SrcExpr.take(),
2385 &Op.BasePath, CastTypeInfo, LPLoc, RPLoc));
John McCallb45ae252011-10-05 07:41:44 +00002386}
2387
2388ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
2389 SourceLocation LPLoc,
2390 Expr *CastExpr,
2391 SourceLocation RPLoc) {
Sebastian Redl20ff0e22012-02-13 19:55:43 +00002392 assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
John McCallb45ae252011-10-05 07:41:44 +00002393 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
2394 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
2395 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getLocEnd());
2396
Sebastian Redl20ff0e22012-02-13 19:55:43 +00002397 Op.CheckCXXCStyleCast(/*FunctionalStyle=*/true, /*ListInit=*/false);
John McCallb45ae252011-10-05 07:41:44 +00002398 if (Op.SrcExpr.isInvalid())
2399 return ExprError();
Daniel Jaspera770a4d2012-07-16 08:05:07 +00002400
2401 if (CXXConstructExpr *ConstructExpr = dyn_cast<CXXConstructExpr>(Op.SrcExpr.get()))
Enea Zaffanella1245a542013-09-07 05:49:53 +00002402 ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc));
John McCallb45ae252011-10-05 07:41:44 +00002403
John McCall5acb0c92011-10-17 18:40:02 +00002404 return Op.complete(CXXFunctionalCastExpr::Create(Context, Op.ResultType,
Eli Friedmancdd4b782013-08-15 22:02:56 +00002405 Op.ValueKind, CastTypeInfo, Op.Kind,
2406 Op.SrcExpr.take(), &Op.BasePath, LPLoc, RPLoc));
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002407}