blob: 06fc9d83bad05bcbf4e5dc30691ebb17a6c5652e [file] [log] [blame]
Sebastian Redl26d85b12008-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 Redle3dc28a2008-11-07 23:29:29 +000020#include <set>
Sebastian Redl26d85b12008-11-05 21:50:06 +000021using namespace clang;
22
Sebastian Redl37d6de32008-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 Redl26d85b12008-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
Douglas Gregor9103bb22008-12-17 22:52:20 +000068 // If the type is dependent, we won't do the semantic analysis now.
69 // FIXME: should we check this in a more fine-grained manner?
70 bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
71
Sebastian Redl26d85b12008-11-05 21:50:06 +000072 switch (Kind) {
73 default: assert(0 && "Unknown C++ cast!");
74
75 case tok::kw_const_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +000076 if (!TypeDependent)
77 CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redl26d85b12008-11-05 21:50:06 +000078 return new CXXConstCastExpr(DestType.getNonReferenceType(), Ex,
79 DestType, OpLoc);
80
81 case tok::kw_dynamic_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +000082 if (!TypeDependent)
83 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redl26d85b12008-11-05 21:50:06 +000084 return new CXXDynamicCastExpr(DestType.getNonReferenceType(), Ex,
85 DestType, OpLoc);
86
87 case tok::kw_reinterpret_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +000088 if (!TypeDependent)
89 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redl26d85b12008-11-05 21:50:06 +000090 return new CXXReinterpretCastExpr(DestType.getNonReferenceType(), Ex,
91 DestType, OpLoc);
92
93 case tok::kw_static_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +000094 if (!TypeDependent)
95 CheckStaticCast(*this, Ex, DestType, OpRange);
Sebastian Redl26d85b12008-11-05 21:50:06 +000096 return new CXXStaticCastExpr(DestType.getNonReferenceType(), Ex,
97 DestType, OpLoc);
98 }
99
100 return true;
101}
102
103/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
104/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
105/// like this:
106/// const char *str = "literal";
107/// legacy_function(const_cast\<char*\>(str));
108void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000109CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
110 const SourceRange &OpRange, const SourceRange &DestRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000111{
112 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
113
Sebastian Redl37d6de32008-11-08 13:00:26 +0000114 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000115 QualType SrcType = SrcExpr->getType();
116 if (const ReferenceType *DestTypeTmp = DestType->getAsReferenceType()) {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000117 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000118 // Cannot cast non-lvalue to reference type.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000119 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Chris Lattnerd1625842008-11-24 06:25:27 +0000120 << "const_cast" << OrigDestType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000121 return;
122 }
123
124 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
125 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000126 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
127 SrcType = Self.Context.getPointerType(SrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000128 } else {
129 // C++ 5.2.11p1: Otherwise, the result is an rvalue and the
130 // lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
131 // conversions are performed on the expression.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000132 Self.DefaultFunctionArrayConversion(SrcExpr);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000133 SrcType = SrcExpr->getType();
134 }
135
136 if (!DestType->isPointerType()) {
137 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
138 // was a reference type, we converted it to a pointer above.
139 // C++ 5.2.11p3: For two pointer types [...]
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000140 Self.Diag(OpRange.getBegin(), diag::err_bad_const_cast_dest)
Chris Lattnerd1625842008-11-24 06:25:27 +0000141 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000142 return;
143 }
144 if (DestType->isFunctionPointerType()) {
145 // Cannot cast direct function pointers.
146 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
147 // T is the ultimate pointee of source and target type.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000148 Self.Diag(OpRange.getBegin(), diag::err_bad_const_cast_dest)
Chris Lattnerd1625842008-11-24 06:25:27 +0000149 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000150 return;
151 }
Sebastian Redl37d6de32008-11-08 13:00:26 +0000152 SrcType = Self.Context.getCanonicalType(SrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000153
154 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
155 // completely equal.
156 // FIXME: const_cast should probably not be able to convert between pointers
157 // to different address spaces.
158 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
159 // in multi-level pointers may change, but the level count must be the same,
160 // as must be the final pointee type.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000161 while (SrcType != DestType &&
162 Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000163 SrcType = SrcType.getUnqualifiedType();
164 DestType = DestType.getUnqualifiedType();
165 }
166
167 // Doug Gregor said to disallow this until users complain.
168#if 0
169 // If we end up with constant arrays of equal size, unwrap those too. A cast
170 // from const int [N] to int (&)[N] is invalid by my reading of the
171 // standard, but g++ accepts it even with -ansi -pedantic.
172 // No more than one level, though, so don't embed this in the unwrap loop
173 // above.
174 const ConstantArrayType *SrcTypeArr, *DestTypeArr;
Sebastian Redl37d6de32008-11-08 13:00:26 +0000175 if ((SrcTypeArr = Self.Context.getAsConstantArrayType(SrcType)) &&
176 (DestTypeArr = Self.Context.getAsConstantArrayType(DestType)))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000177 {
178 if (SrcTypeArr->getSize() != DestTypeArr->getSize()) {
179 // Different array sizes.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000180 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000181 << "const_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000182 return;
183 }
184 SrcType = SrcTypeArr->getElementType().getUnqualifiedType();
185 DestType = DestTypeArr->getElementType().getUnqualifiedType();
186 }
187#endif
188
189 // Since we're dealing in canonical types, the remainder must be the same.
190 if (SrcType != DestType) {
191 // Cast between unrelated types.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000192 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000193 << "const_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000194 return;
195 }
196}
197
198/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
199/// valid.
200/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
201/// like this:
202/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
203void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000204CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
205 const SourceRange &OpRange, const SourceRange &DestRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000206{
207 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
208
Sebastian Redl37d6de32008-11-08 13:00:26 +0000209 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000210 QualType SrcType = SrcExpr->getType();
211 if (const ReferenceType *DestTypeTmp = DestType->getAsReferenceType()) {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000212 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000213 // Cannot cast non-lvalue to reference type.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000214 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Chris Lattnerd1625842008-11-24 06:25:27 +0000215 << "reinterpret_cast" << OrigDestType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000216 return;
217 }
218
219 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
220 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
221 // built-in & and * operators.
222 // This code does this transformation for the checked types.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000223 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
224 SrcType = Self.Context.getPointerType(SrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000225 } else {
226 // C++ 5.2.10p1: [...] the lvalue-to-rvalue, array-to-pointer, and
227 // function-to-pointer standard conversions are performed on the
228 // expression v.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000229 Self.DefaultFunctionArrayConversion(SrcExpr);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000230 SrcType = SrcExpr->getType();
231 }
232
233 // Canonicalize source for comparison.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000234 SrcType = Self.Context.getCanonicalType(SrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000235
236 bool destIsPtr = DestType->isPointerType();
237 bool srcIsPtr = SrcType->isPointerType();
238 if (!destIsPtr && !srcIsPtr) {
239 // Except for std::nullptr_t->integer, which is not supported yet, and
240 // lvalue->reference, which is handled above, at least one of the two
241 // arguments must be a pointer.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000242 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000243 << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000244 return;
245 }
246
247 if (SrcType == DestType) {
248 // C++ 5.2.10p2 has a note that mentions that, subject to all other
249 // restrictions, a cast to the same type is allowed. The intent is not
250 // entirely clear here, since all other paragraphs explicitly forbid casts
251 // to the same type. However, the behavior of compilers is pretty consistent
252 // on this point: allow same-type conversion if the involved are pointers,
253 // disallow otherwise.
254 return;
255 }
256
257 // Note: Clang treats enumeration types as integral types. If this is ever
258 // changed for C++, the additional check here will be redundant.
259 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
Sebastian Redl03a6cf92008-11-05 22:15:14 +0000260 assert(srcIsPtr && "One type must be a pointer");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000261 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
262 // type large enough to hold it.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000263 if (Self.Context.getTypeSize(SrcType) >
264 Self.Context.getTypeSize(DestType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000265 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_small_int)
Chris Lattnerd1625842008-11-24 06:25:27 +0000266 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000267 }
268 return;
269 }
270
271 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
Sebastian Redl03a6cf92008-11-05 22:15:14 +0000272 assert(destIsPtr && "One type must be a pointer");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000273 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
274 // converted to a pointer.
275 return;
276 }
277
278 if (!destIsPtr || !srcIsPtr) {
279 // With the valid non-pointer conversions out of the way, we can be even
280 // more stringent.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000281 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000282 << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000283 return;
284 }
285
286 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000287 if (CastsAwayConstness(Self, SrcType, DestType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000288 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Chris Lattnerd1625842008-11-24 06:25:27 +0000289 << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000290 return;
291 }
292
293 // Not casting away constness, so the only remaining check is for compatible
294 // pointer categories.
295
296 if (SrcType->isFunctionPointerType()) {
297 if (DestType->isFunctionPointerType()) {
298 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
299 // a pointer to a function of a different type.
300 return;
301 }
302
303 // FIXME: Handle member pointers.
304
305 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
306 // an object type or vice versa is conditionally-supported.
307 // Compilers support it in C++03 too, though, because it's necessary for
308 // casting the return value of dlsym() and GetProcAddress().
309 // FIXME: Conditionally-supported behavior should be configurable in the
310 // TargetInfo or similar.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000311 if (!Self.getLangOptions().CPlusPlus0x) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000312 Self.Diag(OpRange.getBegin(), diag::ext_reinterpret_cast_fn_obj)
313 << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000314 }
315 return;
316 }
317
318 // FIXME: Handle member pointers.
319
320 if (DestType->isFunctionPointerType()) {
321 // See above.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000322 if (!Self.getLangOptions().CPlusPlus0x) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000323 Self.Diag(OpRange.getBegin(), diag::ext_reinterpret_cast_fn_obj)
324 << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000325 }
326 return;
327 }
328
329 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
330 // a pointer to an object of different type.
331 // Void pointers are not specified, but supported by every compiler out there.
332 // So we finish by allowing everything that remains - it's got to be two
333 // object pointers.
334}
335
336/// CastsAwayConstness - Check if the pointer conversion from SrcType
337/// to DestType casts away constness as defined in C++
338/// 5.2.11p8ff. This is used by the cast checkers. Both arguments
339/// must denote pointer types.
340bool
Sebastian Redl37d6de32008-11-08 13:00:26 +0000341CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000342{
343 // Casting away constness is defined in C++ 5.2.11p8 with reference to
344 // C++ 4.4.
345 // We piggyback on Sema::IsQualificationConversion for this, since the rules
346 // are non-trivial. So first we construct Tcv *...cv* as described in
347 // C++ 5.2.11p8.
348
349 QualType UnwrappedSrcType = SrcType, UnwrappedDestType = DestType;
350 llvm::SmallVector<unsigned, 8> cv1, cv2;
351
352 // Find the qualifications.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000353 while (Self.UnwrapSimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000354 cv1.push_back(UnwrappedSrcType.getCVRQualifiers());
355 cv2.push_back(UnwrappedDestType.getCVRQualifiers());
356 }
357 assert(cv1.size() > 0 && "Must have at least one pointer level.");
358
359 // Construct void pointers with those qualifiers (in reverse order of
360 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000361 QualType SrcConstruct = Self.Context.VoidTy;
362 QualType DestConstruct = Self.Context.VoidTy;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000363 for (llvm::SmallVector<unsigned, 8>::reverse_iterator i1 = cv1.rbegin(),
364 i2 = cv2.rbegin();
365 i1 != cv1.rend(); ++i1, ++i2)
366 {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000367 SrcConstruct = Self.Context.getPointerType(
368 SrcConstruct.getQualifiedType(*i1));
369 DestConstruct = Self.Context.getPointerType(
370 DestConstruct.getQualifiedType(*i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000371 }
372
373 // Test if they're compatible.
374 return SrcConstruct != DestConstruct &&
Sebastian Redl37d6de32008-11-08 13:00:26 +0000375 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000376}
377
378/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
379/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
380/// implicit conversions explicit and getting rid of data loss warnings.
381void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000382CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
383 const SourceRange &OpRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000384{
385 // The order the tests is not entirely arbitrary. There is one conversion
386 // that can be handled in two different ways. Given:
387 // struct A {};
388 // struct B : public A {
389 // B(); B(const A&);
390 // };
391 // const A &a = B();
392 // the cast static_cast<const B&>(a) could be seen as either a static
393 // reference downcast, or an explicit invocation of the user-defined
394 // conversion using B's conversion constructor.
395 // DR 427 specifies that the downcast is to be applied here.
396
397 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
398 if (DestType->isVoidType()) {
399 return;
400 }
401
402 // C++ 5.2.9p5, reference downcast.
403 // See the function for details.
404 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000405 if (TryStaticReferenceDowncast(Self, SrcExpr, DestType, OpRange)
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000406 > TSC_NotApplicable) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000407 return;
408 }
409
410 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
411 // [...] if the declaration "T t(e);" is well-formed, [...].
Sebastian Redl37d6de32008-11-08 13:00:26 +0000412 if (TryStaticImplicitCast(Self, SrcExpr, DestType, OpRange) >
413 TSC_NotApplicable) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000414 return;
415 }
416
417 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
418 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
419 // conversions, subject to further restrictions.
420 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
421 // of qualification conversions impossible.
422
423 // The lvalue-to-rvalue, array-to-pointer and function-to-pointer conversions
424 // are applied to the expression.
425 QualType OrigSrcType = SrcExpr->getType();
Sebastian Redl37d6de32008-11-08 13:00:26 +0000426 Self.DefaultFunctionArrayConversion(SrcExpr);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000427
Sebastian Redl37d6de32008-11-08 13:00:26 +0000428 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
Sebastian Redl26d85b12008-11-05 21:50:06 +0000429
430 // Reverse integral promotion/conversion. All such conversions are themselves
431 // again integral promotions or conversions and are thus already handled by
432 // p2 (TryDirectInitialization above).
433 // (Note: any data loss warnings should be suppressed.)
434 // The exception is the reverse of enum->integer, i.e. integer->enum (and
435 // enum->enum). See also C++ 5.2.9p7.
436 // The same goes for reverse floating point promotion/conversion and
437 // floating-integral conversions. Again, only floating->enum is relevant.
438 if (DestType->isEnumeralType()) {
439 if (SrcType->isComplexType() || SrcType->isVectorType()) {
440 // Fall through - these cannot be converted.
441 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
442 return;
443 }
444 }
445
446 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
447 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000448 if (TryStaticPointerDowncast(Self, SrcType, DestType, OpRange)
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000449 > TSC_NotApplicable) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000450 return;
451 }
452
453 // Reverse member pointer conversion. C++ 5.11 specifies member pointer
454 // conversion. C++ 5.2.9p9 has additional information.
455 // DR54's access restrictions apply here also.
456 // FIXME: Don't have member pointers yet.
457
458 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
459 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
460 // just the usual constness stuff.
461 if (const PointerType *SrcPointer = SrcType->getAsPointerType()) {
462 QualType SrcPointee = SrcPointer->getPointeeType();
463 if (SrcPointee->isVoidType()) {
464 if (const PointerType *DestPointer = DestType->getAsPointerType()) {
465 QualType DestPointee = DestPointer->getPointeeType();
466 if (DestPointee->isObjectType()) {
467 // This is definitely the intended conversion, but it might fail due
468 // to a const violation.
469 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000470 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Chris Lattnerd1625842008-11-24 06:25:27 +0000471 << "static_cast" << DestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-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 Lattnerc9c7c4e2008-11-18 22:52:51 +0000483 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000484 << "static_cast" << DestType << OrigSrcType
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000485 << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000486}
487
488/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000489TryStaticCastResult
490TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
491 const SourceRange &OpRange)
Sebastian Redl26d85b12008-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 Redl37d6de32008-11-08 13:00:26 +0000502 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000503 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000504 }
505
506 const ReferenceType *DestReference = DestType->getAsReferenceType();
507 if (!DestReference) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000508 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000509 }
510 QualType DestPointee = DestReference->getPointeeType();
511
Sebastian Redl37d6de32008-11-08 13:00:26 +0000512 return TryStaticDowncast(Self, SrcExpr->getType(), DestPointee, OpRange,
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000513 SrcExpr->getType(), DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000514}
515
516/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000517TryStaticCastResult
518TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
519 const SourceRange &OpRange)
Sebastian Redl26d85b12008-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 Redle3dc28a2008-11-07 23:29:29 +0000531 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000532 }
533
534 const PointerType *DestPointer = DestType->getAsPointerType();
535 if (!DestPointer) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000536 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000537 }
538
Sebastian Redl37d6de32008-11-08 13:00:26 +0000539 return TryStaticDowncast(Self, SrcPointer->getPointeeType(),
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000540 DestPointer->getPointeeType(),
541 OpRange, SrcType, DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000542}
543
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000544/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
545/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Sebastian Redl26d85b12008-11-05 21:50:06 +0000546/// DestType, both of which must be canonical, is possible and allowed.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000547TryStaticCastResult
548TryStaticDowncast(Sema &Self, QualType SrcType, QualType DestType,
549 const SourceRange &OpRange, QualType OrigSrcType,
550 QualType OrigDestType)
Sebastian Redl26d85b12008-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 Redle3dc28a2008-11-07 23:29:29 +0000554 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000555 }
556
557 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
558 /*DetectVirtual=*/true);
Sebastian Redl37d6de32008-11-08 13:00:26 +0000559 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
Sebastian Redle3dc28a2008-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 Lattnerc9c7c4e2008-11-18 22:52:51 +0000583 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Chris Lattnerd1625842008-11-24 06:25:27 +0000584 << "static_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000585 return TSC_Failed;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000586 }
587
588 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000589 // This code is analoguous to that in CheckDerivedToBaseConversion, except
590 // that it builds the paths in reverse order.
591 // To sum up: record all paths to the base and build a nice string from
592 // them. Use it to spice up the error message.
593 Paths.clear();
594 Paths.setRecordingPaths(true);
Sebastian Redl37d6de32008-11-08 13:00:26 +0000595 Self.IsDerivedFrom(DestType, SrcType, Paths);
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000596 std::string PathDisplayStr;
597 std::set<unsigned> DisplayedPaths;
598 for (BasePaths::paths_iterator Path = Paths.begin();
599 Path != Paths.end(); ++Path) {
600 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
601 // We haven't displayed a path to this particular base
602 // class subobject yet.
603 PathDisplayStr += "\n ";
604 for (BasePath::const_reverse_iterator Element = Path->rbegin();
605 Element != Path->rend(); ++Element)
606 PathDisplayStr += Element->Base->getType().getAsString() + " -> ";
607 PathDisplayStr += DestType.getAsString();
608 }
609 }
610
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000611 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Chris Lattnerd1625842008-11-24 06:25:27 +0000612 << SrcType.getUnqualifiedType() << DestType.getUnqualifiedType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000613 << PathDisplayStr << OpRange;
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000614 return TSC_Failed;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000615 }
616
617 if (Paths.getDetectedVirtual() != 0) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000618 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000619 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
Chris Lattnerd1625842008-11-24 06:25:27 +0000620 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000621 return TSC_Failed;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000622 }
623
624 // FIXME: Test accessibility.
625
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000626 return TSC_Success;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000627}
628
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000629/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
630/// is valid:
631///
632/// An expression e can be explicitly converted to a type T using a
633/// @c static_cast if the declaration "T t(e);" is well-formed [...].
Sebastian Redl37d6de32008-11-08 13:00:26 +0000634TryStaticCastResult
635TryStaticImplicitCast(Sema &Self, Expr *SrcExpr, QualType DestType,
636 const SourceRange &OpRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000637{
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000638 if (DestType->isReferenceType()) {
639 // At this point of CheckStaticCast, if the destination is a reference,
640 // this has to work. There is no other way that works.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000641 return Self.CheckReferenceInit(SrcExpr, DestType) ?
642 TSC_Failed : TSC_Success;
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000643 }
644 if (DestType->isRecordType()) {
645 // FIXME: Use an implementation of C++ [over.match.ctor] for this.
646 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000647 }
648
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000649 // FIXME: To get a proper error from invalid conversions here, we need to
650 // reimplement more of this.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000651 ImplicitConversionSequence ICS = Self.TryImplicitConversion(
652 SrcExpr, DestType);
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000653 return ICS.ConversionKind == ImplicitConversionSequence::BadConversion ?
654 TSC_NotApplicable : TSC_Success;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000655}
656
657/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
658/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
659/// checked downcasts in class hierarchies.
660void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000661CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
662 const SourceRange &OpRange,
663 const SourceRange &DestRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000664{
665 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl37d6de32008-11-08 13:00:26 +0000666 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000667
668 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
669 // or "pointer to cv void".
670
671 QualType DestPointee;
672 const PointerType *DestPointer = DestType->getAsPointerType();
673 const ReferenceType *DestReference = DestType->getAsReferenceType();
674 if (DestPointer) {
675 DestPointee = DestPointer->getPointeeType();
676 } else if (DestReference) {
677 DestPointee = DestReference->getPointeeType();
678 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000679 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000680 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000681 return;
682 }
683
684 const RecordType *DestRecord = DestPointee->getAsRecordType();
685 if (DestPointee->isVoidType()) {
686 assert(DestPointer && "Reference to void is not possible");
687 } else if (DestRecord) {
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000688 if (Self.DiagnoseIncompleteType(OpRange.getBegin(), DestPointee,
689 diag::err_bad_dynamic_cast_incomplete,
690 DestRange))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000691 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000692 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000693 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000694 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000695 return;
696 }
697
698 // C++ 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
699 // complete class type, [...]. If T is a reference type, v shall be an
700 // lvalue of a complete class type, [...].
701
Sebastian Redl37d6de32008-11-08 13:00:26 +0000702 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000703 QualType SrcPointee;
704 if (DestPointer) {
705 if (const PointerType *SrcPointer = SrcType->getAsPointerType()) {
706 SrcPointee = SrcPointer->getPointeeType();
707 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000708 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000709 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000710 return;
711 }
712 } else {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000713 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000714 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Chris Lattnerd1625842008-11-24 06:25:27 +0000715 << "dynamic_cast" << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000716 }
717 SrcPointee = SrcType;
718 }
719
720 const RecordType *SrcRecord = SrcPointee->getAsRecordType();
721 if (SrcRecord) {
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000722 if (Self.DiagnoseIncompleteType(OpRange.getBegin(), SrcPointee,
723 diag::err_bad_dynamic_cast_incomplete,
724 SrcExpr->getSourceRange()))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000725 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000726 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000727 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000728 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000729 return;
730 }
731
732 assert((DestPointer || DestReference) &&
733 "Bad destination non-ptr/ref slipped through.");
734 assert((DestRecord || DestPointee->isVoidType()) &&
735 "Bad destination pointee slipped through.");
736 assert(SrcRecord && "Bad source pointee slipped through.");
737
738 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
739 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000740 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Chris Lattnerd1625842008-11-24 06:25:27 +0000741 << "dynamic_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000742 return;
743 }
744
745 // C++ 5.2.7p3: If the type of v is the same as the required result type,
746 // [except for cv].
747 if (DestRecord == SrcRecord) {
748 return;
749 }
750
751 // C++ 5.2.7p5
752 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000753 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
754 Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
Chris Lattnerd1625842008-11-24 06:25:27 +0000755 OpRange.getBegin(), OpRange);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000756 // Diagnostic already emitted on error.
757 return;
758 }
759
760 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Sebastian Redl37d6de32008-11-08 13:00:26 +0000761 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(Self.Context);
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000762 assert(SrcDecl && "Definition missing");
763 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000764 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000765 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000766 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000767
768 // Done. Everything else is run-time checks.
769}