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