blob: 25ad7b6a87c04c78659afe9b97b26662d1ff67e5 [file] [log] [blame]
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +00001//===--- SemaNamedCast.cpp - Semantic Analysis for Named Casts ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ named casts.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000016#include "clang/AST/ExprCXX.h"
17#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlssond624e162009-08-26 23:45:07 +000019#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000020#include "llvm/ADT/SmallVector.h"
Sebastian Redl015085f2008-11-07 23:29:29 +000021#include <set>
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000022using namespace clang;
23
Douglas Gregore81f58e2010-11-08 03:40:48 +000024
25static void NoteAllOverloadCandidates(Expr* const Expr, Sema& sema);
26
Sebastian Redl9f831db2009-07-25 15:41:38 +000027enum TryCastResult {
28 TC_NotApplicable, ///< The cast method is not applicable.
29 TC_Success, ///< The cast method is appropriate and successful.
30 TC_Failed ///< The cast method is appropriate, but failed. A
31 ///< diagnostic has been emitted.
32};
33
34enum CastType {
35 CT_Const, ///< const_cast
36 CT_Static, ///< static_cast
37 CT_Reinterpret, ///< reinterpret_cast
38 CT_Dynamic, ///< dynamic_cast
39 CT_CStyle, ///< (Type)expr
40 CT_Functional ///< Type(expr)
Sebastian Redl842ef522008-11-08 13:00:26 +000041};
42
Douglas Gregore81f58e2010-11-08 03:40:48 +000043
44
45
Sebastian Redl842ef522008-11-08 13:00:26 +000046static void CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
47 const SourceRange &OpRange,
48 const SourceRange &DestRange);
49static void CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
50 const SourceRange &OpRange,
Anders Carlsson7cd39e02009-09-15 04:48:33 +000051 const SourceRange &DestRange,
John McCalle3027922010-08-25 11:45:40 +000052 CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +000053static void CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlssonf10e4142009-08-07 22:21:05 +000054 const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +000055 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +000056 CXXCastPath &BasePath);
Sebastian Redl842ef522008-11-08 13:00:26 +000057static void CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
58 const SourceRange &OpRange,
Mike Stump11289f42009-09-09 15:08:12 +000059 const SourceRange &DestRange,
John McCalle3027922010-08-25 11:45:40 +000060 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +000061 CXXCastPath &BasePath);
Sebastian Redl842ef522008-11-08 13:00:26 +000062
63static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
Sebastian Redl9f831db2009-07-25 15:41:38 +000064
65// The Try functions attempt a specific way of casting. If they succeed, they
66// return TC_Success. If their way of casting is not appropriate for the given
67// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
68// to emit if no other way succeeds. If their way of casting is appropriate but
69// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
70// they emit a specialized diagnostic.
71// All diagnostics returned by these functions must expect the same three
72// arguments:
73// %0: Cast Type (a value from the CastType enumeration)
74// %1: Source Type
75// %2: Destination Type
76static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
77 QualType DestType, unsigned &msg);
78static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
Anders Carlsson7d3360f2010-04-24 19:36:51 +000079 QualType DestType, bool CStyle,
80 const SourceRange &OpRange,
81 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +000082 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +000083 CXXCastPath &BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +000084static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
85 QualType DestType, bool CStyle,
86 const SourceRange &OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +000087 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +000088 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +000089 CXXCastPath &BasePath);
Douglas Gregor8f3952c2009-11-15 09:20:52 +000090static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
91 CanQualType DestType, bool CStyle,
Sebastian Redl9f831db2009-07-25 15:41:38 +000092 const SourceRange &OpRange,
93 QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +000094 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +000095 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +000096 CXXCastPath &BasePath);
Douglas Gregorc934bc82010-03-07 23:24:59 +000097static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr,
Anders Carlssonb78feca2010-04-24 19:22:20 +000098 QualType SrcType,
99 QualType DestType,bool CStyle,
100 const SourceRange &OpRange,
101 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000102 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000103 CXXCastPath &BasePath);
Anders Carlssonb78feca2010-04-24 19:22:20 +0000104
Sebastian Redl7c353682009-11-14 21:15:49 +0000105static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000106 QualType DestType, bool CStyle,
107 const SourceRange &OpRange,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000108 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000109 CastKind &Kind);
Sebastian Redl7c353682009-11-14 21:15:49 +0000110static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000111 QualType DestType, bool CStyle,
112 const SourceRange &OpRange,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000113 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000114 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000115 CXXCastPath &BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000116static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
117 bool CStyle, unsigned &msg);
118static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
119 QualType DestType, bool CStyle,
120 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000121 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000122 CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +0000123
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000124/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
John McCalldadc5752010-08-24 06:29:42 +0000125ExprResult
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000126Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John McCallba7bf592010-08-24 05:47:05 +0000127 SourceLocation LAngleBracketLoc, ParsedType Ty,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000128 SourceLocation RAngleBracketLoc,
John McCallfaf5fb42010-08-26 23:41:50 +0000129 SourceLocation LParenLoc, Expr *E,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000130 SourceLocation RParenLoc) {
John McCalld377e042010-01-15 19:13:16 +0000131
John McCall97513962010-01-15 18:39:57 +0000132 TypeSourceInfo *DestTInfo;
133 QualType DestType = GetTypeFromParser(Ty, &DestTInfo);
134 if (!DestTInfo)
135 DestTInfo = Context.getTrivialTypeSourceInfo(DestType, SourceLocation());
John McCalld377e042010-01-15 19:13:16 +0000136
137 return BuildCXXNamedCast(OpLoc, Kind, DestTInfo, move(E),
138 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
139 SourceRange(LParenLoc, RParenLoc));
140}
141
John McCalldadc5752010-08-24 06:29:42 +0000142ExprResult
John McCalld377e042010-01-15 19:13:16 +0000143Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
John McCallfaf5fb42010-08-26 23:41:50 +0000144 TypeSourceInfo *DestTInfo, Expr *Ex,
John McCalld377e042010-01-15 19:13:16 +0000145 SourceRange AngleBrackets, SourceRange Parens) {
John McCalld377e042010-01-15 19:13:16 +0000146 QualType DestType = DestTInfo->getType();
147
148 SourceRange OpRange(OpLoc, Parens.getEnd());
149 SourceRange DestRange = AngleBrackets;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000150
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000151 // If the type is dependent, we won't do the semantic analysis now.
152 // FIXME: should we check this in a more fine-grained manner?
153 bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
154
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +0000155 if (Ex->isBoundMemberFunction(Context))
156 Diag(Ex->getLocStart(), diag::err_invalid_use_of_bound_member_func)
157 << Ex->getSourceRange();
158
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000159 switch (Kind) {
160 default: assert(0 && "Unknown C++ cast!");
161
162 case tok::kw_const_cast:
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000163 if (!TypeDependent)
164 CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
John McCallcf142162010-08-07 06:22:56 +0000165 return Owned(CXXConstCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +0000166 DestType.getNonLValueExprType(Context),
John McCallcf142162010-08-07 06:22:56 +0000167 Ex, DestTInfo, OpLoc));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000168
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000169 case tok::kw_dynamic_cast: {
John McCalle3027922010-08-25 11:45:40 +0000170 CastKind Kind = CK_Unknown;
John McCallcf142162010-08-07 06:22:56 +0000171 CXXCastPath BasePath;
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000172 if (!TypeDependent)
Anders Carlssona70cff62010-04-24 19:06:50 +0000173 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange, Kind, BasePath);
John McCallcf142162010-08-07 06:22:56 +0000174 return Owned(CXXDynamicCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +0000175 DestType.getNonLValueExprType(Context),
John McCallcf142162010-08-07 06:22:56 +0000176 Kind, Ex, &BasePath, DestTInfo,
177 OpLoc));
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000178 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000179 case tok::kw_reinterpret_cast: {
John McCalle3027922010-08-25 11:45:40 +0000180 CastKind Kind = CK_Unknown;
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000181 if (!TypeDependent)
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000182 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange, Kind);
John McCallcf142162010-08-07 06:22:56 +0000183 return Owned(CXXReinterpretCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +0000184 DestType.getNonLValueExprType(Context),
John McCallcf142162010-08-07 06:22:56 +0000185 Kind, Ex, 0,
Anders Carlssona70cff62010-04-24 19:06:50 +0000186 DestTInfo, OpLoc));
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000187 }
Anders Carlssonf10e4142009-08-07 22:21:05 +0000188 case tok::kw_static_cast: {
John McCalle3027922010-08-25 11:45:40 +0000189 CastKind Kind = CK_Unknown;
John McCallcf142162010-08-07 06:22:56 +0000190 CXXCastPath BasePath;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000191 if (!TypeDependent)
Anders Carlssona70cff62010-04-24 19:06:50 +0000192 CheckStaticCast(*this, Ex, DestType, OpRange, Kind, BasePath);
Anders Carlssone9766d52009-09-09 21:33:21 +0000193
John McCallcf142162010-08-07 06:22:56 +0000194 return Owned(CXXStaticCastExpr::Create(Context,
Douglas Gregora8a089b2010-07-13 18:40:04 +0000195 DestType.getNonLValueExprType(Context),
John McCallcf142162010-08-07 06:22:56 +0000196 Kind, Ex, &BasePath,
197 DestTInfo, OpLoc));
Anders Carlssonf10e4142009-08-07 22:21:05 +0000198 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000199 }
200
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000201 return ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000202}
203
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000204/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
205/// this removes one level of indirection from both types, provided that they're
206/// the same kind of pointer (plain or to-member). Unlike the Sema function,
207/// this one doesn't care if the two pointers-to-member don't point into the
208/// same class. This is because CastsAwayConstness doesn't care.
Dan Gohman28ade552010-07-26 21:25:24 +0000209static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000210 const PointerType *T1PtrType = T1->getAs<PointerType>(),
211 *T2PtrType = T2->getAs<PointerType>();
212 if (T1PtrType && T2PtrType) {
213 T1 = T1PtrType->getPointeeType();
214 T2 = T2PtrType->getPointeeType();
215 return true;
216 }
Fariborz Jahanian8c3f06d2010-02-03 20:32:31 +0000217 const ObjCObjectPointerType *T1ObjCPtrType =
218 T1->getAs<ObjCObjectPointerType>(),
219 *T2ObjCPtrType =
220 T2->getAs<ObjCObjectPointerType>();
221 if (T1ObjCPtrType) {
222 if (T2ObjCPtrType) {
223 T1 = T1ObjCPtrType->getPointeeType();
224 T2 = T2ObjCPtrType->getPointeeType();
225 return true;
226 }
227 else if (T2PtrType) {
228 T1 = T1ObjCPtrType->getPointeeType();
229 T2 = T2PtrType->getPointeeType();
230 return true;
231 }
232 }
233 else if (T2ObjCPtrType) {
234 if (T1PtrType) {
235 T2 = T2ObjCPtrType->getPointeeType();
236 T1 = T1PtrType->getPointeeType();
237 return true;
238 }
239 }
240
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000241 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
242 *T2MPType = T2->getAs<MemberPointerType>();
243 if (T1MPType && T2MPType) {
244 T1 = T1MPType->getPointeeType();
245 T2 = T2MPType->getPointeeType();
246 return true;
247 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000248
249 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
250 *T2BPType = T2->getAs<BlockPointerType>();
251 if (T1BPType && T2BPType) {
252 T1 = T1BPType->getPointeeType();
253 T2 = T2BPType->getPointeeType();
254 return true;
255 }
256
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000257 return false;
258}
259
Sebastian Redla5a77a62009-01-27 23:18:31 +0000260/// CastsAwayConstness - Check if the pointer conversion from SrcType to
261/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
262/// the cast checkers. Both arguments must denote pointer (possibly to member)
263/// types.
Sebastian Redl802f14c2009-10-22 15:07:22 +0000264static bool
Mike Stump11289f42009-09-09 15:08:12 +0000265CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
Sebastian Redla5a77a62009-01-27 23:18:31 +0000266 // Casting away constness is defined in C++ 5.2.11p8 with reference to
267 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
268 // the rules are non-trivial. So first we construct Tcv *...cv* as described
269 // in C++ 5.2.11p8.
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000270 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
271 SrcType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000272 "Source type is not pointer or pointer to member.");
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000273 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
274 DestType->isBlockPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000275 "Destination type is not pointer or pointer to member.");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000276
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000277 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
278 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
John McCall8ccfcb52009-09-24 19:53:00 +0000279 llvm::SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000280
281 // Find the qualifications.
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000282 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
Anders Carlsson76f513f2010-06-04 22:47:55 +0000283 Qualifiers SrcQuals;
284 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
285 cv1.push_back(SrcQuals);
286
287 Qualifiers DestQuals;
288 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
289 cv2.push_back(DestQuals);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000290 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +0000291 if (cv1.empty())
292 return false;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000293
294 // Construct void pointers with those qualifiers (in reverse order of
295 // unwrapping, of course).
Sebastian Redl842ef522008-11-08 13:00:26 +0000296 QualType SrcConstruct = Self.Context.VoidTy;
297 QualType DestConstruct = Self.Context.VoidTy;
John McCall8ccfcb52009-09-24 19:53:00 +0000298 ASTContext &Context = Self.Context;
299 for (llvm::SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
300 i2 = cv2.rbegin();
Mike Stump11289f42009-09-09 15:08:12 +0000301 i1 != cv1.rend(); ++i1, ++i2) {
John McCall8ccfcb52009-09-24 19:53:00 +0000302 SrcConstruct
303 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
304 DestConstruct
305 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000306 }
307
308 // Test if they're compatible.
309 return SrcConstruct != DestConstruct &&
Sebastian Redl842ef522008-11-08 13:00:26 +0000310 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000311}
312
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000313/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
314/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
315/// checked downcasts in class hierarchies.
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000316static void
Sebastian Redl842ef522008-11-08 13:00:26 +0000317CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
318 const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +0000319 const SourceRange &DestRange, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000320 CXXCastPath &BasePath) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000321 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl842ef522008-11-08 13:00:26 +0000322 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000323
324 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
325 // or "pointer to cv void".
326
327 QualType DestPointee;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000328 const PointerType *DestPointer = DestType->getAs<PointerType>();
329 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000330 if (DestPointer) {
331 DestPointee = DestPointer->getPointeeType();
332 } else if (DestReference) {
333 DestPointee = DestReference->getPointeeType();
334 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000335 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000336 << OrigDestType << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000337 return;
338 }
339
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000340 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000341 if (DestPointee->isVoidType()) {
342 assert(DestPointer && "Reference to void is not possible");
343 } else if (DestRecord) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000344 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor89336232010-03-29 23:34:08 +0000345 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssond624e162009-08-26 23:45:07 +0000346 << DestRange))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000347 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000348 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000349 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000350 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000351 return;
352 }
353
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000354 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
355 // complete class type, [...]. If T is an lvalue reference type, v shall be
356 // an lvalue of a complete class type, [...]. If T is an rvalue reference
357 // type, v shall be an expression having a complete effective class type,
358 // [...]
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000359
Sebastian Redl842ef522008-11-08 13:00:26 +0000360 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000361 QualType SrcPointee;
362 if (DestPointer) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000363 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000364 SrcPointee = SrcPointer->getPointeeType();
365 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000366 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000367 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000368 return;
369 }
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000370 } else if (DestReference->isLValueReferenceType()) {
Sebastian Redl842ef522008-11-08 13:00:26 +0000371 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000372 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000373 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000374 }
375 SrcPointee = SrcType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000376 } else {
377 SrcPointee = SrcType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000378 }
379
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000380 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000381 if (SrcRecord) {
Douglas Gregored0cfbd2009-03-09 16:13:40 +0000382 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor89336232010-03-29 23:34:08 +0000383 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssond624e162009-08-26 23:45:07 +0000384 << SrcExpr->getSourceRange()))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000385 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000386 } else {
Chris Lattner29e812b2008-11-20 06:06:08 +0000387 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000388 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000389 return;
390 }
391
392 assert((DestPointer || DestReference) &&
393 "Bad destination non-ptr/ref slipped through.");
394 assert((DestRecord || DestPointee->isVoidType()) &&
395 "Bad destination pointee slipped through.");
396 assert(SrcRecord && "Bad source pointee slipped through.");
397
398 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
399 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000400 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000401 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000402 return;
403 }
404
405 // C++ 5.2.7p3: If the type of v is the same as the required result type,
406 // [except for cv].
407 if (DestRecord == SrcRecord) {
John McCalle3027922010-08-25 11:45:40 +0000408 Kind = CK_NoOp;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000409 return;
410 }
411
412 // C++ 5.2.7p5
413 // Upcasts are resolved statically.
Sebastian Redl842ef522008-11-08 13:00:26 +0000414 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000415 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
416 OpRange.getBegin(), OpRange,
417 &BasePath))
418 return;
419
John McCalle3027922010-08-25 11:45:40 +0000420 Kind = CK_DerivedToBase;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000421
422 // If we are casting to or through a virtual base class, we need a
423 // vtable.
424 if (Self.BasePathInvolvesVirtualBase(BasePath))
425 Self.MarkVTableUsed(OpRange.getBegin(),
426 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000427 return;
428 }
429
430 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000431 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000432 assert(SrcDecl && "Definition missing");
433 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner29e812b2008-11-20 06:06:08 +0000434 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000435 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000436 }
Douglas Gregor88d292c2010-05-13 16:44:06 +0000437 Self.MarkVTableUsed(OpRange.getBegin(),
438 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000439
440 // Done. Everything else is run-time checks.
John McCalle3027922010-08-25 11:45:40 +0000441 Kind = CK_Dynamic;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000442}
Sebastian Redl9f831db2009-07-25 15:41:38 +0000443
444/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
445/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
446/// like this:
447/// const char *str = "literal";
448/// legacy_function(const_cast\<char*\>(str));
449void
450CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +0000451 const SourceRange &OpRange, const SourceRange &DestRange) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000452 if (!DestType->isLValueReferenceType())
Douglas Gregorb92a1562010-02-03 00:27:59 +0000453 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000454
455 unsigned msg = diag::err_bad_cxx_cast_generic;
456 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
457 && msg != 0)
458 Self.Diag(OpRange.getBegin(), msg) << CT_Const
459 << SrcExpr->getType() << DestType << OpRange;
460}
461
462/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
463/// valid.
464/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
465/// like this:
466/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
467void
468CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000469 const SourceRange &OpRange, const SourceRange &DestRange,
John McCalle3027922010-08-25 11:45:40 +0000470 CastKind &Kind) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000471 if (!DestType->isLValueReferenceType())
Douglas Gregorb92a1562010-02-03 00:27:59 +0000472 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000473
474 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000475 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
476 msg, Kind)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000477 != TC_Success && msg != 0)
Douglas Gregore81f58e2010-11-08 03:40:48 +0000478 {
479 if (SrcExpr->getType() == Self.Context.OverloadTy)
480 {
481 //FIXME: &f<int>; is overloaded and resolvable
482 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
483 << OverloadExpr::find(SrcExpr).Expression->getName()
484 << DestType << OpRange;
485 NoteAllOverloadCandidates(SrcExpr, Self);
486
487 }
488 else
489 Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
Sebastian Redl9f831db2009-07-25 15:41:38 +0000490 << SrcExpr->getType() << DestType << OpRange;
Douglas Gregore81f58e2010-11-08 03:40:48 +0000491 }
492
Sebastian Redl9f831db2009-07-25 15:41:38 +0000493}
494
495
496/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
497/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
498/// implicit conversions explicit and getting rid of data loss warnings.
499void
500CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
John McCalle3027922010-08-25 11:45:40 +0000501 const SourceRange &OpRange, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000502 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000503 // This test is outside everything else because it's the only case where
504 // a non-lvalue-reference target type does not lead to decay.
505 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman03bf60a2009-11-16 05:44:20 +0000506 if (DestType->isVoidType()) {
John McCalle3027922010-08-25 11:45:40 +0000507 Kind = CK_ToVoid;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000508 return;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000509 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000510
Douglas Gregorad8b2222009-11-06 01:14:41 +0000511 if (!DestType->isLValueReferenceType() && !DestType->isRecordType())
Douglas Gregorb92a1562010-02-03 00:27:59 +0000512 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000513
514 unsigned msg = diag::err_bad_cxx_cast_generic;
Sebastian Redl7c353682009-11-14 21:15:49 +0000515 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg,
Anders Carlssona70cff62010-04-24 19:06:50 +0000516 Kind, BasePath) != TC_Success && msg != 0)
Douglas Gregore81f58e2010-11-08 03:40:48 +0000517 {
518 if ( SrcExpr->getType() == Self.Context.OverloadTy )
519 {
520 OverloadExpr* oe = OverloadExpr::find(SrcExpr).Expression;
521 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
522 << oe->getName() << DestType << OpRange << oe->getQualifierRange();
523 NoteAllOverloadCandidates(SrcExpr, Self);
524 }
525 else
526 Self.Diag(OpRange.getBegin(), msg) << CT_Static
Sebastian Redl9f831db2009-07-25 15:41:38 +0000527 << SrcExpr->getType() << DestType << OpRange;
Douglas Gregore81f58e2010-11-08 03:40:48 +0000528 }
John McCalle3027922010-08-25 11:45:40 +0000529 else if (Kind == CK_Unknown || Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +0000530 Self.CheckCastAlign(SrcExpr, DestType, OpRange);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000531}
532
533/// TryStaticCast - Check if a static cast can be performed, and do so if
534/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
535/// and casting away constness.
Sebastian Redl7c353682009-11-14 21:15:49 +0000536static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000537 QualType DestType, bool CStyle,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000538 const SourceRange &OpRange, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000539 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000540 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000541 // The order the tests is not entirely arbitrary. There is one conversion
542 // that can be handled in two different ways. Given:
543 // struct A {};
544 // struct B : public A {
545 // B(); B(const A&);
546 // };
547 // const A &a = B();
548 // the cast static_cast<const B&>(a) could be seen as either a static
549 // reference downcast, or an explicit invocation of the user-defined
550 // conversion using B's conversion constructor.
551 // DR 427 specifies that the downcast is to be applied here.
552
553 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
554 // Done outside this function.
555
556 TryCastResult tcr;
557
558 // C++ 5.2.9p5, reference downcast.
559 // See the function for details.
560 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redl7c353682009-11-14 21:15:49 +0000561 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle, OpRange,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000562 msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000563 if (tcr != TC_NotApplicable)
564 return tcr;
565
566 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
567 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
568 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
Sebastian Redl7c353682009-11-14 21:15:49 +0000569 if (tcr != TC_NotApplicable) {
John McCalle3027922010-08-25 11:45:40 +0000570 Kind = CK_NoOp;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000571 return tcr;
Sebastian Redl7c353682009-11-14 21:15:49 +0000572 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000573
574 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
575 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000576 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
Douglas Gregorb33eed02010-04-16 22:09:46 +0000577 Kind);
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000578 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000579 return tcr;
Anders Carlssone9766d52009-09-09 21:33:21 +0000580
Sebastian Redl9f831db2009-07-25 15:41:38 +0000581 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
582 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
583 // conversions, subject to further restrictions.
584 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
585 // of qualification conversions impossible.
586 // In the CStyle case, the earlier attempt to const_cast should have taken
587 // care of reverse qualification conversions.
588
589 QualType OrigSrcType = SrcExpr->getType();
590
591 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
592
Douglas Gregor0bf31402010-10-08 23:50:27 +0000593 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
594 // converted to an integral type.
595 if (Self.getLangOptions().CPlusPlus0x && SrcType->isEnumeralType()) {
596 if (DestType->isIntegralType(Self.Context)) {
597 Kind = CK_IntegralCast;
598 return TC_Success;
599 }
600 }
601
Sebastian Redl9f831db2009-07-25 15:41:38 +0000602 // Reverse integral promotion/conversion. All such conversions are themselves
603 // again integral promotions or conversions and are thus already handled by
604 // p2 (TryDirectInitialization above).
605 // (Note: any data loss warnings should be suppressed.)
606 // The exception is the reverse of enum->integer, i.e. integer->enum (and
607 // enum->enum). See also C++ 5.2.9p7.
608 // The same goes for reverse floating point promotion/conversion and
609 // floating-integral conversions. Again, only floating->enum is relevant.
610 if (DestType->isEnumeralType()) {
611 if (SrcType->isComplexType() || SrcType->isVectorType()) {
612 // Fall through - these cannot be converted.
Eli Friedman03bf60a2009-11-16 05:44:20 +0000613 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
John McCalle3027922010-08-25 11:45:40 +0000614 Kind = CK_IntegralCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000615 return TC_Success;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000616 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000617 }
618
619 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
620 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000621 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000622 Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000623 if (tcr != TC_NotApplicable)
624 return tcr;
625
626 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
627 // conversion. C++ 5.2.9p9 has additional information.
628 // DR54's access restrictions apply here also.
Douglas Gregorc934bc82010-03-07 23:24:59 +0000629 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssonb78feca2010-04-24 19:22:20 +0000630 OpRange, msg, Kind, BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000631 if (tcr != TC_NotApplicable)
632 return tcr;
633
634 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
635 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
636 // just the usual constness stuff.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000637 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000638 QualType SrcPointee = SrcPointer->getPointeeType();
639 if (SrcPointee->isVoidType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000640 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000641 QualType DestPointee = DestPointer->getPointeeType();
642 if (DestPointee->isIncompleteOrObjectType()) {
643 // This is definitely the intended conversion, but it might fail due
644 // to a const violation.
645 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
646 msg = diag::err_bad_cxx_cast_const_away;
647 return TC_Failed;
648 }
John McCalle3027922010-08-25 11:45:40 +0000649 Kind = CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000650 return TC_Success;
651 }
652 }
Fariborz Jahanianeee16692010-05-10 23:46:53 +0000653 else if (DestType->isObjCObjectPointerType()) {
654 // allow both c-style cast and static_cast of objective-c pointers as
655 // they are pervasive.
John McCalle3027922010-08-25 11:45:40 +0000656 Kind = CK_AnyPointerToObjCPointerCast;
Fariborz Jahanian859c4152009-12-08 23:09:15 +0000657 return TC_Success;
658 }
Fariborz Jahanianffe912c2009-12-11 22:40:48 +0000659 else if (CStyle && DestType->isBlockPointerType()) {
660 // allow c-style cast of void * to block pointers.
John McCalle3027922010-08-25 11:45:40 +0000661 Kind = CK_AnyPointerToBlockPointerCast;
Fariborz Jahanianffe912c2009-12-11 22:40:48 +0000662 return TC_Success;
663 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000664 }
665 }
Fariborz Jahanianb0901b72010-05-12 18:16:59 +0000666 // Allow arbitray objective-c pointer conversion with static casts.
667 if (SrcType->isObjCObjectPointerType() &&
668 DestType->isObjCObjectPointerType())
669 return TC_Success;
670
Sebastian Redl9f831db2009-07-25 15:41:38 +0000671 // We tried everything. Everything! Nothing works! :-(
672 return TC_NotApplicable;
673}
674
675/// Tests whether a conversion according to N2844 is valid.
676TryCastResult
677TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +0000678 unsigned &msg) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000679 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
680 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000681 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000682 if (!R)
683 return TC_NotApplicable;
684
685 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
686 return TC_NotApplicable;
687
688 // Because we try the reference downcast before this function, from now on
689 // this is the only cast possibility, so we issue an error if we fail now.
690 // FIXME: Should allow casting away constness if CStyle.
691 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +0000692 bool ObjCConversion;
Douglas Gregor3ec1bf22009-11-05 13:06:35 +0000693 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
694 SrcExpr->getType(), R->getPointeeType(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +0000695 DerivedToBase, ObjCConversion) <
Sebastian Redl9f831db2009-07-25 15:41:38 +0000696 Sema::Ref_Compatible_With_Added_Qualification) {
697 msg = diag::err_bad_lvalue_to_rvalue_cast;
698 return TC_Failed;
699 }
700
Douglas Gregor031296e2010-03-25 00:20:38 +0000701 // FIXME: We should probably have an AST node for lvalue-to-rvalue
702 // conversions.
Sebastian Redl9f831db2009-07-25 15:41:38 +0000703 return TC_Success;
704}
705
706/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
707TryCastResult
708TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
709 bool CStyle, const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +0000710 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000711 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000712 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
713 // cast to type "reference to cv2 D", where D is a class derived from B,
714 // if a valid standard conversion from "pointer to D" to "pointer to B"
715 // exists, cv2 >= cv1, and B is not a virtual base class of D.
716 // In addition, DR54 clarifies that the base must be accessible in the
717 // current context. Although the wording of DR54 only applies to the pointer
718 // variant of this rule, the intent is clearly for it to apply to the this
719 // conversion as well.
720
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000721 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000722 if (!DestReference) {
723 return TC_NotApplicable;
724 }
725 bool RValueRef = DestReference->isRValueReferenceType();
726 if (!RValueRef && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
727 // We know the left side is an lvalue reference, so we can suggest a reason.
728 msg = diag::err_bad_cxx_cast_rvalue;
729 return TC_NotApplicable;
730 }
731
732 QualType DestPointee = DestReference->getPointeeType();
733
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000734 return TryStaticDowncast(Self,
735 Self.Context.getCanonicalType(SrcExpr->getType()),
736 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000737 OpRange, SrcExpr->getType(), DestType, msg, Kind,
738 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000739}
740
741/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
742TryCastResult
743TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +0000744 bool CStyle, const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +0000745 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000746 CXXCastPath &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000747 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
748 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
749 // is a class derived from B, if a valid standard conversion from "pointer
750 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
751 // class of D.
752 // In addition, DR54 clarifies that the base must be accessible in the
753 // current context.
754
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000755 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000756 if (!DestPointer) {
757 return TC_NotApplicable;
758 }
759
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000760 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000761 if (!SrcPointer) {
762 msg = diag::err_bad_static_cast_pointer_nonpointer;
763 return TC_NotApplicable;
764 }
765
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000766 return TryStaticDowncast(Self,
767 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
768 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000769 CStyle, OpRange, SrcType, DestType, msg, Kind,
770 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000771}
772
773/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
774/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000775/// DestType is possible and allowed.
Sebastian Redl9f831db2009-07-25 15:41:38 +0000776TryCastResult
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000777TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000778 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000779 QualType OrigDestType, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000780 CastKind &Kind, CXXCastPath &BasePath) {
Sebastian Redl802f14c2009-10-22 15:07:22 +0000781 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregor89336232010-03-29 23:34:08 +0000782 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, Self.PDiag(0)) ||
783 Self.RequireCompleteType(OpRange.getBegin(), DestType, Self.PDiag(0)))
Sebastian Redl802f14c2009-10-22 15:07:22 +0000784 return TC_NotApplicable;
785
Sebastian Redl9f831db2009-07-25 15:41:38 +0000786 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000787 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000788 return TC_NotApplicable;
789 }
790
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000791 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000792 /*DetectVirtual=*/true);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000793 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
794 return TC_NotApplicable;
795 }
796
797 // Target type does derive from source type. Now we're serious. If an error
798 // appears now, it's not ignored.
799 // This may not be entirely in line with the standard. Take for example:
800 // struct A {};
801 // struct B : virtual A {
802 // B(A&);
803 // };
Mike Stump11289f42009-09-09 15:08:12 +0000804 //
Sebastian Redl9f831db2009-07-25 15:41:38 +0000805 // void f()
806 // {
807 // (void)static_cast<const B&>(*((A*)0));
808 // }
809 // As far as the standard is concerned, p5 does not apply (A is virtual), so
810 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
811 // However, both GCC and Comeau reject this example, and accepting it would
812 // mean more complex code if we're to preserve the nice error message.
813 // FIXME: Being 100% compliant here would be nice to have.
814
815 // Must preserve cv, as always, unless we're in C-style mode.
816 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
817 msg = diag::err_bad_cxx_cast_const_away;
818 return TC_Failed;
819 }
820
821 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
822 // This code is analoguous to that in CheckDerivedToBaseConversion, except
823 // that it builds the paths in reverse order.
824 // To sum up: record all paths to the base and build a nice string from
825 // them. Use it to spice up the error message.
826 if (!Paths.isRecordingPaths()) {
827 Paths.clear();
828 Paths.setRecordingPaths(true);
829 Self.IsDerivedFrom(DestType, SrcType, Paths);
830 }
831 std::string PathDisplayStr;
832 std::set<unsigned> DisplayedPaths;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000833 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000834 PI != PE; ++PI) {
835 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
836 // We haven't displayed a path to this particular base
837 // class subobject yet.
838 PathDisplayStr += "\n ";
Douglas Gregor36d1b142009-10-06 17:59:45 +0000839 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
840 EE = PI->rend();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000841 EI != EE; ++EI)
842 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000843 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000844 }
845 }
846
847 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000848 << QualType(SrcType).getUnqualifiedType()
849 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9f831db2009-07-25 15:41:38 +0000850 << PathDisplayStr << OpRange;
851 msg = 0;
852 return TC_Failed;
853 }
854
855 if (Paths.getDetectedVirtual() != 0) {
856 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
857 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
858 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
859 msg = 0;
860 return TC_Failed;
861 }
862
John McCall5b0829a2010-02-10 09:31:12 +0000863 if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
John McCall5b0829a2010-02-10 09:31:12 +0000864 SrcType, DestType,
John McCall1064d7e2010-03-16 05:22:47 +0000865 Paths.front(),
866 diag::err_downcast_from_inaccessible_base)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000867 msg = 0;
868 return TC_Failed;
869 }
870
Anders Carlsson7d3360f2010-04-24 19:36:51 +0000871 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +0000872 Kind = CK_BaseToDerived;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000873 return TC_Success;
874}
875
876/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
877/// C++ 5.2.9p9 is valid:
878///
879/// An rvalue of type "pointer to member of D of type cv1 T" can be
880/// converted to an rvalue of type "pointer to member of B of type cv2 T",
881/// where B is a base class of D [...].
882///
883TryCastResult
Douglas Gregorc934bc82010-03-07 23:24:59 +0000884TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr, QualType SrcType,
885 QualType DestType, bool CStyle,
886 const SourceRange &OpRange,
John McCalle3027922010-08-25 11:45:40 +0000887 unsigned &msg, CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +0000888 CXXCastPath &BasePath) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000889 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000890 if (!DestMemPtr)
891 return TC_NotApplicable;
Douglas Gregorc934bc82010-03-07 23:24:59 +0000892
893 bool WasOverloadedFunction = false;
John McCall16df1e52010-03-30 21:47:33 +0000894 DeclAccessPair FoundOverload;
Douglas Gregor064fdb22010-04-14 23:11:21 +0000895 if (SrcExpr->getType() == Self.Context.OverloadTy) {
896 if (FunctionDecl *Fn
897 = Self.ResolveAddressOfOverloadedFunction(SrcExpr, DestType, false,
898 FoundOverload)) {
899 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
900 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
901 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
902 WasOverloadedFunction = true;
903 }
Douglas Gregorc934bc82010-03-07 23:24:59 +0000904 }
Douglas Gregor064fdb22010-04-14 23:11:21 +0000905
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000906 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000907 if (!SrcMemPtr) {
908 msg = diag::err_bad_static_cast_member_pointer_nonmp;
909 return TC_NotApplicable;
910 }
911
912 // T == T, modulo cv
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000913 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
914 DestMemPtr->getPointeeType()))
Sebastian Redl9f831db2009-07-25 15:41:38 +0000915 return TC_NotApplicable;
916
917 // B base of D
918 QualType SrcClass(SrcMemPtr->getClass(), 0);
919 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssonb78feca2010-04-24 19:22:20 +0000920 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000921 /*DetectVirtual=*/true);
922 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
923 return TC_NotApplicable;
924 }
925
926 // B is a base of D. But is it an allowed base? If not, it's a hard error.
Douglas Gregor27ac4292010-05-21 20:29:55 +0000927 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000928 Paths.clear();
929 Paths.setRecordingPaths(true);
930 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
931 assert(StillOkay);
932 StillOkay = StillOkay;
933 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
934 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
935 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
936 msg = 0;
937 return TC_Failed;
938 }
939
940 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
941 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
942 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
943 msg = 0;
944 return TC_Failed;
945 }
946
John McCall5b0829a2010-02-10 09:31:12 +0000947 if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
Eli Friedmand4c75cd2010-07-23 19:25:41 +0000948 DestClass, SrcClass,
John McCall1064d7e2010-03-16 05:22:47 +0000949 Paths.front(),
950 diag::err_upcast_to_inaccessible_base)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000951 msg = 0;
952 return TC_Failed;
953 }
954
Douglas Gregorc934bc82010-03-07 23:24:59 +0000955 if (WasOverloadedFunction) {
956 // Resolve the address of the overloaded function again, this time
957 // allowing complaints if something goes wrong.
958 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr,
959 DestType,
John McCall16df1e52010-03-30 21:47:33 +0000960 true,
961 FoundOverload);
Douglas Gregorc934bc82010-03-07 23:24:59 +0000962 if (!Fn) {
963 msg = 0;
964 return TC_Failed;
965 }
966
John McCall16df1e52010-03-30 21:47:33 +0000967 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
Douglas Gregorc934bc82010-03-07 23:24:59 +0000968 if (!SrcExpr) {
969 msg = 0;
970 return TC_Failed;
971 }
972 }
973
Anders Carlssonb78feca2010-04-24 19:22:20 +0000974 Self.BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +0000975 Kind = CK_DerivedToBaseMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000976 return TC_Success;
977}
978
979/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
980/// is valid:
981///
982/// An expression e can be explicitly converted to a type T using a
983/// @c static_cast if the declaration "T t(e);" is well-formed [...].
984TryCastResult
Sebastian Redl7c353682009-11-14 21:15:49 +0000985TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000986 bool CStyle, const SourceRange &OpRange, unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +0000987 CastKind &Kind) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +0000988 if (DestType->isRecordType()) {
989 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
990 diag::err_bad_dynamic_cast_incomplete)) {
991 msg = 0;
992 return TC_Failed;
993 }
994 }
Douglas Gregorb33eed02010-04-16 22:09:46 +0000995
Douglas Gregor5c8ffab2010-04-16 19:30:02 +0000996 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
997 InitializationKind InitKind
Douglas Gregorb33eed02010-04-16 22:09:46 +0000998 = InitializationKind::CreateCast(/*FIXME:*/OpRange,
999 CStyle);
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001000 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExpr, 1);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001001
1002 // At this point of CheckStaticCast, if the destination is a reference,
1003 // or the expression is an overload expression this has to work.
1004 // There is no other way that works.
1005 // On the other hand, if we're checking a C-style cast, we've still got
1006 // the reinterpret_cast way.
1007
Douglas Gregorb33eed02010-04-16 22:09:46 +00001008 if (InitSeq.getKind() == InitializationSequence::FailedSequence &&
Douglas Gregore81f58e2010-11-08 03:40:48 +00001009 (CStyle || !DestType->isReferenceType()))
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001010 return TC_NotApplicable;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001011
John McCalldadc5752010-08-24 06:29:42 +00001012 ExprResult Result
John McCallfaf5fb42010-08-26 23:41:50 +00001013 = InitSeq.Perform(Self, Entity, InitKind, MultiExprArg(Self, &SrcExpr, 1));
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001014 if (Result.isInvalid()) {
1015 msg = 0;
1016 return TC_Failed;
1017 }
1018
Douglas Gregorb33eed02010-04-16 22:09:46 +00001019 if (InitSeq.isConstructorInitialization())
John McCalle3027922010-08-25 11:45:40 +00001020 Kind = CK_ConstructorConversion;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001021 else
John McCalle3027922010-08-25 11:45:40 +00001022 Kind = CK_NoOp;
Douglas Gregorb33eed02010-04-16 22:09:46 +00001023
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00001024 SrcExpr = Result.takeAs<Expr>();
1025 return TC_Success;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001026}
1027
1028/// TryConstCast - See if a const_cast from source to destination is allowed,
1029/// and perform it if it is.
1030static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
1031 bool CStyle, unsigned &msg) {
1032 DestType = Self.Context.getCanonicalType(DestType);
1033 QualType SrcType = SrcExpr->getType();
1034 if (const LValueReferenceType *DestTypeTmp =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001035 DestType->getAs<LValueReferenceType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001036 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
1037 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1038 // is C-style, static_cast might find a way, so we simply suggest a
1039 // message and tell the parent to keep searching.
1040 msg = diag::err_bad_cxx_cast_rvalue;
1041 return TC_NotApplicable;
1042 }
1043
1044 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
1045 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
1046 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1047 SrcType = Self.Context.getPointerType(SrcType);
1048 }
1049
1050 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1051 // the rules for const_cast are the same as those used for pointers.
1052
John McCall0e704f72010-05-18 09:35:29 +00001053 if (!DestType->isPointerType() &&
1054 !DestType->isMemberPointerType() &&
1055 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001056 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1057 // was a reference type, we converted it to a pointer above.
1058 // The status of rvalue references isn't entirely clear, but it looks like
1059 // conversion to them is simply invalid.
1060 // C++ 5.2.11p3: For two pointer types [...]
1061 if (!CStyle)
1062 msg = diag::err_bad_const_cast_dest;
1063 return TC_NotApplicable;
1064 }
1065 if (DestType->isFunctionPointerType() ||
1066 DestType->isMemberFunctionPointerType()) {
1067 // Cannot cast direct function pointers.
1068 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1069 // T is the ultimate pointee of source and target type.
1070 if (!CStyle)
1071 msg = diag::err_bad_const_cast_dest;
1072 return TC_NotApplicable;
1073 }
1074 SrcType = Self.Context.getCanonicalType(SrcType);
1075
1076 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1077 // completely equal.
1078 // FIXME: const_cast should probably not be able to convert between pointers
1079 // to different address spaces.
1080 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1081 // in multi-level pointers may change, but the level count must be the same,
1082 // as must be the final pointee type.
1083 while (SrcType != DestType &&
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001084 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Chandler Carruth585fb1e2009-12-29 08:05:19 +00001085 Qualifiers Quals;
1086 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, Quals);
1087 DestType = Self.Context.getUnqualifiedArrayType(DestType, Quals);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001088 }
1089
1090 // Since we're dealing in canonical types, the remainder must be the same.
1091 if (SrcType != DestType)
1092 return TC_NotApplicable;
1093
1094 return TC_Success;
1095}
1096
Douglas Gregore81f58e2010-11-08 03:40:48 +00001097
1098static void NoteAllOverloadCandidates(Expr* const Expr, Sema& sema)
1099{
1100
1101 assert(Expr->getType() == sema.Context.OverloadTy);
1102
1103 OverloadExpr::FindResult Ovl = OverloadExpr::find(Expr);
1104 OverloadExpr *const OvlExpr = Ovl.Expression;
1105
1106 for (UnresolvedSetIterator it = OvlExpr->decls_begin(),
1107 end = OvlExpr->decls_end(); it != end; ++it) {
1108 if ( FunctionTemplateDecl *ftd =
1109 dyn_cast<FunctionTemplateDecl>((*it)->getUnderlyingDecl()) )
1110 {
1111 sema.NoteOverloadCandidate(ftd->getTemplatedDecl());
1112 }
1113 else if ( FunctionDecl *f =
1114 dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl()) )
1115 {
1116 sema.NoteOverloadCandidate(f);
1117 }
1118 }
1119}
1120
1121
Sebastian Redl9f831db2009-07-25 15:41:38 +00001122static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
1123 QualType DestType, bool CStyle,
1124 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001125 unsigned &msg,
John McCalle3027922010-08-25 11:45:40 +00001126 CastKind &Kind) {
Douglas Gregor51954272010-07-13 23:17:26 +00001127 bool IsLValueCast = false;
1128
Sebastian Redl9f831db2009-07-25 15:41:38 +00001129 DestType = Self.Context.getCanonicalType(DestType);
1130 QualType SrcType = SrcExpr->getType();
Douglas Gregore81f58e2010-11-08 03:40:48 +00001131
1132 // Is the source an overloaded name? (i.e. &foo)
1133 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5)
1134 if (SrcType == Self.Context.OverloadTy )
1135 return TC_NotApplicable;
1136
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001137 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001138 bool LValue = DestTypeTmp->isLValueReferenceType();
1139 if (LValue && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
1140 // Cannot cast non-lvalue to reference type. See the similar comment in
1141 // const_cast.
1142 msg = diag::err_bad_cxx_cast_rvalue;
1143 return TC_NotApplicable;
1144 }
1145
1146 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1147 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1148 // built-in & and * operators.
1149 // This code does this transformation for the checked types.
1150 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1151 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregore81f58e2010-11-08 03:40:48 +00001152
Douglas Gregor51954272010-07-13 23:17:26 +00001153 IsLValueCast = true;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001154 }
1155
1156 // Canonicalize source for comparison.
1157 SrcType = Self.Context.getCanonicalType(SrcType);
1158
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001159 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1160 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001161 if (DestMemPtr && SrcMemPtr) {
1162 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1163 // can be explicitly converted to an rvalue of type "pointer to member
1164 // of Y of type T2" if T1 and T2 are both function types or both object
1165 // types.
1166 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1167 SrcMemPtr->getPointeeType()->isFunctionType())
1168 return TC_NotApplicable;
1169
1170 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1171 // constness.
1172 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1173 // we accept it.
1174 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1175 msg = diag::err_bad_cxx_cast_const_away;
1176 return TC_Failed;
1177 }
1178
Charles Davisebab1ed2010-08-16 05:30:44 +00001179 // Don't allow casting between member pointers of different sizes.
1180 if (Self.Context.getTypeSize(DestMemPtr) !=
1181 Self.Context.getTypeSize(SrcMemPtr)) {
1182 msg = diag::err_bad_cxx_cast_member_pointer_size;
1183 return TC_Failed;
1184 }
1185
Sebastian Redl9f831db2009-07-25 15:41:38 +00001186 // A valid member pointer cast.
John McCalle3027922010-08-25 11:45:40 +00001187 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001188 return TC_Success;
1189 }
1190
1191 // See below for the enumeral issue.
Douglas Gregor6972a622010-06-16 00:35:25 +00001192 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001193 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1194 // type large enough to hold it. A value of std::nullptr_t can be
1195 // converted to an integral type; the conversion has the same meaning
1196 // and validity as a conversion of (void*)0 to the integral type.
1197 if (Self.Context.getTypeSize(SrcType) >
1198 Self.Context.getTypeSize(DestType)) {
1199 msg = diag::err_bad_reinterpret_cast_small_int;
1200 return TC_Failed;
1201 }
John McCalle3027922010-08-25 11:45:40 +00001202 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001203 return TC_Success;
1204 }
1205
Anders Carlsson570af5d2009-09-16 19:19:43 +00001206 bool destIsVector = DestType->isVectorType();
1207 bool srcIsVector = SrcType->isVectorType();
1208 if (srcIsVector || destIsVector) {
Douglas Gregor6972a622010-06-16 00:35:25 +00001209 // FIXME: Should this also apply to floating point types?
1210 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1211 bool destIsScalar = DestType->isIntegralType(Self.Context);
Anders Carlsson570af5d2009-09-16 19:19:43 +00001212
1213 // Check if this is a cast between a vector and something else.
1214 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1215 !(srcIsVector && destIsVector))
1216 return TC_NotApplicable;
1217
1218 // If both types have the same size, we can successfully cast.
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001219 if (Self.Context.getTypeSize(SrcType)
1220 == Self.Context.getTypeSize(DestType)) {
John McCalle3027922010-08-25 11:45:40 +00001221 Kind = CK_BitCast;
Anders Carlsson570af5d2009-09-16 19:19:43 +00001222 return TC_Success;
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001223 }
Anders Carlsson570af5d2009-09-16 19:19:43 +00001224
1225 if (destIsScalar)
1226 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1227 else if (srcIsScalar)
1228 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1229 else
1230 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1231
1232 return TC_Failed;
1233 }
1234
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001235 bool destIsPtr = DestType->isAnyPointerType() ||
1236 DestType->isBlockPointerType();
1237 bool srcIsPtr = SrcType->isAnyPointerType() ||
1238 SrcType->isBlockPointerType();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001239 if (!destIsPtr && !srcIsPtr) {
1240 // Except for std::nullptr_t->integer and lvalue->reference, which are
1241 // handled above, at least one of the two arguments must be a pointer.
1242 return TC_NotApplicable;
1243 }
1244
1245 if (SrcType == DestType) {
1246 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1247 // restrictions, a cast to the same type is allowed. The intent is not
1248 // entirely clear here, since all other paragraphs explicitly forbid casts
1249 // to the same type. However, the behavior of compilers is pretty consistent
1250 // on this point: allow same-type conversion if the involved types are
1251 // pointers, disallow otherwise.
John McCalle3027922010-08-25 11:45:40 +00001252 Kind = CK_NoOp;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001253 return TC_Success;
1254 }
1255
Douglas Gregor6972a622010-06-16 00:35:25 +00001256 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001257 assert(srcIsPtr && "One type must be a pointer");
1258 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1259 // type large enough to hold it.
1260 if (Self.Context.getTypeSize(SrcType) >
1261 Self.Context.getTypeSize(DestType)) {
1262 msg = diag::err_bad_reinterpret_cast_small_int;
1263 return TC_Failed;
1264 }
John McCalle3027922010-08-25 11:45:40 +00001265 Kind = CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001266 return TC_Success;
1267 }
1268
Douglas Gregorb90df602010-06-16 00:17:44 +00001269 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001270 assert(destIsPtr && "One type must be a pointer");
1271 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1272 // converted to a pointer.
John McCalle3027922010-08-25 11:45:40 +00001273 Kind = CK_IntegralToPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001274 return TC_Success;
1275 }
1276
1277 if (!destIsPtr || !srcIsPtr) {
1278 // With the valid non-pointer conversions out of the way, we can be even
1279 // more stringent.
1280 return TC_NotApplicable;
1281 }
1282
1283 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1284 // The C-style cast operator can.
1285 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1286 msg = diag::err_bad_cxx_cast_const_away;
1287 return TC_Failed;
1288 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001289
1290 // Cannot convert between block pointers and Objective-C object pointers.
1291 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1292 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1293 return TC_NotApplicable;
1294
1295 // Any pointer can be cast to an Objective-C pointer type with a C-style
1296 // cast.
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001297 if (CStyle && DestType->isObjCObjectPointerType()) {
John McCalle3027922010-08-25 11:45:40 +00001298 Kind = CK_AnyPointerToObjCPointerCast;
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001299 return TC_Success;
1300 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001301
Sebastian Redl9f831db2009-07-25 15:41:38 +00001302 // Not casting away constness, so the only remaining check is for compatible
1303 // pointer categories.
John McCalle3027922010-08-25 11:45:40 +00001304 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001305
1306 if (SrcType->isFunctionPointerType()) {
1307 if (DestType->isFunctionPointerType()) {
1308 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1309 // a pointer to a function of a different type.
1310 return TC_Success;
1311 }
1312
1313 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1314 // an object type or vice versa is conditionally-supported.
1315 // Compilers support it in C++03 too, though, because it's necessary for
1316 // casting the return value of dlsym() and GetProcAddress().
1317 // FIXME: Conditionally-supported behavior should be configurable in the
1318 // TargetInfo or similar.
1319 if (!Self.getLangOptions().CPlusPlus0x)
1320 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1321 return TC_Success;
1322 }
1323
1324 if (DestType->isFunctionPointerType()) {
1325 // See above.
1326 if (!Self.getLangOptions().CPlusPlus0x)
1327 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1328 return TC_Success;
1329 }
Douglas Gregoreaff2cb2010-07-08 20:27:32 +00001330
Sebastian Redl9f831db2009-07-25 15:41:38 +00001331 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1332 // a pointer to an object of different type.
1333 // Void pointers are not specified, but supported by every compiler out there.
1334 // So we finish by allowing everything that remains - it's got to be two
1335 // object pointers.
1336 return TC_Success;
1337}
1338
Anders Carlssona70cff62010-04-24 19:06:50 +00001339bool
1340Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr,
John McCalle3027922010-08-25 11:45:40 +00001341 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001342 CXXCastPath &BasePath,
Anders Carlssona70cff62010-04-24 19:06:50 +00001343 bool FunctionalStyle) {
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +00001344 if (CastExpr->isBoundMemberFunction(Context))
1345 return Diag(CastExpr->getLocStart(),
1346 diag::err_invalid_use_of_bound_member_func)
1347 << CastExpr->getSourceRange();
1348
Sebastian Redl9f831db2009-07-25 15:41:38 +00001349 // This test is outside everything else because it's the only case where
1350 // a non-lvalue-reference target type does not lead to decay.
1351 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Anders Carlsson9500ad12009-10-18 20:31:03 +00001352 if (CastTy->isVoidType()) {
John McCalle3027922010-08-25 11:45:40 +00001353 Kind = CK_ToVoid;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001354 return false;
Anders Carlsson9500ad12009-10-18 20:31:03 +00001355 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001356
1357 // If the type is dependent, we won't do any other semantic analysis now.
1358 if (CastTy->isDependentType() || CastExpr->isTypeDependent())
1359 return false;
1360
Douglas Gregorad8b2222009-11-06 01:14:41 +00001361 if (!CastTy->isLValueReferenceType() && !CastTy->isRecordType())
Douglas Gregorb92a1562010-02-03 00:27:59 +00001362 DefaultFunctionArrayLvalueConversion(CastExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001363
1364 // C++ [expr.cast]p5: The conversions performed by
1365 // - a const_cast,
1366 // - a static_cast,
1367 // - a static_cast followed by a const_cast,
1368 // - a reinterpret_cast, or
1369 // - a reinterpret_cast followed by a const_cast,
1370 // can be performed using the cast notation of explicit type conversion.
1371 // [...] If a conversion can be interpreted in more than one of the ways
1372 // listed above, the interpretation that appears first in the list is used,
1373 // even if a cast resulting from that interpretation is ill-formed.
1374 // In plain language, this means trying a const_cast ...
1375 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssonf1ae6d42009-09-01 20:52:42 +00001376 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1377 msg);
Anders Carlsson027732b2009-10-19 18:14:28 +00001378 if (tcr == TC_Success)
John McCalle3027922010-08-25 11:45:40 +00001379 Kind = CK_NoOp;
Anders Carlsson027732b2009-10-19 18:14:28 +00001380
Sebastian Redl9f831db2009-07-25 15:41:38 +00001381 if (tcr == TC_NotApplicable) {
1382 // ... or if that is not possible, a static_cast, ignoring const, ...
Anders Carlssona70cff62010-04-24 19:06:50 +00001383 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg, Kind,
1384 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001385 if (tcr == TC_NotApplicable) {
1386 // ... and finally a reinterpret_cast, ignoring const.
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001387 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1388 Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001389 }
1390 }
1391
Nick Lewycky14d88eb2010-11-09 00:19:31 +00001392 if (tcr != TC_Success && msg != 0) {
1393 if (CastExpr->getType() == Context.OverloadTy) {
Douglas Gregore81f58e2010-11-08 03:40:48 +00001394 DeclAccessPair Found;
Nick Lewycky14d88eb2010-11-09 00:19:31 +00001395 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(CastExpr,
Douglas Gregore81f58e2010-11-08 03:40:48 +00001396 CastTy,
1397 /* Complain */ true,
1398 Found);
1399 assert(!Fn && "cast failed but able to resolve overload expression!!");
Nick Lewycky14d88eb2010-11-09 00:19:31 +00001400 (void)Fn;
1401 } else {
Douglas Gregore81f58e2010-11-08 03:40:48 +00001402 Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
1403 << CastExpr->getType() << CastTy << R;
1404 }
1405 }
John McCalle3027922010-08-25 11:45:40 +00001406 else if (Kind == CK_Unknown || Kind == CK_BitCast)
John McCall2b5c1b22010-08-12 21:44:57 +00001407 CheckCastAlign(CastExpr, CastTy, R);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001408
1409 return tcr != TC_Success;
1410}