blob: 6e005e8365fda93fc2f31f0a9d138975f7308b21 [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.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000111 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue,
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000112 "const_cast", OrigDestType.getAsString(), SrcExpr->getSourceRange());
113 return;
114 }
115
116 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
117 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000118 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
119 SrcType = Self.Context.getPointerType(SrcType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000120 } else {
121 // C++ 5.2.11p1: Otherwise, the result is an rvalue and the
122 // lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
123 // conversions are performed on the expression.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000124 Self.DefaultFunctionArrayConversion(SrcExpr);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000125 SrcType = SrcExpr->getType();
126 }
127
128 if (!DestType->isPointerType()) {
129 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
130 // was a reference type, we converted it to a pointer above.
131 // C++ 5.2.11p3: For two pointer types [...]
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000132 Self.Diag(OpRange.getBegin(), diag::err_bad_const_cast_dest,
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000133 OrigDestType.getAsString(), DestRange);
134 return;
135 }
136 if (DestType->isFunctionPointerType()) {
137 // Cannot cast direct function pointers.
138 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
139 // T is the ultimate pointee of source and target type.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000140 Self.Diag(OpRange.getBegin(), diag::err_bad_const_cast_dest,
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000141 OrigDestType.getAsString(), DestRange);
142 return;
143 }
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000144 SrcType = Self.Context.getCanonicalType(SrcType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000145
146 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
147 // completely equal.
148 // FIXME: const_cast should probably not be able to convert between pointers
149 // to different address spaces.
150 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
151 // in multi-level pointers may change, but the level count must be the same,
152 // as must be the final pointee type.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000153 while (SrcType != DestType &&
154 Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000155 SrcType = SrcType.getUnqualifiedType();
156 DestType = DestType.getUnqualifiedType();
157 }
158
159 // Doug Gregor said to disallow this until users complain.
160#if 0
161 // If we end up with constant arrays of equal size, unwrap those too. A cast
162 // from const int [N] to int (&)[N] is invalid by my reading of the
163 // standard, but g++ accepts it even with -ansi -pedantic.
164 // No more than one level, though, so don't embed this in the unwrap loop
165 // above.
166 const ConstantArrayType *SrcTypeArr, *DestTypeArr;
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000167 if ((SrcTypeArr = Self.Context.getAsConstantArrayType(SrcType)) &&
168 (DestTypeArr = Self.Context.getAsConstantArrayType(DestType)))
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000169 {
170 if (SrcTypeArr->getSize() != DestTypeArr->getSize()) {
171 // Different array sizes.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000172 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic,
173 "const_cast", OrigDestType.getAsString(), OrigSrcType.getAsString(),
174 OpRange);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000175 return;
176 }
177 SrcType = SrcTypeArr->getElementType().getUnqualifiedType();
178 DestType = DestTypeArr->getElementType().getUnqualifiedType();
179 }
180#endif
181
182 // Since we're dealing in canonical types, the remainder must be the same.
183 if (SrcType != DestType) {
184 // Cast between unrelated types.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000185 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic, "const_cast",
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000186 OrigDestType.getAsString(), OrigSrcType.getAsString(), OpRange);
187 return;
188 }
189}
190
191/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
192/// valid.
193/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
194/// like this:
195/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
196void
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000197CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
198 const SourceRange &OpRange, const SourceRange &DestRange)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000199{
200 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
201
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000202 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000203 QualType SrcType = SrcExpr->getType();
204 if (const ReferenceType *DestTypeTmp = DestType->getAsReferenceType()) {
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000205 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000206 // Cannot cast non-lvalue to reference type.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000207 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue,
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000208 "reinterpret_cast", OrigDestType.getAsString(),
209 SrcExpr->getSourceRange());
210 return;
211 }
212
213 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
214 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
215 // built-in & and * operators.
216 // This code does this transformation for the checked types.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000217 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
218 SrcType = Self.Context.getPointerType(SrcType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000219 } else {
220 // C++ 5.2.10p1: [...] the lvalue-to-rvalue, array-to-pointer, and
221 // function-to-pointer standard conversions are performed on the
222 // expression v.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000223 Self.DefaultFunctionArrayConversion(SrcExpr);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000224 SrcType = SrcExpr->getType();
225 }
226
227 // Canonicalize source for comparison.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000228 SrcType = Self.Context.getCanonicalType(SrcType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000229
230 bool destIsPtr = DestType->isPointerType();
231 bool srcIsPtr = SrcType->isPointerType();
232 if (!destIsPtr && !srcIsPtr) {
233 // Except for std::nullptr_t->integer, which is not supported yet, and
234 // lvalue->reference, which is handled above, at least one of the two
235 // arguments must be a pointer.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000236 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic,
237 "reinterpret_cast", OrigDestType.getAsString(), OrigSrcType.getAsString(),
238 OpRange);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000239 return;
240 }
241
242 if (SrcType == DestType) {
243 // C++ 5.2.10p2 has a note that mentions that, subject to all other
244 // restrictions, a cast to the same type is allowed. The intent is not
245 // entirely clear here, since all other paragraphs explicitly forbid casts
246 // to the same type. However, the behavior of compilers is pretty consistent
247 // on this point: allow same-type conversion if the involved are pointers,
248 // disallow otherwise.
249 return;
250 }
251
252 // Note: Clang treats enumeration types as integral types. If this is ever
253 // changed for C++, the additional check here will be redundant.
254 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
Sebastian Redldbed5902008-11-05 22:15:14 +0000255 assert(srcIsPtr && "One type must be a pointer");
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000256 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
257 // type large enough to hold it.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000258 if (Self.Context.getTypeSize(SrcType) >
259 Self.Context.getTypeSize(DestType)) {
260 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_small_int,
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000261 OrigDestType.getAsString(), DestRange);
262 }
263 return;
264 }
265
266 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
Sebastian Redldbed5902008-11-05 22:15:14 +0000267 assert(destIsPtr && "One type must be a pointer");
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000268 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
269 // converted to a pointer.
270 return;
271 }
272
273 if (!destIsPtr || !srcIsPtr) {
274 // With the valid non-pointer conversions out of the way, we can be even
275 // more stringent.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000276 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic,
277 "reinterpret_cast", OrigDestType.getAsString(), OrigSrcType.getAsString(),
278 OpRange);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000279 return;
280 }
281
282 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000283 if (CastsAwayConstness(Self, SrcType, DestType)) {
284 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away,
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000285 "reinterpret_cast", OrigDestType.getAsString(), OrigSrcType.getAsString(),
286 OpRange);
287 return;
288 }
289
290 // Not casting away constness, so the only remaining check is for compatible
291 // pointer categories.
292
293 if (SrcType->isFunctionPointerType()) {
294 if (DestType->isFunctionPointerType()) {
295 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
296 // a pointer to a function of a different type.
297 return;
298 }
299
300 // FIXME: Handle member pointers.
301
302 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
303 // an object type or vice versa is conditionally-supported.
304 // Compilers support it in C++03 too, though, because it's necessary for
305 // casting the return value of dlsym() and GetProcAddress().
306 // FIXME: Conditionally-supported behavior should be configurable in the
307 // TargetInfo or similar.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000308 if (!Self.getLangOptions().CPlusPlus0x) {
309 Self.Diag(OpRange.getBegin(), diag::ext_reinterpret_cast_fn_obj, OpRange);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000310 }
311 return;
312 }
313
314 // FIXME: Handle member pointers.
315
316 if (DestType->isFunctionPointerType()) {
317 // See above.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000318 if (!Self.getLangOptions().CPlusPlus0x) {
319 Self.Diag(OpRange.getBegin(), diag::ext_reinterpret_cast_fn_obj, OpRange);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000320 }
321 return;
322 }
323
324 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
325 // a pointer to an object of different type.
326 // Void pointers are not specified, but supported by every compiler out there.
327 // So we finish by allowing everything that remains - it's got to be two
328 // object pointers.
329}
330
331/// CastsAwayConstness - Check if the pointer conversion from SrcType
332/// to DestType casts away constness as defined in C++
333/// 5.2.11p8ff. This is used by the cast checkers. Both arguments
334/// must denote pointer types.
335bool
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000336CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000337{
338 // Casting away constness is defined in C++ 5.2.11p8 with reference to
339 // C++ 4.4.
340 // We piggyback on Sema::IsQualificationConversion for this, since the rules
341 // are non-trivial. So first we construct Tcv *...cv* as described in
342 // C++ 5.2.11p8.
343
344 QualType UnwrappedSrcType = SrcType, UnwrappedDestType = DestType;
345 llvm::SmallVector<unsigned, 8> cv1, cv2;
346
347 // Find the qualifications.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000348 while (Self.UnwrapSimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000349 cv1.push_back(UnwrappedSrcType.getCVRQualifiers());
350 cv2.push_back(UnwrappedDestType.getCVRQualifiers());
351 }
352 assert(cv1.size() > 0 && "Must have at least one pointer level.");
353
354 // Construct void pointers with those qualifiers (in reverse order of
355 // unwrapping, of course).
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000356 QualType SrcConstruct = Self.Context.VoidTy;
357 QualType DestConstruct = Self.Context.VoidTy;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000358 for (llvm::SmallVector<unsigned, 8>::reverse_iterator i1 = cv1.rbegin(),
359 i2 = cv2.rbegin();
360 i1 != cv1.rend(); ++i1, ++i2)
361 {
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000362 SrcConstruct = Self.Context.getPointerType(
363 SrcConstruct.getQualifiedType(*i1));
364 DestConstruct = Self.Context.getPointerType(
365 DestConstruct.getQualifiedType(*i2));
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000366 }
367
368 // Test if they're compatible.
369 return SrcConstruct != DestConstruct &&
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000370 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000371}
372
373/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
374/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
375/// implicit conversions explicit and getting rid of data loss warnings.
376void
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000377CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
378 const SourceRange &OpRange)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000379{
380 // The order the tests is not entirely arbitrary. There is one conversion
381 // that can be handled in two different ways. Given:
382 // struct A {};
383 // struct B : public A {
384 // B(); B(const A&);
385 // };
386 // const A &a = B();
387 // the cast static_cast<const B&>(a) could be seen as either a static
388 // reference downcast, or an explicit invocation of the user-defined
389 // conversion using B's conversion constructor.
390 // DR 427 specifies that the downcast is to be applied here.
391
392 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
393 if (DestType->isVoidType()) {
394 return;
395 }
396
397 // C++ 5.2.9p5, reference downcast.
398 // See the function for details.
399 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000400 if (TryStaticReferenceDowncast(Self, SrcExpr, DestType, OpRange)
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000401 > TSC_NotApplicable) {
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000402 return;
403 }
404
405 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
406 // [...] if the declaration "T t(e);" is well-formed, [...].
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000407 if (TryStaticImplicitCast(Self, SrcExpr, DestType, OpRange) >
408 TSC_NotApplicable) {
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000409 return;
410 }
411
412 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
413 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
414 // conversions, subject to further restrictions.
415 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
416 // of qualification conversions impossible.
417
418 // The lvalue-to-rvalue, array-to-pointer and function-to-pointer conversions
419 // are applied to the expression.
420 QualType OrigSrcType = SrcExpr->getType();
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000421 Self.DefaultFunctionArrayConversion(SrcExpr);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000422
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000423 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000424
425 // Reverse integral promotion/conversion. All such conversions are themselves
426 // again integral promotions or conversions and are thus already handled by
427 // p2 (TryDirectInitialization above).
428 // (Note: any data loss warnings should be suppressed.)
429 // The exception is the reverse of enum->integer, i.e. integer->enum (and
430 // enum->enum). See also C++ 5.2.9p7.
431 // The same goes for reverse floating point promotion/conversion and
432 // floating-integral conversions. Again, only floating->enum is relevant.
433 if (DestType->isEnumeralType()) {
434 if (SrcType->isComplexType() || SrcType->isVectorType()) {
435 // Fall through - these cannot be converted.
436 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
437 return;
438 }
439 }
440
441 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
442 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000443 if (TryStaticPointerDowncast(Self, SrcType, DestType, OpRange)
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000444 > TSC_NotApplicable) {
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000445 return;
446 }
447
448 // Reverse member pointer conversion. C++ 5.11 specifies member pointer
449 // conversion. C++ 5.2.9p9 has additional information.
450 // DR54's access restrictions apply here also.
451 // FIXME: Don't have member pointers yet.
452
453 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
454 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
455 // just the usual constness stuff.
456 if (const PointerType *SrcPointer = SrcType->getAsPointerType()) {
457 QualType SrcPointee = SrcPointer->getPointeeType();
458 if (SrcPointee->isVoidType()) {
459 if (const PointerType *DestPointer = DestType->getAsPointerType()) {
460 QualType DestPointee = DestPointer->getPointeeType();
461 if (DestPointee->isObjectType()) {
462 // This is definitely the intended conversion, but it might fail due
463 // to a const violation.
464 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000465 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away,
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000466 "static_cast", DestType.getAsString(),
467 OrigSrcType.getAsString(), OpRange);
468 }
469 return;
470 }
471 }
472 }
473 }
474
475 // We tried everything. Everything! Nothing works! :-(
476 // FIXME: Error reporting could be a lot better. Should store the reason
477 // why every substep failed and, at the end, select the most specific and
478 // report that.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000479 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic, "static_cast",
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000480 DestType.getAsString(), OrigSrcType.getAsString(), OpRange);
481}
482
483/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000484TryStaticCastResult
485TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
486 const SourceRange &OpRange)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000487{
488 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
489 // cast to type "reference to cv2 D", where D is a class derived from B,
490 // if a valid standard conversion from "pointer to D" to "pointer to B"
491 // exists, cv2 >= cv1, and B is not a virtual base class of D.
492 // In addition, DR54 clarifies that the base must be accessible in the
493 // current context. Although the wording of DR54 only applies to the pointer
494 // variant of this rule, the intent is clearly for it to apply to the this
495 // conversion as well.
496
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000497 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000498 return TSC_NotApplicable;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000499 }
500
501 const ReferenceType *DestReference = DestType->getAsReferenceType();
502 if (!DestReference) {
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000503 return TSC_NotApplicable;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000504 }
505 QualType DestPointee = DestReference->getPointeeType();
506
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000507 return TryStaticDowncast(Self, SrcExpr->getType(), DestPointee, OpRange,
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000508 SrcExpr->getType(), DestType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000509}
510
511/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000512TryStaticCastResult
513TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
514 const SourceRange &OpRange)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000515{
516 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
517 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
518 // is a class derived from B, if a valid standard conversion from "pointer
519 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
520 // class of D.
521 // In addition, DR54 clarifies that the base must be accessible in the
522 // current context.
523
524 const PointerType *SrcPointer = SrcType->getAsPointerType();
525 if (!SrcPointer) {
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000526 return TSC_NotApplicable;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000527 }
528
529 const PointerType *DestPointer = DestType->getAsPointerType();
530 if (!DestPointer) {
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000531 return TSC_NotApplicable;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000532 }
533
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000534 return TryStaticDowncast(Self, SrcPointer->getPointeeType(),
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000535 DestPointer->getPointeeType(),
536 OpRange, SrcType, DestType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000537}
538
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000539/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
540/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000541/// DestType, both of which must be canonical, is possible and allowed.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000542TryStaticCastResult
543TryStaticDowncast(Sema &Self, QualType SrcType, QualType DestType,
544 const SourceRange &OpRange, QualType OrigSrcType,
545 QualType OrigDestType)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000546{
547 // Downcast can only happen in class hierarchies, so we need classes.
548 if (!DestType->isRecordType() || !SrcType->isRecordType()) {
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000549 return TSC_NotApplicable;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000550 }
551
552 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
553 /*DetectVirtual=*/true);
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000554 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000555 return TSC_NotApplicable;
556 }
557
558 // Target type does derive from source type. Now we're serious. If an error
559 // appears now, it's not ignored.
560 // This may not be entirely in line with the standard. Take for example:
561 // struct A {};
562 // struct B : virtual A {
563 // B(A&);
564 // };
565 //
566 // void f()
567 // {
568 // (void)static_cast<const B&>(*((A*)0));
569 // }
570 // As far as the standard is concerned, p5 does not apply (A is virtual), so
571 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
572 // However, both GCC and Comeau reject this example, and accepting it would
573 // mean more complex code if we're to preserve the nice error message.
574 // FIXME: Being 100% compliant here would be nice to have.
575
576 // Must preserve cv, as always.
577 if (!DestType.isAtLeastAsQualifiedAs(SrcType)) {
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000578 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away,
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000579 "static_cast", OrigDestType.getAsString(), OrigSrcType.getAsString(),
580 OpRange);
581 return TSC_Failed;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000582 }
583
584 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000585 // This code is analoguous to that in CheckDerivedToBaseConversion, except
586 // that it builds the paths in reverse order.
587 // To sum up: record all paths to the base and build a nice string from
588 // them. Use it to spice up the error message.
589 Paths.clear();
590 Paths.setRecordingPaths(true);
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000591 Self.IsDerivedFrom(DestType, SrcType, Paths);
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000592 std::string PathDisplayStr;
593 std::set<unsigned> DisplayedPaths;
594 for (BasePaths::paths_iterator Path = Paths.begin();
595 Path != Paths.end(); ++Path) {
596 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
597 // We haven't displayed a path to this particular base
598 // class subobject yet.
599 PathDisplayStr += "\n ";
600 for (BasePath::const_reverse_iterator Element = Path->rbegin();
601 Element != Path->rend(); ++Element)
602 PathDisplayStr += Element->Base->getType().getAsString() + " -> ";
603 PathDisplayStr += DestType.getAsString();
604 }
605 }
606
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000607 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast,
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000608 SrcType.getUnqualifiedType().getAsString(),
609 DestType.getUnqualifiedType().getAsString(),
610 PathDisplayStr, OpRange);
611 return TSC_Failed;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000612 }
613
614 if (Paths.getDetectedVirtual() != 0) {
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000615 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000616 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual,
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000617 OrigSrcType.getAsString(), OrigDestType.getAsString(),
618 VirtualBase.getAsString(), OpRange);
619 return TSC_Failed;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000620 }
621
622 // FIXME: Test accessibility.
623
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000624 return TSC_Success;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000625}
626
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000627/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
628/// is valid:
629///
630/// An expression e can be explicitly converted to a type T using a
631/// @c static_cast if the declaration "T t(e);" is well-formed [...].
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000632TryStaticCastResult
633TryStaticImplicitCast(Sema &Self, Expr *SrcExpr, QualType DestType,
634 const SourceRange &OpRange)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000635{
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000636 if (DestType->isReferenceType()) {
637 // At this point of CheckStaticCast, if the destination is a reference,
638 // this has to work. There is no other way that works.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000639 return Self.CheckReferenceInit(SrcExpr, DestType) ?
640 TSC_Failed : TSC_Success;
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000641 }
642 if (DestType->isRecordType()) {
643 // FIXME: Use an implementation of C++ [over.match.ctor] for this.
644 return TSC_NotApplicable;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000645 }
646
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000647 // FIXME: To get a proper error from invalid conversions here, we need to
648 // reimplement more of this.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000649 ImplicitConversionSequence ICS = Self.TryImplicitConversion(
650 SrcExpr, DestType);
Sebastian Redl0528e1c2008-11-07 23:29:29 +0000651 return ICS.ConversionKind == ImplicitConversionSequence::BadConversion ?
652 TSC_NotApplicable : TSC_Success;
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000653}
654
655/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
656/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
657/// checked downcasts in class hierarchies.
658void
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000659CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
660 const SourceRange &OpRange,
661 const SourceRange &DestRange)
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000662{
663 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000664 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000665
666 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
667 // or "pointer to cv void".
668
669 QualType DestPointee;
670 const PointerType *DestPointer = DestType->getAsPointerType();
671 const ReferenceType *DestReference = DestType->getAsReferenceType();
672 if (DestPointer) {
673 DestPointee = DestPointer->getPointeeType();
674 } else if (DestReference) {
675 DestPointee = DestReference->getPointeeType();
676 } else {
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000677 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr,
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000678 OrigDestType.getAsString(), DestRange);
679 return;
680 }
681
682 const RecordType *DestRecord = DestPointee->getAsRecordType();
683 if (DestPointee->isVoidType()) {
684 assert(DestPointer && "Reference to void is not possible");
685 } else if (DestRecord) {
686 if (!DestRecord->getDecl()->isDefinition()) {
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000687 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_incomplete,
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000688 DestPointee.getUnqualifiedType().getAsString(), DestRange);
689 return;
690 }
691 } else {
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000692 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class,
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000693 DestPointee.getUnqualifiedType().getAsString(), DestRange);
694 return;
695 }
696
697 // C++ 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
698 // complete class type, [...]. If T is a reference type, v shall be an
699 // lvalue of a complete class type, [...].
700
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000701 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000702 QualType SrcPointee;
703 if (DestPointer) {
704 if (const PointerType *SrcPointer = SrcType->getAsPointerType()) {
705 SrcPointee = SrcPointer->getPointeeType();
706 } else {
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000707 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr,
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000708 OrigSrcType.getAsString(), SrcExpr->getSourceRange());
709 return;
710 }
711 } else {
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000712 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
713 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue,
714 "dynamic_cast", OrigDestType.getAsString(), OpRange);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000715 }
716 SrcPointee = SrcType;
717 }
718
719 const RecordType *SrcRecord = SrcPointee->getAsRecordType();
720 if (SrcRecord) {
721 if (!SrcRecord->getDecl()->isDefinition()) {
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000722 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_incomplete,
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000723 SrcPointee.getUnqualifiedType().getAsString(),
724 SrcExpr->getSourceRange());
725 return;
726 }
727 } else {
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000728 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class,
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000729 SrcPointee.getUnqualifiedType().getAsString(),
730 SrcExpr->getSourceRange());
731 return;
732 }
733
734 assert((DestPointer || DestReference) &&
735 "Bad destination non-ptr/ref slipped through.");
736 assert((DestRecord || DestPointee->isVoidType()) &&
737 "Bad destination pointee slipped through.");
738 assert(SrcRecord && "Bad source pointee slipped through.");
739
740 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
741 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000742 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away,
743 "dynamic_cast", OrigDestType.getAsString(), OrigSrcType.getAsString(),
744 OpRange);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000745 return;
746 }
747
748 // C++ 5.2.7p3: If the type of v is the same as the required result type,
749 // [except for cv].
750 if (DestRecord == SrcRecord) {
751 return;
752 }
753
754 // C++ 5.2.7p5
755 // Upcasts are resolved statically.
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000756 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
757 Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
758 OpRange.getBegin(), OpRange);
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000759 // Diagnostic already emitted on error.
760 return;
761 }
762
763 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000764 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(Self.Context);
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000765 assert(SrcDecl && "Definition missing");
766 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Sebastian Redlf831eeb2008-11-08 13:00:26 +0000767 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic,
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000768 SrcPointee.getUnqualifiedType().getAsString(), SrcExpr->getSourceRange());
769 }
Sebastian Redl2b6b14c2008-11-05 21:50:06 +0000770
771 // Done. Everything else is run-time checks.
772}