blob: ed54f0f5442528a3147f478253cc04534fa90834 [file] [log] [blame]
Sebastian Redl26d85b12008-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 McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
Sebastian Redl26d85b12008-11-05 21:50:06 +000016#include "clang/AST/ExprCXX.h"
17#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000019#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redl26d85b12008-11-05 21:50:06 +000020#include "llvm/ADT/SmallVector.h"
Sebastian Redle3dc28a2008-11-07 23:29:29 +000021#include <set>
Sebastian Redl26d85b12008-11-05 21:50:06 +000022using namespace clang;
23
Douglas Gregor8e960432010-11-08 03:40:48 +000024
Douglas Gregor8e960432010-11-08 03:40:48 +000025
Sebastian Redl9cc11e72009-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 Redl37d6de32008-11-08 13:00:26 +000040};
41
Douglas Gregor8e960432010-11-08 03:40:48 +000042
43
44
John Wiegley429bb272011-04-08 18:41:53 +000045static void CheckConstCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCallf89e55a2010-11-18 06:31:45 +000046 ExprValueKind &VK,
Sebastian Redl37d6de32008-11-08 13:00:26 +000047 const SourceRange &OpRange,
48 const SourceRange &DestRange);
John Wiegley429bb272011-04-08 18:41:53 +000049static void CheckReinterpretCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCallf89e55a2010-11-18 06:31:45 +000050 ExprValueKind &VK,
Sebastian Redl37d6de32008-11-08 13:00:26 +000051 const SourceRange &OpRange,
Anders Carlsson7f9e6462009-09-15 04:48:33 +000052 const SourceRange &DestRange,
John McCall2de56d12010-08-25 11:45:40 +000053 CastKind &Kind);
John Wiegley429bb272011-04-08 18:41:53 +000054static void CheckStaticCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCallf89e55a2010-11-18 06:31:45 +000055 ExprValueKind &VK,
Anders Carlssoncdb61972009-08-07 22:21:05 +000056 const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +000057 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +000058 CXXCastPath &BasePath);
John Wiegley429bb272011-04-08 18:41:53 +000059static void CheckDynamicCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCallf89e55a2010-11-18 06:31:45 +000060 ExprValueKind &VK,
Sebastian Redl37d6de32008-11-08 13:00:26 +000061 const SourceRange &OpRange,
Mike Stump1eb44332009-09-09 15:08:12 +000062 const SourceRange &DestRange,
John McCall2de56d12010-08-25 11:45:40 +000063 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +000064 CXXCastPath &BasePath);
Sebastian Redl37d6de32008-11-08 13:00:26 +000065
66static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
Sebastian Redl9cc11e72009-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 Gregor8ec14e62011-01-26 21:04:06 +000080 QualType DestType, bool CStyle,
81 CastKind &Kind,
Douglas Gregor88b22a42011-01-25 16:13:26 +000082 CXXCastPath &BasePath,
83 unsigned &msg);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000084static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
Anders Carlssonf9d68e12010-04-24 19:36:51 +000085 QualType DestType, bool CStyle,
86 const SourceRange &OpRange,
87 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +000088 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +000089 CXXCastPath &BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000090static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
91 QualType DestType, bool CStyle,
92 const SourceRange &OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +000093 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +000094 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +000095 CXXCastPath &BasePath);
Douglas Gregorab15d0e2009-11-15 09:20:52 +000096static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
97 CanQualType DestType, bool CStyle,
Sebastian Redl9cc11e72009-07-25 15:41:38 +000098 const SourceRange &OpRange,
99 QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000100 QualType OrigDestType, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000101 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000102 CXXCastPath &BasePath);
John Wiegley429bb272011-04-08 18:41:53 +0000103static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
Anders Carlssoncee22422010-04-24 19:22:20 +0000104 QualType SrcType,
105 QualType DestType,bool CStyle,
106 const SourceRange &OpRange,
107 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000108 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000109 CXXCastPath &BasePath);
Anders Carlssoncee22422010-04-24 19:22:20 +0000110
John Wiegley429bb272011-04-08 18:41:53 +0000111static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000112 QualType DestType, bool CStyle,
113 const SourceRange &OpRange,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000114 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000115 CastKind &Kind);
John Wiegley429bb272011-04-08 18:41:53 +0000116static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000117 QualType DestType, bool CStyle,
118 const SourceRange &OpRange,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000119 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000120 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000121 CXXCastPath &BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000122static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
123 bool CStyle, unsigned &msg);
John Wiegley429bb272011-04-08 18:41:53 +0000124static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000125 QualType DestType, bool CStyle,
126 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000127 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000128 CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +0000129
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000130
Sebastian Redl26d85b12008-11-05 21:50:06 +0000131/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
John McCall60d7b3a2010-08-24 06:29:42 +0000132ExprResult
Sebastian Redl26d85b12008-11-05 21:50:06 +0000133Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John McCallb3d87482010-08-24 05:47:05 +0000134 SourceLocation LAngleBracketLoc, ParsedType Ty,
Sebastian Redl26d85b12008-11-05 21:50:06 +0000135 SourceLocation RAngleBracketLoc,
John McCallf312b1e2010-08-26 23:41:50 +0000136 SourceLocation LParenLoc, Expr *E,
Sebastian Redl26d85b12008-11-05 21:50:06 +0000137 SourceLocation RParenLoc) {
John McCallc89724c2010-01-15 19:13:16 +0000138
John McCall9d125032010-01-15 18:39:57 +0000139 TypeSourceInfo *DestTInfo;
140 QualType DestType = GetTypeFromParser(Ty, &DestTInfo);
141 if (!DestTInfo)
142 DestTInfo = Context.getTrivialTypeSourceInfo(DestType, SourceLocation());
John McCallc89724c2010-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 McCall60d7b3a2010-08-24 06:29:42 +0000149ExprResult
John McCallc89724c2010-01-15 19:13:16 +0000150Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John Wiegley429bb272011-04-08 18:41:53 +0000151 TypeSourceInfo *DestTInfo, Expr *E,
John McCallc89724c2010-01-15 19:13:16 +0000152 SourceRange AngleBrackets, SourceRange Parens) {
John Wiegley429bb272011-04-08 18:41:53 +0000153 ExprResult Ex = Owned(E);
John McCallc89724c2010-01-15 19:13:16 +0000154 QualType DestType = DestTInfo->getType();
155
156 SourceRange OpRange(OpLoc, Parens.getEnd());
157 SourceRange DestRange = AngleBrackets;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000158
Douglas Gregor9103bb22008-12-17 22:52:20 +0000159 // If the type is dependent, we won't do the semantic analysis now.
160 // FIXME: should we check this in a more fine-grained manner?
John Wiegley429bb272011-04-08 18:41:53 +0000161 bool TypeDependent = DestType->isDependentType() || Ex.get()->isTypeDependent();
Douglas Gregor9103bb22008-12-17 22:52:20 +0000162
John McCallf89e55a2010-11-18 06:31:45 +0000163 ExprValueKind VK = VK_RValue;
John McCalla21e06c2010-11-26 10:57:22 +0000164 if (TypeDependent)
165 VK = Expr::getValueKindForType(DestType);
166
Sebastian Redl26d85b12008-11-05 21:50:06 +0000167 switch (Kind) {
John McCalldaa8e4e2010-11-15 09:13:47 +0000168 default: llvm_unreachable("Unknown C++ cast!");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000169
170 case tok::kw_const_cast:
John Wiegley429bb272011-04-08 18:41:53 +0000171 if (!TypeDependent) {
John McCallf89e55a2010-11-18 06:31:45 +0000172 CheckConstCast(*this, Ex, DestType, VK, OpRange, DestRange);
John Wiegley429bb272011-04-08 18:41:53 +0000173 if (Ex.isInvalid())
174 return ExprError();
175 }
John McCallf871d0c2010-08-07 06:22:56 +0000176 return Owned(CXXConstCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +0000177 DestType.getNonLValueExprType(Context),
John Wiegley429bb272011-04-08 18:41:53 +0000178 VK, Ex.take(), DestTInfo, OpLoc,
Douglas Gregor1d5d0b92011-01-12 22:41:29 +0000179 Parens.getEnd()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000180
Anders Carlsson714179b2009-08-02 19:07:59 +0000181 case tok::kw_dynamic_cast: {
John McCalldaa8e4e2010-11-15 09:13:47 +0000182 CastKind Kind = CK_Dependent;
John McCallf871d0c2010-08-07 06:22:56 +0000183 CXXCastPath BasePath;
John Wiegley429bb272011-04-08 18:41:53 +0000184 if (!TypeDependent) {
John McCallf89e55a2010-11-18 06:31:45 +0000185 CheckDynamicCast(*this, Ex, DestType, VK, OpRange, DestRange,
186 Kind, BasePath);
John Wiegley429bb272011-04-08 18:41:53 +0000187 if (Ex.isInvalid())
188 return ExprError();
189 }
John McCallf871d0c2010-08-07 06:22:56 +0000190 return Owned(CXXDynamicCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +0000191 DestType.getNonLValueExprType(Context),
John Wiegley429bb272011-04-08 18:41:53 +0000192 VK, Kind, Ex.take(), &BasePath, DestTInfo,
Douglas Gregor1d5d0b92011-01-12 22:41:29 +0000193 OpLoc, Parens.getEnd()));
Anders Carlsson714179b2009-08-02 19:07:59 +0000194 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000195 case tok::kw_reinterpret_cast: {
John McCalldaa8e4e2010-11-15 09:13:47 +0000196 CastKind Kind = CK_Dependent;
John Wiegley429bb272011-04-08 18:41:53 +0000197 if (!TypeDependent) {
John McCallf89e55a2010-11-18 06:31:45 +0000198 CheckReinterpretCast(*this, Ex, DestType, VK, OpRange, DestRange, Kind);
John Wiegley429bb272011-04-08 18:41:53 +0000199 if (Ex.isInvalid())
200 return ExprError();
201 }
John McCallf871d0c2010-08-07 06:22:56 +0000202 return Owned(CXXReinterpretCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +0000203 DestType.getNonLValueExprType(Context),
John Wiegley429bb272011-04-08 18:41:53 +0000204 VK, Kind, Ex.take(), 0,
Douglas Gregor1d5d0b92011-01-12 22:41:29 +0000205 DestTInfo, OpLoc, Parens.getEnd()));
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000206 }
Anders Carlssoncdb61972009-08-07 22:21:05 +0000207 case tok::kw_static_cast: {
John McCalldaa8e4e2010-11-15 09:13:47 +0000208 CastKind Kind = CK_Dependent;
John McCallf871d0c2010-08-07 06:22:56 +0000209 CXXCastPath BasePath;
John Wiegley429bb272011-04-08 18:41:53 +0000210 if (!TypeDependent) {
John McCallf89e55a2010-11-18 06:31:45 +0000211 CheckStaticCast(*this, Ex, DestType, VK, OpRange, Kind, BasePath);
John Wiegley429bb272011-04-08 18:41:53 +0000212 if (Ex.isInvalid())
213 return ExprError();
214 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000215
John McCallf871d0c2010-08-07 06:22:56 +0000216 return Owned(CXXStaticCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +0000217 DestType.getNonLValueExprType(Context),
John Wiegley429bb272011-04-08 18:41:53 +0000218 VK, Kind, Ex.take(), &BasePath,
Douglas Gregor1d5d0b92011-01-12 22:41:29 +0000219 DestTInfo, OpLoc, Parens.getEnd()));
Anders Carlssoncdb61972009-08-07 22:21:05 +0000220 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000221 }
222
Sebastian Redlf53597f2009-03-15 17:47:39 +0000223 return ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000224}
225
John McCall79ab2c82011-02-14 18:34:10 +0000226/// Try to diagnose a failed overloaded cast. Returns true if
227/// diagnostics were emitted.
228static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
229 SourceRange range, Expr *src,
230 QualType destType) {
231 switch (CT) {
232 // These cast kinds don't consider user-defined conversions.
233 case CT_Const:
234 case CT_Reinterpret:
235 case CT_Dynamic:
236 return false;
237
238 // These do.
239 case CT_Static:
240 case CT_CStyle:
241 case CT_Functional:
242 break;
243 }
244
245 QualType srcType = src->getType();
246 if (!destType->isRecordType() && !srcType->isRecordType())
247 return false;
248
249 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
250 InitializationKind initKind
251 = InitializationKind::CreateCast(/*type range?*/ range,
252 (CT == CT_CStyle || CT == CT_Functional));
253 InitializationSequence sequence(S, entity, initKind, &src, 1);
254
255 assert(sequence.getKind() == InitializationSequence::FailedSequence &&
256 "initialization succeeded on second try?");
257 switch (sequence.getFailureKind()) {
258 default: return false;
259
260 case InitializationSequence::FK_ConstructorOverloadFailed:
261 case InitializationSequence::FK_UserConversionOverloadFailed:
262 break;
263 }
264
265 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
266
267 unsigned msg = 0;
268 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
269
270 switch (sequence.getFailedOverloadResult()) {
271 case OR_Success: llvm_unreachable("successful failed overload");
272 return false;
273 case OR_No_Viable_Function:
274 if (candidates.empty())
275 msg = diag::err_ovl_no_conversion_in_cast;
276 else
277 msg = diag::err_ovl_no_viable_conversion_in_cast;
278 howManyCandidates = OCD_AllCandidates;
279 break;
280
281 case OR_Ambiguous:
282 msg = diag::err_ovl_ambiguous_conversion_in_cast;
283 howManyCandidates = OCD_ViableCandidates;
284 break;
285
286 case OR_Deleted:
287 msg = diag::err_ovl_deleted_conversion_in_cast;
288 howManyCandidates = OCD_ViableCandidates;
289 break;
290 }
291
292 S.Diag(range.getBegin(), msg)
293 << CT << srcType << destType
294 << range << src->getSourceRange();
295
296 candidates.NoteCandidates(S, howManyCandidates, &src, 1);
297
298 return true;
299}
300
301/// Diagnose a failed cast.
302static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
303 SourceRange opRange, Expr *src, QualType destType) {
John McCall864c0412011-04-26 20:42:42 +0000304 if (src->getType() == S.Context.BoundMemberTy) {
305 (void) S.CheckPlaceholderExpr(src); // will always fail
306 return;
307 }
308
John McCall79ab2c82011-02-14 18:34:10 +0000309 if (msg == diag::err_bad_cxx_cast_generic &&
310 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType))
311 return;
312
313 S.Diag(opRange.getBegin(), msg) << castType
314 << src->getType() << destType << opRange << src->getSourceRange();
315}
316
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000317/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
318/// this removes one level of indirection from both types, provided that they're
319/// the same kind of pointer (plain or to-member). Unlike the Sema function,
320/// this one doesn't care if the two pointers-to-member don't point into the
321/// same class. This is because CastsAwayConstness doesn't care.
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000322static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000323 const PointerType *T1PtrType = T1->getAs<PointerType>(),
324 *T2PtrType = T2->getAs<PointerType>();
325 if (T1PtrType && T2PtrType) {
326 T1 = T1PtrType->getPointeeType();
327 T2 = T2PtrType->getPointeeType();
328 return true;
329 }
Fariborz Jahanian72a86592010-02-03 20:32:31 +0000330 const ObjCObjectPointerType *T1ObjCPtrType =
331 T1->getAs<ObjCObjectPointerType>(),
332 *T2ObjCPtrType =
333 T2->getAs<ObjCObjectPointerType>();
334 if (T1ObjCPtrType) {
335 if (T2ObjCPtrType) {
336 T1 = T1ObjCPtrType->getPointeeType();
337 T2 = T2ObjCPtrType->getPointeeType();
338 return true;
339 }
340 else if (T2PtrType) {
341 T1 = T1ObjCPtrType->getPointeeType();
342 T2 = T2PtrType->getPointeeType();
343 return true;
344 }
345 }
346 else if (T2ObjCPtrType) {
347 if (T1PtrType) {
348 T2 = T2ObjCPtrType->getPointeeType();
349 T1 = T1PtrType->getPointeeType();
350 return true;
351 }
352 }
353
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000354 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
355 *T2MPType = T2->getAs<MemberPointerType>();
356 if (T1MPType && T2MPType) {
357 T1 = T1MPType->getPointeeType();
358 T2 = T2MPType->getPointeeType();
359 return true;
360 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000361
362 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
363 *T2BPType = T2->getAs<BlockPointerType>();
364 if (T1BPType && T2BPType) {
365 T1 = T1BPType->getPointeeType();
366 T2 = T2BPType->getPointeeType();
367 return true;
368 }
369
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000370 return false;
371}
372
Sebastian Redldb647282009-01-27 23:18:31 +0000373/// CastsAwayConstness - Check if the pointer conversion from SrcType to
374/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
375/// the cast checkers. Both arguments must denote pointer (possibly to member)
376/// types.
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000377static bool
Mike Stump1eb44332009-09-09 15:08:12 +0000378CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
Sebastian Redldb647282009-01-27 23:18:31 +0000379 // Casting away constness is defined in C++ 5.2.11p8 with reference to
380 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
381 // the rules are non-trivial. So first we construct Tcv *...cv* as described
382 // in C++ 5.2.11p8.
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000383 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
384 SrcType->isBlockPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000385 "Source type is not pointer or pointer to member.");
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000386 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
387 DestType->isBlockPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000388 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000389
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000390 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
391 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
John McCall0953e762009-09-24 19:53:00 +0000392 llvm::SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000393
Douglas Gregord4c5f842011-04-15 17:59:54 +0000394 // Find the qualifiers. We only care about cvr-qualifiers for the
395 // purpose of this check, because other qualifiers (address spaces,
396 // Objective-C GC, etc.) are part of the type's identity.
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000397 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
Anders Carlsson52647c62010-06-04 22:47:55 +0000398 Qualifiers SrcQuals;
399 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
Douglas Gregord4c5f842011-04-15 17:59:54 +0000400 cv1.push_back(Qualifiers::fromCVRMask(SrcQuals.getCVRQualifiers()));
Anders Carlsson52647c62010-06-04 22:47:55 +0000401
402 Qualifiers DestQuals;
403 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
Douglas Gregord4c5f842011-04-15 17:59:54 +0000404 cv2.push_back(Qualifiers::fromCVRMask(DestQuals.getCVRQualifiers()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000405 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000406 if (cv1.empty())
407 return false;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000408
409 // Construct void pointers with those qualifiers (in reverse order of
410 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000411 QualType SrcConstruct = Self.Context.VoidTy;
412 QualType DestConstruct = Self.Context.VoidTy;
John McCall0953e762009-09-24 19:53:00 +0000413 ASTContext &Context = Self.Context;
414 for (llvm::SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
415 i2 = cv2.rbegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000416 i1 != cv1.rend(); ++i1, ++i2) {
John McCall0953e762009-09-24 19:53:00 +0000417 SrcConstruct
418 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
419 DestConstruct
420 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000421 }
422
423 // Test if they're compatible.
424 return SrcConstruct != DestConstruct &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +0000425 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000426}
427
Sebastian Redl26d85b12008-11-05 21:50:06 +0000428/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
429/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
430/// checked downcasts in class hierarchies.
Anders Carlsson714179b2009-08-02 19:07:59 +0000431static void
John Wiegley429bb272011-04-08 18:41:53 +0000432CheckDynamicCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCallf89e55a2010-11-18 06:31:45 +0000433 ExprValueKind &VK, const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +0000434 const SourceRange &DestRange, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000435 CXXCastPath &BasePath) {
John Wiegley429bb272011-04-08 18:41:53 +0000436 QualType OrigDestType = DestType, OrigSrcType = SrcExpr.get()->getType();
Sebastian Redl37d6de32008-11-08 13:00:26 +0000437 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000438
439 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
440 // or "pointer to cv void".
441
442 QualType DestPointee;
Ted Kremenek6217b802009-07-29 21:53:49 +0000443 const PointerType *DestPointer = DestType->getAs<PointerType>();
John McCallf89e55a2010-11-18 06:31:45 +0000444 const ReferenceType *DestReference = 0;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000445 if (DestPointer) {
446 DestPointee = DestPointer->getPointeeType();
John McCallf89e55a2010-11-18 06:31:45 +0000447 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000448 DestPointee = DestReference->getPointeeType();
Douglas Gregordc843f22011-01-22 00:06:57 +0000449 VK = isa<LValueReferenceType>(DestReference) ? VK_LValue
450 : isa<RValueReferenceType>(DestReference) ? VK_XValue
451 : VK_RValue;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000452 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000453 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000454 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000455 return;
456 }
457
Ted Kremenek6217b802009-07-29 21:53:49 +0000458 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000459 if (DestPointee->isVoidType()) {
460 assert(DestPointer && "Reference to void is not possible");
461 } else if (DestRecord) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000462 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000463 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssonb7906612009-08-26 23:45:07 +0000464 << DestRange))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000465 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000466 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000467 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000468 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000469 return;
470 }
471
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000472 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
473 // complete class type, [...]. If T is an lvalue reference type, v shall be
Douglas Gregordc843f22011-01-22 00:06:57 +0000474 // an lvalue of a complete class type, [...]. If T is an rvalue reference
475 // type, v shall be an expression having a complete class type, [...]
Sebastian Redl37d6de32008-11-08 13:00:26 +0000476 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000477 QualType SrcPointee;
478 if (DestPointer) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000479 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000480 SrcPointee = SrcPointer->getPointeeType();
481 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000482 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
John Wiegley429bb272011-04-08 18:41:53 +0000483 << OrigSrcType << SrcExpr.get()->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000484 return;
485 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000486 } else if (DestReference->isLValueReferenceType()) {
John Wiegley429bb272011-04-08 18:41:53 +0000487 if (!SrcExpr.get()->isLValue()) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000488 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000489 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000490 }
491 SrcPointee = SrcType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000492 } else {
493 SrcPointee = SrcType;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000494 }
495
Ted Kremenek6217b802009-07-29 21:53:49 +0000496 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000497 if (SrcRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000498 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000499 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
John Wiegley429bb272011-04-08 18:41:53 +0000500 << SrcExpr.get()->getSourceRange()))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000501 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000502 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000503 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
John Wiegley429bb272011-04-08 18:41:53 +0000504 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000505 return;
506 }
507
508 assert((DestPointer || DestReference) &&
509 "Bad destination non-ptr/ref slipped through.");
510 assert((DestRecord || DestPointee->isVoidType()) &&
511 "Bad destination pointee slipped through.");
512 assert(SrcRecord && "Bad source pointee slipped through.");
513
514 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
515 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +0000516 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000517 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000518 return;
519 }
520
521 // C++ 5.2.7p3: If the type of v is the same as the required result type,
522 // [except for cv].
523 if (DestRecord == SrcRecord) {
John McCall2de56d12010-08-25 11:45:40 +0000524 Kind = CK_NoOp;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000525 return;
526 }
527
528 // C++ 5.2.7p5
529 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000530 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000531 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
532 OpRange.getBegin(), OpRange,
533 &BasePath))
534 return;
535
John McCall2de56d12010-08-25 11:45:40 +0000536 Kind = CK_DerivedToBase;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000537
538 // If we are casting to or through a virtual base class, we need a
539 // vtable.
540 if (Self.BasePathInvolvesVirtualBase(BasePath))
541 Self.MarkVTableUsed(OpRange.getBegin(),
542 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000543 return;
544 }
545
546 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor952b0172010-02-11 01:04:33 +0000547 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000548 assert(SrcDecl && "Definition missing");
549 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000550 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
John Wiegley429bb272011-04-08 18:41:53 +0000551 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000552 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000553 Self.MarkVTableUsed(OpRange.getBegin(),
554 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000555
556 // Done. Everything else is run-time checks.
John McCall2de56d12010-08-25 11:45:40 +0000557 Kind = CK_Dynamic;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000558}
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000559
560/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
561/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
562/// like this:
563/// const char *str = "literal";
564/// legacy_function(const_cast\<char*\>(str));
565void
John Wiegley429bb272011-04-08 18:41:53 +0000566CheckConstCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, ExprValueKind &VK,
Mike Stump1eb44332009-09-09 15:08:12 +0000567 const SourceRange &OpRange, const SourceRange &DestRange) {
John McCallf89e55a2010-11-18 06:31:45 +0000568 VK = Expr::getValueKindForType(DestType);
John Wiegley429bb272011-04-08 18:41:53 +0000569 if (VK == VK_RValue) {
570 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
571 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
572 return;
573 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000574
575 unsigned msg = diag::err_bad_cxx_cast_generic;
John Wiegley429bb272011-04-08 18:41:53 +0000576 if (TryConstCast(Self, SrcExpr.get(), DestType, /*CStyle*/false, msg) != TC_Success
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000577 && msg != 0)
578 Self.Diag(OpRange.getBegin(), msg) << CT_Const
John Wiegley429bb272011-04-08 18:41:53 +0000579 << SrcExpr.get()->getType() << DestType << OpRange;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000580}
581
582/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
583/// valid.
584/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
585/// like this:
586/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
587void
John Wiegley429bb272011-04-08 18:41:53 +0000588CheckReinterpretCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCallf89e55a2010-11-18 06:31:45 +0000589 ExprValueKind &VK, const SourceRange &OpRange,
590 const SourceRange &DestRange, CastKind &Kind) {
591 VK = Expr::getValueKindForType(DestType);
John Wiegley429bb272011-04-08 18:41:53 +0000592 if (VK == VK_RValue) {
593 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
594 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
595 return;
596 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000597
598 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson3c31a392009-09-26 00:12:34 +0000599 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
600 msg, Kind)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000601 != TC_Success && msg != 0)
Douglas Gregor8e960432010-11-08 03:40:48 +0000602 {
John Wiegley429bb272011-04-08 18:41:53 +0000603 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
604 return;
605 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor8e960432010-11-08 03:40:48 +0000606 //FIXME: &f<int>; is overloaded and resolvable
607 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
John Wiegley429bb272011-04-08 18:41:53 +0000608 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
Douglas Gregor8e960432010-11-08 03:40:48 +0000609 << DestType << OpRange;
John Wiegley429bb272011-04-08 18:41:53 +0000610 Self.NoteAllOverloadCandidates(SrcExpr.get());
Douglas Gregor8e960432010-11-08 03:40:48 +0000611
John McCall79ab2c82011-02-14 18:34:10 +0000612 } else {
John Wiegley429bb272011-04-08 18:41:53 +0000613 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(), DestType);
Douglas Gregor8e960432010-11-08 03:40:48 +0000614 }
John McCall79ab2c82011-02-14 18:34:10 +0000615 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000616}
617
618
619/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
620/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
621/// implicit conversions explicit and getting rid of data loss warnings.
622void
John Wiegley429bb272011-04-08 18:41:53 +0000623CheckStaticCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCallf89e55a2010-11-18 06:31:45 +0000624 ExprValueKind &VK, const SourceRange &OpRange,
625 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000626 // This test is outside everything else because it's the only case where
627 // a non-lvalue-reference target type does not lead to decay.
628 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000629 if (DestType->isVoidType()) {
John Wiegley429bb272011-04-08 18:41:53 +0000630 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
631 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
632 return;
633 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000634 ExprResult SingleFunctionExpression =
John Wiegley429bb272011-04-08 18:41:53 +0000635 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr.get(),
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000636 false, // Decay Function to ptr
637 true, // Complain
638 OpRange, DestType, diag::err_bad_static_cast_overload);
639 if (SingleFunctionExpression.isUsable())
640 {
John Wiegley429bb272011-04-08 18:41:53 +0000641 SrcExpr = SingleFunctionExpression;
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000642 Kind = CK_ToVoid;
643 }
644 }
645 else
646 Kind = CK_ToVoid;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000647 return;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000648 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000649
John McCallf89e55a2010-11-18 06:31:45 +0000650 VK = Expr::getValueKindForType(DestType);
John Wiegley429bb272011-04-08 18:41:53 +0000651 if (VK == VK_RValue && !DestType->isRecordType()) {
652 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
653 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
654 return;
655 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000656
657 unsigned msg = diag::err_bad_cxx_cast_generic;
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000658 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg,
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000659 Kind, BasePath) != TC_Success && msg != 0) {
John Wiegley429bb272011-04-08 18:41:53 +0000660 if (SrcExpr.isInvalid())
661 return;
662 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
663 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
Douglas Gregor8e960432010-11-08 03:40:48 +0000664 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
Douglas Gregor4c9be892011-02-28 20:01:57 +0000665 << oe->getName() << DestType << OpRange
666 << oe->getQualifierLoc().getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +0000667 Self.NoteAllOverloadCandidates(SrcExpr.get());
John McCall79ab2c82011-02-14 18:34:10 +0000668 } else {
John Wiegley429bb272011-04-08 18:41:53 +0000669 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType);
Douglas Gregor8e960432010-11-08 03:40:48 +0000670 }
Douglas Gregor8e960432010-11-08 03:40:48 +0000671 }
John McCalle2b76882010-11-16 05:46:29 +0000672 else if (Kind == CK_BitCast)
John Wiegley429bb272011-04-08 18:41:53 +0000673 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000674}
675
676/// TryStaticCast - Check if a static cast can be performed, and do so if
677/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
678/// and casting away constness.
John Wiegley429bb272011-04-08 18:41:53 +0000679static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000680 QualType DestType, bool CStyle,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000681 const SourceRange &OpRange, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000682 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000683 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000684 // The order the tests is not entirely arbitrary. There is one conversion
685 // that can be handled in two different ways. Given:
686 // struct A {};
687 // struct B : public A {
688 // B(); B(const A&);
689 // };
690 // const A &a = B();
691 // the cast static_cast<const B&>(a) could be seen as either a static
692 // reference downcast, or an explicit invocation of the user-defined
693 // conversion using B's conversion constructor.
694 // DR 427 specifies that the downcast is to be applied here.
695
696 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
697 // Done outside this function.
698
699 TryCastResult tcr;
700
701 // C++ 5.2.9p5, reference downcast.
702 // See the function for details.
703 // DR 427 specifies that this is to be applied before paragraph 2.
John Wiegley429bb272011-04-08 18:41:53 +0000704 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle, OpRange,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000705 msg, Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000706 if (tcr != TC_NotApplicable)
707 return tcr;
708
Douglas Gregordc843f22011-01-22 00:06:57 +0000709 // C++0x [expr.static.cast]p3:
710 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
711 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
John Wiegley429bb272011-04-08 18:41:53 +0000712 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind, BasePath,
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000713 msg);
Douglas Gregor88b22a42011-01-25 16:13:26 +0000714 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000715 return tcr;
716
717 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
718 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000719 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
Douglas Gregord6e44a32010-04-16 22:09:46 +0000720 Kind);
John Wiegley429bb272011-04-08 18:41:53 +0000721 if (SrcExpr.isInvalid())
722 return TC_Failed;
Anders Carlsson3c31a392009-09-26 00:12:34 +0000723 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000724 return tcr;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000725
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000726 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
727 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
728 // conversions, subject to further restrictions.
729 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
730 // of qualification conversions impossible.
731 // In the CStyle case, the earlier attempt to const_cast should have taken
732 // care of reverse qualification conversions.
733
John Wiegley429bb272011-04-08 18:41:53 +0000734 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000735
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000736 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
Douglas Gregor1e856d92011-02-18 03:01:41 +0000737 // converted to an integral type. [...] A value of a scoped enumeration type
738 // can also be explicitly converted to a floating-point type [...].
739 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
740 if (Enum->getDecl()->isScoped()) {
741 if (DestType->isBooleanType()) {
742 Kind = CK_IntegralToBoolean;
743 return TC_Success;
744 } else if (DestType->isIntegralType(Self.Context)) {
745 Kind = CK_IntegralCast;
746 return TC_Success;
747 } else if (DestType->isRealFloatingType()) {
748 Kind = CK_IntegralToFloating;
749 return TC_Success;
750 }
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000751 }
752 }
Douglas Gregor1e856d92011-02-18 03:01:41 +0000753
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000754 // Reverse integral promotion/conversion. All such conversions are themselves
755 // again integral promotions or conversions and are thus already handled by
756 // p2 (TryDirectInitialization above).
757 // (Note: any data loss warnings should be suppressed.)
758 // The exception is the reverse of enum->integer, i.e. integer->enum (and
759 // enum->enum). See also C++ 5.2.9p7.
760 // The same goes for reverse floating point promotion/conversion and
761 // floating-integral conversions. Again, only floating->enum is relevant.
762 if (DestType->isEnumeralType()) {
763 if (SrcType->isComplexType() || SrcType->isVectorType()) {
764 // Fall through - these cannot be converted.
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000765 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
John McCall2de56d12010-08-25 11:45:40 +0000766 Kind = CK_IntegralCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000767 return TC_Success;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000768 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000769 }
770
771 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
772 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000773 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000774 Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000775 if (tcr != TC_NotApplicable)
776 return tcr;
777
778 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
779 // conversion. C++ 5.2.9p9 has additional information.
780 // DR54's access restrictions apply here also.
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000781 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssoncee22422010-04-24 19:22:20 +0000782 OpRange, msg, Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000783 if (tcr != TC_NotApplicable)
784 return tcr;
785
786 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
787 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
788 // just the usual constness stuff.
Ted Kremenek6217b802009-07-29 21:53:49 +0000789 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000790 QualType SrcPointee = SrcPointer->getPointeeType();
791 if (SrcPointee->isVoidType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000792 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000793 QualType DestPointee = DestPointer->getPointeeType();
794 if (DestPointee->isIncompleteOrObjectType()) {
795 // This is definitely the intended conversion, but it might fail due
796 // to a const violation.
797 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +0000798 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000799 return TC_Failed;
800 }
John McCall2de56d12010-08-25 11:45:40 +0000801 Kind = CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000802 return TC_Success;
803 }
804 }
Fariborz Jahanian2f6c5502010-05-10 23:46:53 +0000805 else if (DestType->isObjCObjectPointerType()) {
806 // allow both c-style cast and static_cast of objective-c pointers as
807 // they are pervasive.
John McCall2de56d12010-08-25 11:45:40 +0000808 Kind = CK_AnyPointerToObjCPointerCast;
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +0000809 return TC_Success;
810 }
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +0000811 else if (CStyle && DestType->isBlockPointerType()) {
812 // allow c-style cast of void * to block pointers.
John McCall2de56d12010-08-25 11:45:40 +0000813 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +0000814 return TC_Success;
815 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000816 }
817 }
Fariborz Jahanian65267b22010-05-12 18:16:59 +0000818 // Allow arbitray objective-c pointer conversion with static casts.
819 if (SrcType->isObjCObjectPointerType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +0000820 DestType->isObjCObjectPointerType()) {
821 Kind = CK_BitCast;
Fariborz Jahanian65267b22010-05-12 18:16:59 +0000822 return TC_Success;
John McCalldaa8e4e2010-11-15 09:13:47 +0000823 }
Fariborz Jahanian65267b22010-05-12 18:16:59 +0000824
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000825 // We tried everything. Everything! Nothing works! :-(
826 return TC_NotApplicable;
827}
828
829/// Tests whether a conversion according to N2844 is valid.
830TryCastResult
831TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000832 bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
833 unsigned &msg) {
Douglas Gregordc843f22011-01-22 00:06:57 +0000834 // C++0x [expr.static.cast]p3:
835 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
836 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenek6217b802009-07-29 21:53:49 +0000837 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000838 if (!R)
839 return TC_NotApplicable;
840
Douglas Gregordc843f22011-01-22 00:06:57 +0000841 if (!SrcExpr->isGLValue())
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000842 return TC_NotApplicable;
843
844 // Because we try the reference downcast before this function, from now on
845 // this is the only cast possibility, so we issue an error if we fail now.
846 // FIXME: Should allow casting away constness if CStyle.
847 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +0000848 bool ObjCConversion;
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000849 QualType FromType = SrcExpr->getType();
850 QualType ToType = R->getPointeeType();
851 if (CStyle) {
852 FromType = FromType.getUnqualifiedType();
853 ToType = ToType.getUnqualifiedType();
854 }
855
Douglas Gregor393896f2009-11-05 13:06:35 +0000856 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000857 ToType, FromType,
Douglas Gregor569c3162010-08-07 11:51:51 +0000858 DerivedToBase, ObjCConversion) <
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000859 Sema::Ref_Compatible_With_Added_Qualification) {
860 msg = diag::err_bad_lvalue_to_rvalue_cast;
861 return TC_Failed;
862 }
863
Douglas Gregor88b22a42011-01-25 16:13:26 +0000864 if (DerivedToBase) {
865 Kind = CK_DerivedToBase;
866 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
867 /*DetectVirtual=*/true);
868 if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
869 return TC_NotApplicable;
870
871 Self.BuildBasePathArray(Paths, BasePath);
872 } else
873 Kind = CK_NoOp;
874
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000875 return TC_Success;
876}
877
878/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
879TryCastResult
880TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
881 bool CStyle, const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +0000882 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000883 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000884 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
885 // cast to type "reference to cv2 D", where D is a class derived from B,
886 // if a valid standard conversion from "pointer to D" to "pointer to B"
887 // exists, cv2 >= cv1, and B is not a virtual base class of D.
888 // In addition, DR54 clarifies that the base must be accessible in the
889 // current context. Although the wording of DR54 only applies to the pointer
890 // variant of this rule, the intent is clearly for it to apply to the this
891 // conversion as well.
892
Ted Kremenek6217b802009-07-29 21:53:49 +0000893 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000894 if (!DestReference) {
895 return TC_NotApplicable;
896 }
897 bool RValueRef = DestReference->isRValueReferenceType();
John McCall7eb0a9e2010-11-24 05:12:34 +0000898 if (!RValueRef && !SrcExpr->isLValue()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000899 // We know the left side is an lvalue reference, so we can suggest a reason.
900 msg = diag::err_bad_cxx_cast_rvalue;
901 return TC_NotApplicable;
902 }
903
904 QualType DestPointee = DestReference->getPointeeType();
905
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000906 return TryStaticDowncast(Self,
907 Self.Context.getCanonicalType(SrcExpr->getType()),
908 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000909 OpRange, SrcExpr->getType(), DestType, msg, Kind,
910 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000911}
912
913/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
914TryCastResult
915TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000916 bool CStyle, const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +0000917 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000918 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000919 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
920 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
921 // is a class derived from B, if a valid standard conversion from "pointer
922 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
923 // class of D.
924 // In addition, DR54 clarifies that the base must be accessible in the
925 // current context.
926
Ted Kremenek6217b802009-07-29 21:53:49 +0000927 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000928 if (!DestPointer) {
929 return TC_NotApplicable;
930 }
931
Ted Kremenek6217b802009-07-29 21:53:49 +0000932 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000933 if (!SrcPointer) {
934 msg = diag::err_bad_static_cast_pointer_nonpointer;
935 return TC_NotApplicable;
936 }
937
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000938 return TryStaticDowncast(Self,
939 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
940 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000941 CStyle, OpRange, SrcType, DestType, msg, Kind,
942 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000943}
944
945/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
946/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000947/// DestType is possible and allowed.
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000948TryCastResult
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000949TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000950 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000951 QualType OrigDestType, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000952 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000953 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000954 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, Self.PDiag(0)) ||
955 Self.RequireCompleteType(OpRange.getBegin(), DestType, Self.PDiag(0)))
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000956 return TC_NotApplicable;
957
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000958 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000959 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000960 return TC_NotApplicable;
961 }
962
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000963 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000964 /*DetectVirtual=*/true);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000965 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
966 return TC_NotApplicable;
967 }
968
969 // Target type does derive from source type. Now we're serious. If an error
970 // appears now, it's not ignored.
971 // This may not be entirely in line with the standard. Take for example:
972 // struct A {};
973 // struct B : virtual A {
974 // B(A&);
975 // };
Mike Stump1eb44332009-09-09 15:08:12 +0000976 //
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000977 // void f()
978 // {
979 // (void)static_cast<const B&>(*((A*)0));
980 // }
981 // As far as the standard is concerned, p5 does not apply (A is virtual), so
982 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
983 // However, both GCC and Comeau reject this example, and accepting it would
984 // mean more complex code if we're to preserve the nice error message.
985 // FIXME: Being 100% compliant here would be nice to have.
986
987 // Must preserve cv, as always, unless we're in C-style mode.
988 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +0000989 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000990 return TC_Failed;
991 }
992
993 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
994 // This code is analoguous to that in CheckDerivedToBaseConversion, except
995 // that it builds the paths in reverse order.
996 // To sum up: record all paths to the base and build a nice string from
997 // them. Use it to spice up the error message.
998 if (!Paths.isRecordingPaths()) {
999 Paths.clear();
1000 Paths.setRecordingPaths(true);
1001 Self.IsDerivedFrom(DestType, SrcType, Paths);
1002 }
1003 std::string PathDisplayStr;
1004 std::set<unsigned> DisplayedPaths;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001005 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001006 PI != PE; ++PI) {
1007 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
1008 // We haven't displayed a path to this particular base
1009 // class subobject yet.
1010 PathDisplayStr += "\n ";
Douglas Gregora8f32e02009-10-06 17:59:45 +00001011 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
1012 EE = PI->rend();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001013 EI != EE; ++EI)
1014 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001015 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001016 }
1017 }
1018
1019 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001020 << QualType(SrcType).getUnqualifiedType()
1021 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001022 << PathDisplayStr << OpRange;
1023 msg = 0;
1024 return TC_Failed;
1025 }
1026
1027 if (Paths.getDetectedVirtual() != 0) {
1028 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1029 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1030 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1031 msg = 0;
1032 return TC_Failed;
1033 }
1034
John McCall417d39f2011-02-14 23:21:33 +00001035 if (!CStyle) {
1036 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1037 SrcType, DestType,
1038 Paths.front(),
John McCall58e6f342010-03-16 05:22:47 +00001039 diag::err_downcast_from_inaccessible_base)) {
John McCall417d39f2011-02-14 23:21:33 +00001040 case Sema::AR_accessible:
1041 case Sema::AR_delayed: // be optimistic
1042 case Sema::AR_dependent: // be optimistic
1043 break;
1044
1045 case Sema::AR_inaccessible:
1046 msg = 0;
1047 return TC_Failed;
1048 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001049 }
1050
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001051 Self.BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00001052 Kind = CK_BaseToDerived;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001053 return TC_Success;
1054}
1055
1056/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1057/// C++ 5.2.9p9 is valid:
1058///
1059/// An rvalue of type "pointer to member of D of type cv1 T" can be
1060/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1061/// where B is a base class of D [...].
1062///
1063TryCastResult
John Wiegley429bb272011-04-08 18:41:53 +00001064TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001065 QualType DestType, bool CStyle,
1066 const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +00001067 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001068 CXXCastPath &BasePath) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001069 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001070 if (!DestMemPtr)
1071 return TC_NotApplicable;
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001072
1073 bool WasOverloadedFunction = false;
John McCall6bb80172010-03-30 21:47:33 +00001074 DeclAccessPair FoundOverload;
John Wiegley429bb272011-04-08 18:41:53 +00001075 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor1a8cf732010-04-14 23:11:21 +00001076 if (FunctionDecl *Fn
John Wiegley429bb272011-04-08 18:41:53 +00001077 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
Douglas Gregor1a8cf732010-04-14 23:11:21 +00001078 FoundOverload)) {
1079 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1080 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1081 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1082 WasOverloadedFunction = true;
1083 }
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001084 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00001085
Ted Kremenek6217b802009-07-29 21:53:49 +00001086 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001087 if (!SrcMemPtr) {
1088 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1089 return TC_NotApplicable;
1090 }
1091
1092 // T == T, modulo cv
Douglas Gregora4923eb2009-11-16 21:35:15 +00001093 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1094 DestMemPtr->getPointeeType()))
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001095 return TC_NotApplicable;
1096
1097 // B base of D
1098 QualType SrcClass(SrcMemPtr->getClass(), 0);
1099 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssoncee22422010-04-24 19:22:20 +00001100 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001101 /*DetectVirtual=*/true);
1102 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
1103 return TC_NotApplicable;
1104 }
1105
1106 // B is a base of D. But is it an allowed base? If not, it's a hard error.
Douglas Gregore0d5fe22010-05-21 20:29:55 +00001107 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001108 Paths.clear();
1109 Paths.setRecordingPaths(true);
1110 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
1111 assert(StillOkay);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001112 (void)StillOkay;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001113 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1114 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1115 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1116 msg = 0;
1117 return TC_Failed;
1118 }
1119
1120 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1121 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1122 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1123 msg = 0;
1124 return TC_Failed;
1125 }
1126
John McCall417d39f2011-02-14 23:21:33 +00001127 if (!CStyle) {
1128 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1129 DestClass, SrcClass,
1130 Paths.front(),
1131 diag::err_upcast_to_inaccessible_base)) {
1132 case Sema::AR_accessible:
1133 case Sema::AR_delayed:
1134 case Sema::AR_dependent:
1135 // Optimistically assume that the delayed and dependent cases
1136 // will work out.
1137 break;
1138
1139 case Sema::AR_inaccessible:
1140 msg = 0;
1141 return TC_Failed;
1142 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001143 }
1144
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001145 if (WasOverloadedFunction) {
1146 // Resolve the address of the overloaded function again, this time
1147 // allowing complaints if something goes wrong.
John Wiegley429bb272011-04-08 18:41:53 +00001148 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001149 DestType,
John McCall6bb80172010-03-30 21:47:33 +00001150 true,
1151 FoundOverload);
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001152 if (!Fn) {
1153 msg = 0;
1154 return TC_Failed;
1155 }
1156
John McCall6bb80172010-03-30 21:47:33 +00001157 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
John Wiegley429bb272011-04-08 18:41:53 +00001158 if (!SrcExpr.isUsable()) {
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001159 msg = 0;
1160 return TC_Failed;
1161 }
1162 }
1163
Anders Carlssoncee22422010-04-24 19:22:20 +00001164 Self.BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00001165 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001166 return TC_Success;
1167}
1168
1169/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1170/// is valid:
1171///
1172/// An expression e can be explicitly converted to a type T using a
1173/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1174TryCastResult
John Wiegley429bb272011-04-08 18:41:53 +00001175TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00001176 bool CStyle, const SourceRange &OpRange, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +00001177 CastKind &Kind) {
Anders Carlssond851b372009-09-07 18:25:47 +00001178 if (DestType->isRecordType()) {
1179 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1180 diag::err_bad_dynamic_cast_incomplete)) {
1181 msg = 0;
1182 return TC_Failed;
1183 }
1184 }
Douglas Gregord6e44a32010-04-16 22:09:46 +00001185
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001186 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1187 InitializationKind InitKind
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001188 = InitializationKind::CreateCast(/*FIXME:*/OpRange, CStyle);
John Wiegley429bb272011-04-08 18:41:53 +00001189 Expr *SrcExprRaw = SrcExpr.get();
1190 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExprRaw, 1);
Douglas Gregor8e960432010-11-08 03:40:48 +00001191
1192 // At this point of CheckStaticCast, if the destination is a reference,
1193 // or the expression is an overload expression this has to work.
1194 // There is no other way that works.
1195 // On the other hand, if we're checking a C-style cast, we've still got
1196 // the reinterpret_cast way.
1197
Douglas Gregord6e44a32010-04-16 22:09:46 +00001198 if (InitSeq.getKind() == InitializationSequence::FailedSequence &&
Douglas Gregor8e960432010-11-08 03:40:48 +00001199 (CStyle || !DestType->isReferenceType()))
Anders Carlsson3c31a392009-09-26 00:12:34 +00001200 return TC_NotApplicable;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001201
John McCall60d7b3a2010-08-24 06:29:42 +00001202 ExprResult Result
John Wiegley429bb272011-04-08 18:41:53 +00001203 = InitSeq.Perform(Self, Entity, InitKind, MultiExprArg(Self, &SrcExprRaw, 1));
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001204 if (Result.isInvalid()) {
1205 msg = 0;
1206 return TC_Failed;
1207 }
1208
Douglas Gregord6e44a32010-04-16 22:09:46 +00001209 if (InitSeq.isConstructorInitialization())
John McCall2de56d12010-08-25 11:45:40 +00001210 Kind = CK_ConstructorConversion;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001211 else
John McCall2de56d12010-08-25 11:45:40 +00001212 Kind = CK_NoOp;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001213
John Wiegley429bb272011-04-08 18:41:53 +00001214 SrcExpr = move(Result);
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001215 return TC_Success;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001216}
1217
1218/// TryConstCast - See if a const_cast from source to destination is allowed,
1219/// and perform it if it is.
1220static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
1221 bool CStyle, unsigned &msg) {
1222 DestType = Self.Context.getCanonicalType(DestType);
1223 QualType SrcType = SrcExpr->getType();
Douglas Gregor575d2a32011-01-22 00:19:52 +00001224 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
1225 if (DestTypeTmp->isLValueReferenceType() && !SrcExpr->isLValue()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001226 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1227 // is C-style, static_cast might find a way, so we simply suggest a
1228 // message and tell the parent to keep searching.
1229 msg = diag::err_bad_cxx_cast_rvalue;
1230 return TC_NotApplicable;
1231 }
1232
1233 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
1234 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
1235 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1236 SrcType = Self.Context.getPointerType(SrcType);
1237 }
1238
1239 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1240 // the rules for const_cast are the same as those used for pointers.
1241
John McCalld425d2b2010-05-18 09:35:29 +00001242 if (!DestType->isPointerType() &&
1243 !DestType->isMemberPointerType() &&
1244 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001245 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1246 // was a reference type, we converted it to a pointer above.
1247 // The status of rvalue references isn't entirely clear, but it looks like
1248 // conversion to them is simply invalid.
1249 // C++ 5.2.11p3: For two pointer types [...]
1250 if (!CStyle)
1251 msg = diag::err_bad_const_cast_dest;
1252 return TC_NotApplicable;
1253 }
1254 if (DestType->isFunctionPointerType() ||
1255 DestType->isMemberFunctionPointerType()) {
1256 // Cannot cast direct function pointers.
1257 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1258 // T is the ultimate pointee of source and target type.
1259 if (!CStyle)
1260 msg = diag::err_bad_const_cast_dest;
1261 return TC_NotApplicable;
1262 }
1263 SrcType = Self.Context.getCanonicalType(SrcType);
1264
1265 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1266 // completely equal.
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001267 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1268 // in multi-level pointers may change, but the level count must be the same,
1269 // as must be the final pointee type.
1270 while (SrcType != DestType &&
Douglas Gregor5a57efd2010-06-09 03:53:18 +00001271 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001272 Qualifiers SrcQuals, DestQuals;
1273 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
1274 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
1275
1276 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
1277 // the other qualifiers (e.g., address spaces) are identical.
1278 SrcQuals.removeCVRQualifiers();
1279 DestQuals.removeCVRQualifiers();
1280 if (SrcQuals != DestQuals)
1281 return TC_NotApplicable;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001282 }
1283
1284 // Since we're dealing in canonical types, the remainder must be the same.
1285 if (SrcType != DestType)
1286 return TC_NotApplicable;
1287
1288 return TC_Success;
1289}
1290
Douglas Gregorfadb53b2011-03-12 01:48:56 +00001291
John Wiegley429bb272011-04-08 18:41:53 +00001292static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001293 QualType DestType, bool CStyle,
1294 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +00001295 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +00001296 CastKind &Kind) {
Douglas Gregore39a3892010-07-13 23:17:26 +00001297 bool IsLValueCast = false;
1298
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001299 DestType = Self.Context.getCanonicalType(DestType);
John Wiegley429bb272011-04-08 18:41:53 +00001300 QualType SrcType = SrcExpr.get()->getType();
Douglas Gregor8e960432010-11-08 03:40:48 +00001301
1302 // Is the source an overloaded name? (i.e. &foo)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001303 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ...
1304 if (SrcType == Self.Context.OverloadTy) {
1305 // ... unless foo<int> resolves to an lvalue unambiguously
1306 ExprResult SingleFunctionExpr =
John Wiegley429bb272011-04-08 18:41:53 +00001307 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr.get(),
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001308 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
1309 );
1310 if (SingleFunctionExpr.isUsable()) {
John Wiegley429bb272011-04-08 18:41:53 +00001311 SrcExpr = move(SingleFunctionExpr);
1312 SrcType = SrcExpr.get()->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001313 }
1314 else
1315 return TC_NotApplicable;
1316 }
Douglas Gregor8e960432010-11-08 03:40:48 +00001317
Ted Kremenek6217b802009-07-29 21:53:49 +00001318 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001319 bool LValue = DestTypeTmp->isLValueReferenceType();
John Wiegley429bb272011-04-08 18:41:53 +00001320 if (LValue && !SrcExpr.get()->isLValue()) {
Douglas Gregor575d2a32011-01-22 00:19:52 +00001321 // Cannot cast non-lvalue to lvalue reference type. See the similar
1322 // comment in const_cast.
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001323 msg = diag::err_bad_cxx_cast_rvalue;
1324 return TC_NotApplicable;
1325 }
1326
1327 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1328 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1329 // built-in & and * operators.
Argyrios Kyrtzidisb464a5b2011-04-22 22:31:13 +00001330
Argyrios Kyrtzidisbb29d1b2011-04-22 23:57:57 +00001331 const char *inappropriate = 0;
1332 switch (SrcExpr.get()->getObjectKind()) {
Argyrios Kyrtzidise5e3d312011-04-23 01:10:24 +00001333 case OK_Ordinary:
1334 break;
Argyrios Kyrtzidisbb29d1b2011-04-22 23:57:57 +00001335 case OK_BitField: inappropriate = "bit-field"; break;
1336 case OK_VectorComponent: inappropriate = "vector element"; break;
1337 case OK_ObjCProperty: inappropriate = "property expression"; break;
1338 }
1339 if (inappropriate) {
1340 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
1341 << inappropriate << DestType
1342 << OpRange << SrcExpr.get()->getSourceRange();
1343 msg = 0; SrcExpr = ExprError();
Argyrios Kyrtzidisb464a5b2011-04-22 22:31:13 +00001344 return TC_NotApplicable;
1345 }
1346
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001347 // This code does this transformation for the checked types.
1348 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1349 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregor8e960432010-11-08 03:40:48 +00001350
Douglas Gregore39a3892010-07-13 23:17:26 +00001351 IsLValueCast = true;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001352 }
1353
1354 // Canonicalize source for comparison.
1355 SrcType = Self.Context.getCanonicalType(SrcType);
1356
Ted Kremenek6217b802009-07-29 21:53:49 +00001357 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1358 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001359 if (DestMemPtr && SrcMemPtr) {
1360 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1361 // can be explicitly converted to an rvalue of type "pointer to member
1362 // of Y of type T2" if T1 and T2 are both function types or both object
1363 // types.
1364 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1365 SrcMemPtr->getPointeeType()->isFunctionType())
1366 return TC_NotApplicable;
1367
1368 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1369 // constness.
1370 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1371 // we accept it.
1372 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001373 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001374 return TC_Failed;
1375 }
1376
Charles Davisf231df32010-08-16 05:30:44 +00001377 // Don't allow casting between member pointers of different sizes.
1378 if (Self.Context.getTypeSize(DestMemPtr) !=
1379 Self.Context.getTypeSize(SrcMemPtr)) {
1380 msg = diag::err_bad_cxx_cast_member_pointer_size;
1381 return TC_Failed;
1382 }
1383
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001384 // A valid member pointer cast.
John McCall2de56d12010-08-25 11:45:40 +00001385 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001386 return TC_Success;
1387 }
1388
1389 // See below for the enumeral issue.
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001390 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001391 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1392 // type large enough to hold it. A value of std::nullptr_t can be
1393 // converted to an integral type; the conversion has the same meaning
1394 // and validity as a conversion of (void*)0 to the integral type.
1395 if (Self.Context.getTypeSize(SrcType) >
1396 Self.Context.getTypeSize(DestType)) {
1397 msg = diag::err_bad_reinterpret_cast_small_int;
1398 return TC_Failed;
1399 }
John McCall2de56d12010-08-25 11:45:40 +00001400 Kind = CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001401 return TC_Success;
1402 }
1403
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001404 bool destIsVector = DestType->isVectorType();
1405 bool srcIsVector = SrcType->isVectorType();
1406 if (srcIsVector || destIsVector) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001407 // FIXME: Should this also apply to floating point types?
1408 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1409 bool destIsScalar = DestType->isIntegralType(Self.Context);
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001410
1411 // Check if this is a cast between a vector and something else.
1412 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1413 !(srcIsVector && destIsVector))
1414 return TC_NotApplicable;
1415
1416 // If both types have the same size, we can successfully cast.
Douglas Gregorf2a55392009-12-22 22:47:22 +00001417 if (Self.Context.getTypeSize(SrcType)
1418 == Self.Context.getTypeSize(DestType)) {
John McCall2de56d12010-08-25 11:45:40 +00001419 Kind = CK_BitCast;
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001420 return TC_Success;
Douglas Gregorf2a55392009-12-22 22:47:22 +00001421 }
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001422
1423 if (destIsScalar)
1424 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1425 else if (srcIsScalar)
1426 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1427 else
1428 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1429
1430 return TC_Failed;
1431 }
1432
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001433 bool destIsPtr = DestType->isAnyPointerType() ||
1434 DestType->isBlockPointerType();
1435 bool srcIsPtr = SrcType->isAnyPointerType() ||
1436 SrcType->isBlockPointerType();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001437 if (!destIsPtr && !srcIsPtr) {
1438 // Except for std::nullptr_t->integer and lvalue->reference, which are
1439 // handled above, at least one of the two arguments must be a pointer.
1440 return TC_NotApplicable;
1441 }
1442
1443 if (SrcType == DestType) {
1444 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1445 // restrictions, a cast to the same type is allowed. The intent is not
1446 // entirely clear here, since all other paragraphs explicitly forbid casts
1447 // to the same type. However, the behavior of compilers is pretty consistent
1448 // on this point: allow same-type conversion if the involved types are
1449 // pointers, disallow otherwise.
John McCall2de56d12010-08-25 11:45:40 +00001450 Kind = CK_NoOp;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001451 return TC_Success;
1452 }
1453
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001454 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001455 assert(srcIsPtr && "One type must be a pointer");
1456 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1457 // type large enough to hold it.
1458 if (Self.Context.getTypeSize(SrcType) >
1459 Self.Context.getTypeSize(DestType)) {
1460 msg = diag::err_bad_reinterpret_cast_small_int;
1461 return TC_Failed;
1462 }
John McCall2de56d12010-08-25 11:45:40 +00001463 Kind = CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001464 return TC_Success;
1465 }
1466
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001467 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001468 assert(destIsPtr && "One type must be a pointer");
1469 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1470 // converted to a pointer.
John McCall404cd162010-11-13 01:35:44 +00001471 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1472 // necessarily converted to a null pointer value.]
John McCall2de56d12010-08-25 11:45:40 +00001473 Kind = CK_IntegralToPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001474 return TC_Success;
1475 }
1476
1477 if (!destIsPtr || !srcIsPtr) {
1478 // With the valid non-pointer conversions out of the way, we can be even
1479 // more stringent.
1480 return TC_NotApplicable;
1481 }
1482
1483 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1484 // The C-style cast operator can.
1485 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001486 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001487 return TC_Failed;
1488 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001489
1490 // Cannot convert between block pointers and Objective-C object pointers.
1491 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1492 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1493 return TC_NotApplicable;
1494
1495 // Any pointer can be cast to an Objective-C pointer type with a C-style
1496 // cast.
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001497 if (CStyle && DestType->isObjCObjectPointerType()) {
John McCall2de56d12010-08-25 11:45:40 +00001498 Kind = CK_AnyPointerToObjCPointerCast;
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001499 return TC_Success;
1500 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001501
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001502 // Not casting away constness, so the only remaining check is for compatible
1503 // pointer categories.
John McCall2de56d12010-08-25 11:45:40 +00001504 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001505
1506 if (SrcType->isFunctionPointerType()) {
1507 if (DestType->isFunctionPointerType()) {
1508 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1509 // a pointer to a function of a different type.
1510 return TC_Success;
1511 }
1512
1513 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1514 // an object type or vice versa is conditionally-supported.
1515 // Compilers support it in C++03 too, though, because it's necessary for
1516 // casting the return value of dlsym() and GetProcAddress().
1517 // FIXME: Conditionally-supported behavior should be configurable in the
1518 // TargetInfo or similar.
1519 if (!Self.getLangOptions().CPlusPlus0x)
1520 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1521 return TC_Success;
1522 }
1523
1524 if (DestType->isFunctionPointerType()) {
1525 // See above.
1526 if (!Self.getLangOptions().CPlusPlus0x)
1527 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1528 return TC_Success;
1529 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001530
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001531 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1532 // a pointer to an object of different type.
1533 // Void pointers are not specified, but supported by every compiler out there.
1534 // So we finish by allowing everything that remains - it's got to be two
1535 // object pointers.
1536 return TC_Success;
John McCall79ab2c82011-02-14 18:34:10 +00001537}
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001538
John Wiegley429bb272011-04-08 18:41:53 +00001539ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001540Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, ExprValueKind &VK,
John Wiegley429bb272011-04-08 18:41:53 +00001541 Expr *CastExpr, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001542 CXXCastPath &BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001543 bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001544 // This test is outside everything else because it's the only case where
1545 // a non-lvalue-reference target type does not lead to decay.
1546 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001547 if (CastTy->isVoidType()) {
John McCallfb8721c2011-04-10 19:13:55 +00001548 Kind = CK_ToVoid;
1549
John Wiegley429bb272011-04-08 18:41:53 +00001550 ExprResult CastExprRes = IgnoredValueConversions(CastExpr);
1551 if (CastExprRes.isInvalid())
1552 return ExprError();
1553 CastExpr = CastExprRes.take();
John McCallfb8721c2011-04-10 19:13:55 +00001554
John McCall864c0412011-04-26 20:42:42 +00001555 if (CastExpr->getType() == Context.BoundMemberTy)
1556 return CheckPlaceholderExpr(CastExpr); // will always fail
1557
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001558 if (CastExpr->getType() == Context.OverloadTy) {
1559 ExprResult SingleFunctionExpr =
Douglas Gregorfadb53b2011-03-12 01:48:56 +00001560 ResolveAndFixSingleFunctionTemplateSpecialization(
1561 CastExpr, /* Decay Function to ptr */ false,
1562 /* Complain */ true, R, CastTy,
1563 diag::err_bad_cstyle_cast_overload);
John McCallfb8721c2011-04-10 19:13:55 +00001564 if (SingleFunctionExpr.isInvalid())
1565 return ExprError();
1566 CastExpr = SingleFunctionExpr.take();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001567 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001568
John McCallfb8721c2011-04-10 19:13:55 +00001569 assert(!CastExpr->getType()->isPlaceholderType());
1570
John Wiegley429bb272011-04-08 18:41:53 +00001571 return Owned(CastExpr);
Anton Yartsevd06fea82011-03-27 09:32:40 +00001572 }
1573
John McCall9b4b9d62010-11-30 02:05:44 +00001574 // Make sure we determine the value kind before we bail out for
1575 // dependent types.
1576 VK = Expr::getValueKindForType(CastTy);
1577
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001578 // If the type is dependent, we won't do any other semantic analysis now.
John McCalldaa8e4e2010-11-15 09:13:47 +00001579 if (CastTy->isDependentType() || CastExpr->isTypeDependent()) {
1580 Kind = CK_Dependent;
John Wiegley429bb272011-04-08 18:41:53 +00001581 return Owned(CastExpr);
John McCalldaa8e4e2010-11-15 09:13:47 +00001582 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001583
John Wiegley429bb272011-04-08 18:41:53 +00001584 if (VK == VK_RValue && !CastTy->isRecordType()) {
1585 ExprResult CastExprRes = DefaultFunctionArrayLvalueConversion(CastExpr);
1586 if (CastExprRes.isInvalid())
1587 return ExprError();
1588 CastExpr = CastExprRes.take();
1589 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001590
John McCallfb8721c2011-04-10 19:13:55 +00001591 // AltiVec vector initialization with a single literal.
1592 if (const VectorType *vecTy = CastTy->getAs<VectorType>())
1593 if (vecTy->getVectorKind() == VectorType::AltiVecVector
1594 && (CastExpr->getType()->isIntegerType()
1595 || CastExpr->getType()->isFloatingType())) {
1596 Kind = CK_VectorSplat;
1597 return Owned(CastExpr);
1598 }
1599
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001600 // C++ [expr.cast]p5: The conversions performed by
1601 // - a const_cast,
1602 // - a static_cast,
1603 // - a static_cast followed by a const_cast,
1604 // - a reinterpret_cast, or
1605 // - a reinterpret_cast followed by a const_cast,
1606 // can be performed using the cast notation of explicit type conversion.
1607 // [...] If a conversion can be interpreted in more than one of the ways
1608 // listed above, the interpretation that appears first in the list is used,
1609 // even if a cast resulting from that interpretation is ill-formed.
1610 // In plain language, this means trying a const_cast ...
1611 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001612 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1613 msg);
Anders Carlssonda921fd2009-10-19 18:14:28 +00001614 if (tcr == TC_Success)
John McCall2de56d12010-08-25 11:45:40 +00001615 Kind = CK_NoOp;
Anders Carlssonda921fd2009-10-19 18:14:28 +00001616
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001617 if (tcr == TC_NotApplicable) {
1618 // ... or if that is not possible, a static_cast, ignoring const, ...
John Wiegley429bb272011-04-08 18:41:53 +00001619 ExprResult CastExprRes = Owned(CastExpr);
Richard Trieu32ac00d2011-04-16 01:09:30 +00001620 tcr = TryStaticCast(*this, CastExprRes, CastTy, /*CStyle*/true, R, msg,
1621 Kind, BasePath);
John Wiegley429bb272011-04-08 18:41:53 +00001622 if (CastExprRes.isInvalid())
1623 return ExprError();
1624 CastExpr = CastExprRes.take();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001625 if (tcr == TC_NotApplicable) {
1626 // ... and finally a reinterpret_cast, ignoring const.
John Wiegley429bb272011-04-08 18:41:53 +00001627 CastExprRes = Owned(CastExpr);
Richard Trieu32ac00d2011-04-16 01:09:30 +00001628 tcr = TryReinterpretCast(*this, CastExprRes, CastTy, /*CStyle*/true, R,
1629 msg, Kind);
John Wiegley429bb272011-04-08 18:41:53 +00001630 if (CastExprRes.isInvalid())
1631 return ExprError();
1632 CastExpr = CastExprRes.take();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001633 }
1634 }
1635
Nick Lewycky43328e92010-11-09 00:19:31 +00001636 if (tcr != TC_Success && msg != 0) {
1637 if (CastExpr->getType() == Context.OverloadTy) {
Douglas Gregor8e960432010-11-08 03:40:48 +00001638 DeclAccessPair Found;
John Wiegley429bb272011-04-08 18:41:53 +00001639 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(CastExpr,
Douglas Gregor8e960432010-11-08 03:40:48 +00001640 CastTy,
1641 /* Complain */ true,
1642 Found);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001643
Richard Trieu32ac00d2011-04-16 01:09:30 +00001644 assert(!Fn && "cast failed but able to resolve overload expression!!");
Nick Lewycky43328e92010-11-09 00:19:31 +00001645 (void)Fn;
John McCall79ab2c82011-02-14 18:34:10 +00001646
Nick Lewycky43328e92010-11-09 00:19:31 +00001647 } else {
John McCall79ab2c82011-02-14 18:34:10 +00001648 diagnoseBadCast(*this, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
1649 R, CastExpr, CastTy);
Douglas Gregor8e960432010-11-08 03:40:48 +00001650 }
1651 }
John McCalle2b76882010-11-16 05:46:29 +00001652 else if (Kind == CK_BitCast)
John McCallb7f4ffe2010-08-12 21:44:57 +00001653 CheckCastAlign(CastExpr, CastTy, R);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001654
John Wiegley429bb272011-04-08 18:41:53 +00001655 if (tcr != TC_Success)
1656 return ExprError();
1657
1658 return Owned(CastExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001659}