blob: d1a8b6dedfe9bfc8fbab5383769eb5adbc44e28d [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,
Anders Carlsson7f9e6462009-09-15 04:48:33 +000044 const SourceRange &DestRange,
45 CastExpr::CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +000046static void CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlssoncdb61972009-08-07 22:21:05 +000047 const SourceRange &OpRange,
Anders Carlsson0aebc812009-09-09 21:33:21 +000048 CastExpr::CastKind &Kind,
49 CXXMethodDecl *&ConversionDecl);
Sebastian Redl37d6de32008-11-08 13:00:26 +000050static void CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
51 const SourceRange &OpRange,
Mike Stump1eb44332009-09-09 15:08:12 +000052 const SourceRange &DestRange,
Anders Carlsson714179b2009-08-02 19:07:59 +000053 CastExpr::CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +000054
55static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000056
57// The Try functions attempt a specific way of casting. If they succeed, they
58// return TC_Success. If their way of casting is not appropriate for the given
59// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
60// to emit if no other way succeeds. If their way of casting is appropriate but
61// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
62// they emit a specialized diagnostic.
63// All diagnostics returned by these functions must expect the same three
64// arguments:
65// %0: Cast Type (a value from the CastType enumeration)
66// %1: Source Type
67// %2: Destination Type
68static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
69 QualType DestType, unsigned &msg);
70static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
71 QualType DestType, bool CStyle,
72 const SourceRange &OpRange,
73 unsigned &msg);
74static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
75 QualType DestType, bool CStyle,
76 const SourceRange &OpRange,
77 unsigned &msg);
78static TryCastResult TryStaticDowncast(Sema &Self, QualType SrcType,
79 QualType DestType, bool CStyle,
80 const SourceRange &OpRange,
81 QualType OrigSrcType,
82 QualType OrigDestType, unsigned &msg);
83static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType,
84 QualType DestType,bool CStyle,
85 const SourceRange &OpRange,
86 unsigned &msg);
87static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *SrcExpr,
88 QualType DestType, bool CStyle,
89 const SourceRange &OpRange,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +000090 unsigned &msg,
91 CXXMethodDecl *&ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000092static TryCastResult TryStaticCast(Sema &Self, Expr *SrcExpr,
93 QualType DestType, bool CStyle,
Mike Stump1eb44332009-09-09 15:08:12 +000094 CastExpr::CastKind &Kind,
Sebastian Redl9cc11e72009-07-25 15:41:38 +000095 const SourceRange &OpRange,
Anders Carlssoncb3c3082009-09-01 20:52:42 +000096 unsigned &msg,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +000097 CXXMethodDecl *&ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000098static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
99 bool CStyle, unsigned &msg);
100static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
101 QualType DestType, bool CStyle,
Mike Stump1eb44332009-09-09 15:08:12 +0000102 CastExpr::CastKind &Kind,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000103 const SourceRange &OpRange,
104 unsigned &msg);
Sebastian Redl37d6de32008-11-08 13:00:26 +0000105
Sebastian Redl26d85b12008-11-05 21:50:06 +0000106/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000107Action::OwningExprResult
Sebastian Redl26d85b12008-11-05 21:50:06 +0000108Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
109 SourceLocation LAngleBracketLoc, TypeTy *Ty,
110 SourceLocation RAngleBracketLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000111 SourceLocation LParenLoc, ExprArg E,
Sebastian Redl26d85b12008-11-05 21:50:06 +0000112 SourceLocation RParenLoc) {
Anders Carlssone9146f22009-05-01 19:49:17 +0000113 Expr *Ex = E.takeAs<Expr>();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000114 // FIXME: Preserve type source info.
115 QualType DestType = GetTypeFromParser(Ty);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000116 SourceRange OpRange(OpLoc, RParenLoc);
117 SourceRange DestRange(LAngleBracketLoc, RAngleBracketLoc);
118
Douglas Gregor9103bb22008-12-17 22:52:20 +0000119 // If the type is dependent, we won't do the semantic analysis now.
120 // FIXME: should we check this in a more fine-grained manner?
121 bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
122
Sebastian Redl26d85b12008-11-05 21:50:06 +0000123 switch (Kind) {
124 default: assert(0 && "Unknown C++ cast!");
125
126 case tok::kw_const_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +0000127 if (!TypeDependent)
128 CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000129 return Owned(new (Context) CXXConstCastExpr(DestType.getNonReferenceType(),
130 Ex, DestType, OpLoc));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000131
Anders Carlsson714179b2009-08-02 19:07:59 +0000132 case tok::kw_dynamic_cast: {
133 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregor9103bb22008-12-17 22:52:20 +0000134 if (!TypeDependent)
Anders Carlsson714179b2009-08-02 19:07:59 +0000135 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000136 return Owned(new (Context)CXXDynamicCastExpr(DestType.getNonReferenceType(),
Anders Carlsson714179b2009-08-02 19:07:59 +0000137 Kind, Ex, DestType, OpLoc));
138 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000139 case tok::kw_reinterpret_cast: {
140 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregor9103bb22008-12-17 22:52:20 +0000141 if (!TypeDependent)
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000142 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000143 return Owned(new (Context) CXXReinterpretCastExpr(
144 DestType.getNonReferenceType(),
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000145 Kind, Ex, DestType, OpLoc));
146 }
Anders Carlssoncdb61972009-08-07 22:21:05 +0000147 case tok::kw_static_cast: {
148 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000149 if (!TypeDependent) {
150 CXXMethodDecl *Method = 0;
151
152 CheckStaticCast(*this, Ex, DestType, OpRange, Kind, Method);
153
154 if (Method) {
155 OwningExprResult CastArg
156 = BuildCXXCastArgument(OpLoc, DestType.getNonReferenceType(),
157 Kind, Method, Owned(Ex));
158 if (CastArg.isInvalid())
159 return ExprError();
160
161 Ex = CastArg.takeAs<Expr>();
162 }
163 }
164
Sebastian Redlf53597f2009-03-15 17:47:39 +0000165 return Owned(new (Context) CXXStaticCastExpr(DestType.getNonReferenceType(),
Anders Carlssoncdb61972009-08-07 22:21:05 +0000166 Kind, Ex, DestType, OpLoc));
167 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000168 }
169
Sebastian Redlf53597f2009-03-15 17:47:39 +0000170 return ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000171}
172
Sebastian Redldb647282009-01-27 23:18:31 +0000173/// CastsAwayConstness - Check if the pointer conversion from SrcType to
174/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
175/// the cast checkers. Both arguments must denote pointer (possibly to member)
176/// types.
Sebastian Redl26d85b12008-11-05 21:50:06 +0000177bool
Mike Stump1eb44332009-09-09 15:08:12 +0000178CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
Sebastian Redldb647282009-01-27 23:18:31 +0000179 // Casting away constness is defined in C++ 5.2.11p8 with reference to
180 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
181 // the rules are non-trivial. So first we construct Tcv *...cv* as described
182 // in C++ 5.2.11p8.
183 assert((SrcType->isPointerType() || SrcType->isMemberPointerType()) &&
184 "Source type is not pointer or pointer to member.");
185 assert((DestType->isPointerType() || DestType->isMemberPointerType()) &&
186 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000187
188 QualType UnwrappedSrcType = SrcType, UnwrappedDestType = DestType;
189 llvm::SmallVector<unsigned, 8> cv1, cv2;
190
191 // Find the qualifications.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000192 while (Self.UnwrapSimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000193 cv1.push_back(UnwrappedSrcType.getCVRQualifiers());
194 cv2.push_back(UnwrappedDestType.getCVRQualifiers());
195 }
196 assert(cv1.size() > 0 && "Must have at least one pointer level.");
197
198 // Construct void pointers with those qualifiers (in reverse order of
199 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000200 QualType SrcConstruct = Self.Context.VoidTy;
201 QualType DestConstruct = Self.Context.VoidTy;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000202 for (llvm::SmallVector<unsigned, 8>::reverse_iterator i1 = cv1.rbegin(),
203 i2 = cv2.rbegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000204 i1 != cv1.rend(); ++i1, ++i2) {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000205 SrcConstruct = Self.Context.getPointerType(
206 SrcConstruct.getQualifiedType(*i1));
207 DestConstruct = Self.Context.getPointerType(
208 DestConstruct.getQualifiedType(*i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000209 }
210
211 // Test if they're compatible.
212 return SrcConstruct != DestConstruct &&
Sebastian Redl37d6de32008-11-08 13:00:26 +0000213 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000214}
215
Sebastian Redl26d85b12008-11-05 21:50:06 +0000216/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
217/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
218/// checked downcasts in class hierarchies.
Anders Carlsson714179b2009-08-02 19:07:59 +0000219static void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000220CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
221 const SourceRange &OpRange,
Mike Stump1eb44332009-09-09 15:08:12 +0000222 const SourceRange &DestRange, CastExpr::CastKind &Kind) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000223 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl37d6de32008-11-08 13:00:26 +0000224 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000225
226 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
227 // or "pointer to cv void".
228
229 QualType DestPointee;
Ted Kremenek6217b802009-07-29 21:53:49 +0000230 const PointerType *DestPointer = DestType->getAs<PointerType>();
231 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000232 if (DestPointer) {
233 DestPointee = DestPointer->getPointeeType();
234 } else if (DestReference) {
235 DestPointee = DestReference->getPointeeType();
236 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000237 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000238 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000239 return;
240 }
241
Ted Kremenek6217b802009-07-29 21:53:49 +0000242 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000243 if (DestPointee->isVoidType()) {
244 assert(DestPointer && "Reference to void is not possible");
245 } else if (DestRecord) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000246 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000247 PDiag(diag::err_bad_dynamic_cast_incomplete)
248 << DestRange))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000249 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000250 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000251 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000252 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000253 return;
254 }
255
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000256 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
257 // complete class type, [...]. If T is an lvalue reference type, v shall be
258 // an lvalue of a complete class type, [...]. If T is an rvalue reference
259 // type, v shall be an expression having a complete effective class type,
260 // [...]
Sebastian Redl26d85b12008-11-05 21:50:06 +0000261
Sebastian Redl37d6de32008-11-08 13:00:26 +0000262 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000263 QualType SrcPointee;
264 if (DestPointer) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000265 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000266 SrcPointee = SrcPointer->getPointeeType();
267 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000268 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000269 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000270 return;
271 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000272 } else if (DestReference->isLValueReferenceType()) {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000273 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000274 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000275 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000276 }
277 SrcPointee = SrcType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000278 } else {
279 SrcPointee = SrcType;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000280 }
281
Ted Kremenek6217b802009-07-29 21:53:49 +0000282 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000283 if (SrcRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000284 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000285 PDiag(diag::err_bad_dynamic_cast_incomplete)
286 << SrcExpr->getSourceRange()))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000287 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000288 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000289 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000290 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000291 return;
292 }
293
294 assert((DestPointer || DestReference) &&
295 "Bad destination non-ptr/ref slipped through.");
296 assert((DestRecord || DestPointee->isVoidType()) &&
297 "Bad destination pointee slipped through.");
298 assert(SrcRecord && "Bad source pointee slipped through.");
299
300 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
301 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000302 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000303 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000304 return;
305 }
306
307 // C++ 5.2.7p3: If the type of v is the same as the required result type,
308 // [except for cv].
309 if (DestRecord == SrcRecord) {
310 return;
311 }
312
313 // C++ 5.2.7p5
314 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000315 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
316 Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
Chris Lattnerd1625842008-11-24 06:25:27 +0000317 OpRange.getBegin(), OpRange);
Anders Carlsson714179b2009-08-02 19:07:59 +0000318 Kind = CastExpr::CK_DerivedToBase;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000319 // Diagnostic already emitted on error.
320 return;
321 }
322
323 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Sebastian Redl37d6de32008-11-08 13:00:26 +0000324 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(Self.Context);
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000325 assert(SrcDecl && "Definition missing");
326 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000327 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000328 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000329 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000330
331 // Done. Everything else is run-time checks.
Anders Carlsson714179b2009-08-02 19:07:59 +0000332 Kind = CastExpr::CK_Dynamic;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000333}
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000334
335/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
336/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
337/// like this:
338/// const char *str = "literal";
339/// legacy_function(const_cast\<char*\>(str));
340void
341CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000342 const SourceRange &OpRange, const SourceRange &DestRange) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000343 if (!DestType->isLValueReferenceType())
344 Self.DefaultFunctionArrayConversion(SrcExpr);
345
346 unsigned msg = diag::err_bad_cxx_cast_generic;
347 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
348 && msg != 0)
349 Self.Diag(OpRange.getBegin(), msg) << CT_Const
350 << SrcExpr->getType() << DestType << OpRange;
351}
352
353/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
354/// valid.
355/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
356/// like this:
357/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
358void
359CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000360 const SourceRange &OpRange, const SourceRange &DestRange,
361 CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000362 if (!DestType->isLValueReferenceType())
363 Self.DefaultFunctionArrayConversion(SrcExpr);
364
365 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000366 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, Kind,
367 OpRange, msg)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000368 != TC_Success && msg != 0)
369 Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
370 << SrcExpr->getType() << DestType << OpRange;
371}
372
373
374/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
375/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
376/// implicit conversions explicit and getting rid of data loss warnings.
377void
378CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson0aebc812009-09-09 21:33:21 +0000379 const SourceRange &OpRange, CastExpr::CastKind &Kind,
380 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000381 // This test is outside everything else because it's the only case where
382 // a non-lvalue-reference target type does not lead to decay.
383 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
384 if (DestType->isVoidType()) {
385 return;
386 }
387
388 if (!DestType->isLValueReferenceType())
389 Self.DefaultFunctionArrayConversion(SrcExpr);
390
391 unsigned msg = diag::err_bad_cxx_cast_generic;
Mike Stump1eb44332009-09-09 15:08:12 +0000392 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, Kind,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000393 OpRange, msg, ConversionDecl)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000394 != TC_Success && msg != 0)
395 Self.Diag(OpRange.getBegin(), msg) << CT_Static
396 << SrcExpr->getType() << DestType << OpRange;
397}
398
399/// TryStaticCast - Check if a static cast can be performed, and do so if
400/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
401/// and casting away constness.
402static TryCastResult TryStaticCast(Sema &Self, Expr *SrcExpr,
403 QualType DestType, bool CStyle,
Mike Stump1eb44332009-09-09 15:08:12 +0000404 CastExpr::CastKind &Kind,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000405 const SourceRange &OpRange, unsigned &msg,
Mike Stump1eb44332009-09-09 15:08:12 +0000406 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000407 // The order the tests is not entirely arbitrary. There is one conversion
408 // that can be handled in two different ways. Given:
409 // struct A {};
410 // struct B : public A {
411 // B(); B(const A&);
412 // };
413 // const A &a = B();
414 // the cast static_cast<const B&>(a) could be seen as either a static
415 // reference downcast, or an explicit invocation of the user-defined
416 // conversion using B's conversion constructor.
417 // DR 427 specifies that the downcast is to be applied here.
418
419 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
420 // Done outside this function.
421
422 TryCastResult tcr;
423
424 // C++ 5.2.9p5, reference downcast.
425 // See the function for details.
426 // DR 427 specifies that this is to be applied before paragraph 2.
427 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle,OpRange,msg);
428 if (tcr != TC_NotApplicable)
429 return tcr;
430
431 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
432 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
433 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
434 if (tcr != TC_NotApplicable)
435 return tcr;
436
437 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
438 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000439 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
440 ConversionDecl);
Anders Carlsson0aebc812009-09-09 21:33:21 +0000441 if (tcr != TC_NotApplicable) {
442 if (ConversionDecl) {
443 if (isa<CXXConstructorDecl>(ConversionDecl))
444 Kind = CastExpr::CK_ConstructorConversion;
445 else if (isa<CXXConversionDecl>(ConversionDecl))
446 Kind = CastExpr::CK_UserDefinedConversion;
447 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000448 return tcr;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000449 }
450
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000451 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
452 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
453 // conversions, subject to further restrictions.
454 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
455 // of qualification conversions impossible.
456 // In the CStyle case, the earlier attempt to const_cast should have taken
457 // care of reverse qualification conversions.
458
459 QualType OrigSrcType = SrcExpr->getType();
460
461 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
462
463 // Reverse integral promotion/conversion. All such conversions are themselves
464 // again integral promotions or conversions and are thus already handled by
465 // p2 (TryDirectInitialization above).
466 // (Note: any data loss warnings should be suppressed.)
467 // The exception is the reverse of enum->integer, i.e. integer->enum (and
468 // enum->enum). See also C++ 5.2.9p7.
469 // The same goes for reverse floating point promotion/conversion and
470 // floating-integral conversions. Again, only floating->enum is relevant.
471 if (DestType->isEnumeralType()) {
472 if (SrcType->isComplexType() || SrcType->isVectorType()) {
473 // Fall through - these cannot be converted.
474 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType())
475 return TC_Success;
476 }
477
478 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
479 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
480 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg);
481 if (tcr != TC_NotApplicable)
482 return tcr;
483
484 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
485 // conversion. C++ 5.2.9p9 has additional information.
486 // DR54's access restrictions apply here also.
487 tcr = TryStaticMemberPointerUpcast(Self, SrcType, DestType, CStyle,
488 OpRange, msg);
489 if (tcr != TC_NotApplicable)
490 return tcr;
491
492 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
493 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
494 // just the usual constness stuff.
Ted Kremenek6217b802009-07-29 21:53:49 +0000495 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000496 QualType SrcPointee = SrcPointer->getPointeeType();
497 if (SrcPointee->isVoidType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000498 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000499 QualType DestPointee = DestPointer->getPointeeType();
500 if (DestPointee->isIncompleteOrObjectType()) {
501 // This is definitely the intended conversion, but it might fail due
502 // to a const violation.
503 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
504 msg = diag::err_bad_cxx_cast_const_away;
505 return TC_Failed;
506 }
507 return TC_Success;
508 }
509 }
510 }
511 }
512
513 // We tried everything. Everything! Nothing works! :-(
514 return TC_NotApplicable;
515}
516
517/// Tests whether a conversion according to N2844 is valid.
518TryCastResult
519TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000520 unsigned &msg) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000521 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
522 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenek6217b802009-07-29 21:53:49 +0000523 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000524 if (!R)
525 return TC_NotApplicable;
526
527 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
528 return TC_NotApplicable;
529
530 // Because we try the reference downcast before this function, from now on
531 // this is the only cast possibility, so we issue an error if we fail now.
532 // FIXME: Should allow casting away constness if CStyle.
533 bool DerivedToBase;
534 if (Self.CompareReferenceRelationship(SrcExpr->getType(), R->getPointeeType(),
535 DerivedToBase) <
536 Sema::Ref_Compatible_With_Added_Qualification) {
537 msg = diag::err_bad_lvalue_to_rvalue_cast;
538 return TC_Failed;
539 }
540
541 // FIXME: Similar to CheckReferenceInit, we actually need more AST annotation
542 // than nothing.
543 return TC_Success;
544}
545
546/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
547TryCastResult
548TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
549 bool CStyle, const SourceRange &OpRange,
Mike Stump1eb44332009-09-09 15:08:12 +0000550 unsigned &msg) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000551 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
552 // cast to type "reference to cv2 D", where D is a class derived from B,
553 // if a valid standard conversion from "pointer to D" to "pointer to B"
554 // exists, cv2 >= cv1, and B is not a virtual base class of D.
555 // In addition, DR54 clarifies that the base must be accessible in the
556 // current context. Although the wording of DR54 only applies to the pointer
557 // variant of this rule, the intent is clearly for it to apply to the this
558 // conversion as well.
559
Ted Kremenek6217b802009-07-29 21:53:49 +0000560 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000561 if (!DestReference) {
562 return TC_NotApplicable;
563 }
564 bool RValueRef = DestReference->isRValueReferenceType();
565 if (!RValueRef && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
566 // We know the left side is an lvalue reference, so we can suggest a reason.
567 msg = diag::err_bad_cxx_cast_rvalue;
568 return TC_NotApplicable;
569 }
570
571 QualType DestPointee = DestReference->getPointeeType();
572
573 return TryStaticDowncast(Self, SrcExpr->getType(), DestPointee, CStyle,
574 OpRange, SrcExpr->getType(), DestType, msg);
575}
576
577/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
578TryCastResult
579TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000580 bool CStyle, const SourceRange &OpRange,
581 unsigned &msg) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000582 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
583 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
584 // is a class derived from B, if a valid standard conversion from "pointer
585 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
586 // class of D.
587 // In addition, DR54 clarifies that the base must be accessible in the
588 // current context.
589
Ted Kremenek6217b802009-07-29 21:53:49 +0000590 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000591 if (!DestPointer) {
592 return TC_NotApplicable;
593 }
594
Ted Kremenek6217b802009-07-29 21:53:49 +0000595 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000596 if (!SrcPointer) {
597 msg = diag::err_bad_static_cast_pointer_nonpointer;
598 return TC_NotApplicable;
599 }
600
601 return TryStaticDowncast(Self, SrcPointer->getPointeeType(),
602 DestPointer->getPointeeType(), CStyle,
603 OpRange, SrcType, DestType, msg);
604}
605
606/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
607/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
608/// DestType, both of which must be canonical, is possible and allowed.
609TryCastResult
610TryStaticDowncast(Sema &Self, QualType SrcType, QualType DestType,
611 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Mike Stump1eb44332009-09-09 15:08:12 +0000612 QualType OrigDestType, unsigned &msg) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000613 // Downcast can only happen in class hierarchies, so we need classes.
614 if (!DestType->isRecordType() || !SrcType->isRecordType()) {
615 return TC_NotApplicable;
616 }
617
618 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
619 /*DetectVirtual=*/true);
620 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
621 return TC_NotApplicable;
622 }
623
624 // Target type does derive from source type. Now we're serious. If an error
625 // appears now, it's not ignored.
626 // This may not be entirely in line with the standard. Take for example:
627 // struct A {};
628 // struct B : virtual A {
629 // B(A&);
630 // };
Mike Stump1eb44332009-09-09 15:08:12 +0000631 //
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000632 // void f()
633 // {
634 // (void)static_cast<const B&>(*((A*)0));
635 // }
636 // As far as the standard is concerned, p5 does not apply (A is virtual), so
637 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
638 // However, both GCC and Comeau reject this example, and accepting it would
639 // mean more complex code if we're to preserve the nice error message.
640 // FIXME: Being 100% compliant here would be nice to have.
641
642 // Must preserve cv, as always, unless we're in C-style mode.
643 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
644 msg = diag::err_bad_cxx_cast_const_away;
645 return TC_Failed;
646 }
647
648 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
649 // This code is analoguous to that in CheckDerivedToBaseConversion, except
650 // that it builds the paths in reverse order.
651 // To sum up: record all paths to the base and build a nice string from
652 // them. Use it to spice up the error message.
653 if (!Paths.isRecordingPaths()) {
654 Paths.clear();
655 Paths.setRecordingPaths(true);
656 Self.IsDerivedFrom(DestType, SrcType, Paths);
657 }
658 std::string PathDisplayStr;
659 std::set<unsigned> DisplayedPaths;
660 for (BasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
661 PI != PE; ++PI) {
662 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
663 // We haven't displayed a path to this particular base
664 // class subobject yet.
665 PathDisplayStr += "\n ";
666 for (BasePath::const_reverse_iterator EI = PI->rbegin(),EE = PI->rend();
667 EI != EE; ++EI)
668 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
669 PathDisplayStr += DestType.getAsString();
670 }
671 }
672
673 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
674 << SrcType.getUnqualifiedType() << DestType.getUnqualifiedType()
675 << PathDisplayStr << OpRange;
676 msg = 0;
677 return TC_Failed;
678 }
679
680 if (Paths.getDetectedVirtual() != 0) {
681 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
682 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
683 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
684 msg = 0;
685 return TC_Failed;
686 }
687
688 if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
689 diag::err_downcast_from_inaccessible_base, Paths,
690 OpRange.getBegin(), DeclarationName())) {
691 msg = 0;
692 return TC_Failed;
693 }
694
695 return TC_Success;
696}
697
698/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
699/// C++ 5.2.9p9 is valid:
700///
701/// An rvalue of type "pointer to member of D of type cv1 T" can be
702/// converted to an rvalue of type "pointer to member of B of type cv2 T",
703/// where B is a base class of D [...].
704///
705TryCastResult
706TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType, QualType DestType,
707 bool CStyle, const SourceRange &OpRange,
Mike Stump1eb44332009-09-09 15:08:12 +0000708 unsigned &msg) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000709 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000710 if (!DestMemPtr)
711 return TC_NotApplicable;
Ted Kremenek6217b802009-07-29 21:53:49 +0000712 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000713 if (!SrcMemPtr) {
714 msg = diag::err_bad_static_cast_member_pointer_nonmp;
715 return TC_NotApplicable;
716 }
717
718 // T == T, modulo cv
719 if (Self.Context.getCanonicalType(
720 SrcMemPtr->getPointeeType().getUnqualifiedType()) !=
721 Self.Context.getCanonicalType(DestMemPtr->getPointeeType().
722 getUnqualifiedType()))
723 return TC_NotApplicable;
724
725 // B base of D
726 QualType SrcClass(SrcMemPtr->getClass(), 0);
727 QualType DestClass(DestMemPtr->getClass(), 0);
728 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
729 /*DetectVirtual=*/true);
730 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
731 return TC_NotApplicable;
732 }
733
734 // B is a base of D. But is it an allowed base? If not, it's a hard error.
735 if (Paths.isAmbiguous(DestClass)) {
736 Paths.clear();
737 Paths.setRecordingPaths(true);
738 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
739 assert(StillOkay);
740 StillOkay = StillOkay;
741 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
742 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
743 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
744 msg = 0;
745 return TC_Failed;
746 }
747
748 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
749 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
750 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
751 msg = 0;
752 return TC_Failed;
753 }
754
755 if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
756 diag::err_downcast_from_inaccessible_base, Paths,
757 OpRange.getBegin(), DeclarationName())) {
758 msg = 0;
759 return TC_Failed;
760 }
761
762 return TC_Success;
763}
764
765/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
766/// is valid:
767///
768/// An expression e can be explicitly converted to a type T using a
769/// @c static_cast if the declaration "T t(e);" is well-formed [...].
770TryCastResult
771TryStaticImplicitCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000772 bool CStyle, const SourceRange &OpRange, unsigned &msg,
Mike Stump1eb44332009-09-09 15:08:12 +0000773 CXXMethodDecl *&ConversionDecl) {
Anders Carlssond851b372009-09-07 18:25:47 +0000774 if (DestType->isRecordType()) {
775 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
776 diag::err_bad_dynamic_cast_incomplete)) {
777 msg = 0;
778 return TC_Failed;
779 }
780 }
Mike Stump1eb44332009-09-09 15:08:12 +0000781
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000782 if (DestType->isReferenceType()) {
783 // At this point of CheckStaticCast, if the destination is a reference,
784 // this has to work. There is no other way that works.
785 // On the other hand, if we're checking a C-style cast, we've still got
786 // the reinterpret_cast way. In that case, we pass an ICS so we don't
787 // get error messages.
788 ImplicitConversionSequence ICS;
Mike Stump1eb44332009-09-09 15:08:12 +0000789 bool failed = Self.CheckReferenceInit(SrcExpr, DestType,
Douglas Gregor739d8282009-09-23 23:04:10 +0000790 OpRange.getBegin(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000791 /*SuppressUserConversions=*/false,
792 /*AllowExplicit=*/false,
793 /*ForceRValue=*/false,
794 CStyle ? &ICS : 0);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000795 if (!failed)
796 return TC_Success;
797 if (CStyle)
798 return TC_NotApplicable;
799 // If we didn't pass the ICS, we already got an error message.
800 msg = 0;
801 return TC_Failed;
802 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000803
804 // FIXME: To get a proper error from invalid conversions here, we need to
805 // reimplement more of this.
806 // FIXME: This does not actually perform the conversion, and thus does not
807 // check for ambiguity or access.
Mike Stump1eb44332009-09-09 15:08:12 +0000808 ImplicitConversionSequence ICS =
Anders Carlssonda7a18b2009-08-27 17:24:15 +0000809 Self.TryImplicitConversion(SrcExpr, DestType,
810 /*SuppressUserConversions=*/false,
Anders Carlsson83b534c2009-08-28 16:22:20 +0000811 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +0000812 /*ForceRValue=*/false,
813 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +0000814
Anders Carlsson0aebc812009-09-09 21:33:21 +0000815 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion) {
Mike Stump1eb44332009-09-09 15:08:12 +0000816 if (CXXMethodDecl *MD =
Fariborz Jahanian4fc7ab32009-08-28 15:11:24 +0000817 dyn_cast<CXXMethodDecl>(ICS.UserDefined.ConversionFunction))
818 ConversionDecl = MD;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000819 }
820
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000821 return ICS.ConversionKind == ImplicitConversionSequence::BadConversion ?
822 TC_NotApplicable : TC_Success;
823}
824
825/// TryConstCast - See if a const_cast from source to destination is allowed,
826/// and perform it if it is.
827static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
828 bool CStyle, unsigned &msg) {
829 DestType = Self.Context.getCanonicalType(DestType);
830 QualType SrcType = SrcExpr->getType();
831 if (const LValueReferenceType *DestTypeTmp =
Ted Kremenek6217b802009-07-29 21:53:49 +0000832 DestType->getAs<LValueReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000833 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
834 // Cannot const_cast non-lvalue to lvalue reference type. But if this
835 // is C-style, static_cast might find a way, so we simply suggest a
836 // message and tell the parent to keep searching.
837 msg = diag::err_bad_cxx_cast_rvalue;
838 return TC_NotApplicable;
839 }
840
841 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
842 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
843 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
844 SrcType = Self.Context.getPointerType(SrcType);
845 }
846
847 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
848 // the rules for const_cast are the same as those used for pointers.
849
850 if (!DestType->isPointerType() && !DestType->isMemberPointerType()) {
851 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
852 // was a reference type, we converted it to a pointer above.
853 // The status of rvalue references isn't entirely clear, but it looks like
854 // conversion to them is simply invalid.
855 // C++ 5.2.11p3: For two pointer types [...]
856 if (!CStyle)
857 msg = diag::err_bad_const_cast_dest;
858 return TC_NotApplicable;
859 }
860 if (DestType->isFunctionPointerType() ||
861 DestType->isMemberFunctionPointerType()) {
862 // Cannot cast direct function pointers.
863 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
864 // T is the ultimate pointee of source and target type.
865 if (!CStyle)
866 msg = diag::err_bad_const_cast_dest;
867 return TC_NotApplicable;
868 }
869 SrcType = Self.Context.getCanonicalType(SrcType);
870
871 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
872 // completely equal.
873 // FIXME: const_cast should probably not be able to convert between pointers
874 // to different address spaces.
875 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
876 // in multi-level pointers may change, but the level count must be the same,
877 // as must be the final pointee type.
878 while (SrcType != DestType &&
879 Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
880 SrcType = SrcType.getUnqualifiedType();
881 DestType = DestType.getUnqualifiedType();
882 }
883
884 // Since we're dealing in canonical types, the remainder must be the same.
885 if (SrcType != DestType)
886 return TC_NotApplicable;
887
888 return TC_Success;
889}
890
891static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
892 QualType DestType, bool CStyle,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000893 CastExpr::CastKind &Kind,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000894 const SourceRange &OpRange,
895 unsigned &msg) {
896 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
897
898 DestType = Self.Context.getCanonicalType(DestType);
899 QualType SrcType = SrcExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000900 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000901 bool LValue = DestTypeTmp->isLValueReferenceType();
902 if (LValue && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
903 // Cannot cast non-lvalue to reference type. See the similar comment in
904 // const_cast.
905 msg = diag::err_bad_cxx_cast_rvalue;
906 return TC_NotApplicable;
907 }
908
909 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
910 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
911 // built-in & and * operators.
912 // This code does this transformation for the checked types.
913 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
914 SrcType = Self.Context.getPointerType(SrcType);
915 }
916
917 // Canonicalize source for comparison.
918 SrcType = Self.Context.getCanonicalType(SrcType);
919
Ted Kremenek6217b802009-07-29 21:53:49 +0000920 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
921 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000922 if (DestMemPtr && SrcMemPtr) {
923 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
924 // can be explicitly converted to an rvalue of type "pointer to member
925 // of Y of type T2" if T1 and T2 are both function types or both object
926 // types.
927 if (DestMemPtr->getPointeeType()->isFunctionType() !=
928 SrcMemPtr->getPointeeType()->isFunctionType())
929 return TC_NotApplicable;
930
931 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
932 // constness.
933 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
934 // we accept it.
935 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
936 msg = diag::err_bad_cxx_cast_const_away;
937 return TC_Failed;
938 }
939
940 // A valid member pointer cast.
941 return TC_Success;
942 }
943
944 // See below for the enumeral issue.
945 if (SrcType->isNullPtrType() && DestType->isIntegralType() &&
946 !DestType->isEnumeralType()) {
947 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
948 // type large enough to hold it. A value of std::nullptr_t can be
949 // converted to an integral type; the conversion has the same meaning
950 // and validity as a conversion of (void*)0 to the integral type.
951 if (Self.Context.getTypeSize(SrcType) >
952 Self.Context.getTypeSize(DestType)) {
953 msg = diag::err_bad_reinterpret_cast_small_int;
954 return TC_Failed;
955 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000956 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000957 return TC_Success;
958 }
959
Anders Carlsson0de51bc2009-09-16 19:19:43 +0000960 bool destIsVector = DestType->isVectorType();
961 bool srcIsVector = SrcType->isVectorType();
962 if (srcIsVector || destIsVector) {
963 bool srcIsScalar = SrcType->isIntegralType() && !SrcType->isEnumeralType();
964 bool destIsScalar =
965 DestType->isIntegralType() && !DestType->isEnumeralType();
966
967 // Check if this is a cast between a vector and something else.
968 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
969 !(srcIsVector && destIsVector))
970 return TC_NotApplicable;
971
972 // If both types have the same size, we can successfully cast.
973 if (Self.Context.getTypeSize(SrcType) == Self.Context.getTypeSize(DestType))
974 return TC_Success;
975
976 if (destIsScalar)
977 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
978 else if (srcIsScalar)
979 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
980 else
981 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
982
983 return TC_Failed;
984 }
985
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000986 bool destIsPtr = DestType->isPointerType();
987 bool srcIsPtr = SrcType->isPointerType();
988 if (!destIsPtr && !srcIsPtr) {
989 // Except for std::nullptr_t->integer and lvalue->reference, which are
990 // handled above, at least one of the two arguments must be a pointer.
991 return TC_NotApplicable;
992 }
993
994 if (SrcType == DestType) {
995 // C++ 5.2.10p2 has a note that mentions that, subject to all other
996 // restrictions, a cast to the same type is allowed. The intent is not
997 // entirely clear here, since all other paragraphs explicitly forbid casts
998 // to the same type. However, the behavior of compilers is pretty consistent
999 // on this point: allow same-type conversion if the involved types are
1000 // pointers, disallow otherwise.
1001 return TC_Success;
1002 }
1003
1004 // Note: Clang treats enumeration types as integral types. If this is ever
1005 // changed for C++, the additional check here will be redundant.
1006 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
1007 assert(srcIsPtr && "One type must be a pointer");
1008 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1009 // type large enough to hold it.
1010 if (Self.Context.getTypeSize(SrcType) >
1011 Self.Context.getTypeSize(DestType)) {
1012 msg = diag::err_bad_reinterpret_cast_small_int;
1013 return TC_Failed;
1014 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001015 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001016 return TC_Success;
1017 }
1018
1019 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
1020 assert(destIsPtr && "One type must be a pointer");
1021 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1022 // converted to a pointer.
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001023 Kind = CastExpr::CK_IntegralToPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001024 return TC_Success;
1025 }
1026
1027 if (!destIsPtr || !srcIsPtr) {
1028 // With the valid non-pointer conversions out of the way, we can be even
1029 // more stringent.
1030 return TC_NotApplicable;
1031 }
1032
1033 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1034 // The C-style cast operator can.
1035 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1036 msg = diag::err_bad_cxx_cast_const_away;
1037 return TC_Failed;
1038 }
1039
1040 // Not casting away constness, so the only remaining check is for compatible
1041 // pointer categories.
1042
1043 if (SrcType->isFunctionPointerType()) {
1044 if (DestType->isFunctionPointerType()) {
1045 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1046 // a pointer to a function of a different type.
1047 return TC_Success;
1048 }
1049
1050 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1051 // an object type or vice versa is conditionally-supported.
1052 // Compilers support it in C++03 too, though, because it's necessary for
1053 // casting the return value of dlsym() and GetProcAddress().
1054 // FIXME: Conditionally-supported behavior should be configurable in the
1055 // TargetInfo or similar.
1056 if (!Self.getLangOptions().CPlusPlus0x)
1057 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1058 return TC_Success;
1059 }
1060
1061 if (DestType->isFunctionPointerType()) {
1062 // See above.
1063 if (!Self.getLangOptions().CPlusPlus0x)
1064 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1065 return TC_Success;
1066 }
1067
1068 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1069 // a pointer to an object of different type.
1070 // Void pointers are not specified, but supported by every compiler out there.
1071 // So we finish by allowing everything that remains - it's got to be two
1072 // object pointers.
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001073 Kind = CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001074 return TC_Success;
1075}
1076
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00001077bool Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00001078 CastExpr::CastKind &Kind, bool FunctionalStyle,
Mike Stump1eb44332009-09-09 15:08:12 +00001079 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001080 // This test is outside everything else because it's the only case where
1081 // a non-lvalue-reference target type does not lead to decay.
1082 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1083 if (CastTy->isVoidType())
1084 return false;
1085
1086 // If the type is dependent, we won't do any other semantic analysis now.
1087 if (CastTy->isDependentType() || CastExpr->isTypeDependent())
1088 return false;
1089
1090 if (!CastTy->isLValueReferenceType())
1091 DefaultFunctionArrayConversion(CastExpr);
1092
1093 // C++ [expr.cast]p5: The conversions performed by
1094 // - a const_cast,
1095 // - a static_cast,
1096 // - a static_cast followed by a const_cast,
1097 // - a reinterpret_cast, or
1098 // - a reinterpret_cast followed by a const_cast,
1099 // can be performed using the cast notation of explicit type conversion.
1100 // [...] If a conversion can be interpreted in more than one of the ways
1101 // listed above, the interpretation that appears first in the list is used,
1102 // even if a cast resulting from that interpretation is ill-formed.
1103 // In plain language, this means trying a const_cast ...
1104 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001105 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1106 msg);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001107 if (tcr == TC_NotApplicable) {
1108 // ... or if that is not possible, a static_cast, ignoring const, ...
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001109 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, Kind, R, msg,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00001110 ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001111 if (tcr == TC_NotApplicable) {
1112 // ... and finally a reinterpret_cast, ignoring const.
Mike Stump1eb44332009-09-09 15:08:12 +00001113 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, Kind,
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001114 R, msg);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001115 }
1116 }
1117
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001118 if (tcr != TC_Success && msg != 0)
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00001119 Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001120 << CastExpr->getType() << CastTy << R;
1121
1122 return tcr != TC_Success;
1123}