blob: a62effa4a713894209b133567c1aea5ccfecbc43 [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 Carlssona70cff62010-04-24 19:06:50 +000049 CastExpr::CastKind &Kind,
50 CXXBaseSpecifierArray &BasePath);
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 Carlssona70cff62010-04-24 19:06:50 +000054 CastExpr::CastKind &Kind,
55 CXXBaseSpecifierArray &BasePath);
Sebastian Redl842ef522008-11-08 13:00:26 +000056
57static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
Sebastian Redl9f831db2009-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,
73 QualType DestType, bool CStyle,
74 const SourceRange &OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +000075 unsigned &msg,
76 CastExpr::CastKind &Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +000077static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
78 QualType DestType, bool CStyle,
79 const SourceRange &OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +000080 unsigned &msg,
81 CastExpr::CastKind &Kind);
Douglas Gregor8f3952c2009-11-15 09:20:52 +000082static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
83 CanQualType DestType, bool CStyle,
Sebastian Redl9f831db2009-07-25 15:41:38 +000084 const SourceRange &OpRange,
85 QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +000086 QualType OrigDestType, unsigned &msg,
87 CastExpr::CastKind &Kind);
Douglas Gregorc934bc82010-03-07 23:24:59 +000088static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr,
89 QualType SrcType,
Sebastian Redl9f831db2009-07-25 15:41:38 +000090 QualType DestType,bool CStyle,
91 const SourceRange &OpRange,
Anders Carlsson3f0db2b2009-10-30 00:46:35 +000092 unsigned &msg,
93 CastExpr::CastKind &Kind);
Sebastian Redl7c353682009-11-14 21:15:49 +000094static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +000095 QualType DestType, bool CStyle,
96 const SourceRange &OpRange,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +000097 unsigned &msg,
Douglas Gregorb33eed02010-04-16 22:09:46 +000098 CastExpr::CastKind &Kind);
Sebastian Redl7c353682009-11-14 21:15:49 +000099static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000100 QualType DestType, bool CStyle,
101 const SourceRange &OpRange,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000102 unsigned &msg,
Anders Carlssona70cff62010-04-24 19:06:50 +0000103 CastExpr::CastKind &Kind,
104 CXXBaseSpecifierArray &BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000105static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
106 bool CStyle, unsigned &msg);
107static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
108 QualType DestType, bool CStyle,
109 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000110 unsigned &msg,
111 CastExpr::CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +0000112
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000113/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000114Action::OwningExprResult
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000115Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
116 SourceLocation LAngleBracketLoc, TypeTy *Ty,
117 SourceLocation RAngleBracketLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000118 SourceLocation LParenLoc, ExprArg E,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000119 SourceLocation RParenLoc) {
John McCalld377e042010-01-15 19:13:16 +0000120
John McCall97513962010-01-15 18:39:57 +0000121 TypeSourceInfo *DestTInfo;
122 QualType DestType = GetTypeFromParser(Ty, &DestTInfo);
123 if (!DestTInfo)
124 DestTInfo = Context.getTrivialTypeSourceInfo(DestType, SourceLocation());
John McCalld377e042010-01-15 19:13:16 +0000125
126 return BuildCXXNamedCast(OpLoc, Kind, DestTInfo, move(E),
127 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
128 SourceRange(LParenLoc, RParenLoc));
129}
130
131Action::OwningExprResult
132Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
133 TypeSourceInfo *DestTInfo, ExprArg E,
134 SourceRange AngleBrackets, SourceRange Parens) {
135 Expr *Ex = E.takeAs<Expr>();
136 QualType DestType = DestTInfo->getType();
137
138 SourceRange OpRange(OpLoc, Parens.getEnd());
139 SourceRange DestRange = AngleBrackets;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000140
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000141 // If the type is dependent, we won't do the semantic analysis now.
142 // FIXME: should we check this in a more fine-grained manner?
143 bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
144
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000145 switch (Kind) {
146 default: assert(0 && "Unknown C++ cast!");
147
148 case tok::kw_const_cast:
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000149 if (!TypeDependent)
150 CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000151 return Owned(new (Context) CXXConstCastExpr(DestType.getNonReferenceType(),
John McCall97513962010-01-15 18:39:57 +0000152 Ex, DestTInfo, OpLoc));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000153
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000154 case tok::kw_dynamic_cast: {
155 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson5d270e82010-04-24 18:38:56 +0000156 CXXBaseSpecifierArray BasePath;
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000157 if (!TypeDependent)
Anders Carlssona70cff62010-04-24 19:06:50 +0000158 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange, Kind, BasePath);
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000159 return Owned(new (Context)CXXDynamicCastExpr(DestType.getNonReferenceType(),
Anders Carlsson5d270e82010-04-24 18:38:56 +0000160 Kind, Ex, BasePath, DestTInfo,
161 OpLoc));
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000162 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000163 case tok::kw_reinterpret_cast: {
164 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000165 if (!TypeDependent)
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000166 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000167 return Owned(new (Context) CXXReinterpretCastExpr(
168 DestType.getNonReferenceType(),
Anders Carlssona70cff62010-04-24 19:06:50 +0000169 Kind, Ex, CXXBaseSpecifierArray(),
170 DestTInfo, OpLoc));
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000171 }
Anders Carlssonf10e4142009-08-07 22:21:05 +0000172 case tok::kw_static_cast: {
173 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlsson5d270e82010-04-24 18:38:56 +0000174 CXXBaseSpecifierArray BasePath;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000175 if (!TypeDependent)
Anders Carlssona70cff62010-04-24 19:06:50 +0000176 CheckStaticCast(*this, Ex, DestType, OpRange, Kind, BasePath);
Anders Carlssone9766d52009-09-09 21:33:21 +0000177
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000178 return Owned(new (Context) CXXStaticCastExpr(DestType.getNonReferenceType(),
Anders Carlsson5d270e82010-04-24 18:38:56 +0000179 Kind, Ex, BasePath,
180 DestTInfo, OpLoc));
Anders Carlssonf10e4142009-08-07 22:21:05 +0000181 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000182 }
183
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000184 return ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000185}
186
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000187/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
188/// this removes one level of indirection from both types, provided that they're
189/// the same kind of pointer (plain or to-member). Unlike the Sema function,
190/// this one doesn't care if the two pointers-to-member don't point into the
191/// same class. This is because CastsAwayConstness doesn't care.
192bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
193 const PointerType *T1PtrType = T1->getAs<PointerType>(),
194 *T2PtrType = T2->getAs<PointerType>();
195 if (T1PtrType && T2PtrType) {
196 T1 = T1PtrType->getPointeeType();
197 T2 = T2PtrType->getPointeeType();
198 return true;
199 }
Fariborz Jahanian8c3f06d2010-02-03 20:32:31 +0000200 const ObjCObjectPointerType *T1ObjCPtrType =
201 T1->getAs<ObjCObjectPointerType>(),
202 *T2ObjCPtrType =
203 T2->getAs<ObjCObjectPointerType>();
204 if (T1ObjCPtrType) {
205 if (T2ObjCPtrType) {
206 T1 = T1ObjCPtrType->getPointeeType();
207 T2 = T2ObjCPtrType->getPointeeType();
208 return true;
209 }
210 else if (T2PtrType) {
211 T1 = T1ObjCPtrType->getPointeeType();
212 T2 = T2PtrType->getPointeeType();
213 return true;
214 }
215 }
216 else if (T2ObjCPtrType) {
217 if (T1PtrType) {
218 T2 = T2ObjCPtrType->getPointeeType();
219 T1 = T1PtrType->getPointeeType();
220 return true;
221 }
222 }
223
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000224 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
225 *T2MPType = T2->getAs<MemberPointerType>();
226 if (T1MPType && T2MPType) {
227 T1 = T1MPType->getPointeeType();
228 T2 = T2MPType->getPointeeType();
229 return true;
230 }
231 return false;
232}
233
Sebastian Redla5a77a62009-01-27 23:18:31 +0000234/// CastsAwayConstness - Check if the pointer conversion from SrcType to
235/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
236/// the cast checkers. Both arguments must denote pointer (possibly to member)
237/// types.
Sebastian Redl802f14c2009-10-22 15:07:22 +0000238static bool
Mike Stump11289f42009-09-09 15:08:12 +0000239CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
Sebastian Redla5a77a62009-01-27 23:18:31 +0000240 // Casting away constness is defined in C++ 5.2.11p8 with reference to
241 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
242 // the rules are non-trivial. So first we construct Tcv *...cv* as described
243 // in C++ 5.2.11p8.
Fariborz Jahanian8c3f06d2010-02-03 20:32:31 +0000244 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000245 "Source type is not pointer or pointer to member.");
Fariborz Jahanian8c3f06d2010-02-03 20:32:31 +0000246 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000247 "Destination type is not pointer or pointer to member.");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000248
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000249 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
250 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
John McCall8ccfcb52009-09-24 19:53:00 +0000251 llvm::SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000252
253 // Find the qualifications.
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000254 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCall8ccfcb52009-09-24 19:53:00 +0000255 cv1.push_back(UnwrappedSrcType.getQualifiers());
256 cv2.push_back(UnwrappedDestType.getQualifiers());
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000257 }
258 assert(cv1.size() > 0 && "Must have at least one pointer level.");
259
260 // Construct void pointers with those qualifiers (in reverse order of
261 // unwrapping, of course).
Sebastian Redl842ef522008-11-08 13:00:26 +0000262 QualType SrcConstruct = Self.Context.VoidTy;
263 QualType DestConstruct = Self.Context.VoidTy;
John McCall8ccfcb52009-09-24 19:53:00 +0000264 ASTContext &Context = Self.Context;
265 for (llvm::SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
266 i2 = cv2.rbegin();
Mike Stump11289f42009-09-09 15:08:12 +0000267 i1 != cv1.rend(); ++i1, ++i2) {
John McCall8ccfcb52009-09-24 19:53:00 +0000268 SrcConstruct
269 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
270 DestConstruct
271 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000272 }
273
274 // Test if they're compatible.
275 return SrcConstruct != DestConstruct &&
Sebastian Redl842ef522008-11-08 13:00:26 +0000276 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000277}
278
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000279/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
280/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
281/// checked downcasts in class hierarchies.
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000282static void
Sebastian Redl842ef522008-11-08 13:00:26 +0000283CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
284 const SourceRange &OpRange,
Anders Carlssona70cff62010-04-24 19:06:50 +0000285 const SourceRange &DestRange, CastExpr::CastKind &Kind,
286 CXXBaseSpecifierArray &BasePath) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000287 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl842ef522008-11-08 13:00:26 +0000288 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000289
290 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
291 // or "pointer to cv void".
292
293 QualType DestPointee;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000294 const PointerType *DestPointer = DestType->getAs<PointerType>();
295 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000296 if (DestPointer) {
297 DestPointee = DestPointer->getPointeeType();
298 } else if (DestReference) {
299 DestPointee = DestReference->getPointeeType();
300 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000301 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000302 << OrigDestType << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000303 return;
304 }
305
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000306 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000307 if (DestPointee->isVoidType()) {
308 assert(DestPointer && "Reference to void is not possible");
309 } else if (DestRecord) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000310 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor89336232010-03-29 23:34:08 +0000311 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssond624e162009-08-26 23:45:07 +0000312 << DestRange))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000313 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000314 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000315 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000316 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000317 return;
318 }
319
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000320 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
321 // complete class type, [...]. If T is an lvalue reference type, v shall be
322 // an lvalue of a complete class type, [...]. If T is an rvalue reference
323 // type, v shall be an expression having a complete effective class type,
324 // [...]
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000325
Sebastian Redl842ef522008-11-08 13:00:26 +0000326 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000327 QualType SrcPointee;
328 if (DestPointer) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000329 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000330 SrcPointee = SrcPointer->getPointeeType();
331 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000332 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000333 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000334 return;
335 }
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000336 } else if (DestReference->isLValueReferenceType()) {
Sebastian Redl842ef522008-11-08 13:00:26 +0000337 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000338 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000339 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000340 }
341 SrcPointee = SrcType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000342 } else {
343 SrcPointee = SrcType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000344 }
345
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000346 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000347 if (SrcRecord) {
Douglas Gregored0cfbd2009-03-09 16:13:40 +0000348 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor89336232010-03-29 23:34:08 +0000349 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssond624e162009-08-26 23:45:07 +0000350 << SrcExpr->getSourceRange()))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000351 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000352 } else {
Chris Lattner29e812b2008-11-20 06:06:08 +0000353 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000354 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000355 return;
356 }
357
358 assert((DestPointer || DestReference) &&
359 "Bad destination non-ptr/ref slipped through.");
360 assert((DestRecord || DestPointee->isVoidType()) &&
361 "Bad destination pointee slipped through.");
362 assert(SrcRecord && "Bad source pointee slipped through.");
363
364 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
365 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000366 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000367 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000368 return;
369 }
370
371 // C++ 5.2.7p3: If the type of v is the same as the required result type,
372 // [except for cv].
373 if (DestRecord == SrcRecord) {
374 return;
375 }
376
377 // C++ 5.2.7p5
378 // Upcasts are resolved statically.
Sebastian Redl842ef522008-11-08 13:00:26 +0000379 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000380 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
381 OpRange.getBegin(), OpRange,
382 &BasePath))
383 return;
384
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000385 Kind = CastExpr::CK_DerivedToBase;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000386 return;
387 }
388
389 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000390 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000391 assert(SrcDecl && "Definition missing");
392 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner29e812b2008-11-20 06:06:08 +0000393 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000394 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000395 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000396
397 // Done. Everything else is run-time checks.
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000398 Kind = CastExpr::CK_Dynamic;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000399}
Sebastian Redl9f831db2009-07-25 15:41:38 +0000400
401/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
402/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
403/// like this:
404/// const char *str = "literal";
405/// legacy_function(const_cast\<char*\>(str));
406void
407CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +0000408 const SourceRange &OpRange, const SourceRange &DestRange) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000409 if (!DestType->isLValueReferenceType())
Douglas Gregorb92a1562010-02-03 00:27:59 +0000410 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000411
412 unsigned msg = diag::err_bad_cxx_cast_generic;
413 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
414 && msg != 0)
415 Self.Diag(OpRange.getBegin(), msg) << CT_Const
416 << SrcExpr->getType() << DestType << OpRange;
417}
418
419/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
420/// valid.
421/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
422/// like this:
423/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
424void
425CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000426 const SourceRange &OpRange, const SourceRange &DestRange,
427 CastExpr::CastKind &Kind) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000428 if (!DestType->isLValueReferenceType())
Douglas Gregorb92a1562010-02-03 00:27:59 +0000429 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000430
431 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000432 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
433 msg, Kind)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000434 != TC_Success && msg != 0)
435 Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
436 << SrcExpr->getType() << DestType << OpRange;
437}
438
439
440/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
441/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
442/// implicit conversions explicit and getting rid of data loss warnings.
443void
444CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlssona70cff62010-04-24 19:06:50 +0000445 const SourceRange &OpRange, CastExpr::CastKind &Kind,
446 CXXBaseSpecifierArray &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000447 // This test is outside everything else because it's the only case where
448 // a non-lvalue-reference target type does not lead to decay.
449 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman03bf60a2009-11-16 05:44:20 +0000450 if (DestType->isVoidType()) {
451 Kind = CastExpr::CK_ToVoid;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000452 return;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000453 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000454
Douglas Gregorad8b2222009-11-06 01:14:41 +0000455 if (!DestType->isLValueReferenceType() && !DestType->isRecordType())
Douglas Gregorb92a1562010-02-03 00:27:59 +0000456 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000457
458 unsigned msg = diag::err_bad_cxx_cast_generic;
Sebastian Redl7c353682009-11-14 21:15:49 +0000459 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg,
Anders Carlssona70cff62010-04-24 19:06:50 +0000460 Kind, BasePath) != TC_Success && msg != 0)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000461 Self.Diag(OpRange.getBegin(), msg) << CT_Static
462 << SrcExpr->getType() << DestType << OpRange;
463}
464
465/// TryStaticCast - Check if a static cast can be performed, and do so if
466/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
467/// and casting away constness.
Sebastian Redl7c353682009-11-14 21:15:49 +0000468static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000469 QualType DestType, bool CStyle,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000470 const SourceRange &OpRange, unsigned &msg,
Anders Carlssona70cff62010-04-24 19:06:50 +0000471 CastExpr::CastKind &Kind,
472 CXXBaseSpecifierArray &BasePath) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000473 // The order the tests is not entirely arbitrary. There is one conversion
474 // that can be handled in two different ways. Given:
475 // struct A {};
476 // struct B : public A {
477 // B(); B(const A&);
478 // };
479 // const A &a = B();
480 // the cast static_cast<const B&>(a) could be seen as either a static
481 // reference downcast, or an explicit invocation of the user-defined
482 // conversion using B's conversion constructor.
483 // DR 427 specifies that the downcast is to be applied here.
484
485 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
486 // Done outside this function.
487
488 TryCastResult tcr;
489
490 // C++ 5.2.9p5, reference downcast.
491 // See the function for details.
492 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redl7c353682009-11-14 21:15:49 +0000493 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle, OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000494 msg, Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000495 if (tcr != TC_NotApplicable)
496 return tcr;
497
498 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
499 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
500 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
Sebastian Redl7c353682009-11-14 21:15:49 +0000501 if (tcr != TC_NotApplicable) {
502 Kind = CastExpr::CK_NoOp;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000503 return tcr;
Sebastian Redl7c353682009-11-14 21:15:49 +0000504 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000505
506 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
507 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000508 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
Douglas Gregorb33eed02010-04-16 22:09:46 +0000509 Kind);
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000510 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000511 return tcr;
Anders Carlssone9766d52009-09-09 21:33:21 +0000512
Sebastian Redl9f831db2009-07-25 15:41:38 +0000513 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
514 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
515 // conversions, subject to further restrictions.
516 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
517 // of qualification conversions impossible.
518 // In the CStyle case, the earlier attempt to const_cast should have taken
519 // care of reverse qualification conversions.
520
521 QualType OrigSrcType = SrcExpr->getType();
522
523 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
524
525 // Reverse integral promotion/conversion. All such conversions are themselves
526 // again integral promotions or conversions and are thus already handled by
527 // p2 (TryDirectInitialization above).
528 // (Note: any data loss warnings should be suppressed.)
529 // The exception is the reverse of enum->integer, i.e. integer->enum (and
530 // enum->enum). See also C++ 5.2.9p7.
531 // The same goes for reverse floating point promotion/conversion and
532 // floating-integral conversions. Again, only floating->enum is relevant.
533 if (DestType->isEnumeralType()) {
534 if (SrcType->isComplexType() || SrcType->isVectorType()) {
535 // Fall through - these cannot be converted.
Eli Friedman03bf60a2009-11-16 05:44:20 +0000536 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
537 Kind = CastExpr::CK_IntegralCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000538 return TC_Success;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000539 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000540 }
541
542 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
543 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000544 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
545 Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000546 if (tcr != TC_NotApplicable)
547 return tcr;
548
549 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
550 // conversion. C++ 5.2.9p9 has additional information.
551 // DR54's access restrictions apply here also.
Douglas Gregorc934bc82010-03-07 23:24:59 +0000552 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlsson3f0db2b2009-10-30 00:46:35 +0000553 OpRange, msg, Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000554 if (tcr != TC_NotApplicable)
555 return tcr;
556
557 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
558 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
559 // just the usual constness stuff.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000560 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000561 QualType SrcPointee = SrcPointer->getPointeeType();
562 if (SrcPointee->isVoidType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000563 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000564 QualType DestPointee = DestPointer->getPointeeType();
565 if (DestPointee->isIncompleteOrObjectType()) {
566 // This is definitely the intended conversion, but it might fail due
567 // to a const violation.
568 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
569 msg = diag::err_bad_cxx_cast_const_away;
570 return TC_Failed;
571 }
Eli Friedman03bf60a2009-11-16 05:44:20 +0000572 Kind = CastExpr::CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000573 return TC_Success;
574 }
575 }
Fariborz Jahanian859c4152009-12-08 23:09:15 +0000576 else if (CStyle && DestType->isObjCObjectPointerType()) {
577 // allow c-style cast of objective-c pointers as they are pervasive.
578 Kind = CastExpr::CK_AnyPointerToObjCPointerCast;
579 return TC_Success;
580 }
Fariborz Jahanianffe912c2009-12-11 22:40:48 +0000581 else if (CStyle && DestType->isBlockPointerType()) {
582 // allow c-style cast of void * to block pointers.
583 Kind = CastExpr::CK_AnyPointerToBlockPointerCast;
584 return TC_Success;
585 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000586 }
587 }
588
589 // We tried everything. Everything! Nothing works! :-(
590 return TC_NotApplicable;
591}
592
593/// Tests whether a conversion according to N2844 is valid.
594TryCastResult
595TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +0000596 unsigned &msg) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000597 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
598 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000599 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000600 if (!R)
601 return TC_NotApplicable;
602
603 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
604 return TC_NotApplicable;
605
606 // Because we try the reference downcast before this function, from now on
607 // this is the only cast possibility, so we issue an error if we fail now.
608 // FIXME: Should allow casting away constness if CStyle.
609 bool DerivedToBase;
Douglas Gregor3ec1bf22009-11-05 13:06:35 +0000610 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
611 SrcExpr->getType(), R->getPointeeType(),
Sebastian Redl9f831db2009-07-25 15:41:38 +0000612 DerivedToBase) <
613 Sema::Ref_Compatible_With_Added_Qualification) {
614 msg = diag::err_bad_lvalue_to_rvalue_cast;
615 return TC_Failed;
616 }
617
Douglas Gregor031296e2010-03-25 00:20:38 +0000618 // FIXME: We should probably have an AST node for lvalue-to-rvalue
619 // conversions.
Sebastian Redl9f831db2009-07-25 15:41:38 +0000620 return TC_Success;
621}
622
623/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
624TryCastResult
625TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
626 bool CStyle, const SourceRange &OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000627 unsigned &msg, CastExpr::CastKind &Kind) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000628 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
629 // cast to type "reference to cv2 D", where D is a class derived from B,
630 // if a valid standard conversion from "pointer to D" to "pointer to B"
631 // exists, cv2 >= cv1, and B is not a virtual base class of D.
632 // In addition, DR54 clarifies that the base must be accessible in the
633 // current context. Although the wording of DR54 only applies to the pointer
634 // variant of this rule, the intent is clearly for it to apply to the this
635 // conversion as well.
636
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000637 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000638 if (!DestReference) {
639 return TC_NotApplicable;
640 }
641 bool RValueRef = DestReference->isRValueReferenceType();
642 if (!RValueRef && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
643 // We know the left side is an lvalue reference, so we can suggest a reason.
644 msg = diag::err_bad_cxx_cast_rvalue;
645 return TC_NotApplicable;
646 }
647
648 QualType DestPointee = DestReference->getPointeeType();
649
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000650 return TryStaticDowncast(Self,
651 Self.Context.getCanonicalType(SrcExpr->getType()),
652 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000653 OpRange, SrcExpr->getType(), DestType, msg, Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000654}
655
656/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
657TryCastResult
658TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +0000659 bool CStyle, const SourceRange &OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000660 unsigned &msg, CastExpr::CastKind &Kind) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000661 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
662 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
663 // is a class derived from B, if a valid standard conversion from "pointer
664 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
665 // class of D.
666 // In addition, DR54 clarifies that the base must be accessible in the
667 // current context.
668
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000669 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000670 if (!DestPointer) {
671 return TC_NotApplicable;
672 }
673
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000674 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000675 if (!SrcPointer) {
676 msg = diag::err_bad_static_cast_pointer_nonpointer;
677 return TC_NotApplicable;
678 }
679
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000680 return TryStaticDowncast(Self,
681 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
682 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
683 CStyle, OpRange, SrcType, DestType, msg, Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000684}
685
686/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
687/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000688/// DestType is possible and allowed.
Sebastian Redl9f831db2009-07-25 15:41:38 +0000689TryCastResult
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000690TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000691 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000692 QualType OrigDestType, unsigned &msg,
693 CastExpr::CastKind &Kind) {
Sebastian Redl802f14c2009-10-22 15:07:22 +0000694 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregor89336232010-03-29 23:34:08 +0000695 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, Self.PDiag(0)) ||
696 Self.RequireCompleteType(OpRange.getBegin(), DestType, Self.PDiag(0)))
Sebastian Redl802f14c2009-10-22 15:07:22 +0000697 return TC_NotApplicable;
698
Sebastian Redl9f831db2009-07-25 15:41:38 +0000699 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000700 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000701 return TC_NotApplicable;
702 }
703
Douglas Gregor36d1b142009-10-06 17:59:45 +0000704 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
705 /*DetectVirtual=*/true);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000706 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
707 return TC_NotApplicable;
708 }
709
710 // Target type does derive from source type. Now we're serious. If an error
711 // appears now, it's not ignored.
712 // This may not be entirely in line with the standard. Take for example:
713 // struct A {};
714 // struct B : virtual A {
715 // B(A&);
716 // };
Mike Stump11289f42009-09-09 15:08:12 +0000717 //
Sebastian Redl9f831db2009-07-25 15:41:38 +0000718 // void f()
719 // {
720 // (void)static_cast<const B&>(*((A*)0));
721 // }
722 // As far as the standard is concerned, p5 does not apply (A is virtual), so
723 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
724 // However, both GCC and Comeau reject this example, and accepting it would
725 // mean more complex code if we're to preserve the nice error message.
726 // FIXME: Being 100% compliant here would be nice to have.
727
728 // Must preserve cv, as always, unless we're in C-style mode.
729 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
730 msg = diag::err_bad_cxx_cast_const_away;
731 return TC_Failed;
732 }
733
734 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
735 // This code is analoguous to that in CheckDerivedToBaseConversion, except
736 // that it builds the paths in reverse order.
737 // To sum up: record all paths to the base and build a nice string from
738 // them. Use it to spice up the error message.
739 if (!Paths.isRecordingPaths()) {
740 Paths.clear();
741 Paths.setRecordingPaths(true);
742 Self.IsDerivedFrom(DestType, SrcType, Paths);
743 }
744 std::string PathDisplayStr;
745 std::set<unsigned> DisplayedPaths;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000746 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000747 PI != PE; ++PI) {
748 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
749 // We haven't displayed a path to this particular base
750 // class subobject yet.
751 PathDisplayStr += "\n ";
Douglas Gregor36d1b142009-10-06 17:59:45 +0000752 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
753 EE = PI->rend();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000754 EI != EE; ++EI)
755 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000756 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000757 }
758 }
759
760 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000761 << QualType(SrcType).getUnqualifiedType()
762 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9f831db2009-07-25 15:41:38 +0000763 << PathDisplayStr << OpRange;
764 msg = 0;
765 return TC_Failed;
766 }
767
768 if (Paths.getDetectedVirtual() != 0) {
769 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
770 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
771 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
772 msg = 0;
773 return TC_Failed;
774 }
775
John McCall5b0829a2010-02-10 09:31:12 +0000776 if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
John McCall5b0829a2010-02-10 09:31:12 +0000777 SrcType, DestType,
John McCall1064d7e2010-03-16 05:22:47 +0000778 Paths.front(),
779 diag::err_downcast_from_inaccessible_base)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000780 msg = 0;
781 return TC_Failed;
782 }
783
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000784 Kind = CastExpr::CK_BaseToDerived;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000785 return TC_Success;
786}
787
788/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
789/// C++ 5.2.9p9 is valid:
790///
791/// An rvalue of type "pointer to member of D of type cv1 T" can be
792/// converted to an rvalue of type "pointer to member of B of type cv2 T",
793/// where B is a base class of D [...].
794///
795TryCastResult
Douglas Gregorc934bc82010-03-07 23:24:59 +0000796TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr, QualType SrcType,
797 QualType DestType, bool CStyle,
798 const SourceRange &OpRange,
Anders Carlsson3f0db2b2009-10-30 00:46:35 +0000799 unsigned &msg, CastExpr::CastKind &Kind) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000800 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000801 if (!DestMemPtr)
802 return TC_NotApplicable;
Douglas Gregorc934bc82010-03-07 23:24:59 +0000803
804 bool WasOverloadedFunction = false;
John McCall16df1e52010-03-30 21:47:33 +0000805 DeclAccessPair FoundOverload;
Douglas Gregor064fdb22010-04-14 23:11:21 +0000806 if (SrcExpr->getType() == Self.Context.OverloadTy) {
807 if (FunctionDecl *Fn
808 = Self.ResolveAddressOfOverloadedFunction(SrcExpr, DestType, false,
809 FoundOverload)) {
810 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
811 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
812 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
813 WasOverloadedFunction = true;
814 }
Douglas Gregorc934bc82010-03-07 23:24:59 +0000815 }
Douglas Gregor064fdb22010-04-14 23:11:21 +0000816
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000817 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000818 if (!SrcMemPtr) {
819 msg = diag::err_bad_static_cast_member_pointer_nonmp;
820 return TC_NotApplicable;
821 }
822
823 // T == T, modulo cv
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000824 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
825 DestMemPtr->getPointeeType()))
Sebastian Redl9f831db2009-07-25 15:41:38 +0000826 return TC_NotApplicable;
827
828 // B base of D
829 QualType SrcClass(SrcMemPtr->getClass(), 0);
830 QualType DestClass(DestMemPtr->getClass(), 0);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000831 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000832 /*DetectVirtual=*/true);
833 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
834 return TC_NotApplicable;
835 }
836
837 // B is a base of D. But is it an allowed base? If not, it's a hard error.
838 if (Paths.isAmbiguous(DestClass)) {
839 Paths.clear();
840 Paths.setRecordingPaths(true);
841 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
842 assert(StillOkay);
843 StillOkay = StillOkay;
844 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
845 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
846 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
847 msg = 0;
848 return TC_Failed;
849 }
850
851 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
852 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
853 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
854 msg = 0;
855 return TC_Failed;
856 }
857
John McCall5b0829a2010-02-10 09:31:12 +0000858 if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
John McCall5b0829a2010-02-10 09:31:12 +0000859 DestType, SrcType,
John McCall1064d7e2010-03-16 05:22:47 +0000860 Paths.front(),
861 diag::err_upcast_to_inaccessible_base)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000862 msg = 0;
863 return TC_Failed;
864 }
865
Douglas Gregorc934bc82010-03-07 23:24:59 +0000866 if (WasOverloadedFunction) {
867 // Resolve the address of the overloaded function again, this time
868 // allowing complaints if something goes wrong.
869 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr,
870 DestType,
John McCall16df1e52010-03-30 21:47:33 +0000871 true,
872 FoundOverload);
Douglas Gregorc934bc82010-03-07 23:24:59 +0000873 if (!Fn) {
874 msg = 0;
875 return TC_Failed;
876 }
877
John McCall16df1e52010-03-30 21:47:33 +0000878 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
Douglas Gregorc934bc82010-03-07 23:24:59 +0000879 if (!SrcExpr) {
880 msg = 0;
881 return TC_Failed;
882 }
883 }
884
Anders Carlsson3f0db2b2009-10-30 00:46:35 +0000885 Kind = CastExpr::CK_DerivedToBaseMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000886 return TC_Success;
887}
888
889/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
890/// is valid:
891///
892/// An expression e can be explicitly converted to a type T using a
893/// @c static_cast if the declaration "T t(e);" is well-formed [...].
894TryCastResult
Sebastian Redl7c353682009-11-14 21:15:49 +0000895TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000896 bool CStyle, const SourceRange &OpRange, unsigned &msg,
Douglas Gregorb33eed02010-04-16 22:09:46 +0000897 CastExpr::CastKind &Kind) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +0000898 if (DestType->isRecordType()) {
899 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
900 diag::err_bad_dynamic_cast_incomplete)) {
901 msg = 0;
902 return TC_Failed;
903 }
904 }
Douglas Gregorb33eed02010-04-16 22:09:46 +0000905
906 // At this point of CheckStaticCast, if the destination is a reference,
907 // this has to work. There is no other way that works.
908 // On the other hand, if we're checking a C-style cast, we've still got
909 // the reinterpret_cast way.
Douglas Gregor5c8ffab2010-04-16 19:30:02 +0000910 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
911 InitializationKind InitKind
Douglas Gregorb33eed02010-04-16 22:09:46 +0000912 = InitializationKind::CreateCast(/*FIXME:*/OpRange,
913 CStyle);
Douglas Gregor5c8ffab2010-04-16 19:30:02 +0000914 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExpr, 1);
Douglas Gregorb33eed02010-04-16 22:09:46 +0000915 if (InitSeq.getKind() == InitializationSequence::FailedSequence &&
916 (CStyle || !DestType->isReferenceType()))
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000917 return TC_NotApplicable;
Douglas Gregorb33eed02010-04-16 22:09:46 +0000918
Douglas Gregor5c8ffab2010-04-16 19:30:02 +0000919 Sema::OwningExprResult Result
Douglas Gregorb33eed02010-04-16 22:09:46 +0000920 = InitSeq.Perform(Self, Entity, InitKind,
921 Action::MultiExprArg(Self, (void**)&SrcExpr, 1));
Douglas Gregor5c8ffab2010-04-16 19:30:02 +0000922 if (Result.isInvalid()) {
923 msg = 0;
924 return TC_Failed;
925 }
926
Douglas Gregorb33eed02010-04-16 22:09:46 +0000927 if (InitSeq.isConstructorInitialization())
928 Kind = CastExpr::CK_ConstructorConversion;
929 else
930 Kind = CastExpr::CK_NoOp;
931
Douglas Gregor5c8ffab2010-04-16 19:30:02 +0000932 SrcExpr = Result.takeAs<Expr>();
933 return TC_Success;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000934}
935
936/// TryConstCast - See if a const_cast from source to destination is allowed,
937/// and perform it if it is.
938static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
939 bool CStyle, unsigned &msg) {
940 DestType = Self.Context.getCanonicalType(DestType);
941 QualType SrcType = SrcExpr->getType();
942 if (const LValueReferenceType *DestTypeTmp =
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000943 DestType->getAs<LValueReferenceType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000944 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
945 // Cannot const_cast non-lvalue to lvalue reference type. But if this
946 // is C-style, static_cast might find a way, so we simply suggest a
947 // message and tell the parent to keep searching.
948 msg = diag::err_bad_cxx_cast_rvalue;
949 return TC_NotApplicable;
950 }
951
952 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
953 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
954 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
955 SrcType = Self.Context.getPointerType(SrcType);
956 }
957
958 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
959 // the rules for const_cast are the same as those used for pointers.
960
961 if (!DestType->isPointerType() && !DestType->isMemberPointerType()) {
962 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
963 // was a reference type, we converted it to a pointer above.
964 // The status of rvalue references isn't entirely clear, but it looks like
965 // conversion to them is simply invalid.
966 // C++ 5.2.11p3: For two pointer types [...]
967 if (!CStyle)
968 msg = diag::err_bad_const_cast_dest;
969 return TC_NotApplicable;
970 }
971 if (DestType->isFunctionPointerType() ||
972 DestType->isMemberFunctionPointerType()) {
973 // Cannot cast direct function pointers.
974 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
975 // T is the ultimate pointee of source and target type.
976 if (!CStyle)
977 msg = diag::err_bad_const_cast_dest;
978 return TC_NotApplicable;
979 }
980 SrcType = Self.Context.getCanonicalType(SrcType);
981
982 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
983 // completely equal.
984 // FIXME: const_cast should probably not be able to convert between pointers
985 // to different address spaces.
986 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
987 // in multi-level pointers may change, but the level count must be the same,
988 // as must be the final pointee type.
989 while (SrcType != DestType &&
990 Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Chandler Carruth585fb1e2009-12-29 08:05:19 +0000991 Qualifiers Quals;
992 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, Quals);
993 DestType = Self.Context.getUnqualifiedArrayType(DestType, Quals);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000994 }
995
996 // Since we're dealing in canonical types, the remainder must be the same.
997 if (SrcType != DestType)
998 return TC_NotApplicable;
999
1000 return TC_Success;
1001}
1002
1003static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
1004 QualType DestType, bool CStyle,
1005 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001006 unsigned &msg,
1007 CastExpr::CastKind &Kind) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001008 DestType = Self.Context.getCanonicalType(DestType);
1009 QualType SrcType = SrcExpr->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001010 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001011 bool LValue = DestTypeTmp->isLValueReferenceType();
1012 if (LValue && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
1013 // Cannot cast non-lvalue to reference type. See the similar comment in
1014 // const_cast.
1015 msg = diag::err_bad_cxx_cast_rvalue;
1016 return TC_NotApplicable;
1017 }
1018
1019 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1020 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1021 // built-in & and * operators.
1022 // This code does this transformation for the checked types.
1023 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1024 SrcType = Self.Context.getPointerType(SrcType);
1025 }
1026
1027 // Canonicalize source for comparison.
1028 SrcType = Self.Context.getCanonicalType(SrcType);
1029
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001030 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1031 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001032 if (DestMemPtr && SrcMemPtr) {
1033 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1034 // can be explicitly converted to an rvalue of type "pointer to member
1035 // of Y of type T2" if T1 and T2 are both function types or both object
1036 // types.
1037 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1038 SrcMemPtr->getPointeeType()->isFunctionType())
1039 return TC_NotApplicable;
1040
1041 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1042 // constness.
1043 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1044 // we accept it.
1045 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1046 msg = diag::err_bad_cxx_cast_const_away;
1047 return TC_Failed;
1048 }
1049
1050 // A valid member pointer cast.
Anders Carlsson9500ad12009-10-18 20:31:03 +00001051 Kind = CastExpr::CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001052 return TC_Success;
1053 }
1054
1055 // See below for the enumeral issue.
1056 if (SrcType->isNullPtrType() && DestType->isIntegralType() &&
1057 !DestType->isEnumeralType()) {
1058 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1059 // type large enough to hold it. A value of std::nullptr_t can be
1060 // converted to an integral type; the conversion has the same meaning
1061 // and validity as a conversion of (void*)0 to the integral type.
1062 if (Self.Context.getTypeSize(SrcType) >
1063 Self.Context.getTypeSize(DestType)) {
1064 msg = diag::err_bad_reinterpret_cast_small_int;
1065 return TC_Failed;
1066 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +00001067 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001068 return TC_Success;
1069 }
1070
Anders Carlsson570af5d2009-09-16 19:19:43 +00001071 bool destIsVector = DestType->isVectorType();
1072 bool srcIsVector = SrcType->isVectorType();
1073 if (srcIsVector || destIsVector) {
1074 bool srcIsScalar = SrcType->isIntegralType() && !SrcType->isEnumeralType();
1075 bool destIsScalar =
1076 DestType->isIntegralType() && !DestType->isEnumeralType();
1077
1078 // Check if this is a cast between a vector and something else.
1079 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1080 !(srcIsVector && destIsVector))
1081 return TC_NotApplicable;
1082
1083 // If both types have the same size, we can successfully cast.
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001084 if (Self.Context.getTypeSize(SrcType)
1085 == Self.Context.getTypeSize(DestType)) {
1086 Kind = CastExpr::CK_BitCast;
Anders Carlsson570af5d2009-09-16 19:19:43 +00001087 return TC_Success;
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001088 }
Anders Carlsson570af5d2009-09-16 19:19:43 +00001089
1090 if (destIsScalar)
1091 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1092 else if (srcIsScalar)
1093 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1094 else
1095 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1096
1097 return TC_Failed;
1098 }
1099
Fariborz Jahanian8c3f06d2010-02-03 20:32:31 +00001100 bool destIsPtr = DestType->isAnyPointerType();
1101 bool srcIsPtr = SrcType->isAnyPointerType();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001102 if (!destIsPtr && !srcIsPtr) {
1103 // Except for std::nullptr_t->integer and lvalue->reference, which are
1104 // handled above, at least one of the two arguments must be a pointer.
1105 return TC_NotApplicable;
1106 }
1107
1108 if (SrcType == DestType) {
1109 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1110 // restrictions, a cast to the same type is allowed. The intent is not
1111 // entirely clear here, since all other paragraphs explicitly forbid casts
1112 // to the same type. However, the behavior of compilers is pretty consistent
1113 // on this point: allow same-type conversion if the involved types are
1114 // pointers, disallow otherwise.
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001115 Kind = CastExpr::CK_NoOp;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001116 return TC_Success;
1117 }
1118
1119 // Note: Clang treats enumeration types as integral types. If this is ever
1120 // changed for C++, the additional check here will be redundant.
1121 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
1122 assert(srcIsPtr && "One type must be a pointer");
1123 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1124 // type large enough to hold it.
1125 if (Self.Context.getTypeSize(SrcType) >
1126 Self.Context.getTypeSize(DestType)) {
1127 msg = diag::err_bad_reinterpret_cast_small_int;
1128 return TC_Failed;
1129 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +00001130 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001131 return TC_Success;
1132 }
1133
1134 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
1135 assert(destIsPtr && "One type must be a pointer");
1136 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1137 // converted to a pointer.
Anders Carlsson7cd39e02009-09-15 04:48:33 +00001138 Kind = CastExpr::CK_IntegralToPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001139 return TC_Success;
1140 }
1141
1142 if (!destIsPtr || !srcIsPtr) {
1143 // With the valid non-pointer conversions out of the way, we can be even
1144 // more stringent.
1145 return TC_NotApplicable;
1146 }
1147
1148 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1149 // The C-style cast operator can.
1150 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1151 msg = diag::err_bad_cxx_cast_const_away;
1152 return TC_Failed;
1153 }
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001154 if (CStyle && DestType->isObjCObjectPointerType()) {
1155 Kind = CastExpr::CK_AnyPointerToObjCPointerCast;
1156 return TC_Success;
1157 }
1158
Sebastian Redl9f831db2009-07-25 15:41:38 +00001159 // Not casting away constness, so the only remaining check is for compatible
1160 // pointer categories.
Anders Carlsson9500ad12009-10-18 20:31:03 +00001161 Kind = CastExpr::CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001162
1163 if (SrcType->isFunctionPointerType()) {
1164 if (DestType->isFunctionPointerType()) {
1165 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1166 // a pointer to a function of a different type.
1167 return TC_Success;
1168 }
1169
1170 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1171 // an object type or vice versa is conditionally-supported.
1172 // Compilers support it in C++03 too, though, because it's necessary for
1173 // casting the return value of dlsym() and GetProcAddress().
1174 // FIXME: Conditionally-supported behavior should be configurable in the
1175 // TargetInfo or similar.
1176 if (!Self.getLangOptions().CPlusPlus0x)
1177 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1178 return TC_Success;
1179 }
1180
1181 if (DestType->isFunctionPointerType()) {
1182 // See above.
1183 if (!Self.getLangOptions().CPlusPlus0x)
1184 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1185 return TC_Success;
1186 }
1187
1188 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1189 // a pointer to an object of different type.
1190 // Void pointers are not specified, but supported by every compiler out there.
1191 // So we finish by allowing everything that remains - it's got to be two
1192 // object pointers.
1193 return TC_Success;
1194}
1195
Anders Carlssona70cff62010-04-24 19:06:50 +00001196bool
1197Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr,
1198 CastExpr::CastKind &Kind,
1199 CXXBaseSpecifierArray &BasePath,
1200 bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001201 // This test is outside everything else because it's the only case where
1202 // a non-lvalue-reference target type does not lead to decay.
1203 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Anders Carlsson9500ad12009-10-18 20:31:03 +00001204 if (CastTy->isVoidType()) {
1205 Kind = CastExpr::CK_ToVoid;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001206 return false;
Anders Carlsson9500ad12009-10-18 20:31:03 +00001207 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001208
1209 // If the type is dependent, we won't do any other semantic analysis now.
1210 if (CastTy->isDependentType() || CastExpr->isTypeDependent())
1211 return false;
1212
Douglas Gregorad8b2222009-11-06 01:14:41 +00001213 if (!CastTy->isLValueReferenceType() && !CastTy->isRecordType())
Douglas Gregorb92a1562010-02-03 00:27:59 +00001214 DefaultFunctionArrayLvalueConversion(CastExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001215
1216 // C++ [expr.cast]p5: The conversions performed by
1217 // - a const_cast,
1218 // - a static_cast,
1219 // - a static_cast followed by a const_cast,
1220 // - a reinterpret_cast, or
1221 // - a reinterpret_cast followed by a const_cast,
1222 // can be performed using the cast notation of explicit type conversion.
1223 // [...] If a conversion can be interpreted in more than one of the ways
1224 // listed above, the interpretation that appears first in the list is used,
1225 // even if a cast resulting from that interpretation is ill-formed.
1226 // In plain language, this means trying a const_cast ...
1227 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssonf1ae6d42009-09-01 20:52:42 +00001228 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1229 msg);
Anders Carlsson027732b2009-10-19 18:14:28 +00001230 if (tcr == TC_Success)
1231 Kind = CastExpr::CK_NoOp;
1232
Sebastian Redl9f831db2009-07-25 15:41:38 +00001233 if (tcr == TC_NotApplicable) {
1234 // ... or if that is not possible, a static_cast, ignoring const, ...
Anders Carlssona70cff62010-04-24 19:06:50 +00001235 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg, Kind,
1236 BasePath);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001237 if (tcr == TC_NotApplicable) {
1238 // ... and finally a reinterpret_cast, ignoring const.
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001239 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1240 Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001241 }
1242 }
1243
Sebastian Redl9f831db2009-07-25 15:41:38 +00001244 if (tcr != TC_Success && msg != 0)
Sebastian Redl955a0672009-07-29 13:50:23 +00001245 Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
Sebastian Redl9f831db2009-07-25 15:41:38 +00001246 << CastExpr->getType() << CastTy << R;
1247
1248 return tcr != TC_Success;
1249}