1 //===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements semantic analysis for cast expressions, including
10 // 1) C-style casts like '(int) x'
11 // 2) C++ functional casts like 'int(x)'
12 // 3) C++ named casts like 'static_cast<int>(x)'
14 //===----------------------------------------------------------------------===//
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTStructuralEquivalence.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/RecordLayout.h"
22 #include "clang/Basic/PartialDiagnostic.h"
23 #include "clang/Basic/TargetInfo.h"
24 #include "clang/Lex/Preprocessor.h"
25 #include "clang/Sema/Initialization.h"
26 #include "clang/Sema/SemaInternal.h"
27 #include "llvm/ADT/SmallVector.h"
29 using namespace clang
;
34 TC_NotApplicable
, ///< The cast method is not applicable.
35 TC_Success
, ///< The cast method is appropriate and successful.
36 TC_Extension
, ///< The cast method is appropriate and accepted as a
37 ///< language extension.
38 TC_Failed
///< The cast method is appropriate, but failed. A
39 ///< diagnostic has been emitted.
42 static bool isValidCast(TryCastResult TCR
) {
43 return TCR
== TC_Success
|| TCR
== TC_Extension
;
47 CT_Const
, ///< const_cast
48 CT_Static
, ///< static_cast
49 CT_Reinterpret
, ///< reinterpret_cast
50 CT_Dynamic
, ///< dynamic_cast
51 CT_CStyle
, ///< (Type)expr
52 CT_Functional
, ///< Type(expr)
53 CT_Addrspace
///< addrspace_cast
57 struct CastOperation
{
58 CastOperation(Sema
&S
, QualType destType
, ExprResult src
)
59 : Self(S
), SrcExpr(src
), DestType(destType
),
60 ResultType(destType
.getNonLValueExprType(S
.Context
)),
61 ValueKind(Expr::getValueKindForType(destType
)),
62 Kind(CK_Dependent
), IsARCUnbridgedCast(false) {
64 // C++ [expr.type]/8.2.2:
65 // If a pr-value initially has the type cv-T, where T is a
66 // cv-unqualified non-class, non-array type, the type of the
67 // expression is adjusted to T prior to any further analysis.
68 if (!S
.Context
.getLangOpts().ObjC
&& !DestType
->isRecordType() &&
69 !DestType
->isArrayType()) {
70 DestType
= DestType
.getUnqualifiedType();
73 if (const BuiltinType
*placeholder
=
74 src
.get()->getType()->getAsPlaceholderType()) {
75 PlaceholderKind
= placeholder
->getKind();
77 PlaceholderKind
= (BuiltinType::Kind
) 0;
85 ExprValueKind ValueKind
;
87 BuiltinType::Kind PlaceholderKind
;
89 bool IsARCUnbridgedCast
;
92 SourceRange DestRange
;
94 // Top-level semantics-checking routines.
95 void CheckConstCast();
96 void CheckReinterpretCast();
97 void CheckStaticCast();
98 void CheckDynamicCast();
99 void CheckCXXCStyleCast(bool FunctionalCast
, bool ListInitialization
);
100 void CheckCStyleCast();
101 void CheckBuiltinBitCast();
102 void CheckAddrspaceCast();
104 void updatePartOfExplicitCastFlags(CastExpr
*CE
) {
105 // Walk down from the CE to the OrigSrcExpr, and mark all immediate
106 // ImplicitCastExpr's as being part of ExplicitCastExpr. The original CE
107 // (which is a ExplicitCastExpr), and the OrigSrcExpr are not touched.
108 for (; auto *ICE
= dyn_cast
<ImplicitCastExpr
>(CE
->getSubExpr()); CE
= ICE
)
109 ICE
->setIsPartOfExplicitCast(true);
112 /// Complete an apparently-successful cast operation that yields
113 /// the given expression.
114 ExprResult
complete(CastExpr
*castExpr
) {
115 // If this is an unbridged cast, wrap the result in an implicit
116 // cast that yields the unbridged-cast placeholder type.
117 if (IsARCUnbridgedCast
) {
118 castExpr
= ImplicitCastExpr::Create(
119 Self
.Context
, Self
.Context
.ARCUnbridgedCastTy
, CK_Dependent
,
120 castExpr
, nullptr, castExpr
->getValueKind(),
121 Self
.CurFPFeatureOverrides());
123 updatePartOfExplicitCastFlags(castExpr
);
127 // Internal convenience methods.
129 /// Try to handle the given placeholder expression kind. Return
130 /// true if the source expression has the appropriate placeholder
131 /// kind. A placeholder can only be claimed once.
132 bool claimPlaceholder(BuiltinType::Kind K
) {
133 if (PlaceholderKind
!= K
) return false;
135 PlaceholderKind
= (BuiltinType::Kind
) 0;
139 bool isPlaceholder() const {
140 return PlaceholderKind
!= 0;
142 bool isPlaceholder(BuiltinType::Kind K
) const {
143 return PlaceholderKind
== K
;
146 // Language specific cast restrictions for address spaces.
147 void checkAddressSpaceCast(QualType SrcType
, QualType DestType
);
149 void checkCastAlign() {
150 Self
.CheckCastAlign(SrcExpr
.get(), DestType
, OpRange
);
153 void checkObjCConversion(Sema::CheckedConversionKind CCK
) {
154 assert(Self
.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers());
156 Expr
*src
= SrcExpr
.get();
157 if (Self
.CheckObjCConversion(OpRange
, DestType
, src
, CCK
) ==
159 IsARCUnbridgedCast
= true;
163 /// Check for and handle non-overload placeholder expressions.
164 void checkNonOverloadPlaceholders() {
165 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload
))
168 SrcExpr
= Self
.CheckPlaceholderExpr(SrcExpr
.get());
169 if (SrcExpr
.isInvalid())
171 PlaceholderKind
= (BuiltinType::Kind
) 0;
175 void CheckNoDeref(Sema
&S
, const QualType FromType
, const QualType ToType
,
176 SourceLocation OpLoc
) {
177 if (const auto *PtrType
= dyn_cast
<PointerType
>(FromType
)) {
178 if (PtrType
->getPointeeType()->hasAttr(attr::NoDeref
)) {
179 if (const auto *DestType
= dyn_cast
<PointerType
>(ToType
)) {
180 if (!DestType
->getPointeeType()->hasAttr(attr::NoDeref
)) {
181 S
.Diag(OpLoc
, diag::warn_noderef_to_dereferenceable_pointer
);
188 struct CheckNoDerefRAII
{
189 CheckNoDerefRAII(CastOperation
&Op
) : Op(Op
) {}
190 ~CheckNoDerefRAII() {
191 if (!Op
.SrcExpr
.isInvalid())
192 CheckNoDeref(Op
.Self
, Op
.SrcExpr
.get()->getType(), Op
.ResultType
,
193 Op
.OpRange
.getBegin());
200 static void DiagnoseCastQual(Sema
&Self
, const ExprResult
&SrcExpr
,
203 // The Try functions attempt a specific way of casting. If they succeed, they
204 // return TC_Success. If their way of casting is not appropriate for the given
205 // arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
206 // to emit if no other way succeeds. If their way of casting is appropriate but
207 // fails, they return TC_Failed and *must* set diag; they can set it to 0 if
208 // they emit a specialized diagnostic.
209 // All diagnostics returned by these functions must expect the same three
211 // %0: Cast Type (a value from the CastType enumeration)
213 // %2: Destination Type
214 static TryCastResult
TryLValueToRValueCast(Sema
&Self
, Expr
*SrcExpr
,
215 QualType DestType
, bool CStyle
,
217 CXXCastPath
&BasePath
,
219 static TryCastResult
TryStaticReferenceDowncast(Sema
&Self
, Expr
*SrcExpr
,
220 QualType DestType
, bool CStyle
,
224 CXXCastPath
&BasePath
);
225 static TryCastResult
TryStaticPointerDowncast(Sema
&Self
, QualType SrcType
,
226 QualType DestType
, bool CStyle
,
230 CXXCastPath
&BasePath
);
231 static TryCastResult
TryStaticDowncast(Sema
&Self
, CanQualType SrcType
,
232 CanQualType DestType
, bool CStyle
,
234 QualType OrigSrcType
,
235 QualType OrigDestType
, unsigned &msg
,
237 CXXCastPath
&BasePath
);
238 static TryCastResult
TryStaticMemberPointerUpcast(Sema
&Self
, ExprResult
&SrcExpr
,
240 QualType DestType
,bool CStyle
,
244 CXXCastPath
&BasePath
);
246 static TryCastResult
TryStaticImplicitCast(Sema
&Self
, ExprResult
&SrcExpr
,
248 Sema::CheckedConversionKind CCK
,
250 unsigned &msg
, CastKind
&Kind
,
251 bool ListInitialization
);
252 static TryCastResult
TryStaticCast(Sema
&Self
, ExprResult
&SrcExpr
,
254 Sema::CheckedConversionKind CCK
,
256 unsigned &msg
, CastKind
&Kind
,
257 CXXCastPath
&BasePath
,
258 bool ListInitialization
);
259 static TryCastResult
TryConstCast(Sema
&Self
, ExprResult
&SrcExpr
,
260 QualType DestType
, bool CStyle
,
262 static TryCastResult
TryReinterpretCast(Sema
&Self
, ExprResult
&SrcExpr
,
263 QualType DestType
, bool CStyle
,
264 SourceRange OpRange
, unsigned &msg
,
266 static TryCastResult
TryAddressSpaceCast(Sema
&Self
, ExprResult
&SrcExpr
,
267 QualType DestType
, bool CStyle
,
268 unsigned &msg
, CastKind
&Kind
);
270 /// ActOnCXXNamedCast - Parse
271 /// {dynamic,static,reinterpret,const,addrspace}_cast's.
273 Sema::ActOnCXXNamedCast(SourceLocation OpLoc
, tok::TokenKind Kind
,
274 SourceLocation LAngleBracketLoc
, Declarator
&D
,
275 SourceLocation RAngleBracketLoc
,
276 SourceLocation LParenLoc
, Expr
*E
,
277 SourceLocation RParenLoc
) {
279 assert(!D
.isInvalidType());
281 TypeSourceInfo
*TInfo
= GetTypeForDeclaratorCast(D
, E
->getType());
282 if (D
.isInvalidType())
285 if (getLangOpts().CPlusPlus
) {
286 // Check that there are no default arguments (C++ only).
287 CheckExtraCXXDefaultArguments(D
);
290 return BuildCXXNamedCast(OpLoc
, Kind
, TInfo
, E
,
291 SourceRange(LAngleBracketLoc
, RAngleBracketLoc
),
292 SourceRange(LParenLoc
, RParenLoc
));
296 Sema::BuildCXXNamedCast(SourceLocation OpLoc
, tok::TokenKind Kind
,
297 TypeSourceInfo
*DestTInfo
, Expr
*E
,
298 SourceRange AngleBrackets
, SourceRange Parens
) {
300 QualType DestType
= DestTInfo
->getType();
302 // If the type is dependent, we won't do the semantic analysis now.
304 DestType
->isDependentType() || Ex
.get()->isTypeDependent();
306 CastOperation
Op(*this, DestType
, E
);
307 Op
.OpRange
= SourceRange(OpLoc
, Parens
.getEnd());
308 Op
.DestRange
= AngleBrackets
;
311 default: llvm_unreachable("Unknown C++ cast!");
313 case tok::kw_addrspace_cast
:
314 if (!TypeDependent
) {
315 Op
.CheckAddrspaceCast();
316 if (Op
.SrcExpr
.isInvalid())
319 return Op
.complete(CXXAddrspaceCastExpr::Create(
320 Context
, Op
.ResultType
, Op
.ValueKind
, Op
.Kind
, Op
.SrcExpr
.get(),
321 DestTInfo
, OpLoc
, Parens
.getEnd(), AngleBrackets
));
323 case tok::kw_const_cast
:
324 if (!TypeDependent
) {
326 if (Op
.SrcExpr
.isInvalid())
328 DiscardMisalignedMemberAddress(DestType
.getTypePtr(), E
);
330 return Op
.complete(CXXConstCastExpr::Create(Context
, Op
.ResultType
,
331 Op
.ValueKind
, Op
.SrcExpr
.get(), DestTInfo
,
332 OpLoc
, Parens
.getEnd(),
335 case tok::kw_dynamic_cast
: {
336 // dynamic_cast is not supported in C++ for OpenCL.
337 if (getLangOpts().OpenCLCPlusPlus
) {
338 return ExprError(Diag(OpLoc
, diag::err_openclcxx_not_supported
)
342 if (!TypeDependent
) {
343 Op
.CheckDynamicCast();
344 if (Op
.SrcExpr
.isInvalid())
347 return Op
.complete(CXXDynamicCastExpr::Create(Context
, Op
.ResultType
,
348 Op
.ValueKind
, Op
.Kind
, Op
.SrcExpr
.get(),
349 &Op
.BasePath
, DestTInfo
,
350 OpLoc
, Parens
.getEnd(),
353 case tok::kw_reinterpret_cast
: {
354 if (!TypeDependent
) {
355 Op
.CheckReinterpretCast();
356 if (Op
.SrcExpr
.isInvalid())
358 DiscardMisalignedMemberAddress(DestType
.getTypePtr(), E
);
360 return Op
.complete(CXXReinterpretCastExpr::Create(Context
, Op
.ResultType
,
361 Op
.ValueKind
, Op
.Kind
, Op
.SrcExpr
.get(),
362 nullptr, DestTInfo
, OpLoc
,
366 case tok::kw_static_cast
: {
367 if (!TypeDependent
) {
368 Op
.CheckStaticCast();
369 if (Op
.SrcExpr
.isInvalid())
371 DiscardMisalignedMemberAddress(DestType
.getTypePtr(), E
);
374 return Op
.complete(CXXStaticCastExpr::Create(
375 Context
, Op
.ResultType
, Op
.ValueKind
, Op
.Kind
, Op
.SrcExpr
.get(),
376 &Op
.BasePath
, DestTInfo
, CurFPFeatureOverrides(), OpLoc
,
377 Parens
.getEnd(), AngleBrackets
));
382 ExprResult
Sema::ActOnBuiltinBitCastExpr(SourceLocation KWLoc
, Declarator
&D
,
384 SourceLocation RParenLoc
) {
385 assert(!D
.isInvalidType());
387 TypeSourceInfo
*TInfo
= GetTypeForDeclaratorCast(D
, Operand
.get()->getType());
388 if (D
.isInvalidType())
391 return BuildBuiltinBitCastExpr(KWLoc
, TInfo
, Operand
.get(), RParenLoc
);
394 ExprResult
Sema::BuildBuiltinBitCastExpr(SourceLocation KWLoc
,
395 TypeSourceInfo
*TSI
, Expr
*Operand
,
396 SourceLocation RParenLoc
) {
397 CastOperation
Op(*this, TSI
->getType(), Operand
);
398 Op
.OpRange
= SourceRange(KWLoc
, RParenLoc
);
399 TypeLoc TL
= TSI
->getTypeLoc();
400 Op
.DestRange
= SourceRange(TL
.getBeginLoc(), TL
.getEndLoc());
402 if (!Operand
->isTypeDependent() && !TSI
->getType()->isDependentType()) {
403 Op
.CheckBuiltinBitCast();
404 if (Op
.SrcExpr
.isInvalid())
408 BuiltinBitCastExpr
*BCE
=
409 new (Context
) BuiltinBitCastExpr(Op
.ResultType
, Op
.ValueKind
, Op
.Kind
,
410 Op
.SrcExpr
.get(), TSI
, KWLoc
, RParenLoc
);
411 return Op
.complete(BCE
);
414 /// Try to diagnose a failed overloaded cast. Returns true if
415 /// diagnostics were emitted.
416 static bool tryDiagnoseOverloadedCast(Sema
&S
, CastType CT
,
417 SourceRange range
, Expr
*src
,
419 bool listInitialization
) {
421 // These cast kinds don't consider user-defined conversions.
435 QualType srcType
= src
->getType();
436 if (!destType
->isRecordType() && !srcType
->isRecordType())
439 InitializedEntity entity
= InitializedEntity::InitializeTemporary(destType
);
440 InitializationKind initKind
441 = (CT
== CT_CStyle
)? InitializationKind::CreateCStyleCast(range
.getBegin(),
442 range
, listInitialization
)
443 : (CT
== CT_Functional
)? InitializationKind::CreateFunctionalCast(range
,
445 : InitializationKind::CreateCast(/*type range?*/ range
);
446 InitializationSequence
sequence(S
, entity
, initKind
, src
);
448 assert(sequence
.Failed() && "initialization succeeded on second try?");
449 switch (sequence
.getFailureKind()) {
450 default: return false;
452 case InitializationSequence::FK_ConstructorOverloadFailed
:
453 case InitializationSequence::FK_UserConversionOverloadFailed
:
454 case InitializationSequence::FK_ParenthesizedListInitFailed
:
458 OverloadCandidateSet
&candidates
= sequence
.getFailedCandidateSet();
461 OverloadCandidateDisplayKind howManyCandidates
= OCD_AllCandidates
;
463 switch (sequence
.getFailedOverloadResult()) {
464 case OR_Success
: llvm_unreachable("successful failed overload");
465 case OR_No_Viable_Function
:
466 if (candidates
.empty())
467 msg
= diag::err_ovl_no_conversion_in_cast
;
469 msg
= diag::err_ovl_no_viable_conversion_in_cast
;
470 howManyCandidates
= OCD_AllCandidates
;
474 msg
= diag::err_ovl_ambiguous_conversion_in_cast
;
475 howManyCandidates
= OCD_AmbiguousCandidates
;
479 msg
= diag::err_ovl_deleted_conversion_in_cast
;
480 howManyCandidates
= OCD_ViableCandidates
;
484 candidates
.NoteCandidates(
485 PartialDiagnosticAt(range
.getBegin(),
486 S
.PDiag(msg
) << CT
<< srcType
<< destType
<< range
487 << src
->getSourceRange()),
488 S
, howManyCandidates
, src
);
493 /// Diagnose a failed cast.
494 static void diagnoseBadCast(Sema
&S
, unsigned msg
, CastType castType
,
495 SourceRange opRange
, Expr
*src
, QualType destType
,
496 bool listInitialization
) {
497 if (msg
== diag::err_bad_cxx_cast_generic
&&
498 tryDiagnoseOverloadedCast(S
, castType
, opRange
, src
, destType
,
502 S
.Diag(opRange
.getBegin(), msg
) << castType
503 << src
->getType() << destType
<< opRange
<< src
->getSourceRange();
505 // Detect if both types are (ptr to) class, and note any incompleteness.
506 int DifferentPtrness
= 0;
507 QualType From
= destType
;
508 if (auto Ptr
= From
->getAs
<PointerType
>()) {
509 From
= Ptr
->getPointeeType();
512 QualType To
= src
->getType();
513 if (auto Ptr
= To
->getAs
<PointerType
>()) {
514 To
= Ptr
->getPointeeType();
517 if (!DifferentPtrness
) {
518 auto RecFrom
= From
->getAs
<RecordType
>();
519 auto RecTo
= To
->getAs
<RecordType
>();
520 if (RecFrom
&& RecTo
) {
521 auto DeclFrom
= RecFrom
->getAsCXXRecordDecl();
522 if (!DeclFrom
->isCompleteDefinition())
523 S
.Diag(DeclFrom
->getLocation(), diag::note_type_incomplete
) << DeclFrom
;
524 auto DeclTo
= RecTo
->getAsCXXRecordDecl();
525 if (!DeclTo
->isCompleteDefinition())
526 S
.Diag(DeclTo
->getLocation(), diag::note_type_incomplete
) << DeclTo
;
532 /// The kind of unwrapping we did when determining whether a conversion casts
534 enum CastAwayConstnessKind
{
535 /// The conversion does not cast away constness.
537 /// We unwrapped similar types.
539 /// We unwrapped dissimilar types with similar representations (eg, a pointer
540 /// versus an Objective-C object pointer).
541 CACK_SimilarKind
= 2,
542 /// We unwrapped representationally-unrelated types, such as a pointer versus
543 /// a pointer-to-member.
548 /// Unwrap one level of types for CastsAwayConstness.
550 /// Like Sema::UnwrapSimilarTypes, this removes one level of indirection from
551 /// both types, provided that they're both pointer-like or array-like. Unlike
552 /// the Sema function, doesn't care if the unwrapped pieces are related.
554 /// This function may remove additional levels as necessary for correctness:
555 /// the resulting T1 is unwrapped sufficiently that it is never an array type,
556 /// so that its qualifiers can be directly compared to those of T2 (which will
557 /// have the combined set of qualifiers from all indermediate levels of T2),
558 /// as (effectively) required by [expr.const.cast]p7 replacing T1's qualifiers
559 /// with those from T2.
560 static CastAwayConstnessKind
561 unwrapCastAwayConstnessLevel(ASTContext
&Context
, QualType
&T1
, QualType
&T2
) {
562 enum { None
, Ptr
, MemPtr
, BlockPtr
, Array
};
563 auto Classify
= [](QualType T
) {
564 if (T
->isAnyPointerType()) return Ptr
;
565 if (T
->isMemberPointerType()) return MemPtr
;
566 if (T
->isBlockPointerType()) return BlockPtr
;
567 // We somewhat-arbitrarily don't look through VLA types here. This is at
568 // least consistent with the behavior of UnwrapSimilarTypes.
569 if (T
->isConstantArrayType() || T
->isIncompleteArrayType()) return Array
;
573 auto Unwrap
= [&](QualType T
) {
574 if (auto *AT
= Context
.getAsArrayType(T
))
575 return AT
->getElementType();
576 return T
->getPointeeType();
579 CastAwayConstnessKind Kind
;
581 if (T2
->isReferenceType()) {
582 // Special case: if the destination type is a reference type, unwrap it as
583 // the first level. (The source will have been an lvalue expression in this
584 // case, so there is no corresponding "reference to" in T1 to remove.) This
585 // simulates removing a "pointer to" from both sides.
586 T2
= T2
->getPointeeType();
587 Kind
= CastAwayConstnessKind::CACK_Similar
;
588 } else if (Context
.UnwrapSimilarTypes(T1
, T2
)) {
589 Kind
= CastAwayConstnessKind::CACK_Similar
;
591 // Try unwrapping mismatching levels.
592 int T1Class
= Classify(T1
);
594 return CastAwayConstnessKind::CACK_None
;
596 int T2Class
= Classify(T2
);
598 return CastAwayConstnessKind::CACK_None
;
602 Kind
= T1Class
== T2Class
? CastAwayConstnessKind::CACK_SimilarKind
603 : CastAwayConstnessKind::CACK_Incoherent
;
606 // We've unwrapped at least one level. If the resulting T1 is a (possibly
607 // multidimensional) array type, any qualifier on any matching layer of
608 // T2 is considered to correspond to T1. Decompose down to the element
609 // type of T1 so that we can compare properly.
611 Context
.UnwrapSimilarArrayTypes(T1
, T2
);
613 if (Classify(T1
) != Array
)
616 auto T2Class
= Classify(T2
);
620 if (T2Class
!= Array
)
621 Kind
= CastAwayConstnessKind::CACK_Incoherent
;
622 else if (Kind
!= CastAwayConstnessKind::CACK_Incoherent
)
623 Kind
= CastAwayConstnessKind::CACK_SimilarKind
;
626 T2
= Unwrap(T2
).withCVRQualifiers(T2
.getCVRQualifiers());
632 /// Check if the pointer conversion from SrcType to DestType casts away
633 /// constness as defined in C++ [expr.const.cast]. This is used by the cast
634 /// checkers. Both arguments must denote pointer (possibly to member) types.
636 /// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
637 /// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
638 static CastAwayConstnessKind
639 CastsAwayConstness(Sema
&Self
, QualType SrcType
, QualType DestType
,
640 bool CheckCVR
, bool CheckObjCLifetime
,
641 QualType
*TheOffendingSrcType
= nullptr,
642 QualType
*TheOffendingDestType
= nullptr,
643 Qualifiers
*CastAwayQualifiers
= nullptr) {
644 // If the only checking we care about is for Objective-C lifetime qualifiers,
645 // and we're not in ObjC mode, there's nothing to check.
646 if (!CheckCVR
&& CheckObjCLifetime
&& !Self
.Context
.getLangOpts().ObjC
)
647 return CastAwayConstnessKind::CACK_None
;
649 if (!DestType
->isReferenceType()) {
650 assert((SrcType
->isAnyPointerType() || SrcType
->isMemberPointerType() ||
651 SrcType
->isBlockPointerType()) &&
652 "Source type is not pointer or pointer to member.");
653 assert((DestType
->isAnyPointerType() || DestType
->isMemberPointerType() ||
654 DestType
->isBlockPointerType()) &&
655 "Destination type is not pointer or pointer to member.");
658 QualType UnwrappedSrcType
= Self
.Context
.getCanonicalType(SrcType
),
659 UnwrappedDestType
= Self
.Context
.getCanonicalType(DestType
);
661 // Find the qualifiers. We only care about cvr-qualifiers for the
662 // purpose of this check, because other qualifiers (address spaces,
663 // Objective-C GC, etc.) are part of the type's identity.
664 QualType PrevUnwrappedSrcType
= UnwrappedSrcType
;
665 QualType PrevUnwrappedDestType
= UnwrappedDestType
;
666 auto WorstKind
= CastAwayConstnessKind::CACK_Similar
;
667 bool AllConstSoFar
= true;
668 while (auto Kind
= unwrapCastAwayConstnessLevel(
669 Self
.Context
, UnwrappedSrcType
, UnwrappedDestType
)) {
670 // Track the worst kind of unwrap we needed to do before we found a
672 if (Kind
> WorstKind
)
675 // Determine the relevant qualifiers at this level.
676 Qualifiers SrcQuals
, DestQuals
;
677 Self
.Context
.getUnqualifiedArrayType(UnwrappedSrcType
, SrcQuals
);
678 Self
.Context
.getUnqualifiedArrayType(UnwrappedDestType
, DestQuals
);
680 // We do not meaningfully track object const-ness of Objective-C object
681 // types. Remove const from the source type if either the source or
682 // the destination is an Objective-C object type.
683 if (UnwrappedSrcType
->isObjCObjectType() ||
684 UnwrappedDestType
->isObjCObjectType())
685 SrcQuals
.removeConst();
688 Qualifiers SrcCvrQuals
=
689 Qualifiers::fromCVRMask(SrcQuals
.getCVRQualifiers());
690 Qualifiers DestCvrQuals
=
691 Qualifiers::fromCVRMask(DestQuals
.getCVRQualifiers());
693 if (SrcCvrQuals
!= DestCvrQuals
) {
694 if (CastAwayQualifiers
)
695 *CastAwayQualifiers
= SrcCvrQuals
- DestCvrQuals
;
697 // If we removed a cvr-qualifier, this is casting away 'constness'.
698 if (!DestCvrQuals
.compatiblyIncludes(SrcCvrQuals
)) {
699 if (TheOffendingSrcType
)
700 *TheOffendingSrcType
= PrevUnwrappedSrcType
;
701 if (TheOffendingDestType
)
702 *TheOffendingDestType
= PrevUnwrappedDestType
;
706 // If any prior level was not 'const', this is also casting away
707 // 'constness'. We noted the outermost type missing a 'const' already.
713 if (CheckObjCLifetime
&&
714 !DestQuals
.compatiblyIncludesObjCLifetime(SrcQuals
))
717 // If we found our first non-const-qualified type, this may be the place
718 // where things start to go wrong.
719 if (AllConstSoFar
&& !DestQuals
.hasConst()) {
720 AllConstSoFar
= false;
721 if (TheOffendingSrcType
)
722 *TheOffendingSrcType
= PrevUnwrappedSrcType
;
723 if (TheOffendingDestType
)
724 *TheOffendingDestType
= PrevUnwrappedDestType
;
727 PrevUnwrappedSrcType
= UnwrappedSrcType
;
728 PrevUnwrappedDestType
= UnwrappedDestType
;
731 return CastAwayConstnessKind::CACK_None
;
734 static TryCastResult
getCastAwayConstnessCastKind(CastAwayConstnessKind CACK
,
737 case CastAwayConstnessKind::CACK_None
:
738 llvm_unreachable("did not cast away constness");
740 case CastAwayConstnessKind::CACK_Similar
:
741 // FIXME: Accept these as an extension too?
742 case CastAwayConstnessKind::CACK_SimilarKind
:
743 DiagID
= diag::err_bad_cxx_cast_qualifiers_away
;
746 case CastAwayConstnessKind::CACK_Incoherent
:
747 DiagID
= diag::ext_bad_cxx_cast_qualifiers_away_incoherent
;
751 llvm_unreachable("unexpected cast away constness kind");
754 /// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
755 /// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
756 /// checked downcasts in class hierarchies.
757 void CastOperation::CheckDynamicCast() {
758 CheckNoDerefRAII
NoderefCheck(*this);
760 if (ValueKind
== VK_PRValue
)
761 SrcExpr
= Self
.DefaultFunctionArrayLvalueConversion(SrcExpr
.get());
762 else if (isPlaceholder())
763 SrcExpr
= Self
.CheckPlaceholderExpr(SrcExpr
.get());
764 if (SrcExpr
.isInvalid()) // if conversion failed, don't report another error
767 QualType OrigSrcType
= SrcExpr
.get()->getType();
768 QualType DestType
= Self
.Context
.getCanonicalType(this->DestType
);
770 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
771 // or "pointer to cv void".
773 QualType DestPointee
;
774 const PointerType
*DestPointer
= DestType
->getAs
<PointerType
>();
775 const ReferenceType
*DestReference
= nullptr;
777 DestPointee
= DestPointer
->getPointeeType();
778 } else if ((DestReference
= DestType
->getAs
<ReferenceType
>())) {
779 DestPointee
= DestReference
->getPointeeType();
781 Self
.Diag(OpRange
.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr
)
782 << this->DestType
<< DestRange
;
783 SrcExpr
= ExprError();
787 const RecordType
*DestRecord
= DestPointee
->getAs
<RecordType
>();
788 if (DestPointee
->isVoidType()) {
789 assert(DestPointer
&& "Reference to void is not possible");
790 } else if (DestRecord
) {
791 if (Self
.RequireCompleteType(OpRange
.getBegin(), DestPointee
,
792 diag::err_bad_cast_incomplete
,
794 SrcExpr
= ExprError();
798 Self
.Diag(OpRange
.getBegin(), diag::err_bad_dynamic_cast_not_class
)
799 << DestPointee
.getUnqualifiedType() << DestRange
;
800 SrcExpr
= ExprError();
804 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
805 // complete class type, [...]. If T is an lvalue reference type, v shall be
806 // an lvalue of a complete class type, [...]. If T is an rvalue reference
807 // type, v shall be an expression having a complete class type, [...]
808 QualType SrcType
= Self
.Context
.getCanonicalType(OrigSrcType
);
811 if (const PointerType
*SrcPointer
= SrcType
->getAs
<PointerType
>()) {
812 SrcPointee
= SrcPointer
->getPointeeType();
814 Self
.Diag(OpRange
.getBegin(), diag::err_bad_dynamic_cast_not_ptr
)
815 << OrigSrcType
<< this->DestType
<< SrcExpr
.get()->getSourceRange();
816 SrcExpr
= ExprError();
819 } else if (DestReference
->isLValueReferenceType()) {
820 if (!SrcExpr
.get()->isLValue()) {
821 Self
.Diag(OpRange
.getBegin(), diag::err_bad_cxx_cast_rvalue
)
822 << CT_Dynamic
<< OrigSrcType
<< this->DestType
<< OpRange
;
824 SrcPointee
= SrcType
;
826 // If we're dynamic_casting from a prvalue to an rvalue reference, we need
827 // to materialize the prvalue before we bind the reference to it.
828 if (SrcExpr
.get()->isPRValue())
829 SrcExpr
= Self
.CreateMaterializeTemporaryExpr(
830 SrcType
, SrcExpr
.get(), /*IsLValueReference*/ false);
831 SrcPointee
= SrcType
;
834 const RecordType
*SrcRecord
= SrcPointee
->getAs
<RecordType
>();
836 if (Self
.RequireCompleteType(OpRange
.getBegin(), SrcPointee
,
837 diag::err_bad_cast_incomplete
,
839 SrcExpr
= ExprError();
843 Self
.Diag(OpRange
.getBegin(), diag::err_bad_dynamic_cast_not_class
)
844 << SrcPointee
.getUnqualifiedType() << SrcExpr
.get()->getSourceRange();
845 SrcExpr
= ExprError();
849 assert((DestPointer
|| DestReference
) &&
850 "Bad destination non-ptr/ref slipped through.");
851 assert((DestRecord
|| DestPointee
->isVoidType()) &&
852 "Bad destination pointee slipped through.");
853 assert(SrcRecord
&& "Bad source pointee slipped through.");
855 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
856 if (!DestPointee
.isAtLeastAsQualifiedAs(SrcPointee
)) {
857 Self
.Diag(OpRange
.getBegin(), diag::err_bad_cxx_cast_qualifiers_away
)
858 << CT_Dynamic
<< OrigSrcType
<< this->DestType
<< OpRange
;
859 SrcExpr
= ExprError();
863 // C++ 5.2.7p3: If the type of v is the same as the required result type,
865 if (DestRecord
== SrcRecord
) {
871 // Upcasts are resolved statically.
873 Self
.IsDerivedFrom(OpRange
.getBegin(), SrcPointee
, DestPointee
)) {
874 if (Self
.CheckDerivedToBaseConversion(SrcPointee
, DestPointee
,
875 OpRange
.getBegin(), OpRange
,
877 SrcExpr
= ExprError();
881 Kind
= CK_DerivedToBase
;
885 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
886 const RecordDecl
*SrcDecl
= SrcRecord
->getDecl()->getDefinition();
887 assert(SrcDecl
&& "Definition missing");
888 if (!cast
<CXXRecordDecl
>(SrcDecl
)->isPolymorphic()) {
889 Self
.Diag(OpRange
.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic
)
890 << SrcPointee
.getUnqualifiedType() << SrcExpr
.get()->getSourceRange();
891 SrcExpr
= ExprError();
894 // dynamic_cast is not available with -fno-rtti.
895 // As an exception, dynamic_cast to void* is available because it doesn't
897 if (!Self
.getLangOpts().RTTI
&& !DestPointee
->isVoidType()) {
898 Self
.Diag(OpRange
.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti
);
899 SrcExpr
= ExprError();
903 // Warns when dynamic_cast is used with RTTI data disabled.
904 if (!Self
.getLangOpts().RTTIData
) {
906 Self
.getASTContext().getTargetInfo().getCXXABI().isMicrosoft();
907 bool isClangCL
= Self
.getDiagnostics().getDiagnosticOptions().getFormat() ==
908 DiagnosticOptions::MSVC
;
909 if (MicrosoftABI
|| !DestPointee
->isVoidType())
910 Self
.Diag(OpRange
.getBegin(),
911 diag::warn_no_dynamic_cast_with_rtti_disabled
)
915 // Done. Everything else is run-time checks.
919 /// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
920 /// Refer to C++ 5.2.11 for details. const_cast is typically used in code
922 /// const char *str = "literal";
923 /// legacy_function(const_cast\<char*\>(str));
924 void CastOperation::CheckConstCast() {
925 CheckNoDerefRAII
NoderefCheck(*this);
927 if (ValueKind
== VK_PRValue
)
928 SrcExpr
= Self
.DefaultFunctionArrayLvalueConversion(SrcExpr
.get());
929 else if (isPlaceholder())
930 SrcExpr
= Self
.CheckPlaceholderExpr(SrcExpr
.get());
931 if (SrcExpr
.isInvalid()) // if conversion failed, don't report another error
934 unsigned msg
= diag::err_bad_cxx_cast_generic
;
935 auto TCR
= TryConstCast(Self
, SrcExpr
, DestType
, /*CStyle*/ false, msg
);
936 if (TCR
!= TC_Success
&& msg
!= 0) {
937 Self
.Diag(OpRange
.getBegin(), msg
) << CT_Const
938 << SrcExpr
.get()->getType() << DestType
<< OpRange
;
940 if (!isValidCast(TCR
))
941 SrcExpr
= ExprError();
944 void CastOperation::CheckAddrspaceCast() {
945 unsigned msg
= diag::err_bad_cxx_cast_generic
;
947 TryAddressSpaceCast(Self
, SrcExpr
, DestType
, /*CStyle*/ false, msg
, Kind
);
948 if (TCR
!= TC_Success
&& msg
!= 0) {
949 Self
.Diag(OpRange
.getBegin(), msg
)
950 << CT_Addrspace
<< SrcExpr
.get()->getType() << DestType
<< OpRange
;
952 if (!isValidCast(TCR
))
953 SrcExpr
= ExprError();
956 /// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
957 /// or downcast between respective pointers or references.
958 static void DiagnoseReinterpretUpDownCast(Sema
&Self
, const Expr
*SrcExpr
,
960 SourceRange OpRange
) {
961 QualType SrcType
= SrcExpr
->getType();
962 // When casting from pointer or reference, get pointee type; use original
964 const CXXRecordDecl
*SrcPointeeRD
= SrcType
->getPointeeCXXRecordDecl();
965 const CXXRecordDecl
*SrcRD
=
966 SrcPointeeRD
? SrcPointeeRD
: SrcType
->getAsCXXRecordDecl();
968 // Examining subobjects for records is only possible if the complete and
969 // valid definition is available. Also, template instantiation is not
971 if (!SrcRD
|| !SrcRD
->isCompleteDefinition() || SrcRD
->isInvalidDecl())
974 const CXXRecordDecl
*DestRD
= DestType
->getPointeeCXXRecordDecl();
976 if (!DestRD
|| !DestRD
->isCompleteDefinition() || DestRD
->isInvalidDecl())
984 CXXBasePaths BasePaths
;
986 if (SrcRD
->isDerivedFrom(DestRD
, BasePaths
))
987 ReinterpretKind
= ReinterpretUpcast
;
988 else if (DestRD
->isDerivedFrom(SrcRD
, BasePaths
))
989 ReinterpretKind
= ReinterpretDowncast
;
993 bool VirtualBase
= true;
994 bool NonZeroOffset
= false;
995 for (CXXBasePaths::const_paths_iterator I
= BasePaths
.begin(),
998 const CXXBasePath
&Path
= *I
;
999 CharUnits Offset
= CharUnits::Zero();
1000 bool IsVirtual
= false;
1001 for (CXXBasePath::const_iterator IElem
= Path
.begin(), EElem
= Path
.end();
1002 IElem
!= EElem
; ++IElem
) {
1003 IsVirtual
= IElem
->Base
->isVirtual();
1006 const CXXRecordDecl
*BaseRD
= IElem
->Base
->getType()->getAsCXXRecordDecl();
1007 assert(BaseRD
&& "Base type should be a valid unqualified class type");
1008 // Don't check if any base has invalid declaration or has no definition
1009 // since it has no layout info.
1010 const CXXRecordDecl
*Class
= IElem
->Class
,
1011 *ClassDefinition
= Class
->getDefinition();
1012 if (Class
->isInvalidDecl() || !ClassDefinition
||
1013 !ClassDefinition
->isCompleteDefinition())
1016 const ASTRecordLayout
&DerivedLayout
=
1017 Self
.Context
.getASTRecordLayout(Class
);
1018 Offset
+= DerivedLayout
.getBaseClassOffset(BaseRD
);
1021 // Don't warn if any path is a non-virtually derived base at offset zero.
1022 if (Offset
.isZero())
1024 // Offset makes sense only for non-virtual bases.
1026 NonZeroOffset
= true;
1028 VirtualBase
= VirtualBase
&& IsVirtual
;
1031 (void) NonZeroOffset
; // Silence set but not used warning.
1032 assert((VirtualBase
|| NonZeroOffset
) &&
1033 "Should have returned if has non-virtual base with zero offset");
1036 ReinterpretKind
== ReinterpretUpcast
? DestType
: SrcType
;
1037 QualType DerivedType
=
1038 ReinterpretKind
== ReinterpretUpcast
? SrcType
: DestType
;
1040 SourceLocation BeginLoc
= OpRange
.getBegin();
1041 Self
.Diag(BeginLoc
, diag::warn_reinterpret_different_from_static
)
1042 << DerivedType
<< BaseType
<< !VirtualBase
<< int(ReinterpretKind
)
1044 Self
.Diag(BeginLoc
, diag::note_reinterpret_updowncast_use_static
)
1045 << int(ReinterpretKind
)
1046 << FixItHint::CreateReplacement(BeginLoc
, "static_cast");
1049 static bool argTypeIsABIEquivalent(QualType SrcType
, QualType DestType
,
1050 ASTContext
&Context
) {
1051 if (SrcType
->isPointerType() && DestType
->isPointerType())
1054 // Allow integral type mismatch if their size are equal.
1055 if (SrcType
->isIntegralType(Context
) && DestType
->isIntegralType(Context
))
1056 if (Context
.getTypeInfoInChars(SrcType
).Width
==
1057 Context
.getTypeInfoInChars(DestType
).Width
)
1060 return Context
.hasSameUnqualifiedType(SrcType
, DestType
);
1063 static unsigned int checkCastFunctionType(Sema
&Self
, const ExprResult
&SrcExpr
,
1064 QualType DestType
) {
1065 unsigned int DiagID
= 0;
1066 const unsigned int DiagList
[] = {diag::warn_cast_function_type_strict
,
1067 diag::warn_cast_function_type
};
1068 for (auto ID
: DiagList
) {
1069 if (!Self
.Diags
.isIgnored(ID
, SrcExpr
.get()->getExprLoc())) {
1077 QualType SrcType
= SrcExpr
.get()->getType();
1078 const FunctionType
*SrcFTy
= nullptr;
1079 const FunctionType
*DstFTy
= nullptr;
1080 if (((SrcType
->isBlockPointerType() || SrcType
->isFunctionPointerType()) &&
1081 DestType
->isFunctionPointerType()) ||
1082 (SrcType
->isMemberFunctionPointerType() &&
1083 DestType
->isMemberFunctionPointerType())) {
1084 SrcFTy
= SrcType
->getPointeeType()->castAs
<FunctionType
>();
1085 DstFTy
= DestType
->getPointeeType()->castAs
<FunctionType
>();
1086 } else if (SrcType
->isFunctionType() && DestType
->isFunctionReferenceType()) {
1087 SrcFTy
= SrcType
->castAs
<FunctionType
>();
1088 DstFTy
= DestType
.getNonReferenceType()->castAs
<FunctionType
>();
1092 assert(SrcFTy
&& DstFTy
);
1094 if (Self
.Context
.hasSameType(SrcFTy
, DstFTy
))
1097 // For strict checks, ensure we have an exact match.
1098 if (DiagID
== diag::warn_cast_function_type_strict
)
1101 auto IsVoidVoid
= [](const FunctionType
*T
) {
1102 if (!T
->getReturnType()->isVoidType())
1104 if (const auto *PT
= T
->getAs
<FunctionProtoType
>())
1105 return !PT
->isVariadic() && PT
->getNumParams() == 0;
1109 // Skip if either function type is void(*)(void)
1110 if (IsVoidVoid(SrcFTy
) || IsVoidVoid(DstFTy
))
1113 // Check return type.
1114 if (!argTypeIsABIEquivalent(SrcFTy
->getReturnType(), DstFTy
->getReturnType(),
1118 // Check if either has unspecified number of parameters
1119 if (SrcFTy
->isFunctionNoProtoType() || DstFTy
->isFunctionNoProtoType())
1122 // Check parameter types.
1124 const auto *SrcFPTy
= cast
<FunctionProtoType
>(SrcFTy
);
1125 const auto *DstFPTy
= cast
<FunctionProtoType
>(DstFTy
);
1127 // In a cast involving function types with a variable argument list only the
1128 // types of initial arguments that are provided are considered.
1129 unsigned NumParams
= SrcFPTy
->getNumParams();
1130 unsigned DstNumParams
= DstFPTy
->getNumParams();
1131 if (NumParams
> DstNumParams
) {
1132 if (!DstFPTy
->isVariadic())
1134 NumParams
= DstNumParams
;
1135 } else if (NumParams
< DstNumParams
) {
1136 if (!SrcFPTy
->isVariadic())
1140 for (unsigned i
= 0; i
< NumParams
; ++i
)
1141 if (!argTypeIsABIEquivalent(SrcFPTy
->getParamType(i
),
1142 DstFPTy
->getParamType(i
), Self
.Context
))
1148 /// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
1150 /// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
1152 /// char *bytes = reinterpret_cast\<char*\>(int_ptr);
1153 void CastOperation::CheckReinterpretCast() {
1154 if (ValueKind
== VK_PRValue
&& !isPlaceholder(BuiltinType::Overload
))
1155 SrcExpr
= Self
.DefaultFunctionArrayLvalueConversion(SrcExpr
.get());
1157 checkNonOverloadPlaceholders();
1158 if (SrcExpr
.isInvalid()) // if conversion failed, don't report another error
1161 unsigned msg
= diag::err_bad_cxx_cast_generic
;
1163 TryReinterpretCast(Self
, SrcExpr
, DestType
,
1164 /*CStyle*/false, OpRange
, msg
, Kind
);
1165 if (tcr
!= TC_Success
&& msg
!= 0) {
1166 if (SrcExpr
.isInvalid()) // if conversion failed, don't report another error
1168 if (SrcExpr
.get()->getType() == Self
.Context
.OverloadTy
) {
1169 //FIXME: &f<int>; is overloaded and resolvable
1170 Self
.Diag(OpRange
.getBegin(), diag::err_bad_reinterpret_cast_overload
)
1171 << OverloadExpr::find(SrcExpr
.get()).Expression
->getName()
1172 << DestType
<< OpRange
;
1173 Self
.NoteAllOverloadCandidates(SrcExpr
.get());
1176 diagnoseBadCast(Self
, msg
, CT_Reinterpret
, OpRange
, SrcExpr
.get(),
1177 DestType
, /*listInitialization=*/false);
1181 if (isValidCast(tcr
)) {
1182 if (Self
.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
1183 checkObjCConversion(Sema::CCK_OtherCast
);
1184 DiagnoseReinterpretUpDownCast(Self
, SrcExpr
.get(), DestType
, OpRange
);
1186 if (unsigned DiagID
= checkCastFunctionType(Self
, SrcExpr
, DestType
))
1187 Self
.Diag(OpRange
.getBegin(), DiagID
)
1188 << SrcExpr
.get()->getType() << DestType
<< OpRange
;
1190 SrcExpr
= ExprError();
1195 /// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
1196 /// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
1197 /// implicit conversions explicit and getting rid of data loss warnings.
1198 void CastOperation::CheckStaticCast() {
1199 CheckNoDerefRAII
NoderefCheck(*this);
1201 if (isPlaceholder()) {
1202 checkNonOverloadPlaceholders();
1203 if (SrcExpr
.isInvalid())
1207 // This test is outside everything else because it's the only case where
1208 // a non-lvalue-reference target type does not lead to decay.
1209 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1210 if (DestType
->isVoidType()) {
1213 if (claimPlaceholder(BuiltinType::Overload
)) {
1214 Self
.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr
,
1215 false, // Decay Function to ptr
1217 OpRange
, DestType
, diag::err_bad_static_cast_overload
);
1218 if (SrcExpr
.isInvalid())
1222 SrcExpr
= Self
.IgnoredValueConversions(SrcExpr
.get());
1226 if (ValueKind
== VK_PRValue
&& !DestType
->isRecordType() &&
1227 !isPlaceholder(BuiltinType::Overload
)) {
1228 SrcExpr
= Self
.DefaultFunctionArrayLvalueConversion(SrcExpr
.get());
1229 if (SrcExpr
.isInvalid()) // if conversion failed, don't report another error
1233 unsigned msg
= diag::err_bad_cxx_cast_generic
;
1235 = TryStaticCast(Self
, SrcExpr
, DestType
, Sema::CCK_OtherCast
, OpRange
, msg
,
1236 Kind
, BasePath
, /*ListInitialization=*/false);
1237 if (tcr
!= TC_Success
&& msg
!= 0) {
1238 if (SrcExpr
.isInvalid())
1240 if (SrcExpr
.get()->getType() == Self
.Context
.OverloadTy
) {
1241 OverloadExpr
* oe
= OverloadExpr::find(SrcExpr
.get()).Expression
;
1242 Self
.Diag(OpRange
.getBegin(), diag::err_bad_static_cast_overload
)
1243 << oe
->getName() << DestType
<< OpRange
1244 << oe
->getQualifierLoc().getSourceRange();
1245 Self
.NoteAllOverloadCandidates(SrcExpr
.get());
1247 diagnoseBadCast(Self
, msg
, CT_Static
, OpRange
, SrcExpr
.get(), DestType
,
1248 /*listInitialization=*/false);
1252 if (isValidCast(tcr
)) {
1253 if (Kind
== CK_BitCast
)
1255 if (Self
.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
1256 checkObjCConversion(Sema::CCK_OtherCast
);
1258 SrcExpr
= ExprError();
1262 static bool IsAddressSpaceConversion(QualType SrcType
, QualType DestType
) {
1263 auto *SrcPtrType
= SrcType
->getAs
<PointerType
>();
1266 auto *DestPtrType
= DestType
->getAs
<PointerType
>();
1269 return SrcPtrType
->getPointeeType().getAddressSpace() !=
1270 DestPtrType
->getPointeeType().getAddressSpace();
1273 /// TryStaticCast - Check if a static cast can be performed, and do so if
1274 /// possible. If @p CStyle, ignore access restrictions on hierarchy casting
1275 /// and casting away constness.
1276 static TryCastResult
TryStaticCast(Sema
&Self
, ExprResult
&SrcExpr
,
1278 Sema::CheckedConversionKind CCK
,
1279 SourceRange OpRange
, unsigned &msg
,
1280 CastKind
&Kind
, CXXCastPath
&BasePath
,
1281 bool ListInitialization
) {
1282 // Determine whether we have the semantics of a C-style cast.
1284 = (CCK
== Sema::CCK_CStyleCast
|| CCK
== Sema::CCK_FunctionalCast
);
1286 // The order the tests is not entirely arbitrary. There is one conversion
1287 // that can be handled in two different ways. Given:
1289 // struct B : public A {
1290 // B(); B(const A&);
1292 // const A &a = B();
1293 // the cast static_cast<const B&>(a) could be seen as either a static
1294 // reference downcast, or an explicit invocation of the user-defined
1295 // conversion using B's conversion constructor.
1296 // DR 427 specifies that the downcast is to be applied here.
1298 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1299 // Done outside this function.
1303 // C++ 5.2.9p5, reference downcast.
1304 // See the function for details.
1305 // DR 427 specifies that this is to be applied before paragraph 2.
1306 tcr
= TryStaticReferenceDowncast(Self
, SrcExpr
.get(), DestType
, CStyle
,
1307 OpRange
, msg
, Kind
, BasePath
);
1308 if (tcr
!= TC_NotApplicable
)
1311 // C++11 [expr.static.cast]p3:
1312 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
1313 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
1314 tcr
= TryLValueToRValueCast(Self
, SrcExpr
.get(), DestType
, CStyle
, Kind
,
1316 if (tcr
!= TC_NotApplicable
)
1319 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
1320 // [...] if the declaration "T t(e);" is well-formed, [...].
1321 tcr
= TryStaticImplicitCast(Self
, SrcExpr
, DestType
, CCK
, OpRange
, msg
,
1322 Kind
, ListInitialization
);
1323 if (SrcExpr
.isInvalid())
1325 if (tcr
!= TC_NotApplicable
)
1328 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
1329 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
1330 // conversions, subject to further restrictions.
1331 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
1332 // of qualification conversions impossible. (In C++20, adding an array bound
1333 // would be the reverse of a qualification conversion, but adding permission
1334 // to add an array bound in a static_cast is a wording oversight.)
1335 // In the CStyle case, the earlier attempt to const_cast should have taken
1336 // care of reverse qualification conversions.
1338 QualType SrcType
= Self
.Context
.getCanonicalType(SrcExpr
.get()->getType());
1340 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
1341 // converted to an integral type. [...] A value of a scoped enumeration type
1342 // can also be explicitly converted to a floating-point type [...].
1343 if (const EnumType
*Enum
= SrcType
->getAs
<EnumType
>()) {
1344 if (Enum
->getDecl()->isScoped()) {
1345 if (DestType
->isBooleanType()) {
1346 Kind
= CK_IntegralToBoolean
;
1348 } else if (DestType
->isIntegralType(Self
.Context
)) {
1349 Kind
= CK_IntegralCast
;
1351 } else if (DestType
->isRealFloatingType()) {
1352 Kind
= CK_IntegralToFloating
;
1358 // Reverse integral promotion/conversion. All such conversions are themselves
1359 // again integral promotions or conversions and are thus already handled by
1360 // p2 (TryDirectInitialization above).
1361 // (Note: any data loss warnings should be suppressed.)
1362 // The exception is the reverse of enum->integer, i.e. integer->enum (and
1363 // enum->enum). See also C++ 5.2.9p7.
1364 // The same goes for reverse floating point promotion/conversion and
1365 // floating-integral conversions. Again, only floating->enum is relevant.
1366 if (DestType
->isEnumeralType()) {
1367 if (Self
.RequireCompleteType(OpRange
.getBegin(), DestType
,
1368 diag::err_bad_cast_incomplete
)) {
1369 SrcExpr
= ExprError();
1372 if (SrcType
->isIntegralOrEnumerationType()) {
1373 // [expr.static.cast]p10 If the enumeration type has a fixed underlying
1374 // type, the value is first converted to that type by integral conversion
1375 const EnumType
*Enum
= DestType
->castAs
<EnumType
>();
1376 Kind
= Enum
->getDecl()->isFixed() &&
1377 Enum
->getDecl()->getIntegerType()->isBooleanType()
1378 ? CK_IntegralToBoolean
1381 } else if (SrcType
->isRealFloatingType()) {
1382 Kind
= CK_FloatingToIntegral
;
1387 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
1388 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
1389 tcr
= TryStaticPointerDowncast(Self
, SrcType
, DestType
, CStyle
, OpRange
, msg
,
1391 if (tcr
!= TC_NotApplicable
)
1394 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
1395 // conversion. C++ 5.2.9p9 has additional information.
1396 // DR54's access restrictions apply here also.
1397 tcr
= TryStaticMemberPointerUpcast(Self
, SrcExpr
, SrcType
, DestType
, CStyle
,
1398 OpRange
, msg
, Kind
, BasePath
);
1399 if (tcr
!= TC_NotApplicable
)
1402 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
1403 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
1404 // just the usual constness stuff.
1405 if (const PointerType
*SrcPointer
= SrcType
->getAs
<PointerType
>()) {
1406 QualType SrcPointee
= SrcPointer
->getPointeeType();
1407 if (SrcPointee
->isVoidType()) {
1408 if (const PointerType
*DestPointer
= DestType
->getAs
<PointerType
>()) {
1409 QualType DestPointee
= DestPointer
->getPointeeType();
1410 if (DestPointee
->isIncompleteOrObjectType()) {
1411 // This is definitely the intended conversion, but it might fail due
1412 // to a qualifier violation. Note that we permit Objective-C lifetime
1413 // and GC qualifier mismatches here.
1415 Qualifiers DestPointeeQuals
= DestPointee
.getQualifiers();
1416 Qualifiers SrcPointeeQuals
= SrcPointee
.getQualifiers();
1417 DestPointeeQuals
.removeObjCGCAttr();
1418 DestPointeeQuals
.removeObjCLifetime();
1419 SrcPointeeQuals
.removeObjCGCAttr();
1420 SrcPointeeQuals
.removeObjCLifetime();
1421 if (DestPointeeQuals
!= SrcPointeeQuals
&&
1422 !DestPointeeQuals
.compatiblyIncludes(SrcPointeeQuals
)) {
1423 msg
= diag::err_bad_cxx_cast_qualifiers_away
;
1427 Kind
= IsAddressSpaceConversion(SrcType
, DestType
)
1428 ? CK_AddressSpaceConversion
1433 // Microsoft permits static_cast from 'pointer-to-void' to
1434 // 'pointer-to-function'.
1435 if (!CStyle
&& Self
.getLangOpts().MSVCCompat
&&
1436 DestPointee
->isFunctionType()) {
1437 Self
.Diag(OpRange
.getBegin(), diag::ext_ms_cast_fn_obj
) << OpRange
;
1442 else if (DestType
->isObjCObjectPointerType()) {
1443 // allow both c-style cast and static_cast of objective-c pointers as
1444 // they are pervasive.
1445 Kind
= CK_CPointerToObjCPointerCast
;
1448 else if (CStyle
&& DestType
->isBlockPointerType()) {
1449 // allow c-style cast of void * to block pointers.
1450 Kind
= CK_AnyPointerToBlockPointerCast
;
1455 // Allow arbitrary objective-c pointer conversion with static casts.
1456 if (SrcType
->isObjCObjectPointerType() &&
1457 DestType
->isObjCObjectPointerType()) {
1461 // Allow ns-pointer to cf-pointer conversion in either direction
1462 // with static casts.
1464 Self
.CheckTollFreeBridgeStaticCast(DestType
, SrcExpr
.get(), Kind
))
1467 // See if it looks like the user is trying to convert between
1468 // related record types, and select a better diagnostic if so.
1469 if (auto SrcPointer
= SrcType
->getAs
<PointerType
>())
1470 if (auto DestPointer
= DestType
->getAs
<PointerType
>())
1471 if (SrcPointer
->getPointeeType()->getAs
<RecordType
>() &&
1472 DestPointer
->getPointeeType()->getAs
<RecordType
>())
1473 msg
= diag::err_bad_cxx_cast_unrelated_class
;
1475 if (SrcType
->isMatrixType() && DestType
->isMatrixType()) {
1476 if (Self
.CheckMatrixCast(OpRange
, DestType
, SrcType
, Kind
)) {
1477 SrcExpr
= ExprError();
1483 // We tried everything. Everything! Nothing works! :-(
1484 return TC_NotApplicable
;
1487 /// Tests whether a conversion according to N2844 is valid.
1488 TryCastResult
TryLValueToRValueCast(Sema
&Self
, Expr
*SrcExpr
,
1489 QualType DestType
, bool CStyle
,
1490 CastKind
&Kind
, CXXCastPath
&BasePath
,
1492 // C++11 [expr.static.cast]p3:
1493 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
1494 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
1495 const RValueReferenceType
*R
= DestType
->getAs
<RValueReferenceType
>();
1497 return TC_NotApplicable
;
1499 if (!SrcExpr
->isGLValue())
1500 return TC_NotApplicable
;
1502 // Because we try the reference downcast before this function, from now on
1503 // this is the only cast possibility, so we issue an error if we fail now.
1504 // FIXME: Should allow casting away constness if CStyle.
1505 QualType FromType
= SrcExpr
->getType();
1506 QualType ToType
= R
->getPointeeType();
1508 FromType
= FromType
.getUnqualifiedType();
1509 ToType
= ToType
.getUnqualifiedType();
1512 Sema::ReferenceConversions RefConv
;
1513 Sema::ReferenceCompareResult RefResult
= Self
.CompareReferenceRelationship(
1514 SrcExpr
->getBeginLoc(), ToType
, FromType
, &RefConv
);
1515 if (RefResult
!= Sema::Ref_Compatible
) {
1516 if (CStyle
|| RefResult
== Sema::Ref_Incompatible
)
1517 return TC_NotApplicable
;
1518 // Diagnose types which are reference-related but not compatible here since
1519 // we can provide better diagnostics. In these cases forwarding to
1520 // [expr.static.cast]p4 should never result in a well-formed cast.
1521 msg
= SrcExpr
->isLValue() ? diag::err_bad_lvalue_to_rvalue_cast
1522 : diag::err_bad_rvalue_to_rvalue_cast
;
1526 if (RefConv
& Sema::ReferenceConversions::DerivedToBase
) {
1527 Kind
= CK_DerivedToBase
;
1528 CXXBasePaths
Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1529 /*DetectVirtual=*/true);
1530 if (!Self
.IsDerivedFrom(SrcExpr
->getBeginLoc(), SrcExpr
->getType(),
1531 R
->getPointeeType(), Paths
))
1532 return TC_NotApplicable
;
1534 Self
.BuildBasePathArray(Paths
, BasePath
);
1541 /// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1543 TryStaticReferenceDowncast(Sema
&Self
, Expr
*SrcExpr
, QualType DestType
,
1544 bool CStyle
, SourceRange OpRange
,
1545 unsigned &msg
, CastKind
&Kind
,
1546 CXXCastPath
&BasePath
) {
1547 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1548 // cast to type "reference to cv2 D", where D is a class derived from B,
1549 // if a valid standard conversion from "pointer to D" to "pointer to B"
1550 // exists, cv2 >= cv1, and B is not a virtual base class of D.
1551 // In addition, DR54 clarifies that the base must be accessible in the
1552 // current context. Although the wording of DR54 only applies to the pointer
1553 // variant of this rule, the intent is clearly for it to apply to the this
1554 // conversion as well.
1556 const ReferenceType
*DestReference
= DestType
->getAs
<ReferenceType
>();
1557 if (!DestReference
) {
1558 return TC_NotApplicable
;
1560 bool RValueRef
= DestReference
->isRValueReferenceType();
1561 if (!RValueRef
&& !SrcExpr
->isLValue()) {
1562 // We know the left side is an lvalue reference, so we can suggest a reason.
1563 msg
= diag::err_bad_cxx_cast_rvalue
;
1564 return TC_NotApplicable
;
1567 QualType DestPointee
= DestReference
->getPointeeType();
1569 // FIXME: If the source is a prvalue, we should issue a warning (because the
1570 // cast always has undefined behavior), and for AST consistency, we should
1571 // materialize a temporary.
1572 return TryStaticDowncast(Self
,
1573 Self
.Context
.getCanonicalType(SrcExpr
->getType()),
1574 Self
.Context
.getCanonicalType(DestPointee
), CStyle
,
1575 OpRange
, SrcExpr
->getType(), DestType
, msg
, Kind
,
1579 /// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1581 TryStaticPointerDowncast(Sema
&Self
, QualType SrcType
, QualType DestType
,
1582 bool CStyle
, SourceRange OpRange
,
1583 unsigned &msg
, CastKind
&Kind
,
1584 CXXCastPath
&BasePath
) {
1585 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1586 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1587 // is a class derived from B, if a valid standard conversion from "pointer
1588 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1590 // In addition, DR54 clarifies that the base must be accessible in the
1593 const PointerType
*DestPointer
= DestType
->getAs
<PointerType
>();
1595 return TC_NotApplicable
;
1598 const PointerType
*SrcPointer
= SrcType
->getAs
<PointerType
>();
1600 msg
= diag::err_bad_static_cast_pointer_nonpointer
;
1601 return TC_NotApplicable
;
1604 return TryStaticDowncast(Self
,
1605 Self
.Context
.getCanonicalType(SrcPointer
->getPointeeType()),
1606 Self
.Context
.getCanonicalType(DestPointer
->getPointeeType()),
1607 CStyle
, OpRange
, SrcType
, DestType
, msg
, Kind
,
1611 /// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1612 /// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
1613 /// DestType is possible and allowed.
1615 TryStaticDowncast(Sema
&Self
, CanQualType SrcType
, CanQualType DestType
,
1616 bool CStyle
, SourceRange OpRange
, QualType OrigSrcType
,
1617 QualType OrigDestType
, unsigned &msg
,
1618 CastKind
&Kind
, CXXCastPath
&BasePath
) {
1619 // We can only work with complete types. But don't complain if it doesn't work
1620 if (!Self
.isCompleteType(OpRange
.getBegin(), SrcType
) ||
1621 !Self
.isCompleteType(OpRange
.getBegin(), DestType
))
1622 return TC_NotApplicable
;
1624 // Downcast can only happen in class hierarchies, so we need classes.
1625 if (!DestType
->getAs
<RecordType
>() || !SrcType
->getAs
<RecordType
>()) {
1626 return TC_NotApplicable
;
1629 CXXBasePaths
Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1630 /*DetectVirtual=*/true);
1631 if (!Self
.IsDerivedFrom(OpRange
.getBegin(), DestType
, SrcType
, Paths
)) {
1632 return TC_NotApplicable
;
1635 // Target type does derive from source type. Now we're serious. If an error
1636 // appears now, it's not ignored.
1637 // This may not be entirely in line with the standard. Take for example:
1639 // struct B : virtual A {
1645 // (void)static_cast<const B&>(*((A*)0));
1647 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1648 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1649 // However, both GCC and Comeau reject this example, and accepting it would
1650 // mean more complex code if we're to preserve the nice error message.
1651 // FIXME: Being 100% compliant here would be nice to have.
1653 // Must preserve cv, as always, unless we're in C-style mode.
1654 if (!CStyle
&& !DestType
.isAtLeastAsQualifiedAs(SrcType
)) {
1655 msg
= diag::err_bad_cxx_cast_qualifiers_away
;
1659 if (Paths
.isAmbiguous(SrcType
.getUnqualifiedType())) {
1660 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1661 // that it builds the paths in reverse order.
1662 // To sum up: record all paths to the base and build a nice string from
1663 // them. Use it to spice up the error message.
1664 if (!Paths
.isRecordingPaths()) {
1666 Paths
.setRecordingPaths(true);
1667 Self
.IsDerivedFrom(OpRange
.getBegin(), DestType
, SrcType
, Paths
);
1669 std::string PathDisplayStr
;
1670 std::set
<unsigned> DisplayedPaths
;
1671 for (clang::CXXBasePath
&Path
: Paths
) {
1672 if (DisplayedPaths
.insert(Path
.back().SubobjectNumber
).second
) {
1673 // We haven't displayed a path to this particular base
1674 // class subobject yet.
1675 PathDisplayStr
+= "\n ";
1676 for (CXXBasePathElement
&PE
: llvm::reverse(Path
))
1677 PathDisplayStr
+= PE
.Base
->getType().getAsString() + " -> ";
1678 PathDisplayStr
+= QualType(DestType
).getAsString();
1682 Self
.Diag(OpRange
.getBegin(), diag::err_ambiguous_base_to_derived_cast
)
1683 << QualType(SrcType
).getUnqualifiedType()
1684 << QualType(DestType
).getUnqualifiedType()
1685 << PathDisplayStr
<< OpRange
;
1690 if (Paths
.getDetectedVirtual() != nullptr) {
1691 QualType
VirtualBase(Paths
.getDetectedVirtual(), 0);
1692 Self
.Diag(OpRange
.getBegin(), diag::err_static_downcast_via_virtual
)
1693 << OrigSrcType
<< OrigDestType
<< VirtualBase
<< OpRange
;
1699 switch (Self
.CheckBaseClassAccess(OpRange
.getBegin(),
1702 diag::err_downcast_from_inaccessible_base
)) {
1703 case Sema::AR_accessible
:
1704 case Sema::AR_delayed
: // be optimistic
1705 case Sema::AR_dependent
: // be optimistic
1708 case Sema::AR_inaccessible
:
1714 Self
.BuildBasePathArray(Paths
, BasePath
);
1715 Kind
= CK_BaseToDerived
;
1719 /// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1720 /// C++ 5.2.9p9 is valid:
1722 /// An rvalue of type "pointer to member of D of type cv1 T" can be
1723 /// converted to an rvalue of type "pointer to member of B of type cv2 T",
1724 /// where B is a base class of D [...].
1727 TryStaticMemberPointerUpcast(Sema
&Self
, ExprResult
&SrcExpr
, QualType SrcType
,
1728 QualType DestType
, bool CStyle
,
1729 SourceRange OpRange
,
1730 unsigned &msg
, CastKind
&Kind
,
1731 CXXCastPath
&BasePath
) {
1732 const MemberPointerType
*DestMemPtr
= DestType
->getAs
<MemberPointerType
>();
1734 return TC_NotApplicable
;
1736 bool WasOverloadedFunction
= false;
1737 DeclAccessPair FoundOverload
;
1738 if (SrcExpr
.get()->getType() == Self
.Context
.OverloadTy
) {
1739 if (FunctionDecl
*Fn
1740 = Self
.ResolveAddressOfOverloadedFunction(SrcExpr
.get(), DestType
, false,
1742 CXXMethodDecl
*M
= cast
<CXXMethodDecl
>(Fn
);
1743 SrcType
= Self
.Context
.getMemberPointerType(Fn
->getType(),
1744 Self
.Context
.getTypeDeclType(M
->getParent()).getTypePtr());
1745 WasOverloadedFunction
= true;
1749 const MemberPointerType
*SrcMemPtr
= SrcType
->getAs
<MemberPointerType
>();
1751 msg
= diag::err_bad_static_cast_member_pointer_nonmp
;
1752 return TC_NotApplicable
;
1755 // Lock down the inheritance model right now in MS ABI, whether or not the
1756 // pointee types are the same.
1757 if (Self
.Context
.getTargetInfo().getCXXABI().isMicrosoft()) {
1758 (void)Self
.isCompleteType(OpRange
.getBegin(), SrcType
);
1759 (void)Self
.isCompleteType(OpRange
.getBegin(), DestType
);
1762 // T == T, modulo cv
1763 if (!Self
.Context
.hasSameUnqualifiedType(SrcMemPtr
->getPointeeType(),
1764 DestMemPtr
->getPointeeType()))
1765 return TC_NotApplicable
;
1768 QualType
SrcClass(SrcMemPtr
->getClass(), 0);
1769 QualType
DestClass(DestMemPtr
->getClass(), 0);
1770 CXXBasePaths
Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1771 /*DetectVirtual=*/true);
1772 if (!Self
.IsDerivedFrom(OpRange
.getBegin(), SrcClass
, DestClass
, Paths
))
1773 return TC_NotApplicable
;
1775 // B is a base of D. But is it an allowed base? If not, it's a hard error.
1776 if (Paths
.isAmbiguous(Self
.Context
.getCanonicalType(DestClass
))) {
1778 Paths
.setRecordingPaths(true);
1780 Self
.IsDerivedFrom(OpRange
.getBegin(), SrcClass
, DestClass
, Paths
);
1783 std::string PathDisplayStr
= Self
.getAmbiguousPathsDisplayString(Paths
);
1784 Self
.Diag(OpRange
.getBegin(), diag::err_ambiguous_memptr_conv
)
1785 << 1 << SrcClass
<< DestClass
<< PathDisplayStr
<< OpRange
;
1790 if (const RecordType
*VBase
= Paths
.getDetectedVirtual()) {
1791 Self
.Diag(OpRange
.getBegin(), diag::err_memptr_conv_via_virtual
)
1792 << SrcClass
<< DestClass
<< QualType(VBase
, 0) << OpRange
;
1798 switch (Self
.CheckBaseClassAccess(OpRange
.getBegin(),
1799 DestClass
, SrcClass
,
1801 diag::err_upcast_to_inaccessible_base
)) {
1802 case Sema::AR_accessible
:
1803 case Sema::AR_delayed
:
1804 case Sema::AR_dependent
:
1805 // Optimistically assume that the delayed and dependent cases
1809 case Sema::AR_inaccessible
:
1815 if (WasOverloadedFunction
) {
1816 // Resolve the address of the overloaded function again, this time
1817 // allowing complaints if something goes wrong.
1818 FunctionDecl
*Fn
= Self
.ResolveAddressOfOverloadedFunction(SrcExpr
.get(),
1827 SrcExpr
= Self
.FixOverloadedFunctionReference(SrcExpr
, FoundOverload
, Fn
);
1828 if (!SrcExpr
.isUsable()) {
1834 Self
.BuildBasePathArray(Paths
, BasePath
);
1835 Kind
= CK_DerivedToBaseMemberPointer
;
1839 /// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1842 /// An expression e can be explicitly converted to a type T using a
1843 /// @c static_cast if the declaration "T t(e);" is well-formed [...].
1845 TryStaticImplicitCast(Sema
&Self
, ExprResult
&SrcExpr
, QualType DestType
,
1846 Sema::CheckedConversionKind CCK
,
1847 SourceRange OpRange
, unsigned &msg
,
1848 CastKind
&Kind
, bool ListInitialization
) {
1849 if (DestType
->isRecordType()) {
1850 if (Self
.RequireCompleteType(OpRange
.getBegin(), DestType
,
1851 diag::err_bad_cast_incomplete
) ||
1852 Self
.RequireNonAbstractType(OpRange
.getBegin(), DestType
,
1853 diag::err_allocation_of_abstract_type
)) {
1859 InitializedEntity Entity
= InitializedEntity::InitializeTemporary(DestType
);
1860 InitializationKind InitKind
1861 = (CCK
== Sema::CCK_CStyleCast
)
1862 ? InitializationKind::CreateCStyleCast(OpRange
.getBegin(), OpRange
,
1864 : (CCK
== Sema::CCK_FunctionalCast
)
1865 ? InitializationKind::CreateFunctionalCast(OpRange
, ListInitialization
)
1866 : InitializationKind::CreateCast(OpRange
);
1867 Expr
*SrcExprRaw
= SrcExpr
.get();
1868 // FIXME: Per DR242, we should check for an implicit conversion sequence
1869 // or for a constructor that could be invoked by direct-initialization
1870 // here, not for an initialization sequence.
1871 InitializationSequence
InitSeq(Self
, Entity
, InitKind
, SrcExprRaw
);
1873 // At this point of CheckStaticCast, if the destination is a reference,
1874 // or the expression is an overload expression this has to work.
1875 // There is no other way that works.
1876 // On the other hand, if we're checking a C-style cast, we've still got
1877 // the reinterpret_cast way.
1879 = (CCK
== Sema::CCK_CStyleCast
|| CCK
== Sema::CCK_FunctionalCast
);
1880 if (InitSeq
.Failed() && (CStyle
|| !DestType
->isReferenceType()))
1881 return TC_NotApplicable
;
1883 ExprResult Result
= InitSeq
.Perform(Self
, Entity
, InitKind
, SrcExprRaw
);
1884 if (Result
.isInvalid()) {
1889 if (InitSeq
.isConstructorInitialization())
1890 Kind
= CK_ConstructorConversion
;
1898 /// TryConstCast - See if a const_cast from source to destination is allowed,
1899 /// and perform it if it is.
1900 static TryCastResult
TryConstCast(Sema
&Self
, ExprResult
&SrcExpr
,
1901 QualType DestType
, bool CStyle
,
1903 DestType
= Self
.Context
.getCanonicalType(DestType
);
1904 QualType SrcType
= SrcExpr
.get()->getType();
1905 bool NeedToMaterializeTemporary
= false;
1907 if (const ReferenceType
*DestTypeTmp
=DestType
->getAs
<ReferenceType
>()) {
1909 // if a pointer to T1 can be explicitly converted to the type "pointer to
1910 // T2" using a const_cast, then the following conversions can also be
1912 // -- an lvalue of type T1 can be explicitly converted to an lvalue of
1913 // type T2 using the cast const_cast<T2&>;
1914 // -- a glvalue of type T1 can be explicitly converted to an xvalue of
1915 // type T2 using the cast const_cast<T2&&>; and
1916 // -- if T1 is a class type, a prvalue of type T1 can be explicitly
1917 // converted to an xvalue of type T2 using the cast const_cast<T2&&>.
1919 if (isa
<LValueReferenceType
>(DestTypeTmp
) && !SrcExpr
.get()->isLValue()) {
1920 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1921 // is C-style, static_cast might find a way, so we simply suggest a
1922 // message and tell the parent to keep searching.
1923 msg
= diag::err_bad_cxx_cast_rvalue
;
1924 return TC_NotApplicable
;
1927 if (isa
<RValueReferenceType
>(DestTypeTmp
) && SrcExpr
.get()->isPRValue()) {
1928 if (!SrcType
->isRecordType()) {
1929 // Cannot const_cast non-class prvalue to rvalue reference type. But if
1930 // this is C-style, static_cast can do this.
1931 msg
= diag::err_bad_cxx_cast_rvalue
;
1932 return TC_NotApplicable
;
1935 // Materialize the class prvalue so that the const_cast can bind a
1937 NeedToMaterializeTemporary
= true;
1940 // It's not completely clear under the standard whether we can
1941 // const_cast bit-field gl-values. Doing so would not be
1942 // intrinsically complicated, but for now, we say no for
1943 // consistency with other compilers and await the word of the
1945 if (SrcExpr
.get()->refersToBitField()) {
1946 msg
= diag::err_bad_cxx_cast_bitfield
;
1947 return TC_NotApplicable
;
1950 DestType
= Self
.Context
.getPointerType(DestTypeTmp
->getPointeeType());
1951 SrcType
= Self
.Context
.getPointerType(SrcType
);
1954 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1955 // the rules for const_cast are the same as those used for pointers.
1957 if (!DestType
->isPointerType() &&
1958 !DestType
->isMemberPointerType() &&
1959 !DestType
->isObjCObjectPointerType()) {
1960 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1961 // was a reference type, we converted it to a pointer above.
1962 // The status of rvalue references isn't entirely clear, but it looks like
1963 // conversion to them is simply invalid.
1964 // C++ 5.2.11p3: For two pointer types [...]
1966 msg
= diag::err_bad_const_cast_dest
;
1967 return TC_NotApplicable
;
1969 if (DestType
->isFunctionPointerType() ||
1970 DestType
->isMemberFunctionPointerType()) {
1971 // Cannot cast direct function pointers.
1972 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1973 // T is the ultimate pointee of source and target type.
1975 msg
= diag::err_bad_const_cast_dest
;
1976 return TC_NotApplicable
;
1979 // C++ [expr.const.cast]p3:
1980 // "For two similar types T1 and T2, [...]"
1982 // We only allow a const_cast to change cvr-qualifiers, not other kinds of
1983 // type qualifiers. (Likewise, we ignore other changes when determining
1984 // whether a cast casts away constness.)
1985 if (!Self
.Context
.hasCvrSimilarType(SrcType
, DestType
))
1986 return TC_NotApplicable
;
1988 if (NeedToMaterializeTemporary
)
1989 // This is a const_cast from a class prvalue to an rvalue reference type.
1990 // Materialize a temporary to store the result of the conversion.
1991 SrcExpr
= Self
.CreateMaterializeTemporaryExpr(SrcExpr
.get()->getType(),
1993 /*IsLValueReference*/ false);
1998 // Checks for undefined behavior in reinterpret_cast.
1999 // The cases that is checked for is:
2000 // *reinterpret_cast<T*>(&a)
2001 // reinterpret_cast<T&>(a)
2002 // where accessing 'a' as type 'T' will result in undefined behavior.
2003 void Sema::CheckCompatibleReinterpretCast(QualType SrcType
, QualType DestType
,
2005 SourceRange Range
) {
2006 unsigned DiagID
= IsDereference
?
2007 diag::warn_pointer_indirection_from_incompatible_type
:
2008 diag::warn_undefined_reinterpret_cast
;
2010 if (Diags
.isIgnored(DiagID
, Range
.getBegin()))
2013 QualType SrcTy
, DestTy
;
2014 if (IsDereference
) {
2015 if (!SrcType
->getAs
<PointerType
>() || !DestType
->getAs
<PointerType
>()) {
2018 SrcTy
= SrcType
->getPointeeType();
2019 DestTy
= DestType
->getPointeeType();
2021 if (!DestType
->getAs
<ReferenceType
>()) {
2025 DestTy
= DestType
->getPointeeType();
2028 // Cast is compatible if the types are the same.
2029 if (Context
.hasSameUnqualifiedType(DestTy
, SrcTy
)) {
2032 // or one of the types is a char or void type
2033 if (DestTy
->isAnyCharacterType() || DestTy
->isVoidType() ||
2034 SrcTy
->isAnyCharacterType() || SrcTy
->isVoidType()) {
2037 // or one of the types is a tag type.
2038 if (SrcTy
->getAs
<TagType
>() || DestTy
->getAs
<TagType
>()) {
2042 // FIXME: Scoped enums?
2043 if ((SrcTy
->isUnsignedIntegerType() && DestTy
->isSignedIntegerType()) ||
2044 (SrcTy
->isSignedIntegerType() && DestTy
->isUnsignedIntegerType())) {
2045 if (Context
.getTypeSize(DestTy
) == Context
.getTypeSize(SrcTy
)) {
2050 Diag(Range
.getBegin(), DiagID
) << SrcType
<< DestType
<< Range
;
2053 static void DiagnoseCastOfObjCSEL(Sema
&Self
, const ExprResult
&SrcExpr
,
2054 QualType DestType
) {
2055 QualType SrcType
= SrcExpr
.get()->getType();
2056 if (Self
.Context
.hasSameType(SrcType
, DestType
))
2058 if (const PointerType
*SrcPtrTy
= SrcType
->getAs
<PointerType
>())
2059 if (SrcPtrTy
->isObjCSelType()) {
2060 QualType DT
= DestType
;
2061 if (isa
<PointerType
>(DestType
))
2062 DT
= DestType
->getPointeeType();
2063 if (!DT
.getUnqualifiedType()->isVoidType())
2064 Self
.Diag(SrcExpr
.get()->getExprLoc(),
2065 diag::warn_cast_pointer_from_sel
)
2066 << SrcType
<< DestType
<< SrcExpr
.get()->getSourceRange();
2070 /// Diagnose casts that change the calling convention of a pointer to a function
2071 /// defined in the current TU.
2072 static void DiagnoseCallingConvCast(Sema
&Self
, const ExprResult
&SrcExpr
,
2073 QualType DstType
, SourceRange OpRange
) {
2074 // Check if this cast would change the calling convention of a function
2076 QualType SrcType
= SrcExpr
.get()->getType();
2077 if (Self
.Context
.hasSameType(SrcType
, DstType
) ||
2078 !SrcType
->isFunctionPointerType() || !DstType
->isFunctionPointerType())
2080 const auto *SrcFTy
=
2081 SrcType
->castAs
<PointerType
>()->getPointeeType()->castAs
<FunctionType
>();
2082 const auto *DstFTy
=
2083 DstType
->castAs
<PointerType
>()->getPointeeType()->castAs
<FunctionType
>();
2084 CallingConv SrcCC
= SrcFTy
->getCallConv();
2085 CallingConv DstCC
= DstFTy
->getCallConv();
2089 // We have a calling convention cast. Check if the source is a pointer to a
2090 // known, specific function that has already been defined.
2091 Expr
*Src
= SrcExpr
.get()->IgnoreParenImpCasts();
2092 if (auto *UO
= dyn_cast
<UnaryOperator
>(Src
))
2093 if (UO
->getOpcode() == UO_AddrOf
)
2094 Src
= UO
->getSubExpr()->IgnoreParenImpCasts();
2095 auto *DRE
= dyn_cast
<DeclRefExpr
>(Src
);
2098 auto *FD
= dyn_cast
<FunctionDecl
>(DRE
->getDecl());
2102 // Only warn if we are casting from the default convention to a non-default
2103 // convention. This can happen when the programmer forgot to apply the calling
2104 // convention to the function declaration and then inserted this cast to
2105 // satisfy the type system.
2106 CallingConv DefaultCC
= Self
.getASTContext().getDefaultCallingConvention(
2107 FD
->isVariadic(), FD
->isCXXInstanceMember());
2108 if (DstCC
== DefaultCC
|| SrcCC
!= DefaultCC
)
2111 // Diagnose this cast, as it is probably bad.
2112 StringRef SrcCCName
= FunctionType::getNameForCallConv(SrcCC
);
2113 StringRef DstCCName
= FunctionType::getNameForCallConv(DstCC
);
2114 Self
.Diag(OpRange
.getBegin(), diag::warn_cast_calling_conv
)
2115 << SrcCCName
<< DstCCName
<< OpRange
;
2117 // The checks above are cheaper than checking if the diagnostic is enabled.
2118 // However, it's worth checking if the warning is enabled before we construct
2120 if (Self
.Diags
.isIgnored(diag::warn_cast_calling_conv
, OpRange
.getBegin()))
2123 // Try to suggest a fixit to change the calling convention of the function
2124 // whose address was taken. Try to use the latest macro for the convention.
2125 // For example, users probably want to write "WINAPI" instead of "__stdcall"
2126 // to match the Windows header declarations.
2127 SourceLocation NameLoc
= FD
->getFirstDecl()->getNameInfo().getLoc();
2128 Preprocessor
&PP
= Self
.getPreprocessor();
2129 SmallVector
<TokenValue
, 6> AttrTokens
;
2130 SmallString
<64> CCAttrText
;
2131 llvm::raw_svector_ostream
OS(CCAttrText
);
2132 if (Self
.getLangOpts().MicrosoftExt
) {
2133 // __stdcall or __vectorcall
2134 OS
<< "__" << DstCCName
;
2135 IdentifierInfo
*II
= PP
.getIdentifierInfo(OS
.str());
2136 AttrTokens
.push_back(II
->isKeyword(Self
.getLangOpts())
2137 ? TokenValue(II
->getTokenID())
2140 // __attribute__((stdcall)) or __attribute__((vectorcall))
2141 OS
<< "__attribute__((" << DstCCName
<< "))";
2142 AttrTokens
.push_back(tok::kw___attribute
);
2143 AttrTokens
.push_back(tok::l_paren
);
2144 AttrTokens
.push_back(tok::l_paren
);
2145 IdentifierInfo
*II
= PP
.getIdentifierInfo(DstCCName
);
2146 AttrTokens
.push_back(II
->isKeyword(Self
.getLangOpts())
2147 ? TokenValue(II
->getTokenID())
2149 AttrTokens
.push_back(tok::r_paren
);
2150 AttrTokens
.push_back(tok::r_paren
);
2152 StringRef AttrSpelling
= PP
.getLastMacroWithSpelling(NameLoc
, AttrTokens
);
2153 if (!AttrSpelling
.empty())
2154 CCAttrText
= AttrSpelling
;
2156 Self
.Diag(NameLoc
, diag::note_change_calling_conv_fixit
)
2157 << FD
<< DstCCName
<< FixItHint::CreateInsertion(NameLoc
, CCAttrText
);
2160 static void checkIntToPointerCast(bool CStyle
, const SourceRange
&OpRange
,
2161 const Expr
*SrcExpr
, QualType DestType
,
2163 QualType SrcType
= SrcExpr
->getType();
2165 // Not warning on reinterpret_cast, boolean, constant expressions, etc
2166 // are not explicit design choices, but consistent with GCC's behavior.
2167 // Feel free to modify them if you've reason/evidence for an alternative.
2168 if (CStyle
&& SrcType
->isIntegralType(Self
.Context
)
2169 && !SrcType
->isBooleanType()
2170 && !SrcType
->isEnumeralType()
2171 && !SrcExpr
->isIntegerConstantExpr(Self
.Context
)
2172 && Self
.Context
.getTypeSize(DestType
) >
2173 Self
.Context
.getTypeSize(SrcType
)) {
2174 // Separate between casts to void* and non-void* pointers.
2175 // Some APIs use (abuse) void* for something like a user context,
2176 // and often that value is an integer even if it isn't a pointer itself.
2177 // Having a separate warning flag allows users to control the warning
2178 // for their workflow.
2179 unsigned Diag
= DestType
->isVoidPointerType() ?
2180 diag::warn_int_to_void_pointer_cast
2181 : diag::warn_int_to_pointer_cast
;
2182 Self
.Diag(OpRange
.getBegin(), Diag
) << SrcType
<< DestType
<< OpRange
;
2186 static bool fixOverloadedReinterpretCastExpr(Sema
&Self
, QualType DestType
,
2187 ExprResult
&Result
) {
2188 // We can only fix an overloaded reinterpret_cast if
2189 // - it is a template with explicit arguments that resolves to an lvalue
2190 // unambiguously, or
2191 // - it is the only function in an overload set that may have its address
2194 Expr
*E
= Result
.get();
2195 // TODO: what if this fails because of DiagnoseUseOfDecl or something
2197 if (Self
.ResolveAndFixSingleFunctionTemplateSpecialization(
2199 Expr::getValueKindForType(DestType
) ==
2200 VK_PRValue
// Convert Fun to Ptr
2205 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
2206 // preserves Result.
2208 if (!Self
.resolveAndFixAddressOfSingleOverloadCandidate(
2209 Result
, /*DoFunctionPointerConversion=*/true))
2211 return Result
.isUsable();
2214 static TryCastResult
TryReinterpretCast(Sema
&Self
, ExprResult
&SrcExpr
,
2215 QualType DestType
, bool CStyle
,
2216 SourceRange OpRange
,
2219 bool IsLValueCast
= false;
2221 DestType
= Self
.Context
.getCanonicalType(DestType
);
2222 QualType SrcType
= SrcExpr
.get()->getType();
2224 // Is the source an overloaded name? (i.e. &foo)
2225 // If so, reinterpret_cast generally can not help us here (13.4, p1, bullet 5)
2226 if (SrcType
== Self
.Context
.OverloadTy
) {
2227 ExprResult FixedExpr
= SrcExpr
;
2228 if (!fixOverloadedReinterpretCastExpr(Self
, DestType
, FixedExpr
))
2229 return TC_NotApplicable
;
2231 assert(FixedExpr
.isUsable() && "Invalid result fixing overloaded expr");
2232 SrcExpr
= FixedExpr
;
2233 SrcType
= SrcExpr
.get()->getType();
2236 if (const ReferenceType
*DestTypeTmp
= DestType
->getAs
<ReferenceType
>()) {
2237 if (!SrcExpr
.get()->isGLValue()) {
2238 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
2239 // similar comment in const_cast.
2240 msg
= diag::err_bad_cxx_cast_rvalue
;
2241 return TC_NotApplicable
;
2245 Self
.CheckCompatibleReinterpretCast(SrcType
, DestType
,
2246 /*IsDereference=*/false, OpRange
);
2249 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
2250 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
2251 // built-in & and * operators.
2253 const char *inappropriate
= nullptr;
2254 switch (SrcExpr
.get()->getObjectKind()) {
2258 msg
= diag::err_bad_cxx_cast_bitfield
;
2259 return TC_NotApplicable
;
2260 // FIXME: Use a specific diagnostic for the rest of these cases.
2261 case OK_VectorComponent
: inappropriate
= "vector element"; break;
2262 case OK_MatrixComponent
:
2263 inappropriate
= "matrix element";
2265 case OK_ObjCProperty
: inappropriate
= "property expression"; break;
2266 case OK_ObjCSubscript
: inappropriate
= "container subscripting expression";
2269 if (inappropriate
) {
2270 Self
.Diag(OpRange
.getBegin(), diag::err_bad_reinterpret_cast_reference
)
2271 << inappropriate
<< DestType
2272 << OpRange
<< SrcExpr
.get()->getSourceRange();
2273 msg
= 0; SrcExpr
= ExprError();
2274 return TC_NotApplicable
;
2277 // This code does this transformation for the checked types.
2278 DestType
= Self
.Context
.getPointerType(DestTypeTmp
->getPointeeType());
2279 SrcType
= Self
.Context
.getPointerType(SrcType
);
2281 IsLValueCast
= true;
2284 // Canonicalize source for comparison.
2285 SrcType
= Self
.Context
.getCanonicalType(SrcType
);
2287 const MemberPointerType
*DestMemPtr
= DestType
->getAs
<MemberPointerType
>(),
2288 *SrcMemPtr
= SrcType
->getAs
<MemberPointerType
>();
2289 if (DestMemPtr
&& SrcMemPtr
) {
2290 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
2291 // can be explicitly converted to an rvalue of type "pointer to member
2292 // of Y of type T2" if T1 and T2 are both function types or both object
2294 if (DestMemPtr
->isMemberFunctionPointer() !=
2295 SrcMemPtr
->isMemberFunctionPointer())
2296 return TC_NotApplicable
;
2298 if (Self
.Context
.getTargetInfo().getCXXABI().isMicrosoft()) {
2299 // We need to determine the inheritance model that the class will use if
2301 (void)Self
.isCompleteType(OpRange
.getBegin(), SrcType
);
2302 (void)Self
.isCompleteType(OpRange
.getBegin(), DestType
);
2305 // Don't allow casting between member pointers of different sizes.
2306 if (Self
.Context
.getTypeSize(DestMemPtr
) !=
2307 Self
.Context
.getTypeSize(SrcMemPtr
)) {
2308 msg
= diag::err_bad_cxx_cast_member_pointer_size
;
2312 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
2314 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
2317 CastsAwayConstness(Self
, SrcType
, DestType
, /*CheckCVR=*/!CStyle
,
2318 /*CheckObjCLifetime=*/CStyle
))
2319 return getCastAwayConstnessCastKind(CACK
, msg
);
2321 // A valid member pointer cast.
2322 assert(!IsLValueCast
);
2323 Kind
= CK_ReinterpretMemberPointer
;
2327 // See below for the enumeral issue.
2328 if (SrcType
->isNullPtrType() && DestType
->isIntegralType(Self
.Context
)) {
2329 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
2330 // type large enough to hold it. A value of std::nullptr_t can be
2331 // converted to an integral type; the conversion has the same meaning
2332 // and validity as a conversion of (void*)0 to the integral type.
2333 if (Self
.Context
.getTypeSize(SrcType
) >
2334 Self
.Context
.getTypeSize(DestType
)) {
2335 msg
= diag::err_bad_reinterpret_cast_small_int
;
2338 Kind
= CK_PointerToIntegral
;
2342 // Allow reinterpret_casts between vectors of the same size and
2343 // between vectors and integers of the same size.
2344 bool destIsVector
= DestType
->isVectorType();
2345 bool srcIsVector
= SrcType
->isVectorType();
2346 if (srcIsVector
|| destIsVector
) {
2347 // Allow bitcasting between SVE VLATs and VLSTs, and vice-versa.
2348 if (Self
.isValidSveBitcast(SrcType
, DestType
)) {
2353 // The non-vector type, if any, must have integral type. This is
2354 // the same rule that C vector casts use; note, however, that enum
2355 // types are not integral in C++.
2356 if ((!destIsVector
&& !DestType
->isIntegralType(Self
.Context
)) ||
2357 (!srcIsVector
&& !SrcType
->isIntegralType(Self
.Context
)))
2358 return TC_NotApplicable
;
2360 // The size we want to consider is eltCount * eltSize.
2361 // That's exactly what the lax-conversion rules will check.
2362 if (Self
.areLaxCompatibleVectorTypes(SrcType
, DestType
)) {
2367 if (Self
.LangOpts
.OpenCL
&& !CStyle
) {
2368 if (DestType
->isExtVectorType() || SrcType
->isExtVectorType()) {
2369 // FIXME: Allow for reinterpret cast between 3 and 4 element vectors
2370 if (Self
.areVectorTypesSameSize(SrcType
, DestType
)) {
2377 // Otherwise, pick a reasonable diagnostic.
2379 msg
= diag::err_bad_cxx_cast_vector_to_scalar_different_size
;
2380 else if (!srcIsVector
)
2381 msg
= diag::err_bad_cxx_cast_scalar_to_vector_different_size
;
2383 msg
= diag::err_bad_cxx_cast_vector_to_vector_different_size
;
2388 if (SrcType
== DestType
) {
2389 // C++ 5.2.10p2 has a note that mentions that, subject to all other
2390 // restrictions, a cast to the same type is allowed so long as it does not
2391 // cast away constness. In C++98, the intent was not entirely clear here,
2392 // since all other paragraphs explicitly forbid casts to the same type.
2393 // C++11 clarifies this case with p2.
2395 // The only allowed types are: integral, enumeration, pointer, or
2396 // pointer-to-member types. We also won't restrict Obj-C pointers either.
2398 TryCastResult Result
= TC_NotApplicable
;
2399 if (SrcType
->isIntegralOrEnumerationType() ||
2400 SrcType
->isAnyPointerType() ||
2401 SrcType
->isMemberPointerType() ||
2402 SrcType
->isBlockPointerType()) {
2403 Result
= TC_Success
;
2408 bool destIsPtr
= DestType
->isAnyPointerType() ||
2409 DestType
->isBlockPointerType();
2410 bool srcIsPtr
= SrcType
->isAnyPointerType() ||
2411 SrcType
->isBlockPointerType();
2412 if (!destIsPtr
&& !srcIsPtr
) {
2413 // Except for std::nullptr_t->integer and lvalue->reference, which are
2414 // handled above, at least one of the two arguments must be a pointer.
2415 return TC_NotApplicable
;
2418 if (DestType
->isIntegralType(Self
.Context
)) {
2419 assert(srcIsPtr
&& "One type must be a pointer");
2420 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
2421 // type large enough to hold it; except in Microsoft mode, where the
2422 // integral type size doesn't matter (except we don't allow bool).
2423 if ((Self
.Context
.getTypeSize(SrcType
) >
2424 Self
.Context
.getTypeSize(DestType
))) {
2425 bool MicrosoftException
=
2426 Self
.getLangOpts().MicrosoftExt
&& !DestType
->isBooleanType();
2427 if (MicrosoftException
) {
2428 unsigned Diag
= SrcType
->isVoidPointerType()
2429 ? diag::warn_void_pointer_to_int_cast
2430 : diag::warn_pointer_to_int_cast
;
2431 Self
.Diag(OpRange
.getBegin(), Diag
) << SrcType
<< DestType
<< OpRange
;
2433 msg
= diag::err_bad_reinterpret_cast_small_int
;
2437 Kind
= CK_PointerToIntegral
;
2441 if (SrcType
->isIntegralOrEnumerationType()) {
2442 assert(destIsPtr
&& "One type must be a pointer");
2443 checkIntToPointerCast(CStyle
, OpRange
, SrcExpr
.get(), DestType
, Self
);
2444 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
2445 // converted to a pointer.
2446 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
2447 // necessarily converted to a null pointer value.]
2448 Kind
= CK_IntegralToPointer
;
2452 if (!destIsPtr
|| !srcIsPtr
) {
2453 // With the valid non-pointer conversions out of the way, we can be even
2455 return TC_NotApplicable
;
2458 // Cannot convert between block pointers and Objective-C object pointers.
2459 if ((SrcType
->isBlockPointerType() && DestType
->isObjCObjectPointerType()) ||
2460 (DestType
->isBlockPointerType() && SrcType
->isObjCObjectPointerType()))
2461 return TC_NotApplicable
;
2463 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
2464 // The C-style cast operator can.
2465 TryCastResult SuccessResult
= TC_Success
;
2467 CastsAwayConstness(Self
, SrcType
, DestType
, /*CheckCVR=*/!CStyle
,
2468 /*CheckObjCLifetime=*/CStyle
))
2469 SuccessResult
= getCastAwayConstnessCastKind(CACK
, msg
);
2471 if (IsAddressSpaceConversion(SrcType
, DestType
)) {
2472 Kind
= CK_AddressSpaceConversion
;
2473 assert(SrcType
->isPointerType() && DestType
->isPointerType());
2475 !DestType
->getPointeeType().getQualifiers().isAddressSpaceSupersetOf(
2476 SrcType
->getPointeeType().getQualifiers())) {
2477 SuccessResult
= TC_Failed
;
2479 } else if (IsLValueCast
) {
2480 Kind
= CK_LValueBitCast
;
2481 } else if (DestType
->isObjCObjectPointerType()) {
2482 Kind
= Self
.PrepareCastToObjCObjectPointer(SrcExpr
);
2483 } else if (DestType
->isBlockPointerType()) {
2484 if (!SrcType
->isBlockPointerType()) {
2485 Kind
= CK_AnyPointerToBlockPointerCast
;
2493 // Any pointer can be cast to an Objective-C pointer type with a C-style
2495 if (CStyle
&& DestType
->isObjCObjectPointerType()) {
2496 return SuccessResult
;
2499 DiagnoseCastOfObjCSEL(Self
, SrcExpr
, DestType
);
2501 DiagnoseCallingConvCast(Self
, SrcExpr
, DestType
, OpRange
);
2503 // Not casting away constness, so the only remaining check is for compatible
2504 // pointer categories.
2506 if (SrcType
->isFunctionPointerType()) {
2507 if (DestType
->isFunctionPointerType()) {
2508 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
2509 // a pointer to a function of a different type.
2510 return SuccessResult
;
2513 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
2514 // an object type or vice versa is conditionally-supported.
2515 // Compilers support it in C++03 too, though, because it's necessary for
2516 // casting the return value of dlsym() and GetProcAddress().
2517 // FIXME: Conditionally-supported behavior should be configurable in the
2518 // TargetInfo or similar.
2519 Self
.Diag(OpRange
.getBegin(),
2520 Self
.getLangOpts().CPlusPlus11
?
2521 diag::warn_cxx98_compat_cast_fn_obj
: diag::ext_cast_fn_obj
)
2523 return SuccessResult
;
2526 if (DestType
->isFunctionPointerType()) {
2528 Self
.Diag(OpRange
.getBegin(),
2529 Self
.getLangOpts().CPlusPlus11
?
2530 diag::warn_cxx98_compat_cast_fn_obj
: diag::ext_cast_fn_obj
)
2532 return SuccessResult
;
2535 // Diagnose address space conversion in nested pointers.
2536 QualType DestPtee
= DestType
->getPointeeType().isNull()
2537 ? DestType
->getPointeeType()
2538 : DestType
->getPointeeType()->getPointeeType();
2539 QualType SrcPtee
= SrcType
->getPointeeType().isNull()
2540 ? SrcType
->getPointeeType()
2541 : SrcType
->getPointeeType()->getPointeeType();
2542 while (!DestPtee
.isNull() && !SrcPtee
.isNull()) {
2543 if (DestPtee
.getAddressSpace() != SrcPtee
.getAddressSpace()) {
2544 Self
.Diag(OpRange
.getBegin(),
2545 diag::warn_bad_cxx_cast_nested_pointer_addr_space
)
2546 << CStyle
<< SrcType
<< DestType
<< SrcExpr
.get()->getSourceRange();
2549 DestPtee
= DestPtee
->getPointeeType();
2550 SrcPtee
= SrcPtee
->getPointeeType();
2553 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
2554 // a pointer to an object of different type.
2555 // Void pointers are not specified, but supported by every compiler out there.
2556 // So we finish by allowing everything that remains - it's got to be two
2558 return SuccessResult
;
2561 static TryCastResult
TryAddressSpaceCast(Sema
&Self
, ExprResult
&SrcExpr
,
2562 QualType DestType
, bool CStyle
,
2563 unsigned &msg
, CastKind
&Kind
) {
2564 if (!Self
.getLangOpts().OpenCL
&& !Self
.getLangOpts().SYCLIsDevice
)
2565 // FIXME: As compiler doesn't have any information about overlapping addr
2566 // spaces at the moment we have to be permissive here.
2567 return TC_NotApplicable
;
2568 // Even though the logic below is general enough and can be applied to
2569 // non-OpenCL mode too, we fast-path above because no other languages
2570 // define overlapping address spaces currently.
2571 auto SrcType
= SrcExpr
.get()->getType();
2572 // FIXME: Should this be generalized to references? The reference parameter
2573 // however becomes a reference pointee type here and therefore rejected.
2574 // Perhaps this is the right behavior though according to C++.
2575 auto SrcPtrType
= SrcType
->getAs
<PointerType
>();
2577 return TC_NotApplicable
;
2578 auto DestPtrType
= DestType
->getAs
<PointerType
>();
2580 return TC_NotApplicable
;
2581 auto SrcPointeeType
= SrcPtrType
->getPointeeType();
2582 auto DestPointeeType
= DestPtrType
->getPointeeType();
2583 if (!DestPointeeType
.isAddressSpaceOverlapping(SrcPointeeType
)) {
2584 msg
= diag::err_bad_cxx_cast_addr_space_mismatch
;
2587 auto SrcPointeeTypeWithoutAS
=
2588 Self
.Context
.removeAddrSpaceQualType(SrcPointeeType
.getCanonicalType());
2589 auto DestPointeeTypeWithoutAS
=
2590 Self
.Context
.removeAddrSpaceQualType(DestPointeeType
.getCanonicalType());
2591 if (Self
.Context
.hasSameType(SrcPointeeTypeWithoutAS
,
2592 DestPointeeTypeWithoutAS
)) {
2593 Kind
= SrcPointeeType
.getAddressSpace() == DestPointeeType
.getAddressSpace()
2595 : CK_AddressSpaceConversion
;
2598 return TC_NotApplicable
;
2602 void CastOperation::checkAddressSpaceCast(QualType SrcType
, QualType DestType
) {
2603 // In OpenCL only conversions between pointers to objects in overlapping
2604 // addr spaces are allowed. v2.0 s6.5.5 - Generic addr space overlaps
2605 // with any named one, except for constant.
2607 // Converting the top level pointee addrspace is permitted for compatible
2608 // addrspaces (such as 'generic int *' to 'local int *' or vice versa), but
2609 // if any of the nested pointee addrspaces differ, we emit a warning
2610 // regardless of addrspace compatibility. This makes
2612 // return (generic int **) p;
2613 // warn even though local -> generic is permitted.
2614 if (Self
.getLangOpts().OpenCL
) {
2615 const Type
*DestPtr
, *SrcPtr
;
2616 bool Nested
= false;
2617 unsigned DiagID
= diag::err_typecheck_incompatible_address_space
;
2618 DestPtr
= Self
.getASTContext().getCanonicalType(DestType
.getTypePtr()),
2619 SrcPtr
= Self
.getASTContext().getCanonicalType(SrcType
.getTypePtr());
2621 while (isa
<PointerType
>(DestPtr
) && isa
<PointerType
>(SrcPtr
)) {
2622 const PointerType
*DestPPtr
= cast
<PointerType
>(DestPtr
);
2623 const PointerType
*SrcPPtr
= cast
<PointerType
>(SrcPtr
);
2624 QualType DestPPointee
= DestPPtr
->getPointeeType();
2625 QualType SrcPPointee
= SrcPPtr
->getPointeeType();
2627 ? DestPPointee
.getAddressSpace() != SrcPPointee
.getAddressSpace()
2628 : !DestPPointee
.isAddressSpaceOverlapping(SrcPPointee
)) {
2629 Self
.Diag(OpRange
.getBegin(), DiagID
)
2630 << SrcType
<< DestType
<< Sema::AA_Casting
2631 << SrcExpr
.get()->getSourceRange();
2633 SrcExpr
= ExprError();
2637 DestPtr
= DestPPtr
->getPointeeType().getTypePtr();
2638 SrcPtr
= SrcPPtr
->getPointeeType().getTypePtr();
2640 DiagID
= diag::ext_nested_pointer_qualifier_mismatch
;
2645 bool Sema::ShouldSplatAltivecScalarInCast(const VectorType
*VecTy
) {
2646 bool SrcCompatXL
= this->getLangOpts().getAltivecSrcCompat() ==
2647 LangOptions::AltivecSrcCompatKind::XL
;
2648 VectorType::VectorKind VKind
= VecTy
->getVectorKind();
2650 if ((VKind
== VectorType::AltiVecVector
) ||
2651 (SrcCompatXL
&& ((VKind
== VectorType::AltiVecBool
) ||
2652 (VKind
== VectorType::AltiVecPixel
)))) {
2658 bool Sema::CheckAltivecInitFromScalar(SourceRange R
, QualType VecTy
,
2660 bool SrcCompatGCC
= this->getLangOpts().getAltivecSrcCompat() ==
2661 LangOptions::AltivecSrcCompatKind::GCC
;
2662 if (this->getLangOpts().AltiVec
&& SrcCompatGCC
) {
2663 this->Diag(R
.getBegin(),
2664 diag::err_invalid_conversion_between_vector_and_integer
)
2665 << VecTy
<< SrcTy
<< R
;
2671 void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle
,
2672 bool ListInitialization
) {
2673 assert(Self
.getLangOpts().CPlusPlus
);
2675 // Handle placeholders.
2676 if (isPlaceholder()) {
2677 // C-style casts can resolve __unknown_any types.
2678 if (claimPlaceholder(BuiltinType::UnknownAny
)) {
2679 SrcExpr
= Self
.checkUnknownAnyCast(DestRange
, DestType
,
2680 SrcExpr
.get(), Kind
,
2681 ValueKind
, BasePath
);
2685 checkNonOverloadPlaceholders();
2686 if (SrcExpr
.isInvalid())
2690 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
2691 // This test is outside everything else because it's the only case where
2692 // a non-lvalue-reference target type does not lead to decay.
2693 if (DestType
->isVoidType()) {
2696 if (claimPlaceholder(BuiltinType::Overload
)) {
2697 Self
.ResolveAndFixSingleFunctionTemplateSpecialization(
2698 SrcExpr
, /* Decay Function to ptr */ false,
2699 /* Complain */ true, DestRange
, DestType
,
2700 diag::err_bad_cstyle_cast_overload
);
2701 if (SrcExpr
.isInvalid())
2705 SrcExpr
= Self
.IgnoredValueConversions(SrcExpr
.get());
2709 // If the type is dependent, we won't do any other semantic analysis now.
2710 if (DestType
->isDependentType() || SrcExpr
.get()->isTypeDependent() ||
2711 SrcExpr
.get()->isValueDependent()) {
2712 assert(Kind
== CK_Dependent
);
2716 if (ValueKind
== VK_PRValue
&& !DestType
->isRecordType() &&
2717 !isPlaceholder(BuiltinType::Overload
)) {
2718 SrcExpr
= Self
.DefaultFunctionArrayLvalueConversion(SrcExpr
.get());
2719 if (SrcExpr
.isInvalid())
2723 // AltiVec vector initialization with a single literal.
2724 if (const VectorType
*vecTy
= DestType
->getAs
<VectorType
>()) {
2725 if (Self
.CheckAltivecInitFromScalar(OpRange
, DestType
,
2726 SrcExpr
.get()->getType())) {
2727 SrcExpr
= ExprError();
2730 if (Self
.ShouldSplatAltivecScalarInCast(vecTy
) &&
2731 (SrcExpr
.get()->getType()->isIntegerType() ||
2732 SrcExpr
.get()->getType()->isFloatingType())) {
2733 Kind
= CK_VectorSplat
;
2734 SrcExpr
= Self
.prepareVectorSplat(DestType
, SrcExpr
.get());
2739 // C++ [expr.cast]p5: The conversions performed by
2742 // - a static_cast followed by a const_cast,
2743 // - a reinterpret_cast, or
2744 // - a reinterpret_cast followed by a const_cast,
2745 // can be performed using the cast notation of explicit type conversion.
2746 // [...] If a conversion can be interpreted in more than one of the ways
2747 // listed above, the interpretation that appears first in the list is used,
2748 // even if a cast resulting from that interpretation is ill-formed.
2749 // In plain language, this means trying a const_cast ...
2750 // Note that for address space we check compatibility after const_cast.
2751 unsigned msg
= diag::err_bad_cxx_cast_generic
;
2752 TryCastResult tcr
= TryConstCast(Self
, SrcExpr
, DestType
,
2753 /*CStyle*/ true, msg
);
2754 if (SrcExpr
.isInvalid())
2756 if (isValidCast(tcr
))
2759 Sema::CheckedConversionKind CCK
=
2760 FunctionalStyle
? Sema::CCK_FunctionalCast
: Sema::CCK_CStyleCast
;
2761 if (tcr
== TC_NotApplicable
) {
2762 tcr
= TryAddressSpaceCast(Self
, SrcExpr
, DestType
, /*CStyle*/ true, msg
,
2764 if (SrcExpr
.isInvalid())
2767 if (tcr
== TC_NotApplicable
) {
2768 // ... or if that is not possible, a static_cast, ignoring const and
2770 tcr
= TryStaticCast(Self
, SrcExpr
, DestType
, CCK
, OpRange
, msg
, Kind
,
2771 BasePath
, ListInitialization
);
2772 if (SrcExpr
.isInvalid())
2775 if (tcr
== TC_NotApplicable
) {
2776 // ... and finally a reinterpret_cast, ignoring const and addr space.
2777 tcr
= TryReinterpretCast(Self
, SrcExpr
, DestType
, /*CStyle*/ true,
2778 OpRange
, msg
, Kind
);
2779 if (SrcExpr
.isInvalid())
2785 if (Self
.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
2787 checkObjCConversion(CCK
);
2789 if (tcr
!= TC_Success
&& msg
!= 0) {
2790 if (SrcExpr
.get()->getType() == Self
.Context
.OverloadTy
) {
2791 DeclAccessPair Found
;
2792 FunctionDecl
*Fn
= Self
.ResolveAddressOfOverloadedFunction(SrcExpr
.get(),
2797 // If DestType is a function type (not to be confused with the function
2798 // pointer type), it will be possible to resolve the function address,
2799 // but the type cast should be considered as failure.
2800 OverloadExpr
*OE
= OverloadExpr::find(SrcExpr
.get()).Expression
;
2801 Self
.Diag(OpRange
.getBegin(), diag::err_bad_cstyle_cast_overload
)
2802 << OE
->getName() << DestType
<< OpRange
2803 << OE
->getQualifierLoc().getSourceRange();
2804 Self
.NoteAllOverloadCandidates(SrcExpr
.get());
2807 diagnoseBadCast(Self
, msg
, (FunctionalStyle
? CT_Functional
: CT_CStyle
),
2808 OpRange
, SrcExpr
.get(), DestType
, ListInitialization
);
2812 if (isValidCast(tcr
)) {
2813 if (Kind
== CK_BitCast
)
2816 if (unsigned DiagID
= checkCastFunctionType(Self
, SrcExpr
, DestType
))
2817 Self
.Diag(OpRange
.getBegin(), DiagID
)
2818 << SrcExpr
.get()->getType() << DestType
<< OpRange
;
2821 SrcExpr
= ExprError();
2825 /// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
2826 /// non-matching type. Such as enum function call to int, int call to
2827 /// pointer; etc. Cast to 'void' is an exception.
2828 static void DiagnoseBadFunctionCast(Sema
&Self
, const ExprResult
&SrcExpr
,
2829 QualType DestType
) {
2830 if (Self
.Diags
.isIgnored(diag::warn_bad_function_cast
,
2831 SrcExpr
.get()->getExprLoc()))
2834 if (!isa
<CallExpr
>(SrcExpr
.get()))
2837 QualType SrcType
= SrcExpr
.get()->getType();
2838 if (DestType
.getUnqualifiedType()->isVoidType())
2840 if ((SrcType
->isAnyPointerType() || SrcType
->isBlockPointerType())
2841 && (DestType
->isAnyPointerType() || DestType
->isBlockPointerType()))
2843 if (SrcType
->isIntegerType() && DestType
->isIntegerType() &&
2844 (SrcType
->isBooleanType() == DestType
->isBooleanType()) &&
2845 (SrcType
->isEnumeralType() == DestType
->isEnumeralType()))
2847 if (SrcType
->isRealFloatingType() && DestType
->isRealFloatingType())
2849 if (SrcType
->isEnumeralType() && DestType
->isEnumeralType())
2851 if (SrcType
->isComplexType() && DestType
->isComplexType())
2853 if (SrcType
->isComplexIntegerType() && DestType
->isComplexIntegerType())
2855 if (SrcType
->isFixedPointType() && DestType
->isFixedPointType())
2858 Self
.Diag(SrcExpr
.get()->getExprLoc(),
2859 diag::warn_bad_function_cast
)
2860 << SrcType
<< DestType
<< SrcExpr
.get()->getSourceRange();
2863 /// Check the semantics of a C-style cast operation, in C.
2864 void CastOperation::CheckCStyleCast() {
2865 assert(!Self
.getLangOpts().CPlusPlus
);
2867 // C-style casts can resolve __unknown_any types.
2868 if (claimPlaceholder(BuiltinType::UnknownAny
)) {
2869 SrcExpr
= Self
.checkUnknownAnyCast(DestRange
, DestType
,
2870 SrcExpr
.get(), Kind
,
2871 ValueKind
, BasePath
);
2875 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2876 // type needs to be scalar.
2877 if (DestType
->isVoidType()) {
2878 // We don't necessarily do lvalue-to-rvalue conversions on this.
2879 SrcExpr
= Self
.IgnoredValueConversions(SrcExpr
.get());
2880 if (SrcExpr
.isInvalid())
2883 // Cast to void allows any expr type.
2888 // If the type is dependent, we won't do any other semantic analysis now.
2889 if (Self
.getASTContext().isDependenceAllowed() &&
2890 (DestType
->isDependentType() || SrcExpr
.get()->isTypeDependent() ||
2891 SrcExpr
.get()->isValueDependent())) {
2892 assert((DestType
->containsErrors() || SrcExpr
.get()->containsErrors() ||
2893 SrcExpr
.get()->containsErrors()) &&
2894 "should only occur in error-recovery path.");
2895 assert(Kind
== CK_Dependent
);
2899 // Overloads are allowed with C extensions, so we need to support them.
2900 if (SrcExpr
.get()->getType() == Self
.Context
.OverloadTy
) {
2902 if (FunctionDecl
*FD
= Self
.ResolveAddressOfOverloadedFunction(
2903 SrcExpr
.get(), DestType
, /*Complain=*/true, DAP
))
2904 SrcExpr
= Self
.FixOverloadedFunctionReference(SrcExpr
.get(), DAP
, FD
);
2907 assert(SrcExpr
.isUsable());
2909 SrcExpr
= Self
.DefaultFunctionArrayLvalueConversion(SrcExpr
.get());
2910 if (SrcExpr
.isInvalid())
2912 QualType SrcType
= SrcExpr
.get()->getType();
2914 assert(!SrcType
->isPlaceholderType());
2916 checkAddressSpaceCast(SrcType
, DestType
);
2917 if (SrcExpr
.isInvalid())
2920 if (Self
.RequireCompleteType(OpRange
.getBegin(), DestType
,
2921 diag::err_typecheck_cast_to_incomplete
)) {
2922 SrcExpr
= ExprError();
2926 // Allow casting a sizeless built-in type to itself.
2927 if (DestType
->isSizelessBuiltinType() &&
2928 Self
.Context
.hasSameUnqualifiedType(DestType
, SrcType
)) {
2933 // Allow bitcasting between compatible SVE vector types.
2934 if ((SrcType
->isVectorType() || DestType
->isVectorType()) &&
2935 Self
.isValidSveBitcast(SrcType
, DestType
)) {
2940 if (!DestType
->isScalarType() && !DestType
->isVectorType() &&
2941 !DestType
->isMatrixType()) {
2942 const RecordType
*DestRecordTy
= DestType
->getAs
<RecordType
>();
2944 if (DestRecordTy
&& Self
.Context
.hasSameUnqualifiedType(DestType
, SrcType
)){
2945 // GCC struct/union extension: allow cast to self.
2946 Self
.Diag(OpRange
.getBegin(), diag::ext_typecheck_cast_nonscalar
)
2947 << DestType
<< SrcExpr
.get()->getSourceRange();
2952 // GCC's cast to union extension.
2953 if (DestRecordTy
&& DestRecordTy
->getDecl()->isUnion()) {
2954 RecordDecl
*RD
= DestRecordTy
->getDecl();
2955 if (CastExpr::getTargetFieldForToUnionCast(RD
, SrcType
)) {
2956 Self
.Diag(OpRange
.getBegin(), diag::ext_typecheck_cast_to_union
)
2957 << SrcExpr
.get()->getSourceRange();
2961 Self
.Diag(OpRange
.getBegin(), diag::err_typecheck_cast_to_union_no_type
)
2962 << SrcType
<< SrcExpr
.get()->getSourceRange();
2963 SrcExpr
= ExprError();
2968 // OpenCL v2.0 s6.13.10 - Allow casts from '0' to event_t type.
2969 if (Self
.getLangOpts().OpenCL
&& DestType
->isEventT()) {
2970 Expr::EvalResult Result
;
2971 if (SrcExpr
.get()->EvaluateAsInt(Result
, Self
.Context
)) {
2972 llvm::APSInt CastInt
= Result
.Val
.getInt();
2974 Kind
= CK_ZeroToOCLOpaqueType
;
2977 Self
.Diag(OpRange
.getBegin(),
2978 diag::err_opencl_cast_non_zero_to_event_t
)
2979 << toString(CastInt
, 10) << SrcExpr
.get()->getSourceRange();
2980 SrcExpr
= ExprError();
2985 // Reject any other conversions to non-scalar types.
2986 Self
.Diag(OpRange
.getBegin(), diag::err_typecheck_cond_expect_scalar
)
2987 << DestType
<< SrcExpr
.get()->getSourceRange();
2988 SrcExpr
= ExprError();
2992 // The type we're casting to is known to be a scalar, a vector, or a matrix.
2994 // Require the operand to be a scalar, a vector, or a matrix.
2995 if (!SrcType
->isScalarType() && !SrcType
->isVectorType() &&
2996 !SrcType
->isMatrixType()) {
2997 Self
.Diag(SrcExpr
.get()->getExprLoc(),
2998 diag::err_typecheck_expect_scalar_operand
)
2999 << SrcType
<< SrcExpr
.get()->getSourceRange();
3000 SrcExpr
= ExprError();
3005 // The type nullptr_t shall not be converted to any type other than void,
3006 // bool, or a pointer type. No type other than nullptr_t shall be converted
3008 if (SrcType
->isNullPtrType()) {
3009 // FIXME: 6.3.2.4p2 says that nullptr_t can be converted to itself, but
3010 // 6.5.4p4 is a constraint check and nullptr_t is not void, bool, or a
3011 // pointer type. We're not going to diagnose that as a constraint violation.
3012 if (!DestType
->isVoidType() && !DestType
->isBooleanType() &&
3013 !DestType
->isPointerType() && !DestType
->isNullPtrType()) {
3014 Self
.Diag(SrcExpr
.get()->getExprLoc(), diag::err_nullptr_cast
)
3015 << /*nullptr to type*/ 0 << DestType
;
3016 SrcExpr
= ExprError();
3019 if (!DestType
->isNullPtrType()) {
3020 // Implicitly cast from the null pointer type to the type of the
3022 CastKind CK
= DestType
->isPointerType() ? CK_NullToPointer
: CK_BitCast
;
3023 SrcExpr
= ImplicitCastExpr::Create(Self
.Context
, DestType
, CK
,
3024 SrcExpr
.get(), nullptr, VK_PRValue
,
3025 Self
.CurFPFeatureOverrides());
3028 if (DestType
->isNullPtrType() && !SrcType
->isNullPtrType()) {
3029 Self
.Diag(SrcExpr
.get()->getExprLoc(), diag::err_nullptr_cast
)
3030 << /*type to nullptr*/ 1 << SrcType
;
3031 SrcExpr
= ExprError();
3035 if (DestType
->isExtVectorType()) {
3036 SrcExpr
= Self
.CheckExtVectorCast(OpRange
, DestType
, SrcExpr
.get(), Kind
);
3040 if (DestType
->getAs
<MatrixType
>() || SrcType
->getAs
<MatrixType
>()) {
3041 if (Self
.CheckMatrixCast(OpRange
, DestType
, SrcType
, Kind
))
3042 SrcExpr
= ExprError();
3046 if (const VectorType
*DestVecTy
= DestType
->getAs
<VectorType
>()) {
3047 if (Self
.CheckAltivecInitFromScalar(OpRange
, DestType
, SrcType
)) {
3048 SrcExpr
= ExprError();
3051 if (Self
.ShouldSplatAltivecScalarInCast(DestVecTy
) &&
3052 (SrcType
->isIntegerType() || SrcType
->isFloatingType())) {
3053 Kind
= CK_VectorSplat
;
3054 SrcExpr
= Self
.prepareVectorSplat(DestType
, SrcExpr
.get());
3055 } else if (Self
.CheckVectorCast(OpRange
, DestType
, SrcType
, Kind
)) {
3056 SrcExpr
= ExprError();
3061 if (SrcType
->isVectorType()) {
3062 if (Self
.CheckVectorCast(OpRange
, SrcType
, DestType
, Kind
))
3063 SrcExpr
= ExprError();
3067 // The source and target types are both scalars, i.e.
3068 // - arithmetic types (fundamental, enum, and complex)
3069 // - all kinds of pointers
3070 // Note that member pointers were filtered out with C++, above.
3072 if (isa
<ObjCSelectorExpr
>(SrcExpr
.get())) {
3073 Self
.Diag(SrcExpr
.get()->getExprLoc(), diag::err_cast_selector_expr
);
3074 SrcExpr
= ExprError();
3078 // Can't cast to or from bfloat
3079 if (DestType
->isBFloat16Type() && !SrcType
->isBFloat16Type()) {
3080 Self
.Diag(SrcExpr
.get()->getExprLoc(), diag::err_cast_to_bfloat16
)
3081 << SrcExpr
.get()->getSourceRange();
3082 SrcExpr
= ExprError();
3085 if (SrcType
->isBFloat16Type() && !DestType
->isBFloat16Type()) {
3086 Self
.Diag(SrcExpr
.get()->getExprLoc(), diag::err_cast_from_bfloat16
)
3087 << SrcExpr
.get()->getSourceRange();
3088 SrcExpr
= ExprError();
3092 // If either type is a pointer, the other type has to be either an
3093 // integer or a pointer.
3094 if (!DestType
->isArithmeticType()) {
3095 if (!SrcType
->isIntegralType(Self
.Context
) && SrcType
->isArithmeticType()) {
3096 Self
.Diag(SrcExpr
.get()->getExprLoc(),
3097 diag::err_cast_pointer_from_non_pointer_int
)
3098 << SrcType
<< SrcExpr
.get()->getSourceRange();
3099 SrcExpr
= ExprError();
3102 checkIntToPointerCast(/* CStyle */ true, OpRange
, SrcExpr
.get(), DestType
,
3104 } else if (!SrcType
->isArithmeticType()) {
3105 if (!DestType
->isIntegralType(Self
.Context
) &&
3106 DestType
->isArithmeticType()) {
3107 Self
.Diag(SrcExpr
.get()->getBeginLoc(),
3108 diag::err_cast_pointer_to_non_pointer_int
)
3109 << DestType
<< SrcExpr
.get()->getSourceRange();
3110 SrcExpr
= ExprError();
3114 if ((Self
.Context
.getTypeSize(SrcType
) >
3115 Self
.Context
.getTypeSize(DestType
)) &&
3116 !DestType
->isBooleanType()) {
3117 // C 6.3.2.3p6: Any pointer type may be converted to an integer type.
3118 // Except as previously specified, the result is implementation-defined.
3119 // If the result cannot be represented in the integer type, the behavior
3120 // is undefined. The result need not be in the range of values of any
3123 if (SrcType
->isVoidPointerType())
3124 Diag
= DestType
->isEnumeralType() ? diag::warn_void_pointer_to_enum_cast
3125 : diag::warn_void_pointer_to_int_cast
;
3126 else if (DestType
->isEnumeralType())
3127 Diag
= diag::warn_pointer_to_enum_cast
;
3129 Diag
= diag::warn_pointer_to_int_cast
;
3130 Self
.Diag(OpRange
.getBegin(), Diag
) << SrcType
<< DestType
<< OpRange
;
3134 if (Self
.getLangOpts().OpenCL
&& !Self
.getOpenCLOptions().isAvailableOption(
3135 "cl_khr_fp16", Self
.getLangOpts())) {
3136 if (DestType
->isHalfType()) {
3137 Self
.Diag(SrcExpr
.get()->getBeginLoc(), diag::err_opencl_cast_to_half
)
3138 << DestType
<< SrcExpr
.get()->getSourceRange();
3139 SrcExpr
= ExprError();
3144 // ARC imposes extra restrictions on casts.
3145 if (Self
.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) {
3146 checkObjCConversion(Sema::CCK_CStyleCast
);
3147 if (SrcExpr
.isInvalid())
3150 const PointerType
*CastPtr
= DestType
->getAs
<PointerType
>();
3151 if (Self
.getLangOpts().ObjCAutoRefCount
&& CastPtr
) {
3152 if (const PointerType
*ExprPtr
= SrcType
->getAs
<PointerType
>()) {
3153 Qualifiers CastQuals
= CastPtr
->getPointeeType().getQualifiers();
3154 Qualifiers ExprQuals
= ExprPtr
->getPointeeType().getQualifiers();
3155 if (CastPtr
->getPointeeType()->isObjCLifetimeType() &&
3156 ExprPtr
->getPointeeType()->isObjCLifetimeType() &&
3157 !CastQuals
.compatiblyIncludesObjCLifetime(ExprQuals
)) {
3158 Self
.Diag(SrcExpr
.get()->getBeginLoc(),
3159 diag::err_typecheck_incompatible_ownership
)
3160 << SrcType
<< DestType
<< Sema::AA_Casting
3161 << SrcExpr
.get()->getSourceRange();
3166 else if (!Self
.CheckObjCARCUnavailableWeakConversion(DestType
, SrcType
)) {
3167 Self
.Diag(SrcExpr
.get()->getBeginLoc(),
3168 diag::err_arc_convesion_of_weak_unavailable
)
3169 << 1 << SrcType
<< DestType
<< SrcExpr
.get()->getSourceRange();
3170 SrcExpr
= ExprError();
3175 if (unsigned DiagID
= checkCastFunctionType(Self
, SrcExpr
, DestType
))
3176 Self
.Diag(OpRange
.getBegin(), DiagID
) << SrcType
<< DestType
<< OpRange
;
3178 if (isa
<PointerType
>(SrcType
) && isa
<PointerType
>(DestType
)) {
3179 QualType SrcTy
= cast
<PointerType
>(SrcType
)->getPointeeType();
3180 QualType DestTy
= cast
<PointerType
>(DestType
)->getPointeeType();
3182 const RecordDecl
*SrcRD
= SrcTy
->getAsRecordDecl();
3183 const RecordDecl
*DestRD
= DestTy
->getAsRecordDecl();
3185 if (SrcRD
&& DestRD
&& SrcRD
->hasAttr
<RandomizeLayoutAttr
>() &&
3187 // The struct we are casting the pointer from was randomized.
3188 Self
.Diag(OpRange
.getBegin(), diag::err_cast_from_randomized_struct
)
3189 << SrcType
<< DestType
;
3190 SrcExpr
= ExprError();
3195 DiagnoseCastOfObjCSEL(Self
, SrcExpr
, DestType
);
3196 DiagnoseCallingConvCast(Self
, SrcExpr
, DestType
, OpRange
);
3197 DiagnoseBadFunctionCast(Self
, SrcExpr
, DestType
);
3198 Kind
= Self
.PrepareScalarCast(SrcExpr
, DestType
);
3199 if (SrcExpr
.isInvalid())
3202 if (Kind
== CK_BitCast
)
3206 void CastOperation::CheckBuiltinBitCast() {
3207 QualType SrcType
= SrcExpr
.get()->getType();
3209 if (Self
.RequireCompleteType(OpRange
.getBegin(), DestType
,
3210 diag::err_typecheck_cast_to_incomplete
) ||
3211 Self
.RequireCompleteType(OpRange
.getBegin(), SrcType
,
3212 diag::err_incomplete_type
)) {
3213 SrcExpr
= ExprError();
3217 if (SrcExpr
.get()->isPRValue())
3218 SrcExpr
= Self
.CreateMaterializeTemporaryExpr(SrcType
, SrcExpr
.get(),
3219 /*IsLValueReference=*/false);
3221 CharUnits DestSize
= Self
.Context
.getTypeSizeInChars(DestType
);
3222 CharUnits SourceSize
= Self
.Context
.getTypeSizeInChars(SrcType
);
3223 if (DestSize
!= SourceSize
) {
3224 Self
.Diag(OpRange
.getBegin(), diag::err_bit_cast_type_size_mismatch
)
3225 << (int)SourceSize
.getQuantity() << (int)DestSize
.getQuantity();
3226 SrcExpr
= ExprError();
3230 if (!DestType
.isTriviallyCopyableType(Self
.Context
)) {
3231 Self
.Diag(OpRange
.getBegin(), diag::err_bit_cast_non_trivially_copyable
)
3233 SrcExpr
= ExprError();
3237 if (!SrcType
.isTriviallyCopyableType(Self
.Context
)) {
3238 Self
.Diag(OpRange
.getBegin(), diag::err_bit_cast_non_trivially_copyable
)
3240 SrcExpr
= ExprError();
3244 Kind
= CK_LValueToRValueBitCast
;
3247 /// DiagnoseCastQual - Warn whenever casts discards a qualifiers, be it either
3248 /// const, volatile or both.
3249 static void DiagnoseCastQual(Sema
&Self
, const ExprResult
&SrcExpr
,
3250 QualType DestType
) {
3251 if (SrcExpr
.isInvalid())
3254 QualType SrcType
= SrcExpr
.get()->getType();
3255 if (!((SrcType
->isAnyPointerType() && DestType
->isAnyPointerType()) ||
3256 DestType
->isLValueReferenceType()))
3259 QualType TheOffendingSrcType
, TheOffendingDestType
;
3260 Qualifiers CastAwayQualifiers
;
3261 if (CastsAwayConstness(Self
, SrcType
, DestType
, true, false,
3262 &TheOffendingSrcType
, &TheOffendingDestType
,
3263 &CastAwayQualifiers
) !=
3264 CastAwayConstnessKind::CACK_Similar
)
3267 // FIXME: 'restrict' is not properly handled here.
3268 int qualifiers
= -1;
3269 if (CastAwayQualifiers
.hasConst() && CastAwayQualifiers
.hasVolatile()) {
3271 } else if (CastAwayQualifiers
.hasConst()) {
3273 } else if (CastAwayQualifiers
.hasVolatile()) {
3276 // This is a variant of int **x; const int **y = (const int **)x;
3277 if (qualifiers
== -1)
3278 Self
.Diag(SrcExpr
.get()->getBeginLoc(), diag::warn_cast_qual2
)
3279 << SrcType
<< DestType
;
3281 Self
.Diag(SrcExpr
.get()->getBeginLoc(), diag::warn_cast_qual
)
3282 << TheOffendingSrcType
<< TheOffendingDestType
<< qualifiers
;
3285 ExprResult
Sema::BuildCStyleCastExpr(SourceLocation LPLoc
,
3286 TypeSourceInfo
*CastTypeInfo
,
3287 SourceLocation RPLoc
,
3289 CastOperation
Op(*this, CastTypeInfo
->getType(), CastExpr
);
3290 Op
.DestRange
= CastTypeInfo
->getTypeLoc().getSourceRange();
3291 Op
.OpRange
= SourceRange(LPLoc
, CastExpr
->getEndLoc());
3293 if (getLangOpts().CPlusPlus
) {
3294 Op
.CheckCXXCStyleCast(/*FunctionalCast=*/ false,
3295 isa
<InitListExpr
>(CastExpr
));
3297 Op
.CheckCStyleCast();
3300 if (Op
.SrcExpr
.isInvalid())
3304 DiagnoseCastQual(Op
.Self
, Op
.SrcExpr
, Op
.DestType
);
3306 return Op
.complete(CStyleCastExpr::Create(
3307 Context
, Op
.ResultType
, Op
.ValueKind
, Op
.Kind
, Op
.SrcExpr
.get(),
3308 &Op
.BasePath
, CurFPFeatureOverrides(), CastTypeInfo
, LPLoc
, RPLoc
));
3311 ExprResult
Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo
*CastTypeInfo
,
3313 SourceLocation LPLoc
,
3315 SourceLocation RPLoc
) {
3316 assert(LPLoc
.isValid() && "List-initialization shouldn't get here.");
3317 CastOperation
Op(*this, Type
, CastExpr
);
3318 Op
.DestRange
= CastTypeInfo
->getTypeLoc().getSourceRange();
3319 Op
.OpRange
= SourceRange(Op
.DestRange
.getBegin(), CastExpr
->getEndLoc());
3321 Op
.CheckCXXCStyleCast(/*FunctionalCast=*/true, /*ListInit=*/false);
3322 if (Op
.SrcExpr
.isInvalid())
3325 auto *SubExpr
= Op
.SrcExpr
.get();
3326 if (auto *BindExpr
= dyn_cast
<CXXBindTemporaryExpr
>(SubExpr
))
3327 SubExpr
= BindExpr
->getSubExpr();
3328 if (auto *ConstructExpr
= dyn_cast
<CXXConstructExpr
>(SubExpr
))
3329 ConstructExpr
->setParenOrBraceRange(SourceRange(LPLoc
, RPLoc
));
3331 return Op
.complete(CXXFunctionalCastExpr::Create(
3332 Context
, Op
.ResultType
, Op
.ValueKind
, CastTypeInfo
, Op
.Kind
,
3333 Op
.SrcExpr
.get(), &Op
.BasePath
, CurFPFeatureOverrides(), LPLoc
, RPLoc
));