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