blob: 0097cd363c8caa81a8040813062df7a664f5b4cd [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 }
Fariborz Jahanian72a86592010-02-03 20:32:31 +0000207 const ObjCObjectPointerType *T1ObjCPtrType =
208 T1->getAs<ObjCObjectPointerType>(),
209 *T2ObjCPtrType =
210 T2->getAs<ObjCObjectPointerType>();
211 if (T1ObjCPtrType) {
212 if (T2ObjCPtrType) {
213 T1 = T1ObjCPtrType->getPointeeType();
214 T2 = T2ObjCPtrType->getPointeeType();
215 return true;
216 }
217 else if (T2PtrType) {
218 T1 = T1ObjCPtrType->getPointeeType();
219 T2 = T2PtrType->getPointeeType();
220 return true;
221 }
222 }
223 else if (T2ObjCPtrType) {
224 if (T1PtrType) {
225 T2 = T2ObjCPtrType->getPointeeType();
226 T1 = T1PtrType->getPointeeType();
227 return true;
228 }
229 }
230
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000231 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
232 *T2MPType = T2->getAs<MemberPointerType>();
233 if (T1MPType && T2MPType) {
234 T1 = T1MPType->getPointeeType();
235 T2 = T2MPType->getPointeeType();
236 return true;
237 }
238 return false;
239}
240
Sebastian Redldb647282009-01-27 23:18:31 +0000241/// CastsAwayConstness - Check if the pointer conversion from SrcType to
242/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
243/// the cast checkers. Both arguments must denote pointer (possibly to member)
244/// types.
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000245static bool
Mike Stump1eb44332009-09-09 15:08:12 +0000246CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
Sebastian Redldb647282009-01-27 23:18:31 +0000247 // Casting away constness is defined in C++ 5.2.11p8 with reference to
248 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
249 // the rules are non-trivial. So first we construct Tcv *...cv* as described
250 // in C++ 5.2.11p8.
Fariborz Jahanian72a86592010-02-03 20:32:31 +0000251 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000252 "Source type is not pointer or pointer to member.");
Fariborz Jahanian72a86592010-02-03 20:32:31 +0000253 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000254 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000255
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000256 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
257 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
John McCall0953e762009-09-24 19:53:00 +0000258 llvm::SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000259
260 // Find the qualifications.
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000261 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCall0953e762009-09-24 19:53:00 +0000262 cv1.push_back(UnwrappedSrcType.getQualifiers());
263 cv2.push_back(UnwrappedDestType.getQualifiers());
Sebastian Redl26d85b12008-11-05 21:50:06 +0000264 }
265 assert(cv1.size() > 0 && "Must have at least one pointer level.");
266
267 // Construct void pointers with those qualifiers (in reverse order of
268 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000269 QualType SrcConstruct = Self.Context.VoidTy;
270 QualType DestConstruct = Self.Context.VoidTy;
John McCall0953e762009-09-24 19:53:00 +0000271 ASTContext &Context = Self.Context;
272 for (llvm::SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
273 i2 = cv2.rbegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000274 i1 != cv1.rend(); ++i1, ++i2) {
John McCall0953e762009-09-24 19:53:00 +0000275 SrcConstruct
276 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
277 DestConstruct
278 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000279 }
280
281 // Test if they're compatible.
282 return SrcConstruct != DestConstruct &&
Sebastian Redl37d6de32008-11-08 13:00:26 +0000283 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000284}
285
Sebastian Redl26d85b12008-11-05 21:50:06 +0000286/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
287/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
288/// checked downcasts in class hierarchies.
Anders Carlsson714179b2009-08-02 19:07:59 +0000289static void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000290CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
291 const SourceRange &OpRange,
Mike Stump1eb44332009-09-09 15:08:12 +0000292 const SourceRange &DestRange, CastExpr::CastKind &Kind) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000293 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl37d6de32008-11-08 13:00:26 +0000294 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000295
296 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
297 // or "pointer to cv void".
298
299 QualType DestPointee;
Ted Kremenek6217b802009-07-29 21:53:49 +0000300 const PointerType *DestPointer = DestType->getAs<PointerType>();
301 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000302 if (DestPointer) {
303 DestPointee = DestPointer->getPointeeType();
304 } else if (DestReference) {
305 DestPointee = DestReference->getPointeeType();
306 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000307 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000308 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000309 return;
310 }
311
Ted Kremenek6217b802009-07-29 21:53:49 +0000312 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000313 if (DestPointee->isVoidType()) {
314 assert(DestPointer && "Reference to void is not possible");
315 } else if (DestRecord) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000316 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000317 PDiag(diag::err_bad_dynamic_cast_incomplete)
318 << DestRange))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000319 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000320 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000321 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000322 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000323 return;
324 }
325
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000326 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
327 // complete class type, [...]. If T is an lvalue reference type, v shall be
328 // an lvalue of a complete class type, [...]. If T is an rvalue reference
329 // type, v shall be an expression having a complete effective class type,
330 // [...]
Sebastian Redl26d85b12008-11-05 21:50:06 +0000331
Sebastian Redl37d6de32008-11-08 13:00:26 +0000332 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000333 QualType SrcPointee;
334 if (DestPointer) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000335 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000336 SrcPointee = SrcPointer->getPointeeType();
337 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000338 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000339 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000340 return;
341 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000342 } else if (DestReference->isLValueReferenceType()) {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000343 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000344 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000345 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000346 }
347 SrcPointee = SrcType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000348 } else {
349 SrcPointee = SrcType;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000350 }
351
Ted Kremenek6217b802009-07-29 21:53:49 +0000352 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000353 if (SrcRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000354 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Anders Carlssonb7906612009-08-26 23:45:07 +0000355 PDiag(diag::err_bad_dynamic_cast_incomplete)
356 << SrcExpr->getSourceRange()))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000357 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000358 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000359 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000360 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000361 return;
362 }
363
364 assert((DestPointer || DestReference) &&
365 "Bad destination non-ptr/ref slipped through.");
366 assert((DestRecord || DestPointee->isVoidType()) &&
367 "Bad destination pointee slipped through.");
368 assert(SrcRecord && "Bad source pointee slipped through.");
369
370 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
371 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000372 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000373 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000374 return;
375 }
376
377 // C++ 5.2.7p3: If the type of v is the same as the required result type,
378 // [except for cv].
379 if (DestRecord == SrcRecord) {
380 return;
381 }
382
383 // C++ 5.2.7p5
384 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000385 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
386 Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
Chris Lattnerd1625842008-11-24 06:25:27 +0000387 OpRange.getBegin(), OpRange);
Anders Carlsson714179b2009-08-02 19:07:59 +0000388 Kind = CastExpr::CK_DerivedToBase;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000389 // Diagnostic already emitted on error.
390 return;
391 }
392
393 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor952b0172010-02-11 01:04:33 +0000394 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000395 assert(SrcDecl && "Definition missing");
396 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000397 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000398 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000399 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000400
401 // Done. Everything else is run-time checks.
Anders Carlsson714179b2009-08-02 19:07:59 +0000402 Kind = CastExpr::CK_Dynamic;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000403}
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000404
405/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
406/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
407/// like this:
408/// const char *str = "literal";
409/// legacy_function(const_cast\<char*\>(str));
410void
411CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000412 const SourceRange &OpRange, const SourceRange &DestRange) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000413 if (!DestType->isLValueReferenceType())
Douglas Gregora873dfc2010-02-03 00:27:59 +0000414 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000415
416 unsigned msg = diag::err_bad_cxx_cast_generic;
417 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
418 && msg != 0)
419 Self.Diag(OpRange.getBegin(), msg) << CT_Const
420 << SrcExpr->getType() << DestType << OpRange;
421}
422
423/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
424/// valid.
425/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
426/// like this:
427/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
428void
429CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000430 const SourceRange &OpRange, const SourceRange &DestRange,
431 CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000432 if (!DestType->isLValueReferenceType())
Douglas Gregora873dfc2010-02-03 00:27:59 +0000433 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000434
435 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson3c31a392009-09-26 00:12:34 +0000436 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
437 msg, Kind)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000438 != TC_Success && msg != 0)
439 Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
440 << SrcExpr->getType() << DestType << OpRange;
441}
442
443
444/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
445/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
446/// implicit conversions explicit and getting rid of data loss warnings.
447void
448CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson0aebc812009-09-09 21:33:21 +0000449 const SourceRange &OpRange, CastExpr::CastKind &Kind,
450 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000451 // This test is outside everything else because it's the only case where
452 // a non-lvalue-reference target type does not lead to decay.
453 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000454 if (DestType->isVoidType()) {
455 Kind = CastExpr::CK_ToVoid;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000456 return;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000457 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000458
Douglas Gregorb653c522009-11-06 01:14:41 +0000459 if (!DestType->isLValueReferenceType() && !DestType->isRecordType())
Douglas Gregora873dfc2010-02-03 00:27:59 +0000460 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000461
462 unsigned msg = diag::err_bad_cxx_cast_generic;
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000463 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000464 Kind, ConversionDecl)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000465 != TC_Success && msg != 0)
466 Self.Diag(OpRange.getBegin(), msg) << CT_Static
467 << SrcExpr->getType() << DestType << OpRange;
468}
469
470/// TryStaticCast - Check if a static cast can be performed, and do so if
471/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
472/// and casting away constness.
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000473static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000474 QualType DestType, bool CStyle,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000475 const SourceRange &OpRange, unsigned &msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000476 CastExpr::CastKind &Kind,
Mike Stump1eb44332009-09-09 15:08:12 +0000477 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000478 // The order the tests is not entirely arbitrary. There is one conversion
479 // that can be handled in two different ways. Given:
480 // struct A {};
481 // struct B : public A {
482 // B(); B(const A&);
483 // };
484 // const A &a = B();
485 // the cast static_cast<const B&>(a) could be seen as either a static
486 // reference downcast, or an explicit invocation of the user-defined
487 // conversion using B's conversion constructor.
488 // DR 427 specifies that the downcast is to be applied here.
489
490 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
491 // Done outside this function.
492
493 TryCastResult tcr;
494
495 // C++ 5.2.9p5, reference downcast.
496 // See the function for details.
497 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000498 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle, OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000499 msg, Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000500 if (tcr != TC_NotApplicable)
501 return tcr;
502
503 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
504 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
505 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000506 if (tcr != TC_NotApplicable) {
507 Kind = CastExpr::CK_NoOp;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000508 return tcr;
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000509 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000510
511 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
512 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000513 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000514 Kind, ConversionDecl);
515 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000516 return tcr;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000517
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000518 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
519 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
520 // conversions, subject to further restrictions.
521 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
522 // of qualification conversions impossible.
523 // In the CStyle case, the earlier attempt to const_cast should have taken
524 // care of reverse qualification conversions.
525
526 QualType OrigSrcType = SrcExpr->getType();
527
528 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
529
530 // Reverse integral promotion/conversion. All such conversions are themselves
531 // again integral promotions or conversions and are thus already handled by
532 // p2 (TryDirectInitialization above).
533 // (Note: any data loss warnings should be suppressed.)
534 // The exception is the reverse of enum->integer, i.e. integer->enum (and
535 // enum->enum). See also C++ 5.2.9p7.
536 // The same goes for reverse floating point promotion/conversion and
537 // floating-integral conversions. Again, only floating->enum is relevant.
538 if (DestType->isEnumeralType()) {
539 if (SrcType->isComplexType() || SrcType->isVectorType()) {
540 // Fall through - these cannot be converted.
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000541 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
542 Kind = CastExpr::CK_IntegralCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000543 return TC_Success;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000544 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000545 }
546
547 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
548 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000549 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
550 Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000551 if (tcr != TC_NotApplicable)
552 return tcr;
553
554 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
555 // conversion. C++ 5.2.9p9 has additional information.
556 // DR54's access restrictions apply here also.
557 tcr = TryStaticMemberPointerUpcast(Self, SrcType, DestType, CStyle,
Anders Carlsson1a31a182009-10-30 00:46:35 +0000558 OpRange, msg, Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000559 if (tcr != TC_NotApplicable)
560 return tcr;
561
562 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
563 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
564 // just the usual constness stuff.
Ted Kremenek6217b802009-07-29 21:53:49 +0000565 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000566 QualType SrcPointee = SrcPointer->getPointeeType();
567 if (SrcPointee->isVoidType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000568 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000569 QualType DestPointee = DestPointer->getPointeeType();
570 if (DestPointee->isIncompleteOrObjectType()) {
571 // This is definitely the intended conversion, but it might fail due
572 // to a const violation.
573 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
574 msg = diag::err_bad_cxx_cast_const_away;
575 return TC_Failed;
576 }
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000577 Kind = CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000578 return TC_Success;
579 }
580 }
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +0000581 else if (CStyle && DestType->isObjCObjectPointerType()) {
582 // allow c-style cast of objective-c pointers as they are pervasive.
583 Kind = CastExpr::CK_AnyPointerToObjCPointerCast;
584 return TC_Success;
585 }
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +0000586 else if (CStyle && DestType->isBlockPointerType()) {
587 // allow c-style cast of void * to block pointers.
588 Kind = CastExpr::CK_AnyPointerToBlockPointerCast;
589 return TC_Success;
590 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000591 }
592 }
593
594 // We tried everything. Everything! Nothing works! :-(
595 return TC_NotApplicable;
596}
597
598/// Tests whether a conversion according to N2844 is valid.
599TryCastResult
600TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000601 unsigned &msg) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000602 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
603 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenek6217b802009-07-29 21:53:49 +0000604 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000605 if (!R)
606 return TC_NotApplicable;
607
608 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
609 return TC_NotApplicable;
610
611 // Because we try the reference downcast before this function, from now on
612 // this is the only cast possibility, so we issue an error if we fail now.
613 // FIXME: Should allow casting away constness if CStyle.
614 bool DerivedToBase;
Douglas Gregor393896f2009-11-05 13:06:35 +0000615 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
616 SrcExpr->getType(), R->getPointeeType(),
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000617 DerivedToBase) <
618 Sema::Ref_Compatible_With_Added_Qualification) {
619 msg = diag::err_bad_lvalue_to_rvalue_cast;
620 return TC_Failed;
621 }
622
623 // FIXME: Similar to CheckReferenceInit, we actually need more AST annotation
624 // than nothing.
625 return TC_Success;
626}
627
628/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
629TryCastResult
630TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
631 bool CStyle, const SourceRange &OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000632 unsigned &msg, CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000633 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
634 // cast to type "reference to cv2 D", where D is a class derived from B,
635 // if a valid standard conversion from "pointer to D" to "pointer to B"
636 // exists, cv2 >= cv1, and B is not a virtual base class of D.
637 // In addition, DR54 clarifies that the base must be accessible in the
638 // current context. Although the wording of DR54 only applies to the pointer
639 // variant of this rule, the intent is clearly for it to apply to the this
640 // conversion as well.
641
Ted Kremenek6217b802009-07-29 21:53:49 +0000642 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000643 if (!DestReference) {
644 return TC_NotApplicable;
645 }
646 bool RValueRef = DestReference->isRValueReferenceType();
647 if (!RValueRef && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
648 // We know the left side is an lvalue reference, so we can suggest a reason.
649 msg = diag::err_bad_cxx_cast_rvalue;
650 return TC_NotApplicable;
651 }
652
653 QualType DestPointee = DestReference->getPointeeType();
654
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000655 return TryStaticDowncast(Self,
656 Self.Context.getCanonicalType(SrcExpr->getType()),
657 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000658 OpRange, SrcExpr->getType(), DestType, msg, Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000659}
660
661/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
662TryCastResult
663TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000664 bool CStyle, const SourceRange &OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000665 unsigned &msg, CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000666 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
667 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
668 // is a class derived from B, if a valid standard conversion from "pointer
669 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
670 // class of D.
671 // In addition, DR54 clarifies that the base must be accessible in the
672 // current context.
673
Ted Kremenek6217b802009-07-29 21:53:49 +0000674 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000675 if (!DestPointer) {
676 return TC_NotApplicable;
677 }
678
Ted Kremenek6217b802009-07-29 21:53:49 +0000679 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000680 if (!SrcPointer) {
681 msg = diag::err_bad_static_cast_pointer_nonpointer;
682 return TC_NotApplicable;
683 }
684
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000685 return TryStaticDowncast(Self,
686 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
687 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
688 CStyle, OpRange, SrcType, DestType, msg, Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000689}
690
691/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
692/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000693/// DestType is possible and allowed.
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000694TryCastResult
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000695TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000696 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000697 QualType OrigDestType, unsigned &msg,
698 CastExpr::CastKind &Kind) {
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000699 // We can only work with complete types. But don't complain if it doesn't work
700 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, PDiag(0)) ||
701 Self.RequireCompleteType(OpRange.getBegin(), DestType, PDiag(0)))
702 return TC_NotApplicable;
703
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000704 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000705 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000706 return TC_NotApplicable;
707 }
708
Douglas Gregora8f32e02009-10-06 17:59:45 +0000709 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
710 /*DetectVirtual=*/true);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000711 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
712 return TC_NotApplicable;
713 }
714
715 // Target type does derive from source type. Now we're serious. If an error
716 // appears now, it's not ignored.
717 // This may not be entirely in line with the standard. Take for example:
718 // struct A {};
719 // struct B : virtual A {
720 // B(A&);
721 // };
Mike Stump1eb44332009-09-09 15:08:12 +0000722 //
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000723 // void f()
724 // {
725 // (void)static_cast<const B&>(*((A*)0));
726 // }
727 // As far as the standard is concerned, p5 does not apply (A is virtual), so
728 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
729 // However, both GCC and Comeau reject this example, and accepting it would
730 // mean more complex code if we're to preserve the nice error message.
731 // FIXME: Being 100% compliant here would be nice to have.
732
733 // Must preserve cv, as always, unless we're in C-style mode.
734 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
735 msg = diag::err_bad_cxx_cast_const_away;
736 return TC_Failed;
737 }
738
739 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
740 // This code is analoguous to that in CheckDerivedToBaseConversion, except
741 // that it builds the paths in reverse order.
742 // To sum up: record all paths to the base and build a nice string from
743 // them. Use it to spice up the error message.
744 if (!Paths.isRecordingPaths()) {
745 Paths.clear();
746 Paths.setRecordingPaths(true);
747 Self.IsDerivedFrom(DestType, SrcType, Paths);
748 }
749 std::string PathDisplayStr;
750 std::set<unsigned> DisplayedPaths;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000751 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000752 PI != PE; ++PI) {
753 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
754 // We haven't displayed a path to this particular base
755 // class subobject yet.
756 PathDisplayStr += "\n ";
Douglas Gregora8f32e02009-10-06 17:59:45 +0000757 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
758 EE = PI->rend();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000759 EI != EE; ++EI)
760 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000761 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000762 }
763 }
764
765 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000766 << QualType(SrcType).getUnqualifiedType()
767 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000768 << PathDisplayStr << OpRange;
769 msg = 0;
770 return TC_Failed;
771 }
772
773 if (Paths.getDetectedVirtual() != 0) {
774 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
775 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
776 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
777 msg = 0;
778 return TC_Failed;
779 }
780
John McCall6b2accb2010-02-10 09:31:12 +0000781 if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
782 /*IsBaseToDerived*/ true,
783 SrcType, DestType,
784 Paths.front())) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000785 msg = 0;
786 return TC_Failed;
787 }
788
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000789 Kind = CastExpr::CK_BaseToDerived;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000790 return TC_Success;
791}
792
793/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
794/// C++ 5.2.9p9 is valid:
795///
796/// An rvalue of type "pointer to member of D of type cv1 T" can be
797/// converted to an rvalue of type "pointer to member of B of type cv2 T",
798/// where B is a base class of D [...].
799///
800TryCastResult
801TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType, QualType DestType,
802 bool CStyle, const SourceRange &OpRange,
Anders Carlsson1a31a182009-10-30 00:46:35 +0000803 unsigned &msg, CastExpr::CastKind &Kind) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000804 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000805 if (!DestMemPtr)
806 return TC_NotApplicable;
Ted Kremenek6217b802009-07-29 21:53:49 +0000807 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000808 if (!SrcMemPtr) {
809 msg = diag::err_bad_static_cast_member_pointer_nonmp;
810 return TC_NotApplicable;
811 }
812
813 // T == T, modulo cv
Douglas Gregora4923eb2009-11-16 21:35:15 +0000814 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
815 DestMemPtr->getPointeeType()))
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000816 return TC_NotApplicable;
817
818 // B base of D
819 QualType SrcClass(SrcMemPtr->getClass(), 0);
820 QualType DestClass(DestMemPtr->getClass(), 0);
Douglas Gregora8f32e02009-10-06 17:59:45 +0000821 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000822 /*DetectVirtual=*/true);
823 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
824 return TC_NotApplicable;
825 }
826
827 // B is a base of D. But is it an allowed base? If not, it's a hard error.
828 if (Paths.isAmbiguous(DestClass)) {
829 Paths.clear();
830 Paths.setRecordingPaths(true);
831 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
832 assert(StillOkay);
833 StillOkay = StillOkay;
834 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
835 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
836 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
837 msg = 0;
838 return TC_Failed;
839 }
840
841 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
842 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
843 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
844 msg = 0;
845 return TC_Failed;
846 }
847
John McCall6b2accb2010-02-10 09:31:12 +0000848 if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
849 /*IsBaseToDerived*/ false,
850 DestType, SrcType,
851 Paths.front())) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000852 msg = 0;
853 return TC_Failed;
854 }
855
Anders Carlsson1a31a182009-10-30 00:46:35 +0000856 Kind = CastExpr::CK_DerivedToBaseMemberPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000857 return TC_Success;
858}
859
860/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
861/// is valid:
862///
863/// An expression e can be explicitly converted to a type T using a
864/// @c static_cast if the declaration "T t(e);" is well-formed [...].
865TryCastResult
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000866TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000867 bool CStyle, const SourceRange &OpRange, unsigned &msg,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000868 CastExpr::CastKind &Kind,
Mike Stump1eb44332009-09-09 15:08:12 +0000869 CXXMethodDecl *&ConversionDecl) {
Anders Carlssond851b372009-09-07 18:25:47 +0000870 if (DestType->isRecordType()) {
871 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
872 diag::err_bad_dynamic_cast_incomplete)) {
873 msg = 0;
874 return TC_Failed;
875 }
876 }
Mike Stump1eb44332009-09-09 15:08:12 +0000877
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000878 if (DestType->isReferenceType()) {
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000879 // All reference bindings insert implicit casts above that do the actual
880 // casting.
881 Kind = CastExpr::CK_NoOp;
882
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000883 // At this point of CheckStaticCast, if the destination is a reference,
884 // this has to work. There is no other way that works.
885 // On the other hand, if we're checking a C-style cast, we've still got
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000886 // the reinterpret_cast way. So in C-style mode, we first try the call
887 // with an ICS to suppress errors.
888 if (CStyle) {
889 ImplicitConversionSequence ICS;
890 if(Self.CheckReferenceInit(SrcExpr, DestType, OpRange.getBegin(),
891 /*SuppressUserConversions=*/false,
892 /*AllowExplicit=*/false, /*ForceRValue=*/false,
893 &ICS))
894 return TC_NotApplicable;
895 }
896 // Now we're committed either way.
897 if(!Self.CheckReferenceInit(SrcExpr, DestType, OpRange.getBegin(),
898 /*SuppressUserConversions=*/false,
899 /*AllowExplicit=*/false,
900 /*ForceRValue=*/false, 0,
901 /*IgnoreBaseAccess=*/CStyle))
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000902 return TC_Success;
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000903
904 // We already got an error message.
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000905 msg = 0;
906 return TC_Failed;
907 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000908
Douglas Gregor19aeac62009-11-14 03:27:21 +0000909 if (DestType->isRecordType()) {
910 if (CXXConstructorDecl *Constructor
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000911 = Self.TryInitializationByConstructor(DestType, &SrcExpr, 1,
Douglas Gregor19aeac62009-11-14 03:27:21 +0000912 OpRange.getBegin(),
Douglas Gregor20093b42009-12-09 23:02:17 +0000913 InitializationKind::CreateDirect(OpRange.getBegin(),
914 OpRange.getBegin(),
915 OpRange.getEnd()))) {
Douglas Gregor19aeac62009-11-14 03:27:21 +0000916 ConversionDecl = Constructor;
917 Kind = CastExpr::CK_ConstructorConversion;
918 return TC_Success;
919 }
920
921 return TC_NotApplicable;
922 }
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000923
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000924 // FIXME: To get a proper error from invalid conversions here, we need to
925 // reimplement more of this.
926 // FIXME: This does not actually perform the conversion, and thus does not
927 // check for ambiguity or access.
Mike Stump1eb44332009-09-09 15:08:12 +0000928 ImplicitConversionSequence ICS =
Anders Carlssonda7a18b2009-08-27 17:24:15 +0000929 Self.TryImplicitConversion(SrcExpr, DestType,
930 /*SuppressUserConversions=*/false,
Anders Carlsson83b534c2009-08-28 16:22:20 +0000931 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +0000932 /*ForceRValue=*/false,
Fariborz Jahanian249cead2009-10-01 20:39:51 +0000933 /*InOverloadResolution=*/false,
934 /*one of user provided casts*/true);
Mike Stump1eb44332009-09-09 15:08:12 +0000935
John McCall1d318332010-01-12 00:44:57 +0000936 if (ICS.isBad())
Anders Carlsson3c31a392009-09-26 00:12:34 +0000937 return TC_NotApplicable;
938
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000939 // The conversion is possible, so commit to it.
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000940 Kind = CastExpr::CK_NoOp;
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000941 msg = 0;
Douglas Gregor68647482009-12-16 03:45:30 +0000942 return Self.PerformImplicitConversion(SrcExpr, DestType, ICS, Sema::AA_Casting,
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000943 /*IgnoreBaseAccess*/CStyle) ?
944 TC_Failed : TC_Success;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000945}
946
947/// TryConstCast - See if a const_cast from source to destination is allowed,
948/// and perform it if it is.
949static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
950 bool CStyle, unsigned &msg) {
951 DestType = Self.Context.getCanonicalType(DestType);
952 QualType SrcType = SrcExpr->getType();
953 if (const LValueReferenceType *DestTypeTmp =
Ted Kremenek6217b802009-07-29 21:53:49 +0000954 DestType->getAs<LValueReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000955 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
956 // Cannot const_cast non-lvalue to lvalue reference type. But if this
957 // is C-style, static_cast might find a way, so we simply suggest a
958 // message and tell the parent to keep searching.
959 msg = diag::err_bad_cxx_cast_rvalue;
960 return TC_NotApplicable;
961 }
962
963 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
964 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
965 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
966 SrcType = Self.Context.getPointerType(SrcType);
967 }
968
969 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
970 // the rules for const_cast are the same as those used for pointers.
971
972 if (!DestType->isPointerType() && !DestType->isMemberPointerType()) {
973 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
974 // was a reference type, we converted it to a pointer above.
975 // The status of rvalue references isn't entirely clear, but it looks like
976 // conversion to them is simply invalid.
977 // C++ 5.2.11p3: For two pointer types [...]
978 if (!CStyle)
979 msg = diag::err_bad_const_cast_dest;
980 return TC_NotApplicable;
981 }
982 if (DestType->isFunctionPointerType() ||
983 DestType->isMemberFunctionPointerType()) {
984 // Cannot cast direct function pointers.
985 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
986 // T is the ultimate pointee of source and target type.
987 if (!CStyle)
988 msg = diag::err_bad_const_cast_dest;
989 return TC_NotApplicable;
990 }
991 SrcType = Self.Context.getCanonicalType(SrcType);
992
993 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
994 // completely equal.
995 // FIXME: const_cast should probably not be able to convert between pointers
996 // to different address spaces.
997 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
998 // in multi-level pointers may change, but the level count must be the same,
999 // as must be the final pointee type.
1000 while (SrcType != DestType &&
1001 Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Chandler Carruth595e2902009-12-29 08:05:19 +00001002 Qualifiers Quals;
1003 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, Quals);
1004 DestType = Self.Context.getUnqualifiedArrayType(DestType, Quals);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001005 }
1006
1007 // Since we're dealing in canonical types, the remainder must be the same.
1008 if (SrcType != DestType)
1009 return TC_NotApplicable;
1010
1011 return TC_Success;
1012}
1013
1014static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
1015 QualType DestType, bool CStyle,
1016 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +00001017 unsigned &msg,
1018 CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001019 DestType = Self.Context.getCanonicalType(DestType);
1020 QualType SrcType = SrcExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001021 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001022 bool LValue = DestTypeTmp->isLValueReferenceType();
1023 if (LValue && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
1024 // Cannot cast non-lvalue to reference type. See the similar comment in
1025 // const_cast.
1026 msg = diag::err_bad_cxx_cast_rvalue;
1027 return TC_NotApplicable;
1028 }
1029
1030 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1031 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1032 // built-in & and * operators.
1033 // This code does this transformation for the checked types.
1034 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1035 SrcType = Self.Context.getPointerType(SrcType);
1036 }
1037
1038 // Canonicalize source for comparison.
1039 SrcType = Self.Context.getCanonicalType(SrcType);
1040
Ted Kremenek6217b802009-07-29 21:53:49 +00001041 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1042 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001043 if (DestMemPtr && SrcMemPtr) {
1044 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1045 // can be explicitly converted to an rvalue of type "pointer to member
1046 // of Y of type T2" if T1 and T2 are both function types or both object
1047 // types.
1048 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1049 SrcMemPtr->getPointeeType()->isFunctionType())
1050 return TC_NotApplicable;
1051
1052 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1053 // constness.
1054 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1055 // we accept it.
1056 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1057 msg = diag::err_bad_cxx_cast_const_away;
1058 return TC_Failed;
1059 }
1060
1061 // A valid member pointer cast.
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001062 Kind = CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001063 return TC_Success;
1064 }
1065
1066 // See below for the enumeral issue.
1067 if (SrcType->isNullPtrType() && DestType->isIntegralType() &&
1068 !DestType->isEnumeralType()) {
1069 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1070 // type large enough to hold it. A value of std::nullptr_t can be
1071 // converted to an integral type; the conversion has the same meaning
1072 // and validity as a conversion of (void*)0 to the integral type.
1073 if (Self.Context.getTypeSize(SrcType) >
1074 Self.Context.getTypeSize(DestType)) {
1075 msg = diag::err_bad_reinterpret_cast_small_int;
1076 return TC_Failed;
1077 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001078 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001079 return TC_Success;
1080 }
1081
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001082 bool destIsVector = DestType->isVectorType();
1083 bool srcIsVector = SrcType->isVectorType();
1084 if (srcIsVector || destIsVector) {
1085 bool srcIsScalar = SrcType->isIntegralType() && !SrcType->isEnumeralType();
1086 bool destIsScalar =
1087 DestType->isIntegralType() && !DestType->isEnumeralType();
1088
1089 // Check if this is a cast between a vector and something else.
1090 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1091 !(srcIsVector && destIsVector))
1092 return TC_NotApplicable;
1093
1094 // If both types have the same size, we can successfully cast.
Douglas Gregorf2a55392009-12-22 22:47:22 +00001095 if (Self.Context.getTypeSize(SrcType)
1096 == Self.Context.getTypeSize(DestType)) {
1097 Kind = CastExpr::CK_BitCast;
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001098 return TC_Success;
Douglas Gregorf2a55392009-12-22 22:47:22 +00001099 }
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001100
1101 if (destIsScalar)
1102 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1103 else if (srcIsScalar)
1104 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1105 else
1106 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1107
1108 return TC_Failed;
1109 }
1110
Fariborz Jahanian72a86592010-02-03 20:32:31 +00001111 bool destIsPtr = DestType->isAnyPointerType();
1112 bool srcIsPtr = SrcType->isAnyPointerType();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001113 if (!destIsPtr && !srcIsPtr) {
1114 // Except for std::nullptr_t->integer and lvalue->reference, which are
1115 // handled above, at least one of the two arguments must be a pointer.
1116 return TC_NotApplicable;
1117 }
1118
1119 if (SrcType == DestType) {
1120 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1121 // restrictions, a cast to the same type is allowed. The intent is not
1122 // entirely clear here, since all other paragraphs explicitly forbid casts
1123 // to the same type. However, the behavior of compilers is pretty consistent
1124 // on this point: allow same-type conversion if the involved types are
1125 // pointers, disallow otherwise.
Douglas Gregorf2a55392009-12-22 22:47:22 +00001126 Kind = CastExpr::CK_NoOp;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001127 return TC_Success;
1128 }
1129
1130 // Note: Clang treats enumeration types as integral types. If this is ever
1131 // changed for C++, the additional check here will be redundant.
1132 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
1133 assert(srcIsPtr && "One type must be a pointer");
1134 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1135 // type large enough to hold it.
1136 if (Self.Context.getTypeSize(SrcType) >
1137 Self.Context.getTypeSize(DestType)) {
1138 msg = diag::err_bad_reinterpret_cast_small_int;
1139 return TC_Failed;
1140 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001141 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001142 return TC_Success;
1143 }
1144
1145 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
1146 assert(destIsPtr && "One type must be a pointer");
1147 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1148 // converted to a pointer.
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001149 Kind = CastExpr::CK_IntegralToPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001150 return TC_Success;
1151 }
1152
1153 if (!destIsPtr || !srcIsPtr) {
1154 // With the valid non-pointer conversions out of the way, we can be even
1155 // more stringent.
1156 return TC_NotApplicable;
1157 }
1158
1159 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1160 // The C-style cast operator can.
1161 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1162 msg = diag::err_bad_cxx_cast_const_away;
1163 return TC_Failed;
1164 }
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001165 if (CStyle && DestType->isObjCObjectPointerType()) {
1166 Kind = CastExpr::CK_AnyPointerToObjCPointerCast;
1167 return TC_Success;
1168 }
1169
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001170 // Not casting away constness, so the only remaining check is for compatible
1171 // pointer categories.
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001172 Kind = CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001173
1174 if (SrcType->isFunctionPointerType()) {
1175 if (DestType->isFunctionPointerType()) {
1176 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1177 // a pointer to a function of a different type.
1178 return TC_Success;
1179 }
1180
1181 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1182 // an object type or vice versa is conditionally-supported.
1183 // Compilers support it in C++03 too, though, because it's necessary for
1184 // casting the return value of dlsym() and GetProcAddress().
1185 // FIXME: Conditionally-supported behavior should be configurable in the
1186 // TargetInfo or similar.
1187 if (!Self.getLangOptions().CPlusPlus0x)
1188 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1189 return TC_Success;
1190 }
1191
1192 if (DestType->isFunctionPointerType()) {
1193 // See above.
1194 if (!Self.getLangOptions().CPlusPlus0x)
1195 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1196 return TC_Success;
1197 }
1198
1199 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1200 // a pointer to an object of different type.
1201 // Void pointers are not specified, but supported by every compiler out there.
1202 // So we finish by allowing everything that remains - it's got to be two
1203 // object pointers.
1204 return TC_Success;
1205}
1206
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00001207bool Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00001208 CastExpr::CastKind &Kind, bool FunctionalStyle,
Mike Stump1eb44332009-09-09 15:08:12 +00001209 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001210 // This test is outside everything else because it's the only case where
1211 // a non-lvalue-reference target type does not lead to decay.
1212 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001213 if (CastTy->isVoidType()) {
1214 Kind = CastExpr::CK_ToVoid;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001215 return false;
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001216 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001217
1218 // If the type is dependent, we won't do any other semantic analysis now.
1219 if (CastTy->isDependentType() || CastExpr->isTypeDependent())
1220 return false;
1221
Douglas Gregorb653c522009-11-06 01:14:41 +00001222 if (!CastTy->isLValueReferenceType() && !CastTy->isRecordType())
Douglas Gregora873dfc2010-02-03 00:27:59 +00001223 DefaultFunctionArrayLvalueConversion(CastExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001224
1225 // C++ [expr.cast]p5: The conversions performed by
1226 // - a const_cast,
1227 // - a static_cast,
1228 // - a static_cast followed by a const_cast,
1229 // - a reinterpret_cast, or
1230 // - a reinterpret_cast followed by a const_cast,
1231 // can be performed using the cast notation of explicit type conversion.
1232 // [...] If a conversion can be interpreted in more than one of the ways
1233 // listed above, the interpretation that appears first in the list is used,
1234 // even if a cast resulting from that interpretation is ill-formed.
1235 // In plain language, this means trying a const_cast ...
1236 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001237 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1238 msg);
Anders Carlssonda921fd2009-10-19 18:14:28 +00001239 if (tcr == TC_Success)
1240 Kind = CastExpr::CK_NoOp;
1241
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001242 if (tcr == TC_NotApplicable) {
1243 // ... or if that is not possible, a static_cast, ignoring const, ...
Anders Carlsson3c31a392009-09-26 00:12:34 +00001244 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1245 Kind, ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001246 if (tcr == TC_NotApplicable) {
1247 // ... and finally a reinterpret_cast, ignoring const.
Anders Carlsson3c31a392009-09-26 00:12:34 +00001248 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1249 Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001250 }
1251 }
1252
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001253 if (tcr != TC_Success && msg != 0)
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00001254 Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001255 << CastExpr->getType() << CastTy << R;
1256
1257 return tcr != TC_Success;
1258}