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