blob: d88bbebec13176c01665c17f6013ce48dc34b21d [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"
Anders Carlssona21e7872009-08-26 23:45:07 +000018#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redl2b6b14c2008-11-05 21:50:06 +000019#include "llvm/ADT/SmallVector.h"
Sebastian Redl0528e1c2008-11-07 23:29:29 +000020#include <set>
Sebastian Redl2b6b14c2008-11-05 21:50:06 +000021using namespace clang;
22
Sebastian Redl0e35d042009-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 Redlf831eeb2008-11-08 13:00:26 +000037};
38
39static void CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
40 const SourceRange &OpRange,
41 const SourceRange &DestRange);
42static void CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
43 const SourceRange &OpRange,
44 const SourceRange &DestRange);
45static void CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson9583fa72009-08-07 22:21:05 +000046 const SourceRange &OpRange,
47 CastExpr::CastKind &Kind);
Sebastian Redlf831eeb2008-11-08 13:00:26 +000048static void CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
49 const SourceRange &OpRange,
Anders Carlsson1ecbf592009-08-02 19:07:59 +000050 const SourceRange &DestRange,
51 CastExpr::CastKind &Kind);
Sebastian Redlf831eeb2008-11-08 13:00:26 +000052
53static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
Sebastian Redl0e35d042009-07-25 15:41:38 +000054
55// The Try functions attempt a specific way of casting. If they succeed, they
56// return TC_Success. If their way of casting is not appropriate for the given
57// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
58// to emit if no other way succeeds. If their way of casting is appropriate but
59// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
60// they emit a specialized diagnostic.
61// All diagnostics returned by these functions must expect the same three
62// arguments:
63// %0: Cast Type (a value from the CastType enumeration)
64// %1: Source Type
65// %2: Destination Type
66static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
67 QualType DestType, unsigned &msg);
68static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
69 QualType DestType, bool CStyle,
70 const SourceRange &OpRange,
71 unsigned &msg);
72static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
73 QualType DestType, bool CStyle,
74 const SourceRange &OpRange,
75 unsigned &msg);
76static TryCastResult TryStaticDowncast(Sema &Self, QualType SrcType,
77 QualType DestType, bool CStyle,
78 const SourceRange &OpRange,
79 QualType OrigSrcType,
80 QualType OrigDestType, unsigned &msg);
81static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType,
82 QualType DestType,bool CStyle,
83 const SourceRange &OpRange,
84 unsigned &msg);
85static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *SrcExpr,
86 QualType DestType, bool CStyle,
87 const SourceRange &OpRange,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +000088 unsigned &msg,
89 CXXMethodDecl *&ConversionDecl);
Sebastian Redl0e35d042009-07-25 15:41:38 +000090static TryCastResult TryStaticCast(Sema &Self, Expr *SrcExpr,
91 QualType DestType, bool CStyle,
Anders Carlssonf1957c82009-09-01 20:52:42 +000092 CastExpr::CastKind &Kind,
Sebastian Redl0e35d042009-07-25 15:41:38 +000093 const SourceRange &OpRange,
Anders Carlssonf1957c82009-09-01 20:52:42 +000094 unsigned &msg,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +000095 CXXMethodDecl *&ConversionDecl);
Sebastian Redl0e35d042009-07-25 15:41:38 +000096static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
97 bool CStyle, unsigned &msg);
98static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
99 QualType DestType, bool CStyle,
Anders Carlssonf1957c82009-09-01 20:52:42 +0000100 CastExpr::CastKind &Kind,
Sebastian Redl0e35d042009-07-25 15:41:38 +0000101 const SourceRange &OpRange,
102 unsigned &msg);
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000103
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000104/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000105Action::OwningExprResult
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000106Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
107 SourceLocation LAngleBracketLoc, TypeTy *Ty,
108 SourceLocation RAngleBracketLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000109 SourceLocation LParenLoc, ExprArg E,
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000110 SourceLocation RParenLoc) {
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000111 Expr *Ex = E.takeAs<Expr>();
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +0000112 // FIXME: Preserve type source info.
113 QualType DestType = GetTypeFromParser(Ty);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000114 SourceRange OpRange(OpLoc, RParenLoc);
115 SourceRange DestRange(LAngleBracketLoc, RAngleBracketLoc);
116
Douglas Gregore6be68a2008-12-17 22:52:20 +0000117 // If the type is dependent, we won't do the semantic analysis now.
118 // FIXME: should we check this in a more fine-grained manner?
119 bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
120
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000121 switch (Kind) {
122 default: assert(0 && "Unknown C++ cast!");
123
124 case tok::kw_const_cast:
Douglas Gregore6be68a2008-12-17 22:52:20 +0000125 if (!TypeDependent)
126 CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000127 return Owned(new (Context) CXXConstCastExpr(DestType.getNonReferenceType(),
128 Ex, DestType, OpLoc));
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000129
Anders Carlsson1ecbf592009-08-02 19:07:59 +0000130 case tok::kw_dynamic_cast: {
131 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregore6be68a2008-12-17 22:52:20 +0000132 if (!TypeDependent)
Anders Carlsson1ecbf592009-08-02 19:07:59 +0000133 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000134 return Owned(new (Context)CXXDynamicCastExpr(DestType.getNonReferenceType(),
Anders Carlsson1ecbf592009-08-02 19:07:59 +0000135 Kind, Ex, DestType, OpLoc));
136 }
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000137 case tok::kw_reinterpret_cast:
Douglas Gregore6be68a2008-12-17 22:52:20 +0000138 if (!TypeDependent)
139 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000140 return Owned(new (Context) CXXReinterpretCastExpr(
141 DestType.getNonReferenceType(),
142 Ex, DestType, OpLoc));
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000143
Anders Carlsson9583fa72009-08-07 22:21:05 +0000144 case tok::kw_static_cast: {
145 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregore6be68a2008-12-17 22:52:20 +0000146 if (!TypeDependent)
Anders Carlsson9583fa72009-08-07 22:21:05 +0000147 CheckStaticCast(*this, Ex, DestType, OpRange, Kind);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000148 return Owned(new (Context) CXXStaticCastExpr(DestType.getNonReferenceType(),
Anders Carlsson9583fa72009-08-07 22:21:05 +0000149 Kind, Ex, DestType, OpLoc));
150 }
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000151 }
152
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000153 return ExprError();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000154}
155
Sebastian Redl04b3f352009-01-27 23:18:31 +0000156/// CastsAwayConstness - Check if the pointer conversion from SrcType to
157/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
158/// the cast checkers. Both arguments must denote pointer (possibly to member)
159/// types.
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000160bool
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000161CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000162{
Sebastian Redl04b3f352009-01-27 23:18:31 +0000163 // Casting away constness is defined in C++ 5.2.11p8 with reference to
164 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
165 // the rules are non-trivial. So first we construct Tcv *...cv* as described
166 // in C++ 5.2.11p8.
167 assert((SrcType->isPointerType() || SrcType->isMemberPointerType()) &&
168 "Source type is not pointer or pointer to member.");
169 assert((DestType->isPointerType() || DestType->isMemberPointerType()) &&
170 "Destination type is not pointer or pointer to member.");
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000171
172 QualType UnwrappedSrcType = SrcType, UnwrappedDestType = DestType;
173 llvm::SmallVector<unsigned, 8> cv1, cv2;
174
175 // Find the qualifications.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000176 while (Self.UnwrapSimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000177 cv1.push_back(UnwrappedSrcType.getCVRQualifiers());
178 cv2.push_back(UnwrappedDestType.getCVRQualifiers());
179 }
180 assert(cv1.size() > 0 && "Must have at least one pointer level.");
181
182 // Construct void pointers with those qualifiers (in reverse order of
183 // unwrapping, of course).
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000184 QualType SrcConstruct = Self.Context.VoidTy;
185 QualType DestConstruct = Self.Context.VoidTy;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000186 for (llvm::SmallVector<unsigned, 8>::reverse_iterator i1 = cv1.rbegin(),
187 i2 = cv2.rbegin();
188 i1 != cv1.rend(); ++i1, ++i2)
189 {
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000190 SrcConstruct = Self.Context.getPointerType(
191 SrcConstruct.getQualifiedType(*i1));
192 DestConstruct = Self.Context.getPointerType(
193 DestConstruct.getQualifiedType(*i2));
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000194 }
195
196 // Test if they're compatible.
197 return SrcConstruct != DestConstruct &&
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000198 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000199}
200
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000201/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
202/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
203/// checked downcasts in class hierarchies.
Anders Carlsson1ecbf592009-08-02 19:07:59 +0000204static void
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000205CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
206 const SourceRange &OpRange,
Anders Carlsson1ecbf592009-08-02 19:07:59 +0000207 const SourceRange &DestRange, CastExpr::CastKind &Kind)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000208{
209 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000210 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000211
212 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
213 // or "pointer to cv void".
214
215 QualType DestPointee;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000216 const PointerType *DestPointer = DestType->getAs<PointerType>();
217 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000218 if (DestPointer) {
219 DestPointee = DestPointer->getPointeeType();
220 } else if (DestReference) {
221 DestPointee = DestReference->getPointeeType();
222 } else {
Chris Lattner70b93d82008-11-18 22:52:51 +0000223 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000224 << OrigDestType << DestRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000225 return;
226 }
227
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000228 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000229 if (DestPointee->isVoidType()) {
230 assert(DestPointer && "Reference to void is not possible");
231 } else if (DestRecord) {
Sebastian Redl0e35d042009-07-25 15:41:38 +0000232 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Anders Carlssona21e7872009-08-26 23:45:07 +0000233 PDiag(diag::err_bad_dynamic_cast_incomplete)
234 << DestRange))
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000235 return;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000236 } else {
Chris Lattner70b93d82008-11-18 22:52:51 +0000237 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000238 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000239 return;
240 }
241
Sebastian Redlce6fff02009-03-16 23:22:08 +0000242 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
243 // complete class type, [...]. If T is an lvalue reference type, v shall be
244 // an lvalue of a complete class type, [...]. If T is an rvalue reference
245 // type, v shall be an expression having a complete effective class type,
246 // [...]
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000247
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000248 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000249 QualType SrcPointee;
250 if (DestPointer) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000251 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000252 SrcPointee = SrcPointer->getPointeeType();
253 } else {
Chris Lattner70b93d82008-11-18 22:52:51 +0000254 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000255 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000256 return;
257 }
Sebastian Redlce6fff02009-03-16 23:22:08 +0000258 } else if (DestReference->isLValueReferenceType()) {
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000259 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattner70b93d82008-11-18 22:52:51 +0000260 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl0e35d042009-07-25 15:41:38 +0000261 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000262 }
263 SrcPointee = SrcType;
Sebastian Redlce6fff02009-03-16 23:22:08 +0000264 } else {
265 SrcPointee = SrcType;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000266 }
267
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000268 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000269 if (SrcRecord) {
Douglas Gregorc84d8932009-03-09 16:13:40 +0000270 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Anders Carlssona21e7872009-08-26 23:45:07 +0000271 PDiag(diag::err_bad_dynamic_cast_incomplete)
272 << SrcExpr->getSourceRange()))
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000273 return;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000274 } else {
Chris Lattner77d52da2008-11-20 06:06:08 +0000275 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000276 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000277 return;
278 }
279
280 assert((DestPointer || DestReference) &&
281 "Bad destination non-ptr/ref slipped through.");
282 assert((DestRecord || DestPointee->isVoidType()) &&
283 "Bad destination pointee slipped through.");
284 assert(SrcRecord && "Bad source pointee slipped through.");
285
286 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
287 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +0000288 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl0e35d042009-07-25 15:41:38 +0000289 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000290 return;
291 }
292
293 // C++ 5.2.7p3: If the type of v is the same as the required result type,
294 // [except for cv].
295 if (DestRecord == SrcRecord) {
296 return;
297 }
298
299 // C++ 5.2.7p5
300 // Upcasts are resolved statically.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000301 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
302 Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
Chris Lattner4bfd2232008-11-24 06:25:27 +0000303 OpRange.getBegin(), OpRange);
Anders Carlsson1ecbf592009-08-02 19:07:59 +0000304 Kind = CastExpr::CK_DerivedToBase;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000305 // Diagnostic already emitted on error.
306 return;
307 }
308
309 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000310 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(Self.Context);
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000311 assert(SrcDecl && "Definition missing");
312 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner77d52da2008-11-20 06:06:08 +0000313 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000314 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000315 }
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000316
317 // Done. Everything else is run-time checks.
Anders Carlsson1ecbf592009-08-02 19:07:59 +0000318 Kind = CastExpr::CK_Dynamic;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000319}
Sebastian Redl0e35d042009-07-25 15:41:38 +0000320
321/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
322/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
323/// like this:
324/// const char *str = "literal";
325/// legacy_function(const_cast\<char*\>(str));
326void
327CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
328 const SourceRange &OpRange, const SourceRange &DestRange)
329{
330 if (!DestType->isLValueReferenceType())
331 Self.DefaultFunctionArrayConversion(SrcExpr);
332
333 unsigned msg = diag::err_bad_cxx_cast_generic;
334 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
335 && msg != 0)
336 Self.Diag(OpRange.getBegin(), msg) << CT_Const
337 << SrcExpr->getType() << DestType << OpRange;
338}
339
340/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
341/// valid.
342/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
343/// like this:
344/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
345void
346CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
347 const SourceRange &OpRange, const SourceRange &DestRange)
348{
349 if (!DestType->isLValueReferenceType())
350 Self.DefaultFunctionArrayConversion(SrcExpr);
351
Anders Carlssonf1957c82009-09-01 20:52:42 +0000352 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Sebastian Redl0e35d042009-07-25 15:41:38 +0000353 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssonf1957c82009-09-01 20:52:42 +0000354 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, Kind,
355 OpRange, msg)
Sebastian Redl0e35d042009-07-25 15:41:38 +0000356 != TC_Success && msg != 0)
357 Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
358 << SrcExpr->getType() << DestType << OpRange;
359}
360
361
362/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
363/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
364/// implicit conversions explicit and getting rid of data loss warnings.
365void
366CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson9583fa72009-08-07 22:21:05 +0000367 const SourceRange &OpRange, CastExpr::CastKind &Kind)
Sebastian Redl0e35d042009-07-25 15:41:38 +0000368{
369 // This test is outside everything else because it's the only case where
370 // a non-lvalue-reference target type does not lead to decay.
371 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
372 if (DestType->isVoidType()) {
373 return;
374 }
375
376 if (!DestType->isLValueReferenceType())
377 Self.DefaultFunctionArrayConversion(SrcExpr);
378
379 unsigned msg = diag::err_bad_cxx_cast_generic;
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +0000380 CXXMethodDecl *ConversionDecl = 0;
Anders Carlssonf1957c82009-09-01 20:52:42 +0000381 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, Kind,
382 OpRange, msg, ConversionDecl)
Sebastian Redl0e35d042009-07-25 15:41:38 +0000383 != TC_Success && msg != 0)
384 Self.Diag(OpRange.getBegin(), msg) << CT_Static
385 << SrcExpr->getType() << DestType << OpRange;
386}
387
388/// TryStaticCast - Check if a static cast can be performed, and do so if
389/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
390/// and casting away constness.
391static TryCastResult TryStaticCast(Sema &Self, Expr *SrcExpr,
392 QualType DestType, bool CStyle,
Anders Carlssonf1957c82009-09-01 20:52:42 +0000393 CastExpr::CastKind &Kind,
394 const SourceRange &OpRange, unsigned &msg,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +0000395 CXXMethodDecl *&ConversionDecl)
Sebastian Redl0e35d042009-07-25 15:41:38 +0000396{
397 // The order the tests is not entirely arbitrary. There is one conversion
398 // that can be handled in two different ways. Given:
399 // struct A {};
400 // struct B : public A {
401 // B(); B(const A&);
402 // };
403 // const A &a = B();
404 // the cast static_cast<const B&>(a) could be seen as either a static
405 // reference downcast, or an explicit invocation of the user-defined
406 // conversion using B's conversion constructor.
407 // DR 427 specifies that the downcast is to be applied here.
408
409 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
410 // Done outside this function.
411
412 TryCastResult tcr;
413
414 // C++ 5.2.9p5, reference downcast.
415 // See the function for details.
416 // DR 427 specifies that this is to be applied before paragraph 2.
417 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle,OpRange,msg);
418 if (tcr != TC_NotApplicable)
419 return tcr;
420
421 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
422 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
423 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
424 if (tcr != TC_NotApplicable)
425 return tcr;
426
427 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
428 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +0000429 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
430 ConversionDecl);
Sebastian Redl0e35d042009-07-25 15:41:38 +0000431 if (tcr != TC_NotApplicable)
432 return tcr;
433
434 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
435 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
436 // conversions, subject to further restrictions.
437 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
438 // of qualification conversions impossible.
439 // In the CStyle case, the earlier attempt to const_cast should have taken
440 // care of reverse qualification conversions.
441
442 QualType OrigSrcType = SrcExpr->getType();
443
444 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
445
446 // Reverse integral promotion/conversion. All such conversions are themselves
447 // again integral promotions or conversions and are thus already handled by
448 // p2 (TryDirectInitialization above).
449 // (Note: any data loss warnings should be suppressed.)
450 // The exception is the reverse of enum->integer, i.e. integer->enum (and
451 // enum->enum). See also C++ 5.2.9p7.
452 // The same goes for reverse floating point promotion/conversion and
453 // floating-integral conversions. Again, only floating->enum is relevant.
454 if (DestType->isEnumeralType()) {
455 if (SrcType->isComplexType() || SrcType->isVectorType()) {
456 // Fall through - these cannot be converted.
457 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType())
458 return TC_Success;
459 }
460
461 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
462 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
463 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg);
464 if (tcr != TC_NotApplicable)
465 return tcr;
466
467 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
468 // conversion. C++ 5.2.9p9 has additional information.
469 // DR54's access restrictions apply here also.
470 tcr = TryStaticMemberPointerUpcast(Self, SrcType, DestType, CStyle,
471 OpRange, msg);
472 if (tcr != TC_NotApplicable)
473 return tcr;
474
475 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
476 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
477 // just the usual constness stuff.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000478 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl0e35d042009-07-25 15:41:38 +0000479 QualType SrcPointee = SrcPointer->getPointeeType();
480 if (SrcPointee->isVoidType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000481 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl0e35d042009-07-25 15:41:38 +0000482 QualType DestPointee = DestPointer->getPointeeType();
483 if (DestPointee->isIncompleteOrObjectType()) {
484 // This is definitely the intended conversion, but it might fail due
485 // to a const violation.
486 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
487 msg = diag::err_bad_cxx_cast_const_away;
488 return TC_Failed;
489 }
490 return TC_Success;
491 }
492 }
493 }
494 }
495
496 // We tried everything. Everything! Nothing works! :-(
497 return TC_NotApplicable;
498}
499
500/// Tests whether a conversion according to N2844 is valid.
501TryCastResult
502TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
503 unsigned &msg)
504{
505 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
506 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000507 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl0e35d042009-07-25 15:41:38 +0000508 if (!R)
509 return TC_NotApplicable;
510
511 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
512 return TC_NotApplicable;
513
514 // Because we try the reference downcast before this function, from now on
515 // this is the only cast possibility, so we issue an error if we fail now.
516 // FIXME: Should allow casting away constness if CStyle.
517 bool DerivedToBase;
518 if (Self.CompareReferenceRelationship(SrcExpr->getType(), R->getPointeeType(),
519 DerivedToBase) <
520 Sema::Ref_Compatible_With_Added_Qualification) {
521 msg = diag::err_bad_lvalue_to_rvalue_cast;
522 return TC_Failed;
523 }
524
525 // FIXME: Similar to CheckReferenceInit, we actually need more AST annotation
526 // than nothing.
527 return TC_Success;
528}
529
530/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
531TryCastResult
532TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
533 bool CStyle, const SourceRange &OpRange,
534 unsigned &msg)
535{
536 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
537 // cast to type "reference to cv2 D", where D is a class derived from B,
538 // if a valid standard conversion from "pointer to D" to "pointer to B"
539 // exists, cv2 >= cv1, and B is not a virtual base class of D.
540 // In addition, DR54 clarifies that the base must be accessible in the
541 // current context. Although the wording of DR54 only applies to the pointer
542 // variant of this rule, the intent is clearly for it to apply to the this
543 // conversion as well.
544
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000545 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl0e35d042009-07-25 15:41:38 +0000546 if (!DestReference) {
547 return TC_NotApplicable;
548 }
549 bool RValueRef = DestReference->isRValueReferenceType();
550 if (!RValueRef && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
551 // We know the left side is an lvalue reference, so we can suggest a reason.
552 msg = diag::err_bad_cxx_cast_rvalue;
553 return TC_NotApplicable;
554 }
555
556 QualType DestPointee = DestReference->getPointeeType();
557
558 return TryStaticDowncast(Self, SrcExpr->getType(), DestPointee, CStyle,
559 OpRange, SrcExpr->getType(), DestType, msg);
560}
561
562/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
563TryCastResult
564TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
565 bool CStyle, const SourceRange &OpRange, unsigned &msg)
566{
567 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
568 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
569 // is a class derived from B, if a valid standard conversion from "pointer
570 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
571 // class of D.
572 // In addition, DR54 clarifies that the base must be accessible in the
573 // current context.
574
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000575 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl0e35d042009-07-25 15:41:38 +0000576 if (!DestPointer) {
577 return TC_NotApplicable;
578 }
579
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000580 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl0e35d042009-07-25 15:41:38 +0000581 if (!SrcPointer) {
582 msg = diag::err_bad_static_cast_pointer_nonpointer;
583 return TC_NotApplicable;
584 }
585
586 return TryStaticDowncast(Self, SrcPointer->getPointeeType(),
587 DestPointer->getPointeeType(), CStyle,
588 OpRange, SrcType, DestType, msg);
589}
590
591/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
592/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
593/// DestType, both of which must be canonical, is possible and allowed.
594TryCastResult
595TryStaticDowncast(Sema &Self, QualType SrcType, QualType DestType,
596 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
597 QualType OrigDestType, unsigned &msg)
598{
599 // Downcast can only happen in class hierarchies, so we need classes.
600 if (!DestType->isRecordType() || !SrcType->isRecordType()) {
601 return TC_NotApplicable;
602 }
603
604 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
605 /*DetectVirtual=*/true);
606 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
607 return TC_NotApplicable;
608 }
609
610 // Target type does derive from source type. Now we're serious. If an error
611 // appears now, it's not ignored.
612 // This may not be entirely in line with the standard. Take for example:
613 // struct A {};
614 // struct B : virtual A {
615 // B(A&);
616 // };
617 //
618 // void f()
619 // {
620 // (void)static_cast<const B&>(*((A*)0));
621 // }
622 // As far as the standard is concerned, p5 does not apply (A is virtual), so
623 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
624 // However, both GCC and Comeau reject this example, and accepting it would
625 // mean more complex code if we're to preserve the nice error message.
626 // FIXME: Being 100% compliant here would be nice to have.
627
628 // Must preserve cv, as always, unless we're in C-style mode.
629 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
630 msg = diag::err_bad_cxx_cast_const_away;
631 return TC_Failed;
632 }
633
634 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
635 // This code is analoguous to that in CheckDerivedToBaseConversion, except
636 // that it builds the paths in reverse order.
637 // To sum up: record all paths to the base and build a nice string from
638 // them. Use it to spice up the error message.
639 if (!Paths.isRecordingPaths()) {
640 Paths.clear();
641 Paths.setRecordingPaths(true);
642 Self.IsDerivedFrom(DestType, SrcType, Paths);
643 }
644 std::string PathDisplayStr;
645 std::set<unsigned> DisplayedPaths;
646 for (BasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
647 PI != PE; ++PI) {
648 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
649 // We haven't displayed a path to this particular base
650 // class subobject yet.
651 PathDisplayStr += "\n ";
652 for (BasePath::const_reverse_iterator EI = PI->rbegin(),EE = PI->rend();
653 EI != EE; ++EI)
654 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
655 PathDisplayStr += DestType.getAsString();
656 }
657 }
658
659 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
660 << SrcType.getUnqualifiedType() << DestType.getUnqualifiedType()
661 << PathDisplayStr << OpRange;
662 msg = 0;
663 return TC_Failed;
664 }
665
666 if (Paths.getDetectedVirtual() != 0) {
667 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
668 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
669 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
670 msg = 0;
671 return TC_Failed;
672 }
673
674 if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
675 diag::err_downcast_from_inaccessible_base, Paths,
676 OpRange.getBegin(), DeclarationName())) {
677 msg = 0;
678 return TC_Failed;
679 }
680
681 return TC_Success;
682}
683
684/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
685/// C++ 5.2.9p9 is valid:
686///
687/// An rvalue of type "pointer to member of D of type cv1 T" can be
688/// converted to an rvalue of type "pointer to member of B of type cv2 T",
689/// where B is a base class of D [...].
690///
691TryCastResult
692TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType, QualType DestType,
693 bool CStyle, const SourceRange &OpRange,
694 unsigned &msg)
695{
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000696 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl0e35d042009-07-25 15:41:38 +0000697 if (!DestMemPtr)
698 return TC_NotApplicable;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000699 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl0e35d042009-07-25 15:41:38 +0000700 if (!SrcMemPtr) {
701 msg = diag::err_bad_static_cast_member_pointer_nonmp;
702 return TC_NotApplicable;
703 }
704
705 // T == T, modulo cv
706 if (Self.Context.getCanonicalType(
707 SrcMemPtr->getPointeeType().getUnqualifiedType()) !=
708 Self.Context.getCanonicalType(DestMemPtr->getPointeeType().
709 getUnqualifiedType()))
710 return TC_NotApplicable;
711
712 // B base of D
713 QualType SrcClass(SrcMemPtr->getClass(), 0);
714 QualType DestClass(DestMemPtr->getClass(), 0);
715 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
716 /*DetectVirtual=*/true);
717 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
718 return TC_NotApplicable;
719 }
720
721 // B is a base of D. But is it an allowed base? If not, it's a hard error.
722 if (Paths.isAmbiguous(DestClass)) {
723 Paths.clear();
724 Paths.setRecordingPaths(true);
725 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
726 assert(StillOkay);
727 StillOkay = StillOkay;
728 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
729 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
730 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
731 msg = 0;
732 return TC_Failed;
733 }
734
735 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
736 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
737 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
738 msg = 0;
739 return TC_Failed;
740 }
741
742 if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
743 diag::err_downcast_from_inaccessible_base, Paths,
744 OpRange.getBegin(), DeclarationName())) {
745 msg = 0;
746 return TC_Failed;
747 }
748
749 return TC_Success;
750}
751
752/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
753/// is valid:
754///
755/// An expression e can be explicitly converted to a type T using a
756/// @c static_cast if the declaration "T t(e);" is well-formed [...].
757TryCastResult
758TryStaticImplicitCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +0000759 bool CStyle, const SourceRange &OpRange, unsigned &msg,
760 CXXMethodDecl *&ConversionDecl)
Sebastian Redl0e35d042009-07-25 15:41:38 +0000761{
762 if (DestType->isReferenceType()) {
763 // At this point of CheckStaticCast, if the destination is a reference,
764 // this has to work. There is no other way that works.
765 // On the other hand, if we're checking a C-style cast, we've still got
766 // the reinterpret_cast way. In that case, we pass an ICS so we don't
767 // get error messages.
768 ImplicitConversionSequence ICS;
Anders Carlsson8f809f92009-08-27 17:30:43 +0000769 bool failed = Self.CheckReferenceInit(SrcExpr, DestType,
770 /*SuppressUserConversions=*/false,
771 /*AllowExplicit=*/false,
772 /*ForceRValue=*/false,
773 CStyle ? &ICS : 0);
Sebastian Redl0e35d042009-07-25 15:41:38 +0000774 if (!failed)
775 return TC_Success;
776 if (CStyle)
777 return TC_NotApplicable;
778 // If we didn't pass the ICS, we already got an error message.
779 msg = 0;
780 return TC_Failed;
781 }
Sebastian Redl0e35d042009-07-25 15:41:38 +0000782
783 // FIXME: To get a proper error from invalid conversions here, we need to
784 // reimplement more of this.
785 // FIXME: This does not actually perform the conversion, and thus does not
786 // check for ambiguity or access.
Anders Carlsson6ed4a612009-08-27 17:24:15 +0000787 ImplicitConversionSequence ICS =
788 Self.TryImplicitConversion(SrcExpr, DestType,
789 /*SuppressUserConversions=*/false,
Anders Carlssonca468502009-08-28 16:22:20 +0000790 /*AllowExplicit=*/true,
Anders Carlsson8e4c1692009-08-28 15:33:32 +0000791 /*ForceRValue=*/false,
792 /*InOverloadResolution=*/false);
Anders Carlsson6ed4a612009-08-27 17:24:15 +0000793
Fariborz Jahanianc8a336f2009-08-26 23:31:30 +0000794 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
Fariborz Jahanian795a3fd2009-08-28 15:11:24 +0000795 if (CXXMethodDecl *MD =
796 dyn_cast<CXXMethodDecl>(ICS.UserDefined.ConversionFunction))
797 ConversionDecl = MD;
Sebastian Redl0e35d042009-07-25 15:41:38 +0000798 return ICS.ConversionKind == ImplicitConversionSequence::BadConversion ?
799 TC_NotApplicable : TC_Success;
800}
801
802/// TryConstCast - See if a const_cast from source to destination is allowed,
803/// and perform it if it is.
804static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
805 bool CStyle, unsigned &msg) {
806 DestType = Self.Context.getCanonicalType(DestType);
807 QualType SrcType = SrcExpr->getType();
808 if (const LValueReferenceType *DestTypeTmp =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000809 DestType->getAs<LValueReferenceType>()) {
Sebastian Redl0e35d042009-07-25 15:41:38 +0000810 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
811 // Cannot const_cast non-lvalue to lvalue reference type. But if this
812 // is C-style, static_cast might find a way, so we simply suggest a
813 // message and tell the parent to keep searching.
814 msg = diag::err_bad_cxx_cast_rvalue;
815 return TC_NotApplicable;
816 }
817
818 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
819 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
820 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
821 SrcType = Self.Context.getPointerType(SrcType);
822 }
823
824 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
825 // the rules for const_cast are the same as those used for pointers.
826
827 if (!DestType->isPointerType() && !DestType->isMemberPointerType()) {
828 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
829 // was a reference type, we converted it to a pointer above.
830 // The status of rvalue references isn't entirely clear, but it looks like
831 // conversion to them is simply invalid.
832 // C++ 5.2.11p3: For two pointer types [...]
833 if (!CStyle)
834 msg = diag::err_bad_const_cast_dest;
835 return TC_NotApplicable;
836 }
837 if (DestType->isFunctionPointerType() ||
838 DestType->isMemberFunctionPointerType()) {
839 // Cannot cast direct function pointers.
840 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
841 // T is the ultimate pointee of source and target type.
842 if (!CStyle)
843 msg = diag::err_bad_const_cast_dest;
844 return TC_NotApplicable;
845 }
846 SrcType = Self.Context.getCanonicalType(SrcType);
847
848 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
849 // completely equal.
850 // FIXME: const_cast should probably not be able to convert between pointers
851 // to different address spaces.
852 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
853 // in multi-level pointers may change, but the level count must be the same,
854 // as must be the final pointee type.
855 while (SrcType != DestType &&
856 Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
857 SrcType = SrcType.getUnqualifiedType();
858 DestType = DestType.getUnqualifiedType();
859 }
860
861 // Since we're dealing in canonical types, the remainder must be the same.
862 if (SrcType != DestType)
863 return TC_NotApplicable;
864
865 return TC_Success;
866}
867
868static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
869 QualType DestType, bool CStyle,
Anders Carlssonf1957c82009-09-01 20:52:42 +0000870 CastExpr::CastKind &Kind,
Sebastian Redl0e35d042009-07-25 15:41:38 +0000871 const SourceRange &OpRange,
872 unsigned &msg) {
873 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
874
875 DestType = Self.Context.getCanonicalType(DestType);
876 QualType SrcType = SrcExpr->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000877 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl0e35d042009-07-25 15:41:38 +0000878 bool LValue = DestTypeTmp->isLValueReferenceType();
879 if (LValue && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
880 // Cannot cast non-lvalue to reference type. See the similar comment in
881 // const_cast.
882 msg = diag::err_bad_cxx_cast_rvalue;
883 return TC_NotApplicable;
884 }
885
886 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
887 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
888 // built-in & and * operators.
889 // This code does this transformation for the checked types.
890 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
891 SrcType = Self.Context.getPointerType(SrcType);
892 }
893
894 // Canonicalize source for comparison.
895 SrcType = Self.Context.getCanonicalType(SrcType);
896
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000897 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
898 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl0e35d042009-07-25 15:41:38 +0000899 if (DestMemPtr && SrcMemPtr) {
900 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
901 // can be explicitly converted to an rvalue of type "pointer to member
902 // of Y of type T2" if T1 and T2 are both function types or both object
903 // types.
904 if (DestMemPtr->getPointeeType()->isFunctionType() !=
905 SrcMemPtr->getPointeeType()->isFunctionType())
906 return TC_NotApplicable;
907
908 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
909 // constness.
910 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
911 // we accept it.
912 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
913 msg = diag::err_bad_cxx_cast_const_away;
914 return TC_Failed;
915 }
916
917 // A valid member pointer cast.
918 return TC_Success;
919 }
920
921 // See below for the enumeral issue.
922 if (SrcType->isNullPtrType() && DestType->isIntegralType() &&
923 !DestType->isEnumeralType()) {
924 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
925 // type large enough to hold it. A value of std::nullptr_t can be
926 // converted to an integral type; the conversion has the same meaning
927 // and validity as a conversion of (void*)0 to the integral type.
928 if (Self.Context.getTypeSize(SrcType) >
929 Self.Context.getTypeSize(DestType)) {
930 msg = diag::err_bad_reinterpret_cast_small_int;
931 return TC_Failed;
932 }
933 return TC_Success;
934 }
935
936 bool destIsPtr = DestType->isPointerType();
937 bool srcIsPtr = SrcType->isPointerType();
938 if (!destIsPtr && !srcIsPtr) {
939 // Except for std::nullptr_t->integer and lvalue->reference, which are
940 // handled above, at least one of the two arguments must be a pointer.
941 return TC_NotApplicable;
942 }
943
944 if (SrcType == DestType) {
945 // C++ 5.2.10p2 has a note that mentions that, subject to all other
946 // restrictions, a cast to the same type is allowed. The intent is not
947 // entirely clear here, since all other paragraphs explicitly forbid casts
948 // to the same type. However, the behavior of compilers is pretty consistent
949 // on this point: allow same-type conversion if the involved types are
950 // pointers, disallow otherwise.
951 return TC_Success;
952 }
953
954 // Note: Clang treats enumeration types as integral types. If this is ever
955 // changed for C++, the additional check here will be redundant.
956 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
957 assert(srcIsPtr && "One type must be a pointer");
958 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
959 // type large enough to hold it.
960 if (Self.Context.getTypeSize(SrcType) >
961 Self.Context.getTypeSize(DestType)) {
962 msg = diag::err_bad_reinterpret_cast_small_int;
963 return TC_Failed;
964 }
965 return TC_Success;
966 }
967
968 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
969 assert(destIsPtr && "One type must be a pointer");
970 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
971 // converted to a pointer.
972 return TC_Success;
973 }
974
975 if (!destIsPtr || !srcIsPtr) {
976 // With the valid non-pointer conversions out of the way, we can be even
977 // more stringent.
978 return TC_NotApplicable;
979 }
980
981 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
982 // The C-style cast operator can.
983 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
984 msg = diag::err_bad_cxx_cast_const_away;
985 return TC_Failed;
986 }
987
988 // Not casting away constness, so the only remaining check is for compatible
989 // pointer categories.
990
991 if (SrcType->isFunctionPointerType()) {
992 if (DestType->isFunctionPointerType()) {
993 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
994 // a pointer to a function of a different type.
995 return TC_Success;
996 }
997
998 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
999 // an object type or vice versa is conditionally-supported.
1000 // Compilers support it in C++03 too, though, because it's necessary for
1001 // casting the return value of dlsym() and GetProcAddress().
1002 // FIXME: Conditionally-supported behavior should be configurable in the
1003 // TargetInfo or similar.
1004 if (!Self.getLangOptions().CPlusPlus0x)
1005 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1006 return TC_Success;
1007 }
1008
1009 if (DestType->isFunctionPointerType()) {
1010 // See above.
1011 if (!Self.getLangOptions().CPlusPlus0x)
1012 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1013 return TC_Success;
1014 }
1015
1016 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1017 // a pointer to an object of different type.
1018 // Void pointers are not specified, but supported by every compiler out there.
1019 // So we finish by allowing everything that remains - it's got to be two
1020 // object pointers.
Anders Carlssonf1957c82009-09-01 20:52:42 +00001021 Kind = CastExpr::CK_BitCast;
Sebastian Redl0e35d042009-07-25 15:41:38 +00001022 return TC_Success;
1023}
1024
Sebastian Redlc358b622009-07-29 13:50:23 +00001025bool Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00001026 CastExpr::CastKind &Kind, bool FunctionalStyle,
1027 CXXMethodDecl *&ConversionDecl)
Sebastian Redl0e35d042009-07-25 15:41:38 +00001028{
1029 // This test is outside everything else because it's the only case where
1030 // a non-lvalue-reference target type does not lead to decay.
1031 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1032 if (CastTy->isVoidType())
1033 return false;
1034
1035 // If the type is dependent, we won't do any other semantic analysis now.
1036 if (CastTy->isDependentType() || CastExpr->isTypeDependent())
1037 return false;
1038
1039 if (!CastTy->isLValueReferenceType())
1040 DefaultFunctionArrayConversion(CastExpr);
1041
1042 // C++ [expr.cast]p5: The conversions performed by
1043 // - a const_cast,
1044 // - a static_cast,
1045 // - a static_cast followed by a const_cast,
1046 // - a reinterpret_cast, or
1047 // - a reinterpret_cast followed by a const_cast,
1048 // can be performed using the cast notation of explicit type conversion.
1049 // [...] If a conversion can be interpreted in more than one of the ways
1050 // listed above, the interpretation that appears first in the list is used,
1051 // even if a cast resulting from that interpretation is ill-formed.
1052 // In plain language, this means trying a const_cast ...
1053 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssonf1957c82009-09-01 20:52:42 +00001054 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1055 msg);
Sebastian Redl0e35d042009-07-25 15:41:38 +00001056 if (tcr == TC_NotApplicable) {
1057 // ... or if that is not possible, a static_cast, ignoring const, ...
Anders Carlssonf1957c82009-09-01 20:52:42 +00001058 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, Kind, R, msg,
Fariborz Jahaniancf13d4a2009-08-26 18:55:36 +00001059 ConversionDecl);
Sebastian Redl0e35d042009-07-25 15:41:38 +00001060 if (tcr == TC_NotApplicable) {
1061 // ... and finally a reinterpret_cast, ignoring const.
Anders Carlssonf1957c82009-09-01 20:52:42 +00001062 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, Kind,
1063 R, msg);
Sebastian Redl0e35d042009-07-25 15:41:38 +00001064 }
1065 }
1066
Sebastian Redl0e35d042009-07-25 15:41:38 +00001067 if (tcr != TC_Success && msg != 0)
Sebastian Redlc358b622009-07-29 13:50:23 +00001068 Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
Sebastian Redl0e35d042009-07-25 15:41:38 +00001069 << CastExpr->getType() << CastTy << R;
1070
1071 return tcr != TC_Success;
1072}