blob: 29e9051082d204fb24e05db0f0def12728049c03 [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 Carlsson5cf86ba2010-04-24 19:06:50 +000049 CastExpr::CastKind &Kind,
50 CXXBaseSpecifierArray &BasePath);
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 Carlsson5cf86ba2010-04-24 19:06:50 +000054 CastExpr::CastKind &Kind,
55 CXXBaseSpecifierArray &BasePath);
Sebastian Redl37d6de32008-11-08 13:00:26 +000056
57static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000058
59// The Try functions attempt a specific way of casting. If they succeed, they
60// return TC_Success. If their way of casting is not appropriate for the given
61// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
62// to emit if no other way succeeds. If their way of casting is appropriate but
63// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
64// they emit a specialized diagnostic.
65// All diagnostics returned by these functions must expect the same three
66// arguments:
67// %0: Cast Type (a value from the CastType enumeration)
68// %1: Source Type
69// %2: Destination Type
70static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
71 QualType DestType, unsigned &msg);
72static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
Anders Carlssonf9d68e12010-04-24 19:36:51 +000073 QualType DestType, bool CStyle,
74 const SourceRange &OpRange,
75 unsigned &msg,
76 CastExpr::CastKind &Kind,
77 CXXBaseSpecifierArray &BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +000078static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
79 QualType DestType, bool CStyle,
80 const SourceRange &OpRange,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +000081 unsigned &msg,
Anders Carlssonf9d68e12010-04-24 19:36:51 +000082 CastExpr::CastKind &Kind,
83 CXXBaseSpecifierArray &BasePath);
Douglas Gregorab15d0e2009-11-15 09:20:52 +000084static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
85 CanQualType DestType, bool CStyle,
Sebastian Redl9cc11e72009-07-25 15:41:38 +000086 const SourceRange &OpRange,
87 QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +000088 QualType OrigDestType, unsigned &msg,
Anders Carlssonf9d68e12010-04-24 19:36:51 +000089 CastExpr::CastKind &Kind,
90 CXXBaseSpecifierArray &BasePath);
Douglas Gregor4ce46c22010-03-07 23:24:59 +000091static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr,
Anders Carlssoncee22422010-04-24 19:22:20 +000092 QualType SrcType,
93 QualType DestType,bool CStyle,
94 const SourceRange &OpRange,
95 unsigned &msg,
96 CastExpr::CastKind &Kind,
97 CXXBaseSpecifierArray &BasePath);
98
Sebastian Redla82e4ae2009-11-14 21:15:49 +000099static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000100 QualType DestType, bool CStyle,
101 const SourceRange &OpRange,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000102 unsigned &msg,
Douglas Gregord6e44a32010-04-16 22:09:46 +0000103 CastExpr::CastKind &Kind);
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000104static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000105 QualType DestType, bool CStyle,
106 const SourceRange &OpRange,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000107 unsigned &msg,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000108 CastExpr::CastKind &Kind,
109 CXXBaseSpecifierArray &BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000110static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
111 bool CStyle, unsigned &msg);
112static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
113 QualType DestType, bool CStyle,
114 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +0000115 unsigned &msg,
116 CastExpr::CastKind &Kind);
Sebastian Redl37d6de32008-11-08 13:00:26 +0000117
Sebastian Redl26d85b12008-11-05 21:50:06 +0000118/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
Sebastian Redlf53597f2009-03-15 17:47:39 +0000119Action::OwningExprResult
Sebastian Redl26d85b12008-11-05 21:50:06 +0000120Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
121 SourceLocation LAngleBracketLoc, TypeTy *Ty,
122 SourceLocation RAngleBracketLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000123 SourceLocation LParenLoc, ExprArg E,
Sebastian Redl26d85b12008-11-05 21:50:06 +0000124 SourceLocation RParenLoc) {
John McCallc89724c2010-01-15 19:13:16 +0000125
John McCall9d125032010-01-15 18:39:57 +0000126 TypeSourceInfo *DestTInfo;
127 QualType DestType = GetTypeFromParser(Ty, &DestTInfo);
128 if (!DestTInfo)
129 DestTInfo = Context.getTrivialTypeSourceInfo(DestType, SourceLocation());
John McCallc89724c2010-01-15 19:13:16 +0000130
131 return BuildCXXNamedCast(OpLoc, Kind, DestTInfo, move(E),
132 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
133 SourceRange(LParenLoc, RParenLoc));
134}
135
136Action::OwningExprResult
137Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
138 TypeSourceInfo *DestTInfo, ExprArg E,
139 SourceRange AngleBrackets, SourceRange Parens) {
140 Expr *Ex = E.takeAs<Expr>();
141 QualType DestType = DestTInfo->getType();
142
143 SourceRange OpRange(OpLoc, Parens.getEnd());
144 SourceRange DestRange = AngleBrackets;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000145
Douglas Gregor9103bb22008-12-17 22:52:20 +0000146 // If the type is dependent, we won't do the semantic analysis now.
147 // FIXME: should we check this in a more fine-grained manner?
148 bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
149
Sebastian Redl26d85b12008-11-05 21:50:06 +0000150 switch (Kind) {
151 default: assert(0 && "Unknown C++ cast!");
152
153 case tok::kw_const_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +0000154 if (!TypeDependent)
155 CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
Douglas Gregor63982352010-07-13 18:40:04 +0000156 return Owned(new (Context) CXXConstCastExpr(
157 DestType.getNonLValueExprType(Context),
John McCall9d125032010-01-15 18:39:57 +0000158 Ex, DestTInfo, OpLoc));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000159
Anders Carlsson714179b2009-08-02 19:07:59 +0000160 case tok::kw_dynamic_cast: {
161 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson41b2dcd2010-04-24 18:38:56 +0000162 CXXBaseSpecifierArray BasePath;
Douglas Gregor9103bb22008-12-17 22:52:20 +0000163 if (!TypeDependent)
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000164 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange, Kind, BasePath);
Douglas Gregor63982352010-07-13 18:40:04 +0000165 return Owned(new (Context)CXXDynamicCastExpr(
166 DestType.getNonLValueExprType(Context),
Anders Carlsson41b2dcd2010-04-24 18:38:56 +0000167 Kind, Ex, BasePath, DestTInfo,
168 OpLoc));
Anders Carlsson714179b2009-08-02 19:07:59 +0000169 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000170 case tok::kw_reinterpret_cast: {
171 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregor9103bb22008-12-17 22:52:20 +0000172 if (!TypeDependent)
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000173 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redlf53597f2009-03-15 17:47:39 +0000174 return Owned(new (Context) CXXReinterpretCastExpr(
Douglas Gregor63982352010-07-13 18:40:04 +0000175 DestType.getNonLValueExprType(Context),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000176 Kind, Ex, CXXBaseSpecifierArray(),
177 DestTInfo, OpLoc));
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000178 }
Anders Carlssoncdb61972009-08-07 22:21:05 +0000179 case tok::kw_static_cast: {
180 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson41b2dcd2010-04-24 18:38:56 +0000181 CXXBaseSpecifierArray BasePath;
Douglas Gregord6e44a32010-04-16 22:09:46 +0000182 if (!TypeDependent)
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000183 CheckStaticCast(*this, Ex, DestType, OpRange, Kind, BasePath);
Anders Carlsson0aebc812009-09-09 21:33:21 +0000184
Douglas Gregor63982352010-07-13 18:40:04 +0000185 return Owned(new (Context) CXXStaticCastExpr(
186 DestType.getNonLValueExprType(Context),
Anders Carlsson41b2dcd2010-04-24 18:38:56 +0000187 Kind, Ex, BasePath,
188 DestTInfo, OpLoc));
Anders Carlssoncdb61972009-08-07 22:21:05 +0000189 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000190 }
191
Sebastian Redlf53597f2009-03-15 17:47:39 +0000192 return ExprError();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000193}
194
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000195/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
196/// this removes one level of indirection from both types, provided that they're
197/// the same kind of pointer (plain or to-member). Unlike the Sema function,
198/// this one doesn't care if the two pointers-to-member don't point into the
199/// same class. This is because CastsAwayConstness doesn't care.
Dan Gohman3c46e8d2010-07-26 21:25:24 +0000200static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000201 const PointerType *T1PtrType = T1->getAs<PointerType>(),
202 *T2PtrType = T2->getAs<PointerType>();
203 if (T1PtrType && T2PtrType) {
204 T1 = T1PtrType->getPointeeType();
205 T2 = T2PtrType->getPointeeType();
206 return true;
207 }
Fariborz Jahanian72a86592010-02-03 20:32:31 +0000208 const ObjCObjectPointerType *T1ObjCPtrType =
209 T1->getAs<ObjCObjectPointerType>(),
210 *T2ObjCPtrType =
211 T2->getAs<ObjCObjectPointerType>();
212 if (T1ObjCPtrType) {
213 if (T2ObjCPtrType) {
214 T1 = T1ObjCPtrType->getPointeeType();
215 T2 = T2ObjCPtrType->getPointeeType();
216 return true;
217 }
218 else if (T2PtrType) {
219 T1 = T1ObjCPtrType->getPointeeType();
220 T2 = T2PtrType->getPointeeType();
221 return true;
222 }
223 }
224 else if (T2ObjCPtrType) {
225 if (T1PtrType) {
226 T2 = T2ObjCPtrType->getPointeeType();
227 T1 = T1PtrType->getPointeeType();
228 return true;
229 }
230 }
231
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000232 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
233 *T2MPType = T2->getAs<MemberPointerType>();
234 if (T1MPType && T2MPType) {
235 T1 = T1MPType->getPointeeType();
236 T2 = T2MPType->getPointeeType();
237 return true;
238 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000239
240 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
241 *T2BPType = T2->getAs<BlockPointerType>();
242 if (T1BPType && T2BPType) {
243 T1 = T1BPType->getPointeeType();
244 T2 = T2BPType->getPointeeType();
245 return true;
246 }
247
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000248 return false;
249}
250
Sebastian Redldb647282009-01-27 23:18:31 +0000251/// CastsAwayConstness - Check if the pointer conversion from SrcType to
252/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
253/// the cast checkers. Both arguments must denote pointer (possibly to member)
254/// types.
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000255static bool
Mike Stump1eb44332009-09-09 15:08:12 +0000256CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
Sebastian Redldb647282009-01-27 23:18:31 +0000257 // Casting away constness is defined in C++ 5.2.11p8 with reference to
258 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
259 // the rules are non-trivial. So first we construct Tcv *...cv* as described
260 // in C++ 5.2.11p8.
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000261 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
262 SrcType->isBlockPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000263 "Source type is not pointer or pointer to member.");
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000264 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
265 DestType->isBlockPointerType()) &&
Sebastian Redldb647282009-01-27 23:18:31 +0000266 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000267
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000268 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
269 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
John McCall0953e762009-09-24 19:53:00 +0000270 llvm::SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000271
272 // Find the qualifications.
Sebastian Redl76d69bb2009-11-18 18:10:53 +0000273 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
Anders Carlsson52647c62010-06-04 22:47:55 +0000274 Qualifiers SrcQuals;
275 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
276 cv1.push_back(SrcQuals);
277
278 Qualifiers DestQuals;
279 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
280 cv2.push_back(DestQuals);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000281 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +0000282 if (cv1.empty())
283 return false;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000284
285 // Construct void pointers with those qualifiers (in reverse order of
286 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000287 QualType SrcConstruct = Self.Context.VoidTy;
288 QualType DestConstruct = Self.Context.VoidTy;
John McCall0953e762009-09-24 19:53:00 +0000289 ASTContext &Context = Self.Context;
290 for (llvm::SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
291 i2 = cv2.rbegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000292 i1 != cv1.rend(); ++i1, ++i2) {
John McCall0953e762009-09-24 19:53:00 +0000293 SrcConstruct
294 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
295 DestConstruct
296 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000297 }
298
299 // Test if they're compatible.
300 return SrcConstruct != DestConstruct &&
Sebastian Redl37d6de32008-11-08 13:00:26 +0000301 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000302}
303
Sebastian Redl26d85b12008-11-05 21:50:06 +0000304/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
305/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
306/// checked downcasts in class hierarchies.
Anders Carlsson714179b2009-08-02 19:07:59 +0000307static void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000308CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
309 const SourceRange &OpRange,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000310 const SourceRange &DestRange, CastExpr::CastKind &Kind,
311 CXXBaseSpecifierArray &BasePath) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000312 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl37d6de32008-11-08 13:00:26 +0000313 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000314
315 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
316 // or "pointer to cv void".
317
318 QualType DestPointee;
Ted Kremenek6217b802009-07-29 21:53:49 +0000319 const PointerType *DestPointer = DestType->getAs<PointerType>();
320 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000321 if (DestPointer) {
322 DestPointee = DestPointer->getPointeeType();
323 } else if (DestReference) {
324 DestPointee = DestReference->getPointeeType();
325 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000326 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000327 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000328 return;
329 }
330
Ted Kremenek6217b802009-07-29 21:53:49 +0000331 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000332 if (DestPointee->isVoidType()) {
333 assert(DestPointer && "Reference to void is not possible");
334 } else if (DestRecord) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000335 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000336 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssonb7906612009-08-26 23:45:07 +0000337 << DestRange))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000338 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000339 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000340 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000341 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000342 return;
343 }
344
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000345 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
346 // complete class type, [...]. If T is an lvalue reference type, v shall be
347 // an lvalue of a complete class type, [...]. If T is an rvalue reference
348 // type, v shall be an expression having a complete effective class type,
349 // [...]
Sebastian Redl26d85b12008-11-05 21:50:06 +0000350
Sebastian Redl37d6de32008-11-08 13:00:26 +0000351 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000352 QualType SrcPointee;
353 if (DestPointer) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000354 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000355 SrcPointee = SrcPointer->getPointeeType();
356 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000357 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000358 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000359 return;
360 }
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000361 } else if (DestReference->isLValueReferenceType()) {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000362 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000363 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000364 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000365 }
366 SrcPointee = SrcType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000367 } else {
368 SrcPointee = SrcType;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000369 }
370
Ted Kremenek6217b802009-07-29 21:53:49 +0000371 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000372 if (SrcRecord) {
Douglas Gregor86447ec2009-03-09 16:13:40 +0000373 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000374 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssonb7906612009-08-26 23:45:07 +0000375 << SrcExpr->getSourceRange()))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000376 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000377 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000378 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000379 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000380 return;
381 }
382
383 assert((DestPointer || DestReference) &&
384 "Bad destination non-ptr/ref slipped through.");
385 assert((DestRecord || DestPointee->isVoidType()) &&
386 "Bad destination pointee slipped through.");
387 assert(SrcRecord && "Bad source pointee slipped through.");
388
389 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
390 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000391 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000392 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000393 return;
394 }
395
396 // C++ 5.2.7p3: If the type of v is the same as the required result type,
397 // [except for cv].
398 if (DestRecord == SrcRecord) {
399 return;
400 }
401
402 // C++ 5.2.7p5
403 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000404 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000405 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
406 OpRange.getBegin(), OpRange,
407 &BasePath))
408 return;
409
Anders Carlsson714179b2009-08-02 19:07:59 +0000410 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000411
412 // If we are casting to or through a virtual base class, we need a
413 // vtable.
414 if (Self.BasePathInvolvesVirtualBase(BasePath))
415 Self.MarkVTableUsed(OpRange.getBegin(),
416 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000417 return;
418 }
419
420 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor952b0172010-02-11 01:04:33 +0000421 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000422 assert(SrcDecl && "Definition missing");
423 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000424 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000425 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000426 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +0000427 Self.MarkVTableUsed(OpRange.getBegin(),
428 cast<CXXRecordDecl>(SrcRecord->getDecl()));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000429
430 // Done. Everything else is run-time checks.
Anders Carlsson714179b2009-08-02 19:07:59 +0000431 Kind = CastExpr::CK_Dynamic;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000432}
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000433
434/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
435/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
436/// like this:
437/// const char *str = "literal";
438/// legacy_function(const_cast\<char*\>(str));
439void
440CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000441 const SourceRange &OpRange, const SourceRange &DestRange) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000442 if (!DestType->isLValueReferenceType())
Douglas Gregora873dfc2010-02-03 00:27:59 +0000443 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000444
445 unsigned msg = diag::err_bad_cxx_cast_generic;
446 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
447 && msg != 0)
448 Self.Diag(OpRange.getBegin(), msg) << CT_Const
449 << SrcExpr->getType() << DestType << OpRange;
450}
451
452/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
453/// valid.
454/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
455/// like this:
456/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
457void
458CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000459 const SourceRange &OpRange, const SourceRange &DestRange,
460 CastExpr::CastKind &Kind) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000461 if (!DestType->isLValueReferenceType())
Douglas Gregora873dfc2010-02-03 00:27:59 +0000462 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000463
464 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson3c31a392009-09-26 00:12:34 +0000465 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
466 msg, Kind)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000467 != TC_Success && msg != 0)
468 Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
469 << SrcExpr->getType() << DestType << OpRange;
470}
471
472
473/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
474/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
475/// implicit conversions explicit and getting rid of data loss warnings.
476void
477CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000478 const SourceRange &OpRange, CastExpr::CastKind &Kind,
479 CXXBaseSpecifierArray &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000480 // This test is outside everything else because it's the only case where
481 // a non-lvalue-reference target type does not lead to decay.
482 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000483 if (DestType->isVoidType()) {
484 Kind = CastExpr::CK_ToVoid;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000485 return;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000486 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000487
Douglas Gregorb653c522009-11-06 01:14:41 +0000488 if (!DestType->isLValueReferenceType() && !DestType->isRecordType())
Douglas Gregora873dfc2010-02-03 00:27:59 +0000489 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000490
491 unsigned msg = diag::err_bad_cxx_cast_generic;
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000492 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000493 Kind, BasePath) != TC_Success && msg != 0)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000494 Self.Diag(OpRange.getBegin(), msg) << CT_Static
495 << SrcExpr->getType() << DestType << OpRange;
496}
497
498/// TryStaticCast - Check if a static cast can be performed, and do so if
499/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
500/// and casting away constness.
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000501static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000502 QualType DestType, bool CStyle,
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000503 const SourceRange &OpRange, unsigned &msg,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000504 CastExpr::CastKind &Kind,
505 CXXBaseSpecifierArray &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000506 // The order the tests is not entirely arbitrary. There is one conversion
507 // that can be handled in two different ways. Given:
508 // struct A {};
509 // struct B : public A {
510 // B(); B(const A&);
511 // };
512 // const A &a = B();
513 // the cast static_cast<const B&>(a) could be seen as either a static
514 // reference downcast, or an explicit invocation of the user-defined
515 // conversion using B's conversion constructor.
516 // DR 427 specifies that the downcast is to be applied here.
517
518 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
519 // Done outside this function.
520
521 TryCastResult tcr;
522
523 // C++ 5.2.9p5, reference downcast.
524 // See the function for details.
525 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000526 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle, OpRange,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000527 msg, Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000528 if (tcr != TC_NotApplicable)
529 return tcr;
530
531 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
532 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
533 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000534 if (tcr != TC_NotApplicable) {
535 Kind = CastExpr::CK_NoOp;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000536 return tcr;
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000537 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000538
539 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
540 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000541 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
Douglas Gregord6e44a32010-04-16 22:09:46 +0000542 Kind);
Anders Carlsson3c31a392009-09-26 00:12:34 +0000543 if (tcr != TC_NotApplicable)
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000544 return tcr;
Anders Carlsson0aebc812009-09-09 21:33:21 +0000545
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000546 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
547 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
548 // conversions, subject to further restrictions.
549 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
550 // of qualification conversions impossible.
551 // In the CStyle case, the earlier attempt to const_cast should have taken
552 // care of reverse qualification conversions.
553
554 QualType OrigSrcType = SrcExpr->getType();
555
556 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
557
558 // Reverse integral promotion/conversion. All such conversions are themselves
559 // again integral promotions or conversions and are thus already handled by
560 // p2 (TryDirectInitialization above).
561 // (Note: any data loss warnings should be suppressed.)
562 // The exception is the reverse of enum->integer, i.e. integer->enum (and
563 // enum->enum). See also C++ 5.2.9p7.
564 // The same goes for reverse floating point promotion/conversion and
565 // floating-integral conversions. Again, only floating->enum is relevant.
566 if (DestType->isEnumeralType()) {
567 if (SrcType->isComplexType() || SrcType->isVectorType()) {
568 // Fall through - these cannot be converted.
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000569 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
570 Kind = CastExpr::CK_IntegralCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000571 return TC_Success;
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000572 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000573 }
574
575 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
576 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000577 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000578 Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000579 if (tcr != TC_NotApplicable)
580 return tcr;
581
582 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
583 // conversion. C++ 5.2.9p9 has additional information.
584 // DR54's access restrictions apply here also.
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000585 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlssoncee22422010-04-24 19:22:20 +0000586 OpRange, msg, Kind, BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000587 if (tcr != TC_NotApplicable)
588 return tcr;
589
590 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
591 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
592 // just the usual constness stuff.
Ted Kremenek6217b802009-07-29 21:53:49 +0000593 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000594 QualType SrcPointee = SrcPointer->getPointeeType();
595 if (SrcPointee->isVoidType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000596 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000597 QualType DestPointee = DestPointer->getPointeeType();
598 if (DestPointee->isIncompleteOrObjectType()) {
599 // This is definitely the intended conversion, but it might fail due
600 // to a const violation.
601 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
602 msg = diag::err_bad_cxx_cast_const_away;
603 return TC_Failed;
604 }
Eli Friedman05d9d7a2009-11-16 05:44:20 +0000605 Kind = CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000606 return TC_Success;
607 }
608 }
Fariborz Jahanian2f6c5502010-05-10 23:46:53 +0000609 else if (DestType->isObjCObjectPointerType()) {
610 // allow both c-style cast and static_cast of objective-c pointers as
611 // they are pervasive.
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +0000612 Kind = CastExpr::CK_AnyPointerToObjCPointerCast;
613 return TC_Success;
614 }
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +0000615 else if (CStyle && DestType->isBlockPointerType()) {
616 // allow c-style cast of void * to block pointers.
617 Kind = CastExpr::CK_AnyPointerToBlockPointerCast;
618 return TC_Success;
619 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000620 }
621 }
Fariborz Jahanian65267b22010-05-12 18:16:59 +0000622 // Allow arbitray objective-c pointer conversion with static casts.
623 if (SrcType->isObjCObjectPointerType() &&
624 DestType->isObjCObjectPointerType())
625 return TC_Success;
626
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000627 // We tried everything. Everything! Nothing works! :-(
628 return TC_NotApplicable;
629}
630
631/// Tests whether a conversion according to N2844 is valid.
632TryCastResult
633TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000634 unsigned &msg) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000635 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
636 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenek6217b802009-07-29 21:53:49 +0000637 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000638 if (!R)
639 return TC_NotApplicable;
640
641 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
642 return TC_NotApplicable;
643
644 // Because we try the reference downcast before this function, from now on
645 // this is the only cast possibility, so we issue an error if we fail now.
646 // FIXME: Should allow casting away constness if CStyle.
647 bool DerivedToBase;
Douglas Gregor393896f2009-11-05 13:06:35 +0000648 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
649 SrcExpr->getType(), R->getPointeeType(),
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000650 DerivedToBase) <
651 Sema::Ref_Compatible_With_Added_Qualification) {
652 msg = diag::err_bad_lvalue_to_rvalue_cast;
653 return TC_Failed;
654 }
655
Douglas Gregorf0e0b172010-03-25 00:20:38 +0000656 // FIXME: We should probably have an AST node for lvalue-to-rvalue
657 // conversions.
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000658 return TC_Success;
659}
660
661/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
662TryCastResult
663TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
664 bool CStyle, const SourceRange &OpRange,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000665 unsigned &msg, CastExpr::CastKind &Kind,
666 CXXBaseSpecifierArray &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000667 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
668 // cast to type "reference to cv2 D", where D is a class derived from B,
669 // if a valid standard conversion from "pointer to D" to "pointer to B"
670 // exists, cv2 >= cv1, and B is not a virtual base class of D.
671 // In addition, DR54 clarifies that the base must be accessible in the
672 // current context. Although the wording of DR54 only applies to the pointer
673 // variant of this rule, the intent is clearly for it to apply to the this
674 // conversion as well.
675
Ted Kremenek6217b802009-07-29 21:53:49 +0000676 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000677 if (!DestReference) {
678 return TC_NotApplicable;
679 }
680 bool RValueRef = DestReference->isRValueReferenceType();
681 if (!RValueRef && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
682 // We know the left side is an lvalue reference, so we can suggest a reason.
683 msg = diag::err_bad_cxx_cast_rvalue;
684 return TC_NotApplicable;
685 }
686
687 QualType DestPointee = DestReference->getPointeeType();
688
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000689 return TryStaticDowncast(Self,
690 Self.Context.getCanonicalType(SrcExpr->getType()),
691 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000692 OpRange, SrcExpr->getType(), DestType, msg, Kind,
693 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000694}
695
696/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
697TryCastResult
698TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump1eb44332009-09-09 15:08:12 +0000699 bool CStyle, const SourceRange &OpRange,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000700 unsigned &msg, CastExpr::CastKind &Kind,
701 CXXBaseSpecifierArray &BasePath) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000702 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
703 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
704 // is a class derived from B, if a valid standard conversion from "pointer
705 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
706 // class of D.
707 // In addition, DR54 clarifies that the base must be accessible in the
708 // current context.
709
Ted Kremenek6217b802009-07-29 21:53:49 +0000710 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000711 if (!DestPointer) {
712 return TC_NotApplicable;
713 }
714
Ted Kremenek6217b802009-07-29 21:53:49 +0000715 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000716 if (!SrcPointer) {
717 msg = diag::err_bad_static_cast_pointer_nonpointer;
718 return TC_NotApplicable;
719 }
720
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000721 return TryStaticDowncast(Self,
722 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
723 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000724 CStyle, OpRange, SrcType, DestType, msg, Kind,
725 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000726}
727
728/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
729/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000730/// DestType is possible and allowed.
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000731TryCastResult
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000732TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000733 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000734 QualType OrigDestType, unsigned &msg,
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000735 CastExpr::CastKind &Kind, CXXBaseSpecifierArray &BasePath) {
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000736 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregorfe6b2d42010-03-29 23:34:08 +0000737 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, Self.PDiag(0)) ||
738 Self.RequireCompleteType(OpRange.getBegin(), DestType, Self.PDiag(0)))
Sebastian Redl5ed66f72009-10-22 15:07:22 +0000739 return TC_NotApplicable;
740
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000741 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000742 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000743 return TC_NotApplicable;
744 }
745
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000746 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +0000747 /*DetectVirtual=*/true);
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000748 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
749 return TC_NotApplicable;
750 }
751
752 // Target type does derive from source type. Now we're serious. If an error
753 // appears now, it's not ignored.
754 // This may not be entirely in line with the standard. Take for example:
755 // struct A {};
756 // struct B : virtual A {
757 // B(A&);
758 // };
Mike Stump1eb44332009-09-09 15:08:12 +0000759 //
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000760 // void f()
761 // {
762 // (void)static_cast<const B&>(*((A*)0));
763 // }
764 // As far as the standard is concerned, p5 does not apply (A is virtual), so
765 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
766 // However, both GCC and Comeau reject this example, and accepting it would
767 // mean more complex code if we're to preserve the nice error message.
768 // FIXME: Being 100% compliant here would be nice to have.
769
770 // Must preserve cv, as always, unless we're in C-style mode.
771 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
772 msg = diag::err_bad_cxx_cast_const_away;
773 return TC_Failed;
774 }
775
776 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
777 // This code is analoguous to that in CheckDerivedToBaseConversion, except
778 // that it builds the paths in reverse order.
779 // To sum up: record all paths to the base and build a nice string from
780 // them. Use it to spice up the error message.
781 if (!Paths.isRecordingPaths()) {
782 Paths.clear();
783 Paths.setRecordingPaths(true);
784 Self.IsDerivedFrom(DestType, SrcType, Paths);
785 }
786 std::string PathDisplayStr;
787 std::set<unsigned> DisplayedPaths;
Douglas Gregora8f32e02009-10-06 17:59:45 +0000788 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000789 PI != PE; ++PI) {
790 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
791 // We haven't displayed a path to this particular base
792 // class subobject yet.
793 PathDisplayStr += "\n ";
Douglas Gregora8f32e02009-10-06 17:59:45 +0000794 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
795 EE = PI->rend();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000796 EI != EE; ++EI)
797 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000798 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000799 }
800 }
801
802 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregorab15d0e2009-11-15 09:20:52 +0000803 << QualType(SrcType).getUnqualifiedType()
804 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000805 << PathDisplayStr << OpRange;
806 msg = 0;
807 return TC_Failed;
808 }
809
810 if (Paths.getDetectedVirtual() != 0) {
811 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
812 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
813 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
814 msg = 0;
815 return TC_Failed;
816 }
817
John McCall6b2accb2010-02-10 09:31:12 +0000818 if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
John McCall6b2accb2010-02-10 09:31:12 +0000819 SrcType, DestType,
John McCall58e6f342010-03-16 05:22:47 +0000820 Paths.front(),
821 diag::err_downcast_from_inaccessible_base)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000822 msg = 0;
823 return TC_Failed;
824 }
825
Anders Carlssonf9d68e12010-04-24 19:36:51 +0000826 Self.BuildBasePathArray(Paths, BasePath);
Anders Carlsson95c5d8a2009-11-12 16:53:16 +0000827 Kind = CastExpr::CK_BaseToDerived;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000828 return TC_Success;
829}
830
831/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
832/// C++ 5.2.9p9 is valid:
833///
834/// An rvalue of type "pointer to member of D of type cv1 T" can be
835/// converted to an rvalue of type "pointer to member of B of type cv2 T",
836/// where B is a base class of D [...].
837///
838TryCastResult
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000839TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr, QualType SrcType,
840 QualType DestType, bool CStyle,
841 const SourceRange &OpRange,
Anders Carlssoncee22422010-04-24 19:22:20 +0000842 unsigned &msg, CastExpr::CastKind &Kind,
843 CXXBaseSpecifierArray &BasePath) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000844 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000845 if (!DestMemPtr)
846 return TC_NotApplicable;
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000847
848 bool WasOverloadedFunction = false;
John McCall6bb80172010-03-30 21:47:33 +0000849 DeclAccessPair FoundOverload;
Douglas Gregor1a8cf732010-04-14 23:11:21 +0000850 if (SrcExpr->getType() == Self.Context.OverloadTy) {
851 if (FunctionDecl *Fn
852 = Self.ResolveAddressOfOverloadedFunction(SrcExpr, DestType, false,
853 FoundOverload)) {
854 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
855 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
856 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
857 WasOverloadedFunction = true;
858 }
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000859 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +0000860
Ted Kremenek6217b802009-07-29 21:53:49 +0000861 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000862 if (!SrcMemPtr) {
863 msg = diag::err_bad_static_cast_member_pointer_nonmp;
864 return TC_NotApplicable;
865 }
866
867 // T == T, modulo cv
Douglas Gregora4923eb2009-11-16 21:35:15 +0000868 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
869 DestMemPtr->getPointeeType()))
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000870 return TC_NotApplicable;
871
872 // B base of D
873 QualType SrcClass(SrcMemPtr->getClass(), 0);
874 QualType DestClass(DestMemPtr->getClass(), 0);
Anders Carlssoncee22422010-04-24 19:22:20 +0000875 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000876 /*DetectVirtual=*/true);
877 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
878 return TC_NotApplicable;
879 }
880
881 // B is a base of D. But is it an allowed base? If not, it's a hard error.
Douglas Gregore0d5fe22010-05-21 20:29:55 +0000882 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000883 Paths.clear();
884 Paths.setRecordingPaths(true);
885 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
886 assert(StillOkay);
887 StillOkay = StillOkay;
888 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
889 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
890 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
891 msg = 0;
892 return TC_Failed;
893 }
894
895 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
896 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
897 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
898 msg = 0;
899 return TC_Failed;
900 }
901
John McCall6b2accb2010-02-10 09:31:12 +0000902 if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
Eli Friedman0fab8cd2010-07-23 19:25:41 +0000903 DestClass, SrcClass,
John McCall58e6f342010-03-16 05:22:47 +0000904 Paths.front(),
905 diag::err_upcast_to_inaccessible_base)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000906 msg = 0;
907 return TC_Failed;
908 }
909
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000910 if (WasOverloadedFunction) {
911 // Resolve the address of the overloaded function again, this time
912 // allowing complaints if something goes wrong.
913 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr,
914 DestType,
John McCall6bb80172010-03-30 21:47:33 +0000915 true,
916 FoundOverload);
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000917 if (!Fn) {
918 msg = 0;
919 return TC_Failed;
920 }
921
John McCall6bb80172010-03-30 21:47:33 +0000922 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
Douglas Gregor4ce46c22010-03-07 23:24:59 +0000923 if (!SrcExpr) {
924 msg = 0;
925 return TC_Failed;
926 }
927 }
928
Anders Carlssoncee22422010-04-24 19:22:20 +0000929 Self.BuildBasePathArray(Paths, BasePath);
Anders Carlsson1a31a182009-10-30 00:46:35 +0000930 Kind = CastExpr::CK_DerivedToBaseMemberPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000931 return TC_Success;
932}
933
934/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
935/// is valid:
936///
937/// An expression e can be explicitly converted to a type T using a
938/// @c static_cast if the declaration "T t(e);" is well-formed [...].
939TryCastResult
Sebastian Redla82e4ae2009-11-14 21:15:49 +0000940TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000941 bool CStyle, const SourceRange &OpRange, unsigned &msg,
Douglas Gregord6e44a32010-04-16 22:09:46 +0000942 CastExpr::CastKind &Kind) {
Anders Carlssond851b372009-09-07 18:25:47 +0000943 if (DestType->isRecordType()) {
944 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
945 diag::err_bad_dynamic_cast_incomplete)) {
946 msg = 0;
947 return TC_Failed;
948 }
949 }
Douglas Gregord6e44a32010-04-16 22:09:46 +0000950
951 // At this point of CheckStaticCast, if the destination is a reference,
952 // this has to work. There is no other way that works.
953 // On the other hand, if we're checking a C-style cast, we've still got
954 // the reinterpret_cast way.
Douglas Gregorf0e43e52010-04-16 19:30:02 +0000955 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
956 InitializationKind InitKind
Douglas Gregord6e44a32010-04-16 22:09:46 +0000957 = InitializationKind::CreateCast(/*FIXME:*/OpRange,
958 CStyle);
Douglas Gregorf0e43e52010-04-16 19:30:02 +0000959 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExpr, 1);
Douglas Gregord6e44a32010-04-16 22:09:46 +0000960 if (InitSeq.getKind() == InitializationSequence::FailedSequence &&
961 (CStyle || !DestType->isReferenceType()))
Anders Carlsson3c31a392009-09-26 00:12:34 +0000962 return TC_NotApplicable;
Douglas Gregord6e44a32010-04-16 22:09:46 +0000963
Douglas Gregorf0e43e52010-04-16 19:30:02 +0000964 Sema::OwningExprResult Result
Douglas Gregord6e44a32010-04-16 22:09:46 +0000965 = InitSeq.Perform(Self, Entity, InitKind,
966 Action::MultiExprArg(Self, (void**)&SrcExpr, 1));
Douglas Gregorf0e43e52010-04-16 19:30:02 +0000967 if (Result.isInvalid()) {
968 msg = 0;
969 return TC_Failed;
970 }
971
Douglas Gregord6e44a32010-04-16 22:09:46 +0000972 if (InitSeq.isConstructorInitialization())
973 Kind = CastExpr::CK_ConstructorConversion;
974 else
975 Kind = CastExpr::CK_NoOp;
976
Douglas Gregorf0e43e52010-04-16 19:30:02 +0000977 SrcExpr = Result.takeAs<Expr>();
978 return TC_Success;
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000979}
980
981/// TryConstCast - See if a const_cast from source to destination is allowed,
982/// and perform it if it is.
983static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
984 bool CStyle, unsigned &msg) {
985 DestType = Self.Context.getCanonicalType(DestType);
986 QualType SrcType = SrcExpr->getType();
987 if (const LValueReferenceType *DestTypeTmp =
Ted Kremenek6217b802009-07-29 21:53:49 +0000988 DestType->getAs<LValueReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +0000989 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
990 // Cannot const_cast non-lvalue to lvalue reference type. But if this
991 // is C-style, static_cast might find a way, so we simply suggest a
992 // message and tell the parent to keep searching.
993 msg = diag::err_bad_cxx_cast_rvalue;
994 return TC_NotApplicable;
995 }
996
997 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
998 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
999 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1000 SrcType = Self.Context.getPointerType(SrcType);
1001 }
1002
1003 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1004 // the rules for const_cast are the same as those used for pointers.
1005
John McCalld425d2b2010-05-18 09:35:29 +00001006 if (!DestType->isPointerType() &&
1007 !DestType->isMemberPointerType() &&
1008 !DestType->isObjCObjectPointerType()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001009 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1010 // was a reference type, we converted it to a pointer above.
1011 // The status of rvalue references isn't entirely clear, but it looks like
1012 // conversion to them is simply invalid.
1013 // C++ 5.2.11p3: For two pointer types [...]
1014 if (!CStyle)
1015 msg = diag::err_bad_const_cast_dest;
1016 return TC_NotApplicable;
1017 }
1018 if (DestType->isFunctionPointerType() ||
1019 DestType->isMemberFunctionPointerType()) {
1020 // Cannot cast direct function pointers.
1021 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1022 // T is the ultimate pointee of source and target type.
1023 if (!CStyle)
1024 msg = diag::err_bad_const_cast_dest;
1025 return TC_NotApplicable;
1026 }
1027 SrcType = Self.Context.getCanonicalType(SrcType);
1028
1029 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1030 // completely equal.
1031 // FIXME: const_cast should probably not be able to convert between pointers
1032 // to different address spaces.
1033 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1034 // in multi-level pointers may change, but the level count must be the same,
1035 // as must be the final pointee type.
1036 while (SrcType != DestType &&
Douglas Gregor5a57efd2010-06-09 03:53:18 +00001037 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Chandler Carruth595e2902009-12-29 08:05:19 +00001038 Qualifiers Quals;
1039 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, Quals);
1040 DestType = Self.Context.getUnqualifiedArrayType(DestType, Quals);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001041 }
1042
1043 // Since we're dealing in canonical types, the remainder must be the same.
1044 if (SrcType != DestType)
1045 return TC_NotApplicable;
1046
1047 return TC_Success;
1048}
1049
1050static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
1051 QualType DestType, bool CStyle,
1052 const SourceRange &OpRange,
Anders Carlsson3c31a392009-09-26 00:12:34 +00001053 unsigned &msg,
1054 CastExpr::CastKind &Kind) {
Douglas Gregore39a3892010-07-13 23:17:26 +00001055 bool IsLValueCast = false;
1056
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001057 DestType = Self.Context.getCanonicalType(DestType);
1058 QualType SrcType = SrcExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001059 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001060 bool LValue = DestTypeTmp->isLValueReferenceType();
1061 if (LValue && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
1062 // Cannot cast non-lvalue to reference type. See the similar comment in
1063 // const_cast.
1064 msg = diag::err_bad_cxx_cast_rvalue;
1065 return TC_NotApplicable;
1066 }
1067
1068 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1069 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1070 // built-in & and * operators.
1071 // This code does this transformation for the checked types.
1072 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1073 SrcType = Self.Context.getPointerType(SrcType);
Douglas Gregore39a3892010-07-13 23:17:26 +00001074 IsLValueCast = true;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001075 }
1076
1077 // Canonicalize source for comparison.
1078 SrcType = Self.Context.getCanonicalType(SrcType);
1079
Ted Kremenek6217b802009-07-29 21:53:49 +00001080 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1081 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001082 if (DestMemPtr && SrcMemPtr) {
1083 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1084 // can be explicitly converted to an rvalue of type "pointer to member
1085 // of Y of type T2" if T1 and T2 are both function types or both object
1086 // types.
1087 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1088 SrcMemPtr->getPointeeType()->isFunctionType())
1089 return TC_NotApplicable;
1090
1091 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1092 // constness.
1093 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1094 // we accept it.
1095 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1096 msg = diag::err_bad_cxx_cast_const_away;
1097 return TC_Failed;
1098 }
1099
1100 // A valid member pointer cast.
Douglas Gregore39a3892010-07-13 23:17:26 +00001101 Kind = IsLValueCast? CastExpr::CK_LValueBitCast : CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001102 return TC_Success;
1103 }
1104
1105 // See below for the enumeral issue.
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001106 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001107 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1108 // type large enough to hold it. A value of std::nullptr_t can be
1109 // converted to an integral type; the conversion has the same meaning
1110 // and validity as a conversion of (void*)0 to the integral type.
1111 if (Self.Context.getTypeSize(SrcType) >
1112 Self.Context.getTypeSize(DestType)) {
1113 msg = diag::err_bad_reinterpret_cast_small_int;
1114 return TC_Failed;
1115 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001116 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001117 return TC_Success;
1118 }
1119
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001120 bool destIsVector = DestType->isVectorType();
1121 bool srcIsVector = SrcType->isVectorType();
1122 if (srcIsVector || destIsVector) {
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001123 // FIXME: Should this also apply to floating point types?
1124 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1125 bool destIsScalar = DestType->isIntegralType(Self.Context);
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001126
1127 // Check if this is a cast between a vector and something else.
1128 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1129 !(srcIsVector && destIsVector))
1130 return TC_NotApplicable;
1131
1132 // If both types have the same size, we can successfully cast.
Douglas Gregorf2a55392009-12-22 22:47:22 +00001133 if (Self.Context.getTypeSize(SrcType)
1134 == Self.Context.getTypeSize(DestType)) {
1135 Kind = CastExpr::CK_BitCast;
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001136 return TC_Success;
Douglas Gregorf2a55392009-12-22 22:47:22 +00001137 }
Anders Carlsson0de51bc2009-09-16 19:19:43 +00001138
1139 if (destIsScalar)
1140 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1141 else if (srcIsScalar)
1142 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1143 else
1144 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1145
1146 return TC_Failed;
1147 }
1148
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001149 bool destIsPtr = DestType->isAnyPointerType() ||
1150 DestType->isBlockPointerType();
1151 bool srcIsPtr = SrcType->isAnyPointerType() ||
1152 SrcType->isBlockPointerType();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001153 if (!destIsPtr && !srcIsPtr) {
1154 // Except for std::nullptr_t->integer and lvalue->reference, which are
1155 // handled above, at least one of the two arguments must be a pointer.
1156 return TC_NotApplicable;
1157 }
1158
1159 if (SrcType == DestType) {
1160 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1161 // restrictions, a cast to the same type is allowed. The intent is not
1162 // entirely clear here, since all other paragraphs explicitly forbid casts
1163 // to the same type. However, the behavior of compilers is pretty consistent
1164 // on this point: allow same-type conversion if the involved types are
1165 // pointers, disallow otherwise.
Douglas Gregorf2a55392009-12-22 22:47:22 +00001166 Kind = CastExpr::CK_NoOp;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001167 return TC_Success;
1168 }
1169
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001170 if (DestType->isIntegralType(Self.Context)) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001171 assert(srcIsPtr && "One type must be a pointer");
1172 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1173 // type large enough to hold it.
1174 if (Self.Context.getTypeSize(SrcType) >
1175 Self.Context.getTypeSize(DestType)) {
1176 msg = diag::err_bad_reinterpret_cast_small_int;
1177 return TC_Failed;
1178 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001179 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001180 return TC_Success;
1181 }
1182
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001183 if (SrcType->isIntegralOrEnumerationType()) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001184 assert(destIsPtr && "One type must be a pointer");
1185 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1186 // converted to a pointer.
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001187 Kind = CastExpr::CK_IntegralToPointer;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001188 return TC_Success;
1189 }
1190
1191 if (!destIsPtr || !srcIsPtr) {
1192 // With the valid non-pointer conversions out of the way, we can be even
1193 // more stringent.
1194 return TC_NotApplicable;
1195 }
1196
1197 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1198 // The C-style cast operator can.
1199 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1200 msg = diag::err_bad_cxx_cast_const_away;
1201 return TC_Failed;
1202 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001203
1204 // Cannot convert between block pointers and Objective-C object pointers.
1205 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1206 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1207 return TC_NotApplicable;
1208
1209 // Any pointer can be cast to an Objective-C pointer type with a C-style
1210 // cast.
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +00001211 if (CStyle && DestType->isObjCObjectPointerType()) {
1212 Kind = CastExpr::CK_AnyPointerToObjCPointerCast;
1213 return TC_Success;
1214 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001215
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001216 // Not casting away constness, so the only remaining check is for compatible
1217 // pointer categories.
Douglas Gregore39a3892010-07-13 23:17:26 +00001218 Kind = IsLValueCast? CastExpr::CK_LValueBitCast : CastExpr::CK_BitCast;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001219
1220 if (SrcType->isFunctionPointerType()) {
1221 if (DestType->isFunctionPointerType()) {
1222 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1223 // a pointer to a function of a different type.
1224 return TC_Success;
1225 }
1226
1227 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1228 // an object type or vice versa is conditionally-supported.
1229 // Compilers support it in C++03 too, though, because it's necessary for
1230 // casting the return value of dlsym() and GetProcAddress().
1231 // FIXME: Conditionally-supported behavior should be configurable in the
1232 // TargetInfo or similar.
1233 if (!Self.getLangOptions().CPlusPlus0x)
1234 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1235 return TC_Success;
1236 }
1237
1238 if (DestType->isFunctionPointerType()) {
1239 // See above.
1240 if (!Self.getLangOptions().CPlusPlus0x)
1241 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1242 return TC_Success;
1243 }
Douglas Gregorbf9fb882010-07-08 20:27:32 +00001244
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001245 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1246 // a pointer to an object of different type.
1247 // Void pointers are not specified, but supported by every compiler out there.
1248 // So we finish by allowing everything that remains - it's got to be two
1249 // object pointers.
1250 return TC_Success;
1251}
1252
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001253bool
1254Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr,
1255 CastExpr::CastKind &Kind,
1256 CXXBaseSpecifierArray &BasePath,
1257 bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001258 // This test is outside everything else because it's the only case where
1259 // a non-lvalue-reference target type does not lead to decay.
1260 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001261 if (CastTy->isVoidType()) {
1262 Kind = CastExpr::CK_ToVoid;
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001263 return false;
Anders Carlssonbb378cb2009-10-18 20:31:03 +00001264 }
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001265
1266 // If the type is dependent, we won't do any other semantic analysis now.
1267 if (CastTy->isDependentType() || CastExpr->isTypeDependent())
1268 return false;
1269
Douglas Gregorb653c522009-11-06 01:14:41 +00001270 if (!CastTy->isLValueReferenceType() && !CastTy->isRecordType())
Douglas Gregora873dfc2010-02-03 00:27:59 +00001271 DefaultFunctionArrayLvalueConversion(CastExpr);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001272
1273 // C++ [expr.cast]p5: The conversions performed by
1274 // - a const_cast,
1275 // - a static_cast,
1276 // - a static_cast followed by a const_cast,
1277 // - a reinterpret_cast, or
1278 // - a reinterpret_cast followed by a const_cast,
1279 // can be performed using the cast notation of explicit type conversion.
1280 // [...] If a conversion can be interpreted in more than one of the ways
1281 // listed above, the interpretation that appears first in the list is used,
1282 // even if a cast resulting from that interpretation is ill-formed.
1283 // In plain language, this means trying a const_cast ...
1284 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001285 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1286 msg);
Anders Carlssonda921fd2009-10-19 18:14:28 +00001287 if (tcr == TC_Success)
1288 Kind = CastExpr::CK_NoOp;
1289
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001290 if (tcr == TC_NotApplicable) {
1291 // ... or if that is not possible, a static_cast, ignoring const, ...
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001292 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg, Kind,
1293 BasePath);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001294 if (tcr == TC_NotApplicable) {
1295 // ... and finally a reinterpret_cast, ignoring const.
Anders Carlsson3c31a392009-09-26 00:12:34 +00001296 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1297 Kind);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001298 }
1299 }
1300
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001301 if (tcr != TC_Success && msg != 0)
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00001302 Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001303 << CastExpr->getType() << CastTy << R;
1304
1305 return tcr != TC_Success;
1306}