Driver: tweak handling of '--analyze' to invoke
[clang.git] / lib / Sema / SemaCXXCast.cpp
blobba1c3b0f407c3dea01c290b597bad761c3d57baf
1 //===--- 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.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/Initialization.h"
16 #include "clang/AST/ExprCXX.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/Basic/PartialDiagnostic.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include <set>
22 using namespace clang;
25 static void NoteAllOverloadCandidates(Expr* const Expr, Sema& sema);
27 enum TryCastResult {
28 TC_NotApplicable, ///< The cast method is not applicable.
29 TC_Success, ///< The cast method is appropriate and successful.
30 TC_Failed ///< The cast method is appropriate, but failed. A
31 ///< diagnostic has been emitted.
34 enum CastType {
35 CT_Const, ///< const_cast
36 CT_Static, ///< static_cast
37 CT_Reinterpret, ///< reinterpret_cast
38 CT_Dynamic, ///< dynamic_cast
39 CT_CStyle, ///< (Type)expr
40 CT_Functional ///< Type(expr)
46 static void CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
47 ExprValueKind &VK,
48 const SourceRange &OpRange,
49 const SourceRange &DestRange);
50 static void CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
51 ExprValueKind &VK,
52 const SourceRange &OpRange,
53 const SourceRange &DestRange,
54 CastKind &Kind);
55 static void CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
56 ExprValueKind &VK,
57 const SourceRange &OpRange,
58 CastKind &Kind,
59 CXXCastPath &BasePath);
60 static void CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
61 ExprValueKind &VK,
62 const SourceRange &OpRange,
63 const SourceRange &DestRange,
64 CastKind &Kind,
65 CXXCastPath &BasePath);
67 static bool CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType);
69 // The Try functions attempt a specific way of casting. If they succeed, they
70 // return TC_Success. If their way of casting is not appropriate for the given
71 // arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
72 // to emit if no other way succeeds. If their way of casting is appropriate but
73 // fails, they return TC_Failed and *must* set diag; they can set it to 0 if
74 // they emit a specialized diagnostic.
75 // All diagnostics returned by these functions must expect the same three
76 // arguments:
77 // %0: Cast Type (a value from the CastType enumeration)
78 // %1: Source Type
79 // %2: Destination Type
80 static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
81 QualType DestType, unsigned &msg);
82 static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
83 QualType DestType, bool CStyle,
84 const SourceRange &OpRange,
85 unsigned &msg,
86 CastKind &Kind,
87 CXXCastPath &BasePath);
88 static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
89 QualType DestType, bool CStyle,
90 const SourceRange &OpRange,
91 unsigned &msg,
92 CastKind &Kind,
93 CXXCastPath &BasePath);
94 static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
95 CanQualType DestType, bool CStyle,
96 const SourceRange &OpRange,
97 QualType OrigSrcType,
98 QualType OrigDestType, unsigned &msg,
99 CastKind &Kind,
100 CXXCastPath &BasePath);
101 static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr,
102 QualType SrcType,
103 QualType DestType,bool CStyle,
104 const SourceRange &OpRange,
105 unsigned &msg,
106 CastKind &Kind,
107 CXXCastPath &BasePath);
109 static TryCastResult TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr,
110 QualType DestType, bool CStyle,
111 const SourceRange &OpRange,
112 unsigned &msg,
113 CastKind &Kind);
114 static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
115 QualType DestType, bool CStyle,
116 const SourceRange &OpRange,
117 unsigned &msg,
118 CastKind &Kind,
119 CXXCastPath &BasePath);
120 static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
121 bool CStyle, unsigned &msg);
122 static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
123 QualType DestType, bool CStyle,
124 const SourceRange &OpRange,
125 unsigned &msg,
126 CastKind &Kind);
128 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
129 ExprResult
130 Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
131 SourceLocation LAngleBracketLoc, ParsedType Ty,
132 SourceLocation RAngleBracketLoc,
133 SourceLocation LParenLoc, Expr *E,
134 SourceLocation RParenLoc) {
136 TypeSourceInfo *DestTInfo;
137 QualType DestType = GetTypeFromParser(Ty, &DestTInfo);
138 if (!DestTInfo)
139 DestTInfo = Context.getTrivialTypeSourceInfo(DestType, SourceLocation());
141 return BuildCXXNamedCast(OpLoc, Kind, DestTInfo, move(E),
142 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
143 SourceRange(LParenLoc, RParenLoc));
146 ExprResult
147 Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
148 TypeSourceInfo *DestTInfo, Expr *Ex,
149 SourceRange AngleBrackets, SourceRange Parens) {
150 QualType DestType = DestTInfo->getType();
152 SourceRange OpRange(OpLoc, Parens.getEnd());
153 SourceRange DestRange = AngleBrackets;
155 // If the type is dependent, we won't do the semantic analysis now.
156 // FIXME: should we check this in a more fine-grained manner?
157 bool TypeDependent = DestType->isDependentType() || Ex->isTypeDependent();
159 if (Ex->isBoundMemberFunction(Context))
160 Diag(Ex->getLocStart(), diag::err_invalid_use_of_bound_member_func)
161 << Ex->getSourceRange();
163 ExprValueKind VK = VK_RValue;
164 if (TypeDependent)
165 VK = Expr::getValueKindForType(DestType);
167 switch (Kind) {
168 default: llvm_unreachable("Unknown C++ cast!");
170 case tok::kw_const_cast:
171 if (!TypeDependent)
172 CheckConstCast(*this, Ex, DestType, VK, OpRange, DestRange);
173 return Owned(CXXConstCastExpr::Create(Context,
174 DestType.getNonLValueExprType(Context),
175 VK, Ex, DestTInfo, OpLoc,
176 Parens.getEnd()));
178 case tok::kw_dynamic_cast: {
179 CastKind Kind = CK_Dependent;
180 CXXCastPath BasePath;
181 if (!TypeDependent)
182 CheckDynamicCast(*this, Ex, DestType, VK, OpRange, DestRange,
183 Kind, BasePath);
184 return Owned(CXXDynamicCastExpr::Create(Context,
185 DestType.getNonLValueExprType(Context),
186 VK, Kind, Ex, &BasePath, DestTInfo,
187 OpLoc, Parens.getEnd()));
189 case tok::kw_reinterpret_cast: {
190 CastKind Kind = CK_Dependent;
191 if (!TypeDependent)
192 CheckReinterpretCast(*this, Ex, DestType, VK, OpRange, DestRange, Kind);
193 return Owned(CXXReinterpretCastExpr::Create(Context,
194 DestType.getNonLValueExprType(Context),
195 VK, Kind, Ex, 0,
196 DestTInfo, OpLoc, Parens.getEnd()));
198 case tok::kw_static_cast: {
199 CastKind Kind = CK_Dependent;
200 CXXCastPath BasePath;
201 if (!TypeDependent)
202 CheckStaticCast(*this, Ex, DestType, VK, OpRange, Kind, BasePath);
204 return Owned(CXXStaticCastExpr::Create(Context,
205 DestType.getNonLValueExprType(Context),
206 VK, Kind, Ex, &BasePath,
207 DestTInfo, OpLoc, Parens.getEnd()));
211 return ExprError();
214 /// UnwrapDissimilarPointerTypes - Like Sema::UnwrapSimilarPointerTypes,
215 /// this removes one level of indirection from both types, provided that they're
216 /// the same kind of pointer (plain or to-member). Unlike the Sema function,
217 /// this one doesn't care if the two pointers-to-member don't point into the
218 /// same class. This is because CastsAwayConstness doesn't care.
219 static bool UnwrapDissimilarPointerTypes(QualType& T1, QualType& T2) {
220 const PointerType *T1PtrType = T1->getAs<PointerType>(),
221 *T2PtrType = T2->getAs<PointerType>();
222 if (T1PtrType && T2PtrType) {
223 T1 = T1PtrType->getPointeeType();
224 T2 = T2PtrType->getPointeeType();
225 return true;
227 const ObjCObjectPointerType *T1ObjCPtrType =
228 T1->getAs<ObjCObjectPointerType>(),
229 *T2ObjCPtrType =
230 T2->getAs<ObjCObjectPointerType>();
231 if (T1ObjCPtrType) {
232 if (T2ObjCPtrType) {
233 T1 = T1ObjCPtrType->getPointeeType();
234 T2 = T2ObjCPtrType->getPointeeType();
235 return true;
237 else if (T2PtrType) {
238 T1 = T1ObjCPtrType->getPointeeType();
239 T2 = T2PtrType->getPointeeType();
240 return true;
243 else if (T2ObjCPtrType) {
244 if (T1PtrType) {
245 T2 = T2ObjCPtrType->getPointeeType();
246 T1 = T1PtrType->getPointeeType();
247 return true;
251 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
252 *T2MPType = T2->getAs<MemberPointerType>();
253 if (T1MPType && T2MPType) {
254 T1 = T1MPType->getPointeeType();
255 T2 = T2MPType->getPointeeType();
256 return true;
259 const BlockPointerType *T1BPType = T1->getAs<BlockPointerType>(),
260 *T2BPType = T2->getAs<BlockPointerType>();
261 if (T1BPType && T2BPType) {
262 T1 = T1BPType->getPointeeType();
263 T2 = T2BPType->getPointeeType();
264 return true;
267 return false;
270 /// CastsAwayConstness - Check if the pointer conversion from SrcType to
271 /// DestType casts away constness as defined in C++ 5.2.11p8ff. This is used by
272 /// the cast checkers. Both arguments must denote pointer (possibly to member)
273 /// types.
274 static bool
275 CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType) {
276 // Casting away constness is defined in C++ 5.2.11p8 with reference to
277 // C++ 4.4. We piggyback on Sema::IsQualificationConversion for this, since
278 // the rules are non-trivial. So first we construct Tcv *...cv* as described
279 // in C++ 5.2.11p8.
280 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
281 SrcType->isBlockPointerType()) &&
282 "Source type is not pointer or pointer to member.");
283 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
284 DestType->isBlockPointerType()) &&
285 "Destination type is not pointer or pointer to member.");
287 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
288 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
289 llvm::SmallVector<Qualifiers, 8> cv1, cv2;
291 // Find the qualifications.
292 while (UnwrapDissimilarPointerTypes(UnwrappedSrcType, UnwrappedDestType)) {
293 Qualifiers SrcQuals;
294 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
295 cv1.push_back(SrcQuals);
297 Qualifiers DestQuals;
298 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
299 cv2.push_back(DestQuals);
301 if (cv1.empty())
302 return false;
304 // Construct void pointers with those qualifiers (in reverse order of
305 // unwrapping, of course).
306 QualType SrcConstruct = Self.Context.VoidTy;
307 QualType DestConstruct = Self.Context.VoidTy;
308 ASTContext &Context = Self.Context;
309 for (llvm::SmallVector<Qualifiers, 8>::reverse_iterator i1 = cv1.rbegin(),
310 i2 = cv2.rbegin();
311 i1 != cv1.rend(); ++i1, ++i2) {
312 SrcConstruct
313 = Context.getPointerType(Context.getQualifiedType(SrcConstruct, *i1));
314 DestConstruct
315 = Context.getPointerType(Context.getQualifiedType(DestConstruct, *i2));
318 // Test if they're compatible.
319 return SrcConstruct != DestConstruct &&
320 !Self.IsQualificationConversion(SrcConstruct, DestConstruct);
323 /// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
324 /// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
325 /// checked downcasts in class hierarchies.
326 static void
327 CheckDynamicCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
328 ExprValueKind &VK, const SourceRange &OpRange,
329 const SourceRange &DestRange, CastKind &Kind,
330 CXXCastPath &BasePath) {
331 QualType OrigDestType = DestType, OrigSrcType = SrcExpr->getType();
332 DestType = Self.Context.getCanonicalType(DestType);
334 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
335 // or "pointer to cv void".
337 QualType DestPointee;
338 const PointerType *DestPointer = DestType->getAs<PointerType>();
339 const ReferenceType *DestReference = 0;
340 if (DestPointer) {
341 DestPointee = DestPointer->getPointeeType();
342 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
343 DestPointee = DestReference->getPointeeType();
344 VK = isa<LValueReferenceType>(DestReference) ? VK_LValue : VK_RValue;
345 } else {
346 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
347 << OrigDestType << DestRange;
348 return;
351 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
352 if (DestPointee->isVoidType()) {
353 assert(DestPointer && "Reference to void is not possible");
354 } else if (DestRecord) {
355 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
356 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
357 << DestRange))
358 return;
359 } else {
360 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
361 << DestPointee.getUnqualifiedType() << DestRange;
362 return;
365 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
366 // complete class type, [...]. If T is an lvalue reference type, v shall be
367 // an lvalue of a complete class type, [...]. If T is an rvalue reference
368 // type, v shall be an expression having a complete effective class type,
369 // [...]
371 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
372 QualType SrcPointee;
373 if (DestPointer) {
374 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
375 SrcPointee = SrcPointer->getPointeeType();
376 } else {
377 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
378 << OrigSrcType << SrcExpr->getSourceRange();
379 return;
381 } else if (DestReference->isLValueReferenceType()) {
382 if (!SrcExpr->isLValue()) {
383 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
384 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
386 SrcPointee = SrcType;
387 } else {
388 SrcPointee = SrcType;
391 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
392 if (SrcRecord) {
393 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
394 Self.PDiag(diag::err_bad_dynamic_cast_incomplete)
395 << SrcExpr->getSourceRange()))
396 return;
397 } else {
398 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
399 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
400 return;
403 assert((DestPointer || DestReference) &&
404 "Bad destination non-ptr/ref slipped through.");
405 assert((DestRecord || DestPointee->isVoidType()) &&
406 "Bad destination pointee slipped through.");
407 assert(SrcRecord && "Bad source pointee slipped through.");
409 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
410 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
411 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_const_away)
412 << CT_Dynamic << OrigSrcType << OrigDestType << OpRange;
413 return;
416 // C++ 5.2.7p3: If the type of v is the same as the required result type,
417 // [except for cv].
418 if (DestRecord == SrcRecord) {
419 Kind = CK_NoOp;
420 return;
423 // C++ 5.2.7p5
424 // Upcasts are resolved statically.
425 if (DestRecord && Self.IsDerivedFrom(SrcPointee, DestPointee)) {
426 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
427 OpRange.getBegin(), OpRange,
428 &BasePath))
429 return;
431 Kind = CK_DerivedToBase;
433 // If we are casting to or through a virtual base class, we need a
434 // vtable.
435 if (Self.BasePathInvolvesVirtualBase(BasePath))
436 Self.MarkVTableUsed(OpRange.getBegin(),
437 cast<CXXRecordDecl>(SrcRecord->getDecl()));
438 return;
441 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
442 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
443 assert(SrcDecl && "Definition missing");
444 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
445 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
446 << SrcPointee.getUnqualifiedType() << SrcExpr->getSourceRange();
448 Self.MarkVTableUsed(OpRange.getBegin(),
449 cast<CXXRecordDecl>(SrcRecord->getDecl()));
451 // Done. Everything else is run-time checks.
452 Kind = CK_Dynamic;
455 /// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
456 /// Refer to C++ 5.2.11 for details. const_cast is typically used in code
457 /// like this:
458 /// const char *str = "literal";
459 /// legacy_function(const_cast\<char*\>(str));
460 void
461 CheckConstCast(Sema &Self, Expr *&SrcExpr, QualType DestType, ExprValueKind &VK,
462 const SourceRange &OpRange, const SourceRange &DestRange) {
463 VK = Expr::getValueKindForType(DestType);
464 if (VK == VK_RValue)
465 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
467 unsigned msg = diag::err_bad_cxx_cast_generic;
468 if (TryConstCast(Self, SrcExpr, DestType, /*CStyle*/false, msg) != TC_Success
469 && msg != 0)
470 Self.Diag(OpRange.getBegin(), msg) << CT_Const
471 << SrcExpr->getType() << DestType << OpRange;
474 /// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
475 /// valid.
476 /// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
477 /// like this:
478 /// char *bytes = reinterpret_cast\<char*\>(int_ptr);
479 void
480 CheckReinterpretCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
481 ExprValueKind &VK, const SourceRange &OpRange,
482 const SourceRange &DestRange, CastKind &Kind) {
483 VK = Expr::getValueKindForType(DestType);
484 if (VK == VK_RValue)
485 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
487 unsigned msg = diag::err_bad_cxx_cast_generic;
488 if (TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange,
489 msg, Kind)
490 != TC_Success && msg != 0)
492 if (SrcExpr->getType() == Self.Context.OverloadTy)
494 //FIXME: &f<int>; is overloaded and resolvable
495 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
496 << OverloadExpr::find(SrcExpr).Expression->getName()
497 << DestType << OpRange;
498 NoteAllOverloadCandidates(SrcExpr, Self);
501 else
502 Self.Diag(OpRange.getBegin(), msg) << CT_Reinterpret
503 << SrcExpr->getType() << DestType << OpRange;
509 /// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
510 /// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
511 /// implicit conversions explicit and getting rid of data loss warnings.
512 void
513 CheckStaticCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
514 ExprValueKind &VK, const SourceRange &OpRange,
515 CastKind &Kind, CXXCastPath &BasePath) {
516 // This test is outside everything else because it's the only case where
517 // a non-lvalue-reference target type does not lead to decay.
518 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
519 if (DestType->isVoidType()) {
520 Self.IgnoredValueConversions(SrcExpr);
521 Kind = CK_ToVoid;
522 return;
525 VK = Expr::getValueKindForType(DestType);
526 if (VK == VK_RValue && !DestType->isRecordType())
527 Self.DefaultFunctionArrayLvalueConversion(SrcExpr);
529 unsigned msg = diag::err_bad_cxx_cast_generic;
530 if (TryStaticCast(Self, SrcExpr, DestType, /*CStyle*/false, OpRange, msg,
531 Kind, BasePath) != TC_Success && msg != 0)
533 if (SrcExpr->getType() == Self.Context.OverloadTy)
535 OverloadExpr* oe = OverloadExpr::find(SrcExpr).Expression;
536 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
537 << oe->getName() << DestType << OpRange << oe->getQualifierRange();
538 NoteAllOverloadCandidates(SrcExpr, Self);
540 else
541 Self.Diag(OpRange.getBegin(), msg) << CT_Static
542 << SrcExpr->getType() << DestType << OpRange;
544 else if (Kind == CK_BitCast)
545 Self.CheckCastAlign(SrcExpr, DestType, OpRange);
548 /// TryStaticCast - Check if a static cast can be performed, and do so if
549 /// possible. If @p CStyle, ignore access restrictions on hierarchy casting
550 /// and casting away constness.
551 static TryCastResult TryStaticCast(Sema &Self, Expr *&SrcExpr,
552 QualType DestType, bool CStyle,
553 const SourceRange &OpRange, unsigned &msg,
554 CastKind &Kind,
555 CXXCastPath &BasePath) {
556 // The order the tests is not entirely arbitrary. There is one conversion
557 // that can be handled in two different ways. Given:
558 // struct A {};
559 // struct B : public A {
560 // B(); B(const A&);
561 // };
562 // const A &a = B();
563 // the cast static_cast<const B&>(a) could be seen as either a static
564 // reference downcast, or an explicit invocation of the user-defined
565 // conversion using B's conversion constructor.
566 // DR 427 specifies that the downcast is to be applied here.
568 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
569 // Done outside this function.
571 TryCastResult tcr;
573 // C++ 5.2.9p5, reference downcast.
574 // See the function for details.
575 // DR 427 specifies that this is to be applied before paragraph 2.
576 tcr = TryStaticReferenceDowncast(Self, SrcExpr, DestType, CStyle, OpRange,
577 msg, Kind, BasePath);
578 if (tcr != TC_NotApplicable)
579 return tcr;
581 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
582 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
583 tcr = TryLValueToRValueCast(Self, SrcExpr, DestType, msg);
584 if (tcr != TC_NotApplicable) {
585 Kind = CK_NoOp;
586 return tcr;
589 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
590 // [...] if the declaration "T t(e);" is well-formed, [...].
591 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CStyle, OpRange, msg,
592 Kind);
593 if (tcr != TC_NotApplicable)
594 return tcr;
596 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
597 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
598 // conversions, subject to further restrictions.
599 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
600 // of qualification conversions impossible.
601 // In the CStyle case, the earlier attempt to const_cast should have taken
602 // care of reverse qualification conversions.
604 QualType OrigSrcType = SrcExpr->getType();
606 QualType SrcType = Self.Context.getCanonicalType(SrcExpr->getType());
608 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
609 // converted to an integral type.
610 if (Self.getLangOptions().CPlusPlus0x && SrcType->isEnumeralType()) {
611 assert(SrcType->getAs<EnumType>()->getDecl()->isScoped());
612 if (DestType->isBooleanType()) {
613 Kind = CK_IntegralToBoolean;
614 return TC_Success;
615 } else if (DestType->isIntegralType(Self.Context)) {
616 Kind = CK_IntegralCast;
617 return TC_Success;
621 // Reverse integral promotion/conversion. All such conversions are themselves
622 // again integral promotions or conversions and are thus already handled by
623 // p2 (TryDirectInitialization above).
624 // (Note: any data loss warnings should be suppressed.)
625 // The exception is the reverse of enum->integer, i.e. integer->enum (and
626 // enum->enum). See also C++ 5.2.9p7.
627 // The same goes for reverse floating point promotion/conversion and
628 // floating-integral conversions. Again, only floating->enum is relevant.
629 if (DestType->isEnumeralType()) {
630 if (SrcType->isComplexType() || SrcType->isVectorType()) {
631 // Fall through - these cannot be converted.
632 } else if (SrcType->isArithmeticType() || SrcType->isEnumeralType()) {
633 Kind = CK_IntegralCast;
634 return TC_Success;
638 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
639 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
640 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
641 Kind, BasePath);
642 if (tcr != TC_NotApplicable)
643 return tcr;
645 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
646 // conversion. C++ 5.2.9p9 has additional information.
647 // DR54's access restrictions apply here also.
648 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
649 OpRange, msg, Kind, BasePath);
650 if (tcr != TC_NotApplicable)
651 return tcr;
653 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
654 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
655 // just the usual constness stuff.
656 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
657 QualType SrcPointee = SrcPointer->getPointeeType();
658 if (SrcPointee->isVoidType()) {
659 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
660 QualType DestPointee = DestPointer->getPointeeType();
661 if (DestPointee->isIncompleteOrObjectType()) {
662 // This is definitely the intended conversion, but it might fail due
663 // to a const violation.
664 if (!CStyle && !DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
665 msg = diag::err_bad_cxx_cast_const_away;
666 return TC_Failed;
668 Kind = CK_BitCast;
669 return TC_Success;
672 else if (DestType->isObjCObjectPointerType()) {
673 // allow both c-style cast and static_cast of objective-c pointers as
674 // they are pervasive.
675 Kind = CK_AnyPointerToObjCPointerCast;
676 return TC_Success;
678 else if (CStyle && DestType->isBlockPointerType()) {
679 // allow c-style cast of void * to block pointers.
680 Kind = CK_AnyPointerToBlockPointerCast;
681 return TC_Success;
685 // Allow arbitray objective-c pointer conversion with static casts.
686 if (SrcType->isObjCObjectPointerType() &&
687 DestType->isObjCObjectPointerType()) {
688 Kind = CK_BitCast;
689 return TC_Success;
692 // We tried everything. Everything! Nothing works! :-(
693 return TC_NotApplicable;
696 /// Tests whether a conversion according to N2844 is valid.
697 TryCastResult
698 TryLValueToRValueCast(Sema &Self, Expr *SrcExpr, QualType DestType,
699 unsigned &msg) {
700 // N2844 5.2.9p3: An lvalue of type "cv1 T1" can be cast to type "rvalue
701 // reference to cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
702 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
703 if (!R)
704 return TC_NotApplicable;
706 if (!SrcExpr->isLValue())
707 return TC_NotApplicable;
709 // Because we try the reference downcast before this function, from now on
710 // this is the only cast possibility, so we issue an error if we fail now.
711 // FIXME: Should allow casting away constness if CStyle.
712 bool DerivedToBase;
713 bool ObjCConversion;
714 if (Self.CompareReferenceRelationship(SrcExpr->getLocStart(),
715 SrcExpr->getType(), R->getPointeeType(),
716 DerivedToBase, ObjCConversion) <
717 Sema::Ref_Compatible_With_Added_Qualification) {
718 msg = diag::err_bad_lvalue_to_rvalue_cast;
719 return TC_Failed;
722 // FIXME: We should probably have an AST node for lvalue-to-rvalue
723 // conversions.
724 return TC_Success;
727 /// Tests whether a conversion according to C++ 5.2.9p5 is valid.
728 TryCastResult
729 TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
730 bool CStyle, const SourceRange &OpRange,
731 unsigned &msg, CastKind &Kind,
732 CXXCastPath &BasePath) {
733 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
734 // cast to type "reference to cv2 D", where D is a class derived from B,
735 // if a valid standard conversion from "pointer to D" to "pointer to B"
736 // exists, cv2 >= cv1, and B is not a virtual base class of D.
737 // In addition, DR54 clarifies that the base must be accessible in the
738 // current context. Although the wording of DR54 only applies to the pointer
739 // variant of this rule, the intent is clearly for it to apply to the this
740 // conversion as well.
742 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
743 if (!DestReference) {
744 return TC_NotApplicable;
746 bool RValueRef = DestReference->isRValueReferenceType();
747 if (!RValueRef && !SrcExpr->isLValue()) {
748 // We know the left side is an lvalue reference, so we can suggest a reason.
749 msg = diag::err_bad_cxx_cast_rvalue;
750 return TC_NotApplicable;
753 QualType DestPointee = DestReference->getPointeeType();
755 return TryStaticDowncast(Self,
756 Self.Context.getCanonicalType(SrcExpr->getType()),
757 Self.Context.getCanonicalType(DestPointee), CStyle,
758 OpRange, SrcExpr->getType(), DestType, msg, Kind,
759 BasePath);
762 /// Tests whether a conversion according to C++ 5.2.9p8 is valid.
763 TryCastResult
764 TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
765 bool CStyle, const SourceRange &OpRange,
766 unsigned &msg, CastKind &Kind,
767 CXXCastPath &BasePath) {
768 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
769 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
770 // is a class derived from B, if a valid standard conversion from "pointer
771 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
772 // class of D.
773 // In addition, DR54 clarifies that the base must be accessible in the
774 // current context.
776 const PointerType *DestPointer = DestType->getAs<PointerType>();
777 if (!DestPointer) {
778 return TC_NotApplicable;
781 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
782 if (!SrcPointer) {
783 msg = diag::err_bad_static_cast_pointer_nonpointer;
784 return TC_NotApplicable;
787 return TryStaticDowncast(Self,
788 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
789 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
790 CStyle, OpRange, SrcType, DestType, msg, Kind,
791 BasePath);
794 /// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
795 /// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
796 /// DestType is possible and allowed.
797 TryCastResult
798 TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
799 bool CStyle, const SourceRange &OpRange, QualType OrigSrcType,
800 QualType OrigDestType, unsigned &msg,
801 CastKind &Kind, CXXCastPath &BasePath) {
802 // We can only work with complete types. But don't complain if it doesn't work
803 if (Self.RequireCompleteType(OpRange.getBegin(), SrcType, Self.PDiag(0)) ||
804 Self.RequireCompleteType(OpRange.getBegin(), DestType, Self.PDiag(0)))
805 return TC_NotApplicable;
807 // Downcast can only happen in class hierarchies, so we need classes.
808 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
809 return TC_NotApplicable;
812 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
813 /*DetectVirtual=*/true);
814 if (!Self.IsDerivedFrom(DestType, SrcType, Paths)) {
815 return TC_NotApplicable;
818 // Target type does derive from source type. Now we're serious. If an error
819 // appears now, it's not ignored.
820 // This may not be entirely in line with the standard. Take for example:
821 // struct A {};
822 // struct B : virtual A {
823 // B(A&);
824 // };
826 // void f()
827 // {
828 // (void)static_cast<const B&>(*((A*)0));
829 // }
830 // As far as the standard is concerned, p5 does not apply (A is virtual), so
831 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
832 // However, both GCC and Comeau reject this example, and accepting it would
833 // mean more complex code if we're to preserve the nice error message.
834 // FIXME: Being 100% compliant here would be nice to have.
836 // Must preserve cv, as always, unless we're in C-style mode.
837 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
838 msg = diag::err_bad_cxx_cast_const_away;
839 return TC_Failed;
842 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
843 // This code is analoguous to that in CheckDerivedToBaseConversion, except
844 // that it builds the paths in reverse order.
845 // To sum up: record all paths to the base and build a nice string from
846 // them. Use it to spice up the error message.
847 if (!Paths.isRecordingPaths()) {
848 Paths.clear();
849 Paths.setRecordingPaths(true);
850 Self.IsDerivedFrom(DestType, SrcType, Paths);
852 std::string PathDisplayStr;
853 std::set<unsigned> DisplayedPaths;
854 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
855 PI != PE; ++PI) {
856 if (DisplayedPaths.insert(PI->back().SubobjectNumber).second) {
857 // We haven't displayed a path to this particular base
858 // class subobject yet.
859 PathDisplayStr += "\n ";
860 for (CXXBasePath::const_reverse_iterator EI = PI->rbegin(),
861 EE = PI->rend();
862 EI != EE; ++EI)
863 PathDisplayStr += EI->Base->getType().getAsString() + " -> ";
864 PathDisplayStr += QualType(DestType).getAsString();
868 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
869 << QualType(SrcType).getUnqualifiedType()
870 << QualType(DestType).getUnqualifiedType()
871 << PathDisplayStr << OpRange;
872 msg = 0;
873 return TC_Failed;
876 if (Paths.getDetectedVirtual() != 0) {
877 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
878 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
879 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
880 msg = 0;
881 return TC_Failed;
884 if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
885 SrcType, DestType,
886 Paths.front(),
887 diag::err_downcast_from_inaccessible_base)) {
888 msg = 0;
889 return TC_Failed;
892 Self.BuildBasePathArray(Paths, BasePath);
893 Kind = CK_BaseToDerived;
894 return TC_Success;
897 /// TryStaticMemberPointerUpcast - Tests whether a conversion according to
898 /// C++ 5.2.9p9 is valid:
900 /// An rvalue of type "pointer to member of D of type cv1 T" can be
901 /// converted to an rvalue of type "pointer to member of B of type cv2 T",
902 /// where B is a base class of D [...].
904 TryCastResult
905 TryStaticMemberPointerUpcast(Sema &Self, Expr *&SrcExpr, QualType SrcType,
906 QualType DestType, bool CStyle,
907 const SourceRange &OpRange,
908 unsigned &msg, CastKind &Kind,
909 CXXCastPath &BasePath) {
910 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
911 if (!DestMemPtr)
912 return TC_NotApplicable;
914 bool WasOverloadedFunction = false;
915 DeclAccessPair FoundOverload;
916 if (SrcExpr->getType() == Self.Context.OverloadTy) {
917 if (FunctionDecl *Fn
918 = Self.ResolveAddressOfOverloadedFunction(SrcExpr, DestType, false,
919 FoundOverload)) {
920 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
921 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
922 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
923 WasOverloadedFunction = true;
927 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
928 if (!SrcMemPtr) {
929 msg = diag::err_bad_static_cast_member_pointer_nonmp;
930 return TC_NotApplicable;
933 // T == T, modulo cv
934 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
935 DestMemPtr->getPointeeType()))
936 return TC_NotApplicable;
938 // B base of D
939 QualType SrcClass(SrcMemPtr->getClass(), 0);
940 QualType DestClass(DestMemPtr->getClass(), 0);
941 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
942 /*DetectVirtual=*/true);
943 if (!Self.IsDerivedFrom(SrcClass, DestClass, Paths)) {
944 return TC_NotApplicable;
947 // B is a base of D. But is it an allowed base? If not, it's a hard error.
948 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
949 Paths.clear();
950 Paths.setRecordingPaths(true);
951 bool StillOkay = Self.IsDerivedFrom(SrcClass, DestClass, Paths);
952 assert(StillOkay);
953 (void)StillOkay;
954 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
955 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
956 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
957 msg = 0;
958 return TC_Failed;
961 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
962 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
963 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
964 msg = 0;
965 return TC_Failed;
968 if (!CStyle && Self.CheckBaseClassAccess(OpRange.getBegin(),
969 DestClass, SrcClass,
970 Paths.front(),
971 diag::err_upcast_to_inaccessible_base)) {
972 msg = 0;
973 return TC_Failed;
976 if (WasOverloadedFunction) {
977 // Resolve the address of the overloaded function again, this time
978 // allowing complaints if something goes wrong.
979 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr,
980 DestType,
981 true,
982 FoundOverload);
983 if (!Fn) {
984 msg = 0;
985 return TC_Failed;
988 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
989 if (!SrcExpr) {
990 msg = 0;
991 return TC_Failed;
995 Self.BuildBasePathArray(Paths, BasePath);
996 Kind = CK_DerivedToBaseMemberPointer;
997 return TC_Success;
1000 /// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1001 /// is valid:
1003 /// An expression e can be explicitly converted to a type T using a
1004 /// @c static_cast if the declaration "T t(e);" is well-formed [...].
1005 TryCastResult
1006 TryStaticImplicitCast(Sema &Self, Expr *&SrcExpr, QualType DestType,
1007 bool CStyle, const SourceRange &OpRange, unsigned &msg,
1008 CastKind &Kind) {
1009 if (DestType->isRecordType()) {
1010 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1011 diag::err_bad_dynamic_cast_incomplete)) {
1012 msg = 0;
1013 return TC_Failed;
1017 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1018 InitializationKind InitKind
1019 = InitializationKind::CreateCast(/*FIXME:*/OpRange,
1020 CStyle);
1021 InitializationSequence InitSeq(Self, Entity, InitKind, &SrcExpr, 1);
1023 // At this point of CheckStaticCast, if the destination is a reference,
1024 // or the expression is an overload expression this has to work.
1025 // There is no other way that works.
1026 // On the other hand, if we're checking a C-style cast, we've still got
1027 // the reinterpret_cast way.
1029 if (InitSeq.getKind() == InitializationSequence::FailedSequence &&
1030 (CStyle || !DestType->isReferenceType()))
1031 return TC_NotApplicable;
1033 ExprResult Result
1034 = InitSeq.Perform(Self, Entity, InitKind, MultiExprArg(Self, &SrcExpr, 1));
1035 if (Result.isInvalid()) {
1036 msg = 0;
1037 return TC_Failed;
1040 if (InitSeq.isConstructorInitialization())
1041 Kind = CK_ConstructorConversion;
1042 else
1043 Kind = CK_NoOp;
1045 SrcExpr = Result.takeAs<Expr>();
1046 return TC_Success;
1049 /// TryConstCast - See if a const_cast from source to destination is allowed,
1050 /// and perform it if it is.
1051 static TryCastResult TryConstCast(Sema &Self, Expr *SrcExpr, QualType DestType,
1052 bool CStyle, unsigned &msg) {
1053 DestType = Self.Context.getCanonicalType(DestType);
1054 QualType SrcType = SrcExpr->getType();
1055 if (const LValueReferenceType *DestTypeTmp =
1056 DestType->getAs<LValueReferenceType>()) {
1057 if (!SrcExpr->isLValue()) {
1058 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1059 // is C-style, static_cast might find a way, so we simply suggest a
1060 // message and tell the parent to keep searching.
1061 msg = diag::err_bad_cxx_cast_rvalue;
1062 return TC_NotApplicable;
1065 // C++ 5.2.11p4: An lvalue of type T1 can be [cast] to an lvalue of type T2
1066 // [...] if a pointer to T1 can be [cast] to the type pointer to T2.
1067 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1068 SrcType = Self.Context.getPointerType(SrcType);
1071 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1072 // the rules for const_cast are the same as those used for pointers.
1074 if (!DestType->isPointerType() &&
1075 !DestType->isMemberPointerType() &&
1076 !DestType->isObjCObjectPointerType()) {
1077 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1078 // was a reference type, we converted it to a pointer above.
1079 // The status of rvalue references isn't entirely clear, but it looks like
1080 // conversion to them is simply invalid.
1081 // C++ 5.2.11p3: For two pointer types [...]
1082 if (!CStyle)
1083 msg = diag::err_bad_const_cast_dest;
1084 return TC_NotApplicable;
1086 if (DestType->isFunctionPointerType() ||
1087 DestType->isMemberFunctionPointerType()) {
1088 // Cannot cast direct function pointers.
1089 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1090 // T is the ultimate pointee of source and target type.
1091 if (!CStyle)
1092 msg = diag::err_bad_const_cast_dest;
1093 return TC_NotApplicable;
1095 SrcType = Self.Context.getCanonicalType(SrcType);
1097 // Unwrap the pointers. Ignore qualifiers. Terminate early if the types are
1098 // completely equal.
1099 // FIXME: const_cast should probably not be able to convert between pointers
1100 // to different address spaces.
1101 // C++ 5.2.11p3 describes the core semantics of const_cast. All cv specifiers
1102 // in multi-level pointers may change, but the level count must be the same,
1103 // as must be the final pointee type.
1104 while (SrcType != DestType &&
1105 Self.Context.UnwrapSimilarPointerTypes(SrcType, DestType)) {
1106 Qualifiers Quals;
1107 SrcType = Self.Context.getUnqualifiedArrayType(SrcType, Quals);
1108 DestType = Self.Context.getUnqualifiedArrayType(DestType, Quals);
1111 // Since we're dealing in canonical types, the remainder must be the same.
1112 if (SrcType != DestType)
1113 return TC_NotApplicable;
1115 return TC_Success;
1119 static void NoteAllOverloadCandidates(Expr* const Expr, Sema& sema)
1122 assert(Expr->getType() == sema.Context.OverloadTy);
1124 OverloadExpr::FindResult Ovl = OverloadExpr::find(Expr);
1125 OverloadExpr *const OvlExpr = Ovl.Expression;
1127 for (UnresolvedSetIterator it = OvlExpr->decls_begin(),
1128 end = OvlExpr->decls_end(); it != end; ++it) {
1129 if ( FunctionTemplateDecl *ftd =
1130 dyn_cast<FunctionTemplateDecl>((*it)->getUnderlyingDecl()) )
1132 sema.NoteOverloadCandidate(ftd->getTemplatedDecl());
1134 else if ( FunctionDecl *f =
1135 dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl()) )
1137 sema.NoteOverloadCandidate(f);
1143 static TryCastResult TryReinterpretCast(Sema &Self, Expr *SrcExpr,
1144 QualType DestType, bool CStyle,
1145 const SourceRange &OpRange,
1146 unsigned &msg,
1147 CastKind &Kind) {
1148 bool IsLValueCast = false;
1150 DestType = Self.Context.getCanonicalType(DestType);
1151 QualType SrcType = SrcExpr->getType();
1153 // Is the source an overloaded name? (i.e. &foo)
1154 // If so, reinterpret_cast can not help us here (13.4, p1, bullet 5)
1155 if (SrcType == Self.Context.OverloadTy)
1156 return TC_NotApplicable;
1158 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
1159 bool LValue = DestTypeTmp->isLValueReferenceType();
1160 if (LValue && !SrcExpr->isLValue()) {
1161 // Cannot cast non-lvalue to reference type. See the similar comment in
1162 // const_cast.
1163 msg = diag::err_bad_cxx_cast_rvalue;
1164 return TC_NotApplicable;
1167 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
1168 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
1169 // built-in & and * operators.
1170 // This code does this transformation for the checked types.
1171 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1172 SrcType = Self.Context.getPointerType(SrcType);
1174 IsLValueCast = true;
1177 // Canonicalize source for comparison.
1178 SrcType = Self.Context.getCanonicalType(SrcType);
1180 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
1181 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
1182 if (DestMemPtr && SrcMemPtr) {
1183 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
1184 // can be explicitly converted to an rvalue of type "pointer to member
1185 // of Y of type T2" if T1 and T2 are both function types or both object
1186 // types.
1187 if (DestMemPtr->getPointeeType()->isFunctionType() !=
1188 SrcMemPtr->getPointeeType()->isFunctionType())
1189 return TC_NotApplicable;
1191 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
1192 // constness.
1193 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
1194 // we accept it.
1195 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1196 msg = diag::err_bad_cxx_cast_const_away;
1197 return TC_Failed;
1200 // Don't allow casting between member pointers of different sizes.
1201 if (Self.Context.getTypeSize(DestMemPtr) !=
1202 Self.Context.getTypeSize(SrcMemPtr)) {
1203 msg = diag::err_bad_cxx_cast_member_pointer_size;
1204 return TC_Failed;
1207 // A valid member pointer cast.
1208 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
1209 return TC_Success;
1212 // See below for the enumeral issue.
1213 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
1214 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
1215 // type large enough to hold it. A value of std::nullptr_t can be
1216 // converted to an integral type; the conversion has the same meaning
1217 // and validity as a conversion of (void*)0 to the integral type.
1218 if (Self.Context.getTypeSize(SrcType) >
1219 Self.Context.getTypeSize(DestType)) {
1220 msg = diag::err_bad_reinterpret_cast_small_int;
1221 return TC_Failed;
1223 Kind = CK_PointerToIntegral;
1224 return TC_Success;
1227 bool destIsVector = DestType->isVectorType();
1228 bool srcIsVector = SrcType->isVectorType();
1229 if (srcIsVector || destIsVector) {
1230 // FIXME: Should this also apply to floating point types?
1231 bool srcIsScalar = SrcType->isIntegralType(Self.Context);
1232 bool destIsScalar = DestType->isIntegralType(Self.Context);
1234 // Check if this is a cast between a vector and something else.
1235 if (!(srcIsScalar && destIsVector) && !(srcIsVector && destIsScalar) &&
1236 !(srcIsVector && destIsVector))
1237 return TC_NotApplicable;
1239 // If both types have the same size, we can successfully cast.
1240 if (Self.Context.getTypeSize(SrcType)
1241 == Self.Context.getTypeSize(DestType)) {
1242 Kind = CK_BitCast;
1243 return TC_Success;
1246 if (destIsScalar)
1247 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
1248 else if (srcIsScalar)
1249 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
1250 else
1251 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
1253 return TC_Failed;
1256 bool destIsPtr = DestType->isAnyPointerType() ||
1257 DestType->isBlockPointerType();
1258 bool srcIsPtr = SrcType->isAnyPointerType() ||
1259 SrcType->isBlockPointerType();
1260 if (!destIsPtr && !srcIsPtr) {
1261 // Except for std::nullptr_t->integer and lvalue->reference, which are
1262 // handled above, at least one of the two arguments must be a pointer.
1263 return TC_NotApplicable;
1266 if (SrcType == DestType) {
1267 // C++ 5.2.10p2 has a note that mentions that, subject to all other
1268 // restrictions, a cast to the same type is allowed. The intent is not
1269 // entirely clear here, since all other paragraphs explicitly forbid casts
1270 // to the same type. However, the behavior of compilers is pretty consistent
1271 // on this point: allow same-type conversion if the involved types are
1272 // pointers, disallow otherwise.
1273 Kind = CK_NoOp;
1274 return TC_Success;
1277 if (DestType->isIntegralType(Self.Context)) {
1278 assert(srcIsPtr && "One type must be a pointer");
1279 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
1280 // type large enough to hold it.
1281 if (Self.Context.getTypeSize(SrcType) >
1282 Self.Context.getTypeSize(DestType)) {
1283 msg = diag::err_bad_reinterpret_cast_small_int;
1284 return TC_Failed;
1286 Kind = CK_PointerToIntegral;
1287 return TC_Success;
1290 if (SrcType->isIntegralOrEnumerationType()) {
1291 assert(destIsPtr && "One type must be a pointer");
1292 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
1293 // converted to a pointer.
1294 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
1295 // necessarily converted to a null pointer value.]
1296 Kind = CK_IntegralToPointer;
1297 return TC_Success;
1300 if (!destIsPtr || !srcIsPtr) {
1301 // With the valid non-pointer conversions out of the way, we can be even
1302 // more stringent.
1303 return TC_NotApplicable;
1306 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
1307 // The C-style cast operator can.
1308 if (!CStyle && CastsAwayConstness(Self, SrcType, DestType)) {
1309 msg = diag::err_bad_cxx_cast_const_away;
1310 return TC_Failed;
1313 // Cannot convert between block pointers and Objective-C object pointers.
1314 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
1315 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
1316 return TC_NotApplicable;
1318 // Any pointer can be cast to an Objective-C pointer type with a C-style
1319 // cast.
1320 if (CStyle && DestType->isObjCObjectPointerType()) {
1321 Kind = CK_AnyPointerToObjCPointerCast;
1322 return TC_Success;
1325 // Not casting away constness, so the only remaining check is for compatible
1326 // pointer categories.
1327 Kind = IsLValueCast? CK_LValueBitCast : CK_BitCast;
1329 if (SrcType->isFunctionPointerType()) {
1330 if (DestType->isFunctionPointerType()) {
1331 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
1332 // a pointer to a function of a different type.
1333 return TC_Success;
1336 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
1337 // an object type or vice versa is conditionally-supported.
1338 // Compilers support it in C++03 too, though, because it's necessary for
1339 // casting the return value of dlsym() and GetProcAddress().
1340 // FIXME: Conditionally-supported behavior should be configurable in the
1341 // TargetInfo or similar.
1342 if (!Self.getLangOptions().CPlusPlus0x)
1343 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1344 return TC_Success;
1347 if (DestType->isFunctionPointerType()) {
1348 // See above.
1349 if (!Self.getLangOptions().CPlusPlus0x)
1350 Self.Diag(OpRange.getBegin(), diag::ext_cast_fn_obj) << OpRange;
1351 return TC_Success;
1354 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
1355 // a pointer to an object of different type.
1356 // Void pointers are not specified, but supported by every compiler out there.
1357 // So we finish by allowing everything that remains - it's got to be two
1358 // object pointers.
1359 return TC_Success;
1362 bool
1363 Sema::CXXCheckCStyleCast(SourceRange R, QualType CastTy, ExprValueKind &VK,
1364 Expr *&CastExpr, CastKind &Kind,
1365 CXXCastPath &BasePath,
1366 bool FunctionalStyle) {
1367 if (CastExpr->isBoundMemberFunction(Context))
1368 return Diag(CastExpr->getLocStart(),
1369 diag::err_invalid_use_of_bound_member_func)
1370 << CastExpr->getSourceRange();
1372 // This test is outside everything else because it's the only case where
1373 // a non-lvalue-reference target type does not lead to decay.
1374 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1375 if (CastTy->isVoidType()) {
1376 IgnoredValueConversions(CastExpr);
1377 Kind = CK_ToVoid;
1378 return false;
1381 // Make sure we determine the value kind before we bail out for
1382 // dependent types.
1383 VK = Expr::getValueKindForType(CastTy);
1385 // If the type is dependent, we won't do any other semantic analysis now.
1386 if (CastTy->isDependentType() || CastExpr->isTypeDependent()) {
1387 Kind = CK_Dependent;
1388 return false;
1391 if (VK == VK_RValue && !CastTy->isRecordType())
1392 DefaultFunctionArrayLvalueConversion(CastExpr);
1394 // C++ [expr.cast]p5: The conversions performed by
1395 // - a const_cast,
1396 // - a static_cast,
1397 // - a static_cast followed by a const_cast,
1398 // - a reinterpret_cast, or
1399 // - a reinterpret_cast followed by a const_cast,
1400 // can be performed using the cast notation of explicit type conversion.
1401 // [...] If a conversion can be interpreted in more than one of the ways
1402 // listed above, the interpretation that appears first in the list is used,
1403 // even if a cast resulting from that interpretation is ill-formed.
1404 // In plain language, this means trying a const_cast ...
1405 unsigned msg = diag::err_bad_cxx_cast_generic;
1406 TryCastResult tcr = TryConstCast(*this, CastExpr, CastTy, /*CStyle*/true,
1407 msg);
1408 if (tcr == TC_Success)
1409 Kind = CK_NoOp;
1411 if (tcr == TC_NotApplicable) {
1412 // ... or if that is not possible, a static_cast, ignoring const, ...
1413 tcr = TryStaticCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg, Kind,
1414 BasePath);
1415 if (tcr == TC_NotApplicable) {
1416 // ... and finally a reinterpret_cast, ignoring const.
1417 tcr = TryReinterpretCast(*this, CastExpr, CastTy, /*CStyle*/true, R, msg,
1418 Kind);
1422 if (tcr != TC_Success && msg != 0) {
1423 if (CastExpr->getType() == Context.OverloadTy) {
1424 DeclAccessPair Found;
1425 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(CastExpr,
1426 CastTy,
1427 /* Complain */ true,
1428 Found);
1429 assert(!Fn && "cast failed but able to resolve overload expression!!");
1430 (void)Fn;
1431 } else {
1432 Diag(R.getBegin(), msg) << (FunctionalStyle ? CT_Functional : CT_CStyle)
1433 << CastExpr->getType() << CastTy << R;
1436 else if (Kind == CK_BitCast)
1437 CheckCastAlign(CastExpr, CastTy, R);
1439 return tcr != TC_Success;