blob: cac76b63e4ca0309f838e739e1ed246db52428ea [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"
Chris Lattner20c6b3b2009-01-27 18:30:58 +000018#include "clang/Basic/DiagnosticSema.h"
Sebastian Redl26d85b12008-11-05 21:50:06 +000019#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);
Sebastian Redl21593ac2009-01-28 18:33:18 +000047static TryStaticCastResult TryStaticMemberPointerUpcast(
48 Sema &Self, QualType SrcType, QualType DestType, const SourceRange &OpRange);
Sebastian Redl37d6de32008-11-08 13:00:26 +000049static TryStaticCastResult TryStaticDowncast(Sema &Self, QualType SrcType,
50 QualType DestType,
51 const SourceRange &OpRange,
52 QualType OrigSrcType,
53 QualType OrigDestType);
54static TryStaticCastResult TryStaticImplicitCast(Sema &Self, Expr *SrcExpr,
55 QualType DestType,
56 const SourceRange &OpRange);
57
Sebastian Redl26d85b12008-11-05 21:50:06 +000058/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
59Action::ExprResult
60Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
61 SourceLocation LAngleBracketLoc, TypeTy *Ty,
62 SourceLocation RAngleBracketLoc,
63 SourceLocation LParenLoc, ExprTy *E,
64 SourceLocation RParenLoc) {
65 Expr *Ex = (Expr*)E;
66 QualType DestType = QualType::getFromOpaquePtr(Ty);
67 SourceRange OpRange(OpLoc, RParenLoc);
68 SourceRange DestRange(LAngleBracketLoc, RAngleBracketLoc);
69
Douglas Gregor9103bb22008-12-17 22:52:20 +000070 // If the type is dependent, we won't do the semantic analysis now.
71 // FIXME: should we check this in a more fine-grained manner?
72 bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
73
Sebastian Redl26d85b12008-11-05 21:50:06 +000074 switch (Kind) {
75 default: assert(0 && "Unknown C++ cast!");
76
77 case tok::kw_const_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +000078 if (!TypeDependent)
79 CheckConstCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redl26d85b12008-11-05 21:50:06 +000080 return new CXXConstCastExpr(DestType.getNonReferenceType(), Ex,
81 DestType, OpLoc);
82
83 case tok::kw_dynamic_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +000084 if (!TypeDependent)
85 CheckDynamicCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redl26d85b12008-11-05 21:50:06 +000086 return new CXXDynamicCastExpr(DestType.getNonReferenceType(), Ex,
87 DestType, OpLoc);
88
89 case tok::kw_reinterpret_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +000090 if (!TypeDependent)
91 CheckReinterpretCast(*this, Ex, DestType, OpRange, DestRange);
Sebastian Redl26d85b12008-11-05 21:50:06 +000092 return new CXXReinterpretCastExpr(DestType.getNonReferenceType(), Ex,
93 DestType, OpLoc);
94
95 case tok::kw_static_cast:
Douglas Gregor9103bb22008-12-17 22:52:20 +000096 if (!TypeDependent)
97 CheckStaticCast(*this, Ex, DestType, OpRange);
Sebastian Redl26d85b12008-11-05 21:50:06 +000098 return new CXXStaticCastExpr(DestType.getNonReferenceType(), Ex,
99 DestType, OpLoc);
100 }
101
102 return true;
103}
104
105/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
106/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
107/// like this:
108/// const char *str = "literal";
109/// legacy_function(const_cast\<char*\>(str));
110void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000111CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
112 const SourceRange &OpRange, const SourceRange &DestRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000113{
114 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
115
Sebastian Redl37d6de32008-11-08 13:00:26 +0000116 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000117 QualType SrcType = SrcExpr->getType();
118 if (const ReferenceType *DestTypeTmp = DestType->getAsReferenceType()) {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000119 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000120 // Cannot cast non-lvalue to reference type.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000121 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Chris Lattnerd1625842008-11-24 06:25:27 +0000122 << "const_cast" << OrigDestType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000123 return;
124 }
125
126 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
127 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000128 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
129 SrcType = Self.Context.getPointerType(SrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000130 } else {
131 // C++ 5.2.11p1: Otherwise, the result is an rvalue and the
132 // lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
133 // conversions are performed on the expression.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000134 Self.DefaultFunctionArrayConversion(SrcExpr);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000135 SrcType = SrcExpr->getType();
136 }
137
Sebastian Redlf20269b2009-01-26 22:19:12 +0000138 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
139 // the rules for const_cast are the same as those used for pointers.
140
141 if (!DestType->isPointerType() && !DestType->isMemberPointerType()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000142 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
143 // was a reference type, we converted it to a pointer above.
144 // C++ 5.2.11p3: For two pointer types [...]
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000145 Self.Diag(OpRange.getBegin(), diag::err_bad_const_cast_dest)
Chris Lattnerd1625842008-11-24 06:25:27 +0000146 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000147 return;
148 }
Sebastian Redlf20269b2009-01-26 22:19:12 +0000149 if (DestType->isFunctionPointerType() ||
150 DestType->isMemberFunctionPointerType()) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000151 // Cannot cast direct function pointers.
152 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
153 // T is the ultimate pointee of source and target type.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000154 Self.Diag(OpRange.getBegin(), diag::err_bad_const_cast_dest)
Chris Lattnerd1625842008-11-24 06:25:27 +0000155 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000156 return;
157 }
Sebastian Redl37d6de32008-11-08 13:00:26 +0000158 SrcType = Self.Context.getCanonicalType(SrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000159
160 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
161 // completely equal.
162 // FIXME: const_cast should probably not be able to convert between pointers
163 // to different address spaces.
164 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
165 // in multi-level pointers may change, but the level count must be the same,
166 // as must be the final pointee type.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000167 while (SrcType != DestType &&
168 Self.UnwrapSimilarPointerTypes(SrcType, DestType)) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000169 SrcType = SrcType.getUnqualifiedType();
170 DestType = DestType.getUnqualifiedType();
171 }
172
173 // Doug Gregor said to disallow this until users complain.
174#if 0
175 // If we end up with constant arrays of equal size, unwrap those too. A cast
176 // from const int [N] to int (&)[N] is invalid by my reading of the
177 // standard, but g++ accepts it even with -ansi -pedantic.
178 // No more than one level, though, so don't embed this in the unwrap loop
179 // above.
180 const ConstantArrayType *SrcTypeArr, *DestTypeArr;
Sebastian Redl37d6de32008-11-08 13:00:26 +0000181 if ((SrcTypeArr = Self.Context.getAsConstantArrayType(SrcType)) &&
182 (DestTypeArr = Self.Context.getAsConstantArrayType(DestType)))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000183 {
184 if (SrcTypeArr->getSize() != DestTypeArr->getSize()) {
185 // Different array sizes.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000186 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000187 << "const_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000188 return;
189 }
190 SrcType = SrcTypeArr->getElementType().getUnqualifiedType();
191 DestType = DestTypeArr->getElementType().getUnqualifiedType();
192 }
193#endif
194
195 // Since we're dealing in canonical types, the remainder must be the same.
196 if (SrcType != DestType) {
197 // Cast between unrelated types.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000198 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000199 << "const_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000200 return;
201 }
202}
203
204/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
205/// valid.
206/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
207/// like this:
208/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
209void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000210CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
211 const SourceRange &OpRange, const SourceRange &DestRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000212{
213 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
214
Sebastian Redl37d6de32008-11-08 13:00:26 +0000215 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000216 QualType SrcType = SrcExpr->getType();
217 if (const ReferenceType *DestTypeTmp = DestType->getAsReferenceType()) {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000218 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000219 // Cannot cast non-lvalue to reference type.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000220 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Chris Lattnerd1625842008-11-24 06:25:27 +0000221 << "reinterpret_cast" << OrigDestType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000222 return;
223 }
224
225 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
226 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
227 // built-in & and * operators.
228 // This code does this transformation for the checked types.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000229 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
230 SrcType = Self.Context.getPointerType(SrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000231 } else {
232 // C++ 5.2.10p1: [...] the lvalue-to-rvalue, array-to-pointer, and
233 // function-to-pointer standard conversions are performed on the
234 // expression v.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000235 Self.DefaultFunctionArrayConversion(SrcExpr);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000236 SrcType = SrcExpr->getType();
237 }
238
239 // Canonicalize source for comparison.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000240 SrcType = Self.Context.getCanonicalType(SrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000241
Sebastian Redldb647282009-01-27 23:18:31 +0000242 const MemberPointerType *DestMemPtr = DestType->getAsMemberPointerType(),
243 *SrcMemPtr = SrcType->getAsMemberPointerType();
244 if (DestMemPtr && SrcMemPtr) {
245 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
246 // can be explicitly converted to an rvalue of type "pointer to member
247 // of Y of type T2" if T1 and T2 are both function types or both object
248 // types.
249 if (DestMemPtr->getPointeeType()->isFunctionType() !=
250 SrcMemPtr->getPointeeType()->isFunctionType()) {
251 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
252 << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
253 return;
254 }
255
256 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
257 // constness.
258 if (CastsAwayConstness(Self, SrcType, DestType)) {
259 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
260 << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
261 return;
262 }
263
264 // A valid member pointer cast.
265 return;
266 }
267
Sebastian Redl26d85b12008-11-05 21:50:06 +0000268 bool destIsPtr = DestType->isPointerType();
269 bool srcIsPtr = SrcType->isPointerType();
270 if (!destIsPtr && !srcIsPtr) {
271 // Except for std::nullptr_t->integer, which is not supported yet, and
272 // lvalue->reference, which is handled above, at least one of the two
273 // arguments must be a pointer.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000274 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000275 << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000276 return;
277 }
278
279 if (SrcType == DestType) {
280 // C++ 5.2.10p2 has a note that mentions that, subject to all other
281 // restrictions, a cast to the same type is allowed. The intent is not
282 // entirely clear here, since all other paragraphs explicitly forbid casts
283 // to the same type. However, the behavior of compilers is pretty consistent
Sebastian Redldb647282009-01-27 23:18:31 +0000284 // on this point: allow same-type conversion if the involved types are
285 // pointers, disallow otherwise.
Sebastian Redl26d85b12008-11-05 21:50:06 +0000286 return;
287 }
288
289 // Note: Clang treats enumeration types as integral types. If this is ever
290 // changed for C++, the additional check here will be redundant.
291 if (DestType->isIntegralType() && !DestType->isEnumeralType()) {
Sebastian Redl03a6cf92008-11-05 22:15:14 +0000292 assert(srcIsPtr && "One type must be a pointer");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000293 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
294 // type large enough to hold it.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000295 if (Self.Context.getTypeSize(SrcType) >
296 Self.Context.getTypeSize(DestType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000297 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_small_int)
Chris Lattnerd1625842008-11-24 06:25:27 +0000298 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000299 }
300 return;
301 }
302
303 if (SrcType->isIntegralType() || SrcType->isEnumeralType()) {
Sebastian Redl03a6cf92008-11-05 22:15:14 +0000304 assert(destIsPtr && "One type must be a pointer");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000305 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
306 // converted to a pointer.
307 return;
308 }
309
310 if (!destIsPtr || !srcIsPtr) {
311 // With the valid non-pointer conversions out of the way, we can be even
312 // more stringent.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000313 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000314 << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000315 return;
316 }
317
318 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000319 if (CastsAwayConstness(Self, SrcType, DestType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000320 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Chris Lattnerd1625842008-11-24 06:25:27 +0000321 << "reinterpret_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000322 return;
323 }
324
325 // Not casting away constness, so the only remaining check is for compatible
326 // pointer categories.
327
328 if (SrcType->isFunctionPointerType()) {
329 if (DestType->isFunctionPointerType()) {
330 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
331 // a pointer to a function of a different type.
332 return;
333 }
334
Sebastian Redl26d85b12008-11-05 21:50:06 +0000335 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
336 // an object type or vice versa is conditionally-supported.
337 // Compilers support it in C++03 too, though, because it's necessary for
338 // casting the return value of dlsym() and GetProcAddress().
339 // FIXME: Conditionally-supported behavior should be configurable in the
340 // TargetInfo or similar.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000341 if (!Self.getLangOptions().CPlusPlus0x) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000342 Self.Diag(OpRange.getBegin(), diag::ext_reinterpret_cast_fn_obj)
343 << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000344 }
345 return;
346 }
347
Sebastian Redl26d85b12008-11-05 21:50:06 +0000348 if (DestType->isFunctionPointerType()) {
349 // See above.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000350 if (!Self.getLangOptions().CPlusPlus0x) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000351 Self.Diag(OpRange.getBegin(), diag::ext_reinterpret_cast_fn_obj)
352 << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000353 }
354 return;
355 }
356
357 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
358 // a pointer to an object of different type.
359 // Void pointers are not specified, but supported by every compiler out there.
360 // So we finish by allowing everything that remains - it's got to be two
361 // object pointers.
362}
363
Sebastian Redldb647282009-01-27 23:18:31 +0000364/// CastsAwayConstness - Check if the pointer conversion from SrcType to
365/// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
366/// the cast checkers. Both arguments must denote pointer (possibly to member)
367/// types.
Sebastian Redl26d85b12008-11-05 21:50:06 +0000368bool
Sebastian Redl37d6de32008-11-08 13:00:26 +0000369CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000370{
Sebastian Redldb647282009-01-27 23:18:31 +0000371 // Casting away constness is defined in C++ 5.2.11p8 with reference to
372 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
373 // the rules are non-trivial. So first we construct Tcv *...cv* as described
374 // in C++ 5.2.11p8.
375 assert((SrcType->isPointerType() || SrcType->isMemberPointerType()) &&
376 "Source type is not pointer or pointer to member.");
377 assert((DestType->isPointerType() || DestType->isMemberPointerType()) &&
378 "Destination type is not pointer or pointer to member.");
Sebastian Redl26d85b12008-11-05 21:50:06 +0000379
380 QualType UnwrappedSrcType = SrcType, UnwrappedDestType = DestType;
381 llvm::SmallVector<unsigned, 8> cv1, cv2;
382
383 // Find the qualifications.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000384 while (Self.UnwrapSimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000385 cv1.push_back(UnwrappedSrcType.getCVRQualifiers());
386 cv2.push_back(UnwrappedDestType.getCVRQualifiers());
387 }
388 assert(cv1.size() > 0 && "Must have at least one pointer level.");
389
390 // Construct void pointers with those qualifiers (in reverse order of
391 // unwrapping, of course).
Sebastian Redl37d6de32008-11-08 13:00:26 +0000392 QualType SrcConstruct = Self.Context.VoidTy;
393 QualType DestConstruct = Self.Context.VoidTy;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000394 for (llvm::SmallVector<unsigned, 8>::reverse_iterator i1 = cv1.rbegin(),
395 i2 = cv2.rbegin();
396 i1 != cv1.rend(); ++i1, ++i2)
397 {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000398 SrcConstruct = Self.Context.getPointerType(
399 SrcConstruct.getQualifiedType(*i1));
400 DestConstruct = Self.Context.getPointerType(
401 DestConstruct.getQualifiedType(*i2));
Sebastian Redl26d85b12008-11-05 21:50:06 +0000402 }
403
404 // Test if they're compatible.
405 return SrcConstruct != DestConstruct &&
Sebastian Redl37d6de32008-11-08 13:00:26 +0000406 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000407}
408
409/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
410/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
411/// implicit conversions explicit and getting rid of data loss warnings.
412void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000413CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
414 const SourceRange &OpRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000415{
416 // The order the tests is not entirely arbitrary. There is one conversion
417 // that can be handled in two different ways. Given:
418 // struct A {};
419 // struct B : public A {
420 // B(); B(const A&);
421 // };
422 // const A &a = B();
423 // the cast static_cast<const B&>(a) could be seen as either a static
424 // reference downcast, or an explicit invocation of the user-defined
425 // conversion using B's conversion constructor.
426 // DR 427 specifies that the downcast is to be applied here.
427
428 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
429 if (DestType->isVoidType()) {
430 return;
431 }
432
433 // C++ 5.2.9p5, reference downcast.
434 // See the function for details.
435 // DR 427 specifies that this is to be applied before paragraph 2.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000436 if (TryStaticReferenceDowncast(Self, SrcExpr, DestType, OpRange)
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000437 > TSC_NotApplicable) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000438 return;
439 }
440
441 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
442 // [...] if the declaration "T t(e);" is well-formed, [...].
Sebastian Redl37d6de32008-11-08 13:00:26 +0000443 if (TryStaticImplicitCast(Self, SrcExpr, DestType, OpRange) >
444 TSC_NotApplicable) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000445 return;
446 }
447
448 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
449 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
450 // conversions, subject to further restrictions.
451 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
452 // of qualification conversions impossible.
453
454 // The lvalue-to-rvalue, array-to-pointer and function-to-pointer conversions
455 // are applied to the expression.
456 QualType OrigSrcType = SrcExpr->getType();
Sebastian Redl37d6de32008-11-08 13:00:26 +0000457 Self.DefaultFunctionArrayConversion(SrcExpr);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000458
Sebastian Redl37d6de32008-11-08 13:00:26 +0000459 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
Sebastian Redl26d85b12008-11-05 21:50:06 +0000460
461 // Reverse integral promotion/conversion. All such conversions are themselves
462 // again integral promotions or conversions and are thus already handled by
463 // p2 (TryDirectInitialization above).
464 // (Note: any data loss warnings should be suppressed.)
465 // The exception is the reverse of enum->integer, i.e. integer->enum (and
466 // enum->enum). See also C++ 5.2.9p7.
467 // The same goes for reverse floating point promotion/conversion and
468 // floating-integral conversions. Again, only floating->enum is relevant.
469 if (DestType->isEnumeralType()) {
470 if (SrcType->isComplexType() || SrcType->isVectorType()) {
471 // Fall through - these cannot be converted.
472 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
473 return;
474 }
475 }
476
477 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
478 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000479 if (TryStaticPointerDowncast(Self, SrcType, DestType, OpRange)
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000480 > TSC_NotApplicable) {
Sebastian Redl26d85b12008-11-05 21:50:06 +0000481 return;
482 }
483
Sebastian Redl21593ac2009-01-28 18:33:18 +0000484 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
Sebastian Redl26d85b12008-11-05 21:50:06 +0000485 // conversion. C++ 5.2.9p9 has additional information.
486 // DR54's access restrictions apply here also.
Sebastian Redl21593ac2009-01-28 18:33:18 +0000487 if (TryStaticMemberPointerUpcast(Self, SrcType, DestType, OpRange)
488 > TSC_NotApplicable) {
489 return;
490 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000491
492 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
493 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
494 // just the usual constness stuff.
495 if (const PointerType *SrcPointer = SrcType->getAsPointerType()) {
496 QualType SrcPointee = SrcPointer->getPointeeType();
497 if (SrcPointee->isVoidType()) {
498 if (const PointerType *DestPointer = DestType->getAsPointerType()) {
499 QualType DestPointee = DestPointer->getPointeeType();
500 if (DestPointee->isObjectType()) {
501 // This is definitely the intended conversion, but it might fail due
502 // to a const violation.
503 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000504 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Chris Lattnerd1625842008-11-24 06:25:27 +0000505 << "static_cast" << DestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000506 }
507 return;
508 }
509 }
510 }
511 }
512
513 // We tried everything. Everything! Nothing works! :-(
514 // FIXME: Error reporting could be a lot better. Should store the reason
515 // why every substep failed and, at the end, select the most specific and
516 // report that.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000517 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000518 << "static_cast" << DestType << OrigSrcType
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000519 << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000520}
521
522/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000523TryStaticCastResult
524TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
525 const SourceRange &OpRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000526{
527 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
528 // cast to type "reference to cv2 D", where D is a class derived from B,
529 // if a valid standard conversion from "pointer to D" to "pointer to B"
530 // exists, cv2 >= cv1, and B is not a virtual base class of D.
531 // In addition, DR54 clarifies that the base must be accessible in the
532 // current context. Although the wording of DR54 only applies to the pointer
533 // variant of this rule, the intent is clearly for it to apply to the this
534 // conversion as well.
535
Sebastian Redl37d6de32008-11-08 13:00:26 +0000536 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000537 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000538 }
539
540 const ReferenceType *DestReference = DestType->getAsReferenceType();
541 if (!DestReference) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000542 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000543 }
544 QualType DestPointee = DestReference->getPointeeType();
545
Sebastian Redl37d6de32008-11-08 13:00:26 +0000546 return TryStaticDowncast(Self, SrcExpr->getType(), DestPointee, OpRange,
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000547 SrcExpr->getType(), DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000548}
549
550/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000551TryStaticCastResult
552TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
553 const SourceRange &OpRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000554{
555 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
556 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
557 // is a class derived from B, if a valid standard conversion from "pointer
558 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
559 // class of D.
560 // In addition, DR54 clarifies that the base must be accessible in the
561 // current context.
562
563 const PointerType *SrcPointer = SrcType->getAsPointerType();
564 if (!SrcPointer) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000565 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000566 }
567
568 const PointerType *DestPointer = DestType->getAsPointerType();
569 if (!DestPointer) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000570 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000571 }
572
Sebastian Redl37d6de32008-11-08 13:00:26 +0000573 return TryStaticDowncast(Self, SrcPointer->getPointeeType(),
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000574 DestPointer->getPointeeType(),
575 OpRange, SrcType, DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000576}
577
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000578/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
579/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
Sebastian Redl26d85b12008-11-05 21:50:06 +0000580/// DestType, both of which must be canonical, is possible and allowed.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000581TryStaticCastResult
582TryStaticDowncast(Sema &Self, QualType SrcType, QualType DestType,
583 const SourceRange &OpRange, QualType OrigSrcType,
584 QualType OrigDestType)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000585{
586 // Downcast can only happen in class hierarchies, so we need classes.
587 if (!DestType->isRecordType() || !SrcType->isRecordType()) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000588 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000589 }
590
591 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
592 /*DetectVirtual=*/true);
Sebastian Redl37d6de32008-11-08 13:00:26 +0000593 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000594 return TSC_NotApplicable;
595 }
596
597 // Target type does derive from source type. Now we're serious. If an error
598 // appears now, it's not ignored.
599 // This may not be entirely in line with the standard. Take for example:
600 // struct A {};
601 // struct B : virtual A {
602 // B(A&);
603 // };
604 //
605 // void f()
606 // {
607 // (void)static_cast<const B&>(*((A*)0));
608 // }
609 // As far as the standard is concerned, p5 does not apply (A is virtual), so
610 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
611 // However, both GCC and Comeau reject this example, and accepting it would
612 // mean more complex code if we're to preserve the nice error message.
613 // FIXME: Being 100% compliant here would be nice to have.
614
615 // Must preserve cv, as always.
616 if (!DestType.isAtLeastAsQualifiedAs(SrcType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000617 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Chris Lattnerd1625842008-11-24 06:25:27 +0000618 << "static_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000619 return TSC_Failed;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000620 }
621
622 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000623 // This code is analoguous to that in CheckDerivedToBaseConversion, except
624 // that it builds the paths in reverse order.
625 // To sum up: record all paths to the base and build a nice string from
626 // them. Use it to spice up the error message.
627 Paths.clear();
628 Paths.setRecordingPaths(true);
Sebastian Redl37d6de32008-11-08 13:00:26 +0000629 Self.IsDerivedFrom(DestType, SrcType, Paths);
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000630 std::string PathDisplayStr;
631 std::set<unsigned> DisplayedPaths;
632 for (BasePaths::paths_iterator Path = Paths.begin();
633 Path != Paths.end(); ++Path) {
634 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
635 // We haven't displayed a path to this particular base
636 // class subobject yet.
637 PathDisplayStr += "\n ";
638 for (BasePath::const_reverse_iterator Element = Path->rbegin();
639 Element != Path->rend(); ++Element)
640 PathDisplayStr += Element->Base->getType().getAsString() + " -> ";
641 PathDisplayStr += DestType.getAsString();
642 }
643 }
644
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000645 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
Chris Lattnerd1625842008-11-24 06:25:27 +0000646 << SrcType.getUnqualifiedType() << DestType.getUnqualifiedType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000647 << PathDisplayStr << OpRange;
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000648 return TSC_Failed;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000649 }
650
651 if (Paths.getDetectedVirtual() != 0) {
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000652 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000653 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
Chris Lattnerd1625842008-11-24 06:25:27 +0000654 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000655 return TSC_Failed;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000656 }
657
658 // FIXME: Test accessibility.
659
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000660 return TSC_Success;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000661}
662
Sebastian Redl21593ac2009-01-28 18:33:18 +0000663/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
664/// C++ 5.2.9p9 is valid:
665///
666/// An rvalue of type "pointer to member of D of type cv1 T" can be
667/// converted to an rvalue of type "pointer to member of B of type cv2 T",
668/// where B is a base class of D [...].
669///
670TryStaticCastResult
671TryStaticMemberPointerUpcast(Sema &Self, QualType SrcType, QualType DestType,
672 const SourceRange &OpRange)
673{
674 const MemberPointerType *SrcMemPtr = SrcType->getAsMemberPointerType();
675 if (!SrcMemPtr)
676 return TSC_NotApplicable;
677 const MemberPointerType *DestMemPtr = DestType->getAsMemberPointerType();
678 if (!DestMemPtr)
679 return TSC_NotApplicable;
680
681 // T == T, modulo cv
682 if (Self.Context.getCanonicalType(
683 SrcMemPtr->getPointeeType().getUnqualifiedType()) !=
684 Self.Context.getCanonicalType(DestMemPtr->getPointeeType().
685 getUnqualifiedType()))
686 return TSC_NotApplicable;
687
688 // B base of D
689 QualType SrcClass(SrcMemPtr->getClass(), 0);
690 QualType DestClass(DestMemPtr->getClass(), 0);
691 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
692 /*DetectVirtual=*/true);
693 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
694 return TSC_NotApplicable;
695 }
696
697 // B is a base of D. But is it an allowed base? If not, it's a hard error.
698 if (Paths.isAmbiguous(DestClass)) {
699 Paths.clear();
700 Paths.setRecordingPaths(true);
701 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
702 assert(StillOkay);
703 StillOkay = StillOkay;
704 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
705 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
706 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
707 return TSC_Failed;
708 }
709
710 if (const CXXRecordType *VBase = Paths.getDetectedVirtual()) {
711 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
712 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
713 return TSC_Failed;
714 }
715
716 // FIXME: Test accessibility.
717
718 return TSC_Success;
719}
720
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000721/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
722/// is valid:
723///
724/// An expression e can be explicitly converted to a type T using a
725/// @c static_cast if the declaration "T t(e);" is well-formed [...].
Sebastian Redl37d6de32008-11-08 13:00:26 +0000726TryStaticCastResult
727TryStaticImplicitCast(Sema &Self, Expr *SrcExpr, QualType DestType,
728 const SourceRange &OpRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000729{
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000730 if (DestType->isReferenceType()) {
731 // At this point of CheckStaticCast, if the destination is a reference,
732 // this has to work. There is no other way that works.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000733 return Self.CheckReferenceInit(SrcExpr, DestType) ?
734 TSC_Failed : TSC_Success;
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000735 }
736 if (DestType->isRecordType()) {
737 // FIXME: Use an implementation of C++ [over.match.ctor] for this.
738 return TSC_NotApplicable;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000739 }
740
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000741 // FIXME: To get a proper error from invalid conversions here, we need to
742 // reimplement more of this.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000743 ImplicitConversionSequence ICS = Self.TryImplicitConversion(
744 SrcExpr, DestType);
Sebastian Redle3dc28a2008-11-07 23:29:29 +0000745 return ICS.ConversionKind == ImplicitConversionSequence::BadConversion ?
746 TSC_NotApplicable : TSC_Success;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000747}
748
749/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
750/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
751/// checked downcasts in class hierarchies.
752void
Sebastian Redl37d6de32008-11-08 13:00:26 +0000753CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
754 const SourceRange &OpRange,
755 const SourceRange &DestRange)
Sebastian Redl26d85b12008-11-05 21:50:06 +0000756{
757 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
Sebastian Redl37d6de32008-11-08 13:00:26 +0000758 DestType = Self.Context.getCanonicalType(DestType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000759
760 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
761 // or "pointer to cv void".
762
763 QualType DestPointee;
764 const PointerType *DestPointer = DestType->getAsPointerType();
765 const ReferenceType *DestReference = DestType->getAsReferenceType();
766 if (DestPointer) {
767 DestPointee = DestPointer->getPointeeType();
768 } else if (DestReference) {
769 DestPointee = DestReference->getPointeeType();
770 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000771 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000772 << OrigDestType << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000773 return;
774 }
775
776 const RecordType *DestRecord = DestPointee->getAsRecordType();
777 if (DestPointee->isVoidType()) {
778 assert(DestPointer && "Reference to void is not possible");
779 } else if (DestRecord) {
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000780 if (Self.DiagnoseIncompleteType(OpRange.getBegin(), DestPointee,
781 diag::err_bad_dynamic_cast_incomplete,
782 DestRange))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000783 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000784 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000785 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000786 << DestPointee.getUnqualifiedType() << DestRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000787 return;
788 }
789
790 // C++ 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
791 // complete class type, [...]. If T is a reference type, v shall be an
792 // lvalue of a complete class type, [...].
793
Sebastian Redl37d6de32008-11-08 13:00:26 +0000794 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000795 QualType SrcPointee;
796 if (DestPointer) {
797 if (const PointerType *SrcPointer = SrcType->getAsPointerType()) {
798 SrcPointee = SrcPointer->getPointeeType();
799 } else {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000800 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
Chris Lattnerd1625842008-11-24 06:25:27 +0000801 << OrigSrcType << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000802 return;
803 }
804 } else {
Sebastian Redl37d6de32008-11-08 13:00:26 +0000805 if (SrcExpr->isLvalue(Self.Context) != Expr::LV_Valid) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000806 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
Chris Lattnerd1625842008-11-24 06:25:27 +0000807 << "dynamic_cast" << OrigDestType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000808 }
809 SrcPointee = SrcType;
810 }
811
812 const RecordType *SrcRecord = SrcPointee->getAsRecordType();
813 if (SrcRecord) {
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000814 if (Self.DiagnoseIncompleteType(OpRange.getBegin(), SrcPointee,
815 diag::err_bad_dynamic_cast_incomplete,
816 SrcExpr->getSourceRange()))
Sebastian Redl26d85b12008-11-05 21:50:06 +0000817 return;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000818 } else {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000819 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000820 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redl26d85b12008-11-05 21:50:06 +0000821 return;
822 }
823
824 assert((DestPointer || DestReference) &&
825 "Bad destination non-ptr/ref slipped through.");
826 assert((DestRecord || DestPointee->isVoidType()) &&
827 "Bad destination pointee slipped through.");
828 assert(SrcRecord && "Bad source pointee slipped through.");
829
830 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
831 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000832 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
Chris Lattnerd1625842008-11-24 06:25:27 +0000833 << "dynamic_cast" << OrigDestType << OrigSrcType << OpRange;
Sebastian Redl26d85b12008-11-05 21:50:06 +0000834 return;
835 }
836
837 // C++ 5.2.7p3: If the type of v is the same as the required result type,
838 // [except for cv].
839 if (DestRecord == SrcRecord) {
840 return;
841 }
842
843 // C++ 5.2.7p5
844 // Upcasts are resolved statically.
Sebastian Redl37d6de32008-11-08 13:00:26 +0000845 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
846 Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
Chris Lattnerd1625842008-11-24 06:25:27 +0000847 OpRange.getBegin(), OpRange);
Sebastian Redl26d85b12008-11-05 21:50:06 +0000848 // Diagnostic already emitted on error.
849 return;
850 }
851
852 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
Sebastian Redl37d6de32008-11-08 13:00:26 +0000853 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition(Self.Context);
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000854 assert(SrcDecl && "Definition missing");
855 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000856 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
Chris Lattnerd1625842008-11-24 06:25:27 +0000857 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000858 }
Sebastian Redl26d85b12008-11-05 21:50:06 +0000859
860 // Done. Everything else is run-time checks.
861}