blob: 5b28bc3d9fdc7bdbced5df2d8d347babc5e2acc3 [file] [log] [blame]
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +00001//===--- SemaNamedCast.cpp - Semantic Analysis for Named Casts ------------===//
2//
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//
10// This file implements semantic analysis for C++ named casts.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000016#include "clang/AST/ExprCXX.h"
17#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlssond624e162009-08-26 23:45:07 +000019#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000020#include "llvm/ADT/SmallVector.h"
Sebastian Redl015085f2008-11-07 23:29:29 +000021#include <set>
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000022using namespace clang;
23
Douglas Gregore81f58e2010-11-08 03:40:48 +000024
Douglas Gregore81f58e2010-11-08 03:40:48 +000025
Sebastian Redl9f831db2009-07-25 15:41:38 +000026enum TryCastResult {
27 TC_NotApplicable, ///< The cast method is not applicable.
28 TC_Success, ///< The cast method is appropriate and successful.
29 TC_Failed ///< The cast method is appropriate, but failed. A
30 ///< diagnostic has been emitted.
31};
32
33enum CastType {
34 CT_Const, ///< const_cast
35 CT_Static, ///< static_cast
36 CT_Reinterpret, ///< reinterpret_cast
37 CT_Dynamic, ///< dynamic_cast
38 CT_CStyle, ///< (Type)expr
39 CT_Functional ///< Type(expr)
Sebastian Redl842ef522008-11-08 13:00:26 +000040};
41
Douglas Gregore81f58e2010-11-08 03:40:48 +000042
43
44
Sebastian Redl842ef522008-11-08 13:00:26 +000045static void CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
John McCall7decc9e2010-11-18 06:31:45 +000046 ExprValueKind &VK,
Sebastian Redl842ef522008-11-08 13:00:26 +000047 const SourceRange &OpRange,
48 const SourceRange &DestRange);
49static void CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
John McCall7decc9e2010-11-18 06:31:45 +000050 ExprValueKind &VK,
Sebastian Redl842ef522008-11-08 13:00:26 +000051 const SourceRange &OpRange,
Anders Carlsson7cd39e02009-09-15 04:48:33 +000052 const SourceRange &DestRange,
John McCalle3027922010-08-25 11:45:40 +000053 CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +000054static void CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
John McCall7decc9e2010-11-18 06:31:45 +000055 ExprValueKind &VK,
Anders Carlssonf10e4142009-08-07 22:21:05 +000056 const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +000057 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +000058 CXXCastPath &BasePath);
Sebastian Redl842ef522008-11-08 13:00:26 +000059static void CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
John McCall7decc9e2010-11-18 06:31:45 +000060 ExprValueKind &VK,
Sebastian Redl842ef522008-11-08 13:00:26 +000061 const SourceRange &OpRange,
Mike Stump11289f42009-09-09 15:08:12 +000062 const SourceRange &DestRange,
John McCalle3027922010-08-25 11:45:40 +000063 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +000064 CXXCastPath &BasePath);
Sebastian Redl842ef522008-11-08 13:00:26 +000065
66static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
Sebastian Redl9f831db2009-07-25 15:41:38 +000067
68// The Try functions attempt a specific way of casting. If they succeed, they
69// return TC_Success. If their way of casting is not appropriate for the given
70// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
71// to emit if no other way succeeds. If their way of casting is appropriate but
72// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
73// they emit a specialized diagnostic.
74// All diagnostics returned by these functions must expect the same three
75// arguments:
76// %0: Cast Type (a value from the CastType enumeration)
77// %1: Source Type
78// %2: Destination Type
79static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
Douglas Gregorce950842011-01-26 21:04:06 +000080 QualType DestType, bool CStyle,
81 CastKind &Kind,
Douglas Gregorba278e22011-01-25 16:13:26 +000082 CXXCastPath &BasePath,
83 unsigned &msg);
Sebastian Redl9f831db2009-07-25 15:41:38 +000084static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
Anders Carlsson7d3360f2010-04-24 19:36:51 +000085 QualType DestType, bool CStyle,
86 const SourceRange &OpRange,
87 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +000088 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +000089 CXXCastPath &BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +000090static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
91 QualType DestType, bool CStyle,
92 const SourceRange &OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +000093 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +000094 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +000095 CXXCastPath &BasePath);
Douglas Gregor8f3952c2009-11-15 09:20:52 +000096static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
97 CanQualType DestType, bool CStyle,
Sebastian Redl9f831db2009-07-25 15:41:38 +000098 const SourceRange &OpRange,
99 QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000100 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000101 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000102 CXXCastPath &BasePath);
Douglas Gregorc934bc82010-03-07 23:24:59 +0000103static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000104 QualType SrcType,
105 QualType DestType,bool CStyle,
106 const SourceRange &OpRange,
107 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000108 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000109 CXXCastPath &BasePath);
Anders Carlssonb78feca2010-04-24 19:22:20 +0000110
Sebastian Redl7c353682009-11-14 21:15:49 +0000111static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000112 QualType DestType, bool CStyle,
113 const SourceRange &OpRange,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000114 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000115 CastKind &Kind);
Sebastian Redl7c353682009-11-14 21:15:49 +0000116static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000117 QualType DestType, bool CStyle,
118 const SourceRange &OpRange,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000119 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000120 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000121 CXXCastPath &BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000122static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
123 bool CStyle, unsigned &msg);
Douglas Gregorb491ed32011-02-19 21:32:49 +0000124static TryCastResult TryReinterpretCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000125 QualType DestType, bool CStyle,
126 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000127 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000128 CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +0000129
Douglas Gregorb491ed32011-02-19 21:32:49 +0000130
131static ExprResult
132ResolveAndFixSingleFunctionTemplateSpecialization(
133 Sema &Self, Expr *SrcExpr,
134 bool DoFunctionPointerConverion = false,
135 bool Complain = false,
136 const SourceRange& OpRangeForComplaining = SourceRange(),
137 QualType DestTypeForComplaining = QualType(),
138 unsigned DiagIDForComplaining = 0);
139
140
141
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000142/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
John McCalldadc5752010-08-24 06:29:42 +0000143ExprResult
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000144Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John McCallba7bf592010-08-24 05:47:05 +0000145 SourceLocation LAngleBracketLoc, ParsedType Ty,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000146 SourceLocation RAngleBracketLoc,
John McCallfaf5fb42010-08-26 23:41:50 +0000147 SourceLocation LParenLoc, Expr *E,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000148 SourceLocation RParenLoc) {
John McCalld377e042010-01-15 19:13:16 +0000149
John McCall97513962010-01-15 18:39:57 +0000150 TypeSourceInfo *DestTInfo;
151 QualType DestType = GetTypeFromParser(Ty, &DestTInfo);
152 if (!DestTInfo)
153 DestTInfo = Context.getTrivialTypeSourceInfo(DestType, SourceLocation());
John McCalld377e042010-01-15 19:13:16 +0000154
155 return BuildCXXNamedCast(OpLoc, Kind, DestTInfo, move(E),
156 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
157 SourceRange(LParenLoc, RParenLoc));
158}
159
John McCalldadc5752010-08-24 06:29:42 +0000160ExprResult
John McCalld377e042010-01-15 19:13:16 +0000161Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John McCallfaf5fb42010-08-26 23:41:50 +0000162 TypeSourceInfo *DestTInfo, Expr *Ex,
John McCalld377e042010-01-15 19:13:16 +0000163 SourceRange AngleBrackets, SourceRange Parens) {
John McCalld377e042010-01-15 19:13:16 +0000164 QualType DestType = DestTInfo->getType();
165
166 SourceRange OpRange(OpLoc, Parens.getEnd());
167 SourceRange DestRange = AngleBrackets;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000168
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000169 // If the type is dependent, we won't do the semantic analysis now.
170 // FIXME: should we check this in a more fine-grained manner?
171 bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
172
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +0000173 if (Ex->isBoundMemberFunction(Context))
174 Diag(Ex->getLocStart(), diag::err_invalid_use_of_bound_member_func)
175 << Ex->getSourceRange();
176
John McCall7decc9e2010-11-18 06:31:45 +0000177 ExprValueKind VK = VK_RValue;
John McCall29ac8e22010-11-26 10:57:22 +0000178 if (TypeDependent)
179 VK = Expr::getValueKindForType(DestType);
180
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000181 switch (Kind) {
John McCall8cb679e2010-11-15 09:13:47 +0000182 default: llvm_unreachable("Unknown C++ cast!");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000183
184 case tok::kw_const_cast:
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000185 if (!TypeDependent)
John McCall7decc9e2010-11-18 06:31:45 +0000186 CheckConstCast(*this, Ex, DestType, VK, OpRange, DestRange);
John McCallcf142162010-08-07 06:22:56 +0000187 return Owned(CXXConstCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +0000188 DestType.getNonLValueExprType(Context),
Douglas Gregor4478f852011-01-12 22:41:29 +0000189 VK, Ex, DestTInfo, OpLoc,
190 Parens.getEnd()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000191
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000192 case tok::kw_dynamic_cast: {
John McCall8cb679e2010-11-15 09:13:47 +0000193 CastKind Kind = CK_Dependent;
John McCallcf142162010-08-07 06:22:56 +0000194 CXXCastPath BasePath;
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000195 if (!TypeDependent)
John McCall7decc9e2010-11-18 06:31:45 +0000196 CheckDynamicCast(*this, Ex, DestType, VK, OpRange, DestRange,
197 Kind, BasePath);
John McCallcf142162010-08-07 06:22:56 +0000198 return Owned(CXXDynamicCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +0000199 DestType.getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +0000200 VK, Kind, Ex, &BasePath, DestTInfo,
Douglas Gregor4478f852011-01-12 22:41:29 +0000201 OpLoc, Parens.getEnd()));
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000202 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000203 case tok::kw_reinterpret_cast: {
John McCall8cb679e2010-11-15 09:13:47 +0000204 CastKind Kind = CK_Dependent;
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000205 if (!TypeDependent)
John McCall7decc9e2010-11-18 06:31:45 +0000206 CheckReinterpretCast(*this, Ex, DestType, VK, OpRange, DestRange, Kind);
John McCallcf142162010-08-07 06:22:56 +0000207 return Owned(CXXReinterpretCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +0000208 DestType.getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +0000209 VK, Kind, Ex, 0,
Douglas Gregor4478f852011-01-12 22:41:29 +0000210 DestTInfo, OpLoc, Parens.getEnd()));
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000211 }
Anders Carlssonf10e4142009-08-07 22:21:05 +0000212 case tok::kw_static_cast: {
John McCall8cb679e2010-11-15 09:13:47 +0000213 CastKind Kind = CK_Dependent;
John McCallcf142162010-08-07 06:22:56 +0000214 CXXCastPath BasePath;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000215 if (!TypeDependent)
John McCall7decc9e2010-11-18 06:31:45 +0000216 CheckStaticCast(*this, Ex, DestType, VK, OpRange, Kind, BasePath);
Anders Carlssone9766d52009-09-09 21:33:21 +0000217
John McCallcf142162010-08-07 06:22:56 +0000218 return Owned(CXXStaticCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +0000219 DestType.getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +0000220 VK, Kind, Ex, &BasePath,
Douglas Gregor4478f852011-01-12 22:41:29 +0000221 DestTInfo, OpLoc, Parens.getEnd()));
Anders Carlssonf10e4142009-08-07 22:21:05 +0000222 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000223 }
224
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000225 return ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000226}
227
John McCall909acf82011-02-14 18:34:10 +0000228/// Try to diagnose a failed overloaded cast. Returns true if
229/// diagnostics were emitted.
230static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
231 SourceRange range, Expr *src,
232 QualType destType) {
233 switch (CT) {
234 // These cast kinds don't consider user-defined conversions.
235 case CT_Const:
236 case CT_Reinterpret:
237 case CT_Dynamic:
238 return false;
239
240 // These do.
241 case CT_Static:
242 case CT_CStyle:
243 case CT_Functional:
244 break;
245 }
246
247 QualType srcType = src->getType();
248 if (!destType->isRecordType() && !srcType->isRecordType())
249 return false;
250
251 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
252 InitializationKind initKind
253 = InitializationKind::CreateCast(/*type range?*/ range,
254 (CT == CT_CStyle || CT == CT_Functional));
255 InitializationSequence sequence(S, entity, initKind, &src, 1);
256
257 assert(sequence.getKind() == InitializationSequence::FailedSequence &&
258 "initialization succeeded on second try?");
259 switch (sequence.getFailureKind()) {
260 default: return false;
261
262 case InitializationSequence::FK_ConstructorOverloadFailed:
263 case InitializationSequence::FK_UserConversionOverloadFailed:
264 break;
265 }
266
267 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
268
269 unsigned msg = 0;
270 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
271
272 switch (sequence.getFailedOverloadResult()) {
273 case OR_Success: llvm_unreachable("successful failed overload");
274 return false;
275 case OR_No_Viable_Function:
276 if (candidates.empty())
277 msg = diag::err_ovl_no_conversion_in_cast;
278 else
279 msg = diag::err_ovl_no_viable_conversion_in_cast;
280 howManyCandidates = OCD_AllCandidates;
281 break;
282
283 case OR_Ambiguous:
284 msg = diag::err_ovl_ambiguous_conversion_in_cast;
285 howManyCandidates = OCD_ViableCandidates;
286 break;
287
288 case OR_Deleted:
289 msg = diag::err_ovl_deleted_conversion_in_cast;
290 howManyCandidates = OCD_ViableCandidates;
291 break;
292 }
293
294 S.Diag(range.getBegin(), msg)
295 << CT << srcType << destType
296 << range << src->getSourceRange();
297
298 candidates.NoteCandidates(S, howManyCandidates, &src, 1);
299
300 return true;
301}
302
303/// Diagnose a failed cast.
304static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
305 SourceRange opRange, Expr *src, QualType destType) {
306 if (msg == diag::err_bad_cxx_cast_generic &&
307 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType))
308 return;
309
310 S.Diag(opRange.getBegin(), msg) << castType
311 << src->getType() << destType << opRange << src->getSourceRange();
312}
313
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000314/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
315/// this removes one level of indirection from both types, provided that they're
316/// the same kind of pointer (plain or to-member). Unlike the Sema function,
317/// this one doesn't care if the two pointers-to-member don't point into the
318/// same class. This is because CastsAwayConstness doesn't care.
Dan Gohman28ade552010-07-26 21:25:24 +0000319static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000320 const PointerType *T1PtrType = T1->getAs<PointerType>(),
321 *T2PtrType = T2->getAs<PointerType>();
322 if (T1PtrType && T2PtrType) {
323 T1 = T1PtrType->getPointeeType();
324 T2 = T2PtrType->getPointeeType();
325 return true;
326 }
Fariborz Jahanian8c3f06d2010-02-03 20:32:31 +0000327 const ObjCObjectPointerType *T1ObjCPtrType =
328 T1->getAs<ObjCObjectPointerType>(),
329 *T2ObjCPtrType =
330 T2->getAs<ObjCObjectPointerType>();
331 if (T1ObjCPtrType) {
332 if (T2ObjCPtrType) {
333 T1 = T1ObjCPtrType->getPointeeType();
334 T2 = T2ObjCPtrType->getPointeeType();
335 return true;
336 }
337 else if (T2PtrType) {
338 T1 = T1ObjCPtrType->getPointeeType();
339 T2 = T2PtrType->getPointeeType();
340 return true;
341 }
342 }
343 else if (T2ObjCPtrType) {
344 if (T1PtrType) {
345 T2 = T2ObjCPtrType->getPointeeType();
346 T1 = T1PtrType->getPointeeType();
347 return true;
348 }
349 }
350
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000351 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
352 *T2MPType = T2->getAs<MemberPointerType>();
353 if (T1MPType && T2MPType) {
354 T1 = T1MPType->getPointeeType();
355 T2 = T2MPType->getPointeeType();
356 return true;
357 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000358
359 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
360 *T2BPType = T2->getAs<BlockPointerType>();
361 if (T1BPType && T2BPType) {
362 T1 = T1BPType->getPointeeType();
363 T2 = T2BPType->getPointeeType();
364 return true;
365 }
366
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000367 return false;
368}
369
Sebastian Redla5a77a62009-01-27 23:18:31 +0000370/// CastsAwayConstness - Check if the pointer conversion from SrcType to
371/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
372/// the cast checkers. Both arguments must denote pointer (possibly to member)
373/// types.
Sebastian Redl802f14c2009-10-22 15:07:22 +0000374static bool
Mike Stump11289f42009-09-09 15:08:12 +0000375CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
Sebastian Redla5a77a62009-01-27 23:18:31 +0000376 // Casting away constness is defined in C++ 5.2.11p8 with reference to
377 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
378 // the rules are non-trivial. So first we construct Tcv *...cv* as described
379 // in C++ 5.2.11p8.
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000380 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
381 SrcType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000382 "Source type is not pointer or pointer to member.");
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000383 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
384 DestType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000385 "Destination type is not pointer or pointer to member.");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000386
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000387 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
388 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
John McCall8ccfcb52009-09-24 19:53:00 +0000389 llvm::SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000390
391 // Find the qualifications.
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000392 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
Anders Carlsson76f513f2010-06-04 22:47:55 +0000393 Qualifiers SrcQuals;
394 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
395 cv1.push_back(SrcQuals);
396
397 Qualifiers DestQuals;
398 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
399 cv2.push_back(DestQuals);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000400 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000401 if (cv1.empty())
402 return false;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000403
404 // Construct void pointers with those qualifiers (in reverse order of
405 // unwrapping, of course).
Sebastian Redl842ef522008-11-08 13:00:26 +0000406 QualType SrcConstruct = Self.Context.VoidTy;
407 QualType DestConstruct = Self.Context.VoidTy;
John McCall8ccfcb52009-09-24 19:53:00 +0000408 ASTContext &Context = Self.Context;
409 for (llvm::SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
410 i2 = cv2.rbegin();
Mike Stump11289f42009-09-09 15:08:12 +0000411 i1 != cv1.rend(); ++i1, ++i2) {
John McCall8ccfcb52009-09-24 19:53:00 +0000412 SrcConstruct
413 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
414 DestConstruct
415 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000416 }
417
418 // Test if they're compatible.
419 return SrcConstruct != DestConstruct &&
Douglas Gregor58281352011-01-27 00:58:17 +0000420 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000421}
422
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000423/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
424/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
425/// checked downcasts in class hierarchies.
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000426static void
Sebastian Redl842ef522008-11-08 13:00:26 +0000427CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
John McCall7decc9e2010-11-18 06:31:45 +0000428 ExprValueKind &VK, const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +0000429 const SourceRange &DestRange, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000430 CXXCastPath &BasePath) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000431 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl842ef522008-11-08 13:00:26 +0000432 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000433
434 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
435 // or "pointer to cv void".
436
437 QualType DestPointee;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000438 const PointerType *DestPointer = DestType->getAs<PointerType>();
John McCall7decc9e2010-11-18 06:31:45 +0000439 const ReferenceType *DestReference = 0;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000440 if (DestPointer) {
441 DestPointee = DestPointer->getPointeeType();
John McCall7decc9e2010-11-18 06:31:45 +0000442 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000443 DestPointee = DestReference->getPointeeType();
Douglas Gregor465184a2011-01-22 00:06:57 +0000444 VK = isa<LValueReferenceType>(DestReference) ? VK_LValue
445 : isa<RValueReferenceType>(DestReference) ? VK_XValue
446 : VK_RValue;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000447 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000448 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000449 << OrigDestType << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000450 return;
451 }
452
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000453 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000454 if (DestPointee->isVoidType()) {
455 assert(DestPointer && "Reference to void is not possible");
456 } else if (DestRecord) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000457 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor89336232010-03-29 23:34:08 +0000458 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssond624e162009-08-26 23:45:07 +0000459 << DestRange))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000460 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000461 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000462 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000463 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000464 return;
465 }
466
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000467 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
468 // complete class type, [...]. If T is an lvalue reference type, v shall be
Douglas Gregor465184a2011-01-22 00:06:57 +0000469 // an lvalue of a complete class type, [...]. If T is an rvalue reference
470 // type, v shall be an expression having a complete class type, [...]
Sebastian Redl842ef522008-11-08 13:00:26 +0000471 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000472 QualType SrcPointee;
473 if (DestPointer) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000474 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000475 SrcPointee = SrcPointer->getPointeeType();
476 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000477 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000478 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000479 return;
480 }
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000481 } else if (DestReference->isLValueReferenceType()) {
John McCall086a4642010-11-24 05:12:34 +0000482 if (!SrcExpr->isLValue()) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000483 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000484 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000485 }
486 SrcPointee = SrcType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000487 } else {
488 SrcPointee = SrcType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000489 }
490
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000491 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000492 if (SrcRecord) {
Douglas Gregored0cfbd2009-03-09 16:13:40 +0000493 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor89336232010-03-29 23:34:08 +0000494 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssond624e162009-08-26 23:45:07 +0000495 << SrcExpr->getSourceRange()))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000496 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000497 } else {
Chris Lattner29e812b2008-11-20 06:06:08 +0000498 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000499 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000500 return;
501 }
502
503 assert((DestPointer || DestReference) &&
504 "Bad destination non-ptr/ref slipped through.");
505 assert((DestRecord || DestPointee->isVoidType()) &&
506 "Bad destination pointee slipped through.");
507 assert(SrcRecord && "Bad source pointee slipped through.");
508
509 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
510 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000511 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000512 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000513 return;
514 }
515
516 // C++ 5.2.7p3: If the type of v is the same as the required result type,
517 // [except for cv].
518 if (DestRecord == SrcRecord) {
John McCalle3027922010-08-25 11:45:40 +0000519 Kind = CK_NoOp;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000520 return;
521 }
522
523 // C++ 5.2.7p5
524 // Upcasts are resolved statically.
Sebastian Redl842ef522008-11-08 13:00:26 +0000525 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000526 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
527 OpRange.getBegin(), OpRange,
528 &BasePath))
529 return;
530
John McCalle3027922010-08-25 11:45:40 +0000531 Kind = CK_DerivedToBase;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000532
533 // If we are casting to or through a virtual base class, we need a
534 // vtable.
535 if (Self.BasePathInvolvesVirtualBase(BasePath))
536 Self.MarkVTableUsed(OpRange.getBegin(),
537 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000538 return;
539 }
540
541 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000542 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000543 assert(SrcDecl && "Definition missing");
544 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner29e812b2008-11-20 06:06:08 +0000545 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000546 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000547 }
Douglas Gregor88d292c2010-05-13 16:44:06 +0000548 Self.MarkVTableUsed(OpRange.getBegin(),
549 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000550
551 // Done. Everything else is run-time checks.
John McCalle3027922010-08-25 11:45:40 +0000552 Kind = CK_Dynamic;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000553}
Sebastian Redl9f831db2009-07-25 15:41:38 +0000554
555/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
556/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
557/// like this:
558/// const char *str = "literal";
559/// legacy_function(const_cast\<char*\>(str));
560void
John McCall7decc9e2010-11-18 06:31:45 +0000561CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType, ExprValueKind &VK,
Mike Stump11289f42009-09-09 15:08:12 +0000562 const SourceRange &OpRange, const SourceRange &DestRange) {
John McCall7decc9e2010-11-18 06:31:45 +0000563 VK = Expr::getValueKindForType(DestType);
564 if (VK == VK_RValue)
Douglas Gregorb92a1562010-02-03 00:27:59 +0000565 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000566
567 unsigned msg = diag::err_bad_cxx_cast_generic;
568 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
569 && msg != 0)
570 Self.Diag(OpRange.getBegin(), msg) << CT_Const
571 << SrcExpr->getType() << DestType << OpRange;
572}
573
574/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
575/// valid.
576/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
577/// like this:
578/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
579void
580CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
John McCall7decc9e2010-11-18 06:31:45 +0000581 ExprValueKind &VK, const SourceRange &OpRange,
582 const SourceRange &DestRange, CastKind &Kind) {
583 VK = Expr::getValueKindForType(DestType);
584 if (VK == VK_RValue)
Douglas Gregorb92a1562010-02-03 00:27:59 +0000585 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000586
587 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000588 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
589 msg, Kind)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000590 != TC_Success && msg != 0)
Douglas Gregore81f58e2010-11-08 03:40:48 +0000591 {
John McCall909acf82011-02-14 18:34:10 +0000592 if (SrcExpr->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +0000593 //FIXME: &f<int>; is overloaded and resolvable
594 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
595 << OverloadExpr::find(SrcExpr).Expression->getName()
596 << DestType << OpRange;
Douglas Gregorb491ed32011-02-19 21:32:49 +0000597 Self.NoteAllOverloadCandidates(SrcExpr);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000598
John McCall909acf82011-02-14 18:34:10 +0000599 } else {
600 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr, DestType);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000601 }
John McCall909acf82011-02-14 18:34:10 +0000602 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000603}
604
605
606/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
607/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
608/// implicit conversions explicit and getting rid of data loss warnings.
609void
610CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
John McCall7decc9e2010-11-18 06:31:45 +0000611 ExprValueKind &VK, const SourceRange &OpRange,
612 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000613 // This test is outside everything else because it's the only case where
614 // a non-lvalue-reference target type does not lead to decay.
615 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman03bf60a2009-11-16 05:44:20 +0000616 if (DestType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +0000617 Self.IgnoredValueConversions(SrcExpr);
Douglas Gregorb491ed32011-02-19 21:32:49 +0000618 if (SrcExpr->getType() == Self.Context.OverloadTy) {
619 ExprResult SingleFunctionExpression =
620 ResolveAndFixSingleFunctionTemplateSpecialization(Self, SrcExpr,
621 false, // Decay Function to ptr
622 true, // Complain
623 OpRange, DestType, diag::err_bad_static_cast_overload);
624 if (SingleFunctionExpression.isUsable())
625 {
626 SrcExpr = SingleFunctionExpression.release();
627 Kind = CK_ToVoid;
628 }
629 }
630 else
631 Kind = CK_ToVoid;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000632 return;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000633 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000634
John McCall7decc9e2010-11-18 06:31:45 +0000635 VK = Expr::getValueKindForType(DestType);
636 if (VK == VK_RValue && !DestType->isRecordType())
Douglas Gregorb92a1562010-02-03 00:27:59 +0000637 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000638
639 unsigned msg = diag::err_bad_cxx_cast_generic;
Sebastian Redl7c353682009-11-14 21:15:49 +0000640 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg,
Douglas Gregorb491ed32011-02-19 21:32:49 +0000641 Kind, BasePath) != TC_Success && msg != 0) {
John McCall909acf82011-02-14 18:34:10 +0000642 if (SrcExpr->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +0000643 OverloadExpr* oe = OverloadExpr::find(SrcExpr).Expression;
644 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
Douglas Gregor0da1d432011-02-28 20:01:57 +0000645 << oe->getName() << DestType << OpRange
646 << oe->getQualifierLoc().getSourceRange();
Douglas Gregorb491ed32011-02-19 21:32:49 +0000647 Self.NoteAllOverloadCandidates(SrcExpr);
John McCall909acf82011-02-14 18:34:10 +0000648 } else {
649 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr, DestType);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000650 }
Douglas Gregore81f58e2010-11-08 03:40:48 +0000651 }
John McCalld50a2712010-11-16 05:46:29 +0000652 else if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +0000653 Self.CheckCastAlign(SrcExpr, DestType, OpRange);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000654}
655
656/// TryStaticCast - Check if a static cast can be performed, and do so if
657/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
658/// and casting away constness.
Sebastian Redl7c353682009-11-14 21:15:49 +0000659static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000660 QualType DestType, bool CStyle,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000661 const SourceRange &OpRange, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000662 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000663 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000664 // The order the tests is not entirely arbitrary. There is one conversion
665 // that can be handled in two different ways. Given:
666 // struct A {};
667 // struct B : public A {
668 // B(); B(const A&);
669 // };
670 // const A &a = B();
671 // the cast static_cast<const B&>(a) could be seen as either a static
672 // reference downcast, or an explicit invocation of the user-defined
673 // conversion using B's conversion constructor.
674 // DR 427 specifies that the downcast is to be applied here.
675
676 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
677 // Done outside this function.
678
679 TryCastResult tcr;
680
681 // C++ 5.2.9p5, reference downcast.
682 // See the function for details.
683 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redl7c353682009-11-14 21:15:49 +0000684 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle, OpRange,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000685 msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000686 if (tcr != TC_NotApplicable)
687 return tcr;
688
Douglas Gregor465184a2011-01-22 00:06:57 +0000689 // C++0x [expr.static.cast]p3:
690 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
691 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Douglas Gregorce950842011-01-26 21:04:06 +0000692 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, CStyle, Kind, BasePath,
693 msg);
Douglas Gregorba278e22011-01-25 16:13:26 +0000694 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000695 return tcr;
696
697 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
698 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000699 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
Douglas Gregorb33eed02010-04-16 22:09:46 +0000700 Kind);
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000701 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000702 return tcr;
Anders Carlssone9766d52009-09-09 21:33:21 +0000703
Sebastian Redl9f831db2009-07-25 15:41:38 +0000704 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
705 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
706 // conversions, subject to further restrictions.
707 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
708 // of qualification conversions impossible.
709 // In the CStyle case, the earlier attempt to const_cast should have taken
710 // care of reverse qualification conversions.
711
Sebastian Redl9f831db2009-07-25 15:41:38 +0000712 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
713
Douglas Gregor0bf31402010-10-08 23:50:27 +0000714 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
Douglas Gregorb327eac2011-02-18 03:01:41 +0000715 // converted to an integral type. [...] A value of a scoped enumeration type
716 // can also be explicitly converted to a floating-point type [...].
717 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
718 if (Enum->getDecl()->isScoped()) {
719 if (DestType->isBooleanType()) {
720 Kind = CK_IntegralToBoolean;
721 return TC_Success;
722 } else if (DestType->isIntegralType(Self.Context)) {
723 Kind = CK_IntegralCast;
724 return TC_Success;
725 } else if (DestType->isRealFloatingType()) {
726 Kind = CK_IntegralToFloating;
727 return TC_Success;
728 }
Douglas Gregor0bf31402010-10-08 23:50:27 +0000729 }
730 }
Douglas Gregorb327eac2011-02-18 03:01:41 +0000731
Sebastian Redl9f831db2009-07-25 15:41:38 +0000732 // Reverse integral promotion/conversion. All such conversions are themselves
733 // again integral promotions or conversions and are thus already handled by
734 // p2 (TryDirectInitialization above).
735 // (Note: any data loss warnings should be suppressed.)
736 // The exception is the reverse of enum->integer, i.e. integer->enum (and
737 // enum->enum). See also C++ 5.2.9p7.
738 // The same goes for reverse floating point promotion/conversion and
739 // floating-integral conversions. Again, only floating->enum is relevant.
740 if (DestType->isEnumeralType()) {
741 if (SrcType->isComplexType() || SrcType->isVectorType()) {
742 // Fall through - these cannot be converted.
Eli Friedman03bf60a2009-11-16 05:44:20 +0000743 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
John McCalle3027922010-08-25 11:45:40 +0000744 Kind = CK_IntegralCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000745 return TC_Success;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000746 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000747 }
748
749 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
750 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000751 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000752 Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000753 if (tcr != TC_NotApplicable)
754 return tcr;
755
756 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
757 // conversion. C++ 5.2.9p9 has additional information.
758 // DR54's access restrictions apply here also.
Douglas Gregorc934bc82010-03-07 23:24:59 +0000759 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000760 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000761 if (tcr != TC_NotApplicable)
762 return tcr;
763
764 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
765 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
766 // just the usual constness stuff.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000767 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000768 QualType SrcPointee = SrcPointer->getPointeeType();
769 if (SrcPointee->isVoidType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000770 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000771 QualType DestPointee = DestPointer->getPointeeType();
772 if (DestPointee->isIncompleteOrObjectType()) {
773 // This is definitely the intended conversion, but it might fail due
774 // to a const violation.
775 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
776 msg = diag::err_bad_cxx_cast_const_away;
777 return TC_Failed;
778 }
John McCalle3027922010-08-25 11:45:40 +0000779 Kind = CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000780 return TC_Success;
781 }
782 }
Fariborz Jahanianeee16692010-05-10 23:46:53 +0000783 else if (DestType->isObjCObjectPointerType()) {
784 // allow both c-style cast and static_cast of objective-c pointers as
785 // they are pervasive.
John McCalle3027922010-08-25 11:45:40 +0000786 Kind = CK_AnyPointerToObjCPointerCast;
Fariborz Jahanian859c4152009-12-08 23:09:15 +0000787 return TC_Success;
788 }
Fariborz Jahanianffe912c2009-12-11 22:40:48 +0000789 else if (CStyle && DestType->isBlockPointerType()) {
790 // allow c-style cast of void * to block pointers.
John McCalle3027922010-08-25 11:45:40 +0000791 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanianffe912c2009-12-11 22:40:48 +0000792 return TC_Success;
793 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000794 }
795 }
Fariborz Jahanianb0901b72010-05-12 18:16:59 +0000796 // Allow arbitray objective-c pointer conversion with static casts.
797 if (SrcType->isObjCObjectPointerType() &&
John McCall8cb679e2010-11-15 09:13:47 +0000798 DestType->isObjCObjectPointerType()) {
799 Kind = CK_BitCast;
Fariborz Jahanianb0901b72010-05-12 18:16:59 +0000800 return TC_Success;
John McCall8cb679e2010-11-15 09:13:47 +0000801 }
Fariborz Jahanianb0901b72010-05-12 18:16:59 +0000802
Sebastian Redl9f831db2009-07-25 15:41:38 +0000803 // We tried everything. Everything! Nothing works! :-(
804 return TC_NotApplicable;
805}
806
807/// Tests whether a conversion according to N2844 is valid.
808TryCastResult
809TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Douglas Gregorce950842011-01-26 21:04:06 +0000810 bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
811 unsigned &msg) {
Douglas Gregor465184a2011-01-22 00:06:57 +0000812 // C++0x [expr.static.cast]p3:
813 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
814 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000815 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000816 if (!R)
817 return TC_NotApplicable;
818
Douglas Gregor465184a2011-01-22 00:06:57 +0000819 if (!SrcExpr->isGLValue())
Sebastian Redl9f831db2009-07-25 15:41:38 +0000820 return TC_NotApplicable;
821
822 // Because we try the reference downcast before this function, from now on
823 // this is the only cast possibility, so we issue an error if we fail now.
824 // FIXME: Should allow casting away constness if CStyle.
825 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +0000826 bool ObjCConversion;
Douglas Gregorce950842011-01-26 21:04:06 +0000827 QualType FromType = SrcExpr->getType();
828 QualType ToType = R->getPointeeType();
829 if (CStyle) {
830 FromType = FromType.getUnqualifiedType();
831 ToType = ToType.getUnqualifiedType();
832 }
833
Douglas Gregor3ec1bf22009-11-05 13:06:35 +0000834 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
Douglas Gregorce950842011-01-26 21:04:06 +0000835 ToType, FromType,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +0000836 DerivedToBase, ObjCConversion) <
Sebastian Redl9f831db2009-07-25 15:41:38 +0000837 Sema::Ref_Compatible_With_Added_Qualification) {
838 msg = diag::err_bad_lvalue_to_rvalue_cast;
839 return TC_Failed;
840 }
841
Douglas Gregorba278e22011-01-25 16:13:26 +0000842 if (DerivedToBase) {
843 Kind = CK_DerivedToBase;
844 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
845 /*DetectVirtual=*/true);
846 if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
847 return TC_NotApplicable;
848
849 Self.BuildBasePathArray(Paths, BasePath);
850 } else
851 Kind = CK_NoOp;
852
Sebastian Redl9f831db2009-07-25 15:41:38 +0000853 return TC_Success;
854}
855
856/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
857TryCastResult
858TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
859 bool CStyle, const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +0000860 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000861 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000862 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
863 // cast to type "reference to cv2 D", where D is a class derived from B,
864 // if a valid standard conversion from "pointer to D" to "pointer to B"
865 // exists, cv2 >= cv1, and B is not a virtual base class of D.
866 // In addition, DR54 clarifies that the base must be accessible in the
867 // current context. Although the wording of DR54 only applies to the pointer
868 // variant of this rule, the intent is clearly for it to apply to the this
869 // conversion as well.
870
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000871 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000872 if (!DestReference) {
873 return TC_NotApplicable;
874 }
875 bool RValueRef = DestReference->isRValueReferenceType();
John McCall086a4642010-11-24 05:12:34 +0000876 if (!RValueRef && !SrcExpr->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000877 // We know the left side is an lvalue reference, so we can suggest a reason.
878 msg = diag::err_bad_cxx_cast_rvalue;
879 return TC_NotApplicable;
880 }
881
882 QualType DestPointee = DestReference->getPointeeType();
883
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000884 return TryStaticDowncast(Self,
885 Self.Context.getCanonicalType(SrcExpr->getType()),
886 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000887 OpRange, SrcExpr->getType(), DestType, msg, Kind,
888 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000889}
890
891/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
892TryCastResult
893TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +0000894 bool CStyle, const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +0000895 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000896 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000897 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
898 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
899 // is a class derived from B, if a valid standard conversion from "pointer
900 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
901 // class of D.
902 // In addition, DR54 clarifies that the base must be accessible in the
903 // current context.
904
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000905 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000906 if (!DestPointer) {
907 return TC_NotApplicable;
908 }
909
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000910 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000911 if (!SrcPointer) {
912 msg = diag::err_bad_static_cast_pointer_nonpointer;
913 return TC_NotApplicable;
914 }
915
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000916 return TryStaticDowncast(Self,
917 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
918 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000919 CStyle, OpRange, SrcType, DestType, msg, Kind,
920 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000921}
922
923/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
924/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000925/// DestType is possible and allowed.
Sebastian Redl9f831db2009-07-25 15:41:38 +0000926TryCastResult
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000927TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000928 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000929 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000930 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl802f14c2009-10-22 15:07:22 +0000931 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregor89336232010-03-29 23:34:08 +0000932 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, Self.PDiag(0)) ||
933 Self.RequireCompleteType(OpRange.getBegin(), DestType, Self.PDiag(0)))
Sebastian Redl802f14c2009-10-22 15:07:22 +0000934 return TC_NotApplicable;
935
Sebastian Redl9f831db2009-07-25 15:41:38 +0000936 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000937 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000938 return TC_NotApplicable;
939 }
940
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000941 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000942 /*DetectVirtual=*/true);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000943 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
944 return TC_NotApplicable;
945 }
946
947 // Target type does derive from source type. Now we're serious. If an error
948 // appears now, it's not ignored.
949 // This may not be entirely in line with the standard. Take for example:
950 // struct A {};
951 // struct B : virtual A {
952 // B(A&);
953 // };
Mike Stump11289f42009-09-09 15:08:12 +0000954 //
Sebastian Redl9f831db2009-07-25 15:41:38 +0000955 // void f()
956 // {
957 // (void)static_cast<const B&>(*((A*)0));
958 // }
959 // As far as the standard is concerned, p5 does not apply (A is virtual), so
960 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
961 // However, both GCC and Comeau reject this example, and accepting it would
962 // mean more complex code if we're to preserve the nice error message.
963 // FIXME: Being 100% compliant here would be nice to have.
964
965 // Must preserve cv, as always, unless we're in C-style mode.
966 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
967 msg = diag::err_bad_cxx_cast_const_away;
968 return TC_Failed;
969 }
970
971 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
972 // This code is analoguous to that in CheckDerivedToBaseConversion, except
973 // that it builds the paths in reverse order.
974 // To sum up: record all paths to the base and build a nice string from
975 // them. Use it to spice up the error message.
976 if (!Paths.isRecordingPaths()) {
977 Paths.clear();
978 Paths.setRecordingPaths(true);
979 Self.IsDerivedFrom(DestType, SrcType, Paths);
980 }
981 std::string PathDisplayStr;
982 std::set<unsigned> DisplayedPaths;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000983 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000984 PI != PE; ++PI) {
985 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
986 // We haven't displayed a path to this particular base
987 // class subobject yet.
988 PathDisplayStr += "\n ";
Douglas Gregor36d1b142009-10-06 17:59:45 +0000989 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
990 EE = PI->rend();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000991 EI != EE; ++EI)
992 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000993 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000994 }
995 }
996
997 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000998 << QualType(SrcType).getUnqualifiedType()
999 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9f831db2009-07-25 15:41:38 +00001000 << PathDisplayStr << OpRange;
1001 msg = 0;
1002 return TC_Failed;
1003 }
1004
1005 if (Paths.getDetectedVirtual() != 0) {
1006 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1007 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1008 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1009 msg = 0;
1010 return TC_Failed;
1011 }
1012
John McCallfe9cf0a2011-02-14 23:21:33 +00001013 if (!CStyle) {
1014 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1015 SrcType, DestType,
1016 Paths.front(),
John McCall1064d7e2010-03-16 05:22:47 +00001017 diag::err_downcast_from_inaccessible_base)) {
John McCallfe9cf0a2011-02-14 23:21:33 +00001018 case Sema::AR_accessible:
1019 case Sema::AR_delayed: // be optimistic
1020 case Sema::AR_dependent: // be optimistic
1021 break;
1022
1023 case Sema::AR_inaccessible:
1024 msg = 0;
1025 return TC_Failed;
1026 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001027 }
1028
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001029 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001030 Kind = CK_BaseToDerived;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001031 return TC_Success;
1032}
1033
1034/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1035/// C++ 5.2.9p9 is valid:
1036///
1037/// An rvalue of type "pointer to member of D of type cv1 T" can be
1038/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1039/// where B is a base class of D [...].
1040///
1041TryCastResult
Douglas Gregorc934bc82010-03-07 23:24:59 +00001042TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr, QualType SrcType,
1043 QualType DestType, bool CStyle,
1044 const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +00001045 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001046 CXXCastPath &BasePath) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001047 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001048 if (!DestMemPtr)
1049 return TC_NotApplicable;
Douglas Gregorc934bc82010-03-07 23:24:59 +00001050
1051 bool WasOverloadedFunction = false;
John McCall16df1e52010-03-30 21:47:33 +00001052 DeclAccessPair FoundOverload;
Douglas Gregor064fdb22010-04-14 23:11:21 +00001053 if (SrcExpr->getType() == Self.Context.OverloadTy) {
1054 if (FunctionDecl *Fn
1055 = Self.ResolveAddressOfOverloadedFunction(SrcExpr, DestType, false,
1056 FoundOverload)) {
1057 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1058 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1059 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1060 WasOverloadedFunction = true;
1061 }
Douglas Gregorc934bc82010-03-07 23:24:59 +00001062 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00001063
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001064 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001065 if (!SrcMemPtr) {
1066 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1067 return TC_NotApplicable;
1068 }
1069
1070 // T == T, modulo cv
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001071 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1072 DestMemPtr->getPointeeType()))
Sebastian Redl9f831db2009-07-25 15:41:38 +00001073 return TC_NotApplicable;
1074
1075 // B base of D
1076 QualType SrcClass(SrcMemPtr->getClass(), 0);
1077 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssonb78feca2010-04-24 19:22:20 +00001078 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001079 /*DetectVirtual=*/true);
1080 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
1081 return TC_NotApplicable;
1082 }
1083
1084 // B is a base of D. But is it an allowed base? If not, it's a hard error.
Douglas Gregor27ac4292010-05-21 20:29:55 +00001085 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001086 Paths.clear();
1087 Paths.setRecordingPaths(true);
1088 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
1089 assert(StillOkay);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001090 (void)StillOkay;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001091 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1092 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1093 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1094 msg = 0;
1095 return TC_Failed;
1096 }
1097
1098 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1099 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1100 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1101 msg = 0;
1102 return TC_Failed;
1103 }
1104
John McCallfe9cf0a2011-02-14 23:21:33 +00001105 if (!CStyle) {
1106 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1107 DestClass, SrcClass,
1108 Paths.front(),
1109 diag::err_upcast_to_inaccessible_base)) {
1110 case Sema::AR_accessible:
1111 case Sema::AR_delayed:
1112 case Sema::AR_dependent:
1113 // Optimistically assume that the delayed and dependent cases
1114 // will work out.
1115 break;
1116
1117 case Sema::AR_inaccessible:
1118 msg = 0;
1119 return TC_Failed;
1120 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001121 }
1122
Douglas Gregorc934bc82010-03-07 23:24:59 +00001123 if (WasOverloadedFunction) {
1124 // Resolve the address of the overloaded function again, this time
1125 // allowing complaints if something goes wrong.
1126 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr,
1127 DestType,
John McCall16df1e52010-03-30 21:47:33 +00001128 true,
1129 FoundOverload);
Douglas Gregorc934bc82010-03-07 23:24:59 +00001130 if (!Fn) {
1131 msg = 0;
1132 return TC_Failed;
1133 }
1134
John McCall16df1e52010-03-30 21:47:33 +00001135 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
Douglas Gregorc934bc82010-03-07 23:24:59 +00001136 if (!SrcExpr) {
1137 msg = 0;
1138 return TC_Failed;
1139 }
1140 }
1141
Anders Carlssonb78feca2010-04-24 19:22:20 +00001142 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001143 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001144 return TC_Success;
1145}
1146
1147/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1148/// is valid:
1149///
1150/// An expression e can be explicitly converted to a type T using a
1151/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1152TryCastResult
Sebastian Redl7c353682009-11-14 21:15:49 +00001153TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00001154 bool CStyle, const SourceRange &OpRange, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001155 CastKind &Kind) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +00001156 if (DestType->isRecordType()) {
1157 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1158 diag::err_bad_dynamic_cast_incomplete)) {
1159 msg = 0;
1160 return TC_Failed;
1161 }
1162 }
Douglas Gregorb33eed02010-04-16 22:09:46 +00001163
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001164 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1165 InitializationKind InitKind
Douglas Gregor58281352011-01-27 00:58:17 +00001166 = InitializationKind::CreateCast(/*FIXME:*/OpRange, CStyle);
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001167 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExpr, 1);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001168
1169 // At this point of CheckStaticCast, if the destination is a reference,
1170 // or the expression is an overload expression this has to work.
1171 // There is no other way that works.
1172 // On the other hand, if we're checking a C-style cast, we've still got
1173 // the reinterpret_cast way.
1174
Douglas Gregorb33eed02010-04-16 22:09:46 +00001175 if (InitSeq.getKind() == InitializationSequence::FailedSequence &&
Douglas Gregore81f58e2010-11-08 03:40:48 +00001176 (CStyle || !DestType->isReferenceType()))
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001177 return TC_NotApplicable;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001178
John McCalldadc5752010-08-24 06:29:42 +00001179 ExprResult Result
John McCallfaf5fb42010-08-26 23:41:50 +00001180 = InitSeq.Perform(Self, Entity, InitKind, MultiExprArg(Self, &SrcExpr, 1));
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001181 if (Result.isInvalid()) {
1182 msg = 0;
1183 return TC_Failed;
1184 }
1185
Douglas Gregorb33eed02010-04-16 22:09:46 +00001186 if (InitSeq.isConstructorInitialization())
John McCalle3027922010-08-25 11:45:40 +00001187 Kind = CK_ConstructorConversion;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001188 else
John McCalle3027922010-08-25 11:45:40 +00001189 Kind = CK_NoOp;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001190
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001191 SrcExpr = Result.takeAs<Expr>();
1192 return TC_Success;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001193}
1194
1195/// TryConstCast - See if a const_cast from source to destination is allowed,
1196/// and perform it if it is.
1197static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
1198 bool CStyle, unsigned &msg) {
1199 DestType = Self.Context.getCanonicalType(DestType);
1200 QualType SrcType = SrcExpr->getType();
Douglas Gregorc1ed20c2011-01-22 00:19:52 +00001201 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
1202 if (DestTypeTmp->isLValueReferenceType() && !SrcExpr->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001203 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1204 // is C-style, static_cast might find a way, so we simply suggest a
1205 // message and tell the parent to keep searching.
1206 msg = diag::err_bad_cxx_cast_rvalue;
1207 return TC_NotApplicable;
1208 }
1209
1210 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
1211 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
1212 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1213 SrcType = Self.Context.getPointerType(SrcType);
1214 }
1215
1216 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1217 // the rules for const_cast are the same as those used for pointers.
1218
John McCall0e704f72010-05-18 09:35:29 +00001219 if (!DestType->isPointerType() &&
1220 !DestType->isMemberPointerType() &&
1221 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001222 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1223 // was a reference type, we converted it to a pointer above.
1224 // The status of rvalue references isn't entirely clear, but it looks like
1225 // conversion to them is simply invalid.
1226 // C++ 5.2.11p3: For two pointer types [...]
1227 if (!CStyle)
1228 msg = diag::err_bad_const_cast_dest;
1229 return TC_NotApplicable;
1230 }
1231 if (DestType->isFunctionPointerType() ||
1232 DestType->isMemberFunctionPointerType()) {
1233 // Cannot cast direct function pointers.
1234 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1235 // T is the ultimate pointee of source and target type.
1236 if (!CStyle)
1237 msg = diag::err_bad_const_cast_dest;
1238 return TC_NotApplicable;
1239 }
1240 SrcType = Self.Context.getCanonicalType(SrcType);
1241
1242 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1243 // completely equal.
1244 // FIXME: const_cast should probably not be able to convert between pointers
1245 // to different address spaces.
1246 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1247 // in multi-level pointers may change, but the level count must be the same,
1248 // as must be the final pointee type.
1249 while (SrcType != DestType &&
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001250 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Chandler Carruth585fb1e2009-12-29 08:05:19 +00001251 Qualifiers Quals;
1252 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, Quals);
1253 DestType = Self.Context.getUnqualifiedArrayType(DestType, Quals);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001254 }
1255
1256 // Since we're dealing in canonical types, the remainder must be the same.
1257 if (SrcType != DestType)
1258 return TC_NotApplicable;
1259
1260 return TC_Success;
1261}
1262
Douglas Gregorb491ed32011-02-19 21:32:49 +00001263// A helper function to resolve and fix an overloaded expression that
1264// can be resolved because it identifies a single function
1265// template specialization
1266// Last three arguments should only be supplied if Complain = true
1267static ExprResult ResolveAndFixSingleFunctionTemplateSpecialization(
1268 Sema &Self, Expr *SrcExpr,
1269 bool DoFunctionPointerConverion,
1270 bool Complain,
1271 const SourceRange& OpRangeForComplaining,
1272 QualType DestTypeForComplaining,
1273 unsigned DiagIDForComplaining) {
1274 assert(SrcExpr->getType() == Self.Context.OverloadTy);
1275 DeclAccessPair Found;
Douglas Gregorb491ed32011-02-19 21:32:49 +00001276 Expr* SingleFunctionExpression = 0;
1277 if (FunctionDecl* Fn = Self.ResolveSingleFunctionTemplateSpecialization(
1278 SrcExpr, false, // false -> Complain
1279 &Found)) {
1280 if (!Self.DiagnoseUseOfDecl(Fn, SrcExpr->getSourceRange().getBegin())) {
1281 // mark the expression as resolved to Fn
1282 SingleFunctionExpression = Self.FixOverloadedFunctionReference(SrcExpr,
1283 Found, Fn);
1284
1285 if (DoFunctionPointerConverion)
1286 Self.DefaultFunctionArrayLvalueConversion(SingleFunctionExpression);
1287 }
Douglas Gregore81f58e2010-11-08 03:40:48 +00001288 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00001289 if (!SingleFunctionExpression && Complain) {
1290 OverloadExpr* oe = OverloadExpr::find(SrcExpr).Expression;
1291 Self.Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
1292 << oe->getName() << DestTypeForComplaining << OpRangeForComplaining
Douglas Gregor0da1d432011-02-28 20:01:57 +00001293 << oe->getQualifierLoc().getSourceRange();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001294 Self.NoteAllOverloadCandidates(SrcExpr);
1295 }
1296 return SingleFunctionExpression;
Douglas Gregore81f58e2010-11-08 03:40:48 +00001297}
1298
Douglas Gregorb491ed32011-02-19 21:32:49 +00001299static TryCastResult TryReinterpretCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001300 QualType DestType, bool CStyle,
1301 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001302 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001303 CastKind &Kind) {
Douglas Gregor51954272010-07-13 23:17:26 +00001304 bool IsLValueCast = false;
1305
Sebastian Redl9f831db2009-07-25 15:41:38 +00001306 DestType = Self.Context.getCanonicalType(DestType);
1307 QualType SrcType = SrcExpr->getType();
Douglas Gregore81f58e2010-11-08 03:40:48 +00001308
1309 // Is the source an overloaded name? (i.e. &foo)
Douglas Gregorb491ed32011-02-19 21:32:49 +00001310 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ...
1311 if (SrcType == Self.Context.OverloadTy) {
1312 // ... unless foo<int> resolves to an lvalue unambiguously
1313 ExprResult SingleFunctionExpr =
1314 ResolveAndFixSingleFunctionTemplateSpecialization(Self, SrcExpr,
1315 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
1316 );
1317 if (SingleFunctionExpr.isUsable()) {
1318 SrcExpr = SingleFunctionExpr.release();
1319 SrcType = SrcExpr->getType();
1320 }
1321 else
1322 return TC_NotApplicable;
1323 }
Douglas Gregore81f58e2010-11-08 03:40:48 +00001324
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001325 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001326 bool LValue = DestTypeTmp->isLValueReferenceType();
John McCall086a4642010-11-24 05:12:34 +00001327 if (LValue && !SrcExpr->isLValue()) {
Douglas Gregorc1ed20c2011-01-22 00:19:52 +00001328 // Cannot cast non-lvalue to lvalue reference type. See the similar
1329 // comment in const_cast.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001330 msg = diag::err_bad_cxx_cast_rvalue;
1331 return TC_NotApplicable;
1332 }
1333
1334 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1335 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1336 // built-in & and * operators.
1337 // This code does this transformation for the checked types.
1338 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1339 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001340
Douglas Gregor51954272010-07-13 23:17:26 +00001341 IsLValueCast = true;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001342 }
1343
1344 // Canonicalize source for comparison.
1345 SrcType = Self.Context.getCanonicalType(SrcType);
1346
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001347 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1348 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001349 if (DestMemPtr && SrcMemPtr) {
1350 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1351 // can be explicitly converted to an rvalue of type "pointer to member
1352 // of Y of type T2" if T1 and T2 are both function types or both object
1353 // types.
1354 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1355 SrcMemPtr->getPointeeType()->isFunctionType())
1356 return TC_NotApplicable;
1357
1358 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1359 // constness.
1360 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1361 // we accept it.
1362 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1363 msg = diag::err_bad_cxx_cast_const_away;
1364 return TC_Failed;
1365 }
1366
Charles Davisebab1ed2010-08-16 05:30:44 +00001367 // Don't allow casting between member pointers of different sizes.
1368 if (Self.Context.getTypeSize(DestMemPtr) !=
1369 Self.Context.getTypeSize(SrcMemPtr)) {
1370 msg = diag::err_bad_cxx_cast_member_pointer_size;
1371 return TC_Failed;
1372 }
1373
Sebastian Redl9f831db2009-07-25 15:41:38 +00001374 // A valid member pointer cast.
John McCalle3027922010-08-25 11:45:40 +00001375 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001376 return TC_Success;
1377 }
1378
1379 // See below for the enumeral issue.
Douglas Gregor6972a622010-06-16 00:35:25 +00001380 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001381 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1382 // type large enough to hold it. A value of std::nullptr_t can be
1383 // converted to an integral type; the conversion has the same meaning
1384 // and validity as a conversion of (void*)0 to the integral type.
1385 if (Self.Context.getTypeSize(SrcType) >
1386 Self.Context.getTypeSize(DestType)) {
1387 msg = diag::err_bad_reinterpret_cast_small_int;
1388 return TC_Failed;
1389 }
John McCalle3027922010-08-25 11:45:40 +00001390 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001391 return TC_Success;
1392 }
1393
Anders Carlsson570af5d2009-09-16 19:19:43 +00001394 bool destIsVector = DestType->isVectorType();
1395 bool srcIsVector = SrcType->isVectorType();
1396 if (srcIsVector || destIsVector) {
Douglas Gregor6972a622010-06-16 00:35:25 +00001397 // FIXME: Should this also apply to floating point types?
1398 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1399 bool destIsScalar = DestType->isIntegralType(Self.Context);
Anders Carlsson570af5d2009-09-16 19:19:43 +00001400
1401 // Check if this is a cast between a vector and something else.
1402 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1403 !(srcIsVector && destIsVector))
1404 return TC_NotApplicable;
1405
1406 // If both types have the same size, we can successfully cast.
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001407 if (Self.Context.getTypeSize(SrcType)
1408 == Self.Context.getTypeSize(DestType)) {
John McCalle3027922010-08-25 11:45:40 +00001409 Kind = CK_BitCast;
Anders Carlsson570af5d2009-09-16 19:19:43 +00001410 return TC_Success;
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001411 }
Anders Carlsson570af5d2009-09-16 19:19:43 +00001412
1413 if (destIsScalar)
1414 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1415 else if (srcIsScalar)
1416 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1417 else
1418 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1419
1420 return TC_Failed;
1421 }
1422
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001423 bool destIsPtr = DestType->isAnyPointerType() ||
1424 DestType->isBlockPointerType();
1425 bool srcIsPtr = SrcType->isAnyPointerType() ||
1426 SrcType->isBlockPointerType();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001427 if (!destIsPtr && !srcIsPtr) {
1428 // Except for std::nullptr_t->integer and lvalue->reference, which are
1429 // handled above, at least one of the two arguments must be a pointer.
1430 return TC_NotApplicable;
1431 }
1432
1433 if (SrcType == DestType) {
1434 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1435 // restrictions, a cast to the same type is allowed. The intent is not
1436 // entirely clear here, since all other paragraphs explicitly forbid casts
1437 // to the same type. However, the behavior of compilers is pretty consistent
1438 // on this point: allow same-type conversion if the involved types are
1439 // pointers, disallow otherwise.
John McCalle3027922010-08-25 11:45:40 +00001440 Kind = CK_NoOp;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001441 return TC_Success;
1442 }
1443
Douglas Gregor6972a622010-06-16 00:35:25 +00001444 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001445 assert(srcIsPtr && "One type must be a pointer");
1446 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1447 // type large enough to hold it.
1448 if (Self.Context.getTypeSize(SrcType) >
1449 Self.Context.getTypeSize(DestType)) {
1450 msg = diag::err_bad_reinterpret_cast_small_int;
1451 return TC_Failed;
1452 }
John McCalle3027922010-08-25 11:45:40 +00001453 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001454 return TC_Success;
1455 }
1456
Douglas Gregorb90df602010-06-16 00:17:44 +00001457 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001458 assert(destIsPtr && "One type must be a pointer");
1459 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1460 // converted to a pointer.
John McCalle84af4e2010-11-13 01:35:44 +00001461 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1462 // necessarily converted to a null pointer value.]
John McCalle3027922010-08-25 11:45:40 +00001463 Kind = CK_IntegralToPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001464 return TC_Success;
1465 }
1466
1467 if (!destIsPtr || !srcIsPtr) {
1468 // With the valid non-pointer conversions out of the way, we can be even
1469 // more stringent.
1470 return TC_NotApplicable;
1471 }
1472
1473 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1474 // The C-style cast operator can.
1475 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1476 msg = diag::err_bad_cxx_cast_const_away;
1477 return TC_Failed;
1478 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001479
1480 // Cannot convert between block pointers and Objective-C object pointers.
1481 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1482 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1483 return TC_NotApplicable;
1484
1485 // Any pointer can be cast to an Objective-C pointer type with a C-style
1486 // cast.
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001487 if (CStyle && DestType->isObjCObjectPointerType()) {
John McCalle3027922010-08-25 11:45:40 +00001488 Kind = CK_AnyPointerToObjCPointerCast;
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001489 return TC_Success;
1490 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001491
Sebastian Redl9f831db2009-07-25 15:41:38 +00001492 // Not casting away constness, so the only remaining check is for compatible
1493 // pointer categories.
John McCalle3027922010-08-25 11:45:40 +00001494 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001495
1496 if (SrcType->isFunctionPointerType()) {
1497 if (DestType->isFunctionPointerType()) {
1498 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1499 // a pointer to a function of a different type.
1500 return TC_Success;
1501 }
1502
1503 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1504 // an object type or vice versa is conditionally-supported.
1505 // Compilers support it in C++03 too, though, because it's necessary for
1506 // casting the return value of dlsym() and GetProcAddress().
1507 // FIXME: Conditionally-supported behavior should be configurable in the
1508 // TargetInfo or similar.
1509 if (!Self.getLangOptions().CPlusPlus0x)
1510 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1511 return TC_Success;
1512 }
1513
1514 if (DestType->isFunctionPointerType()) {
1515 // See above.
1516 if (!Self.getLangOptions().CPlusPlus0x)
1517 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1518 return TC_Success;
1519 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001520
Sebastian Redl9f831db2009-07-25 15:41:38 +00001521 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1522 // a pointer to an object of different type.
1523 // Void pointers are not specified, but supported by every compiler out there.
1524 // So we finish by allowing everything that remains - it's got to be two
1525 // object pointers.
1526 return TC_Success;
John McCall909acf82011-02-14 18:34:10 +00001527}
Sebastian Redl9f831db2009-07-25 15:41:38 +00001528
Anders Carlssona70cff62010-04-24 19:06:50 +00001529bool
John McCall7decc9e2010-11-18 06:31:45 +00001530Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, ExprValueKind &VK,
1531 Expr *&CastExpr, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001532 CXXCastPath &BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00001533 bool FunctionalStyle) {
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00001534 if (CastExpr->isBoundMemberFunction(Context))
1535 return Diag(CastExpr->getLocStart(),
1536 diag::err_invalid_use_of_bound_member_func)
1537 << CastExpr->getSourceRange();
1538
Sebastian Redl9f831db2009-07-25 15:41:38 +00001539 // This test is outside everything else because it's the only case where
1540 // a non-lvalue-reference target type does not lead to decay.
1541 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Anders Carlsson9500ad12009-10-18 20:31:03 +00001542 if (CastTy->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00001543 IgnoredValueConversions(CastExpr);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001544 bool ret = false; // false is 'able to convert'
1545 if (CastExpr->getType() == Context.OverloadTy) {
1546 ExprResult SingleFunctionExpr =
1547 ResolveAndFixSingleFunctionTemplateSpecialization(*this,
1548 CastExpr,
1549 /* Decay Function to ptr */ false,
1550 /* Complain */ true,
1551 R, CastTy, diag::err_bad_cstyle_cast_overload);
1552 if (SingleFunctionExpr.isUsable()) {
1553 CastExpr = SingleFunctionExpr.release();
1554 Kind = CK_ToVoid;
1555 }
1556 else
1557 ret = true;
1558 }
1559 else
1560 Kind = CK_ToVoid;
1561 return ret;
Anders Carlsson9500ad12009-10-18 20:31:03 +00001562 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001563
John McCall4cec5f82010-11-30 02:05:44 +00001564 // Make sure we determine the value kind before we bail out for
1565 // dependent types.
1566 VK = Expr::getValueKindForType(CastTy);
1567
Sebastian Redl9f831db2009-07-25 15:41:38 +00001568 // If the type is dependent, we won't do any other semantic analysis now.
John McCall8cb679e2010-11-15 09:13:47 +00001569 if (CastTy->isDependentType() || CastExpr->isTypeDependent()) {
1570 Kind = CK_Dependent;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001571 return false;
John McCall8cb679e2010-11-15 09:13:47 +00001572 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001573
John McCall7decc9e2010-11-18 06:31:45 +00001574 if (VK == VK_RValue && !CastTy->isRecordType())
Douglas Gregorb92a1562010-02-03 00:27:59 +00001575 DefaultFunctionArrayLvalueConversion(CastExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001576
1577 // C++ [expr.cast]p5: The conversions performed by
1578 // - a const_cast,
1579 // - a static_cast,
1580 // - a static_cast followed by a const_cast,
1581 // - a reinterpret_cast, or
1582 // - a reinterpret_cast followed by a const_cast,
1583 // can be performed using the cast notation of explicit type conversion.
1584 // [...] If a conversion can be interpreted in more than one of the ways
1585 // listed above, the interpretation that appears first in the list is used,
1586 // even if a cast resulting from that interpretation is ill-formed.
1587 // In plain language, this means trying a const_cast ...
1588 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssonf1ae6d42009-09-01 20:52:42 +00001589 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1590 msg);
Anders Carlsson027732b2009-10-19 18:14:28 +00001591 if (tcr == TC_Success)
John McCalle3027922010-08-25 11:45:40 +00001592 Kind = CK_NoOp;
Anders Carlsson027732b2009-10-19 18:14:28 +00001593
Sebastian Redl9f831db2009-07-25 15:41:38 +00001594 if (tcr == TC_NotApplicable) {
1595 // ... or if that is not possible, a static_cast, ignoring const, ...
Anders Carlssona70cff62010-04-24 19:06:50 +00001596 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg, Kind,
1597 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001598 if (tcr == TC_NotApplicable) {
1599 // ... and finally a reinterpret_cast, ignoring const.
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001600 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1601 Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001602 }
1603 }
1604
Nick Lewycky14d88eb2010-11-09 00:19:31 +00001605 if (tcr != TC_Success && msg != 0) {
1606 if (CastExpr->getType() == Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +00001607 DeclAccessPair Found;
Nick Lewycky14d88eb2010-11-09 00:19:31 +00001608 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(CastExpr,
Douglas Gregore81f58e2010-11-08 03:40:48 +00001609 CastTy,
1610 /* Complain */ true,
1611 Found);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001612
1613 assert(!Fn
1614 && "cast failed but able to resolve overload expression!!");
Nick Lewycky14d88eb2010-11-09 00:19:31 +00001615 (void)Fn;
John McCall909acf82011-02-14 18:34:10 +00001616
Nick Lewycky14d88eb2010-11-09 00:19:31 +00001617 } else {
John McCall909acf82011-02-14 18:34:10 +00001618 diagnoseBadCast(*this, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
1619 R, CastExpr, CastTy);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001620 }
1621 }
John McCalld50a2712010-11-16 05:46:29 +00001622 else if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00001623 CheckCastAlign(CastExpr, CastTy, R);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001624
1625 return tcr != TC_Success;
1626}