blob: 648011b1f05fb084a79b1cd3ae6c33ecf8c14b3c [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 Wiegley429bb272011-04-08 18:41:53 +0000163 if (Ex.get()->isBoundMemberFunction(Context))
164 Diag(Ex.get()->getLocStart(), diag::err_invalid_use_of_bound_member_func)
165 << Ex.get()->getSourceRange();
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +0000166
John McCallf89e55a2010-11-18 06:31:45 +0000167 ExprValueKind VK = VK_RValue;
John McCalla21e06c2010-11-26 10:57:22 +0000168 if (TypeDependent)
169 VK = Expr::getValueKindForType(DestType);
170
Sebastian Redl26d85b12008-11-05 21:50:06 +0000171 switch (Kind) {
John McCalldaa8e4e2010-11-15 09:13:47 +0000172 default: llvm_unreachable("Unknown C++ cast!");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000173
174 case tok::kw_const_cast:
John Wiegley429bb272011-04-08 18:41:53 +0000175 if (!TypeDependent) {
John McCallf89e55a2010-11-18 06:31:45 +0000176 CheckConstCast(*this, Ex, DestType, VK, OpRange, DestRange);
John Wiegley429bb272011-04-08 18:41:53 +0000177 if (Ex.isInvalid())
178 return ExprError();
179 }
John McCallf871d0c2010-08-07 06:22:56 +0000180 return Owned(CXXConstCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +0000181 DestType.getNonLValueExprType(Context),
John Wiegley429bb272011-04-08 18:41:53 +0000182 VK, Ex.take(), DestTInfo, OpLoc,
Douglas Gregor1d5d0b92011-01-12 22:41:29 +0000183 Parens.getEnd()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000184
Anders Carlsson714179b2009-08-02 19:07:59 +0000185 case tok::kw_dynamic_cast: {
John McCalldaa8e4e2010-11-15 09:13:47 +0000186 CastKind Kind = CK_Dependent;
John McCallf871d0c2010-08-07 06:22:56 +0000187 CXXCastPath BasePath;
John Wiegley429bb272011-04-08 18:41:53 +0000188 if (!TypeDependent) {
John McCallf89e55a2010-11-18 06:31:45 +0000189 CheckDynamicCast(*this, Ex, DestType, VK, OpRange, DestRange,
190 Kind, BasePath);
John Wiegley429bb272011-04-08 18:41:53 +0000191 if (Ex.isInvalid())
192 return ExprError();
193 }
John McCallf871d0c2010-08-07 06:22:56 +0000194 return Owned(CXXDynamicCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +0000195 DestType.getNonLValueExprType(Context),
John Wiegley429bb272011-04-08 18:41:53 +0000196 VK, Kind, Ex.take(), &BasePath, DestTInfo,
Douglas Gregor1d5d0b92011-01-12 22:41:29 +0000197 OpLoc, Parens.getEnd()));
Anders Carlsson714179b2009-08-02 19:07:59 +0000198 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000199 case tok::kw_reinterpret_cast: {
John McCalldaa8e4e2010-11-15 09:13:47 +0000200 CastKind Kind = CK_Dependent;
John Wiegley429bb272011-04-08 18:41:53 +0000201 if (!TypeDependent) {
John McCallf89e55a2010-11-18 06:31:45 +0000202 CheckReinterpretCast(*this, Ex, DestType, VK, OpRange, DestRange, Kind);
John Wiegley429bb272011-04-08 18:41:53 +0000203 if (Ex.isInvalid())
204 return ExprError();
205 }
John McCallf871d0c2010-08-07 06:22:56 +0000206 return Owned(CXXReinterpretCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +0000207 DestType.getNonLValueExprType(Context),
John Wiegley429bb272011-04-08 18:41:53 +0000208 VK, Kind, Ex.take(), 0,
Douglas Gregor1d5d0b92011-01-12 22:41:29 +0000209 DestTInfo, OpLoc, Parens.getEnd()));
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000210 }
Anders Carlssoncdb61972009-08-07 22:21:05 +0000211 case tok::kw_static_cast: {
John McCalldaa8e4e2010-11-15 09:13:47 +0000212 CastKind Kind = CK_Dependent;
John McCallf871d0c2010-08-07 06:22:56 +0000213 CXXCastPath BasePath;
John Wiegley429bb272011-04-08 18:41:53 +0000214 if (!TypeDependent) {
John McCallf89e55a2010-11-18 06:31:45 +0000215 CheckStaticCast(*this, Ex, DestType, VK, OpRange, Kind, BasePath);
John Wiegley429bb272011-04-08 18:41:53 +0000216 if (Ex.isInvalid())
217 return ExprError();
218 }
Anders Carlsson0aebc812009-09-09 21:33:21 +0000219
John McCallf871d0c2010-08-07 06:22:56 +0000220 return Owned(CXXStaticCastExpr::Create(Context,
Douglas Gregor63982352010-07-13 18:40:04 +0000221 DestType.getNonLValueExprType(Context),
John Wiegley429bb272011-04-08 18:41:53 +0000222 VK, Kind, Ex.take(), &BasePath,
Douglas Gregor1d5d0b92011-01-12 22:41:29 +0000223 DestTInfo, OpLoc, Parens.getEnd()));
Anders Carlssoncdb61972009-08-07 22:21:05 +0000224 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000225 }
226
Sebastian Redlf53597f2009-03-15 17:47:39 +0000227 return ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000228}
229
John McCall79ab2c82011-02-14 18:34:10 +0000230/// Try to diagnose a failed overloaded cast. Returns true if
231/// diagnostics were emitted.
232static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
233 SourceRange range, Expr *src,
234 QualType destType) {
235 switch (CT) {
236 // These cast kinds don't consider user-defined conversions.
237 case CT_Const:
238 case CT_Reinterpret:
239 case CT_Dynamic:
240 return false;
241
242 // These do.
243 case CT_Static:
244 case CT_CStyle:
245 case CT_Functional:
246 break;
247 }
248
249 QualType srcType = src->getType();
250 if (!destType->isRecordType() && !srcType->isRecordType())
251 return false;
252
253 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
254 InitializationKind initKind
255 = InitializationKind::CreateCast(/*type range?*/ range,
256 (CT == CT_CStyle || CT == CT_Functional));
257 InitializationSequence sequence(S, entity, initKind, &src, 1);
258
259 assert(sequence.getKind() == InitializationSequence::FailedSequence &&
260 "initialization succeeded on second try?");
261 switch (sequence.getFailureKind()) {
262 default: return false;
263
264 case InitializationSequence::FK_ConstructorOverloadFailed:
265 case InitializationSequence::FK_UserConversionOverloadFailed:
266 break;
267 }
268
269 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
270
271 unsigned msg = 0;
272 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
273
274 switch (sequence.getFailedOverloadResult()) {
275 case OR_Success: llvm_unreachable("successful failed overload");
276 return false;
277 case OR_No_Viable_Function:
278 if (candidates.empty())
279 msg = diag::err_ovl_no_conversion_in_cast;
280 else
281 msg = diag::err_ovl_no_viable_conversion_in_cast;
282 howManyCandidates = OCD_AllCandidates;
283 break;
284
285 case OR_Ambiguous:
286 msg = diag::err_ovl_ambiguous_conversion_in_cast;
287 howManyCandidates = OCD_ViableCandidates;
288 break;
289
290 case OR_Deleted:
291 msg = diag::err_ovl_deleted_conversion_in_cast;
292 howManyCandidates = OCD_ViableCandidates;
293 break;
294 }
295
296 S.Diag(range.getBegin(), msg)
297 << CT << srcType << destType
298 << range << src->getSourceRange();
299
300 candidates.NoteCandidates(S, howManyCandidates, &src, 1);
301
302 return true;
303}
304
305/// Diagnose a failed cast.
306static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
307 SourceRange opRange, Expr *src, QualType destType) {
308 if (msg == diag::err_bad_cxx_cast_generic &&
309 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType))
310 return;
311
312 S.Diag(opRange.getBegin(), msg) << castType
313 << src->getType() << destType << opRange << src->getSourceRange();
314}
315
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000316/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
317/// this removes one level of indirection from both types, provided that they're
318/// the same kind of pointer (plain or to-member). Unlike the Sema function,
319/// this one doesn't care if the two pointers-to-member don't point into the
320/// same class. This is because CastsAwayConstness doesn't care.
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000321static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000322 const PointerType *T1PtrType = T1->getAs<PointerType>(),
323 *T2PtrType = T2->getAs<PointerType>();
324 if (T1PtrType && T2PtrType) {
325 T1 = T1PtrType->getPointeeType();
326 T2 = T2PtrType->getPointeeType();
327 return true;
328 }
Fariborz Jahanian72a86592010-02-03 20:32:31 +0000329 const ObjCObjectPointerType *T1ObjCPtrType =
330 T1->getAs<ObjCObjectPointerType>(),
331 *T2ObjCPtrType =
332 T2->getAs<ObjCObjectPointerType>();
333 if (T1ObjCPtrType) {
334 if (T2ObjCPtrType) {
335 T1 = T1ObjCPtrType->getPointeeType();
336 T2 = T2ObjCPtrType->getPointeeType();
337 return true;
338 }
339 else if (T2PtrType) {
340 T1 = T1ObjCPtrType->getPointeeType();
341 T2 = T2PtrType->getPointeeType();
342 return true;
343 }
344 }
345 else if (T2ObjCPtrType) {
346 if (T1PtrType) {
347 T2 = T2ObjCPtrType->getPointeeType();
348 T1 = T1PtrType->getPointeeType();
349 return true;
350 }
351 }
352
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000353 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
354 *T2MPType = T2->getAs<MemberPointerType>();
355 if (T1MPType && T2MPType) {
356 T1 = T1MPType->getPointeeType();
357 T2 = T2MPType->getPointeeType();
358 return true;
359 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000360
361 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
362 *T2BPType = T2->getAs<BlockPointerType>();
363 if (T1BPType && T2BPType) {
364 T1 = T1BPType->getPointeeType();
365 T2 = T2BPType->getPointeeType();
366 return true;
367 }
368
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000369 return false;
370}
371
Sebastian Redldb647282009-01-27 23:18:31 +0000372/// CastsAwayConstness - Check if the pointer conversion from SrcType to
373/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
374/// the cast checkers. Both arguments must denote pointer (possibly to member)
375/// types.
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000376static bool
Mike Stump1eb44332009-09-09 15:08:12 +0000377CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
Sebastian Redldb647282009-01-27 23:18:31 +0000378 // Casting away constness is defined in C++ 5.2.11p8 with reference to
379 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
380 // the rules are non-trivial. So first we construct Tcv *...cv* as described
381 // in C++ 5.2.11p8.
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000382 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
383 SrcType->isBlockPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000384 "Source type is not pointer or pointer to member.");
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000385 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
386 DestType->isBlockPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000387 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000388
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000389 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
390 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
John McCall0953e762009-09-24 19:53:00 +0000391 llvm::SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000392
Douglas Gregord4c5f842011-04-15 17:59:54 +0000393 // Find the qualifiers. We only care about cvr-qualifiers for the
394 // purpose of this check, because other qualifiers (address spaces,
395 // Objective-C GC, etc.) are part of the type's identity.
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000396 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
Anders Carlsson52647c62010-06-04 22:47:55 +0000397 Qualifiers SrcQuals;
398 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
Douglas Gregord4c5f842011-04-15 17:59:54 +0000399 cv1.push_back(Qualifiers::fromCVRMask(SrcQuals.getCVRQualifiers()));
Anders Carlsson52647c62010-06-04 22:47:55 +0000400
401 Qualifiers DestQuals;
402 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
Douglas Gregord4c5f842011-04-15 17:59:54 +0000403 cv2.push_back(Qualifiers::fromCVRMask(DestQuals.getCVRQualifiers()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000404 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000405 if (cv1.empty())
406 return false;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000407
408 // Construct void pointers with those qualifiers (in reverse order of
409 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000410 QualType SrcConstruct = Self.Context.VoidTy;
411 QualType DestConstruct = Self.Context.VoidTy;
John McCall0953e762009-09-24 19:53:00 +0000412 ASTContext &Context = Self.Context;
413 for (llvm::SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
414 i2 = cv2.rbegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000415 i1 != cv1.rend(); ++i1, ++i2) {
John McCall0953e762009-09-24 19:53:00 +0000416 SrcConstruct
417 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
418 DestConstruct
419 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000420 }
421
422 // Test if they're compatible.
423 return SrcConstruct != DestConstruct &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +0000424 !Self.IsQualificationConversion(SrcConstruct, DestConstruct, false);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000425}
426
Sebastian Redl26d85b12008-11-05 21:50:06 +0000427/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
428/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
429/// checked downcasts in class hierarchies.
Anders Carlsson714179b2009-08-02 19:07:59 +0000430static void
John Wiegley429bb272011-04-08 18:41:53 +0000431CheckDynamicCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCallf89e55a2010-11-18 06:31:45 +0000432 ExprValueKind &VK, const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +0000433 const SourceRange &DestRange, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000434 CXXCastPath &BasePath) {
John Wiegley429bb272011-04-08 18:41:53 +0000435 QualType OrigDestType = DestType, OrigSrcType = SrcExpr.get()->getType();
Sebastian Redl37d6de32008-11-08 13:00:26 +0000436 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000437
438 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
439 // or "pointer to cv void".
440
441 QualType DestPointee;
Ted Kremenek6217b802009-07-29 21:53:49 +0000442 const PointerType *DestPointer = DestType->getAs<PointerType>();
John McCallf89e55a2010-11-18 06:31:45 +0000443 const ReferenceType *DestReference = 0;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000444 if (DestPointer) {
445 DestPointee = DestPointer->getPointeeType();
John McCallf89e55a2010-11-18 06:31:45 +0000446 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000447 DestPointee = DestReference->getPointeeType();
Douglas Gregordc843f22011-01-22 00:06:57 +0000448 VK = isa<LValueReferenceType>(DestReference) ? VK_LValue
449 : isa<RValueReferenceType>(DestReference) ? VK_XValue
450 : VK_RValue;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000451 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000452 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000453 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000454 return;
455 }
456
Ted Kremenek6217b802009-07-29 21:53:49 +0000457 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000458 if (DestPointee->isVoidType()) {
459 assert(DestPointer && "Reference to void is not possible");
460 } else if (DestRecord) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000461 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000462 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssonb7906612009-08-26 23:45:07 +0000463 << DestRange))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000464 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000465 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000466 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000467 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000468 return;
469 }
470
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000471 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
472 // complete class type, [...]. If T is an lvalue reference type, v shall be
Douglas Gregordc843f22011-01-22 00:06:57 +0000473 // an lvalue of a complete class type, [...]. If T is an rvalue reference
474 // type, v shall be an expression having a complete class type, [...]
Sebastian Redl37d6de32008-11-08 13:00:26 +0000475 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000476 QualType SrcPointee;
477 if (DestPointer) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000478 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000479 SrcPointee = SrcPointer->getPointeeType();
480 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000481 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
John Wiegley429bb272011-04-08 18:41:53 +0000482 << OrigSrcType << SrcExpr.get()->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000483 return;
484 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000485 } else if (DestReference->isLValueReferenceType()) {
John Wiegley429bb272011-04-08 18:41:53 +0000486 if (!SrcExpr.get()->isLValue()) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000487 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000488 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000489 }
490 SrcPointee = SrcType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000491 } else {
492 SrcPointee = SrcType;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000493 }
494
Ted Kremenek6217b802009-07-29 21:53:49 +0000495 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000496 if (SrcRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000497 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000498 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
John Wiegley429bb272011-04-08 18:41:53 +0000499 << SrcExpr.get()->getSourceRange()))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000500 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000501 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000502 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
John Wiegley429bb272011-04-08 18:41:53 +0000503 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000504 return;
505 }
506
507 assert((DestPointer || DestReference) &&
508 "Bad destination non-ptr/ref slipped through.");
509 assert((DestRecord || DestPointee->isVoidType()) &&
510 "Bad destination pointee slipped through.");
511 assert(SrcRecord && "Bad source pointee slipped through.");
512
513 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
514 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +0000515 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000516 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000517 return;
518 }
519
520 // C++ 5.2.7p3: If the type of v is the same as the required result type,
521 // [except for cv].
522 if (DestRecord == SrcRecord) {
John McCall2de56d12010-08-25 11:45:40 +0000523 Kind = CK_NoOp;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000524 return;
525 }
526
527 // C++ 5.2.7p5
528 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000529 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000530 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
531 OpRange.getBegin(), OpRange,
532 &BasePath))
533 return;
534
John McCall2de56d12010-08-25 11:45:40 +0000535 Kind = CK_DerivedToBase;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000536
537 // If we are casting to or through a virtual base class, we need a
538 // vtable.
539 if (Self.BasePathInvolvesVirtualBase(BasePath))
540 Self.MarkVTableUsed(OpRange.getBegin(),
541 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000542 return;
543 }
544
545 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor952b0172010-02-11 01:04:33 +0000546 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000547 assert(SrcDecl && "Definition missing");
548 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000549 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
John Wiegley429bb272011-04-08 18:41:53 +0000550 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000551 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000552 Self.MarkVTableUsed(OpRange.getBegin(),
553 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000554
555 // Done. Everything else is run-time checks.
John McCall2de56d12010-08-25 11:45:40 +0000556 Kind = CK_Dynamic;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000557}
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000558
559/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
560/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
561/// like this:
562/// const char *str = "literal";
563/// legacy_function(const_cast\<char*\>(str));
564void
John Wiegley429bb272011-04-08 18:41:53 +0000565CheckConstCast(Sema &Self, ExprResult &SrcExpr, QualType DestType, ExprValueKind &VK,
Mike Stump1eb44332009-09-09 15:08:12 +0000566 const SourceRange &OpRange, const SourceRange &DestRange) {
John McCallf89e55a2010-11-18 06:31:45 +0000567 VK = Expr::getValueKindForType(DestType);
John Wiegley429bb272011-04-08 18:41:53 +0000568 if (VK == VK_RValue) {
569 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
570 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
571 return;
572 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000573
574 unsigned msg = diag::err_bad_cxx_cast_generic;
John Wiegley429bb272011-04-08 18:41:53 +0000575 if (TryConstCast(Self, SrcExpr.get(), DestType, /*CStyle*/false, msg) != TC_Success
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000576 && msg != 0)
577 Self.Diag(OpRange.getBegin(), msg) << CT_Const
John Wiegley429bb272011-04-08 18:41:53 +0000578 << SrcExpr.get()->getType() << DestType << OpRange;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000579}
580
581/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
582/// valid.
583/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
584/// like this:
585/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
586void
John Wiegley429bb272011-04-08 18:41:53 +0000587CheckReinterpretCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCallf89e55a2010-11-18 06:31:45 +0000588 ExprValueKind &VK, const SourceRange &OpRange,
589 const SourceRange &DestRange, CastKind &Kind) {
590 VK = Expr::getValueKindForType(DestType);
John Wiegley429bb272011-04-08 18:41:53 +0000591 if (VK == VK_RValue) {
592 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
593 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
594 return;
595 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000596
597 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson3c31a392009-09-26 00:12:34 +0000598 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
599 msg, Kind)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000600 != TC_Success && msg != 0)
Douglas Gregor8e960432010-11-08 03:40:48 +0000601 {
John Wiegley429bb272011-04-08 18:41:53 +0000602 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
603 return;
604 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor8e960432010-11-08 03:40:48 +0000605 //FIXME: &f<int>; is overloaded and resolvable
606 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
John Wiegley429bb272011-04-08 18:41:53 +0000607 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
Douglas Gregor8e960432010-11-08 03:40:48 +0000608 << DestType << OpRange;
John Wiegley429bb272011-04-08 18:41:53 +0000609 Self.NoteAllOverloadCandidates(SrcExpr.get());
Douglas Gregor8e960432010-11-08 03:40:48 +0000610
John McCall79ab2c82011-02-14 18:34:10 +0000611 } else {
John Wiegley429bb272011-04-08 18:41:53 +0000612 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(), DestType);
Douglas Gregor8e960432010-11-08 03:40:48 +0000613 }
John McCall79ab2c82011-02-14 18:34:10 +0000614 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000615}
616
617
618/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
619/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
620/// implicit conversions explicit and getting rid of data loss warnings.
621void
John Wiegley429bb272011-04-08 18:41:53 +0000622CheckStaticCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
John McCallf89e55a2010-11-18 06:31:45 +0000623 ExprValueKind &VK, const SourceRange &OpRange,
624 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000625 // This test is outside everything else because it's the only case where
626 // a non-lvalue-reference target type does not lead to decay.
627 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000628 if (DestType->isVoidType()) {
John Wiegley429bb272011-04-08 18:41:53 +0000629 SrcExpr = Self.IgnoredValueConversions(SrcExpr.take());
630 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
631 return;
632 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000633 ExprResult SingleFunctionExpression =
John Wiegley429bb272011-04-08 18:41:53 +0000634 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr.get(),
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000635 false, // Decay Function to ptr
636 true, // Complain
637 OpRange, DestType, diag::err_bad_static_cast_overload);
638 if (SingleFunctionExpression.isUsable())
639 {
John Wiegley429bb272011-04-08 18:41:53 +0000640 SrcExpr = SingleFunctionExpression;
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000641 Kind = CK_ToVoid;
642 }
643 }
644 else
645 Kind = CK_ToVoid;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000646 return;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000647 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000648
John McCallf89e55a2010-11-18 06:31:45 +0000649 VK = Expr::getValueKindForType(DestType);
John Wiegley429bb272011-04-08 18:41:53 +0000650 if (VK == VK_RValue && !DestType->isRecordType()) {
651 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.take());
652 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
653 return;
654 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000655
656 unsigned msg = diag::err_bad_cxx_cast_generic;
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000657 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg,
Douglas Gregor1be8eec2011-02-19 21:32:49 +0000658 Kind, BasePath) != TC_Success && msg != 0) {
John Wiegley429bb272011-04-08 18:41:53 +0000659 if (SrcExpr.isInvalid())
660 return;
661 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
662 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
Douglas Gregor8e960432010-11-08 03:40:48 +0000663 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
Douglas Gregor4c9be892011-02-28 20:01:57 +0000664 << oe->getName() << DestType << OpRange
665 << oe->getQualifierLoc().getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +0000666 Self.NoteAllOverloadCandidates(SrcExpr.get());
John McCall79ab2c82011-02-14 18:34:10 +0000667 } else {
John Wiegley429bb272011-04-08 18:41:53 +0000668 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType);
Douglas Gregor8e960432010-11-08 03:40:48 +0000669 }
Douglas Gregor8e960432010-11-08 03:40:48 +0000670 }
John McCalle2b76882010-11-16 05:46:29 +0000671 else if (Kind == CK_BitCast)
John Wiegley429bb272011-04-08 18:41:53 +0000672 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000673}
674
675/// TryStaticCast - Check if a static cast can be performed, and do so if
676/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
677/// and casting away constness.
John Wiegley429bb272011-04-08 18:41:53 +0000678static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000679 QualType DestType, bool CStyle,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000680 const SourceRange &OpRange, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000681 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000682 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000683 // The order the tests is not entirely arbitrary. There is one conversion
684 // that can be handled in two different ways. Given:
685 // struct A {};
686 // struct B : public A {
687 // B(); B(const A&);
688 // };
689 // const A &a = B();
690 // the cast static_cast<const B&>(a) could be seen as either a static
691 // reference downcast, or an explicit invocation of the user-defined
692 // conversion using B's conversion constructor.
693 // DR 427 specifies that the downcast is to be applied here.
694
695 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
696 // Done outside this function.
697
698 TryCastResult tcr;
699
700 // C++ 5.2.9p5, reference downcast.
701 // See the function for details.
702 // DR 427 specifies that this is to be applied before paragraph 2.
John Wiegley429bb272011-04-08 18:41:53 +0000703 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle, OpRange,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000704 msg, Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000705 if (tcr != TC_NotApplicable)
706 return tcr;
707
Douglas Gregordc843f22011-01-22 00:06:57 +0000708 // C++0x [expr.static.cast]p3:
709 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
710 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
John Wiegley429bb272011-04-08 18:41:53 +0000711 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind, BasePath,
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000712 msg);
Douglas Gregor88b22a42011-01-25 16:13:26 +0000713 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000714 return tcr;
715
716 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
717 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000718 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
Douglas Gregord6e44a32010-04-16 22:09:46 +0000719 Kind);
John Wiegley429bb272011-04-08 18:41:53 +0000720 if (SrcExpr.isInvalid())
721 return TC_Failed;
Anders Carlsson3c31a392009-09-26 00:12:34 +0000722 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000723 return tcr;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000724
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000725 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
726 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
727 // conversions, subject to further restrictions.
728 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
729 // of qualification conversions impossible.
730 // In the CStyle case, the earlier attempt to const_cast should have taken
731 // care of reverse qualification conversions.
732
John Wiegley429bb272011-04-08 18:41:53 +0000733 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000734
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000735 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
Douglas Gregor1e856d92011-02-18 03:01:41 +0000736 // converted to an integral type. [...] A value of a scoped enumeration type
737 // can also be explicitly converted to a floating-point type [...].
738 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
739 if (Enum->getDecl()->isScoped()) {
740 if (DestType->isBooleanType()) {
741 Kind = CK_IntegralToBoolean;
742 return TC_Success;
743 } else if (DestType->isIntegralType(Self.Context)) {
744 Kind = CK_IntegralCast;
745 return TC_Success;
746 } else if (DestType->isRealFloatingType()) {
747 Kind = CK_IntegralToFloating;
748 return TC_Success;
749 }
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000750 }
751 }
Douglas Gregor1e856d92011-02-18 03:01:41 +0000752
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000753 // Reverse integral promotion/conversion. All such conversions are themselves
754 // again integral promotions or conversions and are thus already handled by
755 // p2 (TryDirectInitialization above).
756 // (Note: any data loss warnings should be suppressed.)
757 // The exception is the reverse of enum->integer, i.e. integer->enum (and
758 // enum->enum). See also C++ 5.2.9p7.
759 // The same goes for reverse floating point promotion/conversion and
760 // floating-integral conversions. Again, only floating->enum is relevant.
761 if (DestType->isEnumeralType()) {
762 if (SrcType->isComplexType() || SrcType->isVectorType()) {
763 // Fall through - these cannot be converted.
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000764 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
John McCall2de56d12010-08-25 11:45:40 +0000765 Kind = CK_IntegralCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000766 return TC_Success;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000767 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000768 }
769
770 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
771 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000772 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000773 Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000774 if (tcr != TC_NotApplicable)
775 return tcr;
776
777 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
778 // conversion. C++ 5.2.9p9 has additional information.
779 // DR54's access restrictions apply here also.
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000780 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssoncee22422010-04-24 19:22:20 +0000781 OpRange, msg, Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000782 if (tcr != TC_NotApplicable)
783 return tcr;
784
785 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
786 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
787 // just the usual constness stuff.
Ted Kremenek6217b802009-07-29 21:53:49 +0000788 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000789 QualType SrcPointee = SrcPointer->getPointeeType();
790 if (SrcPointee->isVoidType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000791 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000792 QualType DestPointee = DestPointer->getPointeeType();
793 if (DestPointee->isIncompleteOrObjectType()) {
794 // This is definitely the intended conversion, but it might fail due
795 // to a const violation.
796 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +0000797 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000798 return TC_Failed;
799 }
John McCall2de56d12010-08-25 11:45:40 +0000800 Kind = CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000801 return TC_Success;
802 }
803 }
Fariborz Jahanian2f6c5502010-05-10 23:46:53 +0000804 else if (DestType->isObjCObjectPointerType()) {
805 // allow both c-style cast and static_cast of objective-c pointers as
806 // they are pervasive.
John McCall2de56d12010-08-25 11:45:40 +0000807 Kind = CK_AnyPointerToObjCPointerCast;
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +0000808 return TC_Success;
809 }
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +0000810 else if (CStyle && DestType->isBlockPointerType()) {
811 // allow c-style cast of void * to block pointers.
John McCall2de56d12010-08-25 11:45:40 +0000812 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +0000813 return TC_Success;
814 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000815 }
816 }
Fariborz Jahanian65267b22010-05-12 18:16:59 +0000817 // Allow arbitray objective-c pointer conversion with static casts.
818 if (SrcType->isObjCObjectPointerType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +0000819 DestType->isObjCObjectPointerType()) {
820 Kind = CK_BitCast;
Fariborz Jahanian65267b22010-05-12 18:16:59 +0000821 return TC_Success;
John McCalldaa8e4e2010-11-15 09:13:47 +0000822 }
Fariborz Jahanian65267b22010-05-12 18:16:59 +0000823
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000824 // We tried everything. Everything! Nothing works! :-(
825 return TC_NotApplicable;
826}
827
828/// Tests whether a conversion according to N2844 is valid.
829TryCastResult
830TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000831 bool CStyle, CastKind &Kind, CXXCastPath &BasePath,
832 unsigned &msg) {
Douglas Gregordc843f22011-01-22 00:06:57 +0000833 // C++0x [expr.static.cast]p3:
834 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
835 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenek6217b802009-07-29 21:53:49 +0000836 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000837 if (!R)
838 return TC_NotApplicable;
839
Douglas Gregordc843f22011-01-22 00:06:57 +0000840 if (!SrcExpr->isGLValue())
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000841 return TC_NotApplicable;
842
843 // Because we try the reference downcast before this function, from now on
844 // this is the only cast possibility, so we issue an error if we fail now.
845 // FIXME: Should allow casting away constness if CStyle.
846 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +0000847 bool ObjCConversion;
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000848 QualType FromType = SrcExpr->getType();
849 QualType ToType = R->getPointeeType();
850 if (CStyle) {
851 FromType = FromType.getUnqualifiedType();
852 ToType = ToType.getUnqualifiedType();
853 }
854
Douglas Gregor393896f2009-11-05 13:06:35 +0000855 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
Douglas Gregor8ec14e62011-01-26 21:04:06 +0000856 ToType, FromType,
Douglas Gregor569c3162010-08-07 11:51:51 +0000857 DerivedToBase, ObjCConversion) <
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000858 Sema::Ref_Compatible_With_Added_Qualification) {
859 msg = diag::err_bad_lvalue_to_rvalue_cast;
860 return TC_Failed;
861 }
862
Douglas Gregor88b22a42011-01-25 16:13:26 +0000863 if (DerivedToBase) {
864 Kind = CK_DerivedToBase;
865 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
866 /*DetectVirtual=*/true);
867 if (!Self.IsDerivedFrom(SrcExpr->getType(), R->getPointeeType(), Paths))
868 return TC_NotApplicable;
869
870 Self.BuildBasePathArray(Paths, BasePath);
871 } else
872 Kind = CK_NoOp;
873
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000874 return TC_Success;
875}
876
877/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
878TryCastResult
879TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
880 bool CStyle, const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +0000881 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000882 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000883 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
884 // cast to type "reference to cv2 D", where D is a class derived from B,
885 // if a valid standard conversion from "pointer to D" to "pointer to B"
886 // exists, cv2 >= cv1, and B is not a virtual base class of D.
887 // In addition, DR54 clarifies that the base must be accessible in the
888 // current context. Although the wording of DR54 only applies to the pointer
889 // variant of this rule, the intent is clearly for it to apply to the this
890 // conversion as well.
891
Ted Kremenek6217b802009-07-29 21:53:49 +0000892 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000893 if (!DestReference) {
894 return TC_NotApplicable;
895 }
896 bool RValueRef = DestReference->isRValueReferenceType();
John McCall7eb0a9e2010-11-24 05:12:34 +0000897 if (!RValueRef && !SrcExpr->isLValue()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000898 // We know the left side is an lvalue reference, so we can suggest a reason.
899 msg = diag::err_bad_cxx_cast_rvalue;
900 return TC_NotApplicable;
901 }
902
903 QualType DestPointee = DestReference->getPointeeType();
904
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000905 return TryStaticDowncast(Self,
906 Self.Context.getCanonicalType(SrcExpr->getType()),
907 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000908 OpRange, SrcExpr->getType(), DestType, msg, Kind,
909 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000910}
911
912/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
913TryCastResult
914TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000915 bool CStyle, const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +0000916 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +0000917 CXXCastPath &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000918 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
919 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
920 // is a class derived from B, if a valid standard conversion from "pointer
921 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
922 // class of D.
923 // In addition, DR54 clarifies that the base must be accessible in the
924 // current context.
925
Ted Kremenek6217b802009-07-29 21:53:49 +0000926 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000927 if (!DestPointer) {
928 return TC_NotApplicable;
929 }
930
Ted Kremenek6217b802009-07-29 21:53:49 +0000931 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000932 if (!SrcPointer) {
933 msg = diag::err_bad_static_cast_pointer_nonpointer;
934 return TC_NotApplicable;
935 }
936
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000937 return TryStaticDowncast(Self,
938 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
939 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000940 CStyle, OpRange, SrcType, DestType, msg, Kind,
941 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000942}
943
944/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
945/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000946/// DestType is possible and allowed.
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000947TryCastResult
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000948TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000949 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000950 QualType OrigDestType, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +0000951 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000952 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000953 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, Self.PDiag(0)) ||
954 Self.RequireCompleteType(OpRange.getBegin(), DestType, Self.PDiag(0)))
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000955 return TC_NotApplicable;
956
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000957 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000958 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000959 return TC_NotApplicable;
960 }
961
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000962 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000963 /*DetectVirtual=*/true);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000964 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
965 return TC_NotApplicable;
966 }
967
968 // Target type does derive from source type. Now we're serious. If an error
969 // appears now, it's not ignored.
970 // This may not be entirely in line with the standard. Take for example:
971 // struct A {};
972 // struct B : virtual A {
973 // B(A&);
974 // };
Mike Stump1eb44332009-09-09 15:08:12 +0000975 //
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000976 // void f()
977 // {
978 // (void)static_cast<const B&>(*((A*)0));
979 // }
980 // As far as the standard is concerned, p5 does not apply (A is virtual), so
981 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
982 // However, both GCC and Comeau reject this example, and accepting it would
983 // mean more complex code if we're to preserve the nice error message.
984 // FIXME: Being 100% compliant here would be nice to have.
985
986 // Must preserve cv, as always, unless we're in C-style mode.
987 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +0000988 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000989 return TC_Failed;
990 }
991
992 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
993 // This code is analoguous to that in CheckDerivedToBaseConversion, except
994 // that it builds the paths in reverse order.
995 // To sum up: record all paths to the base and build a nice string from
996 // them. Use it to spice up the error message.
997 if (!Paths.isRecordingPaths()) {
998 Paths.clear();
999 Paths.setRecordingPaths(true);
1000 Self.IsDerivedFrom(DestType, SrcType, Paths);
1001 }
1002 std::string PathDisplayStr;
1003 std::set<unsigned> DisplayedPaths;
Douglas Gregora8f32e02009-10-06 17:59:45 +00001004 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001005 PI != PE; ++PI) {
1006 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
1007 // We haven't displayed a path to this particular base
1008 // class subobject yet.
1009 PathDisplayStr += "\n ";
Douglas Gregora8f32e02009-10-06 17:59:45 +00001010 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
1011 EE = PI->rend();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001012 EI != EE; ++EI)
1013 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001014 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001015 }
1016 }
1017
1018 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregorab15d0e2009-11-15 09:20:52 +00001019 << QualType(SrcType).getUnqualifiedType()
1020 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001021 << PathDisplayStr << OpRange;
1022 msg = 0;
1023 return TC_Failed;
1024 }
1025
1026 if (Paths.getDetectedVirtual() != 0) {
1027 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1028 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1029 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1030 msg = 0;
1031 return TC_Failed;
1032 }
1033
John McCall417d39f2011-02-14 23:21:33 +00001034 if (!CStyle) {
1035 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1036 SrcType, DestType,
1037 Paths.front(),
John McCall58e6f342010-03-16 05:22:47 +00001038 diag::err_downcast_from_inaccessible_base)) {
John McCall417d39f2011-02-14 23:21:33 +00001039 case Sema::AR_accessible:
1040 case Sema::AR_delayed: // be optimistic
1041 case Sema::AR_dependent: // be optimistic
1042 break;
1043
1044 case Sema::AR_inaccessible:
1045 msg = 0;
1046 return TC_Failed;
1047 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001048 }
1049
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001050 Self.BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00001051 Kind = CK_BaseToDerived;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001052 return TC_Success;
1053}
1054
1055/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1056/// C++ 5.2.9p9 is valid:
1057///
1058/// An rvalue of type "pointer to member of D of type cv1 T" can be
1059/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1060/// where B is a base class of D [...].
1061///
1062TryCastResult
John Wiegley429bb272011-04-08 18:41:53 +00001063TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001064 QualType DestType, bool CStyle,
1065 const SourceRange &OpRange,
John McCall2de56d12010-08-25 11:45:40 +00001066 unsigned &msg, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001067 CXXCastPath &BasePath) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001068 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001069 if (!DestMemPtr)
1070 return TC_NotApplicable;
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001071
1072 bool WasOverloadedFunction = false;
John McCall6bb80172010-03-30 21:47:33 +00001073 DeclAccessPair FoundOverload;
John Wiegley429bb272011-04-08 18:41:53 +00001074 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
Douglas Gregor1a8cf732010-04-14 23:11:21 +00001075 if (FunctionDecl *Fn
John Wiegley429bb272011-04-08 18:41:53 +00001076 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
Douglas Gregor1a8cf732010-04-14 23:11:21 +00001077 FoundOverload)) {
1078 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1079 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1080 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1081 WasOverloadedFunction = true;
1082 }
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001083 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00001084
Ted Kremenek6217b802009-07-29 21:53:49 +00001085 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001086 if (!SrcMemPtr) {
1087 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1088 return TC_NotApplicable;
1089 }
1090
1091 // T == T, modulo cv
Douglas Gregora4923eb2009-11-16 21:35:15 +00001092 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1093 DestMemPtr->getPointeeType()))
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001094 return TC_NotApplicable;
1095
1096 // B base of D
1097 QualType SrcClass(SrcMemPtr->getClass(), 0);
1098 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssoncee22422010-04-24 19:22:20 +00001099 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001100 /*DetectVirtual=*/true);
1101 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
1102 return TC_NotApplicable;
1103 }
1104
1105 // 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 +00001106 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001107 Paths.clear();
1108 Paths.setRecordingPaths(true);
1109 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
1110 assert(StillOkay);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00001111 (void)StillOkay;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001112 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1113 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1114 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1115 msg = 0;
1116 return TC_Failed;
1117 }
1118
1119 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1120 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1121 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1122 msg = 0;
1123 return TC_Failed;
1124 }
1125
John McCall417d39f2011-02-14 23:21:33 +00001126 if (!CStyle) {
1127 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1128 DestClass, SrcClass,
1129 Paths.front(),
1130 diag::err_upcast_to_inaccessible_base)) {
1131 case Sema::AR_accessible:
1132 case Sema::AR_delayed:
1133 case Sema::AR_dependent:
1134 // Optimistically assume that the delayed and dependent cases
1135 // will work out.
1136 break;
1137
1138 case Sema::AR_inaccessible:
1139 msg = 0;
1140 return TC_Failed;
1141 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001142 }
1143
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001144 if (WasOverloadedFunction) {
1145 // Resolve the address of the overloaded function again, this time
1146 // allowing complaints if something goes wrong.
John Wiegley429bb272011-04-08 18:41:53 +00001147 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001148 DestType,
John McCall6bb80172010-03-30 21:47:33 +00001149 true,
1150 FoundOverload);
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001151 if (!Fn) {
1152 msg = 0;
1153 return TC_Failed;
1154 }
1155
John McCall6bb80172010-03-30 21:47:33 +00001156 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
John Wiegley429bb272011-04-08 18:41:53 +00001157 if (!SrcExpr.isUsable()) {
Douglas Gregor4ce46c22010-03-07 23:24:59 +00001158 msg = 0;
1159 return TC_Failed;
1160 }
1161 }
1162
Anders Carlssoncee22422010-04-24 19:22:20 +00001163 Self.BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00001164 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001165 return TC_Success;
1166}
1167
1168/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1169/// is valid:
1170///
1171/// An expression e can be explicitly converted to a type T using a
1172/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1173TryCastResult
John Wiegley429bb272011-04-08 18:41:53 +00001174TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00001175 bool CStyle, const SourceRange &OpRange, unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +00001176 CastKind &Kind) {
Anders Carlssond851b372009-09-07 18:25:47 +00001177 if (DestType->isRecordType()) {
1178 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1179 diag::err_bad_dynamic_cast_incomplete)) {
1180 msg = 0;
1181 return TC_Failed;
1182 }
1183 }
Douglas Gregord6e44a32010-04-16 22:09:46 +00001184
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001185 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1186 InitializationKind InitKind
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001187 = InitializationKind::CreateCast(/*FIXME:*/OpRange, CStyle);
John Wiegley429bb272011-04-08 18:41:53 +00001188 Expr *SrcExprRaw = SrcExpr.get();
1189 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExprRaw, 1);
Douglas Gregor8e960432010-11-08 03:40:48 +00001190
1191 // At this point of CheckStaticCast, if the destination is a reference,
1192 // or the expression is an overload expression this has to work.
1193 // There is no other way that works.
1194 // On the other hand, if we're checking a C-style cast, we've still got
1195 // the reinterpret_cast way.
1196
Douglas Gregord6e44a32010-04-16 22:09:46 +00001197 if (InitSeq.getKind() == InitializationSequence::FailedSequence &&
Douglas Gregor8e960432010-11-08 03:40:48 +00001198 (CStyle || !DestType->isReferenceType()))
Anders Carlsson3c31a392009-09-26 00:12:34 +00001199 return TC_NotApplicable;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001200
John McCall60d7b3a2010-08-24 06:29:42 +00001201 ExprResult Result
John Wiegley429bb272011-04-08 18:41:53 +00001202 = InitSeq.Perform(Self, Entity, InitKind, MultiExprArg(Self, &SrcExprRaw, 1));
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001203 if (Result.isInvalid()) {
1204 msg = 0;
1205 return TC_Failed;
1206 }
1207
Douglas Gregord6e44a32010-04-16 22:09:46 +00001208 if (InitSeq.isConstructorInitialization())
John McCall2de56d12010-08-25 11:45:40 +00001209 Kind = CK_ConstructorConversion;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001210 else
John McCall2de56d12010-08-25 11:45:40 +00001211 Kind = CK_NoOp;
Douglas Gregord6e44a32010-04-16 22:09:46 +00001212
John Wiegley429bb272011-04-08 18:41:53 +00001213 SrcExpr = move(Result);
Douglas Gregorf0e43e52010-04-16 19:30:02 +00001214 return TC_Success;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001215}
1216
1217/// TryConstCast - See if a const_cast from source to destination is allowed,
1218/// and perform it if it is.
1219static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
1220 bool CStyle, unsigned &msg) {
1221 DestType = Self.Context.getCanonicalType(DestType);
1222 QualType SrcType = SrcExpr->getType();
Douglas Gregor575d2a32011-01-22 00:19:52 +00001223 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
1224 if (DestTypeTmp->isLValueReferenceType() && !SrcExpr->isLValue()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001225 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1226 // is C-style, static_cast might find a way, so we simply suggest a
1227 // message and tell the parent to keep searching.
1228 msg = diag::err_bad_cxx_cast_rvalue;
1229 return TC_NotApplicable;
1230 }
1231
1232 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
1233 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
1234 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1235 SrcType = Self.Context.getPointerType(SrcType);
1236 }
1237
1238 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1239 // the rules for const_cast are the same as those used for pointers.
1240
John McCalld425d2b2010-05-18 09:35:29 +00001241 if (!DestType->isPointerType() &&
1242 !DestType->isMemberPointerType() &&
1243 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001244 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1245 // was a reference type, we converted it to a pointer above.
1246 // The status of rvalue references isn't entirely clear, but it looks like
1247 // conversion to them is simply invalid.
1248 // C++ 5.2.11p3: For two pointer types [...]
1249 if (!CStyle)
1250 msg = diag::err_bad_const_cast_dest;
1251 return TC_NotApplicable;
1252 }
1253 if (DestType->isFunctionPointerType() ||
1254 DestType->isMemberFunctionPointerType()) {
1255 // Cannot cast direct function pointers.
1256 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1257 // T is the ultimate pointee of source and target type.
1258 if (!CStyle)
1259 msg = diag::err_bad_const_cast_dest;
1260 return TC_NotApplicable;
1261 }
1262 SrcType = Self.Context.getCanonicalType(SrcType);
1263
1264 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1265 // completely equal.
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001266 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1267 // in multi-level pointers may change, but the level count must be the same,
1268 // as must be the final pointee type.
1269 while (SrcType != DestType &&
Douglas Gregor5a57efd2010-06-09 03:53:18 +00001270 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001271 Qualifiers SrcQuals, DestQuals;
1272 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, SrcQuals);
1273 DestType = Self.Context.getUnqualifiedArrayType(DestType, DestQuals);
1274
1275 // const_cast is permitted to strip cvr-qualifiers, only. Make sure that
1276 // the other qualifiers (e.g., address spaces) are identical.
1277 SrcQuals.removeCVRQualifiers();
1278 DestQuals.removeCVRQualifiers();
1279 if (SrcQuals != DestQuals)
1280 return TC_NotApplicable;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001281 }
1282
1283 // Since we're dealing in canonical types, the remainder must be the same.
1284 if (SrcType != DestType)
1285 return TC_NotApplicable;
1286
1287 return TC_Success;
1288}
1289
Douglas Gregorfadb53b2011-03-12 01:48:56 +00001290
John Wiegley429bb272011-04-08 18:41:53 +00001291static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001292 QualType DestType, bool CStyle,
1293 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +00001294 unsigned &msg,
John McCall2de56d12010-08-25 11:45:40 +00001295 CastKind &Kind) {
Douglas Gregore39a3892010-07-13 23:17:26 +00001296 bool IsLValueCast = false;
1297
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001298 DestType = Self.Context.getCanonicalType(DestType);
John Wiegley429bb272011-04-08 18:41:53 +00001299 QualType SrcType = SrcExpr.get()->getType();
Douglas Gregor8e960432010-11-08 03:40:48 +00001300
1301 // Is the source an overloaded name? (i.e. &foo)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001302 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5) ...
1303 if (SrcType == Self.Context.OverloadTy) {
1304 // ... unless foo<int> resolves to an lvalue unambiguously
1305 ExprResult SingleFunctionExpr =
John Wiegley429bb272011-04-08 18:41:53 +00001306 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr.get(),
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001307 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
1308 );
1309 if (SingleFunctionExpr.isUsable()) {
John Wiegley429bb272011-04-08 18:41:53 +00001310 SrcExpr = move(SingleFunctionExpr);
1311 SrcType = SrcExpr.get()->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001312 }
1313 else
1314 return TC_NotApplicable;
1315 }
Douglas Gregor8e960432010-11-08 03:40:48 +00001316
Ted Kremenek6217b802009-07-29 21:53:49 +00001317 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001318 bool LValue = DestTypeTmp->isLValueReferenceType();
John Wiegley429bb272011-04-08 18:41:53 +00001319 if (LValue && !SrcExpr.get()->isLValue()) {
Douglas Gregor575d2a32011-01-22 00:19:52 +00001320 // Cannot cast non-lvalue to lvalue reference type. See the similar
1321 // comment in const_cast.
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001322 msg = diag::err_bad_cxx_cast_rvalue;
1323 return TC_NotApplicable;
1324 }
1325
1326 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1327 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1328 // built-in & and * operators.
Argyrios Kyrtzidisb464a5b2011-04-22 22:31:13 +00001329
Argyrios Kyrtzidisbb29d1b2011-04-22 23:57:57 +00001330 const char *inappropriate = 0;
1331 switch (SrcExpr.get()->getObjectKind()) {
Argyrios Kyrtzidise5e3d312011-04-23 01:10:24 +00001332 case OK_Ordinary:
1333 break;
Argyrios Kyrtzidisbb29d1b2011-04-22 23:57:57 +00001334 case OK_BitField: inappropriate = "bit-field"; break;
1335 case OK_VectorComponent: inappropriate = "vector element"; break;
1336 case OK_ObjCProperty: inappropriate = "property expression"; break;
1337 }
1338 if (inappropriate) {
1339 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
1340 << inappropriate << DestType
1341 << OpRange << SrcExpr.get()->getSourceRange();
1342 msg = 0; SrcExpr = ExprError();
Argyrios Kyrtzidisb464a5b2011-04-22 22:31:13 +00001343 return TC_NotApplicable;
1344 }
1345
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001346 // This code does this transformation for the checked types.
1347 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1348 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregor8e960432010-11-08 03:40:48 +00001349
Douglas Gregore39a3892010-07-13 23:17:26 +00001350 IsLValueCast = true;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001351 }
1352
1353 // Canonicalize source for comparison.
1354 SrcType = Self.Context.getCanonicalType(SrcType);
1355
Ted Kremenek6217b802009-07-29 21:53:49 +00001356 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1357 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001358 if (DestMemPtr && SrcMemPtr) {
1359 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1360 // can be explicitly converted to an rvalue of type "pointer to member
1361 // of Y of type T2" if T1 and T2 are both function types or both object
1362 // types.
1363 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1364 SrcMemPtr->getPointeeType()->isFunctionType())
1365 return TC_NotApplicable;
1366
1367 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1368 // constness.
1369 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1370 // we accept it.
1371 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001372 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001373 return TC_Failed;
1374 }
1375
Charles Davisf231df32010-08-16 05:30:44 +00001376 // Don't allow casting between member pointers of different sizes.
1377 if (Self.Context.getTypeSize(DestMemPtr) !=
1378 Self.Context.getTypeSize(SrcMemPtr)) {
1379 msg = diag::err_bad_cxx_cast_member_pointer_size;
1380 return TC_Failed;
1381 }
1382
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001383 // A valid member pointer cast.
John McCall2de56d12010-08-25 11:45:40 +00001384 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001385 return TC_Success;
1386 }
1387
1388 // See below for the enumeral issue.
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001389 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001390 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1391 // type large enough to hold it. A value of std::nullptr_t can be
1392 // converted to an integral type; the conversion has the same meaning
1393 // and validity as a conversion of (void*)0 to the integral type.
1394 if (Self.Context.getTypeSize(SrcType) >
1395 Self.Context.getTypeSize(DestType)) {
1396 msg = diag::err_bad_reinterpret_cast_small_int;
1397 return TC_Failed;
1398 }
John McCall2de56d12010-08-25 11:45:40 +00001399 Kind = CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001400 return TC_Success;
1401 }
1402
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001403 bool destIsVector = DestType->isVectorType();
1404 bool srcIsVector = SrcType->isVectorType();
1405 if (srcIsVector || destIsVector) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001406 // FIXME: Should this also apply to floating point types?
1407 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1408 bool destIsScalar = DestType->isIntegralType(Self.Context);
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001409
1410 // Check if this is a cast between a vector and something else.
1411 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1412 !(srcIsVector && destIsVector))
1413 return TC_NotApplicable;
1414
1415 // If both types have the same size, we can successfully cast.
Douglas Gregorf2a55392009-12-22 22:47:22 +00001416 if (Self.Context.getTypeSize(SrcType)
1417 == Self.Context.getTypeSize(DestType)) {
John McCall2de56d12010-08-25 11:45:40 +00001418 Kind = CK_BitCast;
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001419 return TC_Success;
Douglas Gregorf2a55392009-12-22 22:47:22 +00001420 }
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001421
1422 if (destIsScalar)
1423 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1424 else if (srcIsScalar)
1425 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1426 else
1427 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1428
1429 return TC_Failed;
1430 }
1431
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001432 bool destIsPtr = DestType->isAnyPointerType() ||
1433 DestType->isBlockPointerType();
1434 bool srcIsPtr = SrcType->isAnyPointerType() ||
1435 SrcType->isBlockPointerType();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001436 if (!destIsPtr && !srcIsPtr) {
1437 // Except for std::nullptr_t->integer and lvalue->reference, which are
1438 // handled above, at least one of the two arguments must be a pointer.
1439 return TC_NotApplicable;
1440 }
1441
1442 if (SrcType == DestType) {
1443 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1444 // restrictions, a cast to the same type is allowed. The intent is not
1445 // entirely clear here, since all other paragraphs explicitly forbid casts
1446 // to the same type. However, the behavior of compilers is pretty consistent
1447 // on this point: allow same-type conversion if the involved types are
1448 // pointers, disallow otherwise.
John McCall2de56d12010-08-25 11:45:40 +00001449 Kind = CK_NoOp;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001450 return TC_Success;
1451 }
1452
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001453 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001454 assert(srcIsPtr && "One type must be a pointer");
1455 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1456 // type large enough to hold it.
1457 if (Self.Context.getTypeSize(SrcType) >
1458 Self.Context.getTypeSize(DestType)) {
1459 msg = diag::err_bad_reinterpret_cast_small_int;
1460 return TC_Failed;
1461 }
John McCall2de56d12010-08-25 11:45:40 +00001462 Kind = CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001463 return TC_Success;
1464 }
1465
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001466 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001467 assert(destIsPtr && "One type must be a pointer");
1468 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1469 // converted to a pointer.
John McCall404cd162010-11-13 01:35:44 +00001470 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1471 // necessarily converted to a null pointer value.]
John McCall2de56d12010-08-25 11:45:40 +00001472 Kind = CK_IntegralToPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001473 return TC_Success;
1474 }
1475
1476 if (!destIsPtr || !srcIsPtr) {
1477 // With the valid non-pointer conversions out of the way, we can be even
1478 // more stringent.
1479 return TC_NotApplicable;
1480 }
1481
1482 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1483 // The C-style cast operator can.
1484 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
Douglas Gregord4c5f842011-04-15 17:59:54 +00001485 msg = diag::err_bad_cxx_cast_qualifiers_away;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001486 return TC_Failed;
1487 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001488
1489 // Cannot convert between block pointers and Objective-C object pointers.
1490 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1491 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1492 return TC_NotApplicable;
1493
1494 // Any pointer can be cast to an Objective-C pointer type with a C-style
1495 // cast.
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001496 if (CStyle && DestType->isObjCObjectPointerType()) {
John McCall2de56d12010-08-25 11:45:40 +00001497 Kind = CK_AnyPointerToObjCPointerCast;
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001498 return TC_Success;
1499 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001500
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001501 // Not casting away constness, so the only remaining check is for compatible
1502 // pointer categories.
John McCall2de56d12010-08-25 11:45:40 +00001503 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001504
1505 if (SrcType->isFunctionPointerType()) {
1506 if (DestType->isFunctionPointerType()) {
1507 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1508 // a pointer to a function of a different type.
1509 return TC_Success;
1510 }
1511
1512 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1513 // an object type or vice versa is conditionally-supported.
1514 // Compilers support it in C++03 too, though, because it's necessary for
1515 // casting the return value of dlsym() and GetProcAddress().
1516 // FIXME: Conditionally-supported behavior should be configurable in the
1517 // TargetInfo or similar.
1518 if (!Self.getLangOptions().CPlusPlus0x)
1519 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1520 return TC_Success;
1521 }
1522
1523 if (DestType->isFunctionPointerType()) {
1524 // See above.
1525 if (!Self.getLangOptions().CPlusPlus0x)
1526 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1527 return TC_Success;
1528 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001529
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001530 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1531 // a pointer to an object of different type.
1532 // Void pointers are not specified, but supported by every compiler out there.
1533 // So we finish by allowing everything that remains - it's got to be two
1534 // object pointers.
1535 return TC_Success;
John McCall79ab2c82011-02-14 18:34:10 +00001536}
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001537
John Wiegley429bb272011-04-08 18:41:53 +00001538ExprResult
John McCallf89e55a2010-11-18 06:31:45 +00001539Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, ExprValueKind &VK,
John Wiegley429bb272011-04-08 18:41:53 +00001540 Expr *CastExpr, CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001541 CXXCastPath &BasePath,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001542 bool FunctionalStyle) {
John Wiegley429bb272011-04-08 18:41:53 +00001543 if (CastExpr->isBoundMemberFunction(Context)) {
1544 Diag(CastExpr->getLocStart(), diag::err_invalid_use_of_bound_member_func)
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +00001545 << CastExpr->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00001546 return ExprError();
1547 }
Argyrios Kyrtzidis11ab7902010-11-01 18:49:26 +00001548
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001549 // This test is outside everything else because it's the only case where
1550 // a non-lvalue-reference target type does not lead to decay.
1551 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001552 if (CastTy->isVoidType()) {
John McCallfb8721c2011-04-10 19:13:55 +00001553 Kind = CK_ToVoid;
1554
John Wiegley429bb272011-04-08 18:41:53 +00001555 ExprResult CastExprRes = IgnoredValueConversions(CastExpr);
1556 if (CastExprRes.isInvalid())
1557 return ExprError();
1558 CastExpr = CastExprRes.take();
John McCallfb8721c2011-04-10 19:13:55 +00001559
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001560 if (CastExpr->getType() == Context.OverloadTy) {
1561 ExprResult SingleFunctionExpr =
Douglas Gregorfadb53b2011-03-12 01:48:56 +00001562 ResolveAndFixSingleFunctionTemplateSpecialization(
1563 CastExpr, /* Decay Function to ptr */ false,
1564 /* Complain */ true, R, CastTy,
1565 diag::err_bad_cstyle_cast_overload);
John McCallfb8721c2011-04-10 19:13:55 +00001566 if (SingleFunctionExpr.isInvalid())
1567 return ExprError();
1568 CastExpr = SingleFunctionExpr.take();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001569 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001570
John McCallfb8721c2011-04-10 19:13:55 +00001571 assert(!CastExpr->getType()->isPlaceholderType());
1572
John Wiegley429bb272011-04-08 18:41:53 +00001573 return Owned(CastExpr);
Anton Yartsevd06fea82011-03-27 09:32:40 +00001574 }
1575
John McCall9b4b9d62010-11-30 02:05:44 +00001576 // Make sure we determine the value kind before we bail out for
1577 // dependent types.
1578 VK = Expr::getValueKindForType(CastTy);
1579
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001580 // If the type is dependent, we won't do any other semantic analysis now.
John McCalldaa8e4e2010-11-15 09:13:47 +00001581 if (CastTy->isDependentType() || CastExpr->isTypeDependent()) {
1582 Kind = CK_Dependent;
John Wiegley429bb272011-04-08 18:41:53 +00001583 return Owned(CastExpr);
John McCalldaa8e4e2010-11-15 09:13:47 +00001584 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001585
John Wiegley429bb272011-04-08 18:41:53 +00001586 if (VK == VK_RValue && !CastTy->isRecordType()) {
1587 ExprResult CastExprRes = DefaultFunctionArrayLvalueConversion(CastExpr);
1588 if (CastExprRes.isInvalid())
1589 return ExprError();
1590 CastExpr = CastExprRes.take();
1591 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001592
John McCallfb8721c2011-04-10 19:13:55 +00001593 // AltiVec vector initialization with a single literal.
1594 if (const VectorType *vecTy = CastTy->getAs<VectorType>())
1595 if (vecTy->getVectorKind() == VectorType::AltiVecVector
1596 && (CastExpr->getType()->isIntegerType()
1597 || CastExpr->getType()->isFloatingType())) {
1598 Kind = CK_VectorSplat;
1599 return Owned(CastExpr);
1600 }
1601
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001602 // C++ [expr.cast]p5: The conversions performed by
1603 // - a const_cast,
1604 // - a static_cast,
1605 // - a static_cast followed by a const_cast,
1606 // - a reinterpret_cast, or
1607 // - a reinterpret_cast followed by a const_cast,
1608 // can be performed using the cast notation of explicit type conversion.
1609 // [...] If a conversion can be interpreted in more than one of the ways
1610 // listed above, the interpretation that appears first in the list is used,
1611 // even if a cast resulting from that interpretation is ill-formed.
1612 // In plain language, this means trying a const_cast ...
1613 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001614 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1615 msg);
Anders Carlssonda921fd2009-10-19 18:14:28 +00001616 if (tcr == TC_Success)
John McCall2de56d12010-08-25 11:45:40 +00001617 Kind = CK_NoOp;
Anders Carlssonda921fd2009-10-19 18:14:28 +00001618
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001619 if (tcr == TC_NotApplicable) {
1620 // ... or if that is not possible, a static_cast, ignoring const, ...
John Wiegley429bb272011-04-08 18:41:53 +00001621 ExprResult CastExprRes = Owned(CastExpr);
Richard Trieu32ac00d2011-04-16 01:09:30 +00001622 tcr = TryStaticCast(*this, CastExprRes, CastTy, /*CStyle*/true, R, msg,
1623 Kind, BasePath);
John Wiegley429bb272011-04-08 18:41:53 +00001624 if (CastExprRes.isInvalid())
1625 return ExprError();
1626 CastExpr = CastExprRes.take();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001627 if (tcr == TC_NotApplicable) {
1628 // ... and finally a reinterpret_cast, ignoring const.
John Wiegley429bb272011-04-08 18:41:53 +00001629 CastExprRes = Owned(CastExpr);
Richard Trieu32ac00d2011-04-16 01:09:30 +00001630 tcr = TryReinterpretCast(*this, CastExprRes, CastTy, /*CStyle*/true, R,
1631 msg, Kind);
John Wiegley429bb272011-04-08 18:41:53 +00001632 if (CastExprRes.isInvalid())
1633 return ExprError();
1634 CastExpr = CastExprRes.take();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001635 }
1636 }
1637
Nick Lewycky43328e92010-11-09 00:19:31 +00001638 if (tcr != TC_Success && msg != 0) {
1639 if (CastExpr->getType() == Context.OverloadTy) {
Douglas Gregor8e960432010-11-08 03:40:48 +00001640 DeclAccessPair Found;
John Wiegley429bb272011-04-08 18:41:53 +00001641 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(CastExpr,
Douglas Gregor8e960432010-11-08 03:40:48 +00001642 CastTy,
1643 /* Complain */ true,
1644 Found);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001645
Richard Trieu32ac00d2011-04-16 01:09:30 +00001646 assert(!Fn && "cast failed but able to resolve overload expression!!");
Nick Lewycky43328e92010-11-09 00:19:31 +00001647 (void)Fn;
John McCall79ab2c82011-02-14 18:34:10 +00001648
Nick Lewycky43328e92010-11-09 00:19:31 +00001649 } else {
John McCall79ab2c82011-02-14 18:34:10 +00001650 diagnoseBadCast(*this, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
1651 R, CastExpr, CastTy);
Douglas Gregor8e960432010-11-08 03:40:48 +00001652 }
1653 }
John McCalle2b76882010-11-16 05:46:29 +00001654 else if (Kind == CK_BitCast)
John McCallb7f4ffe2010-08-12 21:44:57 +00001655 CheckCastAlign(CastExpr, CastTy, R);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001656
John Wiegley429bb272011-04-08 18:41:53 +00001657 if (tcr != TC_Success)
1658 return ExprError();
1659
1660 return Owned(CastExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001661}