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