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