blob: 2dee71308b0a2e0507f76d5a139defd4a969a7e0 [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
14#include "Sema.h"
15#include "SemaInherit.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/ASTContext.h"
Sebastian Redl26d85b12008-11-05 21:50:06 +000018#include "llvm/ADT/SmallVector.h"
Sebastian Redle3dc28a2008-11-07 23:29:29 +000019#include <set>
Sebastian Redl26d85b12008-11-05 21:50:06 +000020using namespace clang;
21
Sebastian Redl9cc11e72009-07-25 15:41:38 +000022enum TryCastResult {
23 TC_NotApplicable, ///< The cast method is not applicable.
24 TC_Success, ///< The cast method is appropriate and successful.
25 TC_Failed ///< The cast method is appropriate, but failed. A
26 ///< diagnostic has been emitted.
27};
28
29enum CastType {
30 CT_Const, ///< const_cast
31 CT_Static, ///< static_cast
32 CT_Reinterpret, ///< reinterpret_cast
33 CT_Dynamic, ///< dynamic_cast
34 CT_CStyle, ///< (Type)expr
35 CT_Functional ///< Type(expr)
Sebastian Redl37d6de32008-11-08 13:00:26 +000036};
37
38static void CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
39 const SourceRange &OpRange,
40 const SourceRange &DestRange);
41static void CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
42 const SourceRange &OpRange,
43 const SourceRange &DestRange);
44static void CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlssoncdb61972009-08-07 22:21:05 +000045 const SourceRange &OpRange,
46 CastExpr::CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +000047static void CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
48 const SourceRange &OpRange,
Anders Carlsson714179b2009-08-02 19:07:59 +000049 const SourceRange &DestRange,
50 CastExpr::CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +000051
52static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000053
54// The Try functions attempt a specific way of casting. If they succeed, they
55// return TC_Success. If their way of casting is not appropriate for the given
56// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
57// to emit if no other way succeeds. If their way of casting is appropriate but
58// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
59// they emit a specialized diagnostic.
60// All diagnostics returned by these functions must expect the same three
61// arguments:
62// %0: Cast Type (a value from the CastType enumeration)
63// %1: Source Type
64// %2: Destination Type
65static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
66 QualType DestType, unsigned &msg);
67static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
68 QualType DestType, bool CStyle,
69 const SourceRange &OpRange,
70 unsigned &msg);
71static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
72 QualType DestType, bool CStyle,
73 const SourceRange &OpRange,
74 unsigned &msg);
75static TryCastResult TryStaticDowncast(Sema &Self, QualType SrcType,
76 QualType DestType, bool CStyle,
77 const SourceRange &OpRange,
78 QualType OrigSrcType,
79 QualType OrigDestType, unsigned &msg);
80static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType,
81 QualType DestType,bool CStyle,
82 const SourceRange &OpRange,
83 unsigned &msg);
84static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *SrcExpr,
85 QualType DestType, bool CStyle,
86 const SourceRange &OpRange,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +000087 unsigned &msg,
88 CXXMethodDecl *&ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000089static TryCastResult TryStaticCast(Sema &Self, Expr *SrcExpr,
90 QualType DestType, bool CStyle,
91 const SourceRange &OpRange,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +000092 CastExpr::CastKind &Kind, unsigned &msg,
93 CXXMethodDecl *&ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000094static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
95 bool CStyle, unsigned &msg);
96static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
97 QualType DestType, bool CStyle,
98 const SourceRange &OpRange,
99 unsigned &msg);
Sebastian Redl37d6de32008-11-08 13:00:26 +0000100
Sebastian Redl26d85b12008-11-05 21:50:06 +0000101/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000102Action::OwningExprResult
Sebastian Redl26d85b12008-11-05 21:50:06 +0000103Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
104 SourceLocation LAngleBracketLoc, TypeTy *Ty,
105 SourceLocation RAngleBracketLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000106 SourceLocation LParenLoc, ExprArg E,
Sebastian Redl26d85b12008-11-05 21:50:06 +0000107 SourceLocation RParenLoc) {
Anders Carlssone9146f22009-05-01 19:49:17 +0000108 Expr *Ex = E.takeAs<Expr>();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000109 // FIXME: Preserve type source info.
110 QualType DestType = GetTypeFromParser(Ty);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000111 SourceRange OpRange(OpLoc, RParenLoc);
112 SourceRange DestRange(LAngleBracketLoc, RAngleBracketLoc);
113
Douglas Gregor9103bb22008-12-17 22:52:20 +0000114 // If the type is dependent, we won't do the semantic analysis now.
115 // FIXME: should we check this in a more fine-grained manner?
116 bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
117
Sebastian Redl26d85b12008-11-05 21:50:06 +0000118 switch (Kind) {
119 default: assert(0 && "Unknown C++ cast!");
120
121 case tok::kw_const_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +0000122 if (!TypeDependent)
123 CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000124 return Owned(new (Context) CXXConstCastExpr(DestType.getNonReferenceType(),
125 Ex, DestType, OpLoc));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000126
Anders Carlsson714179b2009-08-02 19:07:59 +0000127 case tok::kw_dynamic_cast: {
128 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregor9103bb22008-12-17 22:52:20 +0000129 if (!TypeDependent)
Anders Carlsson714179b2009-08-02 19:07:59 +0000130 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000131 return Owned(new (Context)CXXDynamicCastExpr(DestType.getNonReferenceType(),
Anders Carlsson714179b2009-08-02 19:07:59 +0000132 Kind, Ex, DestType, OpLoc));
133 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000134 case tok::kw_reinterpret_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +0000135 if (!TypeDependent)
136 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000137 return Owned(new (Context) CXXReinterpretCastExpr(
138 DestType.getNonReferenceType(),
139 Ex, DestType, OpLoc));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000140
Anders Carlssoncdb61972009-08-07 22:21:05 +0000141 case tok::kw_static_cast: {
142 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregor9103bb22008-12-17 22:52:20 +0000143 if (!TypeDependent)
Anders Carlssoncdb61972009-08-07 22:21:05 +0000144 CheckStaticCast(*this, Ex, DestType, OpRange, Kind);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000145 return Owned(new (Context) CXXStaticCastExpr(DestType.getNonReferenceType(),
Anders Carlssoncdb61972009-08-07 22:21:05 +0000146 Kind, Ex, DestType, OpLoc));
147 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000148 }
149
Sebastian Redlf53597f2009-03-15 17:47:39 +0000150 return ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000151}
152
Sebastian Redldb647282009-01-27 23:18:31 +0000153/// CastsAwayConstness - Check if the pointer conversion from SrcType to
154/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
155/// the cast checkers. Both arguments must denote pointer (possibly to member)
156/// types.
Sebastian Redl26d85b12008-11-05 21:50:06 +0000157bool
Sebastian Redl37d6de32008-11-08 13:00:26 +0000158CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000159{
Sebastian Redldb647282009-01-27 23:18:31 +0000160 // Casting away constness is defined in C++ 5.2.11p8 with reference to
161 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
162 // the rules are non-trivial. So first we construct Tcv *...cv* as described
163 // in C++ 5.2.11p8.
164 assert((SrcType->isPointerType() || SrcType->isMemberPointerType()) &&
165 "Source type is not pointer or pointer to member.");
166 assert((DestType->isPointerType() || DestType->isMemberPointerType()) &&
167 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000168
169 QualType UnwrappedSrcType = SrcType, UnwrappedDestType = DestType;
170 llvm::SmallVector<unsigned, 8> cv1, cv2;
171
172 // Find the qualifications.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000173 while (Self.UnwrapSimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000174 cv1.push_back(UnwrappedSrcType.getCVRQualifiers());
175 cv2.push_back(UnwrappedDestType.getCVRQualifiers());
176 }
177 assert(cv1.size() > 0 && "Must have at least one pointer level.");
178
179 // Construct void pointers with those qualifiers (in reverse order of
180 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000181 QualType SrcConstruct = Self.Context.VoidTy;
182 QualType DestConstruct = Self.Context.VoidTy;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000183 for (llvm::SmallVector<unsigned, 8>::reverse_iterator i1 = cv1.rbegin(),
184 i2 = cv2.rbegin();
185 i1 != cv1.rend(); ++i1, ++i2)
186 {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000187 SrcConstruct = Self.Context.getPointerType(
188 SrcConstruct.getQualifiedType(*i1));
189 DestConstruct = Self.Context.getPointerType(
190 DestConstruct.getQualifiedType(*i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000191 }
192
193 // Test if they're compatible.
194 return SrcConstruct != DestConstruct &&
Sebastian Redl37d6de32008-11-08 13:00:26 +0000195 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000196}
197
Sebastian Redl26d85b12008-11-05 21:50:06 +0000198/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
199/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
200/// checked downcasts in class hierarchies.
Anders Carlsson714179b2009-08-02 19:07:59 +0000201static void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000202CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
203 const SourceRange &OpRange,
Anders Carlsson714179b2009-08-02 19:07:59 +0000204 const SourceRange &DestRange, CastExpr::CastKind &Kind)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000205{
206 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl37d6de32008-11-08 13:00:26 +0000207 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000208
209 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
210 // or "pointer to cv void".
211
212 QualType DestPointee;
Ted Kremenek6217b802009-07-29 21:53:49 +0000213 const PointerType *DestPointer = DestType->getAs<PointerType>();
214 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000215 if (DestPointer) {
216 DestPointee = DestPointer->getPointeeType();
217 } else if (DestReference) {
218 DestPointee = DestReference->getPointeeType();
219 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000220 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000221 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000222 return;
223 }
224
Ted Kremenek6217b802009-07-29 21:53:49 +0000225 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000226 if (DestPointee->isVoidType()) {
227 assert(DestPointer && "Reference to void is not possible");
228 } else if (DestRecord) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000229 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000230 diag::err_bad_dynamic_cast_incomplete,
231 DestRange))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000232 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000233 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000234 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000235 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000236 return;
237 }
238
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000239 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
240 // complete class type, [...]. If T is an lvalue reference type, v shall be
241 // an lvalue of a complete class type, [...]. If T is an rvalue reference
242 // type, v shall be an expression having a complete effective class type,
243 // [...]
Sebastian Redl26d85b12008-11-05 21:50:06 +0000244
Sebastian Redl37d6de32008-11-08 13:00:26 +0000245 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000246 QualType SrcPointee;
247 if (DestPointer) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000248 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000249 SrcPointee = SrcPointer->getPointeeType();
250 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000251 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000252 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000253 return;
254 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000255 } else if (DestReference->isLValueReferenceType()) {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000256 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000257 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000258 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000259 }
260 SrcPointee = SrcType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000261 } else {
262 SrcPointee = SrcType;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000263 }
264
Ted Kremenek6217b802009-07-29 21:53:49 +0000265 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000266 if (SrcRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000267 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000268 diag::err_bad_dynamic_cast_incomplete,
269 SrcExpr->getSourceRange()))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000270 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000271 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000272 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000273 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000274 return;
275 }
276
277 assert((DestPointer || DestReference) &&
278 "Bad destination non-ptr/ref slipped through.");
279 assert((DestRecord || DestPointee->isVoidType()) &&
280 "Bad destination pointee slipped through.");
281 assert(SrcRecord && "Bad source pointee slipped through.");
282
283 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
284 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000285 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000286 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000287 return;
288 }
289
290 // C++ 5.2.7p3: If the type of v is the same as the required result type,
291 // [except for cv].
292 if (DestRecord == SrcRecord) {
293 return;
294 }
295
296 // C++ 5.2.7p5
297 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000298 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
299 Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
Chris Lattnerd1625842008-11-24 06:25:27 +0000300 OpRange.getBegin(), OpRange);
Anders Carlsson714179b2009-08-02 19:07:59 +0000301 Kind = CastExpr::CK_DerivedToBase;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000302 // Diagnostic already emitted on error.
303 return;
304 }
305
306 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Sebastian Redl37d6de32008-11-08 13:00:26 +0000307 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(Self.Context);
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000308 assert(SrcDecl && "Definition missing");
309 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000310 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000311 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000312 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000313
314 // Done. Everything else is run-time checks.
Anders Carlsson714179b2009-08-02 19:07:59 +0000315 Kind = CastExpr::CK_Dynamic;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000316}
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000317
318/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
319/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
320/// like this:
321/// const char *str = "literal";
322/// legacy_function(const_cast\<char*\>(str));
323void
324CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
325 const SourceRange &OpRange, const SourceRange &DestRange)
326{
327 if (!DestType->isLValueReferenceType())
328 Self.DefaultFunctionArrayConversion(SrcExpr);
329
330 unsigned msg = diag::err_bad_cxx_cast_generic;
331 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
332 && msg != 0)
333 Self.Diag(OpRange.getBegin(), msg) << CT_Const
334 << SrcExpr->getType() << DestType << OpRange;
335}
336
337/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
338/// valid.
339/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
340/// like this:
341/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
342void
343CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
344 const SourceRange &OpRange, const SourceRange &DestRange)
345{
346 if (!DestType->isLValueReferenceType())
347 Self.DefaultFunctionArrayConversion(SrcExpr);
348
349 unsigned msg = diag::err_bad_cxx_cast_generic;
350 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg)
351 != TC_Success && msg != 0)
352 Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
353 << SrcExpr->getType() << DestType << OpRange;
354}
355
356
357/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
358/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
359/// implicit conversions explicit and getting rid of data loss warnings.
360void
361CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlssoncdb61972009-08-07 22:21:05 +0000362 const SourceRange &OpRange, CastExpr::CastKind &Kind)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000363{
364 // This test is outside everything else because it's the only case where
365 // a non-lvalue-reference target type does not lead to decay.
366 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
367 if (DestType->isVoidType()) {
368 return;
369 }
370
371 if (!DestType->isLValueReferenceType())
372 Self.DefaultFunctionArrayConversion(SrcExpr);
373
374 unsigned msg = diag::err_bad_cxx_cast_generic;
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000375 CXXMethodDecl *ConversionDecl = 0;
Anders Carlssoncdb61972009-08-07 22:21:05 +0000376 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000377 Kind, msg,
378 ConversionDecl)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000379 != TC_Success && msg != 0)
380 Self.Diag(OpRange.getBegin(), msg) << CT_Static
381 << SrcExpr->getType() << DestType << OpRange;
382}
383
384/// TryStaticCast - Check if a static cast can be performed, and do so if
385/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
386/// and casting away constness.
387static TryCastResult TryStaticCast(Sema &Self, Expr *SrcExpr,
388 QualType DestType, bool CStyle,
389 const SourceRange &OpRange,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000390 CastExpr::CastKind &Kind, unsigned &msg,
391 CXXMethodDecl *&ConversionDecl)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000392{
393 // The order the tests is not entirely arbitrary. There is one conversion
394 // that can be handled in two different ways. Given:
395 // struct A {};
396 // struct B : public A {
397 // B(); B(const A&);
398 // };
399 // const A &a = B();
400 // the cast static_cast<const B&>(a) could be seen as either a static
401 // reference downcast, or an explicit invocation of the user-defined
402 // conversion using B's conversion constructor.
403 // DR 427 specifies that the downcast is to be applied here.
404
405 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
406 // Done outside this function.
407
408 TryCastResult tcr;
409
410 // C++ 5.2.9p5, reference downcast.
411 // See the function for details.
412 // DR 427 specifies that this is to be applied before paragraph 2.
413 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle,OpRange,msg);
414 if (tcr != TC_NotApplicable)
415 return tcr;
416
417 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
418 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
419 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
420 if (tcr != TC_NotApplicable)
421 return tcr;
422
423 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
424 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000425 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
426 ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000427 if (tcr != TC_NotApplicable)
428 return tcr;
429
430 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
431 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
432 // conversions, subject to further restrictions.
433 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
434 // of qualification conversions impossible.
435 // In the CStyle case, the earlier attempt to const_cast should have taken
436 // care of reverse qualification conversions.
437
438 QualType OrigSrcType = SrcExpr->getType();
439
440 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
441
442 // Reverse integral promotion/conversion. All such conversions are themselves
443 // again integral promotions or conversions and are thus already handled by
444 // p2 (TryDirectInitialization above).
445 // (Note: any data loss warnings should be suppressed.)
446 // The exception is the reverse of enum->integer, i.e. integer->enum (and
447 // enum->enum). See also C++ 5.2.9p7.
448 // The same goes for reverse floating point promotion/conversion and
449 // floating-integral conversions. Again, only floating->enum is relevant.
450 if (DestType->isEnumeralType()) {
451 if (SrcType->isComplexType() || SrcType->isVectorType()) {
452 // Fall through - these cannot be converted.
453 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType())
454 return TC_Success;
455 }
456
457 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
458 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
459 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg);
460 if (tcr != TC_NotApplicable)
461 return tcr;
462
463 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
464 // conversion. C++ 5.2.9p9 has additional information.
465 // DR54's access restrictions apply here also.
466 tcr = TryStaticMemberPointerUpcast(Self, SrcType, DestType, CStyle,
467 OpRange, msg);
468 if (tcr != TC_NotApplicable)
469 return tcr;
470
471 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
472 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
473 // just the usual constness stuff.
Ted Kremenek6217b802009-07-29 21:53:49 +0000474 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000475 QualType SrcPointee = SrcPointer->getPointeeType();
476 if (SrcPointee->isVoidType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000477 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000478 QualType DestPointee = DestPointer->getPointeeType();
479 if (DestPointee->isIncompleteOrObjectType()) {
480 // This is definitely the intended conversion, but it might fail due
481 // to a const violation.
482 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
483 msg = diag::err_bad_cxx_cast_const_away;
484 return TC_Failed;
485 }
486 return TC_Success;
487 }
488 }
489 }
490 }
491
492 // We tried everything. Everything! Nothing works! :-(
493 return TC_NotApplicable;
494}
495
496/// Tests whether a conversion according to N2844 is valid.
497TryCastResult
498TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
499 unsigned &msg)
500{
501 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
502 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenek6217b802009-07-29 21:53:49 +0000503 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000504 if (!R)
505 return TC_NotApplicable;
506
507 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
508 return TC_NotApplicable;
509
510 // Because we try the reference downcast before this function, from now on
511 // this is the only cast possibility, so we issue an error if we fail now.
512 // FIXME: Should allow casting away constness if CStyle.
513 bool DerivedToBase;
514 if (Self.CompareReferenceRelationship(SrcExpr->getType(), R->getPointeeType(),
515 DerivedToBase) <
516 Sema::Ref_Compatible_With_Added_Qualification) {
517 msg = diag::err_bad_lvalue_to_rvalue_cast;
518 return TC_Failed;
519 }
520
521 // FIXME: Similar to CheckReferenceInit, we actually need more AST annotation
522 // than nothing.
523 return TC_Success;
524}
525
526/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
527TryCastResult
528TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
529 bool CStyle, const SourceRange &OpRange,
530 unsigned &msg)
531{
532 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
533 // cast to type "reference to cv2 D", where D is a class derived from B,
534 // if a valid standard conversion from "pointer to D" to "pointer to B"
535 // exists, cv2 >= cv1, and B is not a virtual base class of D.
536 // In addition, DR54 clarifies that the base must be accessible in the
537 // current context. Although the wording of DR54 only applies to the pointer
538 // variant of this rule, the intent is clearly for it to apply to the this
539 // conversion as well.
540
Ted Kremenek6217b802009-07-29 21:53:49 +0000541 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000542 if (!DestReference) {
543 return TC_NotApplicable;
544 }
545 bool RValueRef = DestReference->isRValueReferenceType();
546 if (!RValueRef && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
547 // We know the left side is an lvalue reference, so we can suggest a reason.
548 msg = diag::err_bad_cxx_cast_rvalue;
549 return TC_NotApplicable;
550 }
551
552 QualType DestPointee = DestReference->getPointeeType();
553
554 return TryStaticDowncast(Self, SrcExpr->getType(), DestPointee, CStyle,
555 OpRange, SrcExpr->getType(), DestType, msg);
556}
557
558/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
559TryCastResult
560TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
561 bool CStyle, const SourceRange &OpRange, unsigned &msg)
562{
563 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
564 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
565 // is a class derived from B, if a valid standard conversion from "pointer
566 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
567 // class of D.
568 // In addition, DR54 clarifies that the base must be accessible in the
569 // current context.
570
Ted Kremenek6217b802009-07-29 21:53:49 +0000571 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000572 if (!DestPointer) {
573 return TC_NotApplicable;
574 }
575
Ted Kremenek6217b802009-07-29 21:53:49 +0000576 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000577 if (!SrcPointer) {
578 msg = diag::err_bad_static_cast_pointer_nonpointer;
579 return TC_NotApplicable;
580 }
581
582 return TryStaticDowncast(Self, SrcPointer->getPointeeType(),
583 DestPointer->getPointeeType(), CStyle,
584 OpRange, SrcType, DestType, msg);
585}
586
587/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
588/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
589/// DestType, both of which must be canonical, is possible and allowed.
590TryCastResult
591TryStaticDowncast(Sema &Self, QualType SrcType, QualType DestType,
592 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
593 QualType OrigDestType, unsigned &msg)
594{
595 // Downcast can only happen in class hierarchies, so we need classes.
596 if (!DestType->isRecordType() || !SrcType->isRecordType()) {
597 return TC_NotApplicable;
598 }
599
600 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
601 /*DetectVirtual=*/true);
602 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
603 return TC_NotApplicable;
604 }
605
606 // Target type does derive from source type. Now we're serious. If an error
607 // appears now, it's not ignored.
608 // This may not be entirely in line with the standard. Take for example:
609 // struct A {};
610 // struct B : virtual A {
611 // B(A&);
612 // };
613 //
614 // void f()
615 // {
616 // (void)static_cast<const B&>(*((A*)0));
617 // }
618 // As far as the standard is concerned, p5 does not apply (A is virtual), so
619 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
620 // However, both GCC and Comeau reject this example, and accepting it would
621 // mean more complex code if we're to preserve the nice error message.
622 // FIXME: Being 100% compliant here would be nice to have.
623
624 // Must preserve cv, as always, unless we're in C-style mode.
625 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
626 msg = diag::err_bad_cxx_cast_const_away;
627 return TC_Failed;
628 }
629
630 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
631 // This code is analoguous to that in CheckDerivedToBaseConversion, except
632 // that it builds the paths in reverse order.
633 // To sum up: record all paths to the base and build a nice string from
634 // them. Use it to spice up the error message.
635 if (!Paths.isRecordingPaths()) {
636 Paths.clear();
637 Paths.setRecordingPaths(true);
638 Self.IsDerivedFrom(DestType, SrcType, Paths);
639 }
640 std::string PathDisplayStr;
641 std::set<unsigned> DisplayedPaths;
642 for (BasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
643 PI != PE; ++PI) {
644 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
645 // We haven't displayed a path to this particular base
646 // class subobject yet.
647 PathDisplayStr += "\n ";
648 for (BasePath::const_reverse_iterator EI = PI->rbegin(),EE = PI->rend();
649 EI != EE; ++EI)
650 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
651 PathDisplayStr += DestType.getAsString();
652 }
653 }
654
655 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
656 << SrcType.getUnqualifiedType() << DestType.getUnqualifiedType()
657 << PathDisplayStr << OpRange;
658 msg = 0;
659 return TC_Failed;
660 }
661
662 if (Paths.getDetectedVirtual() != 0) {
663 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
664 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
665 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
666 msg = 0;
667 return TC_Failed;
668 }
669
670 if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
671 diag::err_downcast_from_inaccessible_base, Paths,
672 OpRange.getBegin(), DeclarationName())) {
673 msg = 0;
674 return TC_Failed;
675 }
676
677 return TC_Success;
678}
679
680/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
681/// C++ 5.2.9p9 is valid:
682///
683/// An rvalue of type "pointer to member of D of type cv1 T" can be
684/// converted to an rvalue of type "pointer to member of B of type cv2 T",
685/// where B is a base class of D [...].
686///
687TryCastResult
688TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType, QualType DestType,
689 bool CStyle, const SourceRange &OpRange,
690 unsigned &msg)
691{
Ted Kremenek6217b802009-07-29 21:53:49 +0000692 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000693 if (!DestMemPtr)
694 return TC_NotApplicable;
Ted Kremenek6217b802009-07-29 21:53:49 +0000695 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000696 if (!SrcMemPtr) {
697 msg = diag::err_bad_static_cast_member_pointer_nonmp;
698 return TC_NotApplicable;
699 }
700
701 // T == T, modulo cv
702 if (Self.Context.getCanonicalType(
703 SrcMemPtr->getPointeeType().getUnqualifiedType()) !=
704 Self.Context.getCanonicalType(DestMemPtr->getPointeeType().
705 getUnqualifiedType()))
706 return TC_NotApplicable;
707
708 // B base of D
709 QualType SrcClass(SrcMemPtr->getClass(), 0);
710 QualType DestClass(DestMemPtr->getClass(), 0);
711 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
712 /*DetectVirtual=*/true);
713 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
714 return TC_NotApplicable;
715 }
716
717 // B is a base of D. But is it an allowed base? If not, it's a hard error.
718 if (Paths.isAmbiguous(DestClass)) {
719 Paths.clear();
720 Paths.setRecordingPaths(true);
721 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
722 assert(StillOkay);
723 StillOkay = StillOkay;
724 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
725 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
726 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
727 msg = 0;
728 return TC_Failed;
729 }
730
731 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
732 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
733 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
734 msg = 0;
735 return TC_Failed;
736 }
737
738 if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
739 diag::err_downcast_from_inaccessible_base, Paths,
740 OpRange.getBegin(), DeclarationName())) {
741 msg = 0;
742 return TC_Failed;
743 }
744
745 return TC_Success;
746}
747
748/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
749/// is valid:
750///
751/// An expression e can be explicitly converted to a type T using a
752/// @c static_cast if the declaration "T t(e);" is well-formed [...].
753TryCastResult
754TryStaticImplicitCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000755 bool CStyle, const SourceRange &OpRange, unsigned &msg,
756 CXXMethodDecl *&ConversionDecl)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000757{
758 if (DestType->isReferenceType()) {
759 // At this point of CheckStaticCast, if the destination is a reference,
760 // this has to work. There is no other way that works.
761 // On the other hand, if we're checking a C-style cast, we've still got
762 // the reinterpret_cast way. In that case, we pass an ICS so we don't
763 // get error messages.
764 ImplicitConversionSequence ICS;
765 bool failed = Self.CheckReferenceInit(SrcExpr, DestType, CStyle ? &ICS : 0);
766 if (!failed)
767 return TC_Success;
768 if (CStyle)
769 return TC_NotApplicable;
770 // If we didn't pass the ICS, we already got an error message.
771 msg = 0;
772 return TC_Failed;
773 }
774 if (DestType->isRecordType()) {
775 // There are no further possibilities for the target type being a class,
776 // neither in static_cast nor in a C-style cast. So we can fail here.
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000777 if ((ConversionDecl =
778 Self.PerformInitializationByConstructor(DestType, &SrcExpr, 1,
779 OpRange.getBegin(), OpRange, DeclarationName(), Sema::IK_Direct)))
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000780 return TC_Success;
781 // The function already emitted an error.
782 msg = 0;
783 return TC_Failed;
784 }
785
786 // FIXME: To get a proper error from invalid conversions here, we need to
787 // reimplement more of this.
788 // FIXME: This does not actually perform the conversion, and thus does not
789 // check for ambiguity or access.
790 ImplicitConversionSequence ICS = Self.TryImplicitConversion(
791 SrcExpr, DestType);
792 return ICS.ConversionKind == ImplicitConversionSequence::BadConversion ?
793 TC_NotApplicable : TC_Success;
794}
795
796/// TryConstCast - See if a const_cast from source to destination is allowed,
797/// and perform it if it is.
798static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
799 bool CStyle, unsigned &msg) {
800 DestType = Self.Context.getCanonicalType(DestType);
801 QualType SrcType = SrcExpr->getType();
802 if (const LValueReferenceType *DestTypeTmp =
Ted Kremenek6217b802009-07-29 21:53:49 +0000803 DestType->getAs<LValueReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000804 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
805 // Cannot const_cast non-lvalue to lvalue reference type. But if this
806 // is C-style, static_cast might find a way, so we simply suggest a
807 // message and tell the parent to keep searching.
808 msg = diag::err_bad_cxx_cast_rvalue;
809 return TC_NotApplicable;
810 }
811
812 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
813 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
814 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
815 SrcType = Self.Context.getPointerType(SrcType);
816 }
817
818 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
819 // the rules for const_cast are the same as those used for pointers.
820
821 if (!DestType->isPointerType() && !DestType->isMemberPointerType()) {
822 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
823 // was a reference type, we converted it to a pointer above.
824 // The status of rvalue references isn't entirely clear, but it looks like
825 // conversion to them is simply invalid.
826 // C++ 5.2.11p3: For two pointer types [...]
827 if (!CStyle)
828 msg = diag::err_bad_const_cast_dest;
829 return TC_NotApplicable;
830 }
831 if (DestType->isFunctionPointerType() ||
832 DestType->isMemberFunctionPointerType()) {
833 // Cannot cast direct function pointers.
834 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
835 // T is the ultimate pointee of source and target type.
836 if (!CStyle)
837 msg = diag::err_bad_const_cast_dest;
838 return TC_NotApplicable;
839 }
840 SrcType = Self.Context.getCanonicalType(SrcType);
841
842 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
843 // completely equal.
844 // FIXME: const_cast should probably not be able to convert between pointers
845 // to different address spaces.
846 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
847 // in multi-level pointers may change, but the level count must be the same,
848 // as must be the final pointee type.
849 while (SrcType != DestType &&
850 Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
851 SrcType = SrcType.getUnqualifiedType();
852 DestType = DestType.getUnqualifiedType();
853 }
854
855 // Since we're dealing in canonical types, the remainder must be the same.
856 if (SrcType != DestType)
857 return TC_NotApplicable;
858
859 return TC_Success;
860}
861
862static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
863 QualType DestType, bool CStyle,
864 const SourceRange &OpRange,
865 unsigned &msg) {
866 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
867
868 DestType = Self.Context.getCanonicalType(DestType);
869 QualType SrcType = SrcExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000870 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000871 bool LValue = DestTypeTmp->isLValueReferenceType();
872 if (LValue && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
873 // Cannot cast non-lvalue to reference type. See the similar comment in
874 // const_cast.
875 msg = diag::err_bad_cxx_cast_rvalue;
876 return TC_NotApplicable;
877 }
878
879 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
880 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
881 // built-in & and * operators.
882 // This code does this transformation for the checked types.
883 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
884 SrcType = Self.Context.getPointerType(SrcType);
885 }
886
887 // Canonicalize source for comparison.
888 SrcType = Self.Context.getCanonicalType(SrcType);
889
Ted Kremenek6217b802009-07-29 21:53:49 +0000890 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
891 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000892 if (DestMemPtr && SrcMemPtr) {
893 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
894 // can be explicitly converted to an rvalue of type "pointer to member
895 // of Y of type T2" if T1 and T2 are both function types or both object
896 // types.
897 if (DestMemPtr->getPointeeType()->isFunctionType() !=
898 SrcMemPtr->getPointeeType()->isFunctionType())
899 return TC_NotApplicable;
900
901 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
902 // constness.
903 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
904 // we accept it.
905 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
906 msg = diag::err_bad_cxx_cast_const_away;
907 return TC_Failed;
908 }
909
910 // A valid member pointer cast.
911 return TC_Success;
912 }
913
914 // See below for the enumeral issue.
915 if (SrcType->isNullPtrType() && DestType->isIntegralType() &&
916 !DestType->isEnumeralType()) {
917 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
918 // type large enough to hold it. A value of std::nullptr_t can be
919 // converted to an integral type; the conversion has the same meaning
920 // and validity as a conversion of (void*)0 to the integral type.
921 if (Self.Context.getTypeSize(SrcType) >
922 Self.Context.getTypeSize(DestType)) {
923 msg = diag::err_bad_reinterpret_cast_small_int;
924 return TC_Failed;
925 }
926 return TC_Success;
927 }
928
929 bool destIsPtr = DestType->isPointerType();
930 bool srcIsPtr = SrcType->isPointerType();
931 if (!destIsPtr && !srcIsPtr) {
932 // Except for std::nullptr_t->integer and lvalue->reference, which are
933 // handled above, at least one of the two arguments must be a pointer.
934 return TC_NotApplicable;
935 }
936
937 if (SrcType == DestType) {
938 // C++ 5.2.10p2 has a note that mentions that, subject to all other
939 // restrictions, a cast to the same type is allowed. The intent is not
940 // entirely clear here, since all other paragraphs explicitly forbid casts
941 // to the same type. However, the behavior of compilers is pretty consistent
942 // on this point: allow same-type conversion if the involved types are
943 // pointers, disallow otherwise.
944 return TC_Success;
945 }
946
947 // Note: Clang treats enumeration types as integral types. If this is ever
948 // changed for C++, the additional check here will be redundant.
949 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
950 assert(srcIsPtr && "One type must be a pointer");
951 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
952 // type large enough to hold it.
953 if (Self.Context.getTypeSize(SrcType) >
954 Self.Context.getTypeSize(DestType)) {
955 msg = diag::err_bad_reinterpret_cast_small_int;
956 return TC_Failed;
957 }
958 return TC_Success;
959 }
960
961 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
962 assert(destIsPtr && "One type must be a pointer");
963 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
964 // converted to a pointer.
965 return TC_Success;
966 }
967
968 if (!destIsPtr || !srcIsPtr) {
969 // With the valid non-pointer conversions out of the way, we can be even
970 // more stringent.
971 return TC_NotApplicable;
972 }
973
974 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
975 // The C-style cast operator can.
976 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
977 msg = diag::err_bad_cxx_cast_const_away;
978 return TC_Failed;
979 }
980
981 // Not casting away constness, so the only remaining check is for compatible
982 // pointer categories.
983
984 if (SrcType->isFunctionPointerType()) {
985 if (DestType->isFunctionPointerType()) {
986 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
987 // a pointer to a function of a different type.
988 return TC_Success;
989 }
990
991 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
992 // an object type or vice versa is conditionally-supported.
993 // Compilers support it in C++03 too, though, because it's necessary for
994 // casting the return value of dlsym() and GetProcAddress().
995 // FIXME: Conditionally-supported behavior should be configurable in the
996 // TargetInfo or similar.
997 if (!Self.getLangOptions().CPlusPlus0x)
998 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
999 return TC_Success;
1000 }
1001
1002 if (DestType->isFunctionPointerType()) {
1003 // See above.
1004 if (!Self.getLangOptions().CPlusPlus0x)
1005 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1006 return TC_Success;
1007 }
1008
1009 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1010 // a pointer to an object of different type.
1011 // Void pointers are not specified, but supported by every compiler out there.
1012 // So we finish by allowing everything that remains - it's got to be two
1013 // object pointers.
1014 return TC_Success;
1015}
1016
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00001017bool Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00001018 CastExpr::CastKind &Kind, bool FunctionalStyle,
1019 CXXMethodDecl *&ConversionDecl)
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001020{
1021 // This test is outside everything else because it's the only case where
1022 // a non-lvalue-reference target type does not lead to decay.
1023 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1024 if (CastTy->isVoidType())
1025 return false;
1026
1027 // If the type is dependent, we won't do any other semantic analysis now.
1028 if (CastTy->isDependentType() || CastExpr->isTypeDependent())
1029 return false;
1030
1031 if (!CastTy->isLValueReferenceType())
1032 DefaultFunctionArrayConversion(CastExpr);
1033
1034 // C++ [expr.cast]p5: The conversions performed by
1035 // - a const_cast,
1036 // - a static_cast,
1037 // - a static_cast followed by a const_cast,
1038 // - a reinterpret_cast, or
1039 // - a reinterpret_cast followed by a const_cast,
1040 // can be performed using the cast notation of explicit type conversion.
1041 // [...] If a conversion can be interpreted in more than one of the ways
1042 // listed above, the interpretation that appears first in the list is used,
1043 // even if a cast resulting from that interpretation is ill-formed.
1044 // In plain language, this means trying a const_cast ...
1045 unsigned msg = diag::err_bad_cxx_cast_generic;
1046 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,msg);
1047 if (tcr == TC_NotApplicable) {
1048 // ... or if that is not possible, a static_cast, ignoring const, ...
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00001049 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, Kind, msg,
1050 ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001051 if (tcr == TC_NotApplicable) {
1052 // ... and finally a reinterpret_cast, ignoring const.
1053 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg);
1054 }
1055 }
1056
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001057 if (tcr != TC_Success && msg != 0)
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00001058 Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001059 << CastExpr->getType() << CastTy << R;
1060
1061 return tcr != TC_Success;
1062}