blob: 30bb5763f2116d2918fe702f5b6075d2e75b4b99 [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
25static void NoteAllOverloadCandidates(Expr* const Expr, Sema& sema);
26
Sebastian Redl9f831db2009-07-25 15:41:38 +000027enum TryCastResult {
28 TC_NotApplicable, ///< The cast method is not applicable.
29 TC_Success, ///< The cast method is appropriate and successful.
30 TC_Failed ///< The cast method is appropriate, but failed. A
31 ///< diagnostic has been emitted.
32};
33
34enum CastType {
35 CT_Const, ///< const_cast
36 CT_Static, ///< static_cast
37 CT_Reinterpret, ///< reinterpret_cast
38 CT_Dynamic, ///< dynamic_cast
39 CT_CStyle, ///< (Type)expr
40 CT_Functional ///< Type(expr)
Sebastian Redl842ef522008-11-08 13:00:26 +000041};
42
Douglas Gregore81f58e2010-11-08 03:40:48 +000043
44
45
Sebastian Redl842ef522008-11-08 13:00:26 +000046static void CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
John McCall7decc9e2010-11-18 06:31:45 +000047 ExprValueKind &VK,
Sebastian Redl842ef522008-11-08 13:00:26 +000048 const SourceRange &OpRange,
49 const SourceRange &DestRange);
50static void CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
John McCall7decc9e2010-11-18 06:31:45 +000051 ExprValueKind &VK,
Sebastian Redl842ef522008-11-08 13:00:26 +000052 const SourceRange &OpRange,
Anders Carlsson7cd39e02009-09-15 04:48:33 +000053 const SourceRange &DestRange,
John McCalle3027922010-08-25 11:45:40 +000054 CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +000055static void CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
John McCall7decc9e2010-11-18 06:31:45 +000056 ExprValueKind &VK,
Anders Carlssonf10e4142009-08-07 22:21:05 +000057 const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +000058 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +000059 CXXCastPath &BasePath);
Sebastian Redl842ef522008-11-08 13:00:26 +000060static void CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
John McCall7decc9e2010-11-18 06:31:45 +000061 ExprValueKind &VK,
Sebastian Redl842ef522008-11-08 13:00:26 +000062 const SourceRange &OpRange,
Mike Stump11289f42009-09-09 15:08:12 +000063 const SourceRange &DestRange,
John McCalle3027922010-08-25 11:45:40 +000064 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +000065 CXXCastPath &BasePath);
Sebastian Redl842ef522008-11-08 13:00:26 +000066
67static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
Sebastian Redl9f831db2009-07-25 15:41:38 +000068
69// The Try functions attempt a specific way of casting. If they succeed, they
70// return TC_Success. If their way of casting is not appropriate for the given
71// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
72// to emit if no other way succeeds. If their way of casting is appropriate but
73// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
74// they emit a specialized diagnostic.
75// All diagnostics returned by these functions must expect the same three
76// arguments:
77// %0: Cast Type (a value from the CastType enumeration)
78// %1: Source Type
79// %2: Destination Type
80static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
Douglas Gregorce950842011-01-26 21:04:06 +000081 QualType DestType, bool CStyle,
82 CastKind &Kind,
Douglas Gregorba278e22011-01-25 16:13:26 +000083 CXXCastPath &BasePath,
84 unsigned &msg);
Sebastian Redl9f831db2009-07-25 15:41:38 +000085static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
Anders Carlsson7d3360f2010-04-24 19:36:51 +000086 QualType DestType, bool CStyle,
87 const SourceRange &OpRange,
88 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +000089 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +000090 CXXCastPath &BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +000091static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
92 QualType DestType, bool CStyle,
93 const SourceRange &OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +000094 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +000095 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +000096 CXXCastPath &BasePath);
Douglas Gregor8f3952c2009-11-15 09:20:52 +000097static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
98 CanQualType DestType, bool CStyle,
Sebastian Redl9f831db2009-07-25 15:41:38 +000099 const SourceRange &OpRange,
100 QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000101 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000102 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000103 CXXCastPath &BasePath);
Douglas Gregorc934bc82010-03-07 23:24:59 +0000104static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000105 QualType SrcType,
106 QualType DestType,bool CStyle,
107 const SourceRange &OpRange,
108 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000109 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000110 CXXCastPath &BasePath);
Anders Carlssonb78feca2010-04-24 19:22:20 +0000111
Sebastian Redl7c353682009-11-14 21:15:49 +0000112static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000113 QualType DestType, bool CStyle,
114 const SourceRange &OpRange,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000115 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000116 CastKind &Kind);
Sebastian Redl7c353682009-11-14 21:15:49 +0000117static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000118 QualType DestType, bool CStyle,
119 const SourceRange &OpRange,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000120 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000121 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000122 CXXCastPath &BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000123static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
124 bool CStyle, unsigned &msg);
125static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
126 QualType DestType, bool CStyle,
127 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000128 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000129 CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +0000130
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000131/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
John McCalldadc5752010-08-24 06:29:42 +0000132ExprResult
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000133Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John McCallba7bf592010-08-24 05:47:05 +0000134 SourceLocation LAngleBracketLoc, ParsedType Ty,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000135 SourceLocation RAngleBracketLoc,
John McCallfaf5fb42010-08-26 23:41:50 +0000136 SourceLocation LParenLoc, Expr *E,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000137 SourceLocation RParenLoc) {
John McCalld377e042010-01-15 19:13:16 +0000138
John McCall97513962010-01-15 18:39:57 +0000139 TypeSourceInfo *DestTInfo;
140 QualType DestType = GetTypeFromParser(Ty, &DestTInfo);
141 if (!DestTInfo)
142 DestTInfo = Context.getTrivialTypeSourceInfo(DestType, SourceLocation());
John McCalld377e042010-01-15 19:13:16 +0000143
144 return BuildCXXNamedCast(OpLoc, Kind, DestTInfo, move(E),
145 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
146 SourceRange(LParenLoc, RParenLoc));
147}
148
John McCalldadc5752010-08-24 06:29:42 +0000149ExprResult
John McCalld377e042010-01-15 19:13:16 +0000150Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John McCallfaf5fb42010-08-26 23:41:50 +0000151 TypeSourceInfo *DestTInfo, Expr *Ex,
John McCalld377e042010-01-15 19:13:16 +0000152 SourceRange AngleBrackets, SourceRange Parens) {
John McCalld377e042010-01-15 19:13:16 +0000153 QualType DestType = DestTInfo->getType();
154
155 SourceRange OpRange(OpLoc, Parens.getEnd());
156 SourceRange DestRange = AngleBrackets;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000157
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000158 // If the type is dependent, we won't do the semantic analysis now.
159 // FIXME: should we check this in a more fine-grained manner?
160 bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
161
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +0000162 if (Ex->isBoundMemberFunction(Context))
163 Diag(Ex->getLocStart(), diag::err_invalid_use_of_bound_member_func)
164 << Ex->getSourceRange();
165
John McCall7decc9e2010-11-18 06:31:45 +0000166 ExprValueKind VK = VK_RValue;
John McCall29ac8e22010-11-26 10:57:22 +0000167 if (TypeDependent)
168 VK = Expr::getValueKindForType(DestType);
169
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000170 switch (Kind) {
John McCall8cb679e2010-11-15 09:13:47 +0000171 default: llvm_unreachable("Unknown C++ cast!");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000172
173 case tok::kw_const_cast:
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000174 if (!TypeDependent)
John McCall7decc9e2010-11-18 06:31:45 +0000175 CheckConstCast(*this, Ex, DestType, VK, OpRange, DestRange);
John McCallcf142162010-08-07 06:22:56 +0000176 return Owned(CXXConstCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +0000177 DestType.getNonLValueExprType(Context),
Douglas Gregor4478f852011-01-12 22:41:29 +0000178 VK, Ex, DestTInfo, OpLoc,
179 Parens.getEnd()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000180
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000181 case tok::kw_dynamic_cast: {
John McCall8cb679e2010-11-15 09:13:47 +0000182 CastKind Kind = CK_Dependent;
John McCallcf142162010-08-07 06:22:56 +0000183 CXXCastPath BasePath;
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000184 if (!TypeDependent)
John McCall7decc9e2010-11-18 06:31:45 +0000185 CheckDynamicCast(*this, Ex, DestType, VK, OpRange, DestRange,
186 Kind, BasePath);
John McCallcf142162010-08-07 06:22:56 +0000187 return Owned(CXXDynamicCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +0000188 DestType.getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +0000189 VK, Kind, Ex, &BasePath, DestTInfo,
Douglas Gregor4478f852011-01-12 22:41:29 +0000190 OpLoc, Parens.getEnd()));
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000191 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000192 case tok::kw_reinterpret_cast: {
John McCall8cb679e2010-11-15 09:13:47 +0000193 CastKind Kind = CK_Dependent;
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000194 if (!TypeDependent)
John McCall7decc9e2010-11-18 06:31:45 +0000195 CheckReinterpretCast(*this, Ex, DestType, VK, OpRange, DestRange, Kind);
John McCallcf142162010-08-07 06:22:56 +0000196 return Owned(CXXReinterpretCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +0000197 DestType.getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +0000198 VK, Kind, Ex, 0,
Douglas Gregor4478f852011-01-12 22:41:29 +0000199 DestTInfo, OpLoc, Parens.getEnd()));
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000200 }
Anders Carlssonf10e4142009-08-07 22:21:05 +0000201 case tok::kw_static_cast: {
John McCall8cb679e2010-11-15 09:13:47 +0000202 CastKind Kind = CK_Dependent;
John McCallcf142162010-08-07 06:22:56 +0000203 CXXCastPath BasePath;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000204 if (!TypeDependent)
John McCall7decc9e2010-11-18 06:31:45 +0000205 CheckStaticCast(*this, Ex, DestType, VK, OpRange, Kind, BasePath);
Anders Carlssone9766d52009-09-09 21:33:21 +0000206
John McCallcf142162010-08-07 06:22:56 +0000207 return Owned(CXXStaticCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +0000208 DestType.getNonLValueExprType(Context),
John McCall7decc9e2010-11-18 06:31:45 +0000209 VK, Kind, Ex, &BasePath,
Douglas Gregor4478f852011-01-12 22:41:29 +0000210 DestTInfo, OpLoc, Parens.getEnd()));
Anders Carlssonf10e4142009-08-07 22:21:05 +0000211 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000212 }
213
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000214 return ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000215}
216
John McCall909acf82011-02-14 18:34:10 +0000217/// Try to diagnose a failed overloaded cast. Returns true if
218/// diagnostics were emitted.
219static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
220 SourceRange range, Expr *src,
221 QualType destType) {
222 switch (CT) {
223 // These cast kinds don't consider user-defined conversions.
224 case CT_Const:
225 case CT_Reinterpret:
226 case CT_Dynamic:
227 return false;
228
229 // These do.
230 case CT_Static:
231 case CT_CStyle:
232 case CT_Functional:
233 break;
234 }
235
236 QualType srcType = src->getType();
237 if (!destType->isRecordType() && !srcType->isRecordType())
238 return false;
239
240 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
241 InitializationKind initKind
242 = InitializationKind::CreateCast(/*type range?*/ range,
243 (CT == CT_CStyle || CT == CT_Functional));
244 InitializationSequence sequence(S, entity, initKind, &src, 1);
245
246 assert(sequence.getKind() == InitializationSequence::FailedSequence &&
247 "initialization succeeded on second try?");
248 switch (sequence.getFailureKind()) {
249 default: return false;
250
251 case InitializationSequence::FK_ConstructorOverloadFailed:
252 case InitializationSequence::FK_UserConversionOverloadFailed:
253 break;
254 }
255
256 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
257
258 unsigned msg = 0;
259 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
260
261 switch (sequence.getFailedOverloadResult()) {
262 case OR_Success: llvm_unreachable("successful failed overload");
263 return false;
264 case OR_No_Viable_Function:
265 if (candidates.empty())
266 msg = diag::err_ovl_no_conversion_in_cast;
267 else
268 msg = diag::err_ovl_no_viable_conversion_in_cast;
269 howManyCandidates = OCD_AllCandidates;
270 break;
271
272 case OR_Ambiguous:
273 msg = diag::err_ovl_ambiguous_conversion_in_cast;
274 howManyCandidates = OCD_ViableCandidates;
275 break;
276
277 case OR_Deleted:
278 msg = diag::err_ovl_deleted_conversion_in_cast;
279 howManyCandidates = OCD_ViableCandidates;
280 break;
281 }
282
283 S.Diag(range.getBegin(), msg)
284 << CT << srcType << destType
285 << range << src->getSourceRange();
286
287 candidates.NoteCandidates(S, howManyCandidates, &src, 1);
288
289 return true;
290}
291
292/// Diagnose a failed cast.
293static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
294 SourceRange opRange, Expr *src, QualType destType) {
295 if (msg == diag::err_bad_cxx_cast_generic &&
296 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType))
297 return;
298
299 S.Diag(opRange.getBegin(), msg) << castType
300 << src->getType() << destType << opRange << src->getSourceRange();
301}
302
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000303/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
304/// this removes one level of indirection from both types, provided that they're
305/// the same kind of pointer (plain or to-member). Unlike the Sema function,
306/// this one doesn't care if the two pointers-to-member don't point into the
307/// same class. This is because CastsAwayConstness doesn't care.
Dan Gohman28ade552010-07-26 21:25:24 +0000308static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000309 const PointerType *T1PtrType = T1->getAs<PointerType>(),
310 *T2PtrType = T2->getAs<PointerType>();
311 if (T1PtrType && T2PtrType) {
312 T1 = T1PtrType->getPointeeType();
313 T2 = T2PtrType->getPointeeType();
314 return true;
315 }
Fariborz Jahanian8c3f06d2010-02-03 20:32:31 +0000316 const ObjCObjectPointerType *T1ObjCPtrType =
317 T1->getAs<ObjCObjectPointerType>(),
318 *T2ObjCPtrType =
319 T2->getAs<ObjCObjectPointerType>();
320 if (T1ObjCPtrType) {
321 if (T2ObjCPtrType) {
322 T1 = T1ObjCPtrType->getPointeeType();
323 T2 = T2ObjCPtrType->getPointeeType();
324 return true;
325 }
326 else if (T2PtrType) {
327 T1 = T1ObjCPtrType->getPointeeType();
328 T2 = T2PtrType->getPointeeType();
329 return true;
330 }
331 }
332 else if (T2ObjCPtrType) {
333 if (T1PtrType) {
334 T2 = T2ObjCPtrType->getPointeeType();
335 T1 = T1PtrType->getPointeeType();
336 return true;
337 }
338 }
339
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000340 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
341 *T2MPType = T2->getAs<MemberPointerType>();
342 if (T1MPType && T2MPType) {
343 T1 = T1MPType->getPointeeType();
344 T2 = T2MPType->getPointeeType();
345 return true;
346 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000347
348 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
349 *T2BPType = T2->getAs<BlockPointerType>();
350 if (T1BPType && T2BPType) {
351 T1 = T1BPType->getPointeeType();
352 T2 = T2BPType->getPointeeType();
353 return true;
354 }
355
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000356 return false;
357}
358
Sebastian Redla5a77a62009-01-27 23:18:31 +0000359/// CastsAwayConstness - Check if the pointer conversion from SrcType to
360/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
361/// the cast checkers. Both arguments must denote pointer (possibly to member)
362/// types.
Sebastian Redl802f14c2009-10-22 15:07:22 +0000363static bool
Mike Stump11289f42009-09-09 15:08:12 +0000364CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
Sebastian Redla5a77a62009-01-27 23:18:31 +0000365 // Casting away constness is defined in C++ 5.2.11p8 with reference to
366 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
367 // the rules are non-trivial. So first we construct Tcv *...cv* as described
368 // in C++ 5.2.11p8.
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000369 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
370 SrcType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000371 "Source type is not pointer or pointer to member.");
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000372 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
373 DestType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000374 "Destination type is not pointer or pointer to member.");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000375
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000376 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
377 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
John McCall8ccfcb52009-09-24 19:53:00 +0000378 llvm::SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000379
380 // Find the qualifications.
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000381 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
Anders Carlsson76f513f2010-06-04 22:47:55 +0000382 Qualifiers SrcQuals;
383 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
384 cv1.push_back(SrcQuals);
385
386 Qualifiers DestQuals;
387 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
388 cv2.push_back(DestQuals);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000389 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000390 if (cv1.empty())
391 return false;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000392
393 // Construct void pointers with those qualifiers (in reverse order of
394 // unwrapping, of course).
Sebastian Redl842ef522008-11-08 13:00:26 +0000395 QualType SrcConstruct = Self.Context.VoidTy;
396 QualType DestConstruct = Self.Context.VoidTy;
John McCall8ccfcb52009-09-24 19:53:00 +0000397 ASTContext &Context = Self.Context;
398 for (llvm::SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
399 i2 = cv2.rbegin();
Mike Stump11289f42009-09-09 15:08:12 +0000400 i1 != cv1.rend(); ++i1, ++i2) {
John McCall8ccfcb52009-09-24 19:53:00 +0000401 SrcConstruct
402 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
403 DestConstruct
404 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000405 }
406
407 // Test if they're compatible.
408 return SrcConstruct != DestConstruct &&
Douglas Gregor58281352011-01-27 00:58:17 +0000409 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000410}
411
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000412/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
413/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
414/// checked downcasts in class hierarchies.
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000415static void
Sebastian Redl842ef522008-11-08 13:00:26 +0000416CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
John McCall7decc9e2010-11-18 06:31:45 +0000417 ExprValueKind &VK, const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +0000418 const SourceRange &DestRange, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000419 CXXCastPath &BasePath) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000420 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl842ef522008-11-08 13:00:26 +0000421 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000422
423 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
424 // or "pointer to cv void".
425
426 QualType DestPointee;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000427 const PointerType *DestPointer = DestType->getAs<PointerType>();
John McCall7decc9e2010-11-18 06:31:45 +0000428 const ReferenceType *DestReference = 0;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000429 if (DestPointer) {
430 DestPointee = DestPointer->getPointeeType();
John McCall7decc9e2010-11-18 06:31:45 +0000431 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000432 DestPointee = DestReference->getPointeeType();
Douglas Gregor465184a2011-01-22 00:06:57 +0000433 VK = isa<LValueReferenceType>(DestReference) ? VK_LValue
434 : isa<RValueReferenceType>(DestReference) ? VK_XValue
435 : VK_RValue;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000436 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000437 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000438 << OrigDestType << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000439 return;
440 }
441
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000442 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000443 if (DestPointee->isVoidType()) {
444 assert(DestPointer && "Reference to void is not possible");
445 } else if (DestRecord) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000446 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor89336232010-03-29 23:34:08 +0000447 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssond624e162009-08-26 23:45:07 +0000448 << DestRange))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000449 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000450 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000451 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000452 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000453 return;
454 }
455
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000456 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
457 // complete class type, [...]. If T is an lvalue reference type, v shall be
Douglas Gregor465184a2011-01-22 00:06:57 +0000458 // an lvalue of a complete class type, [...]. If T is an rvalue reference
459 // type, v shall be an expression having a complete class type, [...]
Sebastian Redl842ef522008-11-08 13:00:26 +0000460 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000461 QualType SrcPointee;
462 if (DestPointer) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000463 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000464 SrcPointee = SrcPointer->getPointeeType();
465 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000466 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000467 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000468 return;
469 }
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000470 } else if (DestReference->isLValueReferenceType()) {
John McCall086a4642010-11-24 05:12:34 +0000471 if (!SrcExpr->isLValue()) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000472 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000473 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000474 }
475 SrcPointee = SrcType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000476 } else {
477 SrcPointee = SrcType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000478 }
479
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000480 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000481 if (SrcRecord) {
Douglas Gregored0cfbd2009-03-09 16:13:40 +0000482 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor89336232010-03-29 23:34:08 +0000483 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssond624e162009-08-26 23:45:07 +0000484 << SrcExpr->getSourceRange()))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000485 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000486 } else {
Chris Lattner29e812b2008-11-20 06:06:08 +0000487 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000488 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000489 return;
490 }
491
492 assert((DestPointer || DestReference) &&
493 "Bad destination non-ptr/ref slipped through.");
494 assert((DestRecord || DestPointee->isVoidType()) &&
495 "Bad destination pointee slipped through.");
496 assert(SrcRecord && "Bad source pointee slipped through.");
497
498 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
499 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000500 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000501 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000502 return;
503 }
504
505 // C++ 5.2.7p3: If the type of v is the same as the required result type,
506 // [except for cv].
507 if (DestRecord == SrcRecord) {
John McCalle3027922010-08-25 11:45:40 +0000508 Kind = CK_NoOp;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000509 return;
510 }
511
512 // C++ 5.2.7p5
513 // Upcasts are resolved statically.
Sebastian Redl842ef522008-11-08 13:00:26 +0000514 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000515 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
516 OpRange.getBegin(), OpRange,
517 &BasePath))
518 return;
519
John McCalle3027922010-08-25 11:45:40 +0000520 Kind = CK_DerivedToBase;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000521
522 // If we are casting to or through a virtual base class, we need a
523 // vtable.
524 if (Self.BasePathInvolvesVirtualBase(BasePath))
525 Self.MarkVTableUsed(OpRange.getBegin(),
526 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000527 return;
528 }
529
530 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000531 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000532 assert(SrcDecl && "Definition missing");
533 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner29e812b2008-11-20 06:06:08 +0000534 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000535 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000536 }
Douglas Gregor88d292c2010-05-13 16:44:06 +0000537 Self.MarkVTableUsed(OpRange.getBegin(),
538 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000539
540 // Done. Everything else is run-time checks.
John McCalle3027922010-08-25 11:45:40 +0000541 Kind = CK_Dynamic;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000542}
Sebastian Redl9f831db2009-07-25 15:41:38 +0000543
544/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
545/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
546/// like this:
547/// const char *str = "literal";
548/// legacy_function(const_cast\<char*\>(str));
549void
John McCall7decc9e2010-11-18 06:31:45 +0000550CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType, ExprValueKind &VK,
Mike Stump11289f42009-09-09 15:08:12 +0000551 const SourceRange &OpRange, const SourceRange &DestRange) {
John McCall7decc9e2010-11-18 06:31:45 +0000552 VK = Expr::getValueKindForType(DestType);
553 if (VK == VK_RValue)
Douglas Gregorb92a1562010-02-03 00:27:59 +0000554 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000555
556 unsigned msg = diag::err_bad_cxx_cast_generic;
557 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
558 && msg != 0)
559 Self.Diag(OpRange.getBegin(), msg) << CT_Const
560 << SrcExpr->getType() << DestType << OpRange;
561}
562
563/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
564/// valid.
565/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
566/// like this:
567/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
568void
569CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
John McCall7decc9e2010-11-18 06:31:45 +0000570 ExprValueKind &VK, const SourceRange &OpRange,
571 const SourceRange &DestRange, CastKind &Kind) {
572 VK = Expr::getValueKindForType(DestType);
573 if (VK == VK_RValue)
Douglas Gregorb92a1562010-02-03 00:27:59 +0000574 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000575
576 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000577 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
578 msg, Kind)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000579 != TC_Success && msg != 0)
Douglas Gregore81f58e2010-11-08 03:40:48 +0000580 {
John McCall909acf82011-02-14 18:34:10 +0000581 if (SrcExpr->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +0000582 //FIXME: &f<int>; is overloaded and resolvable
583 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
584 << OverloadExpr::find(SrcExpr).Expression->getName()
585 << DestType << OpRange;
586 NoteAllOverloadCandidates(SrcExpr, Self);
587
John McCall909acf82011-02-14 18:34:10 +0000588 } else {
589 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr, DestType);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000590 }
John McCall909acf82011-02-14 18:34:10 +0000591 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000592}
593
594
595/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
596/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
597/// implicit conversions explicit and getting rid of data loss warnings.
598void
599CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
John McCall7decc9e2010-11-18 06:31:45 +0000600 ExprValueKind &VK, const SourceRange &OpRange,
601 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000602 // This test is outside everything else because it's the only case where
603 // a non-lvalue-reference target type does not lead to decay.
604 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman03bf60a2009-11-16 05:44:20 +0000605 if (DestType->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +0000606 Self.IgnoredValueConversions(SrcExpr);
John McCalle3027922010-08-25 11:45:40 +0000607 Kind = CK_ToVoid;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000608 return;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000609 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000610
John McCall7decc9e2010-11-18 06:31:45 +0000611 VK = Expr::getValueKindForType(DestType);
612 if (VK == VK_RValue && !DestType->isRecordType())
Douglas Gregorb92a1562010-02-03 00:27:59 +0000613 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000614
615 unsigned msg = diag::err_bad_cxx_cast_generic;
Sebastian Redl7c353682009-11-14 21:15:49 +0000616 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg,
Anders Carlssona70cff62010-04-24 19:06:50 +0000617 Kind, BasePath) != TC_Success && msg != 0)
Douglas Gregore81f58e2010-11-08 03:40:48 +0000618 {
John McCall909acf82011-02-14 18:34:10 +0000619 if (SrcExpr->getType() == Self.Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +0000620 OverloadExpr* oe = OverloadExpr::find(SrcExpr).Expression;
621 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
622 << oe->getName() << DestType << OpRange << oe->getQualifierRange();
623 NoteAllOverloadCandidates(SrcExpr, Self);
John McCall909acf82011-02-14 18:34:10 +0000624 } else {
625 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr, DestType);
Douglas Gregore81f58e2010-11-08 03:40:48 +0000626 }
Douglas Gregore81f58e2010-11-08 03:40:48 +0000627 }
John McCalld50a2712010-11-16 05:46:29 +0000628 else if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +0000629 Self.CheckCastAlign(SrcExpr, DestType, OpRange);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000630}
631
632/// TryStaticCast - Check if a static cast can be performed, and do so if
633/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
634/// and casting away constness.
Sebastian Redl7c353682009-11-14 21:15:49 +0000635static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000636 QualType DestType, bool CStyle,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000637 const SourceRange &OpRange, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000638 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000639 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000640 // The order the tests is not entirely arbitrary. There is one conversion
641 // that can be handled in two different ways. Given:
642 // struct A {};
643 // struct B : public A {
644 // B(); B(const A&);
645 // };
646 // const A &a = B();
647 // the cast static_cast<const B&>(a) could be seen as either a static
648 // reference downcast, or an explicit invocation of the user-defined
649 // conversion using B's conversion constructor.
650 // DR 427 specifies that the downcast is to be applied here.
651
652 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
653 // Done outside this function.
654
655 TryCastResult tcr;
656
657 // C++ 5.2.9p5, reference downcast.
658 // See the function for details.
659 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redl7c353682009-11-14 21:15:49 +0000660 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle, OpRange,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000661 msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000662 if (tcr != TC_NotApplicable)
663 return tcr;
664
Douglas Gregor465184a2011-01-22 00:06:57 +0000665 // C++0x [expr.static.cast]p3:
666 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
667 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Douglas Gregorce950842011-01-26 21:04:06 +0000668 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, CStyle, Kind, BasePath,
669 msg);
Douglas Gregorba278e22011-01-25 16:13:26 +0000670 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000671 return tcr;
672
673 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
674 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000675 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
Douglas Gregorb33eed02010-04-16 22:09:46 +0000676 Kind);
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000677 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000678 return tcr;
Anders Carlssone9766d52009-09-09 21:33:21 +0000679
Sebastian Redl9f831db2009-07-25 15:41:38 +0000680 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
681 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
682 // conversions, subject to further restrictions.
683 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
684 // of qualification conversions impossible.
685 // In the CStyle case, the earlier attempt to const_cast should have taken
686 // care of reverse qualification conversions.
687
Sebastian Redl9f831db2009-07-25 15:41:38 +0000688 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
689
Douglas Gregor0bf31402010-10-08 23:50:27 +0000690 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
Douglas Gregorb327eac2011-02-18 03:01:41 +0000691 // converted to an integral type. [...] A value of a scoped enumeration type
692 // can also be explicitly converted to a floating-point type [...].
693 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
694 if (Enum->getDecl()->isScoped()) {
695 if (DestType->isBooleanType()) {
696 Kind = CK_IntegralToBoolean;
697 return TC_Success;
698 } else if (DestType->isIntegralType(Self.Context)) {
699 Kind = CK_IntegralCast;
700 return TC_Success;
701 } else if (DestType->isRealFloatingType()) {
702 Kind = CK_IntegralToFloating;
703 return TC_Success;
704 }
Douglas Gregor0bf31402010-10-08 23:50:27 +0000705 }
706 }
Douglas Gregorb327eac2011-02-18 03:01:41 +0000707
Sebastian Redl9f831db2009-07-25 15:41:38 +0000708 // Reverse integral promotion/conversion. All such conversions are themselves
709 // again integral promotions or conversions and are thus already handled by
710 // p2 (TryDirectInitialization above).
711 // (Note: any data loss warnings should be suppressed.)
712 // The exception is the reverse of enum->integer, i.e. integer->enum (and
713 // enum->enum). See also C++ 5.2.9p7.
714 // The same goes for reverse floating point promotion/conversion and
715 // floating-integral conversions. Again, only floating->enum is relevant.
716 if (DestType->isEnumeralType()) {
717 if (SrcType->isComplexType() || SrcType->isVectorType()) {
718 // Fall through - these cannot be converted.
Eli Friedman03bf60a2009-11-16 05:44:20 +0000719 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
John McCalle3027922010-08-25 11:45:40 +0000720 Kind = CK_IntegralCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000721 return TC_Success;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000722 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000723 }
724
725 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
726 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000727 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000728 Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000729 if (tcr != TC_NotApplicable)
730 return tcr;
731
732 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
733 // conversion. C++ 5.2.9p9 has additional information.
734 // DR54's access restrictions apply here also.
Douglas Gregorc934bc82010-03-07 23:24:59 +0000735 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000736 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000737 if (tcr != TC_NotApplicable)
738 return tcr;
739
740 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
741 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
742 // just the usual constness stuff.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000743 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000744 QualType SrcPointee = SrcPointer->getPointeeType();
745 if (SrcPointee->isVoidType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000746 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000747 QualType DestPointee = DestPointer->getPointeeType();
748 if (DestPointee->isIncompleteOrObjectType()) {
749 // This is definitely the intended conversion, but it might fail due
750 // to a const violation.
751 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
752 msg = diag::err_bad_cxx_cast_const_away;
753 return TC_Failed;
754 }
John McCalle3027922010-08-25 11:45:40 +0000755 Kind = CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000756 return TC_Success;
757 }
758 }
Fariborz Jahanianeee16692010-05-10 23:46:53 +0000759 else if (DestType->isObjCObjectPointerType()) {
760 // allow both c-style cast and static_cast of objective-c pointers as
761 // they are pervasive.
John McCalle3027922010-08-25 11:45:40 +0000762 Kind = CK_AnyPointerToObjCPointerCast;
Fariborz Jahanian859c4152009-12-08 23:09:15 +0000763 return TC_Success;
764 }
Fariborz Jahanianffe912c2009-12-11 22:40:48 +0000765 else if (CStyle && DestType->isBlockPointerType()) {
766 // allow c-style cast of void * to block pointers.
John McCalle3027922010-08-25 11:45:40 +0000767 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanianffe912c2009-12-11 22:40:48 +0000768 return TC_Success;
769 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000770 }
771 }
Fariborz Jahanianb0901b72010-05-12 18:16:59 +0000772 // Allow arbitray objective-c pointer conversion with static casts.
773 if (SrcType->isObjCObjectPointerType() &&
John McCall8cb679e2010-11-15 09:13:47 +0000774 DestType->isObjCObjectPointerType()) {
775 Kind = CK_BitCast;
Fariborz Jahanianb0901b72010-05-12 18:16:59 +0000776 return TC_Success;
John McCall8cb679e2010-11-15 09:13:47 +0000777 }
Fariborz Jahanianb0901b72010-05-12 18:16:59 +0000778
Sebastian Redl9f831db2009-07-25 15:41:38 +0000779 // We tried everything. Everything! Nothing works! :-(
780 return TC_NotApplicable;
781}
782
783/// Tests whether a conversion according to N2844 is valid.
784TryCastResult
785TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Douglas Gregorce950842011-01-26 21:04:06 +0000786 bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
787 unsigned &msg) {
Douglas Gregor465184a2011-01-22 00:06:57 +0000788 // C++0x [expr.static.cast]p3:
789 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
790 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000791 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000792 if (!R)
793 return TC_NotApplicable;
794
Douglas Gregor465184a2011-01-22 00:06:57 +0000795 if (!SrcExpr->isGLValue())
Sebastian Redl9f831db2009-07-25 15:41:38 +0000796 return TC_NotApplicable;
797
798 // Because we try the reference downcast before this function, from now on
799 // this is the only cast possibility, so we issue an error if we fail now.
800 // FIXME: Should allow casting away constness if CStyle.
801 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +0000802 bool ObjCConversion;
Douglas Gregorce950842011-01-26 21:04:06 +0000803 QualType FromType = SrcExpr->getType();
804 QualType ToType = R->getPointeeType();
805 if (CStyle) {
806 FromType = FromType.getUnqualifiedType();
807 ToType = ToType.getUnqualifiedType();
808 }
809
Douglas Gregor3ec1bf22009-11-05 13:06:35 +0000810 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
Douglas Gregorce950842011-01-26 21:04:06 +0000811 ToType, FromType,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +0000812 DerivedToBase, ObjCConversion) <
Sebastian Redl9f831db2009-07-25 15:41:38 +0000813 Sema::Ref_Compatible_With_Added_Qualification) {
814 msg = diag::err_bad_lvalue_to_rvalue_cast;
815 return TC_Failed;
816 }
817
Douglas Gregorba278e22011-01-25 16:13:26 +0000818 if (DerivedToBase) {
819 Kind = CK_DerivedToBase;
820 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
821 /*DetectVirtual=*/true);
822 if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
823 return TC_NotApplicable;
824
825 Self.BuildBasePathArray(Paths, BasePath);
826 } else
827 Kind = CK_NoOp;
828
Sebastian Redl9f831db2009-07-25 15:41:38 +0000829 return TC_Success;
830}
831
832/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
833TryCastResult
834TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
835 bool CStyle, const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +0000836 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000837 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000838 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
839 // cast to type "reference to cv2 D", where D is a class derived from B,
840 // if a valid standard conversion from "pointer to D" to "pointer to B"
841 // exists, cv2 >= cv1, and B is not a virtual base class of D.
842 // In addition, DR54 clarifies that the base must be accessible in the
843 // current context. Although the wording of DR54 only applies to the pointer
844 // variant of this rule, the intent is clearly for it to apply to the this
845 // conversion as well.
846
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000847 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000848 if (!DestReference) {
849 return TC_NotApplicable;
850 }
851 bool RValueRef = DestReference->isRValueReferenceType();
John McCall086a4642010-11-24 05:12:34 +0000852 if (!RValueRef && !SrcExpr->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000853 // We know the left side is an lvalue reference, so we can suggest a reason.
854 msg = diag::err_bad_cxx_cast_rvalue;
855 return TC_NotApplicable;
856 }
857
858 QualType DestPointee = DestReference->getPointeeType();
859
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000860 return TryStaticDowncast(Self,
861 Self.Context.getCanonicalType(SrcExpr->getType()),
862 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000863 OpRange, SrcExpr->getType(), DestType, msg, Kind,
864 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000865}
866
867/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
868TryCastResult
869TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +0000870 bool CStyle, const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +0000871 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000872 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000873 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
874 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
875 // is a class derived from B, if a valid standard conversion from "pointer
876 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
877 // class of D.
878 // In addition, DR54 clarifies that the base must be accessible in the
879 // current context.
880
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000881 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000882 if (!DestPointer) {
883 return TC_NotApplicable;
884 }
885
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000886 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000887 if (!SrcPointer) {
888 msg = diag::err_bad_static_cast_pointer_nonpointer;
889 return TC_NotApplicable;
890 }
891
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000892 return TryStaticDowncast(Self,
893 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
894 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000895 CStyle, OpRange, SrcType, DestType, msg, Kind,
896 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000897}
898
899/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
900/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000901/// DestType is possible and allowed.
Sebastian Redl9f831db2009-07-25 15:41:38 +0000902TryCastResult
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000903TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000904 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000905 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000906 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl802f14c2009-10-22 15:07:22 +0000907 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregor89336232010-03-29 23:34:08 +0000908 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, Self.PDiag(0)) ||
909 Self.RequireCompleteType(OpRange.getBegin(), DestType, Self.PDiag(0)))
Sebastian Redl802f14c2009-10-22 15:07:22 +0000910 return TC_NotApplicable;
911
Sebastian Redl9f831db2009-07-25 15:41:38 +0000912 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000913 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000914 return TC_NotApplicable;
915 }
916
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000917 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000918 /*DetectVirtual=*/true);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000919 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
920 return TC_NotApplicable;
921 }
922
923 // Target type does derive from source type. Now we're serious. If an error
924 // appears now, it's not ignored.
925 // This may not be entirely in line with the standard. Take for example:
926 // struct A {};
927 // struct B : virtual A {
928 // B(A&);
929 // };
Mike Stump11289f42009-09-09 15:08:12 +0000930 //
Sebastian Redl9f831db2009-07-25 15:41:38 +0000931 // void f()
932 // {
933 // (void)static_cast<const B&>(*((A*)0));
934 // }
935 // As far as the standard is concerned, p5 does not apply (A is virtual), so
936 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
937 // However, both GCC and Comeau reject this example, and accepting it would
938 // mean more complex code if we're to preserve the nice error message.
939 // FIXME: Being 100% compliant here would be nice to have.
940
941 // Must preserve cv, as always, unless we're in C-style mode.
942 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
943 msg = diag::err_bad_cxx_cast_const_away;
944 return TC_Failed;
945 }
946
947 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
948 // This code is analoguous to that in CheckDerivedToBaseConversion, except
949 // that it builds the paths in reverse order.
950 // To sum up: record all paths to the base and build a nice string from
951 // them. Use it to spice up the error message.
952 if (!Paths.isRecordingPaths()) {
953 Paths.clear();
954 Paths.setRecordingPaths(true);
955 Self.IsDerivedFrom(DestType, SrcType, Paths);
956 }
957 std::string PathDisplayStr;
958 std::set<unsigned> DisplayedPaths;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000959 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000960 PI != PE; ++PI) {
961 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
962 // We haven't displayed a path to this particular base
963 // class subobject yet.
964 PathDisplayStr += "\n ";
Douglas Gregor36d1b142009-10-06 17:59:45 +0000965 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
966 EE = PI->rend();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000967 EI != EE; ++EI)
968 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000969 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000970 }
971 }
972
973 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000974 << QualType(SrcType).getUnqualifiedType()
975 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9f831db2009-07-25 15:41:38 +0000976 << PathDisplayStr << OpRange;
977 msg = 0;
978 return TC_Failed;
979 }
980
981 if (Paths.getDetectedVirtual() != 0) {
982 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
983 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
984 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
985 msg = 0;
986 return TC_Failed;
987 }
988
John McCallfe9cf0a2011-02-14 23:21:33 +0000989 if (!CStyle) {
990 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
991 SrcType, DestType,
992 Paths.front(),
John McCall1064d7e2010-03-16 05:22:47 +0000993 diag::err_downcast_from_inaccessible_base)) {
John McCallfe9cf0a2011-02-14 23:21:33 +0000994 case Sema::AR_accessible:
995 case Sema::AR_delayed: // be optimistic
996 case Sema::AR_dependent: // be optimistic
997 break;
998
999 case Sema::AR_inaccessible:
1000 msg = 0;
1001 return TC_Failed;
1002 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001003 }
1004
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001005 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001006 Kind = CK_BaseToDerived;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001007 return TC_Success;
1008}
1009
1010/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1011/// C++ 5.2.9p9 is valid:
1012///
1013/// An rvalue of type "pointer to member of D of type cv1 T" can be
1014/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1015/// where B is a base class of D [...].
1016///
1017TryCastResult
Douglas Gregorc934bc82010-03-07 23:24:59 +00001018TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr, QualType SrcType,
1019 QualType DestType, bool CStyle,
1020 const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +00001021 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001022 CXXCastPath &BasePath) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001023 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001024 if (!DestMemPtr)
1025 return TC_NotApplicable;
Douglas Gregorc934bc82010-03-07 23:24:59 +00001026
1027 bool WasOverloadedFunction = false;
John McCall16df1e52010-03-30 21:47:33 +00001028 DeclAccessPair FoundOverload;
Douglas Gregor064fdb22010-04-14 23:11:21 +00001029 if (SrcExpr->getType() == Self.Context.OverloadTy) {
1030 if (FunctionDecl *Fn
1031 = Self.ResolveAddressOfOverloadedFunction(SrcExpr, DestType, false,
1032 FoundOverload)) {
1033 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1034 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1035 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1036 WasOverloadedFunction = true;
1037 }
Douglas Gregorc934bc82010-03-07 23:24:59 +00001038 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00001039
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001040 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001041 if (!SrcMemPtr) {
1042 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1043 return TC_NotApplicable;
1044 }
1045
1046 // T == T, modulo cv
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001047 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1048 DestMemPtr->getPointeeType()))
Sebastian Redl9f831db2009-07-25 15:41:38 +00001049 return TC_NotApplicable;
1050
1051 // B base of D
1052 QualType SrcClass(SrcMemPtr->getClass(), 0);
1053 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssonb78feca2010-04-24 19:22:20 +00001054 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9f831db2009-07-25 15:41:38 +00001055 /*DetectVirtual=*/true);
1056 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
1057 return TC_NotApplicable;
1058 }
1059
1060 // 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 +00001061 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001062 Paths.clear();
1063 Paths.setRecordingPaths(true);
1064 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
1065 assert(StillOkay);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00001066 (void)StillOkay;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001067 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1068 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1069 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1070 msg = 0;
1071 return TC_Failed;
1072 }
1073
1074 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1075 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1076 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1077 msg = 0;
1078 return TC_Failed;
1079 }
1080
John McCallfe9cf0a2011-02-14 23:21:33 +00001081 if (!CStyle) {
1082 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1083 DestClass, SrcClass,
1084 Paths.front(),
1085 diag::err_upcast_to_inaccessible_base)) {
1086 case Sema::AR_accessible:
1087 case Sema::AR_delayed:
1088 case Sema::AR_dependent:
1089 // Optimistically assume that the delayed and dependent cases
1090 // will work out.
1091 break;
1092
1093 case Sema::AR_inaccessible:
1094 msg = 0;
1095 return TC_Failed;
1096 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001097 }
1098
Douglas Gregorc934bc82010-03-07 23:24:59 +00001099 if (WasOverloadedFunction) {
1100 // Resolve the address of the overloaded function again, this time
1101 // allowing complaints if something goes wrong.
1102 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr,
1103 DestType,
John McCall16df1e52010-03-30 21:47:33 +00001104 true,
1105 FoundOverload);
Douglas Gregorc934bc82010-03-07 23:24:59 +00001106 if (!Fn) {
1107 msg = 0;
1108 return TC_Failed;
1109 }
1110
John McCall16df1e52010-03-30 21:47:33 +00001111 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
Douglas Gregorc934bc82010-03-07 23:24:59 +00001112 if (!SrcExpr) {
1113 msg = 0;
1114 return TC_Failed;
1115 }
1116 }
1117
Anders Carlssonb78feca2010-04-24 19:22:20 +00001118 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001119 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001120 return TC_Success;
1121}
1122
1123/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1124/// is valid:
1125///
1126/// An expression e can be explicitly converted to a type T using a
1127/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1128TryCastResult
Sebastian Redl7c353682009-11-14 21:15:49 +00001129TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00001130 bool CStyle, const SourceRange &OpRange, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001131 CastKind &Kind) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +00001132 if (DestType->isRecordType()) {
1133 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1134 diag::err_bad_dynamic_cast_incomplete)) {
1135 msg = 0;
1136 return TC_Failed;
1137 }
1138 }
Douglas Gregorb33eed02010-04-16 22:09:46 +00001139
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001140 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1141 InitializationKind InitKind
Douglas Gregor58281352011-01-27 00:58:17 +00001142 = InitializationKind::CreateCast(/*FIXME:*/OpRange, CStyle);
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001143 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExpr, 1);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001144
1145 // At this point of CheckStaticCast, if the destination is a reference,
1146 // or the expression is an overload expression this has to work.
1147 // There is no other way that works.
1148 // On the other hand, if we're checking a C-style cast, we've still got
1149 // the reinterpret_cast way.
1150
Douglas Gregorb33eed02010-04-16 22:09:46 +00001151 if (InitSeq.getKind() == InitializationSequence::FailedSequence &&
Douglas Gregore81f58e2010-11-08 03:40:48 +00001152 (CStyle || !DestType->isReferenceType()))
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001153 return TC_NotApplicable;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001154
John McCalldadc5752010-08-24 06:29:42 +00001155 ExprResult Result
John McCallfaf5fb42010-08-26 23:41:50 +00001156 = InitSeq.Perform(Self, Entity, InitKind, MultiExprArg(Self, &SrcExpr, 1));
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001157 if (Result.isInvalid()) {
1158 msg = 0;
1159 return TC_Failed;
1160 }
1161
Douglas Gregorb33eed02010-04-16 22:09:46 +00001162 if (InitSeq.isConstructorInitialization())
John McCalle3027922010-08-25 11:45:40 +00001163 Kind = CK_ConstructorConversion;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001164 else
John McCalle3027922010-08-25 11:45:40 +00001165 Kind = CK_NoOp;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001166
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001167 SrcExpr = Result.takeAs<Expr>();
1168 return TC_Success;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001169}
1170
1171/// TryConstCast - See if a const_cast from source to destination is allowed,
1172/// and perform it if it is.
1173static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
1174 bool CStyle, unsigned &msg) {
1175 DestType = Self.Context.getCanonicalType(DestType);
1176 QualType SrcType = SrcExpr->getType();
Douglas Gregorc1ed20c2011-01-22 00:19:52 +00001177 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
1178 if (DestTypeTmp->isLValueReferenceType() && !SrcExpr->isLValue()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001179 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1180 // is C-style, static_cast might find a way, so we simply suggest a
1181 // message and tell the parent to keep searching.
1182 msg = diag::err_bad_cxx_cast_rvalue;
1183 return TC_NotApplicable;
1184 }
1185
1186 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
1187 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
1188 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1189 SrcType = Self.Context.getPointerType(SrcType);
1190 }
1191
1192 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1193 // the rules for const_cast are the same as those used for pointers.
1194
John McCall0e704f72010-05-18 09:35:29 +00001195 if (!DestType->isPointerType() &&
1196 !DestType->isMemberPointerType() &&
1197 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001198 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1199 // was a reference type, we converted it to a pointer above.
1200 // The status of rvalue references isn't entirely clear, but it looks like
1201 // conversion to them is simply invalid.
1202 // C++ 5.2.11p3: For two pointer types [...]
1203 if (!CStyle)
1204 msg = diag::err_bad_const_cast_dest;
1205 return TC_NotApplicable;
1206 }
1207 if (DestType->isFunctionPointerType() ||
1208 DestType->isMemberFunctionPointerType()) {
1209 // Cannot cast direct function pointers.
1210 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1211 // T is the ultimate pointee of source and target type.
1212 if (!CStyle)
1213 msg = diag::err_bad_const_cast_dest;
1214 return TC_NotApplicable;
1215 }
1216 SrcType = Self.Context.getCanonicalType(SrcType);
1217
1218 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1219 // completely equal.
1220 // FIXME: const_cast should probably not be able to convert between pointers
1221 // to different address spaces.
1222 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1223 // in multi-level pointers may change, but the level count must be the same,
1224 // as must be the final pointee type.
1225 while (SrcType != DestType &&
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001226 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Chandler Carruth585fb1e2009-12-29 08:05:19 +00001227 Qualifiers Quals;
1228 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, Quals);
1229 DestType = Self.Context.getUnqualifiedArrayType(DestType, Quals);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001230 }
1231
1232 // Since we're dealing in canonical types, the remainder must be the same.
1233 if (SrcType != DestType)
1234 return TC_NotApplicable;
1235
1236 return TC_Success;
1237}
1238
Douglas Gregore81f58e2010-11-08 03:40:48 +00001239
1240static void NoteAllOverloadCandidates(Expr* const Expr, Sema& sema)
1241{
1242
1243 assert(Expr->getType() == sema.Context.OverloadTy);
1244
1245 OverloadExpr::FindResult Ovl = OverloadExpr::find(Expr);
1246 OverloadExpr *const OvlExpr = Ovl.Expression;
1247
1248 for (UnresolvedSetIterator it = OvlExpr->decls_begin(),
1249 end = OvlExpr->decls_end(); it != end; ++it) {
1250 if ( FunctionTemplateDecl *ftd =
1251 dyn_cast<FunctionTemplateDecl>((*it)->getUnderlyingDecl()) )
1252 {
1253 sema.NoteOverloadCandidate(ftd->getTemplatedDecl());
1254 }
1255 else if ( FunctionDecl *f =
1256 dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl()) )
1257 {
1258 sema.NoteOverloadCandidate(f);
1259 }
1260 }
1261}
1262
1263
Sebastian Redl9f831db2009-07-25 15:41:38 +00001264static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
1265 QualType DestType, bool CStyle,
1266 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001267 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001268 CastKind &Kind) {
Douglas Gregor51954272010-07-13 23:17:26 +00001269 bool IsLValueCast = false;
1270
Sebastian Redl9f831db2009-07-25 15:41:38 +00001271 DestType = Self.Context.getCanonicalType(DestType);
1272 QualType SrcType = SrcExpr->getType();
Douglas Gregore81f58e2010-11-08 03:40:48 +00001273
1274 // Is the source an overloaded name? (i.e. &foo)
1275 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5)
John McCalle84af4e2010-11-13 01:35:44 +00001276 if (SrcType == Self.Context.OverloadTy)
Douglas Gregore81f58e2010-11-08 03:40:48 +00001277 return TC_NotApplicable;
1278
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001279 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001280 bool LValue = DestTypeTmp->isLValueReferenceType();
John McCall086a4642010-11-24 05:12:34 +00001281 if (LValue && !SrcExpr->isLValue()) {
Douglas Gregorc1ed20c2011-01-22 00:19:52 +00001282 // Cannot cast non-lvalue to lvalue reference type. See the similar
1283 // comment in const_cast.
Sebastian Redl9f831db2009-07-25 15:41:38 +00001284 msg = diag::err_bad_cxx_cast_rvalue;
1285 return TC_NotApplicable;
1286 }
1287
1288 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1289 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1290 // built-in & and * operators.
1291 // This code does this transformation for the checked types.
1292 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1293 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001294
Douglas Gregor51954272010-07-13 23:17:26 +00001295 IsLValueCast = true;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001296 }
1297
1298 // Canonicalize source for comparison.
1299 SrcType = Self.Context.getCanonicalType(SrcType);
1300
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001301 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1302 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001303 if (DestMemPtr && SrcMemPtr) {
1304 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1305 // can be explicitly converted to an rvalue of type "pointer to member
1306 // of Y of type T2" if T1 and T2 are both function types or both object
1307 // types.
1308 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1309 SrcMemPtr->getPointeeType()->isFunctionType())
1310 return TC_NotApplicable;
1311
1312 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1313 // constness.
1314 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1315 // we accept it.
1316 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1317 msg = diag::err_bad_cxx_cast_const_away;
1318 return TC_Failed;
1319 }
1320
Charles Davisebab1ed2010-08-16 05:30:44 +00001321 // Don't allow casting between member pointers of different sizes.
1322 if (Self.Context.getTypeSize(DestMemPtr) !=
1323 Self.Context.getTypeSize(SrcMemPtr)) {
1324 msg = diag::err_bad_cxx_cast_member_pointer_size;
1325 return TC_Failed;
1326 }
1327
Sebastian Redl9f831db2009-07-25 15:41:38 +00001328 // A valid member pointer cast.
John McCalle3027922010-08-25 11:45:40 +00001329 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001330 return TC_Success;
1331 }
1332
1333 // See below for the enumeral issue.
Douglas Gregor6972a622010-06-16 00:35:25 +00001334 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001335 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1336 // type large enough to hold it. A value of std::nullptr_t can be
1337 // converted to an integral type; the conversion has the same meaning
1338 // and validity as a conversion of (void*)0 to the integral type.
1339 if (Self.Context.getTypeSize(SrcType) >
1340 Self.Context.getTypeSize(DestType)) {
1341 msg = diag::err_bad_reinterpret_cast_small_int;
1342 return TC_Failed;
1343 }
John McCalle3027922010-08-25 11:45:40 +00001344 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001345 return TC_Success;
1346 }
1347
Anders Carlsson570af5d2009-09-16 19:19:43 +00001348 bool destIsVector = DestType->isVectorType();
1349 bool srcIsVector = SrcType->isVectorType();
1350 if (srcIsVector || destIsVector) {
Douglas Gregor6972a622010-06-16 00:35:25 +00001351 // FIXME: Should this also apply to floating point types?
1352 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1353 bool destIsScalar = DestType->isIntegralType(Self.Context);
Anders Carlsson570af5d2009-09-16 19:19:43 +00001354
1355 // Check if this is a cast between a vector and something else.
1356 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1357 !(srcIsVector && destIsVector))
1358 return TC_NotApplicable;
1359
1360 // If both types have the same size, we can successfully cast.
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001361 if (Self.Context.getTypeSize(SrcType)
1362 == Self.Context.getTypeSize(DestType)) {
John McCalle3027922010-08-25 11:45:40 +00001363 Kind = CK_BitCast;
Anders Carlsson570af5d2009-09-16 19:19:43 +00001364 return TC_Success;
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001365 }
Anders Carlsson570af5d2009-09-16 19:19:43 +00001366
1367 if (destIsScalar)
1368 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1369 else if (srcIsScalar)
1370 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1371 else
1372 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1373
1374 return TC_Failed;
1375 }
1376
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001377 bool destIsPtr = DestType->isAnyPointerType() ||
1378 DestType->isBlockPointerType();
1379 bool srcIsPtr = SrcType->isAnyPointerType() ||
1380 SrcType->isBlockPointerType();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001381 if (!destIsPtr && !srcIsPtr) {
1382 // Except for std::nullptr_t->integer and lvalue->reference, which are
1383 // handled above, at least one of the two arguments must be a pointer.
1384 return TC_NotApplicable;
1385 }
1386
1387 if (SrcType == DestType) {
1388 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1389 // restrictions, a cast to the same type is allowed. The intent is not
1390 // entirely clear here, since all other paragraphs explicitly forbid casts
1391 // to the same type. However, the behavior of compilers is pretty consistent
1392 // on this point: allow same-type conversion if the involved types are
1393 // pointers, disallow otherwise.
John McCalle3027922010-08-25 11:45:40 +00001394 Kind = CK_NoOp;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001395 return TC_Success;
1396 }
1397
Douglas Gregor6972a622010-06-16 00:35:25 +00001398 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001399 assert(srcIsPtr && "One type must be a pointer");
1400 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1401 // type large enough to hold it.
1402 if (Self.Context.getTypeSize(SrcType) >
1403 Self.Context.getTypeSize(DestType)) {
1404 msg = diag::err_bad_reinterpret_cast_small_int;
1405 return TC_Failed;
1406 }
John McCalle3027922010-08-25 11:45:40 +00001407 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001408 return TC_Success;
1409 }
1410
Douglas Gregorb90df602010-06-16 00:17:44 +00001411 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001412 assert(destIsPtr && "One type must be a pointer");
1413 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1414 // converted to a pointer.
John McCalle84af4e2010-11-13 01:35:44 +00001415 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1416 // necessarily converted to a null pointer value.]
John McCalle3027922010-08-25 11:45:40 +00001417 Kind = CK_IntegralToPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001418 return TC_Success;
1419 }
1420
1421 if (!destIsPtr || !srcIsPtr) {
1422 // With the valid non-pointer conversions out of the way, we can be even
1423 // more stringent.
1424 return TC_NotApplicable;
1425 }
1426
1427 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1428 // The C-style cast operator can.
1429 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1430 msg = diag::err_bad_cxx_cast_const_away;
1431 return TC_Failed;
1432 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001433
1434 // Cannot convert between block pointers and Objective-C object pointers.
1435 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1436 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1437 return TC_NotApplicable;
1438
1439 // Any pointer can be cast to an Objective-C pointer type with a C-style
1440 // cast.
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001441 if (CStyle && DestType->isObjCObjectPointerType()) {
John McCalle3027922010-08-25 11:45:40 +00001442 Kind = CK_AnyPointerToObjCPointerCast;
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001443 return TC_Success;
1444 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001445
Sebastian Redl9f831db2009-07-25 15:41:38 +00001446 // Not casting away constness, so the only remaining check is for compatible
1447 // pointer categories.
John McCalle3027922010-08-25 11:45:40 +00001448 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001449
1450 if (SrcType->isFunctionPointerType()) {
1451 if (DestType->isFunctionPointerType()) {
1452 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1453 // a pointer to a function of a different type.
1454 return TC_Success;
1455 }
1456
1457 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1458 // an object type or vice versa is conditionally-supported.
1459 // Compilers support it in C++03 too, though, because it's necessary for
1460 // casting the return value of dlsym() and GetProcAddress().
1461 // FIXME: Conditionally-supported behavior should be configurable in the
1462 // TargetInfo or similar.
1463 if (!Self.getLangOptions().CPlusPlus0x)
1464 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1465 return TC_Success;
1466 }
1467
1468 if (DestType->isFunctionPointerType()) {
1469 // See above.
1470 if (!Self.getLangOptions().CPlusPlus0x)
1471 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1472 return TC_Success;
1473 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001474
Sebastian Redl9f831db2009-07-25 15:41:38 +00001475 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1476 // a pointer to an object of different type.
1477 // Void pointers are not specified, but supported by every compiler out there.
1478 // So we finish by allowing everything that remains - it's got to be two
1479 // object pointers.
1480 return TC_Success;
John McCall909acf82011-02-14 18:34:10 +00001481}
Sebastian Redl9f831db2009-07-25 15:41:38 +00001482
Anders Carlssona70cff62010-04-24 19:06:50 +00001483bool
John McCall7decc9e2010-11-18 06:31:45 +00001484Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, ExprValueKind &VK,
1485 Expr *&CastExpr, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001486 CXXCastPath &BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00001487 bool FunctionalStyle) {
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00001488 if (CastExpr->isBoundMemberFunction(Context))
1489 return Diag(CastExpr->getLocStart(),
1490 diag::err_invalid_use_of_bound_member_func)
1491 << CastExpr->getSourceRange();
1492
Sebastian Redl9f831db2009-07-25 15:41:38 +00001493 // This test is outside everything else because it's the only case where
1494 // a non-lvalue-reference target type does not lead to decay.
1495 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Anders Carlsson9500ad12009-10-18 20:31:03 +00001496 if (CastTy->isVoidType()) {
John McCall34376a62010-12-04 03:47:34 +00001497 IgnoredValueConversions(CastExpr);
John McCalle3027922010-08-25 11:45:40 +00001498 Kind = CK_ToVoid;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001499 return false;
Anders Carlsson9500ad12009-10-18 20:31:03 +00001500 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001501
John McCall4cec5f82010-11-30 02:05:44 +00001502 // Make sure we determine the value kind before we bail out for
1503 // dependent types.
1504 VK = Expr::getValueKindForType(CastTy);
1505
Sebastian Redl9f831db2009-07-25 15:41:38 +00001506 // If the type is dependent, we won't do any other semantic analysis now.
John McCall8cb679e2010-11-15 09:13:47 +00001507 if (CastTy->isDependentType() || CastExpr->isTypeDependent()) {
1508 Kind = CK_Dependent;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001509 return false;
John McCall8cb679e2010-11-15 09:13:47 +00001510 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001511
John McCall7decc9e2010-11-18 06:31:45 +00001512 if (VK == VK_RValue && !CastTy->isRecordType())
Douglas Gregorb92a1562010-02-03 00:27:59 +00001513 DefaultFunctionArrayLvalueConversion(CastExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001514
1515 // C++ [expr.cast]p5: The conversions performed by
1516 // - a const_cast,
1517 // - a static_cast,
1518 // - a static_cast followed by a const_cast,
1519 // - a reinterpret_cast, or
1520 // - a reinterpret_cast followed by a const_cast,
1521 // can be performed using the cast notation of explicit type conversion.
1522 // [...] If a conversion can be interpreted in more than one of the ways
1523 // listed above, the interpretation that appears first in the list is used,
1524 // even if a cast resulting from that interpretation is ill-formed.
1525 // In plain language, this means trying a const_cast ...
1526 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssonf1ae6d42009-09-01 20:52:42 +00001527 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1528 msg);
Anders Carlsson027732b2009-10-19 18:14:28 +00001529 if (tcr == TC_Success)
John McCalle3027922010-08-25 11:45:40 +00001530 Kind = CK_NoOp;
Anders Carlsson027732b2009-10-19 18:14:28 +00001531
Sebastian Redl9f831db2009-07-25 15:41:38 +00001532 if (tcr == TC_NotApplicable) {
1533 // ... or if that is not possible, a static_cast, ignoring const, ...
Anders Carlssona70cff62010-04-24 19:06:50 +00001534 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg, Kind,
1535 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001536 if (tcr == TC_NotApplicable) {
1537 // ... and finally a reinterpret_cast, ignoring const.
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001538 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1539 Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001540 }
1541 }
1542
Nick Lewycky14d88eb2010-11-09 00:19:31 +00001543 if (tcr != TC_Success && msg != 0) {
1544 if (CastExpr->getType() == Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +00001545 DeclAccessPair Found;
Nick Lewycky14d88eb2010-11-09 00:19:31 +00001546 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(CastExpr,
Douglas Gregore81f58e2010-11-08 03:40:48 +00001547 CastTy,
1548 /* Complain */ true,
1549 Found);
1550 assert(!Fn && "cast failed but able to resolve overload expression!!");
Nick Lewycky14d88eb2010-11-09 00:19:31 +00001551 (void)Fn;
John McCall909acf82011-02-14 18:34:10 +00001552
Nick Lewycky14d88eb2010-11-09 00:19:31 +00001553 } else {
John McCall909acf82011-02-14 18:34:10 +00001554 diagnoseBadCast(*this, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
1555 R, CastExpr, CastTy);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001556 }
1557 }
John McCalld50a2712010-11-16 05:46:29 +00001558 else if (Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00001559 CheckCastAlign(CastExpr, CastTy, R);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001560
1561 return tcr != TC_Success;
1562}