blob: 37df2a60005ff69a984058c1f2889591d5c0c37d [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);
Douglas Gregorc934bc82010-03-07 23:24:59 +000087static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr,
88 QualType SrcType,
Sebastian Redl9f831db2009-07-25 15:41:38 +000089 QualType DestType,bool CStyle,
90 const SourceRange &OpRange,
Anders Carlsson3f0db2b2009-10-30 00:46:35 +000091 unsigned &msg,
92 CastExpr::CastKind &Kind);
Sebastian Redl7c353682009-11-14 21:15:49 +000093static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +000094 QualType DestType, bool CStyle,
95 const SourceRange &OpRange,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +000096 unsigned &msg,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +000097 CastExpr::CastKind &Kind,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +000098 CXXMethodDecl *&ConversionDecl);
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 Carlsson9d1b34b2009-09-26 00:12:34 +0000103 CastExpr::CastKind &Kind,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000104 CXXMethodDecl *&ConversionDecl);
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;
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000156 if (!TypeDependent)
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000157 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000158 return Owned(new (Context)CXXDynamicCastExpr(DestType.getNonReferenceType(),
John McCall97513962010-01-15 18:39:57 +0000159 Kind, Ex, DestTInfo, OpLoc));
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000160 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000161 case tok::kw_reinterpret_cast: {
162 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000163 if (!TypeDependent)
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000164 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000165 return Owned(new (Context) CXXReinterpretCastExpr(
166 DestType.getNonReferenceType(),
John McCall97513962010-01-15 18:39:57 +0000167 Kind, Ex, DestTInfo, OpLoc));
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000168 }
Anders Carlssonf10e4142009-08-07 22:21:05 +0000169 case tok::kw_static_cast: {
170 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlssone9766d52009-09-09 21:33:21 +0000171 if (!TypeDependent) {
172 CXXMethodDecl *Method = 0;
173
174 CheckStaticCast(*this, Ex, DestType, OpRange, Kind, Method);
175
176 if (Method) {
177 OwningExprResult CastArg
178 = BuildCXXCastArgument(OpLoc, DestType.getNonReferenceType(),
179 Kind, Method, Owned(Ex));
180 if (CastArg.isInvalid())
181 return ExprError();
182
183 Ex = CastArg.takeAs<Expr>();
184 }
185 }
186
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000187 return Owned(new (Context) CXXStaticCastExpr(DestType.getNonReferenceType(),
John McCall97513962010-01-15 18:39:57 +0000188 Kind, Ex, DestTInfo, OpLoc));
Anders Carlssonf10e4142009-08-07 22:21:05 +0000189 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000190 }
191
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000192 return ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000193}
194
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000195/// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
196/// this removes one level of indirection from both types, provided that they're
197/// the same kind of pointer (plain or to-member). Unlike the Sema function,
198/// this one doesn't care if the two pointers-to-member don't point into the
199/// same class. This is because CastsAwayConstness doesn't care.
200bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
201 const PointerType *T1PtrType = T1->getAs<PointerType>(),
202 *T2PtrType = T2->getAs<PointerType>();
203 if (T1PtrType && T2PtrType) {
204 T1 = T1PtrType->getPointeeType();
205 T2 = T2PtrType->getPointeeType();
206 return true;
207 }
Fariborz Jahanian8c3f06d2010-02-03 20:32:31 +0000208 const ObjCObjectPointerType *T1ObjCPtrType =
209 T1->getAs<ObjCObjectPointerType>(),
210 *T2ObjCPtrType =
211 T2->getAs<ObjCObjectPointerType>();
212 if (T1ObjCPtrType) {
213 if (T2ObjCPtrType) {
214 T1 = T1ObjCPtrType->getPointeeType();
215 T2 = T2ObjCPtrType->getPointeeType();
216 return true;
217 }
218 else if (T2PtrType) {
219 T1 = T1ObjCPtrType->getPointeeType();
220 T2 = T2PtrType->getPointeeType();
221 return true;
222 }
223 }
224 else if (T2ObjCPtrType) {
225 if (T1PtrType) {
226 T2 = T2ObjCPtrType->getPointeeType();
227 T1 = T1PtrType->getPointeeType();
228 return true;
229 }
230 }
231
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000232 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
233 *T2MPType = T2->getAs<MemberPointerType>();
234 if (T1MPType && T2MPType) {
235 T1 = T1MPType->getPointeeType();
236 T2 = T2MPType->getPointeeType();
237 return true;
238 }
239 return false;
240}
241
Sebastian Redla5a77a62009-01-27 23:18:31 +0000242/// CastsAwayConstness - Check if the pointer conversion from SrcType to
243/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
244/// the cast checkers. Both arguments must denote pointer (possibly to member)
245/// types.
Sebastian Redl802f14c2009-10-22 15:07:22 +0000246static bool
Mike Stump11289f42009-09-09 15:08:12 +0000247CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
Sebastian Redla5a77a62009-01-27 23:18:31 +0000248 // Casting away constness is defined in C++ 5.2.11p8 with reference to
249 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
250 // the rules are non-trivial. So first we construct Tcv *...cv* as described
251 // in C++ 5.2.11p8.
Fariborz Jahanian8c3f06d2010-02-03 20:32:31 +0000252 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000253 "Source type is not pointer or pointer to member.");
Fariborz Jahanian8c3f06d2010-02-03 20:32:31 +0000254 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType()) &&
Sebastian Redla5a77a62009-01-27 23:18:31 +0000255 "Destination type is not pointer or pointer to member.");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000256
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000257 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
258 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
John McCall8ccfcb52009-09-24 19:53:00 +0000259 llvm::SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000260
261 // Find the qualifications.
Sebastian Redl55db1ec2009-11-18 18:10:53 +0000262 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCall8ccfcb52009-09-24 19:53:00 +0000263 cv1.push_back(UnwrappedSrcType.getQualifiers());
264 cv2.push_back(UnwrappedDestType.getQualifiers());
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000265 }
266 assert(cv1.size() > 0 && "Must have at least one pointer level.");
267
268 // Construct void pointers with those qualifiers (in reverse order of
269 // unwrapping, of course).
Sebastian Redl842ef522008-11-08 13:00:26 +0000270 QualType SrcConstruct = Self.Context.VoidTy;
271 QualType DestConstruct = Self.Context.VoidTy;
John McCall8ccfcb52009-09-24 19:53:00 +0000272 ASTContext &Context = Self.Context;
273 for (llvm::SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
274 i2 = cv2.rbegin();
Mike Stump11289f42009-09-09 15:08:12 +0000275 i1 != cv1.rend(); ++i1, ++i2) {
John McCall8ccfcb52009-09-24 19:53:00 +0000276 SrcConstruct
277 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
278 DestConstruct
279 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000280 }
281
282 // Test if they're compatible.
283 return SrcConstruct != DestConstruct &&
Sebastian Redl842ef522008-11-08 13:00:26 +0000284 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000285}
286
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000287/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
288/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
289/// checked downcasts in class hierarchies.
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000290static void
Sebastian Redl842ef522008-11-08 13:00:26 +0000291CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
292 const SourceRange &OpRange,
Mike Stump11289f42009-09-09 15:08:12 +0000293 const SourceRange &DestRange, CastExpr::CastKind &Kind) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000294 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl842ef522008-11-08 13:00:26 +0000295 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000296
297 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
298 // or "pointer to cv void".
299
300 QualType DestPointee;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000301 const PointerType *DestPointer = DestType->getAs<PointerType>();
302 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000303 if (DestPointer) {
304 DestPointee = DestPointer->getPointeeType();
305 } else if (DestReference) {
306 DestPointee = DestReference->getPointeeType();
307 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000308 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000309 << OrigDestType << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000310 return;
311 }
312
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000313 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000314 if (DestPointee->isVoidType()) {
315 assert(DestPointer && "Reference to void is not possible");
316 } else if (DestRecord) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000317 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Douglas Gregor89336232010-03-29 23:34:08 +0000318 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssond624e162009-08-26 23:45:07 +0000319 << DestRange))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000320 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000321 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000322 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000323 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000324 return;
325 }
326
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000327 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
328 // complete class type, [...]. If T is an lvalue reference type, v shall be
329 // an lvalue of a complete class type, [...]. If T is an rvalue reference
330 // type, v shall be an expression having a complete effective class type,
331 // [...]
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000332
Sebastian Redl842ef522008-11-08 13:00:26 +0000333 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000334 QualType SrcPointee;
335 if (DestPointer) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000336 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000337 SrcPointee = SrcPointer->getPointeeType();
338 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000339 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000340 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000341 return;
342 }
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000343 } else if (DestReference->isLValueReferenceType()) {
Sebastian Redl842ef522008-11-08 13:00:26 +0000344 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000345 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000346 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000347 }
348 SrcPointee = SrcType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000349 } else {
350 SrcPointee = SrcType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000351 }
352
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000353 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000354 if (SrcRecord) {
Douglas Gregored0cfbd2009-03-09 16:13:40 +0000355 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Douglas Gregor89336232010-03-29 23:34:08 +0000356 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
Anders Carlssond624e162009-08-26 23:45:07 +0000357 << SrcExpr->getSourceRange()))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000358 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000359 } else {
Chris Lattner29e812b2008-11-20 06:06:08 +0000360 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000361 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000362 return;
363 }
364
365 assert((DestPointer || DestReference) &&
366 "Bad destination non-ptr/ref slipped through.");
367 assert((DestRecord || DestPointee->isVoidType()) &&
368 "Bad destination pointee slipped through.");
369 assert(SrcRecord && "Bad source pointee slipped through.");
370
371 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
372 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000373 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000374 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000375 return;
376 }
377
378 // C++ 5.2.7p3: If the type of v is the same as the required result type,
379 // [except for cv].
380 if (DestRecord == SrcRecord) {
381 return;
382 }
383
384 // C++ 5.2.7p5
385 // Upcasts are resolved statically.
Sebastian Redl842ef522008-11-08 13:00:26 +0000386 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
387 Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
Chris Lattner1e5665e2008-11-24 06:25:27 +0000388 OpRange.getBegin(), OpRange);
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000389 Kind = CastExpr::CK_DerivedToBase;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000390 // Diagnostic already emitted on error.
391 return;
392 }
393
394 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000395 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000396 assert(SrcDecl && "Definition missing");
397 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner29e812b2008-11-20 06:06:08 +0000398 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000399 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000400 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000401
402 // Done. Everything else is run-time checks.
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000403 Kind = CastExpr::CK_Dynamic;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000404}
Sebastian Redl9f831db2009-07-25 15:41:38 +0000405
406/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
407/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
408/// like this:
409/// const char *str = "literal";
410/// legacy_function(const_cast\<char*\>(str));
411void
412CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +0000413 const SourceRange &OpRange, const SourceRange &DestRange) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000414 if (!DestType->isLValueReferenceType())
Douglas Gregorb92a1562010-02-03 00:27:59 +0000415 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000416
417 unsigned msg = diag::err_bad_cxx_cast_generic;
418 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
419 && msg != 0)
420 Self.Diag(OpRange.getBegin(), msg) << CT_Const
421 << SrcExpr->getType() << DestType << OpRange;
422}
423
424/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
425/// valid.
426/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
427/// like this:
428/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
429void
430CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000431 const SourceRange &OpRange, const SourceRange &DestRange,
432 CastExpr::CastKind &Kind) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000433 if (!DestType->isLValueReferenceType())
Douglas Gregorb92a1562010-02-03 00:27:59 +0000434 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000435
436 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000437 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
438 msg, Kind)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000439 != TC_Success && msg != 0)
440 Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
441 << SrcExpr->getType() << DestType << OpRange;
442}
443
444
445/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
446/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
447/// implicit conversions explicit and getting rid of data loss warnings.
448void
449CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlssone9766d52009-09-09 21:33:21 +0000450 const SourceRange &OpRange, CastExpr::CastKind &Kind,
451 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000452 // This test is outside everything else because it's the only case where
453 // a non-lvalue-reference target type does not lead to decay.
454 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Eli Friedman03bf60a2009-11-16 05:44:20 +0000455 if (DestType->isVoidType()) {
456 Kind = CastExpr::CK_ToVoid;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000457 return;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000458 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000459
Douglas Gregorad8b2222009-11-06 01:14:41 +0000460 if (!DestType->isLValueReferenceType() && !DestType->isRecordType())
Douglas Gregorb92a1562010-02-03 00:27:59 +0000461 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000462
463 unsigned msg = diag::err_bad_cxx_cast_generic;
Sebastian Redl7c353682009-11-14 21:15:49 +0000464 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000465 Kind, ConversionDecl)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000466 != TC_Success && msg != 0)
467 Self.Diag(OpRange.getBegin(), msg) << CT_Static
468 << SrcExpr->getType() << DestType << OpRange;
469}
470
471/// TryStaticCast - Check if a static cast can be performed, and do so if
472/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
473/// and casting away constness.
Sebastian Redl7c353682009-11-14 21:15:49 +0000474static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000475 QualType DestType, bool CStyle,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000476 const SourceRange &OpRange, unsigned &msg,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000477 CastExpr::CastKind &Kind,
Mike Stump11289f42009-09-09 15:08:12 +0000478 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000479 // The order the tests is not entirely arbitrary. There is one conversion
480 // that can be handled in two different ways. Given:
481 // struct A {};
482 // struct B : public A {
483 // B(); B(const A&);
484 // };
485 // const A &a = B();
486 // the cast static_cast<const B&>(a) could be seen as either a static
487 // reference downcast, or an explicit invocation of the user-defined
488 // conversion using B's conversion constructor.
489 // DR 427 specifies that the downcast is to be applied here.
490
491 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
492 // Done outside this function.
493
494 TryCastResult tcr;
495
496 // C++ 5.2.9p5, reference downcast.
497 // See the function for details.
498 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redl7c353682009-11-14 21:15:49 +0000499 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle, OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000500 msg, Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000501 if (tcr != TC_NotApplicable)
502 return tcr;
503
504 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
505 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
506 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
Sebastian Redl7c353682009-11-14 21:15:49 +0000507 if (tcr != TC_NotApplicable) {
508 Kind = CastExpr::CK_NoOp;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000509 return tcr;
Sebastian Redl7c353682009-11-14 21:15:49 +0000510 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000511
512 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
513 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000514 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000515 Kind, ConversionDecl);
516 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000517 return tcr;
Anders Carlssone9766d52009-09-09 21:33:21 +0000518
Sebastian Redl9f831db2009-07-25 15:41:38 +0000519 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
520 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
521 // conversions, subject to further restrictions.
522 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
523 // of qualification conversions impossible.
524 // In the CStyle case, the earlier attempt to const_cast should have taken
525 // care of reverse qualification conversions.
526
527 QualType OrigSrcType = SrcExpr->getType();
528
529 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
530
531 // Reverse integral promotion/conversion. All such conversions are themselves
532 // again integral promotions or conversions and are thus already handled by
533 // p2 (TryDirectInitialization above).
534 // (Note: any data loss warnings should be suppressed.)
535 // The exception is the reverse of enum->integer, i.e. integer->enum (and
536 // enum->enum). See also C++ 5.2.9p7.
537 // The same goes for reverse floating point promotion/conversion and
538 // floating-integral conversions. Again, only floating->enum is relevant.
539 if (DestType->isEnumeralType()) {
540 if (SrcType->isComplexType() || SrcType->isVectorType()) {
541 // Fall through - these cannot be converted.
Eli Friedman03bf60a2009-11-16 05:44:20 +0000542 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
543 Kind = CastExpr::CK_IntegralCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000544 return TC_Success;
Eli Friedman03bf60a2009-11-16 05:44:20 +0000545 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000546 }
547
548 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
549 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000550 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
551 Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000552 if (tcr != TC_NotApplicable)
553 return tcr;
554
555 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
556 // conversion. C++ 5.2.9p9 has additional information.
557 // DR54's access restrictions apply here also.
Douglas Gregorc934bc82010-03-07 23:24:59 +0000558 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
Anders Carlsson3f0db2b2009-10-30 00:46:35 +0000559 OpRange, msg, Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000560 if (tcr != TC_NotApplicable)
561 return tcr;
562
563 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
564 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
565 // just the usual constness stuff.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000566 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000567 QualType SrcPointee = SrcPointer->getPointeeType();
568 if (SrcPointee->isVoidType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000569 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000570 QualType DestPointee = DestPointer->getPointeeType();
571 if (DestPointee->isIncompleteOrObjectType()) {
572 // This is definitely the intended conversion, but it might fail due
573 // to a const violation.
574 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
575 msg = diag::err_bad_cxx_cast_const_away;
576 return TC_Failed;
577 }
Eli Friedman03bf60a2009-11-16 05:44:20 +0000578 Kind = CastExpr::CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000579 return TC_Success;
580 }
581 }
Fariborz Jahanian859c4152009-12-08 23:09:15 +0000582 else if (CStyle && DestType->isObjCObjectPointerType()) {
583 // allow c-style cast of objective-c pointers as they are pervasive.
584 Kind = CastExpr::CK_AnyPointerToObjCPointerCast;
585 return TC_Success;
586 }
Fariborz Jahanianffe912c2009-12-11 22:40:48 +0000587 else if (CStyle && DestType->isBlockPointerType()) {
588 // allow c-style cast of void * to block pointers.
589 Kind = CastExpr::CK_AnyPointerToBlockPointerCast;
590 return TC_Success;
591 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000592 }
593 }
594
595 // We tried everything. Everything! Nothing works! :-(
596 return TC_NotApplicable;
597}
598
599/// Tests whether a conversion according to N2844 is valid.
600TryCastResult
601TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +0000602 unsigned &msg) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000603 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
604 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000605 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000606 if (!R)
607 return TC_NotApplicable;
608
609 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
610 return TC_NotApplicable;
611
612 // Because we try the reference downcast before this function, from now on
613 // this is the only cast possibility, so we issue an error if we fail now.
614 // FIXME: Should allow casting away constness if CStyle.
615 bool DerivedToBase;
Douglas Gregor3ec1bf22009-11-05 13:06:35 +0000616 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
617 SrcExpr->getType(), R->getPointeeType(),
Sebastian Redl9f831db2009-07-25 15:41:38 +0000618 DerivedToBase) <
619 Sema::Ref_Compatible_With_Added_Qualification) {
620 msg = diag::err_bad_lvalue_to_rvalue_cast;
621 return TC_Failed;
622 }
623
Douglas Gregor031296e2010-03-25 00:20:38 +0000624 // FIXME: We should probably have an AST node for lvalue-to-rvalue
625 // conversions.
Sebastian Redl9f831db2009-07-25 15:41:38 +0000626 return TC_Success;
627}
628
629/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
630TryCastResult
631TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
632 bool CStyle, const SourceRange &OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000633 unsigned &msg, CastExpr::CastKind &Kind) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000634 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
635 // cast to type "reference to cv2 D", where D is a class derived from B,
636 // if a valid standard conversion from "pointer to D" to "pointer to B"
637 // exists, cv2 >= cv1, and B is not a virtual base class of D.
638 // In addition, DR54 clarifies that the base must be accessible in the
639 // current context. Although the wording of DR54 only applies to the pointer
640 // variant of this rule, the intent is clearly for it to apply to the this
641 // conversion as well.
642
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000643 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000644 if (!DestReference) {
645 return TC_NotApplicable;
646 }
647 bool RValueRef = DestReference->isRValueReferenceType();
648 if (!RValueRef && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
649 // We know the left side is an lvalue reference, so we can suggest a reason.
650 msg = diag::err_bad_cxx_cast_rvalue;
651 return TC_NotApplicable;
652 }
653
654 QualType DestPointee = DestReference->getPointeeType();
655
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000656 return TryStaticDowncast(Self,
657 Self.Context.getCanonicalType(SrcExpr->getType()),
658 Self.Context.getCanonicalType(DestPointee), CStyle,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000659 OpRange, SrcExpr->getType(), DestType, msg, Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000660}
661
662/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
663TryCastResult
664TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +0000665 bool CStyle, const SourceRange &OpRange,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000666 unsigned &msg, CastExpr::CastKind &Kind) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000667 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
668 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
669 // is a class derived from B, if a valid standard conversion from "pointer
670 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
671 // class of D.
672 // In addition, DR54 clarifies that the base must be accessible in the
673 // current context.
674
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000675 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000676 if (!DestPointer) {
677 return TC_NotApplicable;
678 }
679
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000680 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000681 if (!SrcPointer) {
682 msg = diag::err_bad_static_cast_pointer_nonpointer;
683 return TC_NotApplicable;
684 }
685
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000686 return TryStaticDowncast(Self,
687 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
688 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
689 CStyle, OpRange, SrcType, DestType, msg, Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000690}
691
692/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
693/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000694/// DestType is possible and allowed.
Sebastian Redl9f831db2009-07-25 15:41:38 +0000695TryCastResult
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000696TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000697 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000698 QualType OrigDestType, unsigned &msg,
699 CastExpr::CastKind &Kind) {
Sebastian Redl802f14c2009-10-22 15:07:22 +0000700 // We can only work with complete types. But don't complain if it doesn't work
Douglas Gregor89336232010-03-29 23:34:08 +0000701 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, Self.PDiag(0)) ||
702 Self.RequireCompleteType(OpRange.getBegin(), DestType, Self.PDiag(0)))
Sebastian Redl802f14c2009-10-22 15:07:22 +0000703 return TC_NotApplicable;
704
Sebastian Redl9f831db2009-07-25 15:41:38 +0000705 // Downcast can only happen in class hierarchies, so we need classes.
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000706 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000707 return TC_NotApplicable;
708 }
709
Douglas Gregor36d1b142009-10-06 17:59:45 +0000710 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
711 /*DetectVirtual=*/true);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000712 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
713 return TC_NotApplicable;
714 }
715
716 // Target type does derive from source type. Now we're serious. If an error
717 // appears now, it's not ignored.
718 // This may not be entirely in line with the standard. Take for example:
719 // struct A {};
720 // struct B : virtual A {
721 // B(A&);
722 // };
Mike Stump11289f42009-09-09 15:08:12 +0000723 //
Sebastian Redl9f831db2009-07-25 15:41:38 +0000724 // void f()
725 // {
726 // (void)static_cast<const B&>(*((A*)0));
727 // }
728 // As far as the standard is concerned, p5 does not apply (A is virtual), so
729 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
730 // However, both GCC and Comeau reject this example, and accepting it would
731 // mean more complex code if we're to preserve the nice error message.
732 // FIXME: Being 100% compliant here would be nice to have.
733
734 // Must preserve cv, as always, unless we're in C-style mode.
735 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
736 msg = diag::err_bad_cxx_cast_const_away;
737 return TC_Failed;
738 }
739
740 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
741 // This code is analoguous to that in CheckDerivedToBaseConversion, except
742 // that it builds the paths in reverse order.
743 // To sum up: record all paths to the base and build a nice string from
744 // them. Use it to spice up the error message.
745 if (!Paths.isRecordingPaths()) {
746 Paths.clear();
747 Paths.setRecordingPaths(true);
748 Self.IsDerivedFrom(DestType, SrcType, Paths);
749 }
750 std::string PathDisplayStr;
751 std::set<unsigned> DisplayedPaths;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000752 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000753 PI != PE; ++PI) {
754 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
755 // We haven't displayed a path to this particular base
756 // class subobject yet.
757 PathDisplayStr += "\n ";
Douglas Gregor36d1b142009-10-06 17:59:45 +0000758 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
759 EE = PI->rend();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000760 EI != EE; ++EI)
761 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000762 PathDisplayStr += QualType(DestType).getAsString();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000763 }
764 }
765
766 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Douglas Gregor8f3952c2009-11-15 09:20:52 +0000767 << QualType(SrcType).getUnqualifiedType()
768 << QualType(DestType).getUnqualifiedType()
Sebastian Redl9f831db2009-07-25 15:41:38 +0000769 << PathDisplayStr << OpRange;
770 msg = 0;
771 return TC_Failed;
772 }
773
774 if (Paths.getDetectedVirtual() != 0) {
775 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
776 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
777 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
778 msg = 0;
779 return TC_Failed;
780 }
781
John McCall5b0829a2010-02-10 09:31:12 +0000782 if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
John McCall5b0829a2010-02-10 09:31:12 +0000783 SrcType, DestType,
John McCall1064d7e2010-03-16 05:22:47 +0000784 Paths.front(),
785 diag::err_downcast_from_inaccessible_base)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000786 msg = 0;
787 return TC_Failed;
788 }
789
Anders Carlsson9a1cd872009-11-12 16:53:16 +0000790 Kind = CastExpr::CK_BaseToDerived;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000791 return TC_Success;
792}
793
794/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
795/// C++ 5.2.9p9 is valid:
796///
797/// An rvalue of type "pointer to member of D of type cv1 T" can be
798/// converted to an rvalue of type "pointer to member of B of type cv2 T",
799/// where B is a base class of D [...].
800///
801TryCastResult
Douglas Gregorc934bc82010-03-07 23:24:59 +0000802TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr, QualType SrcType,
803 QualType DestType, bool CStyle,
804 const SourceRange &OpRange,
Anders Carlsson3f0db2b2009-10-30 00:46:35 +0000805 unsigned &msg, CastExpr::CastKind &Kind) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000806 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000807 if (!DestMemPtr)
808 return TC_NotApplicable;
Douglas Gregorc934bc82010-03-07 23:24:59 +0000809
810 bool WasOverloadedFunction = false;
John McCall16df1e52010-03-30 21:47:33 +0000811 DeclAccessPair FoundOverload;
Douglas Gregor064fdb22010-04-14 23:11:21 +0000812 if (SrcExpr->getType() == Self.Context.OverloadTy) {
813 if (FunctionDecl *Fn
814 = Self.ResolveAddressOfOverloadedFunction(SrcExpr, DestType, false,
815 FoundOverload)) {
816 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
817 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
818 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
819 WasOverloadedFunction = true;
820 }
Douglas Gregorc934bc82010-03-07 23:24:59 +0000821 }
Douglas Gregor064fdb22010-04-14 23:11:21 +0000822
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000823 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000824 if (!SrcMemPtr) {
825 msg = diag::err_bad_static_cast_member_pointer_nonmp;
826 return TC_NotApplicable;
827 }
828
829 // T == T, modulo cv
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000830 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
831 DestMemPtr->getPointeeType()))
Sebastian Redl9f831db2009-07-25 15:41:38 +0000832 return TC_NotApplicable;
833
834 // B base of D
835 QualType SrcClass(SrcMemPtr->getClass(), 0);
836 QualType DestClass(DestMemPtr->getClass(), 0);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000837 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000838 /*DetectVirtual=*/true);
839 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
840 return TC_NotApplicable;
841 }
842
843 // B is a base of D. But is it an allowed base? If not, it's a hard error.
844 if (Paths.isAmbiguous(DestClass)) {
845 Paths.clear();
846 Paths.setRecordingPaths(true);
847 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
848 assert(StillOkay);
849 StillOkay = StillOkay;
850 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
851 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
852 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
853 msg = 0;
854 return TC_Failed;
855 }
856
857 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
858 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
859 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
860 msg = 0;
861 return TC_Failed;
862 }
863
John McCall5b0829a2010-02-10 09:31:12 +0000864 if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
John McCall5b0829a2010-02-10 09:31:12 +0000865 DestType, SrcType,
John McCall1064d7e2010-03-16 05:22:47 +0000866 Paths.front(),
867 diag::err_upcast_to_inaccessible_base)) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000868 msg = 0;
869 return TC_Failed;
870 }
871
Douglas Gregorc934bc82010-03-07 23:24:59 +0000872 if (WasOverloadedFunction) {
873 // Resolve the address of the overloaded function again, this time
874 // allowing complaints if something goes wrong.
875 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr,
876 DestType,
John McCall16df1e52010-03-30 21:47:33 +0000877 true,
878 FoundOverload);
Douglas Gregorc934bc82010-03-07 23:24:59 +0000879 if (!Fn) {
880 msg = 0;
881 return TC_Failed;
882 }
883
John McCall16df1e52010-03-30 21:47:33 +0000884 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
Douglas Gregorc934bc82010-03-07 23:24:59 +0000885 if (!SrcExpr) {
886 msg = 0;
887 return TC_Failed;
888 }
889 }
890
Anders Carlsson3f0db2b2009-10-30 00:46:35 +0000891 Kind = CastExpr::CK_DerivedToBaseMemberPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000892 return TC_Success;
893}
894
895/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
896/// is valid:
897///
898/// An expression e can be explicitly converted to a type T using a
899/// @c static_cast if the declaration "T t(e);" is well-formed [...].
900TryCastResult
Sebastian Redl7c353682009-11-14 21:15:49 +0000901TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000902 bool CStyle, const SourceRange &OpRange, unsigned &msg,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000903 CastExpr::CastKind &Kind,
Mike Stump11289f42009-09-09 15:08:12 +0000904 CXXMethodDecl *&ConversionDecl) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +0000905 if (DestType->isRecordType()) {
906 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
907 diag::err_bad_dynamic_cast_incomplete)) {
908 msg = 0;
909 return TC_Failed;
910 }
911 }
Mike Stump11289f42009-09-09 15:08:12 +0000912
Sebastian Redl9f831db2009-07-25 15:41:38 +0000913 if (DestType->isReferenceType()) {
Sebastian Redl7c353682009-11-14 21:15:49 +0000914 // All reference bindings insert implicit casts above that do the actual
915 // casting.
916 Kind = CastExpr::CK_NoOp;
917
Sebastian Redl9f831db2009-07-25 15:41:38 +0000918 // At this point of CheckStaticCast, if the destination is a reference,
919 // this has to work. There is no other way that works.
920 // On the other hand, if we're checking a C-style cast, we've still got
Douglas Gregordeb714c2010-03-24 23:38:29 +0000921 // the reinterpret_cast way.
922 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
923 InitializationKind InitKind = InitializationKind::CreateCast(OpRange,
924 CStyle);
925 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExpr, 1);
926 if (InitSeq.getKind() == InitializationSequence::FailedSequence && CStyle)
927 return TC_NotApplicable;
928
929 Sema::OwningExprResult Result
930 = InitSeq.Perform(Self, Entity, InitKind,
931 Action::MultiExprArg(Self, (void**)&SrcExpr, 1));
932 if (Result.isInvalid()) {
933 msg = 0;
934 return TC_Failed;
Sebastian Redl7c353682009-11-14 21:15:49 +0000935 }
Douglas Gregordeb714c2010-03-24 23:38:29 +0000936
937 SrcExpr = Result.takeAs<Expr>();
938 return TC_Success;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000939 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000940
Douglas Gregorbf3f3222009-11-14 03:27:21 +0000941 if (DestType->isRecordType()) {
942 if (CXXConstructorDecl *Constructor
Sebastian Redl7c353682009-11-14 21:15:49 +0000943 = Self.TryInitializationByConstructor(DestType, &SrcExpr, 1,
Douglas Gregorbf3f3222009-11-14 03:27:21 +0000944 OpRange.getBegin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +0000945 InitializationKind::CreateDirect(OpRange.getBegin(),
946 OpRange.getBegin(),
947 OpRange.getEnd()))) {
Douglas Gregorbf3f3222009-11-14 03:27:21 +0000948 ConversionDecl = Constructor;
949 Kind = CastExpr::CK_ConstructorConversion;
950 return TC_Success;
951 }
952
953 return TC_NotApplicable;
954 }
Sebastian Redl7c353682009-11-14 21:15:49 +0000955
Sebastian Redl9f831db2009-07-25 15:41:38 +0000956 // FIXME: To get a proper error from invalid conversions here, we need to
957 // reimplement more of this.
958 // FIXME: This does not actually perform the conversion, and thus does not
959 // check for ambiguity or access.
Mike Stump11289f42009-09-09 15:08:12 +0000960 ImplicitConversionSequence ICS =
Anders Carlssonef4c7212009-08-27 17:24:15 +0000961 Self.TryImplicitConversion(SrcExpr, DestType,
962 /*SuppressUserConversions=*/false,
Anders Carlssonf2bc7c32009-08-28 16:22:20 +0000963 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +0000964 /*ForceRValue=*/false,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000965 /*InOverloadResolution=*/false,
966 /*one of user provided casts*/true);
Mike Stump11289f42009-09-09 15:08:12 +0000967
John McCall0d1da222010-01-12 00:44:57 +0000968 if (ICS.isBad())
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000969 return TC_NotApplicable;
970
Sebastian Redl7c353682009-11-14 21:15:49 +0000971 // The conversion is possible, so commit to it.
Eli Friedman03bf60a2009-11-16 05:44:20 +0000972 Kind = CastExpr::CK_NoOp;
Sebastian Redl7c353682009-11-14 21:15:49 +0000973 msg = 0;
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +0000974 return Self.PerformImplicitConversion(SrcExpr, DestType, ICS, Sema::AA_Casting,
Sebastian Redl7c353682009-11-14 21:15:49 +0000975 /*IgnoreBaseAccess*/CStyle) ?
976 TC_Failed : TC_Success;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000977}
978
979/// TryConstCast - See if a const_cast from source to destination is allowed,
980/// and perform it if it is.
981static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
982 bool CStyle, unsigned &msg) {
983 DestType = Self.Context.getCanonicalType(DestType);
984 QualType SrcType = SrcExpr->getType();
985 if (const LValueReferenceType *DestTypeTmp =
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000986 DestType->getAs<LValueReferenceType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000987 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
988 // Cannot const_cast non-lvalue to lvalue reference type. But if this
989 // is C-style, static_cast might find a way, so we simply suggest a
990 // message and tell the parent to keep searching.
991 msg = diag::err_bad_cxx_cast_rvalue;
992 return TC_NotApplicable;
993 }
994
995 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
996 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
997 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
998 SrcType = Self.Context.getPointerType(SrcType);
999 }
1000
1001 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1002 // the rules for const_cast are the same as those used for pointers.
1003
1004 if (!DestType->isPointerType() && !DestType->isMemberPointerType()) {
1005 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1006 // was a reference type, we converted it to a pointer above.
1007 // The status of rvalue references isn't entirely clear, but it looks like
1008 // conversion to them is simply invalid.
1009 // C++ 5.2.11p3: For two pointer types [...]
1010 if (!CStyle)
1011 msg = diag::err_bad_const_cast_dest;
1012 return TC_NotApplicable;
1013 }
1014 if (DestType->isFunctionPointerType() ||
1015 DestType->isMemberFunctionPointerType()) {
1016 // Cannot cast direct function pointers.
1017 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1018 // T is the ultimate pointee of source and target type.
1019 if (!CStyle)
1020 msg = diag::err_bad_const_cast_dest;
1021 return TC_NotApplicable;
1022 }
1023 SrcType = Self.Context.getCanonicalType(SrcType);
1024
1025 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1026 // completely equal.
1027 // FIXME: const_cast should probably not be able to convert between pointers
1028 // to different address spaces.
1029 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1030 // in multi-level pointers may change, but the level count must be the same,
1031 // as must be the final pointee type.
1032 while (SrcType != DestType &&
1033 Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Chandler Carruth585fb1e2009-12-29 08:05:19 +00001034 Qualifiers Quals;
1035 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, Quals);
1036 DestType = Self.Context.getUnqualifiedArrayType(DestType, Quals);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001037 }
1038
1039 // Since we're dealing in canonical types, the remainder must be the same.
1040 if (SrcType != DestType)
1041 return TC_NotApplicable;
1042
1043 return TC_Success;
1044}
1045
1046static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
1047 QualType DestType, bool CStyle,
1048 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001049 unsigned &msg,
1050 CastExpr::CastKind &Kind) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001051 DestType = Self.Context.getCanonicalType(DestType);
1052 QualType SrcType = SrcExpr->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001053 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001054 bool LValue = DestTypeTmp->isLValueReferenceType();
1055 if (LValue && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
1056 // Cannot cast non-lvalue to reference type. See the similar comment in
1057 // const_cast.
1058 msg = diag::err_bad_cxx_cast_rvalue;
1059 return TC_NotApplicable;
1060 }
1061
1062 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1063 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1064 // built-in & and * operators.
1065 // This code does this transformation for the checked types.
1066 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1067 SrcType = Self.Context.getPointerType(SrcType);
1068 }
1069
1070 // Canonicalize source for comparison.
1071 SrcType = Self.Context.getCanonicalType(SrcType);
1072
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001073 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1074 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001075 if (DestMemPtr && SrcMemPtr) {
1076 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1077 // can be explicitly converted to an rvalue of type "pointer to member
1078 // of Y of type T2" if T1 and T2 are both function types or both object
1079 // types.
1080 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1081 SrcMemPtr->getPointeeType()->isFunctionType())
1082 return TC_NotApplicable;
1083
1084 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1085 // constness.
1086 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1087 // we accept it.
1088 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1089 msg = diag::err_bad_cxx_cast_const_away;
1090 return TC_Failed;
1091 }
1092
1093 // A valid member pointer cast.
Anders Carlsson9500ad12009-10-18 20:31:03 +00001094 Kind = CastExpr::CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001095 return TC_Success;
1096 }
1097
1098 // See below for the enumeral issue.
1099 if (SrcType->isNullPtrType() && DestType->isIntegralType() &&
1100 !DestType->isEnumeralType()) {
1101 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1102 // type large enough to hold it. A value of std::nullptr_t can be
1103 // converted to an integral type; the conversion has the same meaning
1104 // and validity as a conversion of (void*)0 to the integral type.
1105 if (Self.Context.getTypeSize(SrcType) >
1106 Self.Context.getTypeSize(DestType)) {
1107 msg = diag::err_bad_reinterpret_cast_small_int;
1108 return TC_Failed;
1109 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +00001110 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001111 return TC_Success;
1112 }
1113
Anders Carlsson570af5d2009-09-16 19:19:43 +00001114 bool destIsVector = DestType->isVectorType();
1115 bool srcIsVector = SrcType->isVectorType();
1116 if (srcIsVector || destIsVector) {
1117 bool srcIsScalar = SrcType->isIntegralType() && !SrcType->isEnumeralType();
1118 bool destIsScalar =
1119 DestType->isIntegralType() && !DestType->isEnumeralType();
1120
1121 // Check if this is a cast between a vector and something else.
1122 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1123 !(srcIsVector && destIsVector))
1124 return TC_NotApplicable;
1125
1126 // If both types have the same size, we can successfully cast.
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001127 if (Self.Context.getTypeSize(SrcType)
1128 == Self.Context.getTypeSize(DestType)) {
1129 Kind = CastExpr::CK_BitCast;
Anders Carlsson570af5d2009-09-16 19:19:43 +00001130 return TC_Success;
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001131 }
Anders Carlsson570af5d2009-09-16 19:19:43 +00001132
1133 if (destIsScalar)
1134 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1135 else if (srcIsScalar)
1136 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1137 else
1138 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1139
1140 return TC_Failed;
1141 }
1142
Fariborz Jahanian8c3f06d2010-02-03 20:32:31 +00001143 bool destIsPtr = DestType->isAnyPointerType();
1144 bool srcIsPtr = SrcType->isAnyPointerType();
Sebastian Redl9f831db2009-07-25 15:41:38 +00001145 if (!destIsPtr && !srcIsPtr) {
1146 // Except for std::nullptr_t->integer and lvalue->reference, which are
1147 // handled above, at least one of the two arguments must be a pointer.
1148 return TC_NotApplicable;
1149 }
1150
1151 if (SrcType == DestType) {
1152 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1153 // restrictions, a cast to the same type is allowed. The intent is not
1154 // entirely clear here, since all other paragraphs explicitly forbid casts
1155 // to the same type. However, the behavior of compilers is pretty consistent
1156 // on this point: allow same-type conversion if the involved types are
1157 // pointers, disallow otherwise.
Douglas Gregor19fc0b72009-12-22 22:47:22 +00001158 Kind = CastExpr::CK_NoOp;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001159 return TC_Success;
1160 }
1161
1162 // Note: Clang treats enumeration types as integral types. If this is ever
1163 // changed for C++, the additional check here will be redundant.
1164 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
1165 assert(srcIsPtr && "One type must be a pointer");
1166 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1167 // type large enough to hold it.
1168 if (Self.Context.getTypeSize(SrcType) >
1169 Self.Context.getTypeSize(DestType)) {
1170 msg = diag::err_bad_reinterpret_cast_small_int;
1171 return TC_Failed;
1172 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +00001173 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001174 return TC_Success;
1175 }
1176
1177 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
1178 assert(destIsPtr && "One type must be a pointer");
1179 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1180 // converted to a pointer.
Anders Carlsson7cd39e02009-09-15 04:48:33 +00001181 Kind = CastExpr::CK_IntegralToPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001182 return TC_Success;
1183 }
1184
1185 if (!destIsPtr || !srcIsPtr) {
1186 // With the valid non-pointer conversions out of the way, we can be even
1187 // more stringent.
1188 return TC_NotApplicable;
1189 }
1190
1191 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1192 // The C-style cast operator can.
1193 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1194 msg = diag::err_bad_cxx_cast_const_away;
1195 return TC_Failed;
1196 }
Fariborz Jahanian859c4152009-12-08 23:09:15 +00001197 if (CStyle && DestType->isObjCObjectPointerType()) {
1198 Kind = CastExpr::CK_AnyPointerToObjCPointerCast;
1199 return TC_Success;
1200 }
1201
Sebastian Redl9f831db2009-07-25 15:41:38 +00001202 // Not casting away constness, so the only remaining check is for compatible
1203 // pointer categories.
Anders Carlsson9500ad12009-10-18 20:31:03 +00001204 Kind = CastExpr::CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001205
1206 if (SrcType->isFunctionPointerType()) {
1207 if (DestType->isFunctionPointerType()) {
1208 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1209 // a pointer to a function of a different type.
1210 return TC_Success;
1211 }
1212
1213 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1214 // an object type or vice versa is conditionally-supported.
1215 // Compilers support it in C++03 too, though, because it's necessary for
1216 // casting the return value of dlsym() and GetProcAddress().
1217 // FIXME: Conditionally-supported behavior should be configurable in the
1218 // TargetInfo or similar.
1219 if (!Self.getLangOptions().CPlusPlus0x)
1220 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1221 return TC_Success;
1222 }
1223
1224 if (DestType->isFunctionPointerType()) {
1225 // See above.
1226 if (!Self.getLangOptions().CPlusPlus0x)
1227 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1228 return TC_Success;
1229 }
1230
1231 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1232 // a pointer to an object of different type.
1233 // Void pointers are not specified, but supported by every compiler out there.
1234 // So we finish by allowing everything that remains - it's got to be two
1235 // object pointers.
1236 return TC_Success;
1237}
1238
Sebastian Redl955a0672009-07-29 13:50:23 +00001239bool Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00001240 CastExpr::CastKind &Kind, bool FunctionalStyle,
Mike Stump11289f42009-09-09 15:08:12 +00001241 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001242 // This test is outside everything else because it's the only case where
1243 // a non-lvalue-reference target type does not lead to decay.
1244 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Anders Carlsson9500ad12009-10-18 20:31:03 +00001245 if (CastTy->isVoidType()) {
1246 Kind = CastExpr::CK_ToVoid;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001247 return false;
Anders Carlsson9500ad12009-10-18 20:31:03 +00001248 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001249
1250 // If the type is dependent, we won't do any other semantic analysis now.
1251 if (CastTy->isDependentType() || CastExpr->isTypeDependent())
1252 return false;
1253
Douglas Gregorad8b2222009-11-06 01:14:41 +00001254 if (!CastTy->isLValueReferenceType() && !CastTy->isRecordType())
Douglas Gregorb92a1562010-02-03 00:27:59 +00001255 DefaultFunctionArrayLvalueConversion(CastExpr);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001256
1257 // C++ [expr.cast]p5: The conversions performed by
1258 // - a const_cast,
1259 // - a static_cast,
1260 // - a static_cast followed by a const_cast,
1261 // - a reinterpret_cast, or
1262 // - a reinterpret_cast followed by a const_cast,
1263 // can be performed using the cast notation of explicit type conversion.
1264 // [...] If a conversion can be interpreted in more than one of the ways
1265 // listed above, the interpretation that appears first in the list is used,
1266 // even if a cast resulting from that interpretation is ill-formed.
1267 // In plain language, this means trying a const_cast ...
1268 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssonf1ae6d42009-09-01 20:52:42 +00001269 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1270 msg);
Anders Carlsson027732b2009-10-19 18:14:28 +00001271 if (tcr == TC_Success)
1272 Kind = CastExpr::CK_NoOp;
1273
Sebastian Redl9f831db2009-07-25 15:41:38 +00001274 if (tcr == TC_NotApplicable) {
1275 // ... or if that is not possible, a static_cast, ignoring const, ...
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001276 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1277 Kind, ConversionDecl);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001278 if (tcr == TC_NotApplicable) {
1279 // ... and finally a reinterpret_cast, ignoring const.
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001280 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1281 Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001282 }
1283 }
1284
Sebastian Redl9f831db2009-07-25 15:41:38 +00001285 if (tcr != TC_Success && msg != 0)
Sebastian Redl955a0672009-07-29 13:50:23 +00001286 Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
Sebastian Redl9f831db2009-07-25 15:41:38 +00001287 << CastExpr->getType() << CastTy << R;
1288
1289 return tcr != TC_Success;
1290}