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

Provided by KDAB

Privacy Policy
Improve your Profiling and Debugging skills
Find out more

source code of clang/lib/Sema/SemaCast.cpp