blob: 178bc7a0140710ae0b9dcdcd6b867eab72e09ad3 [file] [log] [blame]
Sebastian Redl3c5aa4d2008-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 Gregor3e1e5272009-12-09 23:02:17 +000015#include "SemaInit.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000016#include "clang/AST/ExprCXX.h"
17#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Anders Carlssond624e162009-08-26 23:45:07 +000019#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000020#include "llvm/ADT/SmallVector.h"
Sebastian Redl015085f2008-11-07 23:29:29 +000021#include <set>
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000022using namespace clang;
23
Sebastian Redl9f831db2009-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 Redl842ef522008-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 Carlsson7cd39e02009-09-15 04:48:33 +000045 const SourceRange &DestRange,
46 CastExpr::CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +000047static void CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlssonf10e4142009-08-07 22:21:05 +000048 const SourceRange &OpRange,
Anders Carlssone9766d52009-09-09 21:33:21 +000049 CastExpr::CastKind &Kind,
50 CXXMethodDecl *&ConversionDecl);
Sebastian Redl842ef522008-11-08 13:00:26 +000051static void CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
52 const SourceRange &OpRange,
Mike Stump11289f42009-09-09 15:08:12 +000053 const SourceRange &DestRange,
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +000054 CastExpr::CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +000055
56static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
Sebastian Redl9f831db2009-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 Carlsson9a1cd872009-11-12 16:53:16 +000074 unsigned &msg,
75 CastExpr::CastKind &Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +000076static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
77 QualType DestType, bool CStyle,
78 const SourceRange &OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +000079 unsigned &msg,
80 CastExpr::CastKind &Kind);
Douglas Gregor8f3952c2009-11-15 09:20:52 +000081static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
82 CanQualType DestType, bool CStyle,
Sebastian Redl9f831db2009-07-25 15:41:38 +000083 const SourceRange &OpRange,
84 QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +000085 QualType OrigDestType, unsigned &msg,
86 CastExpr::CastKind &Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +000087static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType,
88 QualType DestType,bool CStyle,
89 const SourceRange &OpRange,
Anders Carlsson3f0db2b2009-10-30 00:46:35 +000090 unsigned &msg,
91 CastExpr::CastKind &Kind);
Sebastian Redl7c353682009-11-14 21:15:49 +000092static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +000093 QualType DestType, bool CStyle,
94 const SourceRange &OpRange,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +000095 unsigned &msg,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +000096 CastExpr::CastKind &Kind,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +000097 CXXMethodDecl *&ConversionDecl);
Sebastian Redl7c353682009-11-14 21:15:49 +000098static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +000099 QualType DestType, bool CStyle,
100 const SourceRange &OpRange,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000101 unsigned &msg,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000102 CastExpr::CastKind &Kind,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000103 CXXMethodDecl *&ConversionDecl);
Sebastian Redl9f831db2009-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 Carlsson9d1b34b2009-09-26 00:12:34 +0000109 unsigned &msg,
110 CastExpr::CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +0000111
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000112/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000113Action::OwningExprResult
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000114Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
115 SourceLocation LAngleBracketLoc, TypeTy *Ty,
116 SourceLocation RAngleBracketLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000117 SourceLocation LParenLoc, ExprArg E,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000118 SourceLocation RParenLoc) {
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000119 Expr *Ex = E.takeAs<Expr>();
John McCall97513962010-01-15 18:39:57 +0000120 TypeSourceInfo *DestTInfo;
121 QualType DestType = GetTypeFromParser(Ty, &DestTInfo);
122 if (!DestTInfo)
123 DestTInfo = Context.getTrivialTypeSourceInfo(DestType, SourceLocation());
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000124 SourceRange OpRange(OpLoc, RParenLoc);
125 SourceRange DestRange(LAngleBracketLoc, RAngleBracketLoc);
126
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000127 // If the type is dependent, we won't do the semantic analysis now.
128 // FIXME: should we check this in a more fine-grained manner?
129 bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
130
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000131 switch (Kind) {
132 default: assert(0 && "Unknown C++ cast!");
133
134 case tok::kw_const_cast:
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000135 if (!TypeDependent)
136 CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000137 return Owned(new (Context) CXXConstCastExpr(DestType.getNonReferenceType(),
John McCall97513962010-01-15 18:39:57 +0000138 Ex, DestTInfo, OpLoc));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000139
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000140 case tok::kw_dynamic_cast: {
141 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000142 if (!TypeDependent)
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000143 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000144 return Owned(new (Context)CXXDynamicCastExpr(DestType.getNonReferenceType(),
John McCall97513962010-01-15 18:39:57 +0000145 Kind, Ex, DestTInfo, OpLoc));
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000146 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000147 case tok::kw_reinterpret_cast: {
148 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000149 if (!TypeDependent)
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000150 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000151 return Owned(new (Context) CXXReinterpretCastExpr(
152 DestType.getNonReferenceType(),
John McCall97513962010-01-15 18:39:57 +0000153 Kind, Ex, DestTInfo, OpLoc));
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000154 }
Anders Carlssonf10e4142009-08-07 22:21:05 +0000155 case tok::kw_static_cast: {
156 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlssone9766d52009-09-09 21:33:21 +0000157 if (!TypeDependent) {
158 CXXMethodDecl *Method = 0;
159
160 CheckStaticCast(*this, Ex, DestType, OpRange, Kind, Method);
161
162 if (Method) {
163 OwningExprResult CastArg
164 = BuildCXXCastArgument(OpLoc, DestType.getNonReferenceType(),
165 Kind, Method, Owned(Ex));
166 if (CastArg.isInvalid())
167 return ExprError();
168
169 Ex = CastArg.takeAs<Expr>();
170 }
171 }
172
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000173 return Owned(new (Context) CXXStaticCastExpr(DestType.getNonReferenceType(),
John McCall97513962010-01-15 18:39:57 +0000174 Kind, Ex, DestTInfo, OpLoc));
Anders Carlssonf10e4142009-08-07 22:21:05 +0000175 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000176 }
177
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000178 return ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000179}
180
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000181/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
182/// this removes one level of indirection from both types, provided that they're
183/// the same kind of pointer (plain or to-member). Unlike the Sema function,
184/// this one doesn't care if the two pointers-to-member don't point into the
185/// same class. This is because CastsAwayConstness doesn't care.
186bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
187 const PointerType *T1PtrType = T1->getAs<PointerType>(),
188 *T2PtrType = T2->getAs<PointerType>();
189 if (T1PtrType && T2PtrType) {
190 T1 = T1PtrType->getPointeeType();
191 T2 = T2PtrType->getPointeeType();
192 return true;
193 }
194
195 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
196 *T2MPType = T2->getAs<MemberPointerType>();
197 if (T1MPType && T2MPType) {
198 T1 = T1MPType->getPointeeType();
199 T2 = T2MPType->getPointeeType();
200 return true;
201 }
202 return false;
203}
204
Sebastian Redla5a77a62009-01-27 23:18:31 +0000205/// CastsAwayConstness - Check if the pointer conversion from SrcType to
206/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
207/// the cast checkers. Both arguments must denote pointer (possibly to member)
208/// types.
Sebastian Redl802f14c2009-10-22 15:07:22 +0000209static bool
Mike Stump11289f42009-09-09 15:08:12 +0000210CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
Sebastian Redla5a77a62009-01-27 23:18:31 +0000211 // Casting away constness is defined in C++ 5.2.11p8 with reference to
212 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
213 // the rules are non-trivial. So first we construct Tcv *...cv* as described
214 // in C++ 5.2.11p8.
215 assert((SrcType->isPointerType() || SrcType->isMemberPointerType()) &&
216 "Source type is not pointer or pointer to member.");
217 assert((DestType->isPointerType() || DestType->isMemberPointerType()) &&
218 "Destination type is not pointer or pointer to member.");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000219
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000220 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
221 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
John McCall8ccfcb52009-09-24 19:53:00 +0000222 llvm::SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000223
224 // Find the qualifications.
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000225 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCall8ccfcb52009-09-24 19:53:00 +0000226 cv1.push_back(UnwrappedSrcType.getQualifiers());
227 cv2.push_back(UnwrappedDestType.getQualifiers());
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000228 }
229 assert(cv1.size() > 0 && "Must have at least one pointer level.");
230
231 // Construct void pointers with those qualifiers (in reverse order of
232 // unwrapping, of course).
Sebastian Redl842ef522008-11-08 13:00:26 +0000233 QualType SrcConstruct = Self.Context.VoidTy;
234 QualType DestConstruct = Self.Context.VoidTy;
John McCall8ccfcb52009-09-24 19:53:00 +0000235 ASTContext &Context = Self.Context;
236 for (llvm::SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
237 i2 = cv2.rbegin();
Mike Stump11289f42009-09-09 15:08:12 +0000238 i1 != cv1.rend(); ++i1, ++i2) {
John McCall8ccfcb52009-09-24 19:53:00 +0000239 SrcConstruct
240 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
241 DestConstruct
242 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000243 }
244
245 // Test if they're compatible.
246 return SrcConstruct != DestConstruct &&
Sebastian Redl842ef522008-11-08 13:00:26 +0000247 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000248}
249
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000250/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
251/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
252/// checked downcasts in class hierarchies.
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000253static void
Sebastian Redl842ef522008-11-08 13:00:26 +0000254CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
255 const SourceRange &OpRange,
Mike Stump11289f42009-09-09 15:08:12 +0000256 const SourceRange &DestRange, CastExpr::CastKind &Kind) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000257 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl842ef522008-11-08 13:00:26 +0000258 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000259
260 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
261 // or "pointer to cv void".
262
263 QualType DestPointee;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000264 const PointerType *DestPointer = DestType->getAs<PointerType>();
265 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000266 if (DestPointer) {
267 DestPointee = DestPointer->getPointeeType();
268 } else if (DestReference) {
269 DestPointee = DestReference->getPointeeType();
270 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000271 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000272 << OrigDestType << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000273 return;
274 }
275
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000276 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000277 if (DestPointee->isVoidType()) {
278 assert(DestPointer && "Reference to void is not possible");
279 } else if (DestRecord) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000280 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Anders Carlssond624e162009-08-26 23:45:07 +0000281 PDiag(diag::err_bad_dynamic_cast_incomplete)
282 << DestRange))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000283 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000284 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000285 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000286 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000287 return;
288 }
289
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000290 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
291 // complete class type, [...]. If T is an lvalue reference type, v shall be
292 // an lvalue of a complete class type, [...]. If T is an rvalue reference
293 // type, v shall be an expression having a complete effective class type,
294 // [...]
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000295
Sebastian Redl842ef522008-11-08 13:00:26 +0000296 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000297 QualType SrcPointee;
298 if (DestPointer) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000299 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000300 SrcPointee = SrcPointer->getPointeeType();
301 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000302 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000303 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000304 return;
305 }
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000306 } else if (DestReference->isLValueReferenceType()) {
Sebastian Redl842ef522008-11-08 13:00:26 +0000307 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000308 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000309 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000310 }
311 SrcPointee = SrcType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000312 } else {
313 SrcPointee = SrcType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000314 }
315
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000316 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000317 if (SrcRecord) {
Douglas Gregored0cfbd2009-03-09 16:13:40 +0000318 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Anders Carlssond624e162009-08-26 23:45:07 +0000319 PDiag(diag::err_bad_dynamic_cast_incomplete)
320 << SrcExpr->getSourceRange()))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000321 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000322 } else {
Chris Lattner29e812b2008-11-20 06:06:08 +0000323 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000324 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000325 return;
326 }
327
328 assert((DestPointer || DestReference) &&
329 "Bad destination non-ptr/ref slipped through.");
330 assert((DestRecord || DestPointee->isVoidType()) &&
331 "Bad destination pointee slipped through.");
332 assert(SrcRecord && "Bad source pointee slipped through.");
333
334 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
335 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000336 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000337 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000338 return;
339 }
340
341 // C++ 5.2.7p3: If the type of v is the same as the required result type,
342 // [except for cv].
343 if (DestRecord == SrcRecord) {
344 return;
345 }
346
347 // C++ 5.2.7p5
348 // Upcasts are resolved statically.
Sebastian Redl842ef522008-11-08 13:00:26 +0000349 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
350 Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
Chris Lattner1e5665e2008-11-24 06:25:27 +0000351 OpRange.getBegin(), OpRange);
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000352 Kind = CastExpr::CK_DerivedToBase;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000353 // Diagnostic already emitted on error.
354 return;
355 }
356
357 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Sebastian Redl842ef522008-11-08 13:00:26 +0000358 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(Self.Context);
Sebastian Redlb426f6332008-11-06 15:59:35 +0000359 assert(SrcDecl && "Definition missing");
360 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner29e812b2008-11-20 06:06:08 +0000361 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000362 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000363 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000364
365 // Done. Everything else is run-time checks.
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000366 Kind = CastExpr::CK_Dynamic;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000367}
Sebastian Redl9f831db2009-07-25 15:41:38 +0000368
369/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
370/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
371/// like this:
372/// const char *str = "literal";
373/// legacy_function(const_cast\<char*\>(str));
374void
375CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +0000376 const SourceRange &OpRange, const SourceRange &DestRange) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000377 if (!DestType->isLValueReferenceType())
378 Self.DefaultFunctionArrayConversion(SrcExpr);
379
380 unsigned msg = diag::err_bad_cxx_cast_generic;
381 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
382 && msg != 0)
383 Self.Diag(OpRange.getBegin(), msg) << CT_Const
384 << SrcExpr->getType() << DestType << OpRange;
385}
386
387/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
388/// valid.
389/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
390/// like this:
391/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
392void
393CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000394 const SourceRange &OpRange, const SourceRange &DestRange,
395 CastExpr::CastKind &Kind) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000396 if (!DestType->isLValueReferenceType())
397 Self.DefaultFunctionArrayConversion(SrcExpr);
398
399 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000400 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
401 msg, Kind)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000402 != TC_Success && msg != 0)
403 Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
404 << SrcExpr->getType() << DestType << OpRange;
405}
406
407
408/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
409/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
410/// implicit conversions explicit and getting rid of data loss warnings.
411void
412CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlssone9766d52009-09-09 21:33:21 +0000413 const SourceRange &OpRange, CastExpr::CastKind &Kind,
414 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000415 // This test is outside everything else because it's the only case where
416 // a non-lvalue-reference target type does not lead to decay.
417 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman03bf60a2009-11-16 05:44:20 +0000418 if (DestType->isVoidType()) {
419 Kind = CastExpr::CK_ToVoid;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000420 return;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000421 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000422
Douglas Gregorad8b2222009-11-06 01:14:41 +0000423 if (!DestType->isLValueReferenceType() && !DestType->isRecordType())
Sebastian Redl9f831db2009-07-25 15:41:38 +0000424 Self.DefaultFunctionArrayConversion(SrcExpr);
425
426 unsigned msg = diag::err_bad_cxx_cast_generic;
Sebastian Redl7c353682009-11-14 21:15:49 +0000427 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000428 Kind, ConversionDecl)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000429 != TC_Success && msg != 0)
430 Self.Diag(OpRange.getBegin(), msg) << CT_Static
431 << SrcExpr->getType() << DestType << OpRange;
432}
433
434/// TryStaticCast - Check if a static cast can be performed, and do so if
435/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
436/// and casting away constness.
Sebastian Redl7c353682009-11-14 21:15:49 +0000437static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000438 QualType DestType, bool CStyle,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000439 const SourceRange &OpRange, unsigned &msg,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000440 CastExpr::CastKind &Kind,
Mike Stump11289f42009-09-09 15:08:12 +0000441 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000442 // The order the tests is not entirely arbitrary. There is one conversion
443 // that can be handled in two different ways. Given:
444 // struct A {};
445 // struct B : public A {
446 // B(); B(const A&);
447 // };
448 // const A &a = B();
449 // the cast static_cast<const B&>(a) could be seen as either a static
450 // reference downcast, or an explicit invocation of the user-defined
451 // conversion using B's conversion constructor.
452 // DR 427 specifies that the downcast is to be applied here.
453
454 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
455 // Done outside this function.
456
457 TryCastResult tcr;
458
459 // C++ 5.2.9p5, reference downcast.
460 // See the function for details.
461 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redl7c353682009-11-14 21:15:49 +0000462 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle, OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000463 msg, Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000464 if (tcr != TC_NotApplicable)
465 return tcr;
466
467 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
468 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
469 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
Sebastian Redl7c353682009-11-14 21:15:49 +0000470 if (tcr != TC_NotApplicable) {
471 Kind = CastExpr::CK_NoOp;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000472 return tcr;
Sebastian Redl7c353682009-11-14 21:15:49 +0000473 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000474
475 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
476 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000477 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000478 Kind, ConversionDecl);
479 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000480 return tcr;
Anders Carlssone9766d52009-09-09 21:33:21 +0000481
Sebastian Redl9f831db2009-07-25 15:41:38 +0000482 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
483 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
484 // conversions, subject to further restrictions.
485 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
486 // of qualification conversions impossible.
487 // In the CStyle case, the earlier attempt to const_cast should have taken
488 // care of reverse qualification conversions.
489
490 QualType OrigSrcType = SrcExpr->getType();
491
492 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
493
494 // Reverse integral promotion/conversion. All such conversions are themselves
495 // again integral promotions or conversions and are thus already handled by
496 // p2 (TryDirectInitialization above).
497 // (Note: any data loss warnings should be suppressed.)
498 // The exception is the reverse of enum->integer, i.e. integer->enum (and
499 // enum->enum). See also C++ 5.2.9p7.
500 // The same goes for reverse floating point promotion/conversion and
501 // floating-integral conversions. Again, only floating->enum is relevant.
502 if (DestType->isEnumeralType()) {
503 if (SrcType->isComplexType() || SrcType->isVectorType()) {
504 // Fall through - these cannot be converted.
Eli Friedman03bf60a2009-11-16 05:44:20 +0000505 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
506 Kind = CastExpr::CK_IntegralCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000507 return TC_Success;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000508 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000509 }
510
511 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
512 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000513 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
514 Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000515 if (tcr != TC_NotApplicable)
516 return tcr;
517
518 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
519 // conversion. C++ 5.2.9p9 has additional information.
520 // DR54's access restrictions apply here also.
521 tcr = TryStaticMemberPointerUpcast(Self, SrcType, DestType, CStyle,
Anders Carlsson3f0db2b2009-10-30 00:46:35 +0000522 OpRange, msg, Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000523 if (tcr != TC_NotApplicable)
524 return tcr;
525
526 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
527 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
528 // just the usual constness stuff.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000529 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000530 QualType SrcPointee = SrcPointer->getPointeeType();
531 if (SrcPointee->isVoidType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000532 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000533 QualType DestPointee = DestPointer->getPointeeType();
534 if (DestPointee->isIncompleteOrObjectType()) {
535 // This is definitely the intended conversion, but it might fail due
536 // to a const violation.
537 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
538 msg = diag::err_bad_cxx_cast_const_away;
539 return TC_Failed;
540 }
Eli Friedman03bf60a2009-11-16 05:44:20 +0000541 Kind = CastExpr::CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000542 return TC_Success;
543 }
544 }
Fariborz Jahanian859c4152009-12-08 23:09:15 +0000545 else if (CStyle && DestType->isObjCObjectPointerType()) {
546 // allow c-style cast of objective-c pointers as they are pervasive.
547 Kind = CastExpr::CK_AnyPointerToObjCPointerCast;
548 return TC_Success;
549 }
Fariborz Jahanianffe912c2009-12-11 22:40:48 +0000550 else if (CStyle && DestType->isBlockPointerType()) {
551 // allow c-style cast of void * to block pointers.
552 Kind = CastExpr::CK_AnyPointerToBlockPointerCast;
553 return TC_Success;
554 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000555 }
556 }
557
558 // We tried everything. Everything! Nothing works! :-(
559 return TC_NotApplicable;
560}
561
562/// Tests whether a conversion according to N2844 is valid.
563TryCastResult
564TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +0000565 unsigned &msg) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000566 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
567 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000568 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000569 if (!R)
570 return TC_NotApplicable;
571
572 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
573 return TC_NotApplicable;
574
575 // Because we try the reference downcast before this function, from now on
576 // this is the only cast possibility, so we issue an error if we fail now.
577 // FIXME: Should allow casting away constness if CStyle.
578 bool DerivedToBase;
Douglas Gregor3ec1bf22009-11-05 13:06:35 +0000579 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
580 SrcExpr->getType(), R->getPointeeType(),
Sebastian Redl9f831db2009-07-25 15:41:38 +0000581 DerivedToBase) <
582 Sema::Ref_Compatible_With_Added_Qualification) {
583 msg = diag::err_bad_lvalue_to_rvalue_cast;
584 return TC_Failed;
585 }
586
587 // FIXME: Similar to CheckReferenceInit, we actually need more AST annotation
588 // than nothing.
589 return TC_Success;
590}
591
592/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
593TryCastResult
594TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
595 bool CStyle, const SourceRange &OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000596 unsigned &msg, CastExpr::CastKind &Kind) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000597 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
598 // cast to type "reference to cv2 D", where D is a class derived from B,
599 // if a valid standard conversion from "pointer to D" to "pointer to B"
600 // exists, cv2 >= cv1, and B is not a virtual base class of D.
601 // In addition, DR54 clarifies that the base must be accessible in the
602 // current context. Although the wording of DR54 only applies to the pointer
603 // variant of this rule, the intent is clearly for it to apply to the this
604 // conversion as well.
605
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000606 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000607 if (!DestReference) {
608 return TC_NotApplicable;
609 }
610 bool RValueRef = DestReference->isRValueReferenceType();
611 if (!RValueRef && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
612 // We know the left side is an lvalue reference, so we can suggest a reason.
613 msg = diag::err_bad_cxx_cast_rvalue;
614 return TC_NotApplicable;
615 }
616
617 QualType DestPointee = DestReference->getPointeeType();
618
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000619 return TryStaticDowncast(Self,
620 Self.Context.getCanonicalType(SrcExpr->getType()),
621 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000622 OpRange, SrcExpr->getType(), DestType, msg, Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000623}
624
625/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
626TryCastResult
627TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +0000628 bool CStyle, const SourceRange &OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000629 unsigned &msg, CastExpr::CastKind &Kind) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000630 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
631 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
632 // is a class derived from B, if a valid standard conversion from "pointer
633 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
634 // class of D.
635 // In addition, DR54 clarifies that the base must be accessible in the
636 // current context.
637
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000638 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000639 if (!DestPointer) {
640 return TC_NotApplicable;
641 }
642
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000643 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000644 if (!SrcPointer) {
645 msg = diag::err_bad_static_cast_pointer_nonpointer;
646 return TC_NotApplicable;
647 }
648
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000649 return TryStaticDowncast(Self,
650 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
651 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
652 CStyle, OpRange, SrcType, DestType, msg, Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000653}
654
655/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
656/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000657/// DestType is possible and allowed.
Sebastian Redl9f831db2009-07-25 15:41:38 +0000658TryCastResult
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000659TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000660 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000661 QualType OrigDestType, unsigned &msg,
662 CastExpr::CastKind &Kind) {
Sebastian Redl802f14c2009-10-22 15:07:22 +0000663 // We can only work with complete types. But don't complain if it doesn't work
664 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, PDiag(0)) ||
665 Self.RequireCompleteType(OpRange.getBegin(), DestType, PDiag(0)))
666 return TC_NotApplicable;
667
Sebastian Redl9f831db2009-07-25 15:41:38 +0000668 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000669 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000670 return TC_NotApplicable;
671 }
672
Douglas Gregor36d1b142009-10-06 17:59:45 +0000673 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
674 /*DetectVirtual=*/true);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000675 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
676 return TC_NotApplicable;
677 }
678
679 // Target type does derive from source type. Now we're serious. If an error
680 // appears now, it's not ignored.
681 // This may not be entirely in line with the standard. Take for example:
682 // struct A {};
683 // struct B : virtual A {
684 // B(A&);
685 // };
Mike Stump11289f42009-09-09 15:08:12 +0000686 //
Sebastian Redl9f831db2009-07-25 15:41:38 +0000687 // void f()
688 // {
689 // (void)static_cast<const B&>(*((A*)0));
690 // }
691 // As far as the standard is concerned, p5 does not apply (A is virtual), so
692 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
693 // However, both GCC and Comeau reject this example, and accepting it would
694 // mean more complex code if we're to preserve the nice error message.
695 // FIXME: Being 100% compliant here would be nice to have.
696
697 // Must preserve cv, as always, unless we're in C-style mode.
698 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
699 msg = diag::err_bad_cxx_cast_const_away;
700 return TC_Failed;
701 }
702
703 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
704 // This code is analoguous to that in CheckDerivedToBaseConversion, except
705 // that it builds the paths in reverse order.
706 // To sum up: record all paths to the base and build a nice string from
707 // them. Use it to spice up the error message.
708 if (!Paths.isRecordingPaths()) {
709 Paths.clear();
710 Paths.setRecordingPaths(true);
711 Self.IsDerivedFrom(DestType, SrcType, Paths);
712 }
713 std::string PathDisplayStr;
714 std::set<unsigned> DisplayedPaths;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000715 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000716 PI != PE; ++PI) {
717 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
718 // We haven't displayed a path to this particular base
719 // class subobject yet.
720 PathDisplayStr += "\n ";
Douglas Gregor36d1b142009-10-06 17:59:45 +0000721 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
722 EE = PI->rend();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000723 EI != EE; ++EI)
724 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000725 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000726 }
727 }
728
729 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000730 << QualType(SrcType).getUnqualifiedType()
731 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9f831db2009-07-25 15:41:38 +0000732 << PathDisplayStr << OpRange;
733 msg = 0;
734 return TC_Failed;
735 }
736
737 if (Paths.getDetectedVirtual() != 0) {
738 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
739 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
740 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
741 msg = 0;
742 return TC_Failed;
743 }
744
745 if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
746 diag::err_downcast_from_inaccessible_base, Paths,
747 OpRange.getBegin(), DeclarationName())) {
748 msg = 0;
749 return TC_Failed;
750 }
751
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000752 Kind = CastExpr::CK_BaseToDerived;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000753 return TC_Success;
754}
755
756/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
757/// C++ 5.2.9p9 is valid:
758///
759/// An rvalue of type "pointer to member of D of type cv1 T" can be
760/// converted to an rvalue of type "pointer to member of B of type cv2 T",
761/// where B is a base class of D [...].
762///
763TryCastResult
764TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType, QualType DestType,
765 bool CStyle, const SourceRange &OpRange,
Anders Carlsson3f0db2b2009-10-30 00:46:35 +0000766 unsigned &msg, CastExpr::CastKind &Kind) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000767 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000768 if (!DestMemPtr)
769 return TC_NotApplicable;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000770 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000771 if (!SrcMemPtr) {
772 msg = diag::err_bad_static_cast_member_pointer_nonmp;
773 return TC_NotApplicable;
774 }
775
776 // T == T, modulo cv
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000777 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
778 DestMemPtr->getPointeeType()))
Sebastian Redl9f831db2009-07-25 15:41:38 +0000779 return TC_NotApplicable;
780
781 // B base of D
782 QualType SrcClass(SrcMemPtr->getClass(), 0);
783 QualType DestClass(DestMemPtr->getClass(), 0);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000784 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000785 /*DetectVirtual=*/true);
786 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
787 return TC_NotApplicable;
788 }
789
790 // B is a base of D. But is it an allowed base? If not, it's a hard error.
791 if (Paths.isAmbiguous(DestClass)) {
792 Paths.clear();
793 Paths.setRecordingPaths(true);
794 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
795 assert(StillOkay);
796 StillOkay = StillOkay;
797 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
798 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
799 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
800 msg = 0;
801 return TC_Failed;
802 }
803
804 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
805 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
806 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
807 msg = 0;
808 return TC_Failed;
809 }
810
811 if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
812 diag::err_downcast_from_inaccessible_base, Paths,
813 OpRange.getBegin(), DeclarationName())) {
814 msg = 0;
815 return TC_Failed;
816 }
817
Anders Carlsson3f0db2b2009-10-30 00:46:35 +0000818 Kind = CastExpr::CK_DerivedToBaseMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000819 return TC_Success;
820}
821
822/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
823/// is valid:
824///
825/// An expression e can be explicitly converted to a type T using a
826/// @c static_cast if the declaration "T t(e);" is well-formed [...].
827TryCastResult
Sebastian Redl7c353682009-11-14 21:15:49 +0000828TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000829 bool CStyle, const SourceRange &OpRange, unsigned &msg,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000830 CastExpr::CastKind &Kind,
Mike Stump11289f42009-09-09 15:08:12 +0000831 CXXMethodDecl *&ConversionDecl) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +0000832 if (DestType->isRecordType()) {
833 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
834 diag::err_bad_dynamic_cast_incomplete)) {
835 msg = 0;
836 return TC_Failed;
837 }
838 }
Mike Stump11289f42009-09-09 15:08:12 +0000839
Sebastian Redl9f831db2009-07-25 15:41:38 +0000840 if (DestType->isReferenceType()) {
Sebastian Redl7c353682009-11-14 21:15:49 +0000841 // All reference bindings insert implicit casts above that do the actual
842 // casting.
843 Kind = CastExpr::CK_NoOp;
844
Sebastian Redl9f831db2009-07-25 15:41:38 +0000845 // At this point of CheckStaticCast, if the destination is a reference,
846 // this has to work. There is no other way that works.
847 // On the other hand, if we're checking a C-style cast, we've still got
Sebastian Redl7c353682009-11-14 21:15:49 +0000848 // the reinterpret_cast way. So in C-style mode, we first try the call
849 // with an ICS to suppress errors.
850 if (CStyle) {
851 ImplicitConversionSequence ICS;
852 if(Self.CheckReferenceInit(SrcExpr, DestType, OpRange.getBegin(),
853 /*SuppressUserConversions=*/false,
854 /*AllowExplicit=*/false, /*ForceRValue=*/false,
855 &ICS))
856 return TC_NotApplicable;
857 }
858 // Now we're committed either way.
859 if(!Self.CheckReferenceInit(SrcExpr, DestType, OpRange.getBegin(),
860 /*SuppressUserConversions=*/false,
861 /*AllowExplicit=*/false,
862 /*ForceRValue=*/false, 0,
863 /*IgnoreBaseAccess=*/CStyle))
Sebastian Redl9f831db2009-07-25 15:41:38 +0000864 return TC_Success;
Sebastian Redl7c353682009-11-14 21:15:49 +0000865
866 // We already got an error message.
Sebastian Redl9f831db2009-07-25 15:41:38 +0000867 msg = 0;
868 return TC_Failed;
869 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000870
Douglas Gregorbf3f3222009-11-14 03:27:21 +0000871 if (DestType->isRecordType()) {
872 if (CXXConstructorDecl *Constructor
Sebastian Redl7c353682009-11-14 21:15:49 +0000873 = Self.TryInitializationByConstructor(DestType, &SrcExpr, 1,
Douglas Gregorbf3f3222009-11-14 03:27:21 +0000874 OpRange.getBegin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +0000875 InitializationKind::CreateDirect(OpRange.getBegin(),
876 OpRange.getBegin(),
877 OpRange.getEnd()))) {
Douglas Gregorbf3f3222009-11-14 03:27:21 +0000878 ConversionDecl = Constructor;
879 Kind = CastExpr::CK_ConstructorConversion;
880 return TC_Success;
881 }
882
883 return TC_NotApplicable;
884 }
Sebastian Redl7c353682009-11-14 21:15:49 +0000885
Sebastian Redl9f831db2009-07-25 15:41:38 +0000886 // FIXME: To get a proper error from invalid conversions here, we need to
887 // reimplement more of this.
888 // FIXME: This does not actually perform the conversion, and thus does not
889 // check for ambiguity or access.
Mike Stump11289f42009-09-09 15:08:12 +0000890 ImplicitConversionSequence ICS =
Anders Carlssonef4c7212009-08-27 17:24:15 +0000891 Self.TryImplicitConversion(SrcExpr, DestType,
892 /*SuppressUserConversions=*/false,
Anders Carlssonf2bc7c32009-08-28 16:22:20 +0000893 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +0000894 /*ForceRValue=*/false,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000895 /*InOverloadResolution=*/false,
896 /*one of user provided casts*/true);
Mike Stump11289f42009-09-09 15:08:12 +0000897
John McCall0d1da222010-01-12 00:44:57 +0000898 if (ICS.isBad())
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000899 return TC_NotApplicable;
900
Sebastian Redl7c353682009-11-14 21:15:49 +0000901 // The conversion is possible, so commit to it.
Eli Friedman03bf60a2009-11-16 05:44:20 +0000902 Kind = CastExpr::CK_NoOp;
Sebastian Redl7c353682009-11-14 21:15:49 +0000903 msg = 0;
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +0000904 return Self.PerformImplicitConversion(SrcExpr, DestType, ICS, Sema::AA_Casting,
Sebastian Redl7c353682009-11-14 21:15:49 +0000905 /*IgnoreBaseAccess*/CStyle) ?
906 TC_Failed : TC_Success;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000907}
908
909/// TryConstCast - See if a const_cast from source to destination is allowed,
910/// and perform it if it is.
911static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
912 bool CStyle, unsigned &msg) {
913 DestType = Self.Context.getCanonicalType(DestType);
914 QualType SrcType = SrcExpr->getType();
915 if (const LValueReferenceType *DestTypeTmp =
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000916 DestType->getAs<LValueReferenceType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000917 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
918 // Cannot const_cast non-lvalue to lvalue reference type. But if this
919 // is C-style, static_cast might find a way, so we simply suggest a
920 // message and tell the parent to keep searching.
921 msg = diag::err_bad_cxx_cast_rvalue;
922 return TC_NotApplicable;
923 }
924
925 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
926 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
927 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
928 SrcType = Self.Context.getPointerType(SrcType);
929 }
930
931 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
932 // the rules for const_cast are the same as those used for pointers.
933
934 if (!DestType->isPointerType() && !DestType->isMemberPointerType()) {
935 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
936 // was a reference type, we converted it to a pointer above.
937 // The status of rvalue references isn't entirely clear, but it looks like
938 // conversion to them is simply invalid.
939 // C++ 5.2.11p3: For two pointer types [...]
940 if (!CStyle)
941 msg = diag::err_bad_const_cast_dest;
942 return TC_NotApplicable;
943 }
944 if (DestType->isFunctionPointerType() ||
945 DestType->isMemberFunctionPointerType()) {
946 // Cannot cast direct function pointers.
947 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
948 // T is the ultimate pointee of source and target type.
949 if (!CStyle)
950 msg = diag::err_bad_const_cast_dest;
951 return TC_NotApplicable;
952 }
953 SrcType = Self.Context.getCanonicalType(SrcType);
954
955 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
956 // completely equal.
957 // FIXME: const_cast should probably not be able to convert between pointers
958 // to different address spaces.
959 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
960 // in multi-level pointers may change, but the level count must be the same,
961 // as must be the final pointee type.
962 while (SrcType != DestType &&
963 Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Chandler Carruth585fb1e2009-12-29 08:05:19 +0000964 Qualifiers Quals;
965 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, Quals);
966 DestType = Self.Context.getUnqualifiedArrayType(DestType, Quals);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000967 }
968
969 // Since we're dealing in canonical types, the remainder must be the same.
970 if (SrcType != DestType)
971 return TC_NotApplicable;
972
973 return TC_Success;
974}
975
976static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
977 QualType DestType, bool CStyle,
978 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000979 unsigned &msg,
980 CastExpr::CastKind &Kind) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000981 DestType = Self.Context.getCanonicalType(DestType);
982 QualType SrcType = SrcExpr->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000983 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000984 bool LValue = DestTypeTmp->isLValueReferenceType();
985 if (LValue && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
986 // Cannot cast non-lvalue to reference type. See the similar comment in
987 // const_cast.
988 msg = diag::err_bad_cxx_cast_rvalue;
989 return TC_NotApplicable;
990 }
991
992 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
993 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
994 // built-in & and * operators.
995 // This code does this transformation for the checked types.
996 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
997 SrcType = Self.Context.getPointerType(SrcType);
998 }
999
1000 // Canonicalize source for comparison.
1001 SrcType = Self.Context.getCanonicalType(SrcType);
1002
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001003 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1004 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001005 if (DestMemPtr && SrcMemPtr) {
1006 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1007 // can be explicitly converted to an rvalue of type "pointer to member
1008 // of Y of type T2" if T1 and T2 are both function types or both object
1009 // types.
1010 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1011 SrcMemPtr->getPointeeType()->isFunctionType())
1012 return TC_NotApplicable;
1013
1014 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1015 // constness.
1016 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1017 // we accept it.
1018 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1019 msg = diag::err_bad_cxx_cast_const_away;
1020 return TC_Failed;
1021 }
1022
1023 // A valid member pointer cast.
Anders Carlsson9500ad12009-10-18 20:31:03 +00001024 Kind = CastExpr::CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001025 return TC_Success;
1026 }
1027
1028 // See below for the enumeral issue.
1029 if (SrcType->isNullPtrType() && DestType->isIntegralType() &&
1030 !DestType->isEnumeralType()) {
1031 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1032 // type large enough to hold it. A value of std::nullptr_t can be
1033 // converted to an integral type; the conversion has the same meaning
1034 // and validity as a conversion of (void*)0 to the integral type.
1035 if (Self.Context.getTypeSize(SrcType) >
1036 Self.Context.getTypeSize(DestType)) {
1037 msg = diag::err_bad_reinterpret_cast_small_int;
1038 return TC_Failed;
1039 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +00001040 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001041 return TC_Success;
1042 }
1043
Anders Carlsson570af5d2009-09-16 19:19:43 +00001044 bool destIsVector = DestType->isVectorType();
1045 bool srcIsVector = SrcType->isVectorType();
1046 if (srcIsVector || destIsVector) {
1047 bool srcIsScalar = SrcType->isIntegralType() && !SrcType->isEnumeralType();
1048 bool destIsScalar =
1049 DestType->isIntegralType() && !DestType->isEnumeralType();
1050
1051 // Check if this is a cast between a vector and something else.
1052 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1053 !(srcIsVector && destIsVector))
1054 return TC_NotApplicable;
1055
1056 // If both types have the same size, we can successfully cast.
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001057 if (Self.Context.getTypeSize(SrcType)
1058 == Self.Context.getTypeSize(DestType)) {
1059 Kind = CastExpr::CK_BitCast;
Anders Carlsson570af5d2009-09-16 19:19:43 +00001060 return TC_Success;
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001061 }
Anders Carlsson570af5d2009-09-16 19:19:43 +00001062
1063 if (destIsScalar)
1064 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1065 else if (srcIsScalar)
1066 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1067 else
1068 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1069
1070 return TC_Failed;
1071 }
1072
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001073 bool destIsPtr =
1074 CStyle? DestType->isAnyPointerType() : DestType->isPointerType();
1075 bool srcIsPtr =
1076 CStyle ? SrcType->isAnyPointerType() : SrcType->isPointerType();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001077 if (!destIsPtr && !srcIsPtr) {
1078 // Except for std::nullptr_t->integer and lvalue->reference, which are
1079 // handled above, at least one of the two arguments must be a pointer.
1080 return TC_NotApplicable;
1081 }
1082
1083 if (SrcType == DestType) {
1084 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1085 // restrictions, a cast to the same type is allowed. The intent is not
1086 // entirely clear here, since all other paragraphs explicitly forbid casts
1087 // to the same type. However, the behavior of compilers is pretty consistent
1088 // on this point: allow same-type conversion if the involved types are
1089 // pointers, disallow otherwise.
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001090 Kind = CastExpr::CK_NoOp;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001091 return TC_Success;
1092 }
1093
1094 // Note: Clang treats enumeration types as integral types. If this is ever
1095 // changed for C++, the additional check here will be redundant.
1096 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
1097 assert(srcIsPtr && "One type must be a pointer");
1098 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1099 // type large enough to hold it.
1100 if (Self.Context.getTypeSize(SrcType) >
1101 Self.Context.getTypeSize(DestType)) {
1102 msg = diag::err_bad_reinterpret_cast_small_int;
1103 return TC_Failed;
1104 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +00001105 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001106 return TC_Success;
1107 }
1108
1109 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
1110 assert(destIsPtr && "One type must be a pointer");
1111 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1112 // converted to a pointer.
Anders Carlsson7cd39e02009-09-15 04:48:33 +00001113 Kind = CastExpr::CK_IntegralToPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001114 return TC_Success;
1115 }
1116
1117 if (!destIsPtr || !srcIsPtr) {
1118 // With the valid non-pointer conversions out of the way, we can be even
1119 // more stringent.
1120 return TC_NotApplicable;
1121 }
1122
1123 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1124 // The C-style cast operator can.
1125 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1126 msg = diag::err_bad_cxx_cast_const_away;
1127 return TC_Failed;
1128 }
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001129 if (CStyle && DestType->isObjCObjectPointerType()) {
1130 Kind = CastExpr::CK_AnyPointerToObjCPointerCast;
1131 return TC_Success;
1132 }
1133
Sebastian Redl9f831db2009-07-25 15:41:38 +00001134 // Not casting away constness, so the only remaining check is for compatible
1135 // pointer categories.
Anders Carlsson9500ad12009-10-18 20:31:03 +00001136 Kind = CastExpr::CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001137
1138 if (SrcType->isFunctionPointerType()) {
1139 if (DestType->isFunctionPointerType()) {
1140 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1141 // a pointer to a function of a different type.
1142 return TC_Success;
1143 }
1144
1145 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1146 // an object type or vice versa is conditionally-supported.
1147 // Compilers support it in C++03 too, though, because it's necessary for
1148 // casting the return value of dlsym() and GetProcAddress().
1149 // FIXME: Conditionally-supported behavior should be configurable in the
1150 // TargetInfo or similar.
1151 if (!Self.getLangOptions().CPlusPlus0x)
1152 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1153 return TC_Success;
1154 }
1155
1156 if (DestType->isFunctionPointerType()) {
1157 // See above.
1158 if (!Self.getLangOptions().CPlusPlus0x)
1159 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1160 return TC_Success;
1161 }
1162
1163 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1164 // a pointer to an object of different type.
1165 // Void pointers are not specified, but supported by every compiler out there.
1166 // So we finish by allowing everything that remains - it's got to be two
1167 // object pointers.
1168 return TC_Success;
1169}
1170
Sebastian Redl955a0672009-07-29 13:50:23 +00001171bool Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00001172 CastExpr::CastKind &Kind, bool FunctionalStyle,
Mike Stump11289f42009-09-09 15:08:12 +00001173 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001174 // This test is outside everything else because it's the only case where
1175 // a non-lvalue-reference target type does not lead to decay.
1176 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Anders Carlsson9500ad12009-10-18 20:31:03 +00001177 if (CastTy->isVoidType()) {
1178 Kind = CastExpr::CK_ToVoid;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001179 return false;
Anders Carlsson9500ad12009-10-18 20:31:03 +00001180 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001181
1182 // If the type is dependent, we won't do any other semantic analysis now.
1183 if (CastTy->isDependentType() || CastExpr->isTypeDependent())
1184 return false;
1185
Douglas Gregorad8b2222009-11-06 01:14:41 +00001186 if (!CastTy->isLValueReferenceType() && !CastTy->isRecordType())
Sebastian Redl9f831db2009-07-25 15:41:38 +00001187 DefaultFunctionArrayConversion(CastExpr);
1188
1189 // C++ [expr.cast]p5: The conversions performed by
1190 // - a const_cast,
1191 // - a static_cast,
1192 // - a static_cast followed by a const_cast,
1193 // - a reinterpret_cast, or
1194 // - a reinterpret_cast followed by a const_cast,
1195 // can be performed using the cast notation of explicit type conversion.
1196 // [...] If a conversion can be interpreted in more than one of the ways
1197 // listed above, the interpretation that appears first in the list is used,
1198 // even if a cast resulting from that interpretation is ill-formed.
1199 // In plain language, this means trying a const_cast ...
1200 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssonf1ae6d42009-09-01 20:52:42 +00001201 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1202 msg);
Anders Carlsson027732b2009-10-19 18:14:28 +00001203 if (tcr == TC_Success)
1204 Kind = CastExpr::CK_NoOp;
1205
Sebastian Redl9f831db2009-07-25 15:41:38 +00001206 if (tcr == TC_NotApplicable) {
1207 // ... or if that is not possible, a static_cast, ignoring const, ...
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001208 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1209 Kind, ConversionDecl);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001210 if (tcr == TC_NotApplicable) {
1211 // ... and finally a reinterpret_cast, ignoring const.
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001212 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1213 Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001214 }
1215 }
1216
Sebastian Redl9f831db2009-07-25 15:41:38 +00001217 if (tcr != TC_Success && msg != 0)
Sebastian Redl955a0672009-07-29 13:50:23 +00001218 Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
Sebastian Redl9f831db2009-07-25 15:41:38 +00001219 << CastExpr->getType() << CastTy << R;
1220
1221 return tcr != TC_Success;
1222}