blob: c7aaa6fc67f33499a97f77673113d8f429a4765d [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"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000015#include "clang/AST/ExprCXX.h"
16#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
Anders Carlssond624e162009-08-26 23:45:07 +000018#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000019#include "llvm/ADT/SmallVector.h"
Sebastian Redl015085f2008-11-07 23:29:29 +000020#include <set>
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +000021using namespace clang;
22
Sebastian Redl9f831db2009-07-25 15:41:38 +000023enum TryCastResult {
24 TC_NotApplicable, ///< The cast method is not applicable.
25 TC_Success, ///< The cast method is appropriate and successful.
26 TC_Failed ///< The cast method is appropriate, but failed. A
27 ///< diagnostic has been emitted.
28};
29
30enum CastType {
31 CT_Const, ///< const_cast
32 CT_Static, ///< static_cast
33 CT_Reinterpret, ///< reinterpret_cast
34 CT_Dynamic, ///< dynamic_cast
35 CT_CStyle, ///< (Type)expr
36 CT_Functional ///< Type(expr)
Sebastian Redl842ef522008-11-08 13:00:26 +000037};
38
39static void CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
40 const SourceRange &OpRange,
41 const SourceRange &DestRange);
42static void CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
43 const SourceRange &OpRange,
Anders Carlsson7cd39e02009-09-15 04:48:33 +000044 const SourceRange &DestRange,
45 CastExpr::CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +000046static void CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlssonf10e4142009-08-07 22:21:05 +000047 const SourceRange &OpRange,
Anders Carlssone9766d52009-09-09 21:33:21 +000048 CastExpr::CastKind &Kind,
49 CXXMethodDecl *&ConversionDecl);
Sebastian Redl842ef522008-11-08 13:00:26 +000050static void CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
51 const SourceRange &OpRange,
Mike Stump11289f42009-09-09 15:08:12 +000052 const SourceRange &DestRange,
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +000053 CastExpr::CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +000054
55static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
Sebastian Redl9f831db2009-07-25 15:41:38 +000056
57// The Try functions attempt a specific way of casting. If they succeed, they
58// return TC_Success. If their way of casting is not appropriate for the given
59// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
60// to emit if no other way succeeds. If their way of casting is appropriate but
61// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
62// they emit a specialized diagnostic.
63// All diagnostics returned by these functions must expect the same three
64// arguments:
65// %0: Cast Type (a value from the CastType enumeration)
66// %1: Source Type
67// %2: Destination Type
68static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
69 QualType DestType, unsigned &msg);
70static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
71 QualType DestType, bool CStyle,
72 const SourceRange &OpRange,
73 unsigned &msg);
74static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
75 QualType DestType, bool CStyle,
76 const SourceRange &OpRange,
77 unsigned &msg);
78static TryCastResult TryStaticDowncast(Sema &Self, QualType SrcType,
79 QualType DestType, bool CStyle,
80 const SourceRange &OpRange,
81 QualType OrigSrcType,
82 QualType OrigDestType, unsigned &msg);
83static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType,
84 QualType DestType,bool CStyle,
85 const SourceRange &OpRange,
86 unsigned &msg);
87static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *SrcExpr,
88 QualType DestType, bool CStyle,
89 const SourceRange &OpRange,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +000090 unsigned &msg,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +000091 CastExpr::CastKind &Kind,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +000092 CXXMethodDecl *&ConversionDecl);
Sebastian Redl9f831db2009-07-25 15:41:38 +000093static TryCastResult TryStaticCast(Sema &Self, Expr *SrcExpr,
94 QualType DestType, bool CStyle,
95 const SourceRange &OpRange,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +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 Redl9f831db2009-07-25 15:41:38 +000099static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
100 bool CStyle, unsigned &msg);
101static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
102 QualType DestType, bool CStyle,
103 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000104 unsigned &msg,
105 CastExpr::CastKind &Kind);
Sebastian Redl842ef522008-11-08 13:00:26 +0000106
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000107/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000108Action::OwningExprResult
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000109Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
110 SourceLocation LAngleBracketLoc, TypeTy *Ty,
111 SourceLocation RAngleBracketLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000112 SourceLocation LParenLoc, ExprArg E,
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000113 SourceLocation RParenLoc) {
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000114 Expr *Ex = E.takeAs<Expr>();
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000115 // FIXME: Preserve type source info.
116 QualType DestType = GetTypeFromParser(Ty);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000117 SourceRange OpRange(OpLoc, RParenLoc);
118 SourceRange DestRange(LAngleBracketLoc, RAngleBracketLoc);
119
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000120 // If the type is dependent, we won't do the semantic analysis now.
121 // FIXME: should we check this in a more fine-grained manner?
122 bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
123
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000124 switch (Kind) {
125 default: assert(0 && "Unknown C++ cast!");
126
127 case tok::kw_const_cast:
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000128 if (!TypeDependent)
129 CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000130 return Owned(new (Context) CXXConstCastExpr(DestType.getNonReferenceType(),
131 Ex, DestType, OpLoc));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000132
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000133 case tok::kw_dynamic_cast: {
134 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000135 if (!TypeDependent)
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000136 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000137 return Owned(new (Context)CXXDynamicCastExpr(DestType.getNonReferenceType(),
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000138 Kind, Ex, DestType, OpLoc));
139 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000140 case tok::kw_reinterpret_cast: {
141 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregor19b8c4f2008-12-17 22:52:20 +0000142 if (!TypeDependent)
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000143 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange, Kind);
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000144 return Owned(new (Context) CXXReinterpretCastExpr(
145 DestType.getNonReferenceType(),
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000146 Kind, Ex, DestType, OpLoc));
147 }
Anders Carlssonf10e4142009-08-07 22:21:05 +0000148 case tok::kw_static_cast: {
149 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Anders Carlssone9766d52009-09-09 21:33:21 +0000150 if (!TypeDependent) {
151 CXXMethodDecl *Method = 0;
152
153 CheckStaticCast(*this, Ex, DestType, OpRange, Kind, Method);
154
155 if (Method) {
156 OwningExprResult CastArg
157 = BuildCXXCastArgument(OpLoc, DestType.getNonReferenceType(),
158 Kind, Method, Owned(Ex));
159 if (CastArg.isInvalid())
160 return ExprError();
161
162 Ex = CastArg.takeAs<Expr>();
163 }
164 }
165
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000166 return Owned(new (Context) CXXStaticCastExpr(DestType.getNonReferenceType(),
Anders Carlssonf10e4142009-08-07 22:21:05 +0000167 Kind, Ex, DestType, OpLoc));
168 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000169 }
170
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000171 return ExprError();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000172}
173
Sebastian Redla5a77a62009-01-27 23:18:31 +0000174/// CastsAwayConstness - Check if the pointer conversion from SrcType to
175/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
176/// the cast checkers. Both arguments must denote pointer (possibly to member)
177/// types.
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000178bool
Mike Stump11289f42009-09-09 15:08:12 +0000179CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
Sebastian Redla5a77a62009-01-27 23:18:31 +0000180 // Casting away constness is defined in C++ 5.2.11p8 with reference to
181 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
182 // the rules are non-trivial. So first we construct Tcv *...cv* as described
183 // in C++ 5.2.11p8.
184 assert((SrcType->isPointerType() || SrcType->isMemberPointerType()) &&
185 "Source type is not pointer or pointer to member.");
186 assert((DestType->isPointerType() || DestType->isMemberPointerType()) &&
187 "Destination type is not pointer or pointer to member.");
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000188
189 QualType UnwrappedSrcType = SrcType, UnwrappedDestType = DestType;
John McCall8ccfcb52009-09-24 19:53:00 +0000190 llvm::SmallVector<Qualifiers, 8> cv1, cv2;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000191
192 // Find the qualifications.
Sebastian Redl842ef522008-11-08 13:00:26 +0000193 while (Self.UnwrapSimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
John McCall8ccfcb52009-09-24 19:53:00 +0000194 cv1.push_back(UnwrappedSrcType.getQualifiers());
195 cv2.push_back(UnwrappedDestType.getQualifiers());
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000196 }
197 assert(cv1.size() > 0 && "Must have at least one pointer level.");
198
199 // Construct void pointers with those qualifiers (in reverse order of
200 // unwrapping, of course).
Sebastian Redl842ef522008-11-08 13:00:26 +0000201 QualType SrcConstruct = Self.Context.VoidTy;
202 QualType DestConstruct = Self.Context.VoidTy;
John McCall8ccfcb52009-09-24 19:53:00 +0000203 ASTContext &Context = Self.Context;
204 for (llvm::SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
205 i2 = cv2.rbegin();
Mike Stump11289f42009-09-09 15:08:12 +0000206 i1 != cv1.rend(); ++i1, ++i2) {
John McCall8ccfcb52009-09-24 19:53:00 +0000207 SrcConstruct
208 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
209 DestConstruct
210 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000211 }
212
213 // Test if they're compatible.
214 return SrcConstruct != DestConstruct &&
Sebastian Redl842ef522008-11-08 13:00:26 +0000215 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000216}
217
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000218/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
219/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
220/// checked downcasts in class hierarchies.
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000221static void
Sebastian Redl842ef522008-11-08 13:00:26 +0000222CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
223 const SourceRange &OpRange,
Mike Stump11289f42009-09-09 15:08:12 +0000224 const SourceRange &DestRange, CastExpr::CastKind &Kind) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000225 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl842ef522008-11-08 13:00:26 +0000226 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000227
228 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
229 // or "pointer to cv void".
230
231 QualType DestPointee;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000232 const PointerType *DestPointer = DestType->getAs<PointerType>();
233 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000234 if (DestPointer) {
235 DestPointee = DestPointer->getPointeeType();
236 } else if (DestReference) {
237 DestPointee = DestReference->getPointeeType();
238 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000239 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000240 << OrigDestType << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000241 return;
242 }
243
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000244 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000245 if (DestPointee->isVoidType()) {
246 assert(DestPointer && "Reference to void is not possible");
247 } else if (DestRecord) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000248 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
Anders Carlssond624e162009-08-26 23:45:07 +0000249 PDiag(diag::err_bad_dynamic_cast_incomplete)
250 << DestRange))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000251 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000252 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000253 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000254 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000255 return;
256 }
257
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000258 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
259 // complete class type, [...]. If T is an lvalue reference type, v shall be
260 // an lvalue of a complete class type, [...]. If T is an rvalue reference
261 // type, v shall be an expression having a complete effective class type,
262 // [...]
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000263
Sebastian Redl842ef522008-11-08 13:00:26 +0000264 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000265 QualType SrcPointee;
266 if (DestPointer) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000267 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000268 SrcPointee = SrcPointer->getPointeeType();
269 } else {
Chris Lattner377d1f82008-11-18 22:52:51 +0000270 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000271 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000272 return;
273 }
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000274 } else if (DestReference->isLValueReferenceType()) {
Sebastian Redl842ef522008-11-08 13:00:26 +0000275 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000276 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000277 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000278 }
279 SrcPointee = SrcType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000280 } else {
281 SrcPointee = SrcType;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000282 }
283
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000284 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000285 if (SrcRecord) {
Douglas Gregored0cfbd2009-03-09 16:13:40 +0000286 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
Anders Carlssond624e162009-08-26 23:45:07 +0000287 PDiag(diag::err_bad_dynamic_cast_incomplete)
288 << SrcExpr->getSourceRange()))
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000289 return;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000290 } else {
Chris Lattner29e812b2008-11-20 06:06:08 +0000291 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000292 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000293 return;
294 }
295
296 assert((DestPointer || DestReference) &&
297 "Bad destination non-ptr/ref slipped through.");
298 assert((DestRecord || DestPointee->isVoidType()) &&
299 "Bad destination pointee slipped through.");
300 assert(SrcRecord && "Bad source pointee slipped through.");
301
302 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
303 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +0000304 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000305 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000306 return;
307 }
308
309 // C++ 5.2.7p3: If the type of v is the same as the required result type,
310 // [except for cv].
311 if (DestRecord == SrcRecord) {
312 return;
313 }
314
315 // C++ 5.2.7p5
316 // Upcasts are resolved statically.
Sebastian Redl842ef522008-11-08 13:00:26 +0000317 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
318 Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
Chris Lattner1e5665e2008-11-24 06:25:27 +0000319 OpRange.getBegin(), OpRange);
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000320 Kind = CastExpr::CK_DerivedToBase;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000321 // Diagnostic already emitted on error.
322 return;
323 }
324
325 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Sebastian Redl842ef522008-11-08 13:00:26 +0000326 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(Self.Context);
Sebastian Redlb426f6332008-11-06 15:59:35 +0000327 assert(SrcDecl && "Definition missing");
328 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattner29e812b2008-11-20 06:06:08 +0000329 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000330 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redlb426f6332008-11-06 15:59:35 +0000331 }
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000332
333 // Done. Everything else is run-time checks.
Anders Carlsson4ab4f7f2009-08-02 19:07:59 +0000334 Kind = CastExpr::CK_Dynamic;
Sebastian Redl3c5aa4d2008-11-05 21:50:06 +0000335}
Sebastian Redl9f831db2009-07-25 15:41:38 +0000336
337/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
338/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
339/// like this:
340/// const char *str = "literal";
341/// legacy_function(const_cast\<char*\>(str));
342void
343CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +0000344 const SourceRange &OpRange, const SourceRange &DestRange) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000345 if (!DestType->isLValueReferenceType())
346 Self.DefaultFunctionArrayConversion(SrcExpr);
347
348 unsigned msg = diag::err_bad_cxx_cast_generic;
349 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
350 && msg != 0)
351 Self.Diag(OpRange.getBegin(), msg) << CT_Const
352 << SrcExpr->getType() << DestType << OpRange;
353}
354
355/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
356/// valid.
357/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
358/// like this:
359/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
360void
361CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000362 const SourceRange &OpRange, const SourceRange &DestRange,
363 CastExpr::CastKind &Kind) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000364 if (!DestType->isLValueReferenceType())
365 Self.DefaultFunctionArrayConversion(SrcExpr);
366
367 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000368 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
369 msg, Kind)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000370 != TC_Success && msg != 0)
371 Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
372 << SrcExpr->getType() << DestType << OpRange;
373}
374
375
376/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
377/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
378/// implicit conversions explicit and getting rid of data loss warnings.
379void
380CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
Anders Carlssone9766d52009-09-09 21:33:21 +0000381 const SourceRange &OpRange, CastExpr::CastKind &Kind,
382 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000383 // This test is outside everything else because it's the only case where
384 // a non-lvalue-reference target type does not lead to decay.
385 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
386 if (DestType->isVoidType()) {
387 return;
388 }
389
390 if (!DestType->isLValueReferenceType())
391 Self.DefaultFunctionArrayConversion(SrcExpr);
392
393 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000394 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false,OpRange, msg,
395 Kind, ConversionDecl)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000396 != TC_Success && msg != 0)
397 Self.Diag(OpRange.getBegin(), msg) << CT_Static
398 << SrcExpr->getType() << DestType << OpRange;
399}
400
401/// TryStaticCast - Check if a static cast can be performed, and do so if
402/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
403/// and casting away constness.
404static TryCastResult TryStaticCast(Sema &Self, Expr *SrcExpr,
405 QualType DestType, bool CStyle,
Anders Carlssonf1ae6d42009-09-01 20:52:42 +0000406 const SourceRange &OpRange, unsigned &msg,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000407 CastExpr::CastKind &Kind,
Mike Stump11289f42009-09-09 15:08:12 +0000408 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000409 // The order the tests is not entirely arbitrary. There is one conversion
410 // that can be handled in two different ways. Given:
411 // struct A {};
412 // struct B : public A {
413 // B(); B(const A&);
414 // };
415 // const A &a = B();
416 // the cast static_cast<const B&>(a) could be seen as either a static
417 // reference downcast, or an explicit invocation of the user-defined
418 // conversion using B's conversion constructor.
419 // DR 427 specifies that the downcast is to be applied here.
420
421 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
422 // Done outside this function.
423
424 TryCastResult tcr;
425
426 // C++ 5.2.9p5, reference downcast.
427 // See the function for details.
428 // DR 427 specifies that this is to be applied before paragraph 2.
429 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle,OpRange,msg);
430 if (tcr != TC_NotApplicable)
431 return tcr;
432
433 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
434 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
435 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
436 if (tcr != TC_NotApplicable)
437 return tcr;
438
439 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
440 // [...] if the declaration "T t(e);" is well-formed, [...].
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000441 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000442 Kind, ConversionDecl);
443 if (tcr != TC_NotApplicable)
Sebastian Redl9f831db2009-07-25 15:41:38 +0000444 return tcr;
Anders Carlssone9766d52009-09-09 21:33:21 +0000445
Sebastian Redl9f831db2009-07-25 15:41:38 +0000446 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
447 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
448 // conversions, subject to further restrictions.
449 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
450 // of qualification conversions impossible.
451 // In the CStyle case, the earlier attempt to const_cast should have taken
452 // care of reverse qualification conversions.
453
454 QualType OrigSrcType = SrcExpr->getType();
455
456 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
457
458 // Reverse integral promotion/conversion. All such conversions are themselves
459 // again integral promotions or conversions and are thus already handled by
460 // p2 (TryDirectInitialization above).
461 // (Note: any data loss warnings should be suppressed.)
462 // The exception is the reverse of enum->integer, i.e. integer->enum (and
463 // enum->enum). See also C++ 5.2.9p7.
464 // The same goes for reverse floating point promotion/conversion and
465 // floating-integral conversions. Again, only floating->enum is relevant.
466 if (DestType->isEnumeralType()) {
467 if (SrcType->isComplexType() || SrcType->isVectorType()) {
468 // Fall through - these cannot be converted.
469 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType())
470 return TC_Success;
471 }
472
473 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
474 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
475 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg);
476 if (tcr != TC_NotApplicable)
477 return tcr;
478
479 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
480 // conversion. C++ 5.2.9p9 has additional information.
481 // DR54's access restrictions apply here also.
482 tcr = TryStaticMemberPointerUpcast(Self, SrcType, DestType, CStyle,
483 OpRange, msg);
484 if (tcr != TC_NotApplicable)
485 return tcr;
486
487 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
488 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
489 // just the usual constness stuff.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000490 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000491 QualType SrcPointee = SrcPointer->getPointeeType();
492 if (SrcPointee->isVoidType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000493 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000494 QualType DestPointee = DestPointer->getPointeeType();
495 if (DestPointee->isIncompleteOrObjectType()) {
496 // This is definitely the intended conversion, but it might fail due
497 // to a const violation.
498 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
499 msg = diag::err_bad_cxx_cast_const_away;
500 return TC_Failed;
501 }
502 return TC_Success;
503 }
504 }
505 }
506 }
507
508 // We tried everything. Everything! Nothing works! :-(
509 return TC_NotApplicable;
510}
511
512/// Tests whether a conversion according to N2844 is valid.
513TryCastResult
514TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +0000515 unsigned &msg) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000516 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
517 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000518 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000519 if (!R)
520 return TC_NotApplicable;
521
522 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid)
523 return TC_NotApplicable;
524
525 // Because we try the reference downcast before this function, from now on
526 // this is the only cast possibility, so we issue an error if we fail now.
527 // FIXME: Should allow casting away constness if CStyle.
528 bool DerivedToBase;
529 if (Self.CompareReferenceRelationship(SrcExpr->getType(), R->getPointeeType(),
530 DerivedToBase) <
531 Sema::Ref_Compatible_With_Added_Qualification) {
532 msg = diag::err_bad_lvalue_to_rvalue_cast;
533 return TC_Failed;
534 }
535
536 // FIXME: Similar to CheckReferenceInit, we actually need more AST annotation
537 // than nothing.
538 return TC_Success;
539}
540
541/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
542TryCastResult
543TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
544 bool CStyle, const SourceRange &OpRange,
Mike Stump11289f42009-09-09 15:08:12 +0000545 unsigned &msg) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000546 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
547 // cast to type "reference to cv2 D", where D is a class derived from B,
548 // if a valid standard conversion from "pointer to D" to "pointer to B"
549 // exists, cv2 >= cv1, and B is not a virtual base class of D.
550 // In addition, DR54 clarifies that the base must be accessible in the
551 // current context. Although the wording of DR54 only applies to the pointer
552 // variant of this rule, the intent is clearly for it to apply to the this
553 // conversion as well.
554
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000555 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000556 if (!DestReference) {
557 return TC_NotApplicable;
558 }
559 bool RValueRef = DestReference->isRValueReferenceType();
560 if (!RValueRef && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
561 // We know the left side is an lvalue reference, so we can suggest a reason.
562 msg = diag::err_bad_cxx_cast_rvalue;
563 return TC_NotApplicable;
564 }
565
566 QualType DestPointee = DestReference->getPointeeType();
567
568 return TryStaticDowncast(Self, SrcExpr->getType(), DestPointee, CStyle,
569 OpRange, SrcExpr->getType(), DestType, msg);
570}
571
572/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
573TryCastResult
574TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
Mike Stump11289f42009-09-09 15:08:12 +0000575 bool CStyle, const SourceRange &OpRange,
576 unsigned &msg) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000577 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
578 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
579 // is a class derived from B, if a valid standard conversion from "pointer
580 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
581 // class of D.
582 // In addition, DR54 clarifies that the base must be accessible in the
583 // current context.
584
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000585 const PointerType *DestPointer = DestType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000586 if (!DestPointer) {
587 return TC_NotApplicable;
588 }
589
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000590 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000591 if (!SrcPointer) {
592 msg = diag::err_bad_static_cast_pointer_nonpointer;
593 return TC_NotApplicable;
594 }
595
596 return TryStaticDowncast(Self, SrcPointer->getPointeeType(),
597 DestPointer->getPointeeType(), CStyle,
598 OpRange, SrcType, DestType, msg);
599}
600
601/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
602/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
603/// DestType, both of which must be canonical, is possible and allowed.
604TryCastResult
605TryStaticDowncast(Sema &Self, QualType SrcType, QualType DestType,
606 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
Mike Stump11289f42009-09-09 15:08:12 +0000607 QualType OrigDestType, unsigned &msg) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000608 // Downcast can only happen in class hierarchies, so we need classes.
609 if (!DestType->isRecordType() || !SrcType->isRecordType()) {
610 return TC_NotApplicable;
611 }
612
Douglas Gregor36d1b142009-10-06 17:59:45 +0000613 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
614 /*DetectVirtual=*/true);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000615 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
616 return TC_NotApplicable;
617 }
618
619 // Target type does derive from source type. Now we're serious. If an error
620 // appears now, it's not ignored.
621 // This may not be entirely in line with the standard. Take for example:
622 // struct A {};
623 // struct B : virtual A {
624 // B(A&);
625 // };
Mike Stump11289f42009-09-09 15:08:12 +0000626 //
Sebastian Redl9f831db2009-07-25 15:41:38 +0000627 // void f()
628 // {
629 // (void)static_cast<const B&>(*((A*)0));
630 // }
631 // As far as the standard is concerned, p5 does not apply (A is virtual), so
632 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
633 // However, both GCC and Comeau reject this example, and accepting it would
634 // mean more complex code if we're to preserve the nice error message.
635 // FIXME: Being 100% compliant here would be nice to have.
636
637 // Must preserve cv, as always, unless we're in C-style mode.
638 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
639 msg = diag::err_bad_cxx_cast_const_away;
640 return TC_Failed;
641 }
642
643 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
644 // This code is analoguous to that in CheckDerivedToBaseConversion, except
645 // that it builds the paths in reverse order.
646 // To sum up: record all paths to the base and build a nice string from
647 // them. Use it to spice up the error message.
648 if (!Paths.isRecordingPaths()) {
649 Paths.clear();
650 Paths.setRecordingPaths(true);
651 Self.IsDerivedFrom(DestType, SrcType, Paths);
652 }
653 std::string PathDisplayStr;
654 std::set<unsigned> DisplayedPaths;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000655 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000656 PI != PE; ++PI) {
657 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
658 // We haven't displayed a path to this particular base
659 // class subobject yet.
660 PathDisplayStr += "\n ";
Douglas Gregor36d1b142009-10-06 17:59:45 +0000661 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
662 EE = PI->rend();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000663 EI != EE; ++EI)
664 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
665 PathDisplayStr += DestType.getAsString();
666 }
667 }
668
669 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
670 << SrcType.getUnqualifiedType() << DestType.getUnqualifiedType()
671 << PathDisplayStr << OpRange;
672 msg = 0;
673 return TC_Failed;
674 }
675
676 if (Paths.getDetectedVirtual() != 0) {
677 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
678 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
679 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
680 msg = 0;
681 return TC_Failed;
682 }
683
684 if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
685 diag::err_downcast_from_inaccessible_base, Paths,
686 OpRange.getBegin(), DeclarationName())) {
687 msg = 0;
688 return TC_Failed;
689 }
690
691 return TC_Success;
692}
693
694/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
695/// C++ 5.2.9p9 is valid:
696///
697/// An rvalue of type "pointer to member of D of type cv1 T" can be
698/// converted to an rvalue of type "pointer to member of B of type cv2 T",
699/// where B is a base class of D [...].
700///
701TryCastResult
702TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType, QualType DestType,
703 bool CStyle, const SourceRange &OpRange,
Mike Stump11289f42009-09-09 15:08:12 +0000704 unsigned &msg) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000705 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000706 if (!DestMemPtr)
707 return TC_NotApplicable;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000708 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000709 if (!SrcMemPtr) {
710 msg = diag::err_bad_static_cast_member_pointer_nonmp;
711 return TC_NotApplicable;
712 }
713
714 // T == T, modulo cv
715 if (Self.Context.getCanonicalType(
716 SrcMemPtr->getPointeeType().getUnqualifiedType()) !=
717 Self.Context.getCanonicalType(DestMemPtr->getPointeeType().
718 getUnqualifiedType()))
719 return TC_NotApplicable;
720
721 // B base of D
722 QualType SrcClass(SrcMemPtr->getClass(), 0);
723 QualType DestClass(DestMemPtr->getClass(), 0);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000724 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/!CStyle,
Sebastian Redl9f831db2009-07-25 15:41:38 +0000725 /*DetectVirtual=*/true);
726 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
727 return TC_NotApplicable;
728 }
729
730 // B is a base of D. But is it an allowed base? If not, it's a hard error.
731 if (Paths.isAmbiguous(DestClass)) {
732 Paths.clear();
733 Paths.setRecordingPaths(true);
734 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
735 assert(StillOkay);
736 StillOkay = StillOkay;
737 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
738 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
739 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
740 msg = 0;
741 return TC_Failed;
742 }
743
744 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
745 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
746 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
747 msg = 0;
748 return TC_Failed;
749 }
750
751 if (!CStyle && Self.CheckBaseClassAccess(DestType, SrcType,
752 diag::err_downcast_from_inaccessible_base, Paths,
753 OpRange.getBegin(), DeclarationName())) {
754 msg = 0;
755 return TC_Failed;
756 }
757
758 return TC_Success;
759}
760
761/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
762/// is valid:
763///
764/// An expression e can be explicitly converted to a type T using a
765/// @c static_cast if the declaration "T t(e);" is well-formed [...].
766TryCastResult
767TryStaticImplicitCast(Sema &Self, Expr *SrcExpr, QualType DestType,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +0000768 bool CStyle, const SourceRange &OpRange, unsigned &msg,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000769 CastExpr::CastKind &Kind,
Mike Stump11289f42009-09-09 15:08:12 +0000770 CXXMethodDecl *&ConversionDecl) {
Anders Carlsson85ec4ff2009-09-07 18:25:47 +0000771 if (DestType->isRecordType()) {
772 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
773 diag::err_bad_dynamic_cast_incomplete)) {
774 msg = 0;
775 return TC_Failed;
776 }
777 }
Mike Stump11289f42009-09-09 15:08:12 +0000778
Sebastian Redl9f831db2009-07-25 15:41:38 +0000779 if (DestType->isReferenceType()) {
780 // At this point of CheckStaticCast, if the destination is a reference,
781 // this has to work. There is no other way that works.
782 // On the other hand, if we're checking a C-style cast, we've still got
783 // the reinterpret_cast way. In that case, we pass an ICS so we don't
784 // get error messages.
785 ImplicitConversionSequence ICS;
Mike Stump11289f42009-09-09 15:08:12 +0000786 bool failed = Self.CheckReferenceInit(SrcExpr, DestType,
Douglas Gregorc809cc22009-09-23 23:04:10 +0000787 OpRange.getBegin(),
Anders Carlsson271e3a42009-08-27 17:30:43 +0000788 /*SuppressUserConversions=*/false,
789 /*AllowExplicit=*/false,
790 /*ForceRValue=*/false,
791 CStyle ? &ICS : 0);
Sebastian Redl9f831db2009-07-25 15:41:38 +0000792 if (!failed)
793 return TC_Success;
794 if (CStyle)
795 return TC_NotApplicable;
796 // If we didn't pass the ICS, we already got an error message.
797 msg = 0;
798 return TC_Failed;
799 }
Sebastian Redl9f831db2009-07-25 15:41:38 +0000800
801 // FIXME: To get a proper error from invalid conversions here, we need to
802 // reimplement more of this.
803 // FIXME: This does not actually perform the conversion, and thus does not
804 // check for ambiguity or access.
Mike Stump11289f42009-09-09 15:08:12 +0000805 ImplicitConversionSequence ICS =
Anders Carlssonef4c7212009-08-27 17:24:15 +0000806 Self.TryImplicitConversion(SrcExpr, DestType,
807 /*SuppressUserConversions=*/false,
Anders Carlssonf2bc7c32009-08-28 16:22:20 +0000808 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +0000809 /*ForceRValue=*/false,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000810 /*InOverloadResolution=*/false,
811 /*one of user provided casts*/true);
Mike Stump11289f42009-09-09 15:08:12 +0000812
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000813 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
814 return TC_NotApplicable;
815
Anders Carlssone9766d52009-09-09 21:33:21 +0000816 if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion) {
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000817 ConversionDecl = cast<CXXMethodDecl>(ICS.UserDefined.ConversionFunction);
818 if (isa<CXXConstructorDecl>(ConversionDecl))
819 Kind = CastExpr::CK_ConstructorConversion;
820 else if (isa<CXXConversionDecl>(ConversionDecl))
821 Kind = CastExpr::CK_UserDefinedConversion;
822 } else if (ICS.ConversionKind ==
823 ImplicitConversionSequence::StandardConversion) {
824 // FIXME: Set the cast kind depending on which types of conversions we have.
Anders Carlssone9766d52009-09-09 21:33:21 +0000825 }
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000826
827 return TC_Success;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000828}
829
830/// TryConstCast - See if a const_cast from source to destination is allowed,
831/// and perform it if it is.
832static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
833 bool CStyle, unsigned &msg) {
834 DestType = Self.Context.getCanonicalType(DestType);
835 QualType SrcType = SrcExpr->getType();
836 if (const LValueReferenceType *DestTypeTmp =
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000837 DestType->getAs<LValueReferenceType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000838 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
839 // Cannot const_cast non-lvalue to lvalue reference type. But if this
840 // is C-style, static_cast might find a way, so we simply suggest a
841 // message and tell the parent to keep searching.
842 msg = diag::err_bad_cxx_cast_rvalue;
843 return TC_NotApplicable;
844 }
845
846 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
847 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
848 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
849 SrcType = Self.Context.getPointerType(SrcType);
850 }
851
852 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
853 // the rules for const_cast are the same as those used for pointers.
854
855 if (!DestType->isPointerType() && !DestType->isMemberPointerType()) {
856 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
857 // was a reference type, we converted it to a pointer above.
858 // The status of rvalue references isn't entirely clear, but it looks like
859 // conversion to them is simply invalid.
860 // C++ 5.2.11p3: For two pointer types [...]
861 if (!CStyle)
862 msg = diag::err_bad_const_cast_dest;
863 return TC_NotApplicable;
864 }
865 if (DestType->isFunctionPointerType() ||
866 DestType->isMemberFunctionPointerType()) {
867 // Cannot cast direct function pointers.
868 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
869 // T is the ultimate pointee of source and target type.
870 if (!CStyle)
871 msg = diag::err_bad_const_cast_dest;
872 return TC_NotApplicable;
873 }
874 SrcType = Self.Context.getCanonicalType(SrcType);
875
876 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
877 // completely equal.
878 // FIXME: const_cast should probably not be able to convert between pointers
879 // to different address spaces.
880 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
881 // in multi-level pointers may change, but the level count must be the same,
882 // as must be the final pointee type.
883 while (SrcType != DestType &&
884 Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
885 SrcType = SrcType.getUnqualifiedType();
886 DestType = DestType.getUnqualifiedType();
887 }
888
889 // Since we're dealing in canonical types, the remainder must be the same.
890 if (SrcType != DestType)
891 return TC_NotApplicable;
892
893 return TC_Success;
894}
895
896static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
897 QualType DestType, bool CStyle,
898 const SourceRange &OpRange,
Anders Carlsson9d1b34b2009-09-26 00:12:34 +0000899 unsigned &msg,
900 CastExpr::CastKind &Kind) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000901 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
902
903 DestType = Self.Context.getCanonicalType(DestType);
904 QualType SrcType = SrcExpr->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000905 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
Sebastian Redl9f831db2009-07-25 15:41:38 +0000906 bool LValue = DestTypeTmp->isLValueReferenceType();
907 if (LValue && SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
908 // Cannot cast non-lvalue to reference type. See the similar comment in
909 // const_cast.
910 msg = diag::err_bad_cxx_cast_rvalue;
911 return TC_NotApplicable;
912 }
913
914 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
915 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
916 // built-in & and * operators.
917 // This code does this transformation for the checked types.
918 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
919 SrcType = Self.Context.getPointerType(SrcType);
920 }
921
922 // Canonicalize source for comparison.
923 SrcType = Self.Context.getCanonicalType(SrcType);
924
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000925 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
926 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
Sebastian Redl9f831db2009-07-25 15:41:38 +0000927 if (DestMemPtr && SrcMemPtr) {
928 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
929 // can be explicitly converted to an rvalue of type "pointer to member
930 // of Y of type T2" if T1 and T2 are both function types or both object
931 // types.
932 if (DestMemPtr->getPointeeType()->isFunctionType() !=
933 SrcMemPtr->getPointeeType()->isFunctionType())
934 return TC_NotApplicable;
935
936 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
937 // constness.
938 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
939 // we accept it.
940 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
941 msg = diag::err_bad_cxx_cast_const_away;
942 return TC_Failed;
943 }
944
945 // A valid member pointer cast.
Anders Carlsson9500ad12009-10-18 20:31:03 +0000946 Kind = CastExpr::CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000947 return TC_Success;
948 }
949
950 // See below for the enumeral issue.
951 if (SrcType->isNullPtrType() && DestType->isIntegralType() &&
952 !DestType->isEnumeralType()) {
953 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
954 // type large enough to hold it. A value of std::nullptr_t can be
955 // converted to an integral type; the conversion has the same meaning
956 // and validity as a conversion of (void*)0 to the integral type.
957 if (Self.Context.getTypeSize(SrcType) >
958 Self.Context.getTypeSize(DestType)) {
959 msg = diag::err_bad_reinterpret_cast_small_int;
960 return TC_Failed;
961 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +0000962 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +0000963 return TC_Success;
964 }
965
Anders Carlsson570af5d2009-09-16 19:19:43 +0000966 bool destIsVector = DestType->isVectorType();
967 bool srcIsVector = SrcType->isVectorType();
968 if (srcIsVector || destIsVector) {
969 bool srcIsScalar = SrcType->isIntegralType() && !SrcType->isEnumeralType();
970 bool destIsScalar =
971 DestType->isIntegralType() && !DestType->isEnumeralType();
972
973 // Check if this is a cast between a vector and something else.
974 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
975 !(srcIsVector && destIsVector))
976 return TC_NotApplicable;
977
978 // If both types have the same size, we can successfully cast.
979 if (Self.Context.getTypeSize(SrcType) == Self.Context.getTypeSize(DestType))
980 return TC_Success;
981
982 if (destIsScalar)
983 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
984 else if (srcIsScalar)
985 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
986 else
987 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
988
989 return TC_Failed;
990 }
991
Sebastian Redl9f831db2009-07-25 15:41:38 +0000992 bool destIsPtr = DestType->isPointerType();
993 bool srcIsPtr = SrcType->isPointerType();
994 if (!destIsPtr && !srcIsPtr) {
995 // Except for std::nullptr_t->integer and lvalue->reference, which are
996 // handled above, at least one of the two arguments must be a pointer.
997 return TC_NotApplicable;
998 }
999
1000 if (SrcType == DestType) {
1001 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1002 // restrictions, a cast to the same type is allowed. The intent is not
1003 // entirely clear here, since all other paragraphs explicitly forbid casts
1004 // to the same type. However, the behavior of compilers is pretty consistent
1005 // on this point: allow same-type conversion if the involved types are
1006 // pointers, disallow otherwise.
1007 return TC_Success;
1008 }
1009
1010 // Note: Clang treats enumeration types as integral types. If this is ever
1011 // changed for C++, the additional check here will be redundant.
1012 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
1013 assert(srcIsPtr && "One type must be a pointer");
1014 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1015 // type large enough to hold it.
1016 if (Self.Context.getTypeSize(SrcType) >
1017 Self.Context.getTypeSize(DestType)) {
1018 msg = diag::err_bad_reinterpret_cast_small_int;
1019 return TC_Failed;
1020 }
Anders Carlsson7cd39e02009-09-15 04:48:33 +00001021 Kind = CastExpr::CK_PointerToIntegral;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001022 return TC_Success;
1023 }
1024
1025 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
1026 assert(destIsPtr && "One type must be a pointer");
1027 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1028 // converted to a pointer.
Anders Carlsson7cd39e02009-09-15 04:48:33 +00001029 Kind = CastExpr::CK_IntegralToPointer;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001030 return TC_Success;
1031 }
1032
1033 if (!destIsPtr || !srcIsPtr) {
1034 // With the valid non-pointer conversions out of the way, we can be even
1035 // more stringent.
1036 return TC_NotApplicable;
1037 }
1038
1039 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1040 // The C-style cast operator can.
1041 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1042 msg = diag::err_bad_cxx_cast_const_away;
1043 return TC_Failed;
1044 }
1045
1046 // Not casting away constness, so the only remaining check is for compatible
1047 // pointer categories.
Anders Carlsson9500ad12009-10-18 20:31:03 +00001048 Kind = CastExpr::CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001049
1050 if (SrcType->isFunctionPointerType()) {
1051 if (DestType->isFunctionPointerType()) {
1052 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1053 // a pointer to a function of a different type.
1054 return TC_Success;
1055 }
1056
1057 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1058 // an object type or vice versa is conditionally-supported.
1059 // Compilers support it in C++03 too, though, because it's necessary for
1060 // casting the return value of dlsym() and GetProcAddress().
1061 // FIXME: Conditionally-supported behavior should be configurable in the
1062 // TargetInfo or similar.
1063 if (!Self.getLangOptions().CPlusPlus0x)
1064 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1065 return TC_Success;
1066 }
1067
1068 if (DestType->isFunctionPointerType()) {
1069 // See above.
1070 if (!Self.getLangOptions().CPlusPlus0x)
1071 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1072 return TC_Success;
1073 }
1074
1075 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1076 // a pointer to an object of different type.
1077 // Void pointers are not specified, but supported by every compiler out there.
1078 // So we finish by allowing everything that remains - it's got to be two
1079 // object pointers.
Anders Carlssonf1ae6d42009-09-01 20:52:42 +00001080 Kind = CastExpr::CK_BitCast;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001081 return TC_Success;
1082}
1083
Sebastian Redl955a0672009-07-29 13:50:23 +00001084bool Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, Expr *&CastExpr,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00001085 CastExpr::CastKind &Kind, bool FunctionalStyle,
Mike Stump11289f42009-09-09 15:08:12 +00001086 CXXMethodDecl *&ConversionDecl) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00001087 // This test is outside everything else because it's the only case where
1088 // a non-lvalue-reference target type does not lead to decay.
1089 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
Anders Carlsson9500ad12009-10-18 20:31:03 +00001090 if (CastTy->isVoidType()) {
1091 Kind = CastExpr::CK_ToVoid;
Sebastian Redl9f831db2009-07-25 15:41:38 +00001092 return false;
Anders Carlsson9500ad12009-10-18 20:31:03 +00001093 }
Sebastian Redl9f831db2009-07-25 15:41:38 +00001094
1095 // If the type is dependent, we won't do any other semantic analysis now.
1096 if (CastTy->isDependentType() || CastExpr->isTypeDependent())
1097 return false;
1098
1099 if (!CastTy->isLValueReferenceType())
1100 DefaultFunctionArrayConversion(CastExpr);
1101
1102 // C++ [expr.cast]p5: The conversions performed by
1103 // - a const_cast,
1104 // - a static_cast,
1105 // - a static_cast followed by a const_cast,
1106 // - a reinterpret_cast, or
1107 // - a reinterpret_cast followed by a const_cast,
1108 // can be performed using the cast notation of explicit type conversion.
1109 // [...] If a conversion can be interpreted in more than one of the ways
1110 // listed above, the interpretation that appears first in the list is used,
1111 // even if a cast resulting from that interpretation is ill-formed.
1112 // In plain language, this means trying a const_cast ...
1113 unsigned msg = diag::err_bad_cxx_cast_generic;
Anders Carlssonf1ae6d42009-09-01 20:52:42 +00001114 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1115 msg);
Anders Carlsson027732b2009-10-19 18:14:28 +00001116 if (tcr == TC_Success)
1117 Kind = CastExpr::CK_NoOp;
1118
Sebastian Redl9f831db2009-07-25 15:41:38 +00001119 if (tcr == TC_NotApplicable) {
1120 // ... or if that is not possible, a static_cast, ignoring const, ...
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001121 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1122 Kind, ConversionDecl);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001123 if (tcr == TC_NotApplicable) {
1124 // ... and finally a reinterpret_cast, ignoring const.
Anders Carlsson9d1b34b2009-09-26 00:12:34 +00001125 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1126 Kind);
Sebastian Redl9f831db2009-07-25 15:41:38 +00001127 }
1128 }
1129
Sebastian Redl9f831db2009-07-25 15:41:38 +00001130 if (tcr != TC_Success && msg != 0)
Sebastian Redl955a0672009-07-29 13:50:23 +00001131 Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
Sebastian Redl9f831db2009-07-25 15:41:38 +00001132 << CastExpr->getType() << CastTy << R;
1133
1134 return tcr != TC_Success;
1135}