blob: 9822a44b0f8ed2c1ead224b3f83e77f10f215652 [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,
Anders Carlsson3c31a392009-09-26 00:12:34 +000091 CastExpr::CastKind &Kind,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +000092 CXXMethodDecl *&ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000093static TryCastResult TryStaticCast(Sema &Self, Expr *SrcExpr,
94 QualType DestType, bool CStyle,
95 const SourceRange &OpRange,
Anders Carlssoncb3c3082009-09-01 20:52:42 +000096 unsigned &msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +000097 CastExpr::CastKind &Kind,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +000098 CXXMethodDecl *&ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000099static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
100 bool CStyle, unsigned &msg);
101static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
102 QualType DestType, bool CStyle,
103 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000104 unsigned &msg,
105 CastExpr::CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +0000106
Sebastian Redl26d85b12008-11-05 21:50:06 +0000107/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000108Action::OwningExprResult
Sebastian Redl26d85b12008-11-05 21:50:06 +0000109Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
110 SourceLocation LAngleBracketLoc, TypeTy *Ty,
111 SourceLocation RAngleBracketLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000112 SourceLocation LParenLoc, ExprArg E,
Sebastian Redl26d85b12008-11-05 21:50:06 +0000113 SourceLocation RParenLoc) {
Anders Carlssone9146f22009-05-01 19:49:17 +0000114 Expr *Ex = E.takeAs<Expr>();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000115 // FIXME: Preserve type source info.
116 QualType DestType = GetTypeFromParser(Ty);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000117 SourceRange OpRange(OpLoc, RParenLoc);
118 SourceRange DestRange(LAngleBracketLoc, RAngleBracketLoc);
119
Douglas Gregor9103bb22008-12-17 22:52:20 +0000120 // If the type is dependent, we won't do the semantic analysis now.
121 // FIXME: should we check this in a more fine-grained manner?
122 bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
123
Sebastian Redl26d85b12008-11-05 21:50:06 +0000124 switch (Kind) {
125 default: assert(0 && "Unknown C++ cast!");
126
127 case tok::kw_const_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +0000128 if (!TypeDependent)
129 CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000130 return Owned(new (Context) CXXConstCastExpr(DestType.getNonReferenceType(),
131 Ex, DestType, OpLoc));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000132
Anders Carlsson714179b2009-08-02 19:07:59 +0000133 case tok::kw_dynamic_cast: {
134 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregor9103bb22008-12-17 22:52:20 +0000135 if (!TypeDependent)
Anders Carlsson714179b2009-08-02 19:07:59 +0000136 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000137 return Owned(new (Context)CXXDynamicCastExpr(DestType.getNonReferenceType(),
Anders Carlsson714179b2009-08-02 19:07:59 +0000138 Kind, Ex, DestType, OpLoc));
139 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000140 case tok::kw_reinterpret_cast: {
141 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregor9103bb22008-12-17 22:52:20 +0000142 if (!TypeDependent)
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000143 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000144 return Owned(new (Context) CXXReinterpretCastExpr(
145 DestType.getNonReferenceType(),
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000146 Kind, Ex, DestType, OpLoc));
147 }
Anders Carlssoncdb61972009-08-07 22:21:05 +0000148 case tok::kw_static_cast: {
149 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000150 if (!TypeDependent) {
151 CXXMethodDecl *Method = 0;
152
153 CheckStaticCast(*this, Ex, DestType, OpRange, Kind, Method);
154
155 if (Method) {
156 OwningExprResult CastArg
157 = BuildCXXCastArgument(OpLoc, DestType.getNonReferenceType(),
158 Kind, Method, Owned(Ex));
159 if (CastArg.isInvalid())
160 return ExprError();
161
162 Ex = CastArg.takeAs<Expr>();
163 }
164 }
165
Sebastian Redlf53597f2009-03-15 17:47:39 +0000166 return Owned(new (Context) CXXStaticCastExpr(DestType.getNonReferenceType(),
Anders Carlssoncdb61972009-08-07 22:21:05 +0000167 Kind, Ex, DestType, OpLoc));
168 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000169 }
170
Sebastian Redlf53597f2009-03-15 17:47:39 +0000171 return ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000172}
173
Sebastian Redldb647282009-01-27 23:18:31 +0000174/// CastsAwayConstness - Check if the pointer conversion from SrcType to
175/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
176/// the cast checkers. Both arguments must denote pointer (possibly to member)
177/// types.
Sebastian Redl26d85b12008-11-05 21:50:06 +0000178bool
Mike Stump1eb44332009-09-09 15:08:12 +0000179CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
Sebastian Redldb647282009-01-27 23:18:31 +0000180 // Casting away constness is defined in C++ 5.2.11p8 with reference to
181 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
182 // the rules are non-trivial. So first we construct Tcv *...cv* as described
183 // in C++ 5.2.11p8.
184 assert((SrcType->isPointerType() || SrcType->isMemberPointerType()) &&
185 "Source type is not pointer or pointer to member.");
186 assert((DestType->isPointerType() || DestType->isMemberPointerType()) &&
187 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000188
189 QualType UnwrappedSrcType = SrcType, UnwrappedDestType = DestType;
John McCall0953e762009-09-24 19:53:00 +0000190 llvm::SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000191
192 // Find the qualifications.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000193 while (Self.UnwrapSimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCall0953e762009-09-24 19:53:00 +0000194 cv1.push_back(UnwrappedSrcType.getQualifiers());
195 cv2.push_back(UnwrappedDestType.getQualifiers());
Sebastian Redl26d85b12008-11-05 21:50:06 +0000196 }
197 assert(cv1.size() > 0 && "Must have at least one pointer level.");
198
199 // Construct void pointers with those qualifiers (in reverse order of
200 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000201 QualType SrcConstruct = Self.Context.VoidTy;
202 QualType DestConstruct = Self.Context.VoidTy;
John McCall0953e762009-09-24 19:53:00 +0000203 ASTContext &Context = Self.Context;
204 for (llvm::SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
205 i2 = cv2.rbegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000206 i1 != cv1.rend(); ++i1, ++i2) {
John McCall0953e762009-09-24 19:53:00 +0000207 SrcConstruct
208 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
209 DestConstruct
210 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000211 }
212
213 // Test if they're compatible.
214 return SrcConstruct != DestConstruct &&
Sebastian Redl37d6de32008-11-08 13:00:26 +0000215 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000216}
217
Sebastian Redl26d85b12008-11-05 21:50:06 +0000218/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
219/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
220/// checked downcasts in class hierarchies.
Anders Carlsson714179b2009-08-02 19:07:59 +0000221static void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000222CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
223 const SourceRange &OpRange,
Mike Stump1eb44332009-09-09 15:08:12 +0000224 const SourceRange &DestRange, CastExpr::CastKind &Kind) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000225 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl37d6de32008-11-08 13:00:26 +0000226 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000227
228 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
229 // or "pointer to cv void".
230
231 QualType DestPointee;
Ted Kremenek6217b802009-07-29 21:53:49 +0000232 const PointerType *DestPointer = DestType->getAs<PointerType>();
233 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000234 if (DestPointer) {
235 DestPointee = DestPointer->getPointeeType();
236 } else if (DestReference) {
237 DestPointee = DestReference->getPointeeType();
238 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000239 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000240 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000241 return;
242 }
243
Ted Kremenek6217b802009-07-29 21:53:49 +0000244 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000245 if (DestPointee->isVoidType()) {
246 assert(DestPointer && "Reference to void is not possible");
247 } else if (DestRecord) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000248 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000249 PDiag(diag::err_bad_dynamic_cast_incomplete)
250 << DestRange))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000251 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000252 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000253 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000254 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000255 return;
256 }
257
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000258 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
259 // complete class type, [...]. If T is an lvalue reference type, v shall be
260 // an lvalue of a complete class type, [...]. If T is an rvalue reference
261 // type, v shall be an expression having a complete effective class type,
262 // [...]
Sebastian Redl26d85b12008-11-05 21:50:06 +0000263
Sebastian Redl37d6de32008-11-08 13:00:26 +0000264 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000265 QualType SrcPointee;
266 if (DestPointer) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000267 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000268 SrcPointee = SrcPointer->getPointeeType();
269 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000270 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000271 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000272 return;
273 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000274 } else if (DestReference->isLValueReferenceType()) {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000275 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000276 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000277 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000278 }
279 SrcPointee = SrcType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000280 } else {
281 SrcPointee = SrcType;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000282 }
283
Ted Kremenek6217b802009-07-29 21:53:49 +0000284 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000285 if (SrcRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000286 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000287 PDiag(diag::err_bad_dynamic_cast_incomplete)
288 << SrcExpr->getSourceRange()))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000289 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000290 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000291 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000292 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000293 return;
294 }
295
296 assert((DestPointer || DestReference) &&
297 "Bad destination non-ptr/ref slipped through.");
298 assert((DestRecord || DestPointee->isVoidType()) &&
299 "Bad destination pointee slipped through.");
300 assert(SrcRecord && "Bad source pointee slipped through.");
301
302 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
303 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000304 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000305 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000306 return;
307 }
308
309 // C++ 5.2.7p3: If the type of v is the same as the required result type,
310 // [except for cv].
311 if (DestRecord == SrcRecord) {
312 return;
313 }
314
315 // C++ 5.2.7p5
316 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000317 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
318 Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
Chris Lattnerd1625842008-11-24 06:25:27 +0000319 OpRange.getBegin(), OpRange);
Anders Carlsson714179b2009-08-02 19:07:59 +0000320 Kind = CastExpr::CK_DerivedToBase;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000321 // Diagnostic already emitted on error.
322 return;
323 }
324
325 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Sebastian Redl37d6de32008-11-08 13:00:26 +0000326 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(Self.Context);
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000327 assert(SrcDecl && "Definition missing");
328 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000329 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000330 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000331 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000332
333 // Done. Everything else is run-time checks.
Anders Carlsson714179b2009-08-02 19:07:59 +0000334 Kind = CastExpr::CK_Dynamic;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000335}
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000336
337/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
338/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
339/// like this:
340/// const char *str = "literal";
341/// legacy_function(const_cast\<char*\>(str));
342void
343CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000344 const SourceRange &OpRange, const SourceRange &DestRange) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000345 if (!DestType->isLValueReferenceType())
346 Self.DefaultFunctionArrayConversion(SrcExpr);
347
348 unsigned msg = diag::err_bad_cxx_cast_generic;
349 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
350 && msg != 0)
351 Self.Diag(OpRange.getBegin(), msg) << CT_Const
352 << SrcExpr->getType() << DestType << OpRange;
353}
354
355/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
356/// valid.
357/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
358/// like this:
359/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
360void
361CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000362 const SourceRange &OpRange, const SourceRange &DestRange,
363 CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000364 if (!DestType->isLValueReferenceType())
365 Self.DefaultFunctionArrayConversion(SrcExpr);
366
367 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson3c31a392009-09-26 00:12:34 +0000368 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
369 msg, Kind)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000370 != TC_Success && msg != 0)
371 Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
372 << SrcExpr->getType() << DestType << OpRange;
373}
374
375
376/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
377/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
378/// implicit conversions explicit and getting rid of data loss warnings.
379void
380CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson0aebc812009-09-09 21:33:21 +0000381 const SourceRange &OpRange, CastExpr::CastKind &Kind,
382 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000383 // This test is outside everything else because it's the only case where
384 // a non-lvalue-reference target type does not lead to decay.
385 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
386 if (DestType->isVoidType()) {
387 return;
388 }
389
390 if (!DestType->isLValueReferenceType())
391 Self.DefaultFunctionArrayConversion(SrcExpr);
392
393 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson3c31a392009-09-26 00:12:34 +0000394 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false,OpRange, msg,
395 Kind, ConversionDecl)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000396 != TC_Success && msg != 0)
397 Self.Diag(OpRange.getBegin(), msg) << CT_Static
398 << SrcExpr->getType() << DestType << OpRange;
399}
400
401/// TryStaticCast - Check if a static cast can be performed, and do so if
402/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
403/// and casting away constness.
404static TryCastResult TryStaticCast(Sema &Self, Expr *SrcExpr,
405 QualType DestType, bool CStyle,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000406 const SourceRange &OpRange, unsigned &msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000407 CastExpr::CastKind &Kind,
Mike Stump1eb44332009-09-09 15:08:12 +0000408 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000409 // The order the tests is not entirely arbitrary. There is one conversion
410 // that can be handled in two different ways. Given:
411 // struct A {};
412 // struct B : public A {
413 // B(); B(const A&);
414 // };
415 // const A &a = B();
416 // the cast static_cast<const B&>(a) could be seen as either a static
417 // reference downcast, or an explicit invocation of the user-defined
418 // conversion using B's conversion constructor.
419 // DR 427 specifies that the downcast is to be applied here.
420
421 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
422 // Done outside this function.
423
424 TryCastResult tcr;
425
426 // C++ 5.2.9p5, reference downcast.
427 // See the function for details.
428 // DR 427 specifies that this is to be applied before paragraph 2.
429 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle,OpRange,msg);
430 if (tcr != TC_NotApplicable)
431 return tcr;
432
433 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
434 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
435 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
436 if (tcr != TC_NotApplicable)
437 return tcr;
438
439 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
440 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000441 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000442 Kind, ConversionDecl);
443 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000444 return tcr;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000445
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000446 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
447 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
448 // conversions, subject to further restrictions.
449 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
450 // of qualification conversions impossible.
451 // In the CStyle case, the earlier attempt to const_cast should have taken
452 // care of reverse qualification conversions.
453
454 QualType OrigSrcType = SrcExpr->getType();
455
456 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
457
458 // Reverse integral promotion/conversion. All such conversions are themselves
459 // again integral promotions or conversions and are thus already handled by
460 // p2 (TryDirectInitialization above).
461 // (Note: any data loss warnings should be suppressed.)
462 // The exception is the reverse of enum->integer, i.e. integer->enum (and
463 // enum->enum). See also C++ 5.2.9p7.
464 // The same goes for reverse floating point promotion/conversion and
465 // floating-integral conversions. Again, only floating->enum is relevant.
466 if (DestType->isEnumeralType()) {
467 if (SrcType->isComplexType() || SrcType->isVectorType()) {
468 // Fall through - these cannot be converted.
469 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType())
470 return TC_Success;
471 }
472
473 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
474 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
475 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg);
476 if (tcr != TC_NotApplicable)
477 return tcr;
478
479 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
480 // conversion. C++ 5.2.9p9 has additional information.
481 // DR54's access restrictions apply here also.
482 tcr = TryStaticMemberPointerUpcast(Self, SrcType, DestType, CStyle,
483 OpRange, msg);
484 if (tcr != TC_NotApplicable)
485 return tcr;
486
487 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
488 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
489 // just the usual constness stuff.
Ted Kremenek6217b802009-07-29 21:53:49 +0000490 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000491 QualType SrcPointee = SrcPointer->getPointeeType();
492 if (SrcPointee->isVoidType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000493 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000494 QualType DestPointee = DestPointer->getPointeeType();
495 if (DestPointee->isIncompleteOrObjectType()) {
496 // This is definitely the intended conversion, but it might fail due
497 // to a const violation.
498 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
499 msg = diag::err_bad_cxx_cast_const_away;
500 return TC_Failed;
501 }
502 return TC_Success;
503 }
504 }
505 }
506 }
507
508 // We tried everything. Everything! Nothing works! :-(
509 return TC_NotApplicable;
510}
511
512/// Tests whether a conversion according to N2844 is valid.
513TryCastResult
514TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000515 unsigned &msg) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000516 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
517 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenek6217b802009-07-29 21:53:49 +0000518 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000519 if (!R)
520 return TC_NotApplicable;
521
522 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
523 return TC_NotApplicable;
524
525 // Because we try the reference downcast before this function, from now on
526 // this is the only cast possibility, so we issue an error if we fail now.
527 // FIXME: Should allow casting away constness if CStyle.
528 bool DerivedToBase;
529 if (Self.CompareReferenceRelationship(SrcExpr->getType(), R->getPointeeType(),
530 DerivedToBase) <
531 Sema::Ref_Compatible_With_Added_Qualification) {
532 msg = diag::err_bad_lvalue_to_rvalue_cast;
533 return TC_Failed;
534 }
535
536 // FIXME: Similar to CheckReferenceInit, we actually need more AST annotation
537 // than nothing.
538 return TC_Success;
539}
540
541/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
542TryCastResult
543TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
544 bool CStyle, const SourceRange &OpRange,
Mike Stump1eb44332009-09-09 15:08:12 +0000545 unsigned &msg) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000546 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
547 // cast to type "reference to cv2 D", where D is a class derived from B,
548 // if a valid standard conversion from "pointer to D" to "pointer to B"
549 // exists, cv2 >= cv1, and B is not a virtual base class of D.
550 // In addition, DR54 clarifies that the base must be accessible in the
551 // current context. Although the wording of DR54 only applies to the pointer
552 // variant of this rule, the intent is clearly for it to apply to the this
553 // conversion as well.
554
Ted Kremenek6217b802009-07-29 21:53:49 +0000555 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000556 if (!DestReference) {
557 return TC_NotApplicable;
558 }
559 bool RValueRef = DestReference->isRValueReferenceType();
560 if (!RValueRef && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
561 // We know the left side is an lvalue reference, so we can suggest a reason.
562 msg = diag::err_bad_cxx_cast_rvalue;
563 return TC_NotApplicable;
564 }
565
566 QualType DestPointee = DestReference->getPointeeType();
567
568 return TryStaticDowncast(Self, SrcExpr->getType(), DestPointee, CStyle,
569 OpRange, SrcExpr->getType(), DestType, msg);
570}
571
572/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
573TryCastResult
574TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000575 bool CStyle, const SourceRange &OpRange,
576 unsigned &msg) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000577 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
578 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
579 // is a class derived from B, if a valid standard conversion from "pointer
580 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
581 // class of D.
582 // In addition, DR54 clarifies that the base must be accessible in the
583 // current context.
584
Ted Kremenek6217b802009-07-29 21:53:49 +0000585 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000586 if (!DestPointer) {
587 return TC_NotApplicable;
588 }
589
Ted Kremenek6217b802009-07-29 21:53:49 +0000590 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000591 if (!SrcPointer) {
592 msg = diag::err_bad_static_cast_pointer_nonpointer;
593 return TC_NotApplicable;
594 }
595
596 return TryStaticDowncast(Self, SrcPointer->getPointeeType(),
597 DestPointer->getPointeeType(), CStyle,
598 OpRange, SrcType, DestType, msg);
599}
600
601/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
602/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
603/// DestType, both of which must be canonical, is possible and allowed.
604TryCastResult
605TryStaticDowncast(Sema &Self, QualType SrcType, QualType DestType,
606 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Mike Stump1eb44332009-09-09 15:08:12 +0000607 QualType OrigDestType, unsigned &msg) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000608 // Downcast can only happen in class hierarchies, so we need classes.
609 if (!DestType->isRecordType() || !SrcType->isRecordType()) {
610 return TC_NotApplicable;
611 }
612
613 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
614 /*DetectVirtual=*/true);
615 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
616 return TC_NotApplicable;
617 }
618
619 // Target type does derive from source type. Now we're serious. If an error
620 // appears now, it's not ignored.
621 // This may not be entirely in line with the standard. Take for example:
622 // struct A {};
623 // struct B : virtual A {
624 // B(A&);
625 // };
Mike Stump1eb44332009-09-09 15:08:12 +0000626 //
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000627 // void f()
628 // {
629 // (void)static_cast<const B&>(*((A*)0));
630 // }
631 // As far as the standard is concerned, p5 does not apply (A is virtual), so
632 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
633 // However, both GCC and Comeau reject this example, and accepting it would
634 // mean more complex code if we're to preserve the nice error message.
635 // FIXME: Being 100% compliant here would be nice to have.
636
637 // Must preserve cv, as always, unless we're in C-style mode.
638 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
639 msg = diag::err_bad_cxx_cast_const_away;
640 return TC_Failed;
641 }
642
643 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
644 // This code is analoguous to that in CheckDerivedToBaseConversion, except
645 // that it builds the paths in reverse order.
646 // To sum up: record all paths to the base and build a nice string from
647 // them. Use it to spice up the error message.
648 if (!Paths.isRecordingPaths()) {
649 Paths.clear();
650 Paths.setRecordingPaths(true);
651 Self.IsDerivedFrom(DestType, SrcType, Paths);
652 }
653 std::string PathDisplayStr;
654 std::set<unsigned> DisplayedPaths;
655 for (BasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
656 PI != PE; ++PI) {
657 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
658 // We haven't displayed a path to this particular base
659 // class subobject yet.
660 PathDisplayStr += "\n ";
661 for (BasePath::const_reverse_iterator EI = PI->rbegin(),EE = PI->rend();
662 EI != EE; ++EI)
663 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
664 PathDisplayStr += DestType.getAsString();
665 }
666 }
667
668 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
669 << SrcType.getUnqualifiedType() << DestType.getUnqualifiedType()
670 << PathDisplayStr << OpRange;
671 msg = 0;
672 return TC_Failed;
673 }
674
675 if (Paths.getDetectedVirtual() != 0) {
676 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
677 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
678 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
679 msg = 0;
680 return TC_Failed;
681 }
682
683 if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
684 diag::err_downcast_from_inaccessible_base, Paths,
685 OpRange.getBegin(), DeclarationName())) {
686 msg = 0;
687 return TC_Failed;
688 }
689
690 return TC_Success;
691}
692
693/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
694/// C++ 5.2.9p9 is valid:
695///
696/// An rvalue of type "pointer to member of D of type cv1 T" can be
697/// converted to an rvalue of type "pointer to member of B of type cv2 T",
698/// where B is a base class of D [...].
699///
700TryCastResult
701TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType, QualType DestType,
702 bool CStyle, const SourceRange &OpRange,
Mike Stump1eb44332009-09-09 15:08:12 +0000703 unsigned &msg) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000704 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000705 if (!DestMemPtr)
706 return TC_NotApplicable;
Ted Kremenek6217b802009-07-29 21:53:49 +0000707 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000708 if (!SrcMemPtr) {
709 msg = diag::err_bad_static_cast_member_pointer_nonmp;
710 return TC_NotApplicable;
711 }
712
713 // T == T, modulo cv
714 if (Self.Context.getCanonicalType(
715 SrcMemPtr->getPointeeType().getUnqualifiedType()) !=
716 Self.Context.getCanonicalType(DestMemPtr->getPointeeType().
717 getUnqualifiedType()))
718 return TC_NotApplicable;
719
720 // B base of D
721 QualType SrcClass(SrcMemPtr->getClass(), 0);
722 QualType DestClass(DestMemPtr->getClass(), 0);
723 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
724 /*DetectVirtual=*/true);
725 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
726 return TC_NotApplicable;
727 }
728
729 // B is a base of D. But is it an allowed base? If not, it's a hard error.
730 if (Paths.isAmbiguous(DestClass)) {
731 Paths.clear();
732 Paths.setRecordingPaths(true);
733 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
734 assert(StillOkay);
735 StillOkay = StillOkay;
736 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
737 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
738 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
739 msg = 0;
740 return TC_Failed;
741 }
742
743 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
744 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
745 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
746 msg = 0;
747 return TC_Failed;
748 }
749
750 if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
751 diag::err_downcast_from_inaccessible_base, Paths,
752 OpRange.getBegin(), DeclarationName())) {
753 msg = 0;
754 return TC_Failed;
755 }
756
757 return TC_Success;
758}
759
760/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
761/// is valid:
762///
763/// An expression e can be explicitly converted to a type T using a
764/// @c static_cast if the declaration "T t(e);" is well-formed [...].
765TryCastResult
766TryStaticImplicitCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000767 bool CStyle, const SourceRange &OpRange, unsigned &msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000768 CastExpr::CastKind &Kind,
Mike Stump1eb44332009-09-09 15:08:12 +0000769 CXXMethodDecl *&ConversionDecl) {
Anders Carlssond851b372009-09-07 18:25:47 +0000770 if (DestType->isRecordType()) {
771 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
772 diag::err_bad_dynamic_cast_incomplete)) {
773 msg = 0;
774 return TC_Failed;
775 }
776 }
Mike Stump1eb44332009-09-09 15:08:12 +0000777
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000778 if (DestType->isReferenceType()) {
779 // At this point of CheckStaticCast, if the destination is a reference,
780 // this has to work. There is no other way that works.
781 // On the other hand, if we're checking a C-style cast, we've still got
782 // the reinterpret_cast way. In that case, we pass an ICS so we don't
783 // get error messages.
784 ImplicitConversionSequence ICS;
Mike Stump1eb44332009-09-09 15:08:12 +0000785 bool failed = Self.CheckReferenceInit(SrcExpr, DestType,
Douglas Gregor739d8282009-09-23 23:04:10 +0000786 OpRange.getBegin(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000787 /*SuppressUserConversions=*/false,
788 /*AllowExplicit=*/false,
789 /*ForceRValue=*/false,
790 CStyle ? &ICS : 0);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000791 if (!failed)
792 return TC_Success;
793 if (CStyle)
794 return TC_NotApplicable;
795 // If we didn't pass the ICS, we already got an error message.
796 msg = 0;
797 return TC_Failed;
798 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000799
800 // FIXME: To get a proper error from invalid conversions here, we need to
801 // reimplement more of this.
802 // FIXME: This does not actually perform the conversion, and thus does not
803 // check for ambiguity or access.
Mike Stump1eb44332009-09-09 15:08:12 +0000804 ImplicitConversionSequence ICS =
Anders Carlssonda7a18b2009-08-27 17:24:15 +0000805 Self.TryImplicitConversion(SrcExpr, DestType,
806 /*SuppressUserConversions=*/false,
Anders Carlsson83b534c2009-08-28 16:22:20 +0000807 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +0000808 /*ForceRValue=*/false,
Fariborz Jahanian249cead2009-10-01 20:39:51 +0000809 /*InOverloadResolution=*/false,
810 /*one of user provided casts*/true);
Mike Stump1eb44332009-09-09 15:08:12 +0000811
Anders Carlsson3c31a392009-09-26 00:12:34 +0000812 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
813 return TC_NotApplicable;
814
Anders Carlsson0aebc812009-09-09 21:33:21 +0000815 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion) {
Anders Carlsson3c31a392009-09-26 00:12:34 +0000816 ConversionDecl = cast<CXXMethodDecl>(ICS.UserDefined.ConversionFunction);
817 if (isa<CXXConstructorDecl>(ConversionDecl))
818 Kind = CastExpr::CK_ConstructorConversion;
819 else if (isa<CXXConversionDecl>(ConversionDecl))
820 Kind = CastExpr::CK_UserDefinedConversion;
821 } else if (ICS.ConversionKind ==
822 ImplicitConversionSequence::StandardConversion) {
823 // FIXME: Set the cast kind depending on which types of conversions we have.
Anders Carlsson0aebc812009-09-09 21:33:21 +0000824 }
Anders Carlsson3c31a392009-09-26 00:12:34 +0000825
826 return TC_Success;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000827}
828
829/// TryConstCast - See if a const_cast from source to destination is allowed,
830/// and perform it if it is.
831static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
832 bool CStyle, unsigned &msg) {
833 DestType = Self.Context.getCanonicalType(DestType);
834 QualType SrcType = SrcExpr->getType();
835 if (const LValueReferenceType *DestTypeTmp =
Ted Kremenek6217b802009-07-29 21:53:49 +0000836 DestType->getAs<LValueReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000837 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
838 // Cannot const_cast non-lvalue to lvalue reference type. But if this
839 // is C-style, static_cast might find a way, so we simply suggest a
840 // message and tell the parent to keep searching.
841 msg = diag::err_bad_cxx_cast_rvalue;
842 return TC_NotApplicable;
843 }
844
845 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
846 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
847 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
848 SrcType = Self.Context.getPointerType(SrcType);
849 }
850
851 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
852 // the rules for const_cast are the same as those used for pointers.
853
854 if (!DestType->isPointerType() && !DestType->isMemberPointerType()) {
855 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
856 // was a reference type, we converted it to a pointer above.
857 // The status of rvalue references isn't entirely clear, but it looks like
858 // conversion to them is simply invalid.
859 // C++ 5.2.11p3: For two pointer types [...]
860 if (!CStyle)
861 msg = diag::err_bad_const_cast_dest;
862 return TC_NotApplicable;
863 }
864 if (DestType->isFunctionPointerType() ||
865 DestType->isMemberFunctionPointerType()) {
866 // Cannot cast direct function pointers.
867 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
868 // T is the ultimate pointee of source and target type.
869 if (!CStyle)
870 msg = diag::err_bad_const_cast_dest;
871 return TC_NotApplicable;
872 }
873 SrcType = Self.Context.getCanonicalType(SrcType);
874
875 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
876 // completely equal.
877 // FIXME: const_cast should probably not be able to convert between pointers
878 // to different address spaces.
879 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
880 // in multi-level pointers may change, but the level count must be the same,
881 // as must be the final pointee type.
882 while (SrcType != DestType &&
883 Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
884 SrcType = SrcType.getUnqualifiedType();
885 DestType = DestType.getUnqualifiedType();
886 }
887
888 // Since we're dealing in canonical types, the remainder must be the same.
889 if (SrcType != DestType)
890 return TC_NotApplicable;
891
892 return TC_Success;
893}
894
895static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
896 QualType DestType, bool CStyle,
897 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000898 unsigned &msg,
899 CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000900 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
901
902 DestType = Self.Context.getCanonicalType(DestType);
903 QualType SrcType = SrcExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000904 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000905 bool LValue = DestTypeTmp->isLValueReferenceType();
906 if (LValue && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
907 // Cannot cast non-lvalue to reference type. See the similar comment in
908 // const_cast.
909 msg = diag::err_bad_cxx_cast_rvalue;
910 return TC_NotApplicable;
911 }
912
913 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
914 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
915 // built-in & and * operators.
916 // This code does this transformation for the checked types.
917 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
918 SrcType = Self.Context.getPointerType(SrcType);
919 }
920
921 // Canonicalize source for comparison.
922 SrcType = Self.Context.getCanonicalType(SrcType);
923
Ted Kremenek6217b802009-07-29 21:53:49 +0000924 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
925 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000926 if (DestMemPtr && SrcMemPtr) {
927 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
928 // can be explicitly converted to an rvalue of type "pointer to member
929 // of Y of type T2" if T1 and T2 are both function types or both object
930 // types.
931 if (DestMemPtr->getPointeeType()->isFunctionType() !=
932 SrcMemPtr->getPointeeType()->isFunctionType())
933 return TC_NotApplicable;
934
935 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
936 // constness.
937 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
938 // we accept it.
939 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
940 msg = diag::err_bad_cxx_cast_const_away;
941 return TC_Failed;
942 }
943
944 // A valid member pointer cast.
945 return TC_Success;
946 }
947
948 // See below for the enumeral issue.
949 if (SrcType->isNullPtrType() && DestType->isIntegralType() &&
950 !DestType->isEnumeralType()) {
951 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
952 // type large enough to hold it. A value of std::nullptr_t can be
953 // converted to an integral type; the conversion has the same meaning
954 // and validity as a conversion of (void*)0 to the integral type.
955 if (Self.Context.getTypeSize(SrcType) >
956 Self.Context.getTypeSize(DestType)) {
957 msg = diag::err_bad_reinterpret_cast_small_int;
958 return TC_Failed;
959 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000960 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000961 return TC_Success;
962 }
963
Anders Carlsson0de51bc2009-09-16 19:19:43 +0000964 bool destIsVector = DestType->isVectorType();
965 bool srcIsVector = SrcType->isVectorType();
966 if (srcIsVector || destIsVector) {
967 bool srcIsScalar = SrcType->isIntegralType() && !SrcType->isEnumeralType();
968 bool destIsScalar =
969 DestType->isIntegralType() && !DestType->isEnumeralType();
970
971 // Check if this is a cast between a vector and something else.
972 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
973 !(srcIsVector && destIsVector))
974 return TC_NotApplicable;
975
976 // If both types have the same size, we can successfully cast.
977 if (Self.Context.getTypeSize(SrcType) == Self.Context.getTypeSize(DestType))
978 return TC_Success;
979
980 if (destIsScalar)
981 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
982 else if (srcIsScalar)
983 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
984 else
985 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
986
987 return TC_Failed;
988 }
989
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000990 bool destIsPtr = DestType->isPointerType();
991 bool srcIsPtr = SrcType->isPointerType();
992 if (!destIsPtr && !srcIsPtr) {
993 // Except for std::nullptr_t->integer and lvalue->reference, which are
994 // handled above, at least one of the two arguments must be a pointer.
995 return TC_NotApplicable;
996 }
997
998 if (SrcType == DestType) {
999 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1000 // restrictions, a cast to the same type is allowed. The intent is not
1001 // entirely clear here, since all other paragraphs explicitly forbid casts
1002 // to the same type. However, the behavior of compilers is pretty consistent
1003 // on this point: allow same-type conversion if the involved types are
1004 // pointers, disallow otherwise.
1005 return TC_Success;
1006 }
1007
1008 // Note: Clang treats enumeration types as integral types. If this is ever
1009 // changed for C++, the additional check here will be redundant.
1010 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
1011 assert(srcIsPtr && "One type must be a pointer");
1012 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1013 // type large enough to hold it.
1014 if (Self.Context.getTypeSize(SrcType) >
1015 Self.Context.getTypeSize(DestType)) {
1016 msg = diag::err_bad_reinterpret_cast_small_int;
1017 return TC_Failed;
1018 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001019 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001020 return TC_Success;
1021 }
1022
1023 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
1024 assert(destIsPtr && "One type must be a pointer");
1025 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1026 // converted to a pointer.
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001027 Kind = CastExpr::CK_IntegralToPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001028 return TC_Success;
1029 }
1030
1031 if (!destIsPtr || !srcIsPtr) {
1032 // With the valid non-pointer conversions out of the way, we can be even
1033 // more stringent.
1034 return TC_NotApplicable;
1035 }
1036
1037 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1038 // The C-style cast operator can.
1039 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1040 msg = diag::err_bad_cxx_cast_const_away;
1041 return TC_Failed;
1042 }
1043
1044 // Not casting away constness, so the only remaining check is for compatible
1045 // pointer categories.
1046
1047 if (SrcType->isFunctionPointerType()) {
1048 if (DestType->isFunctionPointerType()) {
1049 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1050 // a pointer to a function of a different type.
1051 return TC_Success;
1052 }
1053
1054 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1055 // an object type or vice versa is conditionally-supported.
1056 // Compilers support it in C++03 too, though, because it's necessary for
1057 // casting the return value of dlsym() and GetProcAddress().
1058 // FIXME: Conditionally-supported behavior should be configurable in the
1059 // TargetInfo or similar.
1060 if (!Self.getLangOptions().CPlusPlus0x)
1061 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1062 return TC_Success;
1063 }
1064
1065 if (DestType->isFunctionPointerType()) {
1066 // See above.
1067 if (!Self.getLangOptions().CPlusPlus0x)
1068 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1069 return TC_Success;
1070 }
1071
1072 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1073 // a pointer to an object of different type.
1074 // Void pointers are not specified, but supported by every compiler out there.
1075 // So we finish by allowing everything that remains - it's got to be two
1076 // object pointers.
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001077 Kind = CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001078 return TC_Success;
1079}
1080
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00001081bool Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00001082 CastExpr::CastKind &Kind, bool FunctionalStyle,
Mike Stump1eb44332009-09-09 15:08:12 +00001083 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001084 // This test is outside everything else because it's the only case where
1085 // a non-lvalue-reference target type does not lead to decay.
1086 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1087 if (CastTy->isVoidType())
1088 return false;
1089
1090 // If the type is dependent, we won't do any other semantic analysis now.
1091 if (CastTy->isDependentType() || CastExpr->isTypeDependent())
1092 return false;
1093
1094 if (!CastTy->isLValueReferenceType())
1095 DefaultFunctionArrayConversion(CastExpr);
1096
1097 // C++ [expr.cast]p5: The conversions performed by
1098 // - a const_cast,
1099 // - a static_cast,
1100 // - a static_cast followed by a const_cast,
1101 // - a reinterpret_cast, or
1102 // - a reinterpret_cast followed by a const_cast,
1103 // can be performed using the cast notation of explicit type conversion.
1104 // [...] If a conversion can be interpreted in more than one of the ways
1105 // listed above, the interpretation that appears first in the list is used,
1106 // even if a cast resulting from that interpretation is ill-formed.
1107 // In plain language, this means trying a const_cast ...
1108 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001109 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1110 msg);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001111 if (tcr == TC_NotApplicable) {
1112 // ... or if that is not possible, a static_cast, ignoring const, ...
Anders Carlsson3c31a392009-09-26 00:12:34 +00001113 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1114 Kind, ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001115 if (tcr == TC_NotApplicable) {
1116 // ... and finally a reinterpret_cast, ignoring const.
Anders Carlsson3c31a392009-09-26 00:12:34 +00001117 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1118 Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001119 }
1120 }
1121
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001122 if (tcr != TC_Success && msg != 0)
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00001123 Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001124 << CastExpr->getType() << CastTy << R;
1125
1126 return tcr != TC_Success;
1127}