blob: 57c4f9bc2a27b603d56f544f4ca61c43ab3d5ff3 [file] [log] [blame]
Sebastian Redl26d85b12008-11-05 21:50:06 +00001//===--- SemaNamedCast.cpp - Semantic Analysis for Named Casts ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ named casts.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000015#include "SemaInit.h"
Sebastian Redl26d85b12008-11-05 21:50:06 +000016#include "clang/AST/ExprCXX.h"
17#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000019#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redl26d85b12008-11-05 21:50:06 +000020#include "llvm/ADT/SmallVector.h"
Sebastian Redle3dc28a2008-11-07 23:29:29 +000021#include <set>
Sebastian Redl26d85b12008-11-05 21:50:06 +000022using namespace clang;
23
Sebastian Redl9cc11e72009-07-25 15:41:38 +000024enum TryCastResult {
25 TC_NotApplicable, ///< The cast method is not applicable.
26 TC_Success, ///< The cast method is appropriate and successful.
27 TC_Failed ///< The cast method is appropriate, but failed. A
28 ///< diagnostic has been emitted.
29};
30
31enum CastType {
32 CT_Const, ///< const_cast
33 CT_Static, ///< static_cast
34 CT_Reinterpret, ///< reinterpret_cast
35 CT_Dynamic, ///< dynamic_cast
36 CT_CStyle, ///< (Type)expr
37 CT_Functional ///< Type(expr)
Sebastian Redl37d6de32008-11-08 13:00:26 +000038};
39
40static void CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
41 const SourceRange &OpRange,
42 const SourceRange &DestRange);
43static void CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
44 const SourceRange &OpRange,
Anders Carlsson7f9e6462009-09-15 04:48:33 +000045 const SourceRange &DestRange,
46 CastExpr::CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +000047static void CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlssoncdb61972009-08-07 22:21:05 +000048 const SourceRange &OpRange,
Anders Carlsson0aebc812009-09-09 21:33:21 +000049 CastExpr::CastKind &Kind,
50 CXXMethodDecl *&ConversionDecl);
Sebastian Redl37d6de32008-11-08 13:00:26 +000051static void CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
52 const SourceRange &OpRange,
Mike Stump1eb44332009-09-09 15:08:12 +000053 const SourceRange &DestRange,
Anders Carlsson714179b2009-08-02 19:07:59 +000054 CastExpr::CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +000055
56static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000057
58// The Try functions attempt a specific way of casting. If they succeed, they
59// return TC_Success. If their way of casting is not appropriate for the given
60// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
61// to emit if no other way succeeds. If their way of casting is appropriate but
62// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
63// they emit a specialized diagnostic.
64// All diagnostics returned by these functions must expect the same three
65// arguments:
66// %0: Cast Type (a value from the CastType enumeration)
67// %1: Source Type
68// %2: Destination Type
69static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
70 QualType DestType, unsigned &msg);
71static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
72 QualType DestType, bool CStyle,
73 const SourceRange &OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +000074 unsigned &msg,
75 CastExpr::CastKind &Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000076static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
77 QualType DestType, bool CStyle,
78 const SourceRange &OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +000079 unsigned &msg,
80 CastExpr::CastKind &Kind);
Douglas Gregorab15d0e2009-11-15 09:20:52 +000081static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
82 CanQualType DestType, bool CStyle,
Sebastian Redl9cc11e72009-07-25 15:41:38 +000083 const SourceRange &OpRange,
84 QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +000085 QualType OrigDestType, unsigned &msg,
86 CastExpr::CastKind &Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000087static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType,
88 QualType DestType,bool CStyle,
89 const SourceRange &OpRange,
Anders Carlsson1a31a182009-10-30 00:46:35 +000090 unsigned &msg,
91 CastExpr::CastKind &Kind);
Sebastian Redla82e4ae2009-11-14 21:15:49 +000092static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +000093 QualType DestType, bool CStyle,
94 const SourceRange &OpRange,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +000095 unsigned &msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +000096 CastExpr::CastKind &Kind,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +000097 CXXMethodDecl *&ConversionDecl);
Sebastian Redla82e4ae2009-11-14 21:15:49 +000098static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +000099 QualType DestType, bool CStyle,
100 const SourceRange &OpRange,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000101 unsigned &msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000102 CastExpr::CastKind &Kind,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000103 CXXMethodDecl *&ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000104static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
105 bool CStyle, unsigned &msg);
106static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
107 QualType DestType, bool CStyle,
108 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000109 unsigned &msg,
110 CastExpr::CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +0000111
Sebastian Redl26d85b12008-11-05 21:50:06 +0000112/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000113Action::OwningExprResult
Sebastian Redl26d85b12008-11-05 21:50:06 +0000114Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
115 SourceLocation LAngleBracketLoc, TypeTy *Ty,
116 SourceLocation RAngleBracketLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000117 SourceLocation LParenLoc, ExprArg E,
Sebastian Redl26d85b12008-11-05 21:50:06 +0000118 SourceLocation RParenLoc) {
John McCallc89724c2010-01-15 19:13:16 +0000119
John McCall9d125032010-01-15 18:39:57 +0000120 TypeSourceInfo *DestTInfo;
121 QualType DestType = GetTypeFromParser(Ty, &DestTInfo);
122 if (!DestTInfo)
123 DestTInfo = Context.getTrivialTypeSourceInfo(DestType, SourceLocation());
John McCallc89724c2010-01-15 19:13:16 +0000124
125 return BuildCXXNamedCast(OpLoc, Kind, DestTInfo, move(E),
126 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
127 SourceRange(LParenLoc, RParenLoc));
128}
129
130Action::OwningExprResult
131Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
132 TypeSourceInfo *DestTInfo, ExprArg E,
133 SourceRange AngleBrackets, SourceRange Parens) {
134 Expr *Ex = E.takeAs<Expr>();
135 QualType DestType = DestTInfo->getType();
136
137 SourceRange OpRange(OpLoc, Parens.getEnd());
138 SourceRange DestRange = AngleBrackets;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000139
Douglas Gregor9103bb22008-12-17 22:52:20 +0000140 // If the type is dependent, we won't do the semantic analysis now.
141 // FIXME: should we check this in a more fine-grained manner?
142 bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
143
Sebastian Redl26d85b12008-11-05 21:50:06 +0000144 switch (Kind) {
145 default: assert(0 && "Unknown C++ cast!");
146
147 case tok::kw_const_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +0000148 if (!TypeDependent)
149 CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000150 return Owned(new (Context) CXXConstCastExpr(DestType.getNonReferenceType(),
John McCall9d125032010-01-15 18:39:57 +0000151 Ex, DestTInfo, OpLoc));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000152
Anders Carlsson714179b2009-08-02 19:07:59 +0000153 case tok::kw_dynamic_cast: {
154 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregor9103bb22008-12-17 22:52:20 +0000155 if (!TypeDependent)
Anders Carlsson714179b2009-08-02 19:07:59 +0000156 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000157 return Owned(new (Context)CXXDynamicCastExpr(DestType.getNonReferenceType(),
John McCall9d125032010-01-15 18:39:57 +0000158 Kind, Ex, DestTInfo, OpLoc));
Anders Carlsson714179b2009-08-02 19:07:59 +0000159 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000160 case tok::kw_reinterpret_cast: {
161 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregor9103bb22008-12-17 22:52:20 +0000162 if (!TypeDependent)
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000163 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000164 return Owned(new (Context) CXXReinterpretCastExpr(
165 DestType.getNonReferenceType(),
John McCall9d125032010-01-15 18:39:57 +0000166 Kind, Ex, DestTInfo, OpLoc));
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000167 }
Anders Carlssoncdb61972009-08-07 22:21:05 +0000168 case tok::kw_static_cast: {
169 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000170 if (!TypeDependent) {
171 CXXMethodDecl *Method = 0;
172
173 CheckStaticCast(*this, Ex, DestType, OpRange, Kind, Method);
174
175 if (Method) {
176 OwningExprResult CastArg
177 = BuildCXXCastArgument(OpLoc, DestType.getNonReferenceType(),
178 Kind, Method, Owned(Ex));
179 if (CastArg.isInvalid())
180 return ExprError();
181
182 Ex = CastArg.takeAs<Expr>();
183 }
184 }
185
Sebastian Redlf53597f2009-03-15 17:47:39 +0000186 return Owned(new (Context) CXXStaticCastExpr(DestType.getNonReferenceType(),
John McCall9d125032010-01-15 18:39:57 +0000187 Kind, Ex, DestTInfo, OpLoc));
Anders Carlssoncdb61972009-08-07 22:21:05 +0000188 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000189 }
190
Sebastian Redlf53597f2009-03-15 17:47:39 +0000191 return ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000192}
193
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000194/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
195/// this removes one level of indirection from both types, provided that they're
196/// the same kind of pointer (plain or to-member). Unlike the Sema function,
197/// this one doesn't care if the two pointers-to-member don't point into the
198/// same class. This is because CastsAwayConstness doesn't care.
199bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
200 const PointerType *T1PtrType = T1->getAs<PointerType>(),
201 *T2PtrType = T2->getAs<PointerType>();
202 if (T1PtrType && T2PtrType) {
203 T1 = T1PtrType->getPointeeType();
204 T2 = T2PtrType->getPointeeType();
205 return true;
206 }
207
208 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
209 *T2MPType = T2->getAs<MemberPointerType>();
210 if (T1MPType && T2MPType) {
211 T1 = T1MPType->getPointeeType();
212 T2 = T2MPType->getPointeeType();
213 return true;
214 }
215 return false;
216}
217
Sebastian Redldb647282009-01-27 23:18:31 +0000218/// CastsAwayConstness - Check if the pointer conversion from SrcType to
219/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
220/// the cast checkers. Both arguments must denote pointer (possibly to member)
221/// types.
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000222static bool
Mike Stump1eb44332009-09-09 15:08:12 +0000223CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
Sebastian Redldb647282009-01-27 23:18:31 +0000224 // Casting away constness is defined in C++ 5.2.11p8 with reference to
225 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
226 // the rules are non-trivial. So first we construct Tcv *...cv* as described
227 // in C++ 5.2.11p8.
228 assert((SrcType->isPointerType() || SrcType->isMemberPointerType()) &&
229 "Source type is not pointer or pointer to member.");
230 assert((DestType->isPointerType() || DestType->isMemberPointerType()) &&
231 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000232
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000233 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
234 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
John McCall0953e762009-09-24 19:53:00 +0000235 llvm::SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000236
237 // Find the qualifications.
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000238 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCall0953e762009-09-24 19:53:00 +0000239 cv1.push_back(UnwrappedSrcType.getQualifiers());
240 cv2.push_back(UnwrappedDestType.getQualifiers());
Sebastian Redl26d85b12008-11-05 21:50:06 +0000241 }
242 assert(cv1.size() > 0 && "Must have at least one pointer level.");
243
244 // Construct void pointers with those qualifiers (in reverse order of
245 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000246 QualType SrcConstruct = Self.Context.VoidTy;
247 QualType DestConstruct = Self.Context.VoidTy;
John McCall0953e762009-09-24 19:53:00 +0000248 ASTContext &Context = Self.Context;
249 for (llvm::SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
250 i2 = cv2.rbegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000251 i1 != cv1.rend(); ++i1, ++i2) {
John McCall0953e762009-09-24 19:53:00 +0000252 SrcConstruct
253 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
254 DestConstruct
255 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000256 }
257
258 // Test if they're compatible.
259 return SrcConstruct != DestConstruct &&
Sebastian Redl37d6de32008-11-08 13:00:26 +0000260 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000261}
262
Sebastian Redl26d85b12008-11-05 21:50:06 +0000263/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
264/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
265/// checked downcasts in class hierarchies.
Anders Carlsson714179b2009-08-02 19:07:59 +0000266static void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000267CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
268 const SourceRange &OpRange,
Mike Stump1eb44332009-09-09 15:08:12 +0000269 const SourceRange &DestRange, CastExpr::CastKind &Kind) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000270 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl37d6de32008-11-08 13:00:26 +0000271 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000272
273 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
274 // or "pointer to cv void".
275
276 QualType DestPointee;
Ted Kremenek6217b802009-07-29 21:53:49 +0000277 const PointerType *DestPointer = DestType->getAs<PointerType>();
278 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000279 if (DestPointer) {
280 DestPointee = DestPointer->getPointeeType();
281 } else if (DestReference) {
282 DestPointee = DestReference->getPointeeType();
283 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000284 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000285 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000286 return;
287 }
288
Ted Kremenek6217b802009-07-29 21:53:49 +0000289 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000290 if (DestPointee->isVoidType()) {
291 assert(DestPointer && "Reference to void is not possible");
292 } else if (DestRecord) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000293 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000294 PDiag(diag::err_bad_dynamic_cast_incomplete)
295 << DestRange))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000296 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000297 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000298 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000299 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000300 return;
301 }
302
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000303 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
304 // complete class type, [...]. If T is an lvalue reference type, v shall be
305 // an lvalue of a complete class type, [...]. If T is an rvalue reference
306 // type, v shall be an expression having a complete effective class type,
307 // [...]
Sebastian Redl26d85b12008-11-05 21:50:06 +0000308
Sebastian Redl37d6de32008-11-08 13:00:26 +0000309 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000310 QualType SrcPointee;
311 if (DestPointer) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000312 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000313 SrcPointee = SrcPointer->getPointeeType();
314 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000315 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000316 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000317 return;
318 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000319 } else if (DestReference->isLValueReferenceType()) {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000320 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000321 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000322 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000323 }
324 SrcPointee = SrcType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000325 } else {
326 SrcPointee = SrcType;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000327 }
328
Ted Kremenek6217b802009-07-29 21:53:49 +0000329 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000330 if (SrcRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000331 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000332 PDiag(diag::err_bad_dynamic_cast_incomplete)
333 << SrcExpr->getSourceRange()))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000334 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000335 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000336 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000337 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000338 return;
339 }
340
341 assert((DestPointer || DestReference) &&
342 "Bad destination non-ptr/ref slipped through.");
343 assert((DestRecord || DestPointee->isVoidType()) &&
344 "Bad destination pointee slipped through.");
345 assert(SrcRecord && "Bad source pointee slipped through.");
346
347 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
348 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000349 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000350 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000351 return;
352 }
353
354 // C++ 5.2.7p3: If the type of v is the same as the required result type,
355 // [except for cv].
356 if (DestRecord == SrcRecord) {
357 return;
358 }
359
360 // C++ 5.2.7p5
361 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000362 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
363 Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
Chris Lattnerd1625842008-11-24 06:25:27 +0000364 OpRange.getBegin(), OpRange);
Anders Carlsson714179b2009-08-02 19:07:59 +0000365 Kind = CastExpr::CK_DerivedToBase;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000366 // Diagnostic already emitted on error.
367 return;
368 }
369
370 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Sebastian Redl37d6de32008-11-08 13:00:26 +0000371 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(Self.Context);
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000372 assert(SrcDecl && "Definition missing");
373 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000374 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000375 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000376 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000377
378 // Done. Everything else is run-time checks.
Anders Carlsson714179b2009-08-02 19:07:59 +0000379 Kind = CastExpr::CK_Dynamic;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000380}
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000381
382/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
383/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
384/// like this:
385/// const char *str = "literal";
386/// legacy_function(const_cast\<char*\>(str));
387void
388CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000389 const SourceRange &OpRange, const SourceRange &DestRange) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000390 if (!DestType->isLValueReferenceType())
391 Self.DefaultFunctionArrayConversion(SrcExpr);
392
393 unsigned msg = diag::err_bad_cxx_cast_generic;
394 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
395 && msg != 0)
396 Self.Diag(OpRange.getBegin(), msg) << CT_Const
397 << SrcExpr->getType() << DestType << OpRange;
398}
399
400/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
401/// valid.
402/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
403/// like this:
404/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
405void
406CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000407 const SourceRange &OpRange, const SourceRange &DestRange,
408 CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000409 if (!DestType->isLValueReferenceType())
410 Self.DefaultFunctionArrayConversion(SrcExpr);
411
412 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson3c31a392009-09-26 00:12:34 +0000413 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
414 msg, Kind)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000415 != TC_Success && msg != 0)
416 Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
417 << SrcExpr->getType() << DestType << OpRange;
418}
419
420
421/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
422/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
423/// implicit conversions explicit and getting rid of data loss warnings.
424void
425CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson0aebc812009-09-09 21:33:21 +0000426 const SourceRange &OpRange, CastExpr::CastKind &Kind,
427 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000428 // This test is outside everything else because it's the only case where
429 // a non-lvalue-reference target type does not lead to decay.
430 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000431 if (DestType->isVoidType()) {
432 Kind = CastExpr::CK_ToVoid;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000433 return;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000434 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000435
Douglas Gregorb653c522009-11-06 01:14:41 +0000436 if (!DestType->isLValueReferenceType() && !DestType->isRecordType())
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000437 Self.DefaultFunctionArrayConversion(SrcExpr);
438
439 unsigned msg = diag::err_bad_cxx_cast_generic;
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000440 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000441 Kind, ConversionDecl)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000442 != TC_Success && msg != 0)
443 Self.Diag(OpRange.getBegin(), msg) << CT_Static
444 << SrcExpr->getType() << DestType << OpRange;
445}
446
447/// TryStaticCast - Check if a static cast can be performed, and do so if
448/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
449/// and casting away constness.
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000450static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000451 QualType DestType, bool CStyle,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000452 const SourceRange &OpRange, unsigned &msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000453 CastExpr::CastKind &Kind,
Mike Stump1eb44332009-09-09 15:08:12 +0000454 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000455 // The order the tests is not entirely arbitrary. There is one conversion
456 // that can be handled in two different ways. Given:
457 // struct A {};
458 // struct B : public A {
459 // B(); B(const A&);
460 // };
461 // const A &a = B();
462 // the cast static_cast<const B&>(a) could be seen as either a static
463 // reference downcast, or an explicit invocation of the user-defined
464 // conversion using B's conversion constructor.
465 // DR 427 specifies that the downcast is to be applied here.
466
467 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
468 // Done outside this function.
469
470 TryCastResult tcr;
471
472 // C++ 5.2.9p5, reference downcast.
473 // See the function for details.
474 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000475 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle, OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000476 msg, Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000477 if (tcr != TC_NotApplicable)
478 return tcr;
479
480 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
481 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
482 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000483 if (tcr != TC_NotApplicable) {
484 Kind = CastExpr::CK_NoOp;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000485 return tcr;
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000486 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000487
488 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
489 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000490 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000491 Kind, ConversionDecl);
492 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000493 return tcr;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000494
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000495 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
496 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
497 // conversions, subject to further restrictions.
498 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
499 // of qualification conversions impossible.
500 // In the CStyle case, the earlier attempt to const_cast should have taken
501 // care of reverse qualification conversions.
502
503 QualType OrigSrcType = SrcExpr->getType();
504
505 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
506
507 // Reverse integral promotion/conversion. All such conversions are themselves
508 // again integral promotions or conversions and are thus already handled by
509 // p2 (TryDirectInitialization above).
510 // (Note: any data loss warnings should be suppressed.)
511 // The exception is the reverse of enum->integer, i.e. integer->enum (and
512 // enum->enum). See also C++ 5.2.9p7.
513 // The same goes for reverse floating point promotion/conversion and
514 // floating-integral conversions. Again, only floating->enum is relevant.
515 if (DestType->isEnumeralType()) {
516 if (SrcType->isComplexType() || SrcType->isVectorType()) {
517 // Fall through - these cannot be converted.
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000518 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
519 Kind = CastExpr::CK_IntegralCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000520 return TC_Success;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000521 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000522 }
523
524 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
525 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000526 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
527 Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000528 if (tcr != TC_NotApplicable)
529 return tcr;
530
531 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
532 // conversion. C++ 5.2.9p9 has additional information.
533 // DR54's access restrictions apply here also.
534 tcr = TryStaticMemberPointerUpcast(Self, SrcType, DestType, CStyle,
Anders Carlsson1a31a182009-10-30 00:46:35 +0000535 OpRange, msg, Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000536 if (tcr != TC_NotApplicable)
537 return tcr;
538
539 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
540 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
541 // just the usual constness stuff.
Ted Kremenek6217b802009-07-29 21:53:49 +0000542 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000543 QualType SrcPointee = SrcPointer->getPointeeType();
544 if (SrcPointee->isVoidType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000545 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000546 QualType DestPointee = DestPointer->getPointeeType();
547 if (DestPointee->isIncompleteOrObjectType()) {
548 // This is definitely the intended conversion, but it might fail due
549 // to a const violation.
550 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
551 msg = diag::err_bad_cxx_cast_const_away;
552 return TC_Failed;
553 }
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000554 Kind = CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000555 return TC_Success;
556 }
557 }
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +0000558 else if (CStyle && DestType->isObjCObjectPointerType()) {
559 // allow c-style cast of objective-c pointers as they are pervasive.
560 Kind = CastExpr::CK_AnyPointerToObjCPointerCast;
561 return TC_Success;
562 }
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +0000563 else if (CStyle && DestType->isBlockPointerType()) {
564 // allow c-style cast of void * to block pointers.
565 Kind = CastExpr::CK_AnyPointerToBlockPointerCast;
566 return TC_Success;
567 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000568 }
569 }
570
571 // We tried everything. Everything! Nothing works! :-(
572 return TC_NotApplicable;
573}
574
575/// Tests whether a conversion according to N2844 is valid.
576TryCastResult
577TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000578 unsigned &msg) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000579 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
580 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenek6217b802009-07-29 21:53:49 +0000581 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000582 if (!R)
583 return TC_NotApplicable;
584
585 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
586 return TC_NotApplicable;
587
588 // Because we try the reference downcast before this function, from now on
589 // this is the only cast possibility, so we issue an error if we fail now.
590 // FIXME: Should allow casting away constness if CStyle.
591 bool DerivedToBase;
Douglas Gregor393896f2009-11-05 13:06:35 +0000592 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
593 SrcExpr->getType(), R->getPointeeType(),
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000594 DerivedToBase) <
595 Sema::Ref_Compatible_With_Added_Qualification) {
596 msg = diag::err_bad_lvalue_to_rvalue_cast;
597 return TC_Failed;
598 }
599
600 // FIXME: Similar to CheckReferenceInit, we actually need more AST annotation
601 // than nothing.
602 return TC_Success;
603}
604
605/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
606TryCastResult
607TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
608 bool CStyle, const SourceRange &OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000609 unsigned &msg, CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000610 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
611 // cast to type "reference to cv2 D", where D is a class derived from B,
612 // if a valid standard conversion from "pointer to D" to "pointer to B"
613 // exists, cv2 >= cv1, and B is not a virtual base class of D.
614 // In addition, DR54 clarifies that the base must be accessible in the
615 // current context. Although the wording of DR54 only applies to the pointer
616 // variant of this rule, the intent is clearly for it to apply to the this
617 // conversion as well.
618
Ted Kremenek6217b802009-07-29 21:53:49 +0000619 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000620 if (!DestReference) {
621 return TC_NotApplicable;
622 }
623 bool RValueRef = DestReference->isRValueReferenceType();
624 if (!RValueRef && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
625 // We know the left side is an lvalue reference, so we can suggest a reason.
626 msg = diag::err_bad_cxx_cast_rvalue;
627 return TC_NotApplicable;
628 }
629
630 QualType DestPointee = DestReference->getPointeeType();
631
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000632 return TryStaticDowncast(Self,
633 Self.Context.getCanonicalType(SrcExpr->getType()),
634 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000635 OpRange, SrcExpr->getType(), DestType, msg, Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000636}
637
638/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
639TryCastResult
640TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000641 bool CStyle, const SourceRange &OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000642 unsigned &msg, CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000643 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
644 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
645 // is a class derived from B, if a valid standard conversion from "pointer
646 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
647 // class of D.
648 // In addition, DR54 clarifies that the base must be accessible in the
649 // current context.
650
Ted Kremenek6217b802009-07-29 21:53:49 +0000651 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000652 if (!DestPointer) {
653 return TC_NotApplicable;
654 }
655
Ted Kremenek6217b802009-07-29 21:53:49 +0000656 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000657 if (!SrcPointer) {
658 msg = diag::err_bad_static_cast_pointer_nonpointer;
659 return TC_NotApplicable;
660 }
661
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000662 return TryStaticDowncast(Self,
663 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
664 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
665 CStyle, OpRange, SrcType, DestType, msg, Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000666}
667
668/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
669/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000670/// DestType is possible and allowed.
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000671TryCastResult
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000672TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000673 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000674 QualType OrigDestType, unsigned &msg,
675 CastExpr::CastKind &Kind) {
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000676 // We can only work with complete types. But don't complain if it doesn't work
677 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, PDiag(0)) ||
678 Self.RequireCompleteType(OpRange.getBegin(), DestType, PDiag(0)))
679 return TC_NotApplicable;
680
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000681 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000682 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000683 return TC_NotApplicable;
684 }
685
Douglas Gregora8f32e02009-10-06 17:59:45 +0000686 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
687 /*DetectVirtual=*/true);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000688 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
689 return TC_NotApplicable;
690 }
691
692 // Target type does derive from source type. Now we're serious. If an error
693 // appears now, it's not ignored.
694 // This may not be entirely in line with the standard. Take for example:
695 // struct A {};
696 // struct B : virtual A {
697 // B(A&);
698 // };
Mike Stump1eb44332009-09-09 15:08:12 +0000699 //
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000700 // void f()
701 // {
702 // (void)static_cast<const B&>(*((A*)0));
703 // }
704 // As far as the standard is concerned, p5 does not apply (A is virtual), so
705 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
706 // However, both GCC and Comeau reject this example, and accepting it would
707 // mean more complex code if we're to preserve the nice error message.
708 // FIXME: Being 100% compliant here would be nice to have.
709
710 // Must preserve cv, as always, unless we're in C-style mode.
711 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
712 msg = diag::err_bad_cxx_cast_const_away;
713 return TC_Failed;
714 }
715
716 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
717 // This code is analoguous to that in CheckDerivedToBaseConversion, except
718 // that it builds the paths in reverse order.
719 // To sum up: record all paths to the base and build a nice string from
720 // them. Use it to spice up the error message.
721 if (!Paths.isRecordingPaths()) {
722 Paths.clear();
723 Paths.setRecordingPaths(true);
724 Self.IsDerivedFrom(DestType, SrcType, Paths);
725 }
726 std::string PathDisplayStr;
727 std::set<unsigned> DisplayedPaths;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000728 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000729 PI != PE; ++PI) {
730 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
731 // We haven't displayed a path to this particular base
732 // class subobject yet.
733 PathDisplayStr += "\n ";
Douglas Gregora8f32e02009-10-06 17:59:45 +0000734 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
735 EE = PI->rend();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000736 EI != EE; ++EI)
737 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000738 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000739 }
740 }
741
742 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000743 << QualType(SrcType).getUnqualifiedType()
744 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000745 << PathDisplayStr << OpRange;
746 msg = 0;
747 return TC_Failed;
748 }
749
750 if (Paths.getDetectedVirtual() != 0) {
751 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
752 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
753 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
754 msg = 0;
755 return TC_Failed;
756 }
757
758 if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
759 diag::err_downcast_from_inaccessible_base, Paths,
760 OpRange.getBegin(), DeclarationName())) {
761 msg = 0;
762 return TC_Failed;
763 }
764
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000765 Kind = CastExpr::CK_BaseToDerived;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000766 return TC_Success;
767}
768
769/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
770/// C++ 5.2.9p9 is valid:
771///
772/// An rvalue of type "pointer to member of D of type cv1 T" can be
773/// converted to an rvalue of type "pointer to member of B of type cv2 T",
774/// where B is a base class of D [...].
775///
776TryCastResult
777TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType, QualType DestType,
778 bool CStyle, const SourceRange &OpRange,
Anders Carlsson1a31a182009-10-30 00:46:35 +0000779 unsigned &msg, CastExpr::CastKind &Kind) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000780 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000781 if (!DestMemPtr)
782 return TC_NotApplicable;
Ted Kremenek6217b802009-07-29 21:53:49 +0000783 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000784 if (!SrcMemPtr) {
785 msg = diag::err_bad_static_cast_member_pointer_nonmp;
786 return TC_NotApplicable;
787 }
788
789 // T == T, modulo cv
Douglas Gregora4923eb2009-11-16 21:35:15 +0000790 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
791 DestMemPtr->getPointeeType()))
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000792 return TC_NotApplicable;
793
794 // B base of D
795 QualType SrcClass(SrcMemPtr->getClass(), 0);
796 QualType DestClass(DestMemPtr->getClass(), 0);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000797 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000798 /*DetectVirtual=*/true);
799 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
800 return TC_NotApplicable;
801 }
802
803 // B is a base of D. But is it an allowed base? If not, it's a hard error.
804 if (Paths.isAmbiguous(DestClass)) {
805 Paths.clear();
806 Paths.setRecordingPaths(true);
807 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
808 assert(StillOkay);
809 StillOkay = StillOkay;
810 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
811 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
812 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
813 msg = 0;
814 return TC_Failed;
815 }
816
817 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
818 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
819 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
820 msg = 0;
821 return TC_Failed;
822 }
823
824 if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
825 diag::err_downcast_from_inaccessible_base, Paths,
826 OpRange.getBegin(), DeclarationName())) {
827 msg = 0;
828 return TC_Failed;
829 }
830
Anders Carlsson1a31a182009-10-30 00:46:35 +0000831 Kind = CastExpr::CK_DerivedToBaseMemberPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000832 return TC_Success;
833}
834
835/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
836/// is valid:
837///
838/// An expression e can be explicitly converted to a type T using a
839/// @c static_cast if the declaration "T t(e);" is well-formed [...].
840TryCastResult
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000841TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000842 bool CStyle, const SourceRange &OpRange, unsigned &msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000843 CastExpr::CastKind &Kind,
Mike Stump1eb44332009-09-09 15:08:12 +0000844 CXXMethodDecl *&ConversionDecl) {
Anders Carlssond851b372009-09-07 18:25:47 +0000845 if (DestType->isRecordType()) {
846 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
847 diag::err_bad_dynamic_cast_incomplete)) {
848 msg = 0;
849 return TC_Failed;
850 }
851 }
Mike Stump1eb44332009-09-09 15:08:12 +0000852
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000853 if (DestType->isReferenceType()) {
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000854 // All reference bindings insert implicit casts above that do the actual
855 // casting.
856 Kind = CastExpr::CK_NoOp;
857
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000858 // At this point of CheckStaticCast, if the destination is a reference,
859 // this has to work. There is no other way that works.
860 // On the other hand, if we're checking a C-style cast, we've still got
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000861 // the reinterpret_cast way. So in C-style mode, we first try the call
862 // with an ICS to suppress errors.
863 if (CStyle) {
864 ImplicitConversionSequence ICS;
865 if(Self.CheckReferenceInit(SrcExpr, DestType, OpRange.getBegin(),
866 /*SuppressUserConversions=*/false,
867 /*AllowExplicit=*/false, /*ForceRValue=*/false,
868 &ICS))
869 return TC_NotApplicable;
870 }
871 // Now we're committed either way.
872 if(!Self.CheckReferenceInit(SrcExpr, DestType, OpRange.getBegin(),
873 /*SuppressUserConversions=*/false,
874 /*AllowExplicit=*/false,
875 /*ForceRValue=*/false, 0,
876 /*IgnoreBaseAccess=*/CStyle))
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000877 return TC_Success;
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000878
879 // We already got an error message.
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000880 msg = 0;
881 return TC_Failed;
882 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000883
Douglas Gregor19aeac62009-11-14 03:27:21 +0000884 if (DestType->isRecordType()) {
885 if (CXXConstructorDecl *Constructor
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000886 = Self.TryInitializationByConstructor(DestType, &SrcExpr, 1,
Douglas Gregor19aeac62009-11-14 03:27:21 +0000887 OpRange.getBegin(),
Douglas Gregor20093b42009-12-09 23:02:17 +0000888 InitializationKind::CreateDirect(OpRange.getBegin(),
889 OpRange.getBegin(),
890 OpRange.getEnd()))) {
Douglas Gregor19aeac62009-11-14 03:27:21 +0000891 ConversionDecl = Constructor;
892 Kind = CastExpr::CK_ConstructorConversion;
893 return TC_Success;
894 }
895
896 return TC_NotApplicable;
897 }
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000898
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000899 // FIXME: To get a proper error from invalid conversions here, we need to
900 // reimplement more of this.
901 // FIXME: This does not actually perform the conversion, and thus does not
902 // check for ambiguity or access.
Mike Stump1eb44332009-09-09 15:08:12 +0000903 ImplicitConversionSequence ICS =
Anders Carlssonda7a18b2009-08-27 17:24:15 +0000904 Self.TryImplicitConversion(SrcExpr, DestType,
905 /*SuppressUserConversions=*/false,
Anders Carlsson83b534c2009-08-28 16:22:20 +0000906 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +0000907 /*ForceRValue=*/false,
Fariborz Jahanian249cead2009-10-01 20:39:51 +0000908 /*InOverloadResolution=*/false,
909 /*one of user provided casts*/true);
Mike Stump1eb44332009-09-09 15:08:12 +0000910
John McCall1d318332010-01-12 00:44:57 +0000911 if (ICS.isBad())
Anders Carlsson3c31a392009-09-26 00:12:34 +0000912 return TC_NotApplicable;
913
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000914 // The conversion is possible, so commit to it.
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000915 Kind = CastExpr::CK_NoOp;
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000916 msg = 0;
Douglas Gregor68647482009-12-16 03:45:30 +0000917 return Self.PerformImplicitConversion(SrcExpr, DestType, ICS, Sema::AA_Casting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000918 /*IgnoreBaseAccess*/CStyle) ?
919 TC_Failed : TC_Success;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000920}
921
922/// TryConstCast - See if a const_cast from source to destination is allowed,
923/// and perform it if it is.
924static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
925 bool CStyle, unsigned &msg) {
926 DestType = Self.Context.getCanonicalType(DestType);
927 QualType SrcType = SrcExpr->getType();
928 if (const LValueReferenceType *DestTypeTmp =
Ted Kremenek6217b802009-07-29 21:53:49 +0000929 DestType->getAs<LValueReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000930 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
931 // Cannot const_cast non-lvalue to lvalue reference type. But if this
932 // is C-style, static_cast might find a way, so we simply suggest a
933 // message and tell the parent to keep searching.
934 msg = diag::err_bad_cxx_cast_rvalue;
935 return TC_NotApplicable;
936 }
937
938 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
939 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
940 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
941 SrcType = Self.Context.getPointerType(SrcType);
942 }
943
944 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
945 // the rules for const_cast are the same as those used for pointers.
946
947 if (!DestType->isPointerType() && !DestType->isMemberPointerType()) {
948 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
949 // was a reference type, we converted it to a pointer above.
950 // The status of rvalue references isn't entirely clear, but it looks like
951 // conversion to them is simply invalid.
952 // C++ 5.2.11p3: For two pointer types [...]
953 if (!CStyle)
954 msg = diag::err_bad_const_cast_dest;
955 return TC_NotApplicable;
956 }
957 if (DestType->isFunctionPointerType() ||
958 DestType->isMemberFunctionPointerType()) {
959 // Cannot cast direct function pointers.
960 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
961 // T is the ultimate pointee of source and target type.
962 if (!CStyle)
963 msg = diag::err_bad_const_cast_dest;
964 return TC_NotApplicable;
965 }
966 SrcType = Self.Context.getCanonicalType(SrcType);
967
968 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
969 // completely equal.
970 // FIXME: const_cast should probably not be able to convert between pointers
971 // to different address spaces.
972 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
973 // in multi-level pointers may change, but the level count must be the same,
974 // as must be the final pointee type.
975 while (SrcType != DestType &&
976 Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Chandler Carruth595e2902009-12-29 08:05:19 +0000977 Qualifiers Quals;
978 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, Quals);
979 DestType = Self.Context.getUnqualifiedArrayType(DestType, Quals);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000980 }
981
982 // Since we're dealing in canonical types, the remainder must be the same.
983 if (SrcType != DestType)
984 return TC_NotApplicable;
985
986 return TC_Success;
987}
988
989static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
990 QualType DestType, bool CStyle,
991 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000992 unsigned &msg,
993 CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000994 DestType = Self.Context.getCanonicalType(DestType);
995 QualType SrcType = SrcExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000996 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000997 bool LValue = DestTypeTmp->isLValueReferenceType();
998 if (LValue && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
999 // Cannot cast non-lvalue to reference type. See the similar comment in
1000 // const_cast.
1001 msg = diag::err_bad_cxx_cast_rvalue;
1002 return TC_NotApplicable;
1003 }
1004
1005 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1006 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1007 // built-in & and * operators.
1008 // This code does this transformation for the checked types.
1009 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1010 SrcType = Self.Context.getPointerType(SrcType);
1011 }
1012
1013 // Canonicalize source for comparison.
1014 SrcType = Self.Context.getCanonicalType(SrcType);
1015
Ted Kremenek6217b802009-07-29 21:53:49 +00001016 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1017 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001018 if (DestMemPtr && SrcMemPtr) {
1019 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1020 // can be explicitly converted to an rvalue of type "pointer to member
1021 // of Y of type T2" if T1 and T2 are both function types or both object
1022 // types.
1023 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1024 SrcMemPtr->getPointeeType()->isFunctionType())
1025 return TC_NotApplicable;
1026
1027 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1028 // constness.
1029 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1030 // we accept it.
1031 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1032 msg = diag::err_bad_cxx_cast_const_away;
1033 return TC_Failed;
1034 }
1035
1036 // A valid member pointer cast.
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001037 Kind = CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001038 return TC_Success;
1039 }
1040
1041 // See below for the enumeral issue.
1042 if (SrcType->isNullPtrType() && DestType->isIntegralType() &&
1043 !DestType->isEnumeralType()) {
1044 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1045 // type large enough to hold it. A value of std::nullptr_t can be
1046 // converted to an integral type; the conversion has the same meaning
1047 // and validity as a conversion of (void*)0 to the integral type.
1048 if (Self.Context.getTypeSize(SrcType) >
1049 Self.Context.getTypeSize(DestType)) {
1050 msg = diag::err_bad_reinterpret_cast_small_int;
1051 return TC_Failed;
1052 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001053 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001054 return TC_Success;
1055 }
1056
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001057 bool destIsVector = DestType->isVectorType();
1058 bool srcIsVector = SrcType->isVectorType();
1059 if (srcIsVector || destIsVector) {
1060 bool srcIsScalar = SrcType->isIntegralType() && !SrcType->isEnumeralType();
1061 bool destIsScalar =
1062 DestType->isIntegralType() && !DestType->isEnumeralType();
1063
1064 // Check if this is a cast between a vector and something else.
1065 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1066 !(srcIsVector && destIsVector))
1067 return TC_NotApplicable;
1068
1069 // If both types have the same size, we can successfully cast.
Douglas Gregorf2a55392009-12-22 22:47:22 +00001070 if (Self.Context.getTypeSize(SrcType)
1071 == Self.Context.getTypeSize(DestType)) {
1072 Kind = CastExpr::CK_BitCast;
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001073 return TC_Success;
Douglas Gregorf2a55392009-12-22 22:47:22 +00001074 }
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001075
1076 if (destIsScalar)
1077 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1078 else if (srcIsScalar)
1079 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1080 else
1081 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1082
1083 return TC_Failed;
1084 }
1085
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001086 bool destIsPtr =
1087 CStyle? DestType->isAnyPointerType() : DestType->isPointerType();
1088 bool srcIsPtr =
1089 CStyle ? SrcType->isAnyPointerType() : SrcType->isPointerType();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001090 if (!destIsPtr && !srcIsPtr) {
1091 // Except for std::nullptr_t->integer and lvalue->reference, which are
1092 // handled above, at least one of the two arguments must be a pointer.
1093 return TC_NotApplicable;
1094 }
1095
1096 if (SrcType == DestType) {
1097 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1098 // restrictions, a cast to the same type is allowed. The intent is not
1099 // entirely clear here, since all other paragraphs explicitly forbid casts
1100 // to the same type. However, the behavior of compilers is pretty consistent
1101 // on this point: allow same-type conversion if the involved types are
1102 // pointers, disallow otherwise.
Douglas Gregorf2a55392009-12-22 22:47:22 +00001103 Kind = CastExpr::CK_NoOp;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001104 return TC_Success;
1105 }
1106
1107 // Note: Clang treats enumeration types as integral types. If this is ever
1108 // changed for C++, the additional check here will be redundant.
1109 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
1110 assert(srcIsPtr && "One type must be a pointer");
1111 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1112 // type large enough to hold it.
1113 if (Self.Context.getTypeSize(SrcType) >
1114 Self.Context.getTypeSize(DestType)) {
1115 msg = diag::err_bad_reinterpret_cast_small_int;
1116 return TC_Failed;
1117 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001118 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001119 return TC_Success;
1120 }
1121
1122 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
1123 assert(destIsPtr && "One type must be a pointer");
1124 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1125 // converted to a pointer.
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001126 Kind = CastExpr::CK_IntegralToPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001127 return TC_Success;
1128 }
1129
1130 if (!destIsPtr || !srcIsPtr) {
1131 // With the valid non-pointer conversions out of the way, we can be even
1132 // more stringent.
1133 return TC_NotApplicable;
1134 }
1135
1136 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1137 // The C-style cast operator can.
1138 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1139 msg = diag::err_bad_cxx_cast_const_away;
1140 return TC_Failed;
1141 }
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001142 if (CStyle && DestType->isObjCObjectPointerType()) {
1143 Kind = CastExpr::CK_AnyPointerToObjCPointerCast;
1144 return TC_Success;
1145 }
1146
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001147 // Not casting away constness, so the only remaining check is for compatible
1148 // pointer categories.
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001149 Kind = CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001150
1151 if (SrcType->isFunctionPointerType()) {
1152 if (DestType->isFunctionPointerType()) {
1153 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1154 // a pointer to a function of a different type.
1155 return TC_Success;
1156 }
1157
1158 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1159 // an object type or vice versa is conditionally-supported.
1160 // Compilers support it in C++03 too, though, because it's necessary for
1161 // casting the return value of dlsym() and GetProcAddress().
1162 // FIXME: Conditionally-supported behavior should be configurable in the
1163 // TargetInfo or similar.
1164 if (!Self.getLangOptions().CPlusPlus0x)
1165 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1166 return TC_Success;
1167 }
1168
1169 if (DestType->isFunctionPointerType()) {
1170 // See above.
1171 if (!Self.getLangOptions().CPlusPlus0x)
1172 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1173 return TC_Success;
1174 }
1175
1176 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1177 // a pointer to an object of different type.
1178 // Void pointers are not specified, but supported by every compiler out there.
1179 // So we finish by allowing everything that remains - it's got to be two
1180 // object pointers.
1181 return TC_Success;
1182}
1183
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00001184bool Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00001185 CastExpr::CastKind &Kind, bool FunctionalStyle,
Mike Stump1eb44332009-09-09 15:08:12 +00001186 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001187 // This test is outside everything else because it's the only case where
1188 // a non-lvalue-reference target type does not lead to decay.
1189 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001190 if (CastTy->isVoidType()) {
1191 Kind = CastExpr::CK_ToVoid;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001192 return false;
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001193 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001194
1195 // If the type is dependent, we won't do any other semantic analysis now.
1196 if (CastTy->isDependentType() || CastExpr->isTypeDependent())
1197 return false;
1198
Douglas Gregorb653c522009-11-06 01:14:41 +00001199 if (!CastTy->isLValueReferenceType() && !CastTy->isRecordType())
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001200 DefaultFunctionArrayConversion(CastExpr);
1201
1202 // C++ [expr.cast]p5: The conversions performed by
1203 // - a const_cast,
1204 // - a static_cast,
1205 // - a static_cast followed by a const_cast,
1206 // - a reinterpret_cast, or
1207 // - a reinterpret_cast followed by a const_cast,
1208 // can be performed using the cast notation of explicit type conversion.
1209 // [...] If a conversion can be interpreted in more than one of the ways
1210 // listed above, the interpretation that appears first in the list is used,
1211 // even if a cast resulting from that interpretation is ill-formed.
1212 // In plain language, this means trying a const_cast ...
1213 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001214 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1215 msg);
Anders Carlssonda921fd2009-10-19 18:14:28 +00001216 if (tcr == TC_Success)
1217 Kind = CastExpr::CK_NoOp;
1218
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001219 if (tcr == TC_NotApplicable) {
1220 // ... or if that is not possible, a static_cast, ignoring const, ...
Anders Carlsson3c31a392009-09-26 00:12:34 +00001221 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1222 Kind, ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001223 if (tcr == TC_NotApplicable) {
1224 // ... and finally a reinterpret_cast, ignoring const.
Anders Carlsson3c31a392009-09-26 00:12:34 +00001225 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1226 Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001227 }
1228 }
1229
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001230 if (tcr != TC_Success && msg != 0)
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00001231 Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001232 << CastExpr->getType() << CastTy << R;
1233
1234 return tcr != TC_Success;
1235}