blob: 254af541710d5c3dba93d30409fc3306bcc1e08f [file] [log] [blame]
Sebastian Redl2b6b14c2008-11-05 21:50:06 +00001//===--- SemaNamedCast.cpp - Semantic Analysis for Named Casts ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ named casts.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "SemaInherit.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/ASTContext.h"
Sebastian Redl2b6b14c2008-11-05 21:50:06 +000018#include "llvm/ADT/SmallVector.h"
Sebastian Redl0528e1c2008-11-07 23:29:29 +000019#include <set>
Sebastian Redl2b6b14c2008-11-05 21:50:06 +000020using namespace clang;
21
Sebastian Redl0e35d042009-07-25 15:41:38 +000022enum TryCastResult {
23 TC_NotApplicable, ///< The cast method is not applicable.
24 TC_Success, ///< The cast method is appropriate and successful.
25 TC_Failed ///< The cast method is appropriate, but failed. A
26 ///< diagnostic has been emitted.
27};
28
29enum CastType {
30 CT_Const, ///< const_cast
31 CT_Static, ///< static_cast
32 CT_Reinterpret, ///< reinterpret_cast
33 CT_Dynamic, ///< dynamic_cast
34 CT_CStyle, ///< (Type)expr
35 CT_Functional ///< Type(expr)
Sebastian Redlf831eeb2008-11-08 13:00:26 +000036};
37
38static void CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
39 const SourceRange &OpRange,
40 const SourceRange &DestRange);
41static void CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
42 const SourceRange &OpRange,
43 const SourceRange &DestRange);
44static void CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
45 const SourceRange &OpRange);
46static void CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
47 const SourceRange &OpRange,
Anders Carlsson1ecbf592009-08-02 19:07:59 +000048 const SourceRange &DestRange,
49 CastExpr::CastKind &Kind);
Sebastian Redlf831eeb2008-11-08 13:00:26 +000050
51static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
Sebastian Redl0e35d042009-07-25 15:41:38 +000052
53// The Try functions attempt a specific way of casting. If they succeed, they
54// return TC_Success. If their way of casting is not appropriate for the given
55// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
56// to emit if no other way succeeds. If their way of casting is appropriate but
57// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
58// they emit a specialized diagnostic.
59// All diagnostics returned by these functions must expect the same three
60// arguments:
61// %0: Cast Type (a value from the CastType enumeration)
62// %1: Source Type
63// %2: Destination Type
64static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
65 QualType DestType, unsigned &msg);
66static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
67 QualType DestType, bool CStyle,
68 const SourceRange &OpRange,
69 unsigned &msg);
70static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
71 QualType DestType, bool CStyle,
72 const SourceRange &OpRange,
73 unsigned &msg);
74static TryCastResult TryStaticDowncast(Sema &Self, QualType SrcType,
75 QualType DestType, bool CStyle,
76 const SourceRange &OpRange,
77 QualType OrigSrcType,
78 QualType OrigDestType, unsigned &msg);
79static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType,
80 QualType DestType,bool CStyle,
81 const SourceRange &OpRange,
82 unsigned &msg);
83static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *SrcExpr,
84 QualType DestType, bool CStyle,
85 const SourceRange &OpRange,
86 unsigned &msg);
87static TryCastResult TryStaticCast(Sema &Self, Expr *SrcExpr,
88 QualType DestType, bool CStyle,
89 const SourceRange &OpRange,
90 unsigned &msg);
91static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
92 bool CStyle, unsigned &msg);
93static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
94 QualType DestType, bool CStyle,
95 const SourceRange &OpRange,
96 unsigned &msg);
Sebastian Redlf831eeb2008-11-08 13:00:26 +000097
Sebastian Redl2b6b14c2008-11-05 21:50:06 +000098/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +000099Action::OwningExprResult
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000100Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
101 SourceLocation LAngleBracketLoc, TypeTy *Ty,
102 SourceLocation RAngleBracketLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000103 SourceLocation LParenLoc, ExprArg E,
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000104 SourceLocation RParenLoc) {
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000105 Expr *Ex = E.takeAs<Expr>();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000106 QualType DestType = QualType::getFromOpaquePtr(Ty);
107 SourceRange OpRange(OpLoc, RParenLoc);
108 SourceRange DestRange(LAngleBracketLoc, RAngleBracketLoc);
109
Douglas Gregore6be68a2008-12-17 22:52:20 +0000110 // If the type is dependent, we won't do the semantic analysis now.
111 // FIXME: should we check this in a more fine-grained manner?
112 bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
113
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000114 switch (Kind) {
115 default: assert(0 && "Unknown C++ cast!");
116
117 case tok::kw_const_cast:
Douglas Gregore6be68a2008-12-17 22:52:20 +0000118 if (!TypeDependent)
119 CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000120 return Owned(new (Context) CXXConstCastExpr(DestType.getNonReferenceType(),
121 Ex, DestType, OpLoc));
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000122
Anders Carlsson1ecbf592009-08-02 19:07:59 +0000123 case tok::kw_dynamic_cast: {
124 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregore6be68a2008-12-17 22:52:20 +0000125 if (!TypeDependent)
Anders Carlsson1ecbf592009-08-02 19:07:59 +0000126 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000127 return Owned(new (Context)CXXDynamicCastExpr(DestType.getNonReferenceType(),
Anders Carlsson1ecbf592009-08-02 19:07:59 +0000128 Kind, Ex, DestType, OpLoc));
129 }
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000130 case tok::kw_reinterpret_cast:
Douglas Gregore6be68a2008-12-17 22:52:20 +0000131 if (!TypeDependent)
132 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000133 return Owned(new (Context) CXXReinterpretCastExpr(
134 DestType.getNonReferenceType(),
135 Ex, DestType, OpLoc));
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000136
137 case tok::kw_static_cast:
Douglas Gregore6be68a2008-12-17 22:52:20 +0000138 if (!TypeDependent)
139 CheckStaticCast(*this, Ex, DestType, OpRange);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000140 return Owned(new (Context) CXXStaticCastExpr(DestType.getNonReferenceType(),
Anders Carlsson7ef181c2009-07-31 00:48:10 +0000141 CastExpr::CK_Unknown, Ex,
142 DestType, OpLoc));
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000143 }
144
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000145 return ExprError();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000146}
147
Sebastian Redl04b3f352009-01-27 23:18:31 +0000148/// CastsAwayConstness - Check if the pointer conversion from SrcType to
149/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
150/// the cast checkers. Both arguments must denote pointer (possibly to member)
151/// types.
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000152bool
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000153CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000154{
Sebastian Redl04b3f352009-01-27 23:18:31 +0000155 // Casting away constness is defined in C++ 5.2.11p8 with reference to
156 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
157 // the rules are non-trivial. So first we construct Tcv *...cv* as described
158 // in C++ 5.2.11p8.
159 assert((SrcType->isPointerType() || SrcType->isMemberPointerType()) &&
160 "Source type is not pointer or pointer to member.");
161 assert((DestType->isPointerType() || DestType->isMemberPointerType()) &&
162 "Destination type is not pointer or pointer to member.");
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000163
164 QualType UnwrappedSrcType = SrcType, UnwrappedDestType = DestType;
165 llvm::SmallVector<unsigned, 8> cv1, cv2;
166
167 // Find the qualifications.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000168 while (Self.UnwrapSimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000169 cv1.push_back(UnwrappedSrcType.getCVRQualifiers());
170 cv2.push_back(UnwrappedDestType.getCVRQualifiers());
171 }
172 assert(cv1.size() > 0 && "Must have at least one pointer level.");
173
174 // Construct void pointers with those qualifiers (in reverse order of
175 // unwrapping, of course).
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000176 QualType SrcConstruct = Self.Context.VoidTy;
177 QualType DestConstruct = Self.Context.VoidTy;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000178 for (llvm::SmallVector<unsigned, 8>::reverse_iterator i1 = cv1.rbegin(),
179 i2 = cv2.rbegin();
180 i1 != cv1.rend(); ++i1, ++i2)
181 {
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000182 SrcConstruct = Self.Context.getPointerType(
183 SrcConstruct.getQualifiedType(*i1));
184 DestConstruct = Self.Context.getPointerType(
185 DestConstruct.getQualifiedType(*i2));
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000186 }
187
188 // Test if they're compatible.
189 return SrcConstruct != DestConstruct &&
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000190 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000191}
192
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000193/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
194/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
195/// checked downcasts in class hierarchies.
Anders Carlsson1ecbf592009-08-02 19:07:59 +0000196static void
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000197CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
198 const SourceRange &OpRange,
Anders Carlsson1ecbf592009-08-02 19:07:59 +0000199 const SourceRange &DestRange, CastExpr::CastKind &Kind)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000200{
201 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000202 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000203
204 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
205 // or "pointer to cv void".
206
207 QualType DestPointee;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000208 const PointerType *DestPointer = DestType->getAs<PointerType>();
209 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000210 if (DestPointer) {
211 DestPointee = DestPointer->getPointeeType();
212 } else if (DestReference) {
213 DestPointee = DestReference->getPointeeType();
214 } else {
Chris Lattner70b93d82008-11-18 22:52:51 +0000215 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000216 << OrigDestType << DestRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000217 return;
218 }
219
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000220 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000221 if (DestPointee->isVoidType()) {
222 assert(DestPointer && "Reference to void is not possible");
223 } else if (DestRecord) {
Sebastian Redl0e35d042009-07-25 15:41:38 +0000224 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor46fe06e2009-01-19 19:26:10 +0000225 diag::err_bad_dynamic_cast_incomplete,
226 DestRange))
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000227 return;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000228 } else {
Chris Lattner70b93d82008-11-18 22:52:51 +0000229 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000230 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000231 return;
232 }
233
Sebastian Redlce6fff02009-03-16 23:22:08 +0000234 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
235 // complete class type, [...]. If T is an lvalue reference type, v shall be
236 // an lvalue of a complete class type, [...]. If T is an rvalue reference
237 // type, v shall be an expression having a complete effective class type,
238 // [...]
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000239
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000240 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000241 QualType SrcPointee;
242 if (DestPointer) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000243 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000244 SrcPointee = SrcPointer->getPointeeType();
245 } else {
Chris Lattner70b93d82008-11-18 22:52:51 +0000246 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000247 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000248 return;
249 }
Sebastian Redlce6fff02009-03-16 23:22:08 +0000250 } else if (DestReference->isLValueReferenceType()) {
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000251 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattner70b93d82008-11-18 22:52:51 +0000252 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl0e35d042009-07-25 15:41:38 +0000253 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000254 }
255 SrcPointee = SrcType;
Sebastian Redlce6fff02009-03-16 23:22:08 +0000256 } else {
257 SrcPointee = SrcType;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000258 }
259
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000260 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000261 if (SrcRecord) {
Douglas Gregorc84d8932009-03-09 16:13:40 +0000262 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor46fe06e2009-01-19 19:26:10 +0000263 diag::err_bad_dynamic_cast_incomplete,
264 SrcExpr->getSourceRange()))
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000265 return;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000266 } else {
Chris Lattner77d52da2008-11-20 06:06:08 +0000267 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000268 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000269 return;
270 }
271
272 assert((DestPointer || DestReference) &&
273 "Bad destination non-ptr/ref slipped through.");
274 assert((DestRecord || DestPointee->isVoidType()) &&
275 "Bad destination pointee slipped through.");
276 assert(SrcRecord && "Bad source pointee slipped through.");
277
278 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
279 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +0000280 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl0e35d042009-07-25 15:41:38 +0000281 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000282 return;
283 }
284
285 // C++ 5.2.7p3: If the type of v is the same as the required result type,
286 // [except for cv].
287 if (DestRecord == SrcRecord) {
288 return;
289 }
290
291 // C++ 5.2.7p5
292 // Upcasts are resolved statically.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000293 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
294 Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
Chris Lattner4bfd2232008-11-24 06:25:27 +0000295 OpRange.getBegin(), OpRange);
Anders Carlsson1ecbf592009-08-02 19:07:59 +0000296 Kind = CastExpr::CK_DerivedToBase;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000297 // Diagnostic already emitted on error.
298 return;
299 }
300
301 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000302 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(Self.Context);
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000303 assert(SrcDecl && "Definition missing");
304 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner77d52da2008-11-20 06:06:08 +0000305 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000306 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000307 }
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000308
309 // Done. Everything else is run-time checks.
Anders Carlsson1ecbf592009-08-02 19:07:59 +0000310 Kind = CastExpr::CK_Dynamic;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000311}
Sebastian Redl0e35d042009-07-25 15:41:38 +0000312
313/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
314/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
315/// like this:
316/// const char *str = "literal";
317/// legacy_function(const_cast\<char*\>(str));
318void
319CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
320 const SourceRange &OpRange, const SourceRange &DestRange)
321{
322 if (!DestType->isLValueReferenceType())
323 Self.DefaultFunctionArrayConversion(SrcExpr);
324
325 unsigned msg = diag::err_bad_cxx_cast_generic;
326 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
327 && msg != 0)
328 Self.Diag(OpRange.getBegin(), msg) << CT_Const
329 << SrcExpr->getType() << DestType << OpRange;
330}
331
332/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
333/// valid.
334/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
335/// like this:
336/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
337void
338CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
339 const SourceRange &OpRange, const SourceRange &DestRange)
340{
341 if (!DestType->isLValueReferenceType())
342 Self.DefaultFunctionArrayConversion(SrcExpr);
343
344 unsigned msg = diag::err_bad_cxx_cast_generic;
345 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg)
346 != TC_Success && msg != 0)
347 Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
348 << SrcExpr->getType() << DestType << OpRange;
349}
350
351
352/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
353/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
354/// implicit conversions explicit and getting rid of data loss warnings.
355void
356CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
357 const SourceRange &OpRange)
358{
359 // This test is outside everything else because it's the only case where
360 // a non-lvalue-reference target type does not lead to decay.
361 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
362 if (DestType->isVoidType()) {
363 return;
364 }
365
366 if (!DestType->isLValueReferenceType())
367 Self.DefaultFunctionArrayConversion(SrcExpr);
368
369 unsigned msg = diag::err_bad_cxx_cast_generic;
370 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg)
371 != TC_Success && msg != 0)
372 Self.Diag(OpRange.getBegin(), msg) << CT_Static
373 << SrcExpr->getType() << DestType << OpRange;
374}
375
376/// TryStaticCast - Check if a static cast can be performed, and do so if
377/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
378/// and casting away constness.
379static TryCastResult TryStaticCast(Sema &Self, Expr *SrcExpr,
380 QualType DestType, bool CStyle,
381 const SourceRange &OpRange,
382 unsigned &msg)
383{
384 // The order the tests is not entirely arbitrary. There is one conversion
385 // that can be handled in two different ways. Given:
386 // struct A {};
387 // struct B : public A {
388 // B(); B(const A&);
389 // };
390 // const A &a = B();
391 // the cast static_cast<const B&>(a) could be seen as either a static
392 // reference downcast, or an explicit invocation of the user-defined
393 // conversion using B's conversion constructor.
394 // DR 427 specifies that the downcast is to be applied here.
395
396 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
397 // Done outside this function.
398
399 TryCastResult tcr;
400
401 // C++ 5.2.9p5, reference downcast.
402 // See the function for details.
403 // DR 427 specifies that this is to be applied before paragraph 2.
404 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle,OpRange,msg);
405 if (tcr != TC_NotApplicable)
406 return tcr;
407
408 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
409 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
410 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
411 if (tcr != TC_NotApplicable)
412 return tcr;
413
414 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
415 // [...] if the declaration "T t(e);" is well-formed, [...].
416 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg);
417 if (tcr != TC_NotApplicable)
418 return tcr;
419
420 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
421 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
422 // conversions, subject to further restrictions.
423 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
424 // of qualification conversions impossible.
425 // In the CStyle case, the earlier attempt to const_cast should have taken
426 // care of reverse qualification conversions.
427
428 QualType OrigSrcType = SrcExpr->getType();
429
430 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
431
432 // Reverse integral promotion/conversion. All such conversions are themselves
433 // again integral promotions or conversions and are thus already handled by
434 // p2 (TryDirectInitialization above).
435 // (Note: any data loss warnings should be suppressed.)
436 // The exception is the reverse of enum->integer, i.e. integer->enum (and
437 // enum->enum). See also C++ 5.2.9p7.
438 // The same goes for reverse floating point promotion/conversion and
439 // floating-integral conversions. Again, only floating->enum is relevant.
440 if (DestType->isEnumeralType()) {
441 if (SrcType->isComplexType() || SrcType->isVectorType()) {
442 // Fall through - these cannot be converted.
443 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType())
444 return TC_Success;
445 }
446
447 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
448 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
449 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg);
450 if (tcr != TC_NotApplicable)
451 return tcr;
452
453 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
454 // conversion. C++ 5.2.9p9 has additional information.
455 // DR54's access restrictions apply here also.
456 tcr = TryStaticMemberPointerUpcast(Self, SrcType, DestType, CStyle,
457 OpRange, msg);
458 if (tcr != TC_NotApplicable)
459 return tcr;
460
461 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
462 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
463 // just the usual constness stuff.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000464 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl0e35d042009-07-25 15:41:38 +0000465 QualType SrcPointee = SrcPointer->getPointeeType();
466 if (SrcPointee->isVoidType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000467 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl0e35d042009-07-25 15:41:38 +0000468 QualType DestPointee = DestPointer->getPointeeType();
469 if (DestPointee->isIncompleteOrObjectType()) {
470 // This is definitely the intended conversion, but it might fail due
471 // to a const violation.
472 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
473 msg = diag::err_bad_cxx_cast_const_away;
474 return TC_Failed;
475 }
476 return TC_Success;
477 }
478 }
479 }
480 }
481
482 // We tried everything. Everything! Nothing works! :-(
483 return TC_NotApplicable;
484}
485
486/// Tests whether a conversion according to N2844 is valid.
487TryCastResult
488TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
489 unsigned &msg)
490{
491 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
492 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000493 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl0e35d042009-07-25 15:41:38 +0000494 if (!R)
495 return TC_NotApplicable;
496
497 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
498 return TC_NotApplicable;
499
500 // Because we try the reference downcast before this function, from now on
501 // this is the only cast possibility, so we issue an error if we fail now.
502 // FIXME: Should allow casting away constness if CStyle.
503 bool DerivedToBase;
504 if (Self.CompareReferenceRelationship(SrcExpr->getType(), R->getPointeeType(),
505 DerivedToBase) <
506 Sema::Ref_Compatible_With_Added_Qualification) {
507 msg = diag::err_bad_lvalue_to_rvalue_cast;
508 return TC_Failed;
509 }
510
511 // FIXME: Similar to CheckReferenceInit, we actually need more AST annotation
512 // than nothing.
513 return TC_Success;
514}
515
516/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
517TryCastResult
518TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
519 bool CStyle, const SourceRange &OpRange,
520 unsigned &msg)
521{
522 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
523 // cast to type "reference to cv2 D", where D is a class derived from B,
524 // if a valid standard conversion from "pointer to D" to "pointer to B"
525 // exists, cv2 >= cv1, and B is not a virtual base class of D.
526 // In addition, DR54 clarifies that the base must be accessible in the
527 // current context. Although the wording of DR54 only applies to the pointer
528 // variant of this rule, the intent is clearly for it to apply to the this
529 // conversion as well.
530
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000531 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl0e35d042009-07-25 15:41:38 +0000532 if (!DestReference) {
533 return TC_NotApplicable;
534 }
535 bool RValueRef = DestReference->isRValueReferenceType();
536 if (!RValueRef && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
537 // We know the left side is an lvalue reference, so we can suggest a reason.
538 msg = diag::err_bad_cxx_cast_rvalue;
539 return TC_NotApplicable;
540 }
541
542 QualType DestPointee = DestReference->getPointeeType();
543
544 return TryStaticDowncast(Self, SrcExpr->getType(), DestPointee, CStyle,
545 OpRange, SrcExpr->getType(), DestType, msg);
546}
547
548/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
549TryCastResult
550TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
551 bool CStyle, const SourceRange &OpRange, unsigned &msg)
552{
553 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
554 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
555 // is a class derived from B, if a valid standard conversion from "pointer
556 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
557 // class of D.
558 // In addition, DR54 clarifies that the base must be accessible in the
559 // current context.
560
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000561 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl0e35d042009-07-25 15:41:38 +0000562 if (!DestPointer) {
563 return TC_NotApplicable;
564 }
565
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000566 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl0e35d042009-07-25 15:41:38 +0000567 if (!SrcPointer) {
568 msg = diag::err_bad_static_cast_pointer_nonpointer;
569 return TC_NotApplicable;
570 }
571
572 return TryStaticDowncast(Self, SrcPointer->getPointeeType(),
573 DestPointer->getPointeeType(), CStyle,
574 OpRange, SrcType, DestType, msg);
575}
576
577/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
578/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
579/// DestType, both of which must be canonical, is possible and allowed.
580TryCastResult
581TryStaticDowncast(Sema &Self, QualType SrcType, QualType DestType,
582 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
583 QualType OrigDestType, unsigned &msg)
584{
585 // Downcast can only happen in class hierarchies, so we need classes.
586 if (!DestType->isRecordType() || !SrcType->isRecordType()) {
587 return TC_NotApplicable;
588 }
589
590 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
591 /*DetectVirtual=*/true);
592 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
593 return TC_NotApplicable;
594 }
595
596 // Target type does derive from source type. Now we're serious. If an error
597 // appears now, it's not ignored.
598 // This may not be entirely in line with the standard. Take for example:
599 // struct A {};
600 // struct B : virtual A {
601 // B(A&);
602 // };
603 //
604 // void f()
605 // {
606 // (void)static_cast<const B&>(*((A*)0));
607 // }
608 // As far as the standard is concerned, p5 does not apply (A is virtual), so
609 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
610 // However, both GCC and Comeau reject this example, and accepting it would
611 // mean more complex code if we're to preserve the nice error message.
612 // FIXME: Being 100% compliant here would be nice to have.
613
614 // Must preserve cv, as always, unless we're in C-style mode.
615 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
616 msg = diag::err_bad_cxx_cast_const_away;
617 return TC_Failed;
618 }
619
620 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
621 // This code is analoguous to that in CheckDerivedToBaseConversion, except
622 // that it builds the paths in reverse order.
623 // To sum up: record all paths to the base and build a nice string from
624 // them. Use it to spice up the error message.
625 if (!Paths.isRecordingPaths()) {
626 Paths.clear();
627 Paths.setRecordingPaths(true);
628 Self.IsDerivedFrom(DestType, SrcType, Paths);
629 }
630 std::string PathDisplayStr;
631 std::set<unsigned> DisplayedPaths;
632 for (BasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
633 PI != PE; ++PI) {
634 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
635 // We haven't displayed a path to this particular base
636 // class subobject yet.
637 PathDisplayStr += "\n ";
638 for (BasePath::const_reverse_iterator EI = PI->rbegin(),EE = PI->rend();
639 EI != EE; ++EI)
640 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
641 PathDisplayStr += DestType.getAsString();
642 }
643 }
644
645 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
646 << SrcType.getUnqualifiedType() << DestType.getUnqualifiedType()
647 << PathDisplayStr << OpRange;
648 msg = 0;
649 return TC_Failed;
650 }
651
652 if (Paths.getDetectedVirtual() != 0) {
653 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
654 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
655 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
656 msg = 0;
657 return TC_Failed;
658 }
659
660 if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
661 diag::err_downcast_from_inaccessible_base, Paths,
662 OpRange.getBegin(), DeclarationName())) {
663 msg = 0;
664 return TC_Failed;
665 }
666
667 return TC_Success;
668}
669
670/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
671/// C++ 5.2.9p9 is valid:
672///
673/// An rvalue of type "pointer to member of D of type cv1 T" can be
674/// converted to an rvalue of type "pointer to member of B of type cv2 T",
675/// where B is a base class of D [...].
676///
677TryCastResult
678TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType, QualType DestType,
679 bool CStyle, const SourceRange &OpRange,
680 unsigned &msg)
681{
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000682 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl0e35d042009-07-25 15:41:38 +0000683 if (!DestMemPtr)
684 return TC_NotApplicable;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000685 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl0e35d042009-07-25 15:41:38 +0000686 if (!SrcMemPtr) {
687 msg = diag::err_bad_static_cast_member_pointer_nonmp;
688 return TC_NotApplicable;
689 }
690
691 // T == T, modulo cv
692 if (Self.Context.getCanonicalType(
693 SrcMemPtr->getPointeeType().getUnqualifiedType()) !=
694 Self.Context.getCanonicalType(DestMemPtr->getPointeeType().
695 getUnqualifiedType()))
696 return TC_NotApplicable;
697
698 // B base of D
699 QualType SrcClass(SrcMemPtr->getClass(), 0);
700 QualType DestClass(DestMemPtr->getClass(), 0);
701 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
702 /*DetectVirtual=*/true);
703 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
704 return TC_NotApplicable;
705 }
706
707 // B is a base of D. But is it an allowed base? If not, it's a hard error.
708 if (Paths.isAmbiguous(DestClass)) {
709 Paths.clear();
710 Paths.setRecordingPaths(true);
711 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
712 assert(StillOkay);
713 StillOkay = StillOkay;
714 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
715 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
716 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
717 msg = 0;
718 return TC_Failed;
719 }
720
721 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
722 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
723 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
724 msg = 0;
725 return TC_Failed;
726 }
727
728 if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
729 diag::err_downcast_from_inaccessible_base, Paths,
730 OpRange.getBegin(), DeclarationName())) {
731 msg = 0;
732 return TC_Failed;
733 }
734
735 return TC_Success;
736}
737
738/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
739/// is valid:
740///
741/// An expression e can be explicitly converted to a type T using a
742/// @c static_cast if the declaration "T t(e);" is well-formed [...].
743TryCastResult
744TryStaticImplicitCast(Sema &Self, Expr *SrcExpr, QualType DestType,
745 bool CStyle, const SourceRange &OpRange, unsigned &msg)
746{
747 if (DestType->isReferenceType()) {
748 // At this point of CheckStaticCast, if the destination is a reference,
749 // this has to work. There is no other way that works.
750 // On the other hand, if we're checking a C-style cast, we've still got
751 // the reinterpret_cast way. In that case, we pass an ICS so we don't
752 // get error messages.
753 ImplicitConversionSequence ICS;
754 bool failed = Self.CheckReferenceInit(SrcExpr, DestType, CStyle ? &ICS : 0);
755 if (!failed)
756 return TC_Success;
757 if (CStyle)
758 return TC_NotApplicable;
759 // If we didn't pass the ICS, we already got an error message.
760 msg = 0;
761 return TC_Failed;
762 }
763 if (DestType->isRecordType()) {
764 // There are no further possibilities for the target type being a class,
765 // neither in static_cast nor in a C-style cast. So we can fail here.
766 // FIXME: We need to store this constructor in the AST.
767 if (Self.PerformInitializationByConstructor(DestType, &SrcExpr, 1,
768 OpRange.getBegin(), OpRange, DeclarationName(), Sema::IK_Direct))
769 return TC_Success;
770 // The function already emitted an error.
771 msg = 0;
772 return TC_Failed;
773 }
774
775 // FIXME: To get a proper error from invalid conversions here, we need to
776 // reimplement more of this.
777 // FIXME: This does not actually perform the conversion, and thus does not
778 // check for ambiguity or access.
779 ImplicitConversionSequence ICS = Self.TryImplicitConversion(
780 SrcExpr, DestType);
781 return ICS.ConversionKind == ImplicitConversionSequence::BadConversion ?
782 TC_NotApplicable : TC_Success;
783}
784
785/// TryConstCast - See if a const_cast from source to destination is allowed,
786/// and perform it if it is.
787static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
788 bool CStyle, unsigned &msg) {
789 DestType = Self.Context.getCanonicalType(DestType);
790 QualType SrcType = SrcExpr->getType();
791 if (const LValueReferenceType *DestTypeTmp =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000792 DestType->getAs<LValueReferenceType>()) {
Sebastian Redl0e35d042009-07-25 15:41:38 +0000793 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
794 // Cannot const_cast non-lvalue to lvalue reference type. But if this
795 // is C-style, static_cast might find a way, so we simply suggest a
796 // message and tell the parent to keep searching.
797 msg = diag::err_bad_cxx_cast_rvalue;
798 return TC_NotApplicable;
799 }
800
801 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
802 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
803 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
804 SrcType = Self.Context.getPointerType(SrcType);
805 }
806
807 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
808 // the rules for const_cast are the same as those used for pointers.
809
810 if (!DestType->isPointerType() && !DestType->isMemberPointerType()) {
811 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
812 // was a reference type, we converted it to a pointer above.
813 // The status of rvalue references isn't entirely clear, but it looks like
814 // conversion to them is simply invalid.
815 // C++ 5.2.11p3: For two pointer types [...]
816 if (!CStyle)
817 msg = diag::err_bad_const_cast_dest;
818 return TC_NotApplicable;
819 }
820 if (DestType->isFunctionPointerType() ||
821 DestType->isMemberFunctionPointerType()) {
822 // Cannot cast direct function pointers.
823 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
824 // T is the ultimate pointee of source and target type.
825 if (!CStyle)
826 msg = diag::err_bad_const_cast_dest;
827 return TC_NotApplicable;
828 }
829 SrcType = Self.Context.getCanonicalType(SrcType);
830
831 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
832 // completely equal.
833 // FIXME: const_cast should probably not be able to convert between pointers
834 // to different address spaces.
835 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
836 // in multi-level pointers may change, but the level count must be the same,
837 // as must be the final pointee type.
838 while (SrcType != DestType &&
839 Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
840 SrcType = SrcType.getUnqualifiedType();
841 DestType = DestType.getUnqualifiedType();
842 }
843
844 // Since we're dealing in canonical types, the remainder must be the same.
845 if (SrcType != DestType)
846 return TC_NotApplicable;
847
848 return TC_Success;
849}
850
851static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
852 QualType DestType, bool CStyle,
853 const SourceRange &OpRange,
854 unsigned &msg) {
855 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
856
857 DestType = Self.Context.getCanonicalType(DestType);
858 QualType SrcType = SrcExpr->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000859 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl0e35d042009-07-25 15:41:38 +0000860 bool LValue = DestTypeTmp->isLValueReferenceType();
861 if (LValue && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
862 // Cannot cast non-lvalue to reference type. See the similar comment in
863 // const_cast.
864 msg = diag::err_bad_cxx_cast_rvalue;
865 return TC_NotApplicable;
866 }
867
868 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
869 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
870 // built-in & and * operators.
871 // This code does this transformation for the checked types.
872 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
873 SrcType = Self.Context.getPointerType(SrcType);
874 }
875
876 // Canonicalize source for comparison.
877 SrcType = Self.Context.getCanonicalType(SrcType);
878
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000879 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
880 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl0e35d042009-07-25 15:41:38 +0000881 if (DestMemPtr && SrcMemPtr) {
882 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
883 // can be explicitly converted to an rvalue of type "pointer to member
884 // of Y of type T2" if T1 and T2 are both function types or both object
885 // types.
886 if (DestMemPtr->getPointeeType()->isFunctionType() !=
887 SrcMemPtr->getPointeeType()->isFunctionType())
888 return TC_NotApplicable;
889
890 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
891 // constness.
892 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
893 // we accept it.
894 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
895 msg = diag::err_bad_cxx_cast_const_away;
896 return TC_Failed;
897 }
898
899 // A valid member pointer cast.
900 return TC_Success;
901 }
902
903 // See below for the enumeral issue.
904 if (SrcType->isNullPtrType() && DestType->isIntegralType() &&
905 !DestType->isEnumeralType()) {
906 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
907 // type large enough to hold it. A value of std::nullptr_t can be
908 // converted to an integral type; the conversion has the same meaning
909 // and validity as a conversion of (void*)0 to the integral type.
910 if (Self.Context.getTypeSize(SrcType) >
911 Self.Context.getTypeSize(DestType)) {
912 msg = diag::err_bad_reinterpret_cast_small_int;
913 return TC_Failed;
914 }
915 return TC_Success;
916 }
917
918 bool destIsPtr = DestType->isPointerType();
919 bool srcIsPtr = SrcType->isPointerType();
920 if (!destIsPtr && !srcIsPtr) {
921 // Except for std::nullptr_t->integer and lvalue->reference, which are
922 // handled above, at least one of the two arguments must be a pointer.
923 return TC_NotApplicable;
924 }
925
926 if (SrcType == DestType) {
927 // C++ 5.2.10p2 has a note that mentions that, subject to all other
928 // restrictions, a cast to the same type is allowed. The intent is not
929 // entirely clear here, since all other paragraphs explicitly forbid casts
930 // to the same type. However, the behavior of compilers is pretty consistent
931 // on this point: allow same-type conversion if the involved types are
932 // pointers, disallow otherwise.
933 return TC_Success;
934 }
935
936 // Note: Clang treats enumeration types as integral types. If this is ever
937 // changed for C++, the additional check here will be redundant.
938 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
939 assert(srcIsPtr && "One type must be a pointer");
940 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
941 // type large enough to hold it.
942 if (Self.Context.getTypeSize(SrcType) >
943 Self.Context.getTypeSize(DestType)) {
944 msg = diag::err_bad_reinterpret_cast_small_int;
945 return TC_Failed;
946 }
947 return TC_Success;
948 }
949
950 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
951 assert(destIsPtr && "One type must be a pointer");
952 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
953 // converted to a pointer.
954 return TC_Success;
955 }
956
957 if (!destIsPtr || !srcIsPtr) {
958 // With the valid non-pointer conversions out of the way, we can be even
959 // more stringent.
960 return TC_NotApplicable;
961 }
962
963 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
964 // The C-style cast operator can.
965 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
966 msg = diag::err_bad_cxx_cast_const_away;
967 return TC_Failed;
968 }
969
970 // Not casting away constness, so the only remaining check is for compatible
971 // pointer categories.
972
973 if (SrcType->isFunctionPointerType()) {
974 if (DestType->isFunctionPointerType()) {
975 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
976 // a pointer to a function of a different type.
977 return TC_Success;
978 }
979
980 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
981 // an object type or vice versa is conditionally-supported.
982 // Compilers support it in C++03 too, though, because it's necessary for
983 // casting the return value of dlsym() and GetProcAddress().
984 // FIXME: Conditionally-supported behavior should be configurable in the
985 // TargetInfo or similar.
986 if (!Self.getLangOptions().CPlusPlus0x)
987 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
988 return TC_Success;
989 }
990
991 if (DestType->isFunctionPointerType()) {
992 // See above.
993 if (!Self.getLangOptions().CPlusPlus0x)
994 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
995 return TC_Success;
996 }
997
998 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
999 // a pointer to an object of different type.
1000 // Void pointers are not specified, but supported by every compiler out there.
1001 // So we finish by allowing everything that remains - it's got to be two
1002 // object pointers.
1003 return TC_Success;
1004}
1005
1006
Sebastian Redlc358b622009-07-29 13:50:23 +00001007bool Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr,
1008 bool FunctionalStyle)
Sebastian Redl0e35d042009-07-25 15:41:38 +00001009{
1010 // This test is outside everything else because it's the only case where
1011 // a non-lvalue-reference target type does not lead to decay.
1012 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1013 if (CastTy->isVoidType())
1014 return false;
1015
1016 // If the type is dependent, we won't do any other semantic analysis now.
1017 if (CastTy->isDependentType() || CastExpr->isTypeDependent())
1018 return false;
1019
1020 if (!CastTy->isLValueReferenceType())
1021 DefaultFunctionArrayConversion(CastExpr);
1022
1023 // C++ [expr.cast]p5: The conversions performed by
1024 // - a const_cast,
1025 // - a static_cast,
1026 // - a static_cast followed by a const_cast,
1027 // - a reinterpret_cast, or
1028 // - a reinterpret_cast followed by a const_cast,
1029 // can be performed using the cast notation of explicit type conversion.
1030 // [...] If a conversion can be interpreted in more than one of the ways
1031 // listed above, the interpretation that appears first in the list is used,
1032 // even if a cast resulting from that interpretation is ill-formed.
1033 // In plain language, this means trying a const_cast ...
1034 unsigned msg = diag::err_bad_cxx_cast_generic;
1035 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,msg);
1036 if (tcr == TC_NotApplicable) {
1037 // ... or if that is not possible, a static_cast, ignoring const, ...
1038 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg);
1039 if (tcr == TC_NotApplicable) {
1040 // ... and finally a reinterpret_cast, ignoring const.
1041 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg);
1042 }
1043 }
1044
Sebastian Redl0e35d042009-07-25 15:41:38 +00001045 if (tcr != TC_Success && msg != 0)
Sebastian Redlc358b622009-07-29 13:50:23 +00001046 Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
Sebastian Redl0e35d042009-07-25 15:41:38 +00001047 << CastExpr->getType() << CastTy << R;
1048
1049 return tcr != TC_Success;
1050}