1//===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
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)'
13//
14//===----------------------------------------------------------------------===//
15
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/SemaHLSL.h"
27#include "clang/Sema/SemaObjC.h"
28#include "clang/Sema/SemaRISCV.h"
29#include "llvm/ADT/SmallVector.h"
30#include "llvm/ADT/StringExtras.h"
31#include <set>
32using namespace clang;
33
34
35
36enum TryCastResult {
37 TC_NotApplicable, ///< The cast method is not applicable.
38 TC_Success, ///< The cast method is appropriate and successful.
39 TC_Extension, ///< The cast method is appropriate and accepted as a
40 ///< language extension.
41 TC_Failed ///< The cast method is appropriate, but failed. A
42 ///< diagnostic has been emitted.
43};
44
45static bool isValidCast(TryCastResult TCR) {
46 return TCR == TC_Success || TCR == TC_Extension;
47}
48
49enum CastType {
50 CT_Const, ///< const_cast
51 CT_Static, ///< static_cast
52 CT_Reinterpret, ///< reinterpret_cast
53 CT_Dynamic, ///< dynamic_cast
54 CT_CStyle, ///< (Type)expr
55 CT_Functional, ///< Type(expr)
56 CT_Addrspace ///< addrspace_cast
57};
58
59namespace {
60 struct CastOperation {
61 CastOperation(Sema &S, QualType destType, ExprResult src)
62 : Self(S), SrcExpr(src), DestType(destType),
63 ResultType(destType.getNonLValueExprType(Context: S.Context)),
64 ValueKind(Expr::getValueKindForType(T: destType)),
65 Kind(CK_Dependent), IsARCUnbridgedCast(false) {
66
67 // C++ [expr.type]/8.2.2:
68 // If a pr-value initially has the type cv-T, where T is a
69 // cv-unqualified non-class, non-array type, the type of the
70 // expression is adjusted to T prior to any further analysis.
71 // C23 6.5.4p6:
72 // Preceding an expression by a parenthesized type name converts the
73 // value of the expression to the unqualified, non-atomic version of
74 // the named type.
75 // Don't drop __ptrauth qualifiers. We want to treat casting to a
76 // __ptrauth-qualified type as an error instead of implicitly ignoring
77 // the qualifier.
78 if (!S.Context.getLangOpts().ObjC && !DestType->isRecordType() &&
79 !DestType->isArrayType() && !DestType.getPointerAuth()) {
80 DestType = DestType.getAtomicUnqualifiedType();
81 }
82
83 if (const BuiltinType *placeholder =
84 src.get()->getType()->getAsPlaceholderType()) {
85 PlaceholderKind = placeholder->getKind();
86 } else {
87 PlaceholderKind = (BuiltinType::Kind) 0;
88 }
89 }
90
91 Sema &Self;
92 ExprResult SrcExpr;
93 QualType DestType;
94 QualType ResultType;
95 ExprValueKind ValueKind;
96 CastKind Kind;
97 BuiltinType::Kind PlaceholderKind;
98 CXXCastPath BasePath;
99 bool IsARCUnbridgedCast;
100
101 struct OpRangeType {
102 SourceLocation Locations[3];
103
104 OpRangeType(SourceLocation Begin, SourceLocation LParen,
105 SourceLocation RParen)
106 : Locations{Begin, LParen, RParen} {}
107
108 OpRangeType() = default;
109
110 SourceLocation getBegin() const { return Locations[0]; }
111
112 SourceLocation getLParenLoc() const { return Locations[1]; }
113
114 SourceLocation getRParenLoc() const { return Locations[2]; }
115
116 friend const StreamingDiagnostic &
117 operator<<(const StreamingDiagnostic &DB, OpRangeType Op) {
118 return DB << SourceRange(Op);
119 }
120
121 SourceRange getParenRange() const {
122 return SourceRange(getLParenLoc(), getRParenLoc());
123 }
124
125 operator SourceRange() const {
126 return SourceRange(getBegin(), getRParenLoc());
127 }
128 };
129
130 OpRangeType OpRange;
131 SourceRange DestRange;
132
133 // Top-level semantics-checking routines.
134 void CheckConstCast();
135 void CheckReinterpretCast();
136 void CheckStaticCast();
137 void CheckDynamicCast();
138 void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
139 bool CheckHLSLCStyleCast(CheckedConversionKind CCK);
140 void CheckCStyleCast();
141 void CheckBuiltinBitCast();
142 void CheckAddrspaceCast();
143
144 void updatePartOfExplicitCastFlags(CastExpr *CE) {
145 // Walk down from the CE to the OrigSrcExpr, and mark all immediate
146 // ImplicitCastExpr's as being part of ExplicitCastExpr. The original CE
147 // (which is a ExplicitCastExpr), and the OrigSrcExpr are not touched.
148 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Val: CE->getSubExpr()); CE = ICE)
149 ICE->setIsPartOfExplicitCast(true);
150 }
151
152 /// Complete an apparently-successful cast operation that yields
153 /// the given expression.
154 ExprResult complete(CastExpr *castExpr) {
155 // If this is an unbridged cast, wrap the result in an implicit
156 // cast that yields the unbridged-cast placeholder type.
157 if (IsARCUnbridgedCast) {
158 castExpr = ImplicitCastExpr::Create(
159 Context: Self.Context, T: Self.Context.ARCUnbridgedCastTy, Kind: CK_Dependent,
160 Operand: castExpr, BasePath: nullptr, Cat: castExpr->getValueKind(),
161 FPO: Self.CurFPFeatureOverrides());
162 }
163 updatePartOfExplicitCastFlags(CE: castExpr);
164 return castExpr;
165 }
166
167 // Internal convenience methods.
168
169 /// Try to handle the given placeholder expression kind. Return
170 /// true if the source expression has the appropriate placeholder
171 /// kind. A placeholder can only be claimed once.
172 bool claimPlaceholder(BuiltinType::Kind K) {
173 if (PlaceholderKind != K) return false;
174
175 PlaceholderKind = (BuiltinType::Kind) 0;
176 return true;
177 }
178
179 bool isPlaceholder() const {
180 return PlaceholderKind != 0;
181 }
182 bool isPlaceholder(BuiltinType::Kind K) const {
183 return PlaceholderKind == K;
184 }
185
186 // Language specific cast restrictions for address spaces.
187 void checkAddressSpaceCast(QualType SrcType, QualType DestType);
188
189 void checkCastAlign() {
190 Self.CheckCastAlign(Op: SrcExpr.get(), T: DestType, TRange: OpRange);
191 }
192
193 void checkObjCConversion(CheckedConversionKind CCK,
194 bool IsReinterpretCast = false) {
195 assert(Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers());
196
197 Expr *src = SrcExpr.get();
198 if (Self.ObjC().CheckObjCConversion(
199 castRange: OpRange, castType: DestType, op&: src, CCK, Diagnose: true, DiagnoseCFAudited: false, Opc: BO_PtrMemD,
200 IsReinterpretCast) == SemaObjC::ACR_unbridged)
201 IsARCUnbridgedCast = true;
202 SrcExpr = src;
203 }
204
205 void checkQualifiedDestType() {
206 // Destination type may not be qualified with __ptrauth.
207 if (DestType.getPointerAuth()) {
208 Self.Diag(Loc: DestRange.getBegin(), DiagID: diag::err_ptrauth_qualifier_cast)
209 << DestType << DestRange;
210 }
211 }
212
213 /// Check for and handle non-overload placeholder expressions.
214 void checkNonOverloadPlaceholders() {
215 if (!isPlaceholder() || isPlaceholder(K: BuiltinType::Overload))
216 return;
217
218 SrcExpr = Self.CheckPlaceholderExpr(E: SrcExpr.get());
219 if (SrcExpr.isInvalid())
220 return;
221 PlaceholderKind = (BuiltinType::Kind) 0;
222 }
223 };
224
225 void CheckNoDeref(Sema &S, const QualType FromType, const QualType ToType,
226 SourceLocation OpLoc) {
227 if (const auto *PtrType = dyn_cast<PointerType>(Val: FromType)) {
228 if (PtrType->getPointeeType()->hasAttr(AK: attr::NoDeref)) {
229 if (const auto *DestType = dyn_cast<PointerType>(Val: ToType)) {
230 if (!DestType->getPointeeType()->hasAttr(AK: attr::NoDeref)) {
231 S.Diag(Loc: OpLoc, DiagID: diag::warn_noderef_to_dereferenceable_pointer);
232 }
233 }
234 }
235 }
236 }
237
238 struct CheckNoDerefRAII {
239 CheckNoDerefRAII(CastOperation &Op) : Op(Op) {}
240 ~CheckNoDerefRAII() {
241 if (!Op.SrcExpr.isInvalid())
242 CheckNoDeref(S&: Op.Self, FromType: Op.SrcExpr.get()->getType(), ToType: Op.ResultType,
243 OpLoc: Op.OpRange.getBegin());
244 }
245
246 CastOperation &Op;
247 };
248}
249
250static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
251 QualType DestType);
252
253// The Try functions attempt a specific way of casting. If they succeed, they
254// return TC_Success. If their way of casting is not appropriate for the given
255// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
256// to emit if no other way succeeds. If their way of casting is appropriate but
257// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
258// they emit a specialized diagnostic.
259// All diagnostics returned by these functions must expect the same three
260// arguments:
261// %0: Cast Type (a value from the CastType enumeration)
262// %1: Source Type
263// %2: Destination Type
264static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
265 QualType DestType, bool CStyle,
266 CastKind &Kind,
267 CXXCastPath &BasePath,
268 unsigned &msg);
269static TryCastResult
270TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
271 bool CStyle, CastOperation::OpRangeType OpRange,
272 unsigned &msg, CastKind &Kind,
273 CXXCastPath &BasePath);
274static TryCastResult
275TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
276 bool CStyle, CastOperation::OpRangeType OpRange,
277 unsigned &msg, CastKind &Kind, CXXCastPath &BasePath);
278static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
279 CanQualType DestType, bool CStyle,
280 CastOperation::OpRangeType OpRange,
281 QualType OrigSrcType,
282 QualType OrigDestType, unsigned &msg,
283 CastKind &Kind, CXXCastPath &BasePath);
284static TryCastResult
285TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
286 QualType DestType, bool CStyle,
287 CastOperation::OpRangeType OpRange, unsigned &msg,
288 CastKind &Kind, CXXCastPath &BasePath);
289
290static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
291 QualType DestType,
292 CheckedConversionKind CCK,
293 CastOperation::OpRangeType OpRange,
294 unsigned &msg, CastKind &Kind,
295 bool ListInitialization);
296static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
297 QualType DestType, CheckedConversionKind CCK,
298 CastOperation::OpRangeType OpRange,
299 unsigned &msg, CastKind &Kind,
300 CXXCastPath &BasePath,
301 bool ListInitialization);
302static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
303 QualType DestType, bool CStyle,
304 unsigned &msg);
305static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
306 QualType DestType, bool CStyle,
307 CastOperation::OpRangeType OpRange,
308 unsigned &msg, CastKind &Kind);
309static TryCastResult TryAddressSpaceCast(Sema &Self, ExprResult &SrcExpr,
310 QualType DestType, bool CStyle,
311 unsigned &msg, CastKind &Kind);
312
313ExprResult
314Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
315 SourceLocation LAngleBracketLoc, Declarator &D,
316 SourceLocation RAngleBracketLoc,
317 SourceLocation LParenLoc, Expr *E,
318 SourceLocation RParenLoc) {
319
320 assert(!D.isInvalidType());
321
322 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, FromTy: E->getType());
323 if (D.isInvalidType())
324 return ExprError();
325
326 if (getLangOpts().CPlusPlus) {
327 // Check that there are no default arguments (C++ only).
328 CheckExtraCXXDefaultArguments(D);
329 }
330
331 return BuildCXXNamedCast(OpLoc, Kind, Ty: TInfo, E,
332 AngleBrackets: SourceRange(LAngleBracketLoc, RAngleBracketLoc),
333 Parens: SourceRange(LParenLoc, RParenLoc));
334}
335
336ExprResult
337Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
338 TypeSourceInfo *DestTInfo, Expr *E,
339 SourceRange AngleBrackets, SourceRange Parens) {
340 ExprResult Ex = E;
341 QualType DestType = DestTInfo->getType();
342
343 // If the type is dependent, we won't do the semantic analysis now.
344 bool TypeDependent =
345 DestType->isDependentType() || Ex.get()->isTypeDependent();
346
347 CastOperation Op(*this, DestType, E);
348 Op.OpRange =
349 CastOperation::OpRangeType(OpLoc, Parens.getBegin(), Parens.getEnd());
350 Op.DestRange = AngleBrackets;
351
352 Op.checkQualifiedDestType();
353
354 switch (Kind) {
355 default: llvm_unreachable("Unknown C++ cast!");
356
357 case tok::kw_addrspace_cast:
358 if (!TypeDependent) {
359 Op.CheckAddrspaceCast();
360 if (Op.SrcExpr.isInvalid())
361 return ExprError();
362 }
363 return Op.complete(castExpr: CXXAddrspaceCastExpr::Create(
364 Context, T: Op.ResultType, VK: Op.ValueKind, Kind: Op.Kind, Op: Op.SrcExpr.get(),
365 WrittenTy: DestTInfo, L: OpLoc, RParenLoc: Parens.getEnd(), AngleBrackets));
366
367 case tok::kw_const_cast:
368 if (!TypeDependent) {
369 Op.CheckConstCast();
370 if (Op.SrcExpr.isInvalid())
371 return ExprError();
372 DiscardMisalignedMemberAddress(T: DestType.getTypePtr(), E);
373 }
374 return Op.complete(castExpr: CXXConstCastExpr::Create(Context, T: Op.ResultType,
375 VK: Op.ValueKind, Op: Op.SrcExpr.get(), WrittenTy: DestTInfo,
376 L: OpLoc, RParenLoc: Parens.getEnd(),
377 AngleBrackets));
378
379 case tok::kw_dynamic_cast: {
380 // dynamic_cast is not supported in C++ for OpenCL.
381 if (getLangOpts().OpenCLCPlusPlus) {
382 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_openclcxx_not_supported)
383 << "dynamic_cast");
384 }
385
386 if (!TypeDependent) {
387 Op.CheckDynamicCast();
388 if (Op.SrcExpr.isInvalid())
389 return ExprError();
390 }
391 return Op.complete(castExpr: CXXDynamicCastExpr::Create(Context, T: Op.ResultType,
392 VK: Op.ValueKind, Kind: Op.Kind, Op: Op.SrcExpr.get(),
393 Path: &Op.BasePath, Written: DestTInfo,
394 L: OpLoc, RParenLoc: Parens.getEnd(),
395 AngleBrackets));
396 }
397 case tok::kw_reinterpret_cast: {
398 if (!TypeDependent) {
399 Op.CheckReinterpretCast();
400 if (Op.SrcExpr.isInvalid())
401 return ExprError();
402 DiscardMisalignedMemberAddress(T: DestType.getTypePtr(), E);
403 }
404 return Op.complete(castExpr: CXXReinterpretCastExpr::Create(Context, T: Op.ResultType,
405 VK: Op.ValueKind, Kind: Op.Kind, Op: Op.SrcExpr.get(),
406 Path: nullptr, WrittenTy: DestTInfo, L: OpLoc,
407 RParenLoc: Parens.getEnd(),
408 AngleBrackets));
409 }
410 case tok::kw_static_cast: {
411 if (!TypeDependent) {
412 Op.CheckStaticCast();
413 if (Op.SrcExpr.isInvalid())
414 return ExprError();
415 DiscardMisalignedMemberAddress(T: DestType.getTypePtr(), E);
416 }
417
418 return Op.complete(castExpr: CXXStaticCastExpr::Create(
419 Context, T: Op.ResultType, VK: Op.ValueKind, K: Op.Kind, Op: Op.SrcExpr.get(),
420 Path: &Op.BasePath, Written: DestTInfo, FPO: CurFPFeatureOverrides(), L: OpLoc,
421 RParenLoc: Parens.getEnd(), AngleBrackets));
422 }
423 }
424}
425
426ExprResult Sema::ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &D,
427 ExprResult Operand,
428 SourceLocation RParenLoc) {
429 assert(!D.isInvalidType());
430
431 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, FromTy: Operand.get()->getType());
432 if (D.isInvalidType())
433 return ExprError();
434
435 return BuildBuiltinBitCastExpr(KWLoc, TSI: TInfo, Operand: Operand.get(), RParenLoc);
436}
437
438ExprResult Sema::BuildBuiltinBitCastExpr(SourceLocation KWLoc,
439 TypeSourceInfo *TSI, Expr *Operand,
440 SourceLocation RParenLoc) {
441 CastOperation Op(*this, TSI->getType(), Operand);
442 Op.OpRange = CastOperation::OpRangeType(KWLoc, KWLoc, RParenLoc);
443 TypeLoc TL = TSI->getTypeLoc();
444 Op.DestRange = SourceRange(TL.getBeginLoc(), TL.getEndLoc());
445
446 if (!Operand->isTypeDependent() && !TSI->getType()->isDependentType()) {
447 Op.CheckBuiltinBitCast();
448 if (Op.SrcExpr.isInvalid())
449 return ExprError();
450 }
451
452 BuiltinBitCastExpr *BCE =
453 new (Context) BuiltinBitCastExpr(Op.ResultType, Op.ValueKind, Op.Kind,
454 Op.SrcExpr.get(), TSI, KWLoc, RParenLoc);
455 return Op.complete(castExpr: BCE);
456}
457
458/// Try to diagnose a failed overloaded cast. Returns true if
459/// diagnostics were emitted.
460static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
461 CastOperation::OpRangeType range,
462 Expr *src, QualType destType,
463 bool listInitialization) {
464 switch (CT) {
465 // These cast kinds don't consider user-defined conversions.
466 case CT_Const:
467 case CT_Reinterpret:
468 case CT_Dynamic:
469 case CT_Addrspace:
470 return false;
471
472 // These do.
473 case CT_Static:
474 case CT_CStyle:
475 case CT_Functional:
476 break;
477 }
478
479 QualType srcType = src->getType();
480 if (!destType->isRecordType() && !srcType->isRecordType())
481 return false;
482
483 InitializedEntity entity = InitializedEntity::InitializeTemporary(Type: destType);
484 InitializationKind initKind =
485 (CT == CT_CStyle) ? InitializationKind::CreateCStyleCast(
486 StartLoc: range.getBegin(), TypeRange: range, InitList: listInitialization)
487 : (CT == CT_Functional)
488 ? InitializationKind::CreateFunctionalCast(
489 StartLoc: range.getBegin(), ParenRange: range.getParenRange(), InitList: listInitialization)
490 : InitializationKind::CreateCast(/*type range?*/ TypeRange: range);
491 InitializationSequence sequence(S, entity, initKind, src);
492
493 // It could happen that a constructor failed to be used because
494 // it requires a temporary of a broken type. Still, it will be found when
495 // looking for a match.
496 if (!sequence.Failed())
497 return false;
498
499 switch (sequence.getFailureKind()) {
500 default: return false;
501
502 case InitializationSequence::FK_ParenthesizedListInitFailed:
503 // In C++20, if the underlying destination type is a RecordType, Clang
504 // attempts to perform parentesized aggregate initialization if constructor
505 // overload fails:
506 //
507 // C++20 [expr.static.cast]p4:
508 // An expression E can be explicitly converted to a type T...if overload
509 // resolution for a direct-initialization...would find at least one viable
510 // function ([over.match.viable]), or if T is an aggregate type having a
511 // first element X and there is an implicit conversion sequence from E to
512 // the type of X.
513 //
514 // If that fails, then we'll generate the diagnostics from the failed
515 // previous constructor overload attempt. Array initialization, however, is
516 // not done after attempting constructor overloading, so we exit as there
517 // won't be a failed overload result.
518 if (destType->isArrayType())
519 return false;
520 break;
521 case InitializationSequence::FK_ConstructorOverloadFailed:
522 case InitializationSequence::FK_UserConversionOverloadFailed:
523 break;
524 }
525
526 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
527
528 unsigned msg = 0;
529 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
530
531 switch (sequence.getFailedOverloadResult()) {
532 case OR_Success: llvm_unreachable("successful failed overload");
533 case OR_No_Viable_Function:
534 if (candidates.empty())
535 msg = diag::err_ovl_no_conversion_in_cast;
536 else
537 msg = diag::err_ovl_no_viable_conversion_in_cast;
538 howManyCandidates = OCD_AllCandidates;
539 break;
540
541 case OR_Ambiguous:
542 msg = diag::err_ovl_ambiguous_conversion_in_cast;
543 howManyCandidates = OCD_AmbiguousCandidates;
544 break;
545
546 case OR_Deleted: {
547 OverloadCandidateSet::iterator Best;
548 [[maybe_unused]] OverloadingResult Res =
549 candidates.BestViableFunction(S, Loc: range.getBegin(), Best);
550 assert(Res == OR_Deleted && "Inconsistent overload resolution");
551
552 StringLiteral *Msg = Best->Function->getDeletedMessage();
553 candidates.NoteCandidates(
554 PA: PartialDiagnosticAt(range.getBegin(),
555 S.PDiag(DiagID: diag::err_ovl_deleted_conversion_in_cast)
556 << CT << srcType << destType << (Msg != nullptr)
557 << (Msg ? Msg->getString() : StringRef())
558 << range << src->getSourceRange()),
559 S, OCD: OCD_ViableCandidates, Args: src);
560 return true;
561 }
562 }
563
564 candidates.NoteCandidates(
565 PA: PartialDiagnosticAt(range.getBegin(),
566 S.PDiag(DiagID: msg) << CT << srcType << destType << range
567 << src->getSourceRange()),
568 S, OCD: howManyCandidates, Args: src);
569
570 return true;
571}
572
573/// Diagnose a failed cast.
574static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
575 CastOperation::OpRangeType opRange, Expr *src,
576 QualType destType, bool listInitialization) {
577 if (msg == diag::err_bad_cxx_cast_generic &&
578 tryDiagnoseOverloadedCast(S, CT: castType, range: opRange, src, destType,
579 listInitialization))
580 return;
581
582 S.Diag(Loc: opRange.getBegin(), DiagID: msg) << castType
583 << src->getType() << destType << opRange << src->getSourceRange();
584
585 // Detect if both types are (ptr to) class, and note any incompleteness.
586 int DifferentPtrness = 0;
587 QualType From = destType;
588 if (auto Ptr = From->getAs<PointerType>()) {
589 From = Ptr->getPointeeType();
590 DifferentPtrness++;
591 }
592 QualType To = src->getType();
593 if (auto Ptr = To->getAs<PointerType>()) {
594 To = Ptr->getPointeeType();
595 DifferentPtrness--;
596 }
597 if (!DifferentPtrness) {
598 auto RecFrom = From->getAs<RecordType>();
599 auto RecTo = To->getAs<RecordType>();
600 if (RecFrom && RecTo) {
601 auto DeclFrom = RecFrom->getAsCXXRecordDecl();
602 if (!DeclFrom->isCompleteDefinition())
603 S.Diag(Loc: DeclFrom->getLocation(), DiagID: diag::note_type_incomplete) << DeclFrom;
604 auto DeclTo = RecTo->getAsCXXRecordDecl();
605 if (!DeclTo->isCompleteDefinition())
606 S.Diag(Loc: DeclTo->getLocation(), DiagID: diag::note_type_incomplete) << DeclTo;
607 }
608 }
609}
610
611namespace {
612/// The kind of unwrapping we did when determining whether a conversion casts
613/// away constness.
614enum CastAwayConstnessKind {
615 /// The conversion does not cast away constness.
616 CACK_None = 0,
617 /// We unwrapped similar types.
618 CACK_Similar = 1,
619 /// We unwrapped dissimilar types with similar representations (eg, a pointer
620 /// versus an Objective-C object pointer).
621 CACK_SimilarKind = 2,
622 /// We unwrapped representationally-unrelated types, such as a pointer versus
623 /// a pointer-to-member.
624 CACK_Incoherent = 3,
625};
626}
627
628/// Unwrap one level of types for CastsAwayConstness.
629///
630/// Like Sema::UnwrapSimilarTypes, this removes one level of indirection from
631/// both types, provided that they're both pointer-like or array-like. Unlike
632/// the Sema function, doesn't care if the unwrapped pieces are related.
633///
634/// This function may remove additional levels as necessary for correctness:
635/// the resulting T1 is unwrapped sufficiently that it is never an array type,
636/// so that its qualifiers can be directly compared to those of T2 (which will
637/// have the combined set of qualifiers from all indermediate levels of T2),
638/// as (effectively) required by [expr.const.cast]p7 replacing T1's qualifiers
639/// with those from T2.
640static CastAwayConstnessKind
641unwrapCastAwayConstnessLevel(ASTContext &Context, QualType &T1, QualType &T2) {
642 enum { None, Ptr, MemPtr, BlockPtr, Array };
643 auto Classify = [](QualType T) {
644 if (T->isAnyPointerType()) return Ptr;
645 if (T->isMemberPointerType()) return MemPtr;
646 if (T->isBlockPointerType()) return BlockPtr;
647 // We somewhat-arbitrarily don't look through VLA types here. This is at
648 // least consistent with the behavior of UnwrapSimilarTypes.
649 if (T->isConstantArrayType() || T->isIncompleteArrayType()) return Array;
650 return None;
651 };
652
653 auto Unwrap = [&](QualType T) {
654 if (auto *AT = Context.getAsArrayType(T))
655 return AT->getElementType();
656 return T->getPointeeType();
657 };
658
659 CastAwayConstnessKind Kind;
660
661 if (T2->isReferenceType()) {
662 // Special case: if the destination type is a reference type, unwrap it as
663 // the first level. (The source will have been an lvalue expression in this
664 // case, so there is no corresponding "reference to" in T1 to remove.) This
665 // simulates removing a "pointer to" from both sides.
666 T2 = T2->getPointeeType();
667 Kind = CastAwayConstnessKind::CACK_Similar;
668 } else if (Context.UnwrapSimilarTypes(T1, T2)) {
669 Kind = CastAwayConstnessKind::CACK_Similar;
670 } else {
671 // Try unwrapping mismatching levels.
672 int T1Class = Classify(T1);
673 if (T1Class == None)
674 return CastAwayConstnessKind::CACK_None;
675
676 int T2Class = Classify(T2);
677 if (T2Class == None)
678 return CastAwayConstnessKind::CACK_None;
679
680 T1 = Unwrap(T1);
681 T2 = Unwrap(T2);
682 Kind = T1Class == T2Class ? CastAwayConstnessKind::CACK_SimilarKind
683 : CastAwayConstnessKind::CACK_Incoherent;
684 }
685
686 // We've unwrapped at least one level. If the resulting T1 is a (possibly
687 // multidimensional) array type, any qualifier on any matching layer of
688 // T2 is considered to correspond to T1. Decompose down to the element
689 // type of T1 so that we can compare properly.
690 while (true) {
691 Context.UnwrapSimilarArrayTypes(T1, T2);
692
693 if (Classify(T1) != Array)
694 break;
695
696 auto T2Class = Classify(T2);
697 if (T2Class == None)
698 break;
699
700 if (T2Class != Array)
701 Kind = CastAwayConstnessKind::CACK_Incoherent;
702 else if (Kind != CastAwayConstnessKind::CACK_Incoherent)
703 Kind = CastAwayConstnessKind::CACK_SimilarKind;
704
705 T1 = Unwrap(T1);
706 T2 = Unwrap(T2).withCVRQualifiers(CVR: T2.getCVRQualifiers());
707 }
708
709 return Kind;
710}
711
712/// Check if the pointer conversion from SrcType to DestType casts away
713/// constness as defined in C++ [expr.const.cast]. This is used by the cast
714/// checkers. Both arguments must denote pointer (possibly to member) types.
715///
716/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
717/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
718static CastAwayConstnessKind
719CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
720 bool CheckCVR, bool CheckObjCLifetime,
721 QualType *TheOffendingSrcType = nullptr,
722 QualType *TheOffendingDestType = nullptr,
723 Qualifiers *CastAwayQualifiers = nullptr) {
724 // If the only checking we care about is for Objective-C lifetime qualifiers,
725 // and we're not in ObjC mode, there's nothing to check.
726 if (!CheckCVR && CheckObjCLifetime && !Self.Context.getLangOpts().ObjC)
727 return CastAwayConstnessKind::CACK_None;
728
729 if (!DestType->isReferenceType()) {
730 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||
731 SrcType->isBlockPointerType()) &&
732 "Source type is not pointer or pointer to member.");
733 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||
734 DestType->isBlockPointerType()) &&
735 "Destination type is not pointer or pointer to member.");
736 }
737
738 QualType UnwrappedSrcType = Self.Context.getCanonicalType(T: SrcType),
739 UnwrappedDestType = Self.Context.getCanonicalType(T: DestType);
740
741 // Find the qualifiers. We only care about cvr-qualifiers for the
742 // purpose of this check, because other qualifiers (address spaces,
743 // Objective-C GC, etc.) are part of the type's identity.
744 QualType PrevUnwrappedSrcType = UnwrappedSrcType;
745 QualType PrevUnwrappedDestType = UnwrappedDestType;
746 auto WorstKind = CastAwayConstnessKind::CACK_Similar;
747 bool AllConstSoFar = true;
748 while (auto Kind = unwrapCastAwayConstnessLevel(
749 Context&: Self.Context, T1&: UnwrappedSrcType, T2&: UnwrappedDestType)) {
750 // Track the worst kind of unwrap we needed to do before we found a
751 // problem.
752 if (Kind > WorstKind)
753 WorstKind = Kind;
754
755 // Determine the relevant qualifiers at this level.
756 Qualifiers SrcQuals, DestQuals;
757 Self.Context.getUnqualifiedArrayType(T: UnwrappedSrcType, Quals&: SrcQuals);
758 Self.Context.getUnqualifiedArrayType(T: UnwrappedDestType, Quals&: DestQuals);
759
760 // We do not meaningfully track object const-ness of Objective-C object
761 // types. Remove const from the source type if either the source or
762 // the destination is an Objective-C object type.
763 if (UnwrappedSrcType->isObjCObjectType() ||
764 UnwrappedDestType->isObjCObjectType())
765 SrcQuals.removeConst();
766
767 if (CheckCVR) {
768 Qualifiers SrcCvrQuals =
769 Qualifiers::fromCVRMask(CVR: SrcQuals.getCVRQualifiers());
770 Qualifiers DestCvrQuals =
771 Qualifiers::fromCVRMask(CVR: DestQuals.getCVRQualifiers());
772
773 if (SrcCvrQuals != DestCvrQuals) {
774 if (CastAwayQualifiers)
775 *CastAwayQualifiers = SrcCvrQuals - DestCvrQuals;
776
777 // If we removed a cvr-qualifier, this is casting away 'constness'.
778 if (!DestCvrQuals.compatiblyIncludes(other: SrcCvrQuals,
779 Ctx: Self.getASTContext())) {
780 if (TheOffendingSrcType)
781 *TheOffendingSrcType = PrevUnwrappedSrcType;
782 if (TheOffendingDestType)
783 *TheOffendingDestType = PrevUnwrappedDestType;
784 return WorstKind;
785 }
786
787 // If any prior level was not 'const', this is also casting away
788 // 'constness'. We noted the outermost type missing a 'const' already.
789 if (!AllConstSoFar)
790 return WorstKind;
791 }
792 }
793
794 if (CheckObjCLifetime &&
795 !DestQuals.compatiblyIncludesObjCLifetime(other: SrcQuals))
796 return WorstKind;
797
798 // If we found our first non-const-qualified type, this may be the place
799 // where things start to go wrong.
800 if (AllConstSoFar && !DestQuals.hasConst()) {
801 AllConstSoFar = false;
802 if (TheOffendingSrcType)
803 *TheOffendingSrcType = PrevUnwrappedSrcType;
804 if (TheOffendingDestType)
805 *TheOffendingDestType = PrevUnwrappedDestType;
806 }
807
808 PrevUnwrappedSrcType = UnwrappedSrcType;
809 PrevUnwrappedDestType = UnwrappedDestType;
810 }
811
812 return CastAwayConstnessKind::CACK_None;
813}
814
815static TryCastResult getCastAwayConstnessCastKind(CastAwayConstnessKind CACK,
816 unsigned &DiagID) {
817 switch (CACK) {
818 case CastAwayConstnessKind::CACK_None:
819 llvm_unreachable("did not cast away constness");
820
821 case CastAwayConstnessKind::CACK_Similar:
822 // FIXME: Accept these as an extension too?
823 case CastAwayConstnessKind::CACK_SimilarKind:
824 DiagID = diag::err_bad_cxx_cast_qualifiers_away;
825 return TC_Failed;
826
827 case CastAwayConstnessKind::CACK_Incoherent:
828 DiagID = diag::ext_bad_cxx_cast_qualifiers_away_incoherent;
829 return TC_Extension;
830 }
831
832 llvm_unreachable("unexpected cast away constness kind");
833}
834
835/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
836/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
837/// checked downcasts in class hierarchies.
838void CastOperation::CheckDynamicCast() {
839 CheckNoDerefRAII NoderefCheck(*this);
840
841 if (ValueKind == VK_PRValue)
842 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(E: SrcExpr.get());
843 else if (isPlaceholder())
844 SrcExpr = Self.CheckPlaceholderExpr(E: SrcExpr.get());
845 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
846 return;
847
848 QualType OrigSrcType = SrcExpr.get()->getType();
849 QualType DestType = Self.Context.getCanonicalType(T: this->DestType);
850
851 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
852 // or "pointer to cv void".
853
854 QualType DestPointee;
855 const PointerType *DestPointer = DestType->getAs<PointerType>();
856 const ReferenceType *DestReference = nullptr;
857 if (DestPointer) {
858 DestPointee = DestPointer->getPointeeType();
859 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
860 DestPointee = DestReference->getPointeeType();
861 } else {
862 Self.Diag(Loc: OpRange.getBegin(), DiagID: diag::err_bad_dynamic_cast_not_ref_or_ptr)
863 << this->DestType << DestRange;
864 SrcExpr = ExprError();
865 return;
866 }
867
868 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
869 if (DestPointee->isVoidType()) {
870 assert(DestPointer && "Reference to void is not possible");
871 } else if (DestRecord) {
872 if (Self.RequireCompleteType(Loc: OpRange.getBegin(), T: DestPointee,
873 DiagID: diag::err_bad_cast_incomplete,
874 Args: DestRange)) {
875 SrcExpr = ExprError();
876 return;
877 }
878 } else {
879 Self.Diag(Loc: OpRange.getBegin(), DiagID: diag::err_bad_dynamic_cast_not_class)
880 << DestPointee.getUnqualifiedType() << DestRange;
881 SrcExpr = ExprError();
882 return;
883 }
884
885 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
886 // complete class type, [...]. If T is an lvalue reference type, v shall be
887 // an lvalue of a complete class type, [...]. If T is an rvalue reference
888 // type, v shall be an expression having a complete class type, [...]
889 QualType SrcType = Self.Context.getCanonicalType(T: OrigSrcType);
890 QualType SrcPointee;
891 if (DestPointer) {
892 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
893 SrcPointee = SrcPointer->getPointeeType();
894 } else {
895 Self.Diag(Loc: OpRange.getBegin(), DiagID: diag::err_bad_dynamic_cast_not_ptr)
896 << OrigSrcType << this->DestType << SrcExpr.get()->getSourceRange();
897 SrcExpr = ExprError();
898 return;
899 }
900 } else if (DestReference->isLValueReferenceType()) {
901 if (!SrcExpr.get()->isLValue()) {
902 Self.Diag(Loc: OpRange.getBegin(), DiagID: diag::err_bad_cxx_cast_rvalue)
903 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
904 }
905 SrcPointee = SrcType;
906 } else {
907 // If we're dynamic_casting from a prvalue to an rvalue reference, we need
908 // to materialize the prvalue before we bind the reference to it.
909 if (SrcExpr.get()->isPRValue())
910 SrcExpr = Self.CreateMaterializeTemporaryExpr(
911 T: SrcType, Temporary: SrcExpr.get(), /*IsLValueReference*/ BoundToLvalueReference: false);
912 SrcPointee = SrcType;
913 }
914
915 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
916 if (SrcRecord) {
917 if (Self.RequireCompleteType(Loc: OpRange.getBegin(), T: SrcPointee,
918 DiagID: diag::err_bad_cast_incomplete,
919 Args: SrcExpr.get())) {
920 SrcExpr = ExprError();
921 return;
922 }
923 } else {
924 Self.Diag(Loc: OpRange.getBegin(), DiagID: diag::err_bad_dynamic_cast_not_class)
925 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
926 SrcExpr = ExprError();
927 return;
928 }
929
930 assert((DestPointer || DestReference) &&
931 "Bad destination non-ptr/ref slipped through.");
932 assert((DestRecord || DestPointee->isVoidType()) &&
933 "Bad destination pointee slipped through.");
934 assert(SrcRecord && "Bad source pointee slipped through.");
935
936 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
937 if (!DestPointee.isAtLeastAsQualifiedAs(other: SrcPointee, Ctx: Self.getASTContext())) {
938 Self.Diag(Loc: OpRange.getBegin(), DiagID: diag::err_bad_cxx_cast_qualifiers_away)
939 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
940 SrcExpr = ExprError();
941 return;
942 }
943
944 // C++ 5.2.7p3: If the type of v is the same as the required result type,
945 // [except for cv].
946 if (DestRecord == SrcRecord) {
947 Kind = CK_NoOp;
948 return;
949 }
950
951 // C++ 5.2.7p5
952 // Upcasts are resolved statically.
953 if (DestRecord &&
954 Self.IsDerivedFrom(Loc: OpRange.getBegin(), Derived: SrcPointee, Base: DestPointee)) {
955 if (Self.CheckDerivedToBaseConversion(Derived: SrcPointee, Base: DestPointee,
956 Loc: OpRange.getBegin(), Range: OpRange,
957 BasePath: &BasePath)) {
958 SrcExpr = ExprError();
959 return;
960 }
961
962 Kind = CK_DerivedToBase;
963 return;
964 }
965
966 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
967 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
968 assert(SrcDecl && "Definition missing");
969 if (!cast<CXXRecordDecl>(Val: SrcDecl)->isPolymorphic()) {
970 Self.Diag(Loc: OpRange.getBegin(), DiagID: diag::err_bad_dynamic_cast_not_polymorphic)
971 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
972 SrcExpr = ExprError();
973 }
974
975 // dynamic_cast is not available with -fno-rtti.
976 // As an exception, dynamic_cast to void* is available because it doesn't
977 // use RTTI.
978 if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) {
979 Self.Diag(Loc: OpRange.getBegin(), DiagID: diag::err_no_dynamic_cast_with_fno_rtti);
980 SrcExpr = ExprError();
981 return;
982 }
983
984 // Warns when dynamic_cast is used with RTTI data disabled.
985 if (!Self.getLangOpts().RTTIData) {
986 bool MicrosoftABI =
987 Self.getASTContext().getTargetInfo().getCXXABI().isMicrosoft();
988 bool isClangCL = Self.getDiagnostics().getDiagnosticOptions().getFormat() ==
989 DiagnosticOptions::MSVC;
990 if (MicrosoftABI || !DestPointee->isVoidType())
991 Self.Diag(Loc: OpRange.getBegin(),
992 DiagID: diag::warn_no_dynamic_cast_with_rtti_disabled)
993 << isClangCL;
994 }
995
996 // For a dynamic_cast to a final type, IR generation might emit a reference
997 // to the vtable.
998 if (DestRecord) {
999 auto *DestDecl = DestRecord->getAsCXXRecordDecl();
1000 if (DestDecl->isEffectivelyFinal())
1001 Self.MarkVTableUsed(Loc: OpRange.getBegin(), Class: DestDecl);
1002 }
1003
1004 // Done. Everything else is run-time checks.
1005 Kind = CK_Dynamic;
1006}
1007
1008/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
1009/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
1010/// like this:
1011/// const char *str = "literal";
1012/// legacy_function(const_cast\<char*\>(str));
1013void CastOperation::CheckConstCast() {
1014 CheckNoDerefRAII NoderefCheck(*this);
1015
1016 if (ValueKind == VK_PRValue)
1017 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(E: SrcExpr.get());
1018 else if (isPlaceholder())
1019 SrcExpr = Self.CheckPlaceholderExpr(E: SrcExpr.get());
1020 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
1021 return;
1022
1023 unsigned msg = diag::err_bad_cxx_cast_generic;
1024 auto TCR = TryConstCast(Self, SrcExpr, DestType, /*CStyle*/ false, msg);
1025 if (TCR != TC_Success && msg != 0) {
1026 Self.Diag(Loc: OpRange.getBegin(), DiagID: msg) << CT_Const
1027 << SrcExpr.get()->getType() << DestType << OpRange;
1028 }
1029 if (!isValidCast(TCR))
1030 SrcExpr = ExprError();
1031}
1032
1033void CastOperation::CheckAddrspaceCast() {
1034 unsigned msg = diag::err_bad_cxx_cast_generic;
1035 auto TCR =
1036 TryAddressSpaceCast(Self, SrcExpr, DestType, /*CStyle*/ false, msg, Kind);
1037 if (TCR != TC_Success && msg != 0) {
1038 Self.Diag(Loc: OpRange.getBegin(), DiagID: msg)
1039 << CT_Addrspace << SrcExpr.get()->getType() << DestType << OpRange;
1040 }
1041 if (!isValidCast(TCR))
1042 SrcExpr = ExprError();
1043}
1044
1045/// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
1046/// or downcast between respective pointers or references.
1047static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
1048 QualType DestType,
1049 CastOperation::OpRangeType OpRange) {
1050 QualType SrcType = SrcExpr->getType();
1051 // When casting from pointer or reference, get pointee type; use original
1052 // type otherwise.
1053 const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
1054 const CXXRecordDecl *SrcRD =
1055 SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
1056
1057 // Examining subobjects for records is only possible if the complete and
1058 // valid definition is available. Also, template instantiation is not
1059 // allowed here.
1060 if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
1061 return;
1062
1063 const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
1064
1065 if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
1066 return;
1067
1068 enum {
1069 ReinterpretUpcast,
1070 ReinterpretDowncast
1071 } ReinterpretKind;
1072
1073 CXXBasePaths BasePaths;
1074
1075 if (SrcRD->isDerivedFrom(Base: DestRD, Paths&: BasePaths))
1076 ReinterpretKind = ReinterpretUpcast;
1077 else if (DestRD->isDerivedFrom(Base: SrcRD, Paths&: BasePaths))
1078 ReinterpretKind = ReinterpretDowncast;
1079 else
1080 return;
1081
1082 bool VirtualBase = true;
1083 bool NonZeroOffset = false;
1084 for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
1085 E = BasePaths.end();
1086 I != E; ++I) {
1087 const CXXBasePath &Path = *I;
1088 CharUnits Offset = CharUnits::Zero();
1089 bool IsVirtual = false;
1090 for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
1091 IElem != EElem; ++IElem) {
1092 IsVirtual = IElem->Base->isVirtual();
1093 if (IsVirtual)
1094 break;
1095 const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
1096 assert(BaseRD && "Base type should be a valid unqualified class type");
1097 // Don't check if any base has invalid declaration or has no definition
1098 // since it has no layout info.
1099 const CXXRecordDecl *Class = IElem->Class,
1100 *ClassDefinition = Class->getDefinition();
1101 if (Class->isInvalidDecl() || !ClassDefinition ||
1102 !ClassDefinition->isCompleteDefinition())
1103 return;
1104
1105 const ASTRecordLayout &DerivedLayout =
1106 Self.Context.getASTRecordLayout(D: Class);
1107 Offset += DerivedLayout.getBaseClassOffset(Base: BaseRD);
1108 }
1109 if (!IsVirtual) {
1110 // Don't warn if any path is a non-virtually derived base at offset zero.
1111 if (Offset.isZero())
1112 return;
1113 // Offset makes sense only for non-virtual bases.
1114 else
1115 NonZeroOffset = true;
1116 }
1117 VirtualBase = VirtualBase && IsVirtual;
1118 }
1119
1120 (void) NonZeroOffset; // Silence set but not used warning.
1121 assert((VirtualBase || NonZeroOffset) &&
1122 "Should have returned if has non-virtual base with zero offset");
1123
1124 QualType BaseType =
1125 ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
1126 QualType DerivedType =
1127 ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
1128
1129 SourceLocation BeginLoc = OpRange.getBegin();
1130 Self.Diag(Loc: BeginLoc, DiagID: diag::warn_reinterpret_different_from_static)
1131 << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind)
1132 << OpRange;
1133 Self.Diag(Loc: BeginLoc, DiagID: diag::note_reinterpret_updowncast_use_static)
1134 << int(ReinterpretKind)
1135 << FixItHint::CreateReplacement(RemoveRange: BeginLoc, Code: "static_cast");
1136}
1137
1138static bool argTypeIsABIEquivalent(QualType SrcType, QualType DestType,
1139 ASTContext &Context) {
1140 if (SrcType->isPointerType() && DestType->isPointerType())
1141 return true;
1142
1143 // Allow integral type mismatch if their size are equal.
1144 if ((SrcType->isIntegralType(Ctx: Context) || SrcType->isEnumeralType()) &&
1145 (DestType->isIntegralType(Ctx: Context) || DestType->isEnumeralType()))
1146 if (Context.getTypeSizeInChars(T: SrcType) ==
1147 Context.getTypeSizeInChars(T: DestType))
1148 return true;
1149
1150 return Context.hasSameUnqualifiedType(T1: SrcType, T2: DestType);
1151}
1152
1153static unsigned int checkCastFunctionType(Sema &Self, const ExprResult &SrcExpr,
1154 QualType DestType) {
1155 unsigned int DiagID = 0;
1156 const unsigned int DiagList[] = {diag::warn_cast_function_type_strict,
1157 diag::warn_cast_function_type};
1158 for (auto ID : DiagList) {
1159 if (!Self.Diags.isIgnored(DiagID: ID, Loc: SrcExpr.get()->getExprLoc())) {
1160 DiagID = ID;
1161 break;
1162 }
1163 }
1164 if (!DiagID)
1165 return 0;
1166
1167 QualType SrcType = SrcExpr.get()->getType();
1168 const FunctionType *SrcFTy = nullptr;
1169 const FunctionType *DstFTy = nullptr;
1170 if (((SrcType->isBlockPointerType() || SrcType->isFunctionPointerType()) &&
1171 DestType->isFunctionPointerType()) ||
1172 (SrcType->isMemberFunctionPointerType() &&
1173 DestType->isMemberFunctionPointerType())) {
1174 SrcFTy = SrcType->getPointeeType()->castAs<FunctionType>();
1175 DstFTy = DestType->getPointeeType()->castAs<FunctionType>();
1176 } else if (SrcType->isFunctionType() && DestType->isFunctionReferenceType()) {
1177 SrcFTy = SrcType->castAs<FunctionType>();
1178 DstFTy = DestType.getNonReferenceType()->castAs<FunctionType>();
1179 } else {
1180 return 0;
1181 }
1182 assert(SrcFTy && DstFTy);
1183
1184 if (Self.Context.hasSameType(T1: SrcFTy, T2: DstFTy))
1185 return 0;
1186
1187 // For strict checks, ensure we have an exact match.
1188 if (DiagID == diag::warn_cast_function_type_strict)
1189 return DiagID;
1190
1191 auto IsVoidVoid = [](const FunctionType *T) {
1192 if (!T->getReturnType()->isVoidType())
1193 return false;
1194 if (const auto *PT = T->getAs<FunctionProtoType>())
1195 return !PT->isVariadic() && PT->getNumParams() == 0;
1196 return false;
1197 };
1198
1199 auto IsFarProc = [](const FunctionType *T) {
1200 // The definition of FARPROC depends on the platform in terms of its return
1201 // type, which could be int, or long long, etc. We'll look for a source
1202 // signature for: <integer type> (*)() and call that "close enough" to
1203 // FARPROC to be sufficient to silence the diagnostic. This is similar to
1204 // how we allow casts between function pointers and void * for supporting
1205 // dlsym.
1206 // Note: we could check for __stdcall on the function pointer as well, but
1207 // that seems like splitting hairs.
1208 if (!T->getReturnType()->isIntegerType())
1209 return false;
1210 if (const auto *PT = T->getAs<FunctionProtoType>())
1211 return !PT->isVariadic() && PT->getNumParams() == 0;
1212 return true;
1213 };
1214
1215 // Skip if either function type is void(*)(void)
1216 if (IsVoidVoid(SrcFTy) || IsVoidVoid(DstFTy))
1217 return 0;
1218
1219 // On Windows, GetProcAddress() returns a FARPROC, which is a typedef for a
1220 // function pointer type (with no prototype, in C). We don't want to diagnose
1221 // this case so we don't diagnose idiomatic code on Windows.
1222 if (Self.getASTContext().getTargetInfo().getTriple().isOSWindows() &&
1223 IsFarProc(SrcFTy))
1224 return 0;
1225
1226 // Check return type.
1227 if (!argTypeIsABIEquivalent(SrcType: SrcFTy->getReturnType(), DestType: DstFTy->getReturnType(),
1228 Context&: Self.Context))
1229 return DiagID;
1230
1231 // Check if either has unspecified number of parameters
1232 if (SrcFTy->isFunctionNoProtoType() || DstFTy->isFunctionNoProtoType())
1233 return 0;
1234
1235 // Check parameter types.
1236
1237 const auto *SrcFPTy = cast<FunctionProtoType>(Val: SrcFTy);
1238 const auto *DstFPTy = cast<FunctionProtoType>(Val: DstFTy);
1239
1240 // In a cast involving function types with a variable argument list only the
1241 // types of initial arguments that are provided are considered.
1242 unsigned NumParams = SrcFPTy->getNumParams();
1243 unsigned DstNumParams = DstFPTy->getNumParams();
1244 if (NumParams > DstNumParams) {
1245 if (!DstFPTy->isVariadic())
1246 return DiagID;
1247 NumParams = DstNumParams;
1248 } else if (NumParams < DstNumParams) {
1249 if (!SrcFPTy->isVariadic())
1250 return DiagID;
1251 }
1252
1253 for (unsigned i = 0; i < NumParams; ++i)
1254 if (!argTypeIsABIEquivalent(SrcType: SrcFPTy->getParamType(i),
1255 DestType: DstFPTy->getParamType(i), Context&: Self.Context))
1256 return DiagID;
1257
1258 return 0;
1259}
1260
1261/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
1262/// valid.
1263/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
1264/// like this:
1265/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
1266void CastOperation::CheckReinterpretCast() {
1267 if (ValueKind == VK_PRValue && !isPlaceholder(K: BuiltinType::Overload))
1268 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(E: SrcExpr.get());
1269 else
1270 checkNonOverloadPlaceholders();
1271 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
1272 return;
1273
1274 unsigned msg = diag::err_bad_cxx_cast_generic;
1275 TryCastResult tcr =
1276 TryReinterpretCast(Self, SrcExpr, DestType,
1277 /*CStyle*/false, OpRange, msg, Kind);
1278 if (tcr != TC_Success && msg != 0) {
1279 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
1280 return;
1281 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
1282 //FIXME: &f<int>; is overloaded and resolvable
1283 Self.Diag(Loc: OpRange.getBegin(), DiagID: diag::err_bad_reinterpret_cast_overload)
1284 << OverloadExpr::find(E: SrcExpr.get()).Expression->getName()
1285 << DestType << OpRange;
1286 Self.NoteAllOverloadCandidates(E: SrcExpr.get());
1287
1288 } else {
1289 diagnoseBadCast(S&: Self, msg, castType: CT_Reinterpret, opRange: OpRange, src: SrcExpr.get(),
1290 destType: DestType, /*listInitialization=*/false);
1291 }
1292 }
1293
1294 if (isValidCast(TCR: tcr)) {
1295 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
1296 checkObjCConversion(CCK: CheckedConversionKind::OtherCast,
1297 /*IsReinterpretCast=*/true);
1298 DiagnoseReinterpretUpDownCast(Self, SrcExpr: SrcExpr.get(), DestType, OpRange);
1299
1300 if (unsigned DiagID = checkCastFunctionType(Self, SrcExpr, DestType))
1301 Self.Diag(Loc: OpRange.getBegin(), DiagID)
1302 << SrcExpr.get()->getType() << DestType << OpRange;
1303 } else {
1304 SrcExpr = ExprError();
1305 }
1306}
1307
1308
1309/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
1310/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
1311/// implicit conversions explicit and getting rid of data loss warnings.
1312void CastOperation::CheckStaticCast() {
1313 CheckNoDerefRAII NoderefCheck(*this);
1314
1315 if (isPlaceholder()) {
1316 checkNonOverloadPlaceholders();
1317 if (SrcExpr.isInvalid())
1318 return;
1319 }
1320
1321 // This test is outside everything else because it's the only case where
1322 // a non-lvalue-reference target type does not lead to decay.
1323 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1324 if (DestType->isVoidType()) {
1325 Kind = CK_ToVoid;
1326
1327 if (claimPlaceholder(K: BuiltinType::Overload)) {
1328 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
1329 DoFunctionPointerConversion: false, // Decay Function to ptr
1330 Complain: true, // Complain
1331 OpRangeForComplaining: OpRange, DestTypeForComplaining: DestType, DiagIDForComplaining: diag::err_bad_static_cast_overload);
1332 if (SrcExpr.isInvalid())
1333 return;
1334 }
1335
1336 SrcExpr = Self.IgnoredValueConversions(E: SrcExpr.get());
1337 return;
1338 }
1339
1340 if (ValueKind == VK_PRValue && !DestType->isRecordType() &&
1341 !isPlaceholder(K: BuiltinType::Overload)) {
1342 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(E: SrcExpr.get());
1343 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
1344 return;
1345 }
1346
1347 unsigned msg = diag::err_bad_cxx_cast_generic;
1348 TryCastResult tcr =
1349 TryStaticCast(Self, SrcExpr, DestType, CCK: CheckedConversionKind::OtherCast,
1350 OpRange, msg, Kind, BasePath, /*ListInitialization=*/false);
1351 if (tcr != TC_Success && msg != 0) {
1352 if (SrcExpr.isInvalid())
1353 return;
1354 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
1355 OverloadExpr* oe = OverloadExpr::find(E: SrcExpr.get()).Expression;
1356 Self.Diag(Loc: OpRange.getBegin(), DiagID: diag::err_bad_static_cast_overload)
1357 << oe->getName() << DestType << OpRange
1358 << oe->getQualifierLoc().getSourceRange();
1359 Self.NoteAllOverloadCandidates(E: SrcExpr.get());
1360 } else {
1361 diagnoseBadCast(S&: Self, msg, castType: CT_Static, opRange: OpRange, src: SrcExpr.get(), destType: DestType,
1362 /*listInitialization=*/false);
1363 }
1364 }
1365
1366 if (isValidCast(TCR: tcr)) {
1367 if (Kind == CK_BitCast)
1368 checkCastAlign();
1369 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
1370 checkObjCConversion(CCK: CheckedConversionKind::OtherCast);
1371 } else {
1372 SrcExpr = ExprError();
1373 }
1374}
1375
1376static bool IsAddressSpaceConversion(QualType SrcType, QualType DestType) {
1377 auto *SrcPtrType = SrcType->getAs<PointerType>();
1378 if (!SrcPtrType)
1379 return false;
1380 auto *DestPtrType = DestType->getAs<PointerType>();
1381 if (!DestPtrType)
1382 return false;
1383 return SrcPtrType->getPointeeType().getAddressSpace() !=
1384 DestPtrType->getPointeeType().getAddressSpace();
1385}
1386
1387/// TryStaticCast - Check if a static cast can be performed, and do so if
1388/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
1389/// and casting away constness.
1390static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
1391 QualType DestType, CheckedConversionKind CCK,
1392 CastOperation::OpRangeType OpRange,
1393 unsigned &msg, CastKind &Kind,
1394 CXXCastPath &BasePath,
1395 bool ListInitialization) {
1396 // Determine whether we have the semantics of a C-style cast.
1397 bool CStyle = (CCK == CheckedConversionKind::CStyleCast ||
1398 CCK == CheckedConversionKind::FunctionalCast);
1399
1400 // The order the tests is not entirely arbitrary. There is one conversion
1401 // that can be handled in two different ways. Given:
1402 // struct A {};
1403 // struct B : public A {
1404 // B(); B(const A&);
1405 // };
1406 // const A &a = B();
1407 // the cast static_cast<const B&>(a) could be seen as either a static
1408 // reference downcast, or an explicit invocation of the user-defined
1409 // conversion using B's conversion constructor.
1410 // DR 427 specifies that the downcast is to be applied here.
1411
1412 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1413 // Done outside this function.
1414
1415 TryCastResult tcr;
1416
1417 // C++ 5.2.9p5, reference downcast.
1418 // See the function for details.
1419 // DR 427 specifies that this is to be applied before paragraph 2.
1420 tcr = TryStaticReferenceDowncast(Self, SrcExpr: SrcExpr.get(), DestType, CStyle,
1421 OpRange, msg, Kind, BasePath);
1422 if (tcr != TC_NotApplicable)
1423 return tcr;
1424
1425 // C++11 [expr.static.cast]p3:
1426 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
1427 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
1428 tcr = TryLValueToRValueCast(Self, SrcExpr: SrcExpr.get(), DestType, CStyle, Kind,
1429 BasePath, msg);
1430 if (tcr != TC_NotApplicable)
1431 return tcr;
1432
1433 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
1434 // [...] if the declaration "T t(e);" is well-formed, [...].
1435 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
1436 Kind, ListInitialization);
1437 if (SrcExpr.isInvalid())
1438 return TC_Failed;
1439 if (tcr != TC_NotApplicable)
1440 return tcr;
1441
1442 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
1443 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
1444 // conversions, subject to further restrictions.
1445 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
1446 // of qualification conversions impossible. (In C++20, adding an array bound
1447 // would be the reverse of a qualification conversion, but adding permission
1448 // to add an array bound in a static_cast is a wording oversight.)
1449 // In the CStyle case, the earlier attempt to const_cast should have taken
1450 // care of reverse qualification conversions.
1451
1452 QualType SrcType = Self.Context.getCanonicalType(T: SrcExpr.get()->getType());
1453
1454 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
1455 // converted to an integral type. [...] A value of a scoped enumeration type
1456 // can also be explicitly converted to a floating-point type [...].
1457 if (const EnumType *Enum = SrcType->getAs<EnumType>()) {
1458 if (Enum->getDecl()->isScoped()) {
1459 if (DestType->isBooleanType()) {
1460 Kind = CK_IntegralToBoolean;
1461 return TC_Success;
1462 } else if (DestType->isIntegralType(Ctx: Self.Context)) {
1463 Kind = CK_IntegralCast;
1464 return TC_Success;
1465 } else if (DestType->isRealFloatingType()) {
1466 Kind = CK_IntegralToFloating;
1467 return TC_Success;
1468 }
1469 }
1470 }
1471
1472 // Reverse integral promotion/conversion. All such conversions are themselves
1473 // again integral promotions or conversions and are thus already handled by
1474 // p2 (TryDirectInitialization above).
1475 // (Note: any data loss warnings should be suppressed.)
1476 // The exception is the reverse of enum->integer, i.e. integer->enum (and
1477 // enum->enum). See also C++ 5.2.9p7.
1478 // The same goes for reverse floating point promotion/conversion and
1479 // floating-integral conversions. Again, only floating->enum is relevant.
1480 if (DestType->isEnumeralType()) {
1481 if (Self.RequireCompleteType(Loc: OpRange.getBegin(), T: DestType,
1482 DiagID: diag::err_bad_cast_incomplete)) {
1483 SrcExpr = ExprError();
1484 return TC_Failed;
1485 }
1486 if (SrcType->isIntegralOrEnumerationType()) {
1487 // [expr.static.cast]p10 If the enumeration type has a fixed underlying
1488 // type, the value is first converted to that type by integral conversion
1489 const EnumType *Enum = DestType->castAs<EnumType>();
1490 Kind = Enum->getDecl()->isFixed() &&
1491 Enum->getDecl()->getIntegerType()->isBooleanType()
1492 ? CK_IntegralToBoolean
1493 : CK_IntegralCast;
1494 return TC_Success;
1495 } else if (SrcType->isRealFloatingType()) {
1496 Kind = CK_FloatingToIntegral;
1497 return TC_Success;
1498 }
1499 }
1500
1501 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
1502 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
1503 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
1504 Kind, BasePath);
1505 if (tcr != TC_NotApplicable)
1506 return tcr;
1507
1508 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
1509 // conversion. C++ 5.2.9p9 has additional information.
1510 // DR54's access restrictions apply here also.
1511 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
1512 OpRange, msg, Kind, BasePath);
1513 if (tcr != TC_NotApplicable)
1514 return tcr;
1515
1516 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
1517 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
1518 // just the usual constness stuff.
1519 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
1520 QualType SrcPointee = SrcPointer->getPointeeType();
1521 if (SrcPointee->isVoidType()) {
1522 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
1523 QualType DestPointee = DestPointer->getPointeeType();
1524 if (DestPointee->isIncompleteOrObjectType()) {
1525 // This is definitely the intended conversion, but it might fail due
1526 // to a qualifier violation. Note that we permit Objective-C lifetime
1527 // and GC qualifier mismatches here.
1528 if (!CStyle) {
1529 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
1530 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
1531 DestPointeeQuals.removeObjCGCAttr();
1532 DestPointeeQuals.removeObjCLifetime();
1533 SrcPointeeQuals.removeObjCGCAttr();
1534 SrcPointeeQuals.removeObjCLifetime();
1535 if (DestPointeeQuals != SrcPointeeQuals &&
1536 !DestPointeeQuals.compatiblyIncludes(other: SrcPointeeQuals,
1537 Ctx: Self.getASTContext())) {
1538 msg = diag::err_bad_cxx_cast_qualifiers_away;
1539 return TC_Failed;
1540 }
1541 }
1542 Kind = IsAddressSpaceConversion(SrcType, DestType)
1543 ? CK_AddressSpaceConversion
1544 : CK_BitCast;
1545 return TC_Success;
1546 }
1547
1548 // Microsoft permits static_cast from 'pointer-to-void' to
1549 // 'pointer-to-function'.
1550 if (!CStyle && Self.getLangOpts().MSVCCompat &&
1551 DestPointee->isFunctionType()) {
1552 Self.Diag(Loc: OpRange.getBegin(), DiagID: diag::ext_ms_cast_fn_obj) << OpRange;
1553 Kind = CK_BitCast;
1554 return TC_Success;
1555 }
1556 }
1557 else if (DestType->isObjCObjectPointerType()) {
1558 // allow both c-style cast and static_cast of objective-c pointers as
1559 // they are pervasive.
1560 Kind = CK_CPointerToObjCPointerCast;
1561 return TC_Success;
1562 }
1563 else if (CStyle && DestType->isBlockPointerType()) {
1564 // allow c-style cast of void * to block pointers.
1565 Kind = CK_AnyPointerToBlockPointerCast;
1566 return TC_Success;
1567 }
1568 }
1569 }
1570 // Allow arbitrary objective-c pointer conversion with static casts.
1571 if (SrcType->isObjCObjectPointerType() &&
1572 DestType->isObjCObjectPointerType()) {
1573 Kind = CK_BitCast;
1574 return TC_Success;
1575 }
1576 // Allow ns-pointer to cf-pointer conversion in either direction
1577 // with static casts.
1578 if (!CStyle &&
1579 Self.ObjC().CheckTollFreeBridgeStaticCast(castType: DestType, castExpr: SrcExpr.get(), Kind))
1580 return TC_Success;
1581
1582 // See if it looks like the user is trying to convert between
1583 // related record types, and select a better diagnostic if so.
1584 if (auto SrcPointer = SrcType->getAs<PointerType>())
1585 if (auto DestPointer = DestType->getAs<PointerType>())
1586 if (SrcPointer->getPointeeType()->getAs<RecordType>() &&
1587 DestPointer->getPointeeType()->getAs<RecordType>())
1588 msg = diag::err_bad_cxx_cast_unrelated_class;
1589
1590 if (SrcType->isMatrixType() && DestType->isMatrixType()) {
1591 if (Self.CheckMatrixCast(R: OpRange, DestTy: DestType, SrcTy: SrcType, Kind)) {
1592 SrcExpr = ExprError();
1593 return TC_Failed;
1594 }
1595 return TC_Success;
1596 }
1597
1598 // We tried everything. Everything! Nothing works! :-(
1599 return TC_NotApplicable;
1600}
1601
1602/// Tests whether a conversion according to N2844 is valid.
1603TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
1604 QualType DestType, bool CStyle,
1605 CastKind &Kind, CXXCastPath &BasePath,
1606 unsigned &msg) {
1607 // C++11 [expr.static.cast]p3:
1608 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
1609 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
1610 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
1611 if (!R)
1612 return TC_NotApplicable;
1613
1614 if (!SrcExpr->isGLValue())
1615 return TC_NotApplicable;
1616
1617 // Because we try the reference downcast before this function, from now on
1618 // this is the only cast possibility, so we issue an error if we fail now.
1619 // FIXME: Should allow casting away constness if CStyle.
1620 QualType FromType = SrcExpr->getType();
1621 QualType ToType = R->getPointeeType();
1622 if (CStyle) {
1623 FromType = FromType.getUnqualifiedType();
1624 ToType = ToType.getUnqualifiedType();
1625 }
1626
1627 Sema::ReferenceConversions RefConv;
1628 Sema::ReferenceCompareResult RefResult = Self.CompareReferenceRelationship(
1629 Loc: SrcExpr->getBeginLoc(), T1: ToType, T2: FromType, Conv: &RefConv);
1630 if (RefResult != Sema::Ref_Compatible) {
1631 if (CStyle || RefResult == Sema::Ref_Incompatible)
1632 return TC_NotApplicable;
1633 // Diagnose types which are reference-related but not compatible here since
1634 // we can provide better diagnostics. In these cases forwarding to
1635 // [expr.static.cast]p4 should never result in a well-formed cast.
1636 msg = SrcExpr->isLValue() ? diag::err_bad_lvalue_to_rvalue_cast
1637 : diag::err_bad_rvalue_to_rvalue_cast;
1638 return TC_Failed;
1639 }
1640
1641 if (RefConv & Sema::ReferenceConversions::DerivedToBase) {
1642 Kind = CK_DerivedToBase;
1643 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1644 /*DetectVirtual=*/true);
1645 if (!Self.IsDerivedFrom(Loc: SrcExpr->getBeginLoc(), Derived: SrcExpr->getType(),
1646 Base: R->getPointeeType(), Paths))
1647 return TC_NotApplicable;
1648
1649 Self.BuildBasePathArray(Paths, BasePath);
1650 } else
1651 Kind = CK_NoOp;
1652
1653 return TC_Success;
1654}
1655
1656/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1657TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
1658 QualType DestType, bool CStyle,
1659 CastOperation::OpRangeType OpRange,
1660 unsigned &msg, CastKind &Kind,
1661 CXXCastPath &BasePath) {
1662 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1663 // cast to type "reference to cv2 D", where D is a class derived from B,
1664 // if a valid standard conversion from "pointer to D" to "pointer to B"
1665 // exists, cv2 >= cv1, and B is not a virtual base class of D.
1666 // In addition, DR54 clarifies that the base must be accessible in the
1667 // current context. Although the wording of DR54 only applies to the pointer
1668 // variant of this rule, the intent is clearly for it to apply to the this
1669 // conversion as well.
1670
1671 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
1672 if (!DestReference) {
1673 return TC_NotApplicable;
1674 }
1675 bool RValueRef = DestReference->isRValueReferenceType();
1676 if (!RValueRef && !SrcExpr->isLValue()) {
1677 // We know the left side is an lvalue reference, so we can suggest a reason.
1678 msg = diag::err_bad_cxx_cast_rvalue;
1679 return TC_NotApplicable;
1680 }
1681
1682 QualType DestPointee = DestReference->getPointeeType();
1683
1684 // FIXME: If the source is a prvalue, we should issue a warning (because the
1685 // cast always has undefined behavior), and for AST consistency, we should
1686 // materialize a temporary.
1687 return TryStaticDowncast(Self,
1688 SrcType: Self.Context.getCanonicalType(T: SrcExpr->getType()),
1689 DestType: Self.Context.getCanonicalType(T: DestPointee), CStyle,
1690 OpRange, OrigSrcType: SrcExpr->getType(), OrigDestType: DestType, msg, Kind,
1691 BasePath);
1692}
1693
1694/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1695TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
1696 QualType DestType, bool CStyle,
1697 CastOperation::OpRangeType OpRange,
1698 unsigned &msg, CastKind &Kind,
1699 CXXCastPath &BasePath) {
1700 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1701 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1702 // is a class derived from B, if a valid standard conversion from "pointer
1703 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1704 // class of D.
1705 // In addition, DR54 clarifies that the base must be accessible in the
1706 // current context.
1707
1708 const PointerType *DestPointer = DestType->getAs<PointerType>();
1709 if (!DestPointer) {
1710 return TC_NotApplicable;
1711 }
1712
1713 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
1714 if (!SrcPointer) {
1715 msg = diag::err_bad_static_cast_pointer_nonpointer;
1716 return TC_NotApplicable;
1717 }
1718
1719 return TryStaticDowncast(Self,
1720 SrcType: Self.Context.getCanonicalType(T: SrcPointer->getPointeeType()),
1721 DestType: Self.Context.getCanonicalType(T: DestPointer->getPointeeType()),
1722 CStyle, OpRange, OrigSrcType: SrcType, OrigDestType: DestType, msg, Kind,
1723 BasePath);
1724}
1725
1726/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1727/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
1728/// DestType is possible and allowed.
1729TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
1730 CanQualType DestType, bool CStyle,
1731 CastOperation::OpRangeType OpRange,
1732 QualType OrigSrcType, QualType OrigDestType,
1733 unsigned &msg, CastKind &Kind,
1734 CXXCastPath &BasePath) {
1735 // We can only work with complete types. But don't complain if it doesn't work
1736 if (!Self.isCompleteType(Loc: OpRange.getBegin(), T: SrcType) ||
1737 !Self.isCompleteType(Loc: OpRange.getBegin(), T: DestType))
1738 return TC_NotApplicable;
1739
1740 // Downcast can only happen in class hierarchies, so we need classes.
1741 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
1742 return TC_NotApplicable;
1743 }
1744
1745 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1746 /*DetectVirtual=*/true);
1747 if (!Self.IsDerivedFrom(Loc: OpRange.getBegin(), Derived: DestType, Base: SrcType, Paths)) {
1748 return TC_NotApplicable;
1749 }
1750
1751 // Target type does derive from source type. Now we're serious. If an error
1752 // appears now, it's not ignored.
1753 // This may not be entirely in line with the standard. Take for example:
1754 // struct A {};
1755 // struct B : virtual A {
1756 // B(A&);
1757 // };
1758 //
1759 // void f()
1760 // {
1761 // (void)static_cast<const B&>(*((A*)0));
1762 // }
1763 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1764 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1765 // However, both GCC and Comeau reject this example, and accepting it would
1766 // mean more complex code if we're to preserve the nice error message.
1767 // FIXME: Being 100% compliant here would be nice to have.
1768
1769 // Must preserve cv, as always, unless we're in C-style mode.
1770 if (!CStyle &&
1771 !DestType.isAtLeastAsQualifiedAs(Other: SrcType, Ctx: Self.getASTContext())) {
1772 msg = diag::err_bad_cxx_cast_qualifiers_away;
1773 return TC_Failed;
1774 }
1775
1776 if (Paths.isAmbiguous(BaseType: SrcType.getUnqualifiedType())) {
1777 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1778 // that it builds the paths in reverse order.
1779 // To sum up: record all paths to the base and build a nice string from
1780 // them. Use it to spice up the error message.
1781 if (!Paths.isRecordingPaths()) {
1782 Paths.clear();
1783 Paths.setRecordingPaths(true);
1784 Self.IsDerivedFrom(Loc: OpRange.getBegin(), Derived: DestType, Base: SrcType, Paths);
1785 }
1786 std::string PathDisplayStr;
1787 std::set<unsigned> DisplayedPaths;
1788 for (clang::CXXBasePath &Path : Paths) {
1789 if (DisplayedPaths.insert(x: Path.back().SubobjectNumber).second) {
1790 // We haven't displayed a path to this particular base
1791 // class subobject yet.
1792 PathDisplayStr += "\n ";
1793 for (CXXBasePathElement &PE : llvm::reverse(C&: Path))
1794 PathDisplayStr += PE.Base->getType().getAsString() + " -> ";
1795 PathDisplayStr += QualType(DestType).getAsString();
1796 }
1797 }
1798
1799 Self.Diag(Loc: OpRange.getBegin(), DiagID: diag::err_ambiguous_base_to_derived_cast)
1800 << QualType(SrcType).getUnqualifiedType()
1801 << QualType(DestType).getUnqualifiedType()
1802 << PathDisplayStr << OpRange;
1803 msg = 0;
1804 return TC_Failed;
1805 }
1806
1807 if (Paths.getDetectedVirtual() != nullptr) {
1808 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1809 Self.Diag(Loc: OpRange.getBegin(), DiagID: diag::err_static_downcast_via_virtual)
1810 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1811 msg = 0;
1812 return TC_Failed;
1813 }
1814
1815 if (!CStyle) {
1816 switch (Self.CheckBaseClassAccess(AccessLoc: OpRange.getBegin(),
1817 Base: SrcType, Derived: DestType,
1818 Path: Paths.front(),
1819 DiagID: diag::err_downcast_from_inaccessible_base)) {
1820 case Sema::AR_accessible:
1821 case Sema::AR_delayed: // be optimistic
1822 case Sema::AR_dependent: // be optimistic
1823 break;
1824
1825 case Sema::AR_inaccessible:
1826 msg = 0;
1827 return TC_Failed;
1828 }
1829 }
1830
1831 Self.BuildBasePathArray(Paths, BasePath);
1832 Kind = CK_BaseToDerived;
1833 return TC_Success;
1834}
1835
1836/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1837/// C++ 5.2.9p9 is valid:
1838///
1839/// An rvalue of type "pointer to member of D of type cv1 T" can be
1840/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1841/// where B is a base class of D [...].
1842///
1843TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
1844 QualType SrcType, QualType DestType,
1845 bool CStyle,
1846 CastOperation::OpRangeType OpRange,
1847 unsigned &msg, CastKind &Kind,
1848 CXXCastPath &BasePath) {
1849 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
1850 if (!DestMemPtr)
1851 return TC_NotApplicable;
1852
1853 bool WasOverloadedFunction = false;
1854 DeclAccessPair FoundOverload;
1855 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
1856 if (FunctionDecl *Fn
1857 = Self.ResolveAddressOfOverloadedFunction(AddressOfExpr: SrcExpr.get(), TargetType: DestType, Complain: false,
1858 Found&: FoundOverload)) {
1859 CXXMethodDecl *M = cast<CXXMethodDecl>(Val: Fn);
1860 SrcType = Self.Context.getMemberPointerType(
1861 T: Fn->getType(), /*Qualifier=*/nullptr, Cls: M->getParent());
1862 WasOverloadedFunction = true;
1863 }
1864 }
1865
1866 switch (Self.CheckMemberPointerConversion(
1867 FromType: SrcType, ToPtrType: DestMemPtr, Kind, BasePath, CheckLoc: OpRange.getBegin(), OpRange, IgnoreBaseAccess: CStyle,
1868 Direction: Sema::MemberPointerConversionDirection::Upcast)) {
1869 case Sema::MemberPointerConversionResult::Success:
1870 if (Kind == CK_NullToMemberPointer) {
1871 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1872 return TC_NotApplicable;
1873 }
1874 break;
1875 case Sema::MemberPointerConversionResult::DifferentPointee:
1876 case Sema::MemberPointerConversionResult::NotDerived:
1877 return TC_NotApplicable;
1878 case Sema::MemberPointerConversionResult::Ambiguous:
1879 case Sema::MemberPointerConversionResult::Virtual:
1880 case Sema::MemberPointerConversionResult::Inaccessible:
1881 msg = 0;
1882 return TC_Failed;
1883 }
1884
1885 if (WasOverloadedFunction) {
1886 // Resolve the address of the overloaded function again, this time
1887 // allowing complaints if something goes wrong.
1888 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(AddressOfExpr: SrcExpr.get(),
1889 TargetType: DestType,
1890 Complain: true,
1891 Found&: FoundOverload);
1892 if (!Fn) {
1893 msg = 0;
1894 return TC_Failed;
1895 }
1896
1897 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundDecl: FoundOverload, Fn);
1898 if (!SrcExpr.isUsable()) {
1899 msg = 0;
1900 return TC_Failed;
1901 }
1902 }
1903 return TC_Success;
1904}
1905
1906/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1907/// is valid:
1908///
1909/// An expression e can be explicitly converted to a type T using a
1910/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1911TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
1912 QualType DestType,
1913 CheckedConversionKind CCK,
1914 CastOperation::OpRangeType OpRange,
1915 unsigned &msg, CastKind &Kind,
1916 bool ListInitialization) {
1917 if (DestType->isRecordType()) {
1918 if (Self.RequireCompleteType(Loc: OpRange.getBegin(), T: DestType,
1919 DiagID: diag::err_bad_cast_incomplete) ||
1920 Self.RequireNonAbstractType(Loc: OpRange.getBegin(), T: DestType,
1921 DiagID: diag::err_allocation_of_abstract_type)) {
1922 msg = 0;
1923 return TC_Failed;
1924 }
1925 }
1926
1927 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Type: DestType);
1928 InitializationKind InitKind =
1929 (CCK == CheckedConversionKind::CStyleCast)
1930 ? InitializationKind::CreateCStyleCast(StartLoc: OpRange.getBegin(), TypeRange: OpRange,
1931 InitList: ListInitialization)
1932 : (CCK == CheckedConversionKind::FunctionalCast)
1933 ? InitializationKind::CreateFunctionalCast(
1934 StartLoc: OpRange.getBegin(), ParenRange: OpRange.getParenRange(), InitList: ListInitialization)
1935 : InitializationKind::CreateCast(TypeRange: OpRange);
1936 Expr *SrcExprRaw = SrcExpr.get();
1937 // FIXME: Per DR242, we should check for an implicit conversion sequence
1938 // or for a constructor that could be invoked by direct-initialization
1939 // here, not for an initialization sequence.
1940 InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
1941
1942 // At this point of CheckStaticCast, if the destination is a reference,
1943 // or the expression is an overload expression this has to work.
1944 // There is no other way that works.
1945 // On the other hand, if we're checking a C-style cast, we've still got
1946 // the reinterpret_cast way.
1947 bool CStyle = (CCK == CheckedConversionKind::CStyleCast ||
1948 CCK == CheckedConversionKind::FunctionalCast);
1949 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
1950 return TC_NotApplicable;
1951
1952 ExprResult Result = InitSeq.Perform(S&: Self, Entity, Kind: InitKind, Args: SrcExprRaw);
1953 if (Result.isInvalid()) {
1954 msg = 0;
1955 return TC_Failed;
1956 }
1957
1958 if (InitSeq.isConstructorInitialization())
1959 Kind = CK_ConstructorConversion;
1960 else
1961 Kind = CK_NoOp;
1962
1963 SrcExpr = Result;
1964 return TC_Success;
1965}
1966
1967/// TryConstCast - See if a const_cast from source to destination is allowed,
1968/// and perform it if it is.
1969static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
1970 QualType DestType, bool CStyle,
1971 unsigned &msg) {
1972 DestType = Self.Context.getCanonicalType(T: DestType);
1973 QualType SrcType = SrcExpr.get()->getType();
1974 bool NeedToMaterializeTemporary = false;
1975
1976 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
1977 // C++11 5.2.11p4:
1978 // if a pointer to T1 can be explicitly converted to the type "pointer to
1979 // T2" using a const_cast, then the following conversions can also be
1980 // made:
1981 // -- an lvalue of type T1 can be explicitly converted to an lvalue of
1982 // type T2 using the cast const_cast<T2&>;
1983 // -- a glvalue of type T1 can be explicitly converted to an xvalue of
1984 // type T2 using the cast const_cast<T2&&>; and
1985 // -- if T1 is a class type, a prvalue of type T1 can be explicitly
1986 // converted to an xvalue of type T2 using the cast const_cast<T2&&>.
1987
1988 if (isa<LValueReferenceType>(Val: DestTypeTmp) && !SrcExpr.get()->isLValue()) {
1989 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1990 // is C-style, static_cast might find a way, so we simply suggest a
1991 // message and tell the parent to keep searching.
1992 msg = diag::err_bad_cxx_cast_rvalue;
1993 return TC_NotApplicable;
1994 }
1995
1996 if (isa<RValueReferenceType>(Val: DestTypeTmp) && SrcExpr.get()->isPRValue()) {
1997 if (!SrcType->isRecordType()) {
1998 // Cannot const_cast non-class prvalue to rvalue reference type. But if
1999 // this is C-style, static_cast can do this.
2000 msg = diag::err_bad_cxx_cast_rvalue;
2001 return TC_NotApplicable;
2002 }
2003
2004 // Materialize the class prvalue so that the const_cast can bind a
2005 // reference to it.
2006 NeedToMaterializeTemporary = true;
2007 }
2008
2009 // It's not completely clear under the standard whether we can
2010 // const_cast bit-field gl-values. Doing so would not be
2011 // intrinsically complicated, but for now, we say no for
2012 // consistency with other compilers and await the word of the
2013 // committee.
2014 if (SrcExpr.get()->refersToBitField()) {
2015 msg = diag::err_bad_cxx_cast_bitfield;
2016 return TC_NotApplicable;
2017 }
2018
2019 DestType = Self.Context.getPointerType(T: DestTypeTmp->getPointeeType());
2020 SrcType = Self.Context.getPointerType(T: SrcType);
2021 }
2022
2023 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
2024 // the rules for const_cast are the same as those used for pointers.
2025
2026 if (!DestType->isPointerType() &&
2027 !DestType->isMemberPointerType() &&
2028 !DestType->isObjCObjectPointerType()) {
2029 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
2030 // was a reference type, we converted it to a pointer above.
2031 // The status of rvalue references isn't entirely clear, but it looks like
2032 // conversion to them is simply invalid.
2033 // C++ 5.2.11p3: For two pointer types [...]
2034 if (!CStyle)
2035 msg = diag::err_bad_const_cast_dest;
2036 return TC_NotApplicable;
2037 }
2038 if (DestType->isFunctionPointerType() ||
2039 DestType->isMemberFunctionPointerType()) {
2040 // Cannot cast direct function pointers.
2041 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
2042 // T is the ultimate pointee of source and target type.
2043 if (!CStyle)
2044 msg = diag::err_bad_const_cast_dest;
2045 return TC_NotApplicable;
2046 }
2047
2048 // C++ [expr.const.cast]p3:
2049 // "For two similar types T1 and T2, [...]"
2050 //
2051 // We only allow a const_cast to change cvr-qualifiers, not other kinds of
2052 // type qualifiers. (Likewise, we ignore other changes when determining
2053 // whether a cast casts away constness.)
2054 if (!Self.Context.hasCvrSimilarType(T1: SrcType, T2: DestType))
2055 return TC_NotApplicable;
2056
2057 if (NeedToMaterializeTemporary)
2058 // This is a const_cast from a class prvalue to an rvalue reference type.
2059 // Materialize a temporary to store the result of the conversion.
2060 SrcExpr = Self.CreateMaterializeTemporaryExpr(T: SrcExpr.get()->getType(),
2061 Temporary: SrcExpr.get(),
2062 /*IsLValueReference*/ BoundToLvalueReference: false);
2063
2064 return TC_Success;
2065}
2066
2067// Checks for undefined behavior in reinterpret_cast.
2068// The cases that is checked for is:
2069// *reinterpret_cast<T*>(&a)
2070// reinterpret_cast<T&>(a)
2071// where accessing 'a' as type 'T' will result in undefined behavior.
2072void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
2073 bool IsDereference,
2074 SourceRange Range) {
2075 unsigned DiagID = IsDereference ?
2076 diag::warn_pointer_indirection_from_incompatible_type :
2077 diag::warn_undefined_reinterpret_cast;
2078
2079 if (Diags.isIgnored(DiagID, Loc: Range.getBegin()))
2080 return;
2081
2082 QualType SrcTy, DestTy;
2083 if (IsDereference) {
2084 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
2085 return;
2086 }
2087 SrcTy = SrcType->getPointeeType();
2088 DestTy = DestType->getPointeeType();
2089 } else {
2090 if (!DestType->getAs<ReferenceType>()) {
2091 return;
2092 }
2093 SrcTy = SrcType;
2094 DestTy = DestType->getPointeeType();
2095 }
2096
2097 // Cast is compatible if the types are the same.
2098 if (Context.hasSameUnqualifiedType(T1: DestTy, T2: SrcTy)) {
2099 return;
2100 }
2101 // or one of the types is a char or void type
2102 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
2103 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
2104 return;
2105 }
2106 // or one of the types is a tag type.
2107 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
2108 return;
2109 }
2110
2111 // FIXME: Scoped enums?
2112 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
2113 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
2114 if (Context.getTypeSize(T: DestTy) == Context.getTypeSize(T: SrcTy)) {
2115 return;
2116 }
2117 }
2118
2119 if (SrcTy->isDependentType() || DestTy->isDependentType()) {
2120 return;
2121 }
2122
2123 Diag(Loc: Range.getBegin(), DiagID) << SrcType << DestType << Range;
2124}
2125
2126static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
2127 QualType DestType) {
2128 QualType SrcType = SrcExpr.get()->getType();
2129 if (Self.Context.hasSameType(T1: SrcType, T2: DestType))
2130 return;
2131 if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
2132 if (SrcPtrTy->isObjCSelType()) {
2133 QualType DT = DestType;
2134 if (isa<PointerType>(Val: DestType))
2135 DT = DestType->getPointeeType();
2136 if (!DT.getUnqualifiedType()->isVoidType())
2137 Self.Diag(Loc: SrcExpr.get()->getExprLoc(),
2138 DiagID: diag::warn_cast_pointer_from_sel)
2139 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2140 }
2141}
2142
2143/// Diagnose casts that change the calling convention of a pointer to a function
2144/// defined in the current TU.
2145static void DiagnoseCallingConvCast(Sema &Self, const ExprResult &SrcExpr,
2146 QualType DstType,
2147 CastOperation::OpRangeType OpRange) {
2148 // Check if this cast would change the calling convention of a function
2149 // pointer type.
2150 QualType SrcType = SrcExpr.get()->getType();
2151 if (Self.Context.hasSameType(T1: SrcType, T2: DstType) ||
2152 !SrcType->isFunctionPointerType() || !DstType->isFunctionPointerType())
2153 return;
2154 const auto *SrcFTy =
2155 SrcType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
2156 const auto *DstFTy =
2157 DstType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
2158 CallingConv SrcCC = SrcFTy->getCallConv();
2159 CallingConv DstCC = DstFTy->getCallConv();
2160 if (SrcCC == DstCC)
2161 return;
2162
2163 // We have a calling convention cast. Check if the source is a pointer to a
2164 // known, specific function that has already been defined.
2165 Expr *Src = SrcExpr.get()->IgnoreParenImpCasts();
2166 if (auto *UO = dyn_cast<UnaryOperator>(Val: Src))
2167 if (UO->getOpcode() == UO_AddrOf)
2168 Src = UO->getSubExpr()->IgnoreParenImpCasts();
2169 auto *DRE = dyn_cast<DeclRefExpr>(Val: Src);
2170 if (!DRE)
2171 return;
2172 auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl());
2173 if (!FD)
2174 return;
2175
2176 // Only warn if we are casting from the default convention to a non-default
2177 // convention. This can happen when the programmer forgot to apply the calling
2178 // convention to the function declaration and then inserted this cast to
2179 // satisfy the type system.
2180 CallingConv DefaultCC = Self.getASTContext().getDefaultCallingConvention(
2181 IsVariadic: FD->isVariadic(), IsCXXMethod: FD->isCXXInstanceMember());
2182 if (DstCC == DefaultCC || SrcCC != DefaultCC)
2183 return;
2184
2185 // Diagnose this cast, as it is probably bad.
2186 StringRef SrcCCName = FunctionType::getNameForCallConv(CC: SrcCC);
2187 StringRef DstCCName = FunctionType::getNameForCallConv(CC: DstCC);
2188 Self.Diag(Loc: OpRange.getBegin(), DiagID: diag::warn_cast_calling_conv)
2189 << SrcCCName << DstCCName << OpRange;
2190
2191 // The checks above are cheaper than checking if the diagnostic is enabled.
2192 // However, it's worth checking if the warning is enabled before we construct
2193 // a fixit.
2194 if (Self.Diags.isIgnored(DiagID: diag::warn_cast_calling_conv, Loc: OpRange.getBegin()))
2195 return;
2196
2197 // Try to suggest a fixit to change the calling convention of the function
2198 // whose address was taken. Try to use the latest macro for the convention.
2199 // For example, users probably want to write "WINAPI" instead of "__stdcall"
2200 // to match the Windows header declarations.
2201 SourceLocation NameLoc = FD->getFirstDecl()->getNameInfo().getLoc();
2202 Preprocessor &PP = Self.getPreprocessor();
2203 SmallVector<TokenValue, 6> AttrTokens;
2204 SmallString<64> CCAttrText;
2205 llvm::raw_svector_ostream OS(CCAttrText);
2206 if (Self.getLangOpts().MicrosoftExt) {
2207 // __stdcall or __vectorcall
2208 OS << "__" << DstCCName;
2209 IdentifierInfo *II = PP.getIdentifierInfo(Name: OS.str());
2210 AttrTokens.push_back(Elt: II->isKeyword(LangOpts: Self.getLangOpts())
2211 ? TokenValue(II->getTokenID())
2212 : TokenValue(II));
2213 } else {
2214 // __attribute__((stdcall)) or __attribute__((vectorcall))
2215 OS << "__attribute__((" << DstCCName << "))";
2216 AttrTokens.push_back(Elt: tok::kw___attribute);
2217 AttrTokens.push_back(Elt: tok::l_paren);
2218 AttrTokens.push_back(Elt: tok::l_paren);
2219 IdentifierInfo *II = PP.getIdentifierInfo(Name: DstCCName);
2220 AttrTokens.push_back(Elt: II->isKeyword(LangOpts: Self.getLangOpts())
2221 ? TokenValue(II->getTokenID())
2222 : TokenValue(II));
2223 AttrTokens.push_back(Elt: tok::r_paren);
2224 AttrTokens.push_back(Elt: tok::r_paren);
2225 }
2226 StringRef AttrSpelling = PP.getLastMacroWithSpelling(Loc: NameLoc, Tokens: AttrTokens);
2227 if (!AttrSpelling.empty())
2228 CCAttrText = AttrSpelling;
2229 OS << ' ';
2230 Self.Diag(Loc: NameLoc, DiagID: diag::note_change_calling_conv_fixit)
2231 << FD << DstCCName << FixItHint::CreateInsertion(InsertionLoc: NameLoc, Code: CCAttrText);
2232}
2233
2234static void checkIntToPointerCast(bool CStyle, const SourceRange &OpRange,
2235 const Expr *SrcExpr, QualType DestType,
2236 Sema &Self) {
2237 QualType SrcType = SrcExpr->getType();
2238
2239 // Not warning on reinterpret_cast, boolean, constant expressions, etc
2240 // are not explicit design choices, but consistent with GCC's behavior.
2241 // Feel free to modify them if you've reason/evidence for an alternative.
2242 if (CStyle && SrcType->isIntegralType(Ctx: Self.Context)
2243 && !SrcType->isBooleanType()
2244 && !SrcType->isEnumeralType()
2245 && !SrcExpr->isIntegerConstantExpr(Ctx: Self.Context)
2246 && Self.Context.getTypeSize(T: DestType) >
2247 Self.Context.getTypeSize(T: SrcType)) {
2248 // Separate between casts to void* and non-void* pointers.
2249 // Some APIs use (abuse) void* for something like a user context,
2250 // and often that value is an integer even if it isn't a pointer itself.
2251 // Having a separate warning flag allows users to control the warning
2252 // for their workflow.
2253 unsigned Diag = DestType->isVoidPointerType() ?
2254 diag::warn_int_to_void_pointer_cast
2255 : diag::warn_int_to_pointer_cast;
2256 Self.Diag(Loc: OpRange.getBegin(), DiagID: Diag) << SrcType << DestType << OpRange;
2257 }
2258}
2259
2260static bool fixOverloadedReinterpretCastExpr(Sema &Self, QualType DestType,
2261 ExprResult &Result) {
2262 // We can only fix an overloaded reinterpret_cast if
2263 // - it is a template with explicit arguments that resolves to an lvalue
2264 // unambiguously, or
2265 // - it is the only function in an overload set that may have its address
2266 // taken.
2267
2268 Expr *E = Result.get();
2269 // TODO: what if this fails because of DiagnoseUseOfDecl or something
2270 // like it?
2271 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
2272 SrcExpr&: Result,
2273 DoFunctionPointerConversion: Expr::getValueKindForType(T: DestType) ==
2274 VK_PRValue // Convert Fun to Ptr
2275 ) &&
2276 Result.isUsable())
2277 return true;
2278
2279 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
2280 // preserves Result.
2281 Result = E;
2282 if (!Self.resolveAndFixAddressOfSingleOverloadCandidate(
2283 SrcExpr&: Result, /*DoFunctionPointerConversion=*/true))
2284 return false;
2285 return Result.isUsable();
2286}
2287
2288static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
2289 QualType DestType, bool CStyle,
2290 CastOperation::OpRangeType OpRange,
2291 unsigned &msg, CastKind &Kind) {
2292 bool IsLValueCast = false;
2293
2294 DestType = Self.Context.getCanonicalType(T: DestType);
2295 QualType SrcType = SrcExpr.get()->getType();
2296
2297 // Is the source an overloaded name? (i.e. &foo)
2298 // If so, reinterpret_cast generally can not help us here (13.4, p1, bullet 5)
2299 if (SrcType == Self.Context.OverloadTy) {
2300 ExprResult FixedExpr = SrcExpr;
2301 if (!fixOverloadedReinterpretCastExpr(Self, DestType, Result&: FixedExpr))
2302 return TC_NotApplicable;
2303
2304 assert(FixedExpr.isUsable() && "Invalid result fixing overloaded expr");
2305 SrcExpr = FixedExpr;
2306 SrcType = SrcExpr.get()->getType();
2307 }
2308
2309 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
2310 if (!SrcExpr.get()->isGLValue()) {
2311 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
2312 // similar comment in const_cast.
2313 msg = diag::err_bad_cxx_cast_rvalue;
2314 return TC_NotApplicable;
2315 }
2316
2317 if (!CStyle) {
2318 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
2319 /*IsDereference=*/false, Range: OpRange);
2320 }
2321
2322 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
2323 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
2324 // built-in & and * operators.
2325
2326 const char *inappropriate = nullptr;
2327 switch (SrcExpr.get()->getObjectKind()) {
2328 case OK_Ordinary:
2329 break;
2330 case OK_BitField:
2331 msg = diag::err_bad_cxx_cast_bitfield;
2332 return TC_NotApplicable;
2333 // FIXME: Use a specific diagnostic for the rest of these cases.
2334 case OK_VectorComponent: inappropriate = "vector element"; break;
2335 case OK_MatrixComponent:
2336 inappropriate = "matrix element";
2337 break;
2338 case OK_ObjCProperty: inappropriate = "property expression"; break;
2339 case OK_ObjCSubscript: inappropriate = "container subscripting expression";
2340 break;
2341 }
2342 if (inappropriate) {
2343 Self.Diag(Loc: OpRange.getBegin(), DiagID: diag::err_bad_reinterpret_cast_reference)
2344 << inappropriate << DestType
2345 << OpRange << SrcExpr.get()->getSourceRange();
2346 msg = 0; SrcExpr = ExprError();
2347 return TC_NotApplicable;
2348 }
2349
2350 // This code does this transformation for the checked types.
2351 DestType = Self.Context.getPointerType(T: DestTypeTmp->getPointeeType());
2352 SrcType = Self.Context.getPointerType(T: SrcType);
2353
2354 IsLValueCast = true;
2355 }
2356
2357 // Canonicalize source for comparison.
2358 SrcType = Self.Context.getCanonicalType(T: SrcType);
2359
2360 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
2361 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
2362 if (DestMemPtr && SrcMemPtr) {
2363 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
2364 // can be explicitly converted to an rvalue of type "pointer to member
2365 // of Y of type T2" if T1 and T2 are both function types or both object
2366 // types.
2367 if (DestMemPtr->isMemberFunctionPointer() !=
2368 SrcMemPtr->isMemberFunctionPointer())
2369 return TC_NotApplicable;
2370
2371 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2372 // We need to determine the inheritance model that the class will use if
2373 // haven't yet.
2374 (void)Self.isCompleteType(Loc: OpRange.getBegin(), T: SrcType);
2375 (void)Self.isCompleteType(Loc: OpRange.getBegin(), T: DestType);
2376 }
2377
2378 // Don't allow casting between member pointers of different sizes.
2379 if (Self.Context.getTypeSize(T: DestMemPtr) !=
2380 Self.Context.getTypeSize(T: SrcMemPtr)) {
2381 msg = diag::err_bad_cxx_cast_member_pointer_size;
2382 return TC_Failed;
2383 }
2384
2385 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
2386 // constness.
2387 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
2388 // we accept it.
2389 if (auto CACK =
2390 CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
2391 /*CheckObjCLifetime=*/CStyle))
2392 return getCastAwayConstnessCastKind(CACK, DiagID&: msg);
2393
2394 // A valid member pointer cast.
2395 assert(!IsLValueCast);
2396 Kind = CK_ReinterpretMemberPointer;
2397 return TC_Success;
2398 }
2399
2400 // See below for the enumeral issue.
2401 if (SrcType->isNullPtrType() && DestType->isIntegralType(Ctx: Self.Context)) {
2402 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
2403 // type large enough to hold it. A value of std::nullptr_t can be
2404 // converted to an integral type; the conversion has the same meaning
2405 // and validity as a conversion of (void*)0 to the integral type.
2406 if (Self.Context.getTypeSize(T: SrcType) >
2407 Self.Context.getTypeSize(T: DestType)) {
2408 msg = diag::err_bad_reinterpret_cast_small_int;
2409 return TC_Failed;
2410 }
2411 Kind = CK_PointerToIntegral;
2412 return TC_Success;
2413 }
2414
2415 // Allow reinterpret_casts between vectors of the same size and
2416 // between vectors and integers of the same size.
2417 bool destIsVector = DestType->isVectorType();
2418 bool srcIsVector = SrcType->isVectorType();
2419 if (srcIsVector || destIsVector) {
2420 // Allow bitcasting between SVE VLATs and VLSTs, and vice-versa.
2421 if (Self.isValidSveBitcast(srcType: SrcType, destType: DestType)) {
2422 Kind = CK_BitCast;
2423 return TC_Success;
2424 }
2425
2426 // Allow bitcasting between SVE VLATs and VLSTs, and vice-versa.
2427 if (Self.RISCV().isValidRVVBitcast(srcType: SrcType, destType: DestType)) {
2428 Kind = CK_BitCast;
2429 return TC_Success;
2430 }
2431
2432 // The non-vector type, if any, must have integral type. This is
2433 // the same rule that C vector casts use; note, however, that enum
2434 // types are not integral in C++.
2435 if ((!destIsVector && !DestType->isIntegralType(Ctx: Self.Context)) ||
2436 (!srcIsVector && !SrcType->isIntegralType(Ctx: Self.Context)))
2437 return TC_NotApplicable;
2438
2439 // The size we want to consider is eltCount * eltSize.
2440 // That's exactly what the lax-conversion rules will check.
2441 if (Self.areLaxCompatibleVectorTypes(srcType: SrcType, destType: DestType)) {
2442 Kind = CK_BitCast;
2443 return TC_Success;
2444 }
2445
2446 if (Self.LangOpts.OpenCL && !CStyle) {
2447 if (DestType->isExtVectorType() || SrcType->isExtVectorType()) {
2448 // FIXME: Allow for reinterpret cast between 3 and 4 element vectors
2449 if (Self.areVectorTypesSameSize(srcType: SrcType, destType: DestType)) {
2450 Kind = CK_BitCast;
2451 return TC_Success;
2452 }
2453 }
2454 }
2455
2456 // Otherwise, pick a reasonable diagnostic.
2457 if (!destIsVector)
2458 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
2459 else if (!srcIsVector)
2460 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
2461 else
2462 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
2463
2464 return TC_Failed;
2465 }
2466
2467 if (SrcType == DestType) {
2468 // C++ 5.2.10p2 has a note that mentions that, subject to all other
2469 // restrictions, a cast to the same type is allowed so long as it does not
2470 // cast away constness. In C++98, the intent was not entirely clear here,
2471 // since all other paragraphs explicitly forbid casts to the same type.
2472 // C++11 clarifies this case with p2.
2473 //
2474 // The only allowed types are: integral, enumeration, pointer, or
2475 // pointer-to-member types. We also won't restrict Obj-C pointers either.
2476 Kind = CK_NoOp;
2477 TryCastResult Result = TC_NotApplicable;
2478 if (SrcType->isIntegralOrEnumerationType() ||
2479 SrcType->isAnyPointerType() ||
2480 SrcType->isMemberPointerType() ||
2481 SrcType->isBlockPointerType()) {
2482 Result = TC_Success;
2483 }
2484 return Result;
2485 }
2486
2487 bool destIsPtr = DestType->isAnyPointerType() ||
2488 DestType->isBlockPointerType();
2489 bool srcIsPtr = SrcType->isAnyPointerType() ||
2490 SrcType->isBlockPointerType();
2491 if (!destIsPtr && !srcIsPtr) {
2492 // Except for std::nullptr_t->integer and lvalue->reference, which are
2493 // handled above, at least one of the two arguments must be a pointer.
2494 return TC_NotApplicable;
2495 }
2496
2497 if (DestType->isIntegralType(Ctx: Self.Context)) {
2498 assert(srcIsPtr && "One type must be a pointer");
2499 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
2500 // type large enough to hold it; except in Microsoft mode, where the
2501 // integral type size doesn't matter (except we don't allow bool).
2502 if ((Self.Context.getTypeSize(T: SrcType) >
2503 Self.Context.getTypeSize(T: DestType))) {
2504 bool MicrosoftException =
2505 Self.getLangOpts().MicrosoftExt && !DestType->isBooleanType();
2506 if (MicrosoftException) {
2507 unsigned Diag = SrcType->isVoidPointerType()
2508 ? diag::warn_void_pointer_to_int_cast
2509 : diag::warn_pointer_to_int_cast;
2510 Self.Diag(Loc: OpRange.getBegin(), DiagID: Diag) << SrcType << DestType << OpRange;
2511 } else {
2512 msg = diag::err_bad_reinterpret_cast_small_int;
2513 return TC_Failed;
2514 }
2515 }
2516 Kind = CK_PointerToIntegral;
2517 return TC_Success;
2518 }
2519
2520 if (SrcType->isIntegralOrEnumerationType()) {
2521 assert(destIsPtr && "One type must be a pointer");
2522 checkIntToPointerCast(CStyle, OpRange, SrcExpr: SrcExpr.get(), DestType, Self);
2523 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
2524 // converted to a pointer.
2525 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
2526 // necessarily converted to a null pointer value.]
2527 Kind = CK_IntegralToPointer;
2528 return TC_Success;
2529 }
2530
2531 if (!destIsPtr || !srcIsPtr) {
2532 // With the valid non-pointer conversions out of the way, we can be even
2533 // more stringent.
2534 return TC_NotApplicable;
2535 }
2536
2537 // Cannot convert between block pointers and Objective-C object pointers.
2538 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
2539 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
2540 return TC_NotApplicable;
2541
2542 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
2543 // The C-style cast operator can.
2544 TryCastResult SuccessResult = TC_Success;
2545 if (auto CACK =
2546 CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
2547 /*CheckObjCLifetime=*/CStyle))
2548 SuccessResult = getCastAwayConstnessCastKind(CACK, DiagID&: msg);
2549
2550 if (IsAddressSpaceConversion(SrcType, DestType)) {
2551 Kind = CK_AddressSpaceConversion;
2552 assert(SrcType->isPointerType() && DestType->isPointerType());
2553 if (!CStyle &&
2554 !DestType->getPointeeType().getQualifiers().isAddressSpaceSupersetOf(
2555 other: SrcType->getPointeeType().getQualifiers(), Ctx: Self.getASTContext())) {
2556 SuccessResult = TC_Failed;
2557 }
2558 } else if (IsLValueCast) {
2559 Kind = CK_LValueBitCast;
2560 } else if (DestType->isObjCObjectPointerType()) {
2561 Kind = Self.ObjC().PrepareCastToObjCObjectPointer(E&: SrcExpr);
2562 } else if (DestType->isBlockPointerType()) {
2563 if (!SrcType->isBlockPointerType()) {
2564 Kind = CK_AnyPointerToBlockPointerCast;
2565 } else {
2566 Kind = CK_BitCast;
2567 }
2568 } else {
2569 Kind = CK_BitCast;
2570 }
2571
2572 // Any pointer can be cast to an Objective-C pointer type with a C-style
2573 // cast.
2574 if (CStyle && DestType->isObjCObjectPointerType()) {
2575 return SuccessResult;
2576 }
2577 if (CStyle)
2578 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
2579
2580 DiagnoseCallingConvCast(Self, SrcExpr, DstType: DestType, OpRange);
2581
2582 // Not casting away constness, so the only remaining check is for compatible
2583 // pointer categories.
2584
2585 if (SrcType->isFunctionPointerType()) {
2586 if (DestType->isFunctionPointerType()) {
2587 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
2588 // a pointer to a function of a different type.
2589 return SuccessResult;
2590 }
2591
2592 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
2593 // an object type or vice versa is conditionally-supported.
2594 // Compilers support it in C++03 too, though, because it's necessary for
2595 // casting the return value of dlsym() and GetProcAddress().
2596 // FIXME: Conditionally-supported behavior should be configurable in the
2597 // TargetInfo or similar.
2598 Self.Diag(Loc: OpRange.getBegin(),
2599 DiagID: Self.getLangOpts().CPlusPlus11 ?
2600 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2601 << OpRange;
2602 return SuccessResult;
2603 }
2604
2605 if (DestType->isFunctionPointerType()) {
2606 // See above.
2607 Self.Diag(Loc: OpRange.getBegin(),
2608 DiagID: Self.getLangOpts().CPlusPlus11 ?
2609 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2610 << OpRange;
2611 return SuccessResult;
2612 }
2613
2614 // Diagnose address space conversion in nested pointers.
2615 QualType DestPtee = DestType->getPointeeType().isNull()
2616 ? DestType->getPointeeType()
2617 : DestType->getPointeeType()->getPointeeType();
2618 QualType SrcPtee = SrcType->getPointeeType().isNull()
2619 ? SrcType->getPointeeType()
2620 : SrcType->getPointeeType()->getPointeeType();
2621 while (!DestPtee.isNull() && !SrcPtee.isNull()) {
2622 if (DestPtee.getAddressSpace() != SrcPtee.getAddressSpace()) {
2623 Self.Diag(Loc: OpRange.getBegin(),
2624 DiagID: diag::warn_bad_cxx_cast_nested_pointer_addr_space)
2625 << CStyle << SrcType << DestType << SrcExpr.get()->getSourceRange();
2626 break;
2627 }
2628 DestPtee = DestPtee->getPointeeType();
2629 SrcPtee = SrcPtee->getPointeeType();
2630 }
2631
2632 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
2633 // a pointer to an object of different type.
2634 // Void pointers are not specified, but supported by every compiler out there.
2635 // So we finish by allowing everything that remains - it's got to be two
2636 // object pointers.
2637 return SuccessResult;
2638}
2639
2640static TryCastResult TryAddressSpaceCast(Sema &Self, ExprResult &SrcExpr,
2641 QualType DestType, bool CStyle,
2642 unsigned &msg, CastKind &Kind) {
2643 if (!Self.getLangOpts().OpenCL && !Self.getLangOpts().SYCLIsDevice)
2644 // FIXME: As compiler doesn't have any information about overlapping addr
2645 // spaces at the moment we have to be permissive here.
2646 return TC_NotApplicable;
2647 // Even though the logic below is general enough and can be applied to
2648 // non-OpenCL mode too, we fast-path above because no other languages
2649 // define overlapping address spaces currently.
2650 auto SrcType = SrcExpr.get()->getType();
2651 // FIXME: Should this be generalized to references? The reference parameter
2652 // however becomes a reference pointee type here and therefore rejected.
2653 // Perhaps this is the right behavior though according to C++.
2654 auto SrcPtrType = SrcType->getAs<PointerType>();
2655 if (!SrcPtrType)
2656 return TC_NotApplicable;
2657 auto DestPtrType = DestType->getAs<PointerType>();
2658 if (!DestPtrType)
2659 return TC_NotApplicable;
2660 auto SrcPointeeType = SrcPtrType->getPointeeType();
2661 auto DestPointeeType = DestPtrType->getPointeeType();
2662 if (!DestPointeeType.isAddressSpaceOverlapping(T: SrcPointeeType,
2663 Ctx: Self.getASTContext())) {
2664 msg = diag::err_bad_cxx_cast_addr_space_mismatch;
2665 return TC_Failed;
2666 }
2667 auto SrcPointeeTypeWithoutAS =
2668 Self.Context.removeAddrSpaceQualType(T: SrcPointeeType.getCanonicalType());
2669 auto DestPointeeTypeWithoutAS =
2670 Self.Context.removeAddrSpaceQualType(T: DestPointeeType.getCanonicalType());
2671 if (Self.Context.hasSameType(T1: SrcPointeeTypeWithoutAS,
2672 T2: DestPointeeTypeWithoutAS)) {
2673 Kind = SrcPointeeType.getAddressSpace() == DestPointeeType.getAddressSpace()
2674 ? CK_NoOp
2675 : CK_AddressSpaceConversion;
2676 return TC_Success;
2677 } else {
2678 return TC_NotApplicable;
2679 }
2680}
2681
2682void CastOperation::checkAddressSpaceCast(QualType SrcType, QualType DestType) {
2683 // In OpenCL only conversions between pointers to objects in overlapping
2684 // addr spaces are allowed. v2.0 s6.5.5 - Generic addr space overlaps
2685 // with any named one, except for constant.
2686
2687 // Converting the top level pointee addrspace is permitted for compatible
2688 // addrspaces (such as 'generic int *' to 'local int *' or vice versa), but
2689 // if any of the nested pointee addrspaces differ, we emit a warning
2690 // regardless of addrspace compatibility. This makes
2691 // local int ** p;
2692 // return (generic int **) p;
2693 // warn even though local -> generic is permitted.
2694 if (Self.getLangOpts().OpenCL) {
2695 const Type *DestPtr, *SrcPtr;
2696 bool Nested = false;
2697 unsigned DiagID = diag::err_typecheck_incompatible_address_space;
2698 DestPtr = Self.getASTContext().getCanonicalType(T: DestType.getTypePtr()),
2699 SrcPtr = Self.getASTContext().getCanonicalType(T: SrcType.getTypePtr());
2700
2701 while (isa<PointerType>(Val: DestPtr) && isa<PointerType>(Val: SrcPtr)) {
2702 const PointerType *DestPPtr = cast<PointerType>(Val: DestPtr);
2703 const PointerType *SrcPPtr = cast<PointerType>(Val: SrcPtr);
2704 QualType DestPPointee = DestPPtr->getPointeeType();
2705 QualType SrcPPointee = SrcPPtr->getPointeeType();
2706 if (Nested
2707 ? DestPPointee.getAddressSpace() != SrcPPointee.getAddressSpace()
2708 : !DestPPointee.isAddressSpaceOverlapping(T: SrcPPointee,
2709 Ctx: Self.getASTContext())) {
2710 Self.Diag(Loc: OpRange.getBegin(), DiagID)
2711 << SrcType << DestType << AssignmentAction::Casting
2712 << SrcExpr.get()->getSourceRange();
2713 if (!Nested)
2714 SrcExpr = ExprError();
2715 return;
2716 }
2717
2718 DestPtr = DestPPtr->getPointeeType().getTypePtr();
2719 SrcPtr = SrcPPtr->getPointeeType().getTypePtr();
2720 Nested = true;
2721 DiagID = diag::ext_nested_pointer_qualifier_mismatch;
2722 }
2723 }
2724}
2725
2726bool Sema::ShouldSplatAltivecScalarInCast(const VectorType *VecTy) {
2727 bool SrcCompatXL = this->getLangOpts().getAltivecSrcCompat() ==
2728 LangOptions::AltivecSrcCompatKind::XL;
2729 VectorKind VKind = VecTy->getVectorKind();
2730
2731 if ((VKind == VectorKind::AltiVecVector) ||
2732 (SrcCompatXL && ((VKind == VectorKind::AltiVecBool) ||
2733 (VKind == VectorKind::AltiVecPixel)))) {
2734 return true;
2735 }
2736 return false;
2737}
2738
2739bool Sema::CheckAltivecInitFromScalar(SourceRange R, QualType VecTy,
2740 QualType SrcTy) {
2741 bool SrcCompatGCC = this->getLangOpts().getAltivecSrcCompat() ==
2742 LangOptions::AltivecSrcCompatKind::GCC;
2743 if (this->getLangOpts().AltiVec && SrcCompatGCC) {
2744 this->Diag(Loc: R.getBegin(),
2745 DiagID: diag::err_invalid_conversion_between_vector_and_integer)
2746 << VecTy << SrcTy << R;
2747 return true;
2748 }
2749 return false;
2750}
2751
2752void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
2753 bool ListInitialization) {
2754 assert(Self.getLangOpts().CPlusPlus);
2755
2756 // Handle placeholders.
2757 if (isPlaceholder()) {
2758 // C-style casts can resolve __unknown_any types.
2759 if (claimPlaceholder(K: BuiltinType::UnknownAny)) {
2760 SrcExpr = Self.checkUnknownAnyCast(TypeRange: DestRange, CastType: DestType,
2761 CastExpr: SrcExpr.get(), CastKind&: Kind,
2762 VK&: ValueKind, Path&: BasePath);
2763 return;
2764 }
2765
2766 checkNonOverloadPlaceholders();
2767 if (SrcExpr.isInvalid())
2768 return;
2769 }
2770
2771 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
2772 // This test is outside everything else because it's the only case where
2773 // a non-lvalue-reference target type does not lead to decay.
2774 if (DestType->isVoidType()) {
2775 Kind = CK_ToVoid;
2776
2777 if (claimPlaceholder(K: BuiltinType::Overload)) {
2778 Self.ResolveAndFixSingleFunctionTemplateSpecialization(
2779 SrcExpr, /* Decay Function to ptr */ DoFunctionPointerConversion: false,
2780 /* Complain */ true, OpRangeForComplaining: DestRange, DestTypeForComplaining: DestType,
2781 DiagIDForComplaining: diag::err_bad_cstyle_cast_overload);
2782 if (SrcExpr.isInvalid())
2783 return;
2784 }
2785
2786 SrcExpr = Self.IgnoredValueConversions(E: SrcExpr.get());
2787 return;
2788 }
2789
2790 // If the type is dependent, we won't do any other semantic analysis now.
2791 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
2792 SrcExpr.get()->isValueDependent()) {
2793 assert(Kind == CK_Dependent);
2794 return;
2795 }
2796
2797 CheckedConversionKind CCK = FunctionalStyle
2798 ? CheckedConversionKind::FunctionalCast
2799 : CheckedConversionKind::CStyleCast;
2800 if (Self.getLangOpts().HLSL) {
2801 if (CheckHLSLCStyleCast(CCK))
2802 return;
2803 }
2804
2805 if (ValueKind == VK_PRValue && !DestType->isRecordType() &&
2806 !isPlaceholder(K: BuiltinType::Overload)) {
2807 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(E: SrcExpr.get());
2808 if (SrcExpr.isInvalid())
2809 return;
2810 }
2811
2812 // AltiVec vector initialization with a single literal.
2813 if (const VectorType *vecTy = DestType->getAs<VectorType>()) {
2814 if (Self.CheckAltivecInitFromScalar(R: OpRange, VecTy: DestType,
2815 SrcTy: SrcExpr.get()->getType())) {
2816 SrcExpr = ExprError();
2817 return;
2818 }
2819 if (Self.ShouldSplatAltivecScalarInCast(VecTy: vecTy) &&
2820 (SrcExpr.get()->getType()->isIntegerType() ||
2821 SrcExpr.get()->getType()->isFloatingType())) {
2822 Kind = CK_VectorSplat;
2823 SrcExpr = Self.prepareVectorSplat(VectorTy: DestType, SplattedExpr: SrcExpr.get());
2824 return;
2825 }
2826 }
2827
2828 // WebAssembly tables cannot be cast.
2829 QualType SrcType = SrcExpr.get()->getType();
2830 if (SrcType->isWebAssemblyTableType()) {
2831 Self.Diag(Loc: OpRange.getBegin(), DiagID: diag::err_wasm_cast_table)
2832 << 1 << SrcExpr.get()->getSourceRange();
2833 SrcExpr = ExprError();
2834 return;
2835 }
2836
2837 // C++ [expr.cast]p5: The conversions performed by
2838 // - a const_cast,
2839 // - a static_cast,
2840 // - a static_cast followed by a const_cast,
2841 // - a reinterpret_cast, or
2842 // - a reinterpret_cast followed by a const_cast,
2843 // can be performed using the cast notation of explicit type conversion.
2844 // [...] If a conversion can be interpreted in more than one of the ways
2845 // listed above, the interpretation that appears first in the list is used,
2846 // even if a cast resulting from that interpretation is ill-formed.
2847 // In plain language, this means trying a const_cast ...
2848 // Note that for address space we check compatibility after const_cast.
2849 unsigned msg = diag::err_bad_cxx_cast_generic;
2850 TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
2851 /*CStyle*/ true, msg);
2852 if (SrcExpr.isInvalid())
2853 return;
2854 if (isValidCast(TCR: tcr))
2855 Kind = CK_NoOp;
2856
2857 if (tcr == TC_NotApplicable) {
2858 tcr = TryAddressSpaceCast(Self, SrcExpr, DestType, /*CStyle*/ true, msg,
2859 Kind);
2860 if (SrcExpr.isInvalid())
2861 return;
2862
2863 if (tcr == TC_NotApplicable) {
2864 // ... or if that is not possible, a static_cast, ignoring const and
2865 // addr space, ...
2866 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange, msg, Kind,
2867 BasePath, ListInitialization);
2868 if (SrcExpr.isInvalid())
2869 return;
2870
2871 if (tcr == TC_NotApplicable) {
2872 // ... and finally a reinterpret_cast, ignoring const and addr space.
2873 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/ true,
2874 OpRange, msg, Kind);
2875 if (SrcExpr.isInvalid())
2876 return;
2877 }
2878 }
2879 }
2880
2881 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
2882 isValidCast(TCR: tcr))
2883 checkObjCConversion(CCK);
2884
2885 if (tcr != TC_Success && msg != 0) {
2886 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
2887 DeclAccessPair Found;
2888 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(AddressOfExpr: SrcExpr.get(),
2889 TargetType: DestType,
2890 /*Complain*/ true,
2891 Found);
2892 if (Fn) {
2893 // If DestType is a function type (not to be confused with the function
2894 // pointer type), it will be possible to resolve the function address,
2895 // but the type cast should be considered as failure.
2896 OverloadExpr *OE = OverloadExpr::find(E: SrcExpr.get()).Expression;
2897 Self.Diag(Loc: OpRange.getBegin(), DiagID: diag::err_bad_cstyle_cast_overload)
2898 << OE->getName() << DestType << OpRange
2899 << OE->getQualifierLoc().getSourceRange();
2900 Self.NoteAllOverloadCandidates(E: SrcExpr.get());
2901 }
2902 } else {
2903 diagnoseBadCast(S&: Self, msg, castType: (FunctionalStyle ? CT_Functional : CT_CStyle),
2904 opRange: OpRange, src: SrcExpr.get(), destType: DestType, listInitialization: ListInitialization);
2905 }
2906 }
2907
2908 if (isValidCast(TCR: tcr)) {
2909 if (Kind == CK_BitCast)
2910 checkCastAlign();
2911
2912 if (unsigned DiagID = checkCastFunctionType(Self, SrcExpr, DestType))
2913 Self.Diag(Loc: OpRange.getBegin(), DiagID)
2914 << SrcExpr.get()->getType() << DestType << OpRange;
2915
2916 } else {
2917 SrcExpr = ExprError();
2918 }
2919}
2920
2921// CheckHLSLCStyleCast - Returns `true` ihe cast is handled or errored as an
2922// HLSL-specific cast. Returns false if the cast should be checked as a CXX
2923// C-Style cast.
2924bool CastOperation::CheckHLSLCStyleCast(CheckedConversionKind CCK) {
2925 assert(Self.getLangOpts().HLSL && "Must be HLSL!");
2926 QualType SrcTy = SrcExpr.get()->getType();
2927 // HLSL has several unique forms of C-style casts which support aggregate to
2928 // aggregate casting.
2929 // This case should not trigger on regular vector cast, vector truncation
2930 if (Self.HLSL().CanPerformElementwiseCast(Src: SrcExpr.get(), DestType)) {
2931 if (SrcTy->isConstantArrayType())
2932 SrcExpr = Self.ImpCastExprToType(
2933 E: SrcExpr.get(), Type: Self.Context.getArrayParameterType(Ty: SrcTy),
2934 CK: CK_HLSLArrayRValue, VK: VK_PRValue, BasePath: nullptr, CCK);
2935 Kind = CK_HLSLElementwiseCast;
2936 return true;
2937 }
2938
2939 // This case should not trigger on regular vector splat
2940 // If the relative order of this and the HLSLElementWise cast checks
2941 // are changed, it might change which cast handles what in a few cases
2942 if (Self.HLSL().CanPerformAggregateSplatCast(Src: SrcExpr.get(), DestType)) {
2943 const VectorType *VT = SrcTy->getAs<VectorType>();
2944 // change splat from vec1 case to splat from scalar
2945 if (VT && VT->getNumElements() == 1)
2946 SrcExpr = Self.ImpCastExprToType(
2947 E: SrcExpr.get(), Type: VT->getElementType(), CK: CK_HLSLVectorTruncation,
2948 VK: SrcExpr.get()->getValueKind(), BasePath: nullptr, CCK);
2949 // Inserting a scalar cast here allows for a simplified codegen in
2950 // the case the destTy is a vector
2951 if (const VectorType *DVT = DestType->getAs<VectorType>())
2952 SrcExpr = Self.ImpCastExprToType(
2953 E: SrcExpr.get(), Type: DVT->getElementType(),
2954 CK: Self.PrepareScalarCast(src&: SrcExpr, destType: DVT->getElementType()),
2955 VK: SrcExpr.get()->getValueKind(), BasePath: nullptr, CCK);
2956 Kind = CK_HLSLAggregateSplatCast;
2957 return true;
2958 }
2959
2960 // If the destination is an array, we've exhausted the valid HLSL casts, so we
2961 // should emit a dignostic and stop processing.
2962 if (DestType->isArrayType()) {
2963 Self.Diag(Loc: OpRange.getBegin(), DiagID: diag::err_bad_cxx_cast_generic)
2964 << 4 << SrcTy << DestType;
2965 SrcExpr = ExprError();
2966 return true;
2967 }
2968 return false;
2969}
2970
2971/// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
2972/// non-matching type. Such as enum function call to int, int call to
2973/// pointer; etc. Cast to 'void' is an exception.
2974static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
2975 QualType DestType) {
2976 if (Self.Diags.isIgnored(DiagID: diag::warn_bad_function_cast,
2977 Loc: SrcExpr.get()->getExprLoc()))
2978 return;
2979
2980 if (!isa<CallExpr>(Val: SrcExpr.get()))
2981 return;
2982
2983 QualType SrcType = SrcExpr.get()->getType();
2984 if (DestType.getUnqualifiedType()->isVoidType())
2985 return;
2986 if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
2987 && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
2988 return;
2989 if (SrcType->isIntegerType() && DestType->isIntegerType() &&
2990 (SrcType->isBooleanType() == DestType->isBooleanType()) &&
2991 (SrcType->isEnumeralType() == DestType->isEnumeralType()))
2992 return;
2993 if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
2994 return;
2995 if (SrcType->isEnumeralType() && DestType->isEnumeralType())
2996 return;
2997 if (SrcType->isComplexType() && DestType->isComplexType())
2998 return;
2999 if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
3000 return;
3001 if (SrcType->isFixedPointType() && DestType->isFixedPointType())
3002 return;
3003
3004 Self.Diag(Loc: SrcExpr.get()->getExprLoc(),
3005 DiagID: diag::warn_bad_function_cast)
3006 << SrcType << DestType << SrcExpr.get()->getSourceRange();
3007}
3008
3009/// Check the semantics of a C-style cast operation, in C.
3010void CastOperation::CheckCStyleCast() {
3011 assert(!Self.getLangOpts().CPlusPlus);
3012
3013 // C-style casts can resolve __unknown_any types.
3014 if (claimPlaceholder(K: BuiltinType::UnknownAny)) {
3015 SrcExpr = Self.checkUnknownAnyCast(TypeRange: DestRange, CastType: DestType,
3016 CastExpr: SrcExpr.get(), CastKind&: Kind,
3017 VK&: ValueKind, Path&: BasePath);
3018 return;
3019 }
3020
3021 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3022 // type needs to be scalar.
3023 if (DestType->isVoidType()) {
3024 // We don't necessarily do lvalue-to-rvalue conversions on this.
3025 SrcExpr = Self.IgnoredValueConversions(E: SrcExpr.get());
3026 if (SrcExpr.isInvalid())
3027 return;
3028
3029 // Cast to void allows any expr type.
3030 Kind = CK_ToVoid;
3031 return;
3032 }
3033
3034 // If the type is dependent, we won't do any other semantic analysis now.
3035 if (Self.getASTContext().isDependenceAllowed() &&
3036 (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
3037 SrcExpr.get()->isValueDependent())) {
3038 assert((DestType->containsErrors() || SrcExpr.get()->containsErrors() ||
3039 SrcExpr.get()->containsErrors()) &&
3040 "should only occur in error-recovery path.");
3041 assert(Kind == CK_Dependent);
3042 return;
3043 }
3044
3045 // Overloads are allowed with C extensions, so we need to support them.
3046 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
3047 DeclAccessPair DAP;
3048 if (FunctionDecl *FD = Self.ResolveAddressOfOverloadedFunction(
3049 AddressOfExpr: SrcExpr.get(), TargetType: DestType, /*Complain=*/true, Found&: DAP))
3050 SrcExpr = Self.FixOverloadedFunctionReference(E: SrcExpr.get(), FoundDecl: DAP, Fn: FD);
3051 else
3052 return;
3053 assert(SrcExpr.isUsable());
3054 }
3055 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(E: SrcExpr.get());
3056 if (SrcExpr.isInvalid())
3057 return;
3058 QualType SrcType = SrcExpr.get()->getType();
3059
3060 if (SrcType->isWebAssemblyTableType()) {
3061 Self.Diag(Loc: OpRange.getBegin(), DiagID: diag::err_wasm_cast_table)
3062 << 1 << SrcExpr.get()->getSourceRange();
3063 SrcExpr = ExprError();
3064 return;
3065 }
3066
3067 assert(!SrcType->isPlaceholderType());
3068
3069 checkAddressSpaceCast(SrcType, DestType);
3070 if (SrcExpr.isInvalid())
3071 return;
3072
3073 if (Self.RequireCompleteType(Loc: OpRange.getBegin(), T: DestType,
3074 DiagID: diag::err_typecheck_cast_to_incomplete)) {
3075 SrcExpr = ExprError();
3076 return;
3077 }
3078
3079 // Allow casting a sizeless built-in type to itself.
3080 if (DestType->isSizelessBuiltinType() &&
3081 Self.Context.hasSameUnqualifiedType(T1: DestType, T2: SrcType)) {
3082 Kind = CK_NoOp;
3083 return;
3084 }
3085
3086 // Allow bitcasting between compatible SVE vector types.
3087 if ((SrcType->isVectorType() || DestType->isVectorType()) &&
3088 Self.isValidSveBitcast(srcType: SrcType, destType: DestType)) {
3089 Kind = CK_BitCast;
3090 return;
3091 }
3092
3093 // Allow bitcasting between compatible RVV vector types.
3094 if ((SrcType->isVectorType() || DestType->isVectorType()) &&
3095 Self.RISCV().isValidRVVBitcast(srcType: SrcType, destType: DestType)) {
3096 Kind = CK_BitCast;
3097 return;
3098 }
3099
3100 if (!DestType->isScalarType() && !DestType->isVectorType() &&
3101 !DestType->isMatrixType()) {
3102 const RecordType *DestRecordTy = DestType->getAs<RecordType>();
3103
3104 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(T1: DestType, T2: SrcType)){
3105 // GCC struct/union extension: allow cast to self.
3106 Self.Diag(Loc: OpRange.getBegin(), DiagID: diag::ext_typecheck_cast_nonscalar)
3107 << DestType << SrcExpr.get()->getSourceRange();
3108 Kind = CK_NoOp;
3109 return;
3110 }
3111
3112 // GCC's cast to union extension.
3113 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
3114 RecordDecl *RD = DestRecordTy->getDecl();
3115 if (CastExpr::getTargetFieldForToUnionCast(RD, opType: SrcType)) {
3116 Self.Diag(Loc: OpRange.getBegin(), DiagID: diag::ext_typecheck_cast_to_union)
3117 << SrcExpr.get()->getSourceRange();
3118 Kind = CK_ToUnion;
3119 return;
3120 } else {
3121 Self.Diag(Loc: OpRange.getBegin(), DiagID: diag::err_typecheck_cast_to_union_no_type)
3122 << SrcType << SrcExpr.get()->getSourceRange();
3123 SrcExpr = ExprError();
3124 return;
3125 }
3126 }
3127
3128 // OpenCL v2.0 s6.13.10 - Allow casts from '0' to event_t type.
3129 if (Self.getLangOpts().OpenCL && DestType->isEventT()) {
3130 Expr::EvalResult Result;
3131 if (SrcExpr.get()->EvaluateAsInt(Result, Ctx: Self.Context)) {
3132 llvm::APSInt CastInt = Result.Val.getInt();
3133 if (0 == CastInt) {
3134 Kind = CK_ZeroToOCLOpaqueType;
3135 return;
3136 }
3137 Self.Diag(Loc: OpRange.getBegin(),
3138 DiagID: diag::err_opencl_cast_non_zero_to_event_t)
3139 << toString(I: CastInt, Radix: 10) << SrcExpr.get()->getSourceRange();
3140 SrcExpr = ExprError();
3141 return;
3142 }
3143 }
3144
3145 // Reject any other conversions to non-scalar types.
3146 Self.Diag(Loc: OpRange.getBegin(), DiagID: diag::err_typecheck_cond_expect_scalar)
3147 << DestType << SrcExpr.get()->getSourceRange();
3148 SrcExpr = ExprError();
3149 return;
3150 }
3151
3152 // The type we're casting to is known to be a scalar, a vector, or a matrix.
3153
3154 // Require the operand to be a scalar, a vector, or a matrix.
3155 if (!SrcType->isScalarType() && !SrcType->isVectorType() &&
3156 !SrcType->isMatrixType()) {
3157 Self.Diag(Loc: SrcExpr.get()->getExprLoc(),
3158 DiagID: diag::err_typecheck_expect_scalar_operand)
3159 << SrcType << SrcExpr.get()->getSourceRange();
3160 SrcExpr = ExprError();
3161 return;
3162 }
3163
3164 // C23 6.5.5p4:
3165 // ... The type nullptr_t shall not be converted to any type other than
3166 // void, bool or a pointer type.If the target type is nullptr_t, the cast
3167 // expression shall be a null pointer constant or have type nullptr_t.
3168 if (SrcType->isNullPtrType()) {
3169 // FIXME: 6.3.2.4p2 says that nullptr_t can be converted to itself, but
3170 // 6.5.4p4 is a constraint check and nullptr_t is not void, bool, or a
3171 // pointer type. We're not going to diagnose that as a constraint violation.
3172 if (!DestType->isVoidType() && !DestType->isBooleanType() &&
3173 !DestType->isPointerType() && !DestType->isNullPtrType()) {
3174 Self.Diag(Loc: SrcExpr.get()->getExprLoc(), DiagID: diag::err_nullptr_cast)
3175 << /*nullptr to type*/ 0 << DestType;
3176 SrcExpr = ExprError();
3177 return;
3178 }
3179 if (!DestType->isNullPtrType()) {
3180 // Implicitly cast from the null pointer type to the type of the
3181 // destination.
3182 CastKind CK = DestType->isPointerType() ? CK_NullToPointer : CK_BitCast;
3183 SrcExpr = ImplicitCastExpr::Create(Context: Self.Context, T: DestType, Kind: CK,
3184 Operand: SrcExpr.get(), BasePath: nullptr, Cat: VK_PRValue,
3185 FPO: Self.CurFPFeatureOverrides());
3186 }
3187 }
3188
3189 if (DestType->isNullPtrType() && !SrcType->isNullPtrType()) {
3190 if (!SrcExpr.get()->isNullPointerConstant(Ctx&: Self.Context,
3191 NPC: Expr::NPC_NeverValueDependent)) {
3192 Self.Diag(Loc: SrcExpr.get()->getExprLoc(), DiagID: diag::err_nullptr_cast)
3193 << /*type to nullptr*/ 1 << SrcType;
3194 SrcExpr = ExprError();
3195 return;
3196 }
3197 // Need to convert the source from whatever its type is to a null pointer
3198 // type first.
3199 SrcExpr = ImplicitCastExpr::Create(Context: Self.Context, T: DestType, Kind: CK_NullToPointer,
3200 Operand: SrcExpr.get(), BasePath: nullptr, Cat: VK_PRValue,
3201 FPO: Self.CurFPFeatureOverrides());
3202 }
3203
3204 if (DestType->isExtVectorType()) {
3205 SrcExpr = Self.CheckExtVectorCast(R: OpRange, DestTy: DestType, CastExpr: SrcExpr.get(), Kind);
3206 return;
3207 }
3208
3209 if (DestType->getAs<MatrixType>() || SrcType->getAs<MatrixType>()) {
3210 if (Self.CheckMatrixCast(R: OpRange, DestTy: DestType, SrcTy: SrcType, Kind))
3211 SrcExpr = ExprError();
3212 return;
3213 }
3214
3215 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
3216 if (Self.CheckAltivecInitFromScalar(R: OpRange, VecTy: DestType, SrcTy: SrcType)) {
3217 SrcExpr = ExprError();
3218 return;
3219 }
3220 if (Self.ShouldSplatAltivecScalarInCast(VecTy: DestVecTy) &&
3221 (SrcType->isIntegerType() || SrcType->isFloatingType())) {
3222 Kind = CK_VectorSplat;
3223 SrcExpr = Self.prepareVectorSplat(VectorTy: DestType, SplattedExpr: SrcExpr.get());
3224 } else if (Self.CheckVectorCast(R: OpRange, VectorTy: DestType, Ty: SrcType, Kind)) {
3225 SrcExpr = ExprError();
3226 }
3227 return;
3228 }
3229
3230 if (SrcType->isVectorType()) {
3231 if (Self.CheckVectorCast(R: OpRange, VectorTy: SrcType, Ty: DestType, Kind))
3232 SrcExpr = ExprError();
3233 return;
3234 }
3235
3236 // The source and target types are both scalars, i.e.
3237 // - arithmetic types (fundamental, enum, and complex)
3238 // - all kinds of pointers
3239 // Note that member pointers were filtered out with C++, above.
3240
3241 if (isa<ObjCSelectorExpr>(Val: SrcExpr.get())) {
3242 Self.Diag(Loc: SrcExpr.get()->getExprLoc(), DiagID: diag::err_cast_selector_expr);
3243 SrcExpr = ExprError();
3244 return;
3245 }
3246
3247 // If either type is a pointer, the other type has to be either an
3248 // integer or a pointer.
3249 if (!DestType->isArithmeticType()) {
3250 if (!SrcType->isIntegralType(Ctx: Self.Context) && SrcType->isArithmeticType()) {
3251 Self.Diag(Loc: SrcExpr.get()->getExprLoc(),
3252 DiagID: diag::err_cast_pointer_from_non_pointer_int)
3253 << SrcType << SrcExpr.get()->getSourceRange();
3254 SrcExpr = ExprError();
3255 return;
3256 }
3257 checkIntToPointerCast(/* CStyle */ true, OpRange, SrcExpr: SrcExpr.get(), DestType,
3258 Self);
3259 } else if (!SrcType->isArithmeticType()) {
3260 if (!DestType->isIntegralType(Ctx: Self.Context) &&
3261 DestType->isArithmeticType()) {
3262 Self.Diag(Loc: SrcExpr.get()->getBeginLoc(),
3263 DiagID: diag::err_cast_pointer_to_non_pointer_int)
3264 << DestType << SrcExpr.get()->getSourceRange();
3265 SrcExpr = ExprError();
3266 return;
3267 }
3268
3269 if ((Self.Context.getTypeSize(T: SrcType) >
3270 Self.Context.getTypeSize(T: DestType)) &&
3271 !DestType->isBooleanType()) {
3272 // C 6.3.2.3p6: Any pointer type may be converted to an integer type.
3273 // Except as previously specified, the result is implementation-defined.
3274 // If the result cannot be represented in the integer type, the behavior
3275 // is undefined. The result need not be in the range of values of any
3276 // integer type.
3277 unsigned Diag;
3278 if (SrcType->isVoidPointerType())
3279 Diag = DestType->isEnumeralType() ? diag::warn_void_pointer_to_enum_cast
3280 : diag::warn_void_pointer_to_int_cast;
3281 else if (DestType->isEnumeralType())
3282 Diag = diag::warn_pointer_to_enum_cast;
3283 else
3284 Diag = diag::warn_pointer_to_int_cast;
3285 Self.Diag(Loc: OpRange.getBegin(), DiagID: Diag) << SrcType << DestType << OpRange;
3286 }
3287 }
3288
3289 if (Self.getLangOpts().OpenCL && !Self.getOpenCLOptions().isAvailableOption(
3290 Ext: "cl_khr_fp16", LO: Self.getLangOpts())) {
3291 if (DestType->isHalfType()) {
3292 Self.Diag(Loc: SrcExpr.get()->getBeginLoc(), DiagID: diag::err_opencl_cast_to_half)
3293 << DestType << SrcExpr.get()->getSourceRange();
3294 SrcExpr = ExprError();
3295 return;
3296 }
3297 }
3298
3299 // ARC imposes extra restrictions on casts.
3300 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) {
3301 checkObjCConversion(CCK: CheckedConversionKind::CStyleCast);
3302 if (SrcExpr.isInvalid())
3303 return;
3304
3305 const PointerType *CastPtr = DestType->getAs<PointerType>();
3306 if (Self.getLangOpts().ObjCAutoRefCount && CastPtr) {
3307 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
3308 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
3309 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
3310 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
3311 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
3312 !CastQuals.compatiblyIncludesObjCLifetime(other: ExprQuals)) {
3313 Self.Diag(Loc: SrcExpr.get()->getBeginLoc(),
3314 DiagID: diag::err_typecheck_incompatible_ownership)
3315 << SrcType << DestType << AssignmentAction::Casting
3316 << SrcExpr.get()->getSourceRange();
3317 return;
3318 }
3319 }
3320 } else if (!Self.ObjC().CheckObjCARCUnavailableWeakConversion(castType: DestType,
3321 ExprType: SrcType)) {
3322 Self.Diag(Loc: SrcExpr.get()->getBeginLoc(),
3323 DiagID: diag::err_arc_convesion_of_weak_unavailable)
3324 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
3325 SrcExpr = ExprError();
3326 return;
3327 }
3328 }
3329
3330 if (unsigned DiagID = checkCastFunctionType(Self, SrcExpr, DestType))
3331 Self.Diag(Loc: OpRange.getBegin(), DiagID) << SrcType << DestType << OpRange;
3332
3333 if (isa<PointerType>(Val: SrcType) && isa<PointerType>(Val: DestType)) {
3334 QualType SrcTy = cast<PointerType>(Val&: SrcType)->getPointeeType();
3335 QualType DestTy = cast<PointerType>(Val&: DestType)->getPointeeType();
3336
3337 const RecordDecl *SrcRD = SrcTy->getAsRecordDecl();
3338 const RecordDecl *DestRD = DestTy->getAsRecordDecl();
3339
3340 if (SrcRD && DestRD && SrcRD->hasAttr<RandomizeLayoutAttr>() &&
3341 SrcRD != DestRD) {
3342 // The struct we are casting the pointer from was randomized.
3343 Self.Diag(Loc: OpRange.getBegin(), DiagID: diag::err_cast_from_randomized_struct)
3344 << SrcType << DestType;
3345 SrcExpr = ExprError();
3346 return;
3347 }
3348 }
3349
3350 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
3351 DiagnoseCallingConvCast(Self, SrcExpr, DstType: DestType, OpRange);
3352 DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
3353 Kind = Self.PrepareScalarCast(src&: SrcExpr, destType: DestType);
3354 if (SrcExpr.isInvalid())
3355 return;
3356
3357 if (Kind == CK_BitCast)
3358 checkCastAlign();
3359}
3360
3361void CastOperation::CheckBuiltinBitCast() {
3362 QualType SrcType = SrcExpr.get()->getType();
3363
3364 if (Self.RequireCompleteType(Loc: OpRange.getBegin(), T: DestType,
3365 DiagID: diag::err_typecheck_cast_to_incomplete) ||
3366 Self.RequireCompleteType(Loc: OpRange.getBegin(), T: SrcType,
3367 DiagID: diag::err_incomplete_type)) {
3368 SrcExpr = ExprError();
3369 return;
3370 }
3371
3372 if (SrcExpr.get()->isPRValue())
3373 SrcExpr = Self.CreateMaterializeTemporaryExpr(T: SrcType, Temporary: SrcExpr.get(),
3374 /*IsLValueReference=*/BoundToLvalueReference: false);
3375
3376 CharUnits DestSize = Self.Context.getTypeSizeInChars(T: DestType);
3377 CharUnits SourceSize = Self.Context.getTypeSizeInChars(T: SrcType);
3378 if (DestSize != SourceSize) {
3379 Self.Diag(Loc: OpRange.getBegin(), DiagID: diag::err_bit_cast_type_size_mismatch)
3380 << SrcType << DestType << (int)SourceSize.getQuantity()
3381 << (int)DestSize.getQuantity();
3382 SrcExpr = ExprError();
3383 return;
3384 }
3385
3386 if (!DestType.isTriviallyCopyableType(Context: Self.Context)) {
3387 Self.Diag(Loc: OpRange.getBegin(), DiagID: diag::err_bit_cast_non_trivially_copyable)
3388 << 1;
3389 SrcExpr = ExprError();
3390 return;
3391 }
3392
3393 if (!SrcType.isTriviallyCopyableType(Context: Self.Context)) {
3394 Self.Diag(Loc: OpRange.getBegin(), DiagID: diag::err_bit_cast_non_trivially_copyable)
3395 << 0;
3396 SrcExpr = ExprError();
3397 return;
3398 }
3399
3400 Kind = CK_LValueToRValueBitCast;
3401}
3402
3403/// DiagnoseCastQual - Warn whenever casts discards a qualifiers, be it either
3404/// const, volatile or both.
3405static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
3406 QualType DestType) {
3407 if (SrcExpr.isInvalid())
3408 return;
3409
3410 QualType SrcType = SrcExpr.get()->getType();
3411 if (!((SrcType->isAnyPointerType() && DestType->isAnyPointerType()) ||
3412 DestType->isLValueReferenceType()))
3413 return;
3414
3415 QualType TheOffendingSrcType, TheOffendingDestType;
3416 Qualifiers CastAwayQualifiers;
3417 if (CastsAwayConstness(Self, SrcType, DestType, CheckCVR: true, CheckObjCLifetime: false,
3418 TheOffendingSrcType: &TheOffendingSrcType, TheOffendingDestType: &TheOffendingDestType,
3419 CastAwayQualifiers: &CastAwayQualifiers) !=
3420 CastAwayConstnessKind::CACK_Similar)
3421 return;
3422
3423 // FIXME: 'restrict' is not properly handled here.
3424 int qualifiers = -1;
3425 if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) {
3426 qualifiers = 0;
3427 } else if (CastAwayQualifiers.hasConst()) {
3428 qualifiers = 1;
3429 } else if (CastAwayQualifiers.hasVolatile()) {
3430 qualifiers = 2;
3431 }
3432 // This is a variant of int **x; const int **y = (const int **)x;
3433 if (qualifiers == -1)
3434 Self.Diag(Loc: SrcExpr.get()->getBeginLoc(), DiagID: diag::warn_cast_qual2)
3435 << SrcType << DestType;
3436 else
3437 Self.Diag(Loc: SrcExpr.get()->getBeginLoc(), DiagID: diag::warn_cast_qual)
3438 << TheOffendingSrcType << TheOffendingDestType << qualifiers;
3439}
3440
3441ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
3442 TypeSourceInfo *CastTypeInfo,
3443 SourceLocation RPLoc,
3444 Expr *CastExpr) {
3445 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
3446 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
3447 Op.OpRange = CastOperation::OpRangeType(LPLoc, LPLoc, CastExpr->getEndLoc());
3448
3449 if (getLangOpts().CPlusPlus) {
3450 Op.CheckCXXCStyleCast(/*FunctionalCast=*/ FunctionalStyle: false,
3451 ListInitialization: isa<InitListExpr>(Val: CastExpr));
3452 } else {
3453 Op.CheckCStyleCast();
3454 }
3455
3456 if (Op.SrcExpr.isInvalid())
3457 return ExprError();
3458
3459 // -Wcast-qual
3460 DiagnoseCastQual(Self&: Op.Self, SrcExpr: Op.SrcExpr, DestType: Op.DestType);
3461
3462 Op.checkQualifiedDestType();
3463
3464 return Op.complete(castExpr: CStyleCastExpr::Create(
3465 Context, T: Op.ResultType, VK: Op.ValueKind, K: Op.Kind, Op: Op.SrcExpr.get(),
3466 BasePath: &Op.BasePath, FPO: CurFPFeatureOverrides(), WrittenTy: CastTypeInfo, L: LPLoc, R: RPLoc));
3467}
3468
3469ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
3470 QualType Type,
3471 SourceLocation LPLoc,
3472 Expr *CastExpr,
3473 SourceLocation RPLoc) {
3474 assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
3475 CastOperation Op(*this, Type, CastExpr);
3476 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
3477 Op.OpRange =
3478 CastOperation::OpRangeType(Op.DestRange.getBegin(), LPLoc, RPLoc);
3479
3480 Op.CheckCXXCStyleCast(/*FunctionalCast=*/FunctionalStyle: true, /*ListInit=*/ListInitialization: false);
3481 if (Op.SrcExpr.isInvalid())
3482 return ExprError();
3483
3484 Op.checkQualifiedDestType();
3485
3486 // -Wcast-qual
3487 DiagnoseCastQual(Self&: Op.Self, SrcExpr: Op.SrcExpr, DestType: Op.DestType);
3488
3489 return Op.complete(castExpr: CXXFunctionalCastExpr::Create(
3490 Context, T: Op.ResultType, VK: Op.ValueKind, Written: CastTypeInfo, Kind: Op.Kind,
3491 Op: Op.SrcExpr.get(), Path: &Op.BasePath, FPO: CurFPFeatureOverrides(), LPLoc, RPLoc));
3492}
3493