blob: bffdb3f7f604d74003ef0eb38eb8825318349dd1 [file] [log] [blame]
Sebastian Redl2b6b14c2008-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"
15#include "SemaInherit.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/Basic/Diagnostic.h"
19#include "llvm/ADT/SmallVector.h"
Sebastian Redl0528e1c2008-11-07 23:29:29 +000020#include <set>
Sebastian Redl2b6b14c2008-11-05 21:50:06 +000021using namespace clang;
22
Sebastian Redlf831eeb2008-11-08 13:00:26 +000023enum TryStaticCastResult {
24 TSC_NotApplicable, ///< The cast method is not applicable.
25 TSC_Success, ///< The cast method is appropriate and successful.
26 TSC_Failed ///< The cast method is appropriate, but failed. A
27 ///< diagnostic has been emitted.
28};
29
30static void CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
31 const SourceRange &OpRange,
32 const SourceRange &DestRange);
33static void CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
34 const SourceRange &OpRange,
35 const SourceRange &DestRange);
36static void CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
37 const SourceRange &OpRange);
38static void CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
39 const SourceRange &OpRange,
40 const SourceRange &DestRange);
41
42static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
43static TryStaticCastResult TryStaticReferenceDowncast(
44 Sema &Self, Expr *SrcExpr, QualType DestType, const SourceRange &OpRange);
45static TryStaticCastResult TryStaticPointerDowncast(
46 Sema &Self, QualType SrcType, QualType DestType, const SourceRange &OpRange);
47static TryStaticCastResult TryStaticDowncast(Sema &Self, QualType SrcType,
48 QualType DestType,
49 const SourceRange &OpRange,
50 QualType OrigSrcType,
51 QualType OrigDestType);
52static TryStaticCastResult TryStaticImplicitCast(Sema &Self, Expr *SrcExpr,
53 QualType DestType,
54 const SourceRange &OpRange);
55
Sebastian Redl2b6b14c2008-11-05 21:50:06 +000056/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
57Action::ExprResult
58Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
59 SourceLocation LAngleBracketLoc, TypeTy *Ty,
60 SourceLocation RAngleBracketLoc,
61 SourceLocation LParenLoc, ExprTy *E,
62 SourceLocation RParenLoc) {
63 Expr *Ex = (Expr*)E;
64 QualType DestType = QualType::getFromOpaquePtr(Ty);
65 SourceRange OpRange(OpLoc, RParenLoc);
66 SourceRange DestRange(LAngleBracketLoc, RAngleBracketLoc);
67
68 switch (Kind) {
69 default: assert(0 && "Unknown C++ cast!");
70
71 case tok::kw_const_cast:
Sebastian Redlf831eeb2008-11-08 13:00:26 +000072 CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +000073 return new CXXConstCastExpr(DestType.getNonReferenceType(), Ex,
74 DestType, OpLoc);
75
76 case tok::kw_dynamic_cast:
Sebastian Redlf831eeb2008-11-08 13:00:26 +000077 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +000078 return new CXXDynamicCastExpr(DestType.getNonReferenceType(), Ex,
79 DestType, OpLoc);
80
81 case tok::kw_reinterpret_cast:
Sebastian Redlf831eeb2008-11-08 13:00:26 +000082 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +000083 return new CXXReinterpretCastExpr(DestType.getNonReferenceType(), Ex,
84 DestType, OpLoc);
85
86 case tok::kw_static_cast:
Sebastian Redlf831eeb2008-11-08 13:00:26 +000087 CheckStaticCast(*this, Ex, DestType, OpRange);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +000088 return new CXXStaticCastExpr(DestType.getNonReferenceType(), Ex,
89 DestType, OpLoc);
90 }
91
92 return true;
93}
94
95/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
96/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
97/// like this:
98/// const char *str = "literal";
99/// legacy_function(const_cast\<char*\>(str));
100void
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000101CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
102 const SourceRange &OpRange, const SourceRange &DestRange)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000103{
104 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
105
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000106 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000107 QualType SrcType = SrcExpr->getType();
108 if (const ReferenceType *DestTypeTmp = DestType->getAsReferenceType()) {
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000109 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000110 // Cannot cast non-lvalue to reference type.
Chris Lattner70b93d82008-11-18 22:52:51 +0000111 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
112 << "const_cast" << OrigDestType.getAsString()
113 << SrcExpr->getSourceRange();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000114 return;
115 }
116
117 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
118 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000119 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
120 SrcType = Self.Context.getPointerType(SrcType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000121 } else {
122 // C++ 5.2.11p1: Otherwise, the result is an rvalue and the
123 // lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
124 // conversions are performed on the expression.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000125 Self.DefaultFunctionArrayConversion(SrcExpr);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000126 SrcType = SrcExpr->getType();
127 }
128
129 if (!DestType->isPointerType()) {
130 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
131 // was a reference type, we converted it to a pointer above.
132 // C++ 5.2.11p3: For two pointer types [...]
Chris Lattner70b93d82008-11-18 22:52:51 +0000133 Self.Diag(OpRange.getBegin(), diag::err_bad_const_cast_dest)
134 << OrigDestType.getAsString() << DestRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000135 return;
136 }
137 if (DestType->isFunctionPointerType()) {
138 // Cannot cast direct function pointers.
139 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
140 // T is the ultimate pointee of source and target type.
Chris Lattner70b93d82008-11-18 22:52:51 +0000141 Self.Diag(OpRange.getBegin(), diag::err_bad_const_cast_dest)
142 << OrigDestType.getAsString() << DestRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000143 return;
144 }
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000145 SrcType = Self.Context.getCanonicalType(SrcType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000146
147 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
148 // completely equal.
149 // FIXME: const_cast should probably not be able to convert between pointers
150 // to different address spaces.
151 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
152 // in multi-level pointers may change, but the level count must be the same,
153 // as must be the final pointee type.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000154 while (SrcType != DestType &&
155 Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000156 SrcType = SrcType.getUnqualifiedType();
157 DestType = DestType.getUnqualifiedType();
158 }
159
160 // Doug Gregor said to disallow this until users complain.
161#if 0
162 // If we end up with constant arrays of equal size, unwrap those too. A cast
163 // from const int [N] to int (&)[N] is invalid by my reading of the
164 // standard, but g++ accepts it even with -ansi -pedantic.
165 // No more than one level, though, so don't embed this in the unwrap loop
166 // above.
167 const ConstantArrayType *SrcTypeArr, *DestTypeArr;
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000168 if ((SrcTypeArr = Self.Context.getAsConstantArrayType(SrcType)) &&
169 (DestTypeArr = Self.Context.getAsConstantArrayType(DestType)))
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000170 {
171 if (SrcTypeArr->getSize() != DestTypeArr->getSize()) {
172 // Different array sizes.
Chris Lattner70b93d82008-11-18 22:52:51 +0000173 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
174 << "const_cast" << OrigDestType.getAsString()
175 << OrigSrcType.getAsString() << OpRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000176 return;
177 }
178 SrcType = SrcTypeArr->getElementType().getUnqualifiedType();
179 DestType = DestTypeArr->getElementType().getUnqualifiedType();
180 }
181#endif
182
183 // Since we're dealing in canonical types, the remainder must be the same.
184 if (SrcType != DestType) {
185 // Cast between unrelated types.
Chris Lattner70b93d82008-11-18 22:52:51 +0000186 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
187 << "const_cast" << OrigDestType.getAsString()
188 << OrigSrcType.getAsString() << OpRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000189 return;
190 }
191}
192
193/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
194/// valid.
195/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
196/// like this:
197/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
198void
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000199CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
200 const SourceRange &OpRange, const SourceRange &DestRange)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000201{
202 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
203
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000204 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000205 QualType SrcType = SrcExpr->getType();
206 if (const ReferenceType *DestTypeTmp = DestType->getAsReferenceType()) {
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000207 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000208 // Cannot cast non-lvalue to reference type.
Chris Lattner70b93d82008-11-18 22:52:51 +0000209 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
210 << "reinterpret_cast" << OrigDestType.getAsString()
211 << SrcExpr->getSourceRange();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000212 return;
213 }
214
215 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
216 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
217 // built-in & and * operators.
218 // This code does this transformation for the checked types.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000219 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
220 SrcType = Self.Context.getPointerType(SrcType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000221 } else {
222 // C++ 5.2.10p1: [...] the lvalue-to-rvalue, array-to-pointer, and
223 // function-to-pointer standard conversions are performed on the
224 // expression v.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000225 Self.DefaultFunctionArrayConversion(SrcExpr);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000226 SrcType = SrcExpr->getType();
227 }
228
229 // Canonicalize source for comparison.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000230 SrcType = Self.Context.getCanonicalType(SrcType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000231
232 bool destIsPtr = DestType->isPointerType();
233 bool srcIsPtr = SrcType->isPointerType();
234 if (!destIsPtr && !srcIsPtr) {
235 // Except for std::nullptr_t->integer, which is not supported yet, and
236 // lvalue->reference, which is handled above, at least one of the two
237 // arguments must be a pointer.
Chris Lattner70b93d82008-11-18 22:52:51 +0000238 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
239 << "reinterpret_cast" << OrigDestType.getAsString()
240 << OrigSrcType.getAsString() << OpRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000241 return;
242 }
243
244 if (SrcType == DestType) {
245 // C++ 5.2.10p2 has a note that mentions that, subject to all other
246 // restrictions, a cast to the same type is allowed. The intent is not
247 // entirely clear here, since all other paragraphs explicitly forbid casts
248 // to the same type. However, the behavior of compilers is pretty consistent
249 // on this point: allow same-type conversion if the involved are pointers,
250 // disallow otherwise.
251 return;
252 }
253
254 // Note: Clang treats enumeration types as integral types. If this is ever
255 // changed for C++, the additional check here will be redundant.
256 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
Sebastian Redldbed5902008-11-05 22:15:14 +0000257 assert(srcIsPtr && "One type must be a pointer");
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000258 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
259 // type large enough to hold it.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000260 if (Self.Context.getTypeSize(SrcType) >
261 Self.Context.getTypeSize(DestType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +0000262 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_small_int)
263 << OrigDestType.getAsString() << DestRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000264 }
265 return;
266 }
267
268 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
Sebastian Redldbed5902008-11-05 22:15:14 +0000269 assert(destIsPtr && "One type must be a pointer");
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000270 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
271 // converted to a pointer.
272 return;
273 }
274
275 if (!destIsPtr || !srcIsPtr) {
276 // With the valid non-pointer conversions out of the way, we can be even
277 // more stringent.
Chris Lattner70b93d82008-11-18 22:52:51 +0000278 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
279 << "reinterpret_cast" << OrigDestType.getAsString()
280 << OrigSrcType.getAsString() << OpRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000281 return;
282 }
283
284 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000285 if (CastsAwayConstness(Self, SrcType, DestType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +0000286 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
287 << "reinterpret_cast" << OrigDestType.getAsString()
288 << OrigSrcType.getAsString() << OpRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000289 return;
290 }
291
292 // Not casting away constness, so the only remaining check is for compatible
293 // pointer categories.
294
295 if (SrcType->isFunctionPointerType()) {
296 if (DestType->isFunctionPointerType()) {
297 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
298 // a pointer to a function of a different type.
299 return;
300 }
301
302 // FIXME: Handle member pointers.
303
304 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
305 // an object type or vice versa is conditionally-supported.
306 // Compilers support it in C++03 too, though, because it's necessary for
307 // casting the return value of dlsym() and GetProcAddress().
308 // FIXME: Conditionally-supported behavior should be configurable in the
309 // TargetInfo or similar.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000310 if (!Self.getLangOptions().CPlusPlus0x) {
Chris Lattner70b93d82008-11-18 22:52:51 +0000311 Self.Diag(OpRange.getBegin(), diag::ext_reinterpret_cast_fn_obj)
312 << OpRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000313 }
314 return;
315 }
316
317 // FIXME: Handle member pointers.
318
319 if (DestType->isFunctionPointerType()) {
320 // See above.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000321 if (!Self.getLangOptions().CPlusPlus0x) {
Chris Lattner70b93d82008-11-18 22:52:51 +0000322 Self.Diag(OpRange.getBegin(), diag::ext_reinterpret_cast_fn_obj)
323 << OpRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000324 }
325 return;
326 }
327
328 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
329 // a pointer to an object of different type.
330 // Void pointers are not specified, but supported by every compiler out there.
331 // So we finish by allowing everything that remains - it's got to be two
332 // object pointers.
333}
334
335/// CastsAwayConstness - Check if the pointer conversion from SrcType
336/// to DestType casts away constness as defined in C++
337/// 5.2.11p8ff. This is used by the cast checkers. Both arguments
338/// must denote pointer types.
339bool
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000340CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000341{
342 // Casting away constness is defined in C++ 5.2.11p8 with reference to
343 // C++ 4.4.
344 // We piggyback on Sema::IsQualificationConversion for this, since the rules
345 // are non-trivial. So first we construct Tcv *...cv* as described in
346 // C++ 5.2.11p8.
347
348 QualType UnwrappedSrcType = SrcType, UnwrappedDestType = DestType;
349 llvm::SmallVector<unsigned, 8> cv1, cv2;
350
351 // Find the qualifications.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000352 while (Self.UnwrapSimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000353 cv1.push_back(UnwrappedSrcType.getCVRQualifiers());
354 cv2.push_back(UnwrappedDestType.getCVRQualifiers());
355 }
356 assert(cv1.size() > 0 && "Must have at least one pointer level.");
357
358 // Construct void pointers with those qualifiers (in reverse order of
359 // unwrapping, of course).
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000360 QualType SrcConstruct = Self.Context.VoidTy;
361 QualType DestConstruct = Self.Context.VoidTy;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000362 for (llvm::SmallVector<unsigned, 8>::reverse_iterator i1 = cv1.rbegin(),
363 i2 = cv2.rbegin();
364 i1 != cv1.rend(); ++i1, ++i2)
365 {
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000366 SrcConstruct = Self.Context.getPointerType(
367 SrcConstruct.getQualifiedType(*i1));
368 DestConstruct = Self.Context.getPointerType(
369 DestConstruct.getQualifiedType(*i2));
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000370 }
371
372 // Test if they're compatible.
373 return SrcConstruct != DestConstruct &&
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000374 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000375}
376
377/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
378/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
379/// implicit conversions explicit and getting rid of data loss warnings.
380void
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000381CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
382 const SourceRange &OpRange)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000383{
384 // The order the tests is not entirely arbitrary. There is one conversion
385 // that can be handled in two different ways. Given:
386 // struct A {};
387 // struct B : public A {
388 // B(); B(const A&);
389 // };
390 // const A &a = B();
391 // the cast static_cast<const B&>(a) could be seen as either a static
392 // reference downcast, or an explicit invocation of the user-defined
393 // conversion using B's conversion constructor.
394 // DR 427 specifies that the downcast is to be applied here.
395
396 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
397 if (DestType->isVoidType()) {
398 return;
399 }
400
401 // C++ 5.2.9p5, reference downcast.
402 // See the function for details.
403 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000404 if (TryStaticReferenceDowncast(Self, SrcExpr, DestType, OpRange)
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000405 > TSC_NotApplicable) {
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000406 return;
407 }
408
409 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
410 // [...] if the declaration "T t(e);" is well-formed, [...].
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000411 if (TryStaticImplicitCast(Self, SrcExpr, DestType, OpRange) >
412 TSC_NotApplicable) {
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000413 return;
414 }
415
416 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
417 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
418 // conversions, subject to further restrictions.
419 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
420 // of qualification conversions impossible.
421
422 // The lvalue-to-rvalue, array-to-pointer and function-to-pointer conversions
423 // are applied to the expression.
424 QualType OrigSrcType = SrcExpr->getType();
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000425 Self.DefaultFunctionArrayConversion(SrcExpr);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000426
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000427 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000428
429 // Reverse integral promotion/conversion. All such conversions are themselves
430 // again integral promotions or conversions and are thus already handled by
431 // p2 (TryDirectInitialization above).
432 // (Note: any data loss warnings should be suppressed.)
433 // The exception is the reverse of enum->integer, i.e. integer->enum (and
434 // enum->enum). See also C++ 5.2.9p7.
435 // The same goes for reverse floating point promotion/conversion and
436 // floating-integral conversions. Again, only floating->enum is relevant.
437 if (DestType->isEnumeralType()) {
438 if (SrcType->isComplexType() || SrcType->isVectorType()) {
439 // Fall through - these cannot be converted.
440 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
441 return;
442 }
443 }
444
445 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
446 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000447 if (TryStaticPointerDowncast(Self, SrcType, DestType, OpRange)
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000448 > TSC_NotApplicable) {
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000449 return;
450 }
451
452 // Reverse member pointer conversion. C++ 5.11 specifies member pointer
453 // conversion. C++ 5.2.9p9 has additional information.
454 // DR54's access restrictions apply here also.
455 // FIXME: Don't have member pointers yet.
456
457 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
458 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
459 // just the usual constness stuff.
460 if (const PointerType *SrcPointer = SrcType->getAsPointerType()) {
461 QualType SrcPointee = SrcPointer->getPointeeType();
462 if (SrcPointee->isVoidType()) {
463 if (const PointerType *DestPointer = DestType->getAsPointerType()) {
464 QualType DestPointee = DestPointer->getPointeeType();
465 if (DestPointee->isObjectType()) {
466 // This is definitely the intended conversion, but it might fail due
467 // to a const violation.
468 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +0000469 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
470 << "static_cast" << DestType.getAsString()
471 << OrigSrcType.getAsString() << OpRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000472 }
473 return;
474 }
475 }
476 }
477 }
478
479 // We tried everything. Everything! Nothing works! :-(
480 // FIXME: Error reporting could be a lot better. Should store the reason
481 // why every substep failed and, at the end, select the most specific and
482 // report that.
Chris Lattner70b93d82008-11-18 22:52:51 +0000483 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
484 << "static_cast" << DestType.getAsString() << OrigSrcType.getAsString()
485 << OpRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000486}
487
488/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000489TryStaticCastResult
490TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
491 const SourceRange &OpRange)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000492{
493 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
494 // cast to type "reference to cv2 D", where D is a class derived from B,
495 // if a valid standard conversion from "pointer to D" to "pointer to B"
496 // exists, cv2 >= cv1, and B is not a virtual base class of D.
497 // In addition, DR54 clarifies that the base must be accessible in the
498 // current context. Although the wording of DR54 only applies to the pointer
499 // variant of this rule, the intent is clearly for it to apply to the this
500 // conversion as well.
501
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000502 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000503 return TSC_NotApplicable;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000504 }
505
506 const ReferenceType *DestReference = DestType->getAsReferenceType();
507 if (!DestReference) {
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000508 return TSC_NotApplicable;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000509 }
510 QualType DestPointee = DestReference->getPointeeType();
511
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000512 return TryStaticDowncast(Self, SrcExpr->getType(), DestPointee, OpRange,
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000513 SrcExpr->getType(), DestType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000514}
515
516/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000517TryStaticCastResult
518TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
519 const SourceRange &OpRange)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000520{
521 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
522 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
523 // is a class derived from B, if a valid standard conversion from "pointer
524 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
525 // class of D.
526 // In addition, DR54 clarifies that the base must be accessible in the
527 // current context.
528
529 const PointerType *SrcPointer = SrcType->getAsPointerType();
530 if (!SrcPointer) {
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000531 return TSC_NotApplicable;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000532 }
533
534 const PointerType *DestPointer = DestType->getAsPointerType();
535 if (!DestPointer) {
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000536 return TSC_NotApplicable;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000537 }
538
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000539 return TryStaticDowncast(Self, SrcPointer->getPointeeType(),
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000540 DestPointer->getPointeeType(),
541 OpRange, SrcType, DestType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000542}
543
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000544/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
545/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000546/// DestType, both of which must be canonical, is possible and allowed.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000547TryStaticCastResult
548TryStaticDowncast(Sema &Self, QualType SrcType, QualType DestType,
549 const SourceRange &OpRange, QualType OrigSrcType,
550 QualType OrigDestType)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000551{
552 // Downcast can only happen in class hierarchies, so we need classes.
553 if (!DestType->isRecordType() || !SrcType->isRecordType()) {
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000554 return TSC_NotApplicable;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000555 }
556
557 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
558 /*DetectVirtual=*/true);
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000559 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000560 return TSC_NotApplicable;
561 }
562
563 // Target type does derive from source type. Now we're serious. If an error
564 // appears now, it's not ignored.
565 // This may not be entirely in line with the standard. Take for example:
566 // struct A {};
567 // struct B : virtual A {
568 // B(A&);
569 // };
570 //
571 // void f()
572 // {
573 // (void)static_cast<const B&>(*((A*)0));
574 // }
575 // As far as the standard is concerned, p5 does not apply (A is virtual), so
576 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
577 // However, both GCC and Comeau reject this example, and accepting it would
578 // mean more complex code if we're to preserve the nice error message.
579 // FIXME: Being 100% compliant here would be nice to have.
580
581 // Must preserve cv, as always.
582 if (!DestType.isAtLeastAsQualifiedAs(SrcType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +0000583 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
584 << "static_cast" << OrigDestType.getAsString()
585 << OrigSrcType.getAsString() << OpRange;
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000586 return TSC_Failed;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000587 }
588
589 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000590 // This code is analoguous to that in CheckDerivedToBaseConversion, except
591 // that it builds the paths in reverse order.
592 // To sum up: record all paths to the base and build a nice string from
593 // them. Use it to spice up the error message.
594 Paths.clear();
595 Paths.setRecordingPaths(true);
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000596 Self.IsDerivedFrom(DestType, SrcType, Paths);
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000597 std::string PathDisplayStr;
598 std::set<unsigned> DisplayedPaths;
599 for (BasePaths::paths_iterator Path = Paths.begin();
600 Path != Paths.end(); ++Path) {
601 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
602 // We haven't displayed a path to this particular base
603 // class subobject yet.
604 PathDisplayStr += "\n ";
605 for (BasePath::const_reverse_iterator Element = Path->rbegin();
606 Element != Path->rend(); ++Element)
607 PathDisplayStr += Element->Base->getType().getAsString() + " -> ";
608 PathDisplayStr += DestType.getAsString();
609 }
610 }
611
Chris Lattner70b93d82008-11-18 22:52:51 +0000612 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
613 << SrcType.getUnqualifiedType().getAsString()
614 << DestType.getUnqualifiedType().getAsString()
615 << PathDisplayStr << OpRange;
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000616 return TSC_Failed;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000617 }
618
619 if (Paths.getDetectedVirtual() != 0) {
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000620 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
Chris Lattner70b93d82008-11-18 22:52:51 +0000621 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
622 << OrigSrcType.getAsString() << OrigDestType.getAsString()
623 << VirtualBase.getAsString() << OpRange;
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000624 return TSC_Failed;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000625 }
626
627 // FIXME: Test accessibility.
628
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000629 return TSC_Success;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000630}
631
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000632/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
633/// is valid:
634///
635/// An expression e can be explicitly converted to a type T using a
636/// @c static_cast if the declaration "T t(e);" is well-formed [...].
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000637TryStaticCastResult
638TryStaticImplicitCast(Sema &Self, Expr *SrcExpr, QualType DestType,
639 const SourceRange &OpRange)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000640{
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000641 if (DestType->isReferenceType()) {
642 // At this point of CheckStaticCast, if the destination is a reference,
643 // this has to work. There is no other way that works.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000644 return Self.CheckReferenceInit(SrcExpr, DestType) ?
645 TSC_Failed : TSC_Success;
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000646 }
647 if (DestType->isRecordType()) {
648 // FIXME: Use an implementation of C++ [over.match.ctor] for this.
649 return TSC_NotApplicable;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000650 }
651
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000652 // FIXME: To get a proper error from invalid conversions here, we need to
653 // reimplement more of this.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000654 ImplicitConversionSequence ICS = Self.TryImplicitConversion(
655 SrcExpr, DestType);
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000656 return ICS.ConversionKind == ImplicitConversionSequence::BadConversion ?
657 TSC_NotApplicable : TSC_Success;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000658}
659
660/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
661/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
662/// checked downcasts in class hierarchies.
663void
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000664CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
665 const SourceRange &OpRange,
666 const SourceRange &DestRange)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000667{
668 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000669 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000670
671 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
672 // or "pointer to cv void".
673
674 QualType DestPointee;
675 const PointerType *DestPointer = DestType->getAsPointerType();
676 const ReferenceType *DestReference = DestType->getAsReferenceType();
677 if (DestPointer) {
678 DestPointee = DestPointer->getPointeeType();
679 } else if (DestReference) {
680 DestPointee = DestReference->getPointeeType();
681 } else {
Chris Lattner70b93d82008-11-18 22:52:51 +0000682 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
683 << OrigDestType.getAsString() << DestRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000684 return;
685 }
686
687 const RecordType *DestRecord = DestPointee->getAsRecordType();
688 if (DestPointee->isVoidType()) {
689 assert(DestPointer && "Reference to void is not possible");
690 } else if (DestRecord) {
691 if (!DestRecord->getDecl()->isDefinition()) {
Chris Lattner70b93d82008-11-18 22:52:51 +0000692 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_incomplete)
693 << DestPointee.getUnqualifiedType().getAsString() << DestRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000694 return;
695 }
696 } else {
Chris Lattner70b93d82008-11-18 22:52:51 +0000697 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
698 << DestPointee.getUnqualifiedType().getAsString() << DestRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000699 return;
700 }
701
702 // C++ 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
703 // complete class type, [...]. If T is a reference type, v shall be an
704 // lvalue of a complete class type, [...].
705
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000706 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000707 QualType SrcPointee;
708 if (DestPointer) {
709 if (const PointerType *SrcPointer = SrcType->getAsPointerType()) {
710 SrcPointee = SrcPointer->getPointeeType();
711 } else {
Chris Lattner70b93d82008-11-18 22:52:51 +0000712 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
713 << OrigSrcType.getAsString() << SrcExpr->getSourceRange();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000714 return;
715 }
716 } else {
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000717 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattner70b93d82008-11-18 22:52:51 +0000718 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
719 << "dynamic_cast" << OrigDestType.getAsString() << OpRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000720 }
721 SrcPointee = SrcType;
722 }
723
724 const RecordType *SrcRecord = SrcPointee->getAsRecordType();
725 if (SrcRecord) {
726 if (!SrcRecord->getDecl()->isDefinition()) {
Chris Lattner70b93d82008-11-18 22:52:51 +0000727 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_incomplete)
728 << SrcPointee.getUnqualifiedType().getAsString()
729 << SrcExpr->getSourceRange();
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000730 return;
731 }
732 } else {
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000733 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class,
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000734 SrcPointee.getUnqualifiedType().getAsString(),
735 SrcExpr->getSourceRange());
736 return;
737 }
738
739 assert((DestPointer || DestReference) &&
740 "Bad destination non-ptr/ref slipped through.");
741 assert((DestRecord || DestPointee->isVoidType()) &&
742 "Bad destination pointee slipped through.");
743 assert(SrcRecord && "Bad source pointee slipped through.");
744
745 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
746 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +0000747 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
748 << "dynamic_cast" << OrigDestType.getAsString()
749 << OrigSrcType.getAsString() << OpRange;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000750 return;
751 }
752
753 // C++ 5.2.7p3: If the type of v is the same as the required result type,
754 // [except for cv].
755 if (DestRecord == SrcRecord) {
756 return;
757 }
758
759 // C++ 5.2.7p5
760 // Upcasts are resolved statically.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000761 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
762 Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
763 OpRange.getBegin(), OpRange);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000764 // Diagnostic already emitted on error.
765 return;
766 }
767
768 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000769 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(Self.Context);
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000770 assert(SrcDecl && "Definition missing");
771 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000772 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic,
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000773 SrcPointee.getUnqualifiedType().getAsString(), SrcExpr->getSourceRange());
774 }
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000775
776 // Done. Everything else is run-time checks.
777}