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