clang 23.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 if (SrcType->isIntegralOrEnumerationType()) {
1493 // [expr.static.cast]p10 If the enumeration type has a fixed underlying
1494 // type, the value is first converted to that type by integral conversion
1495 const auto *ED = DestType->castAsEnumDecl();
1496 Kind = ED->isFixed() && ED->getIntegerType()->isBooleanType()
1497 ? CK_IntegralToBoolean
1498 : CK_IntegralCast;
1499 return TC_Success;
1500 } else if (SrcType->isRealFloatingType()) {
1501 Kind = CK_FloatingToIntegral;
1502 return TC_Success;
1503 }
1504 }
1505
1506 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
1507 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
1508 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
1509 Kind, BasePath);
1510 if (tcr != TC_NotApplicable)
1511 return tcr;
1512
1513 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
1514 // conversion. C++ 5.2.9p9 has additional information.
1515 // DR54's access restrictions apply here also.
1516 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
1517 OpRange, msg, Kind, BasePath);
1518 if (tcr != TC_NotApplicable)
1519 return tcr;
1520
1521 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
1522 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
1523 // just the usual constness stuff.
1524 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
1525 QualType SrcPointee = SrcPointer->getPointeeType();
1526 if (SrcPointee->isVoidType()) {
1527 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
1528 QualType DestPointee = DestPointer->getPointeeType();
1529 if (DestPointee->isIncompleteOrObjectType()) {
1530 // This is definitely the intended conversion, but it might fail due
1531 // to a qualifier violation. Note that we permit Objective-C lifetime
1532 // and GC qualifier mismatches here.
1533 if (!CStyle) {
1534 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
1535 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
1536 DestPointeeQuals.removeObjCGCAttr();
1537 DestPointeeQuals.removeObjCLifetime();
1538 SrcPointeeQuals.removeObjCGCAttr();
1539 SrcPointeeQuals.removeObjCLifetime();
1540 if (DestPointeeQuals != SrcPointeeQuals &&
1541 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals,
1542 Self.getASTContext())) {
1543 msg = diag::err_bad_cxx_cast_qualifiers_away;
1544 return TC_Failed;
1545 }
1546 }
1547 Kind = IsAddressSpaceConversion(SrcType, DestType)
1548 ? CK_AddressSpaceConversion
1549 : CK_BitCast;
1550 return TC_Success;
1551 }
1552
1553 // Microsoft permits static_cast from 'pointer-to-void' to
1554 // 'pointer-to-function'.
1555 if (!CStyle && Self.getLangOpts().MSVCCompat &&
1556 DestPointee->isFunctionType()) {
1557 Self.Diag(OpRange.getBegin(), diag::ext_ms_cast_fn_obj) << OpRange;
1558 Kind = CK_BitCast;
1559 return TC_Success;
1560 }
1561 }
1562 else if (DestType->isObjCObjectPointerType()) {
1563 // allow both c-style cast and static_cast of objective-c pointers as
1564 // they are pervasive.
1565 Kind = CK_CPointerToObjCPointerCast;
1566 return TC_Success;
1567 }
1568 else if (CStyle && DestType->isBlockPointerType()) {
1569 // allow c-style cast of void * to block pointers.
1570 Kind = CK_AnyPointerToBlockPointerCast;
1571 return TC_Success;
1572 }
1573 }
1574 }
1575 // Allow arbitrary objective-c pointer conversion with static casts.
1576 if (SrcType->isObjCObjectPointerType() &&
1577 DestType->isObjCObjectPointerType()) {
1578 Kind = CK_BitCast;
1579 return TC_Success;
1580 }
1581 // Allow ns-pointer to cf-pointer conversion in either direction
1582 // with static casts.
1583 if (!CStyle &&
1584 Self.ObjC().CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind))
1585 return TC_Success;
1586
1587 // See if it looks like the user is trying to convert between
1588 // related record types, and select a better diagnostic if so.
1589 if (const auto *SrcPointer = SrcType->getAs<PointerType>())
1590 if (const auto *DestPointer = DestType->getAs<PointerType>())
1591 if (SrcPointer->getPointeeType()->isRecordType() &&
1592 DestPointer->getPointeeType()->isRecordType())
1593 msg = diag::err_bad_cxx_cast_unrelated_class;
1594
1595 if (SrcType->isMatrixType() && DestType->isMatrixType()) {
1596 if (Self.CheckMatrixCast(OpRange, DestType, SrcType, Kind)) {
1597 SrcExpr = ExprError();
1598 return TC_Failed;
1599 }
1600 return TC_Success;
1601 }
1602
1603 if (SrcType == Self.Context.AMDGPUFeaturePredicateTy &&
1604 DestType == Self.Context.getLogicalOperationType()) {
1605 SrcExpr = Self.AMDGPU().ExpandAMDGPUPredicateBuiltIn(SrcExpr.get());
1606 Kind = CK_NoOp;
1607 return TC_Success;
1608 }
1609
1610 // We tried everything. Everything! Nothing works! :-(
1611 return TC_NotApplicable;
1612}
1613
1614/// Tests whether a conversion according to N2844 is valid.
1616 QualType DestType, bool CStyle,
1617 SourceRange OpRange, CastKind &Kind,
1618 CXXCastPath &BasePath, unsigned &msg) {
1619 // C++11 [expr.static.cast]p3:
1620 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
1621 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
1622 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
1623 if (!R)
1624 return TC_NotApplicable;
1625
1626 if (!SrcExpr->isGLValue())
1627 return TC_NotApplicable;
1628
1629 // Because we try the reference downcast before this function, from now on
1630 // this is the only cast possibility, so we issue an error if we fail now.
1631 QualType FromType = SrcExpr->getType();
1632 QualType ToType = R->getPointeeType();
1633 if (CStyle) {
1634 FromType = FromType.getUnqualifiedType();
1635 ToType = ToType.getUnqualifiedType();
1636 }
1637
1639 Sema::ReferenceCompareResult RefResult = Self.CompareReferenceRelationship(
1640 SrcExpr->getBeginLoc(), ToType, FromType, &RefConv);
1641 if (RefResult != Sema::Ref_Compatible) {
1642 if (CStyle || RefResult == Sema::Ref_Incompatible)
1643 return TC_NotApplicable;
1644 // Diagnose types which are reference-related but not compatible here since
1645 // we can provide better diagnostics. In these cases forwarding to
1646 // [expr.static.cast]p4 should never result in a well-formed cast.
1647 msg = SrcExpr->isLValue() ? diag::err_bad_lvalue_to_rvalue_cast
1648 : diag::err_bad_rvalue_to_rvalue_cast;
1649 return TC_Failed;
1650 }
1651
1652 if (RefConv & Sema::ReferenceConversions::DerivedToBase) {
1653 Kind = CK_DerivedToBase;
1654 if (Self.CheckDerivedToBaseConversion(FromType, ToType,
1655 SrcExpr->getBeginLoc(), OpRange,
1656 &BasePath, CStyle)) {
1657 msg = 0;
1658 return TC_Failed;
1659 }
1660 } else
1661 Kind = CK_NoOp;
1662
1663 return TC_Success;
1664}
1665
1666/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1668 QualType DestType, bool CStyle,
1669 CastOperation::OpRangeType OpRange,
1670 unsigned &msg, CastKind &Kind,
1671 CXXCastPath &BasePath) {
1672 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1673 // cast to type "reference to cv2 D", where D is a class derived from B,
1674 // if a valid standard conversion from "pointer to D" to "pointer to B"
1675 // exists, cv2 >= cv1, and B is not a virtual base class of D.
1676 // In addition, DR54 clarifies that the base must be accessible in the
1677 // current context. Although the wording of DR54 only applies to the pointer
1678 // variant of this rule, the intent is clearly for it to apply to the this
1679 // conversion as well.
1680
1681 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
1682 if (!DestReference) {
1683 return TC_NotApplicable;
1684 }
1685 bool RValueRef = DestReference->isRValueReferenceType();
1686 if (!RValueRef && !SrcExpr->isLValue()) {
1687 // We know the left side is an lvalue reference, so we can suggest a reason.
1688 msg = diag::err_bad_cxx_cast_rvalue;
1689 return TC_NotApplicable;
1690 }
1691
1692 QualType DestPointee = DestReference->getPointeeType();
1693
1694 // FIXME: If the source is a prvalue, we should issue a warning (because the
1695 // cast always has undefined behavior), and for AST consistency, we should
1696 // materialize a temporary.
1697 return TryStaticDowncast(Self,
1698 Self.Context.getCanonicalType(SrcExpr->getType()),
1699 Self.Context.getCanonicalType(DestPointee), CStyle,
1700 OpRange, SrcExpr->getType(), DestType, msg, Kind,
1701 BasePath);
1702}
1703
1704/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1706 QualType DestType, bool CStyle,
1707 CastOperation::OpRangeType OpRange,
1708 unsigned &msg, CastKind &Kind,
1709 CXXCastPath &BasePath) {
1710 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1711 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1712 // is a class derived from B, if a valid standard conversion from "pointer
1713 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1714 // class of D.
1715 // In addition, DR54 clarifies that the base must be accessible in the
1716 // current context.
1717
1718 const PointerType *DestPointer = DestType->getAs<PointerType>();
1719 if (!DestPointer) {
1720 return TC_NotApplicable;
1721 }
1722
1723 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
1724 if (!SrcPointer) {
1725 msg = diag::err_bad_static_cast_pointer_nonpointer;
1726 return TC_NotApplicable;
1727 }
1728
1729 return TryStaticDowncast(Self,
1730 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1731 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
1732 CStyle, OpRange, SrcType, DestType, msg, Kind,
1733 BasePath);
1734}
1735
1736/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1737/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
1738/// DestType is possible and allowed.
1740 CanQualType DestType, bool CStyle,
1741 CastOperation::OpRangeType OpRange,
1742 QualType OrigSrcType, QualType OrigDestType,
1743 unsigned &msg, CastKind &Kind,
1744 CXXCastPath &BasePath) {
1745 // We can only work with complete types. But don't complain if it doesn't work
1746 if (!Self.isCompleteType(OpRange.getBegin(), SrcType) ||
1747 !Self.isCompleteType(OpRange.getBegin(), DestType))
1748 return TC_NotApplicable;
1749
1750 // Downcast can only happen in class hierarchies, so we need classes.
1751 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
1752 return TC_NotApplicable;
1753 }
1754
1755 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1756 /*DetectVirtual=*/true);
1757 if (!Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths)) {
1758 return TC_NotApplicable;
1759 }
1760
1761 // Target type does derive from source type. Now we're serious. If an error
1762 // appears now, it's not ignored.
1763 // This may not be entirely in line with the standard. Take for example:
1764 // struct A {};
1765 // struct B : virtual A {
1766 // B(A&);
1767 // };
1768 //
1769 // void f()
1770 // {
1771 // (void)static_cast<const B&>(*((A*)0));
1772 // }
1773 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1774 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1775 // However, both GCC and Comeau reject this example, and accepting it would
1776 // mean more complex code if we're to preserve the nice error message.
1777 // FIXME: Being 100% compliant here would be nice to have.
1778
1779 // Must preserve cv, as always, unless we're in C-style mode.
1780 if (!CStyle &&
1781 !DestType.isAtLeastAsQualifiedAs(SrcType, Self.getASTContext())) {
1782 msg = diag::err_bad_cxx_cast_qualifiers_away;
1783 return TC_Failed;
1784 }
1785
1786 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1787 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1788 // that it builds the paths in reverse order.
1789 // To sum up: record all paths to the base and build a nice string from
1790 // them. Use it to spice up the error message.
1791 if (!Paths.isRecordingPaths()) {
1792 Paths.clear();
1793 Paths.setRecordingPaths(true);
1794 Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths);
1795 }
1796 std::string PathDisplayStr;
1797 std::set<unsigned> DisplayedPaths;
1798 for (clang::CXXBasePath &Path : Paths) {
1799 if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) {
1800 // We haven't displayed a path to this particular base
1801 // class subobject yet.
1802 PathDisplayStr += "\n ";
1803 for (CXXBasePathElement &PE : llvm::reverse(Path))
1804 PathDisplayStr += PE.Base->getType().getAsString() + " -> ";
1805 PathDisplayStr += QualType(DestType).getAsString();
1806 }
1807 }
1808
1809 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
1810 << QualType(SrcType).getUnqualifiedType()
1811 << QualType(DestType).getUnqualifiedType()
1812 << PathDisplayStr << OpRange;
1813 msg = 0;
1814 return TC_Failed;
1815 }
1816
1817 if (Paths.getDetectedVirtual() != nullptr) {
1819 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1820 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1821 msg = 0;
1822 return TC_Failed;
1823 }
1824
1825 if (!CStyle) {
1826 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1827 SrcType, DestType,
1828 Paths.front(),
1829 diag::err_downcast_from_inaccessible_base)) {
1831 case Sema::AR_delayed: // be optimistic
1832 case Sema::AR_dependent: // be optimistic
1833 break;
1834
1836 msg = 0;
1837 return TC_Failed;
1838 }
1839 }
1840
1841 Self.BuildBasePathArray(Paths, BasePath);
1842 Kind = CK_BaseToDerived;
1843 return TC_Success;
1844}
1845
1846/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1847/// C++ 5.2.9p9 is valid:
1848///
1849/// An rvalue of type "pointer to member of D of type cv1 T" can be
1850/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1851/// where B is a base class of D [...].
1852///
1854 QualType SrcType, QualType DestType,
1855 bool CStyle,
1856 CastOperation::OpRangeType OpRange,
1857 unsigned &msg, CastKind &Kind,
1858 CXXCastPath &BasePath) {
1859 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
1860 if (!DestMemPtr)
1861 return TC_NotApplicable;
1862
1863 bool WasOverloadedFunction = false;
1864 DeclAccessPair FoundOverload;
1865 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
1866 if (FunctionDecl *Fn
1867 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
1868 FoundOverload)) {
1870 SrcType = Self.Context.getMemberPointerType(
1871 Fn->getType(), /*Qualifier=*/std::nullopt, M->getParent());
1872 WasOverloadedFunction = true;
1873 }
1874 }
1875
1876 switch (Self.CheckMemberPointerConversion(
1877 SrcType, DestMemPtr, Kind, BasePath, OpRange.getBegin(), OpRange, CStyle,
1880 if (Kind == CK_NullToMemberPointer) {
1881 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1882 return TC_NotApplicable;
1883 }
1884 break;
1887 return TC_NotApplicable;
1891 msg = 0;
1892 return TC_Failed;
1893 }
1894
1895 if (WasOverloadedFunction) {
1896 // Resolve the address of the overloaded function again, this time
1897 // allowing complaints if something goes wrong.
1898 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
1899 DestType,
1900 true,
1901 FoundOverload);
1902 if (!Fn) {
1903 msg = 0;
1904 return TC_Failed;
1905 }
1906
1907 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
1908 if (!SrcExpr.isUsable()) {
1909 msg = 0;
1910 return TC_Failed;
1911 }
1912 }
1913 return TC_Success;
1914}
1915
1916/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1917/// is valid:
1918///
1919/// An expression e can be explicitly converted to a type T using a
1920/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1922 QualType DestType,
1924 CastOperation::OpRangeType OpRange,
1925 unsigned &msg, CastKind &Kind,
1926 bool ListInitialization) {
1927 if (DestType->isRecordType()) {
1928 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1929 diag::err_bad_cast_incomplete) ||
1930 Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
1931 diag::err_allocation_of_abstract_type)) {
1932 msg = 0;
1933 return TC_Failed;
1934 }
1935 }
1936
1938 InitializationKind InitKind =
1940 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
1941 ListInitialization)
1944 OpRange.getBegin(), OpRange.getParenRange(), ListInitialization)
1946 Expr *SrcExprRaw = SrcExpr.get();
1947 // FIXME: Per DR242, we should check for an implicit conversion sequence
1948 // or for a constructor that could be invoked by direct-initialization
1949 // here, not for an initialization sequence.
1950 InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
1951
1952 // At this point of CheckStaticCast, if the destination is a reference,
1953 // or the expression is an overload expression this has to work.
1954 // There is no other way that works.
1955 // On the other hand, if we're checking a C-style cast, we've still got
1956 // the reinterpret_cast way.
1957 bool CStyle = (CCK == CheckedConversionKind::CStyleCast ||
1959 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
1960 return TC_NotApplicable;
1961
1962 ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
1963 if (Result.isInvalid()) {
1964 msg = 0;
1965 return TC_Failed;
1966 }
1967
1968 if (InitSeq.isConstructorInitialization())
1969 Kind = CK_ConstructorConversion;
1970 else
1971 Kind = CK_NoOp;
1972
1973 SrcExpr = Result;
1974 return TC_Success;
1975}
1976
1977/// TryConstCast - See if a const_cast from source to destination is allowed,
1978/// and perform it if it is.
1980 QualType DestType, bool CStyle,
1981 unsigned &msg) {
1982 DestType = Self.Context.getCanonicalType(DestType);
1983 QualType SrcType = SrcExpr.get()->getType();
1984 bool NeedToMaterializeTemporary = false;
1985
1986 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
1987 // C++11 5.2.11p4:
1988 // if a pointer to T1 can be explicitly converted to the type "pointer to
1989 // T2" using a const_cast, then the following conversions can also be
1990 // made:
1991 // -- an lvalue of type T1 can be explicitly converted to an lvalue of
1992 // type T2 using the cast const_cast<T2&>;
1993 // -- a glvalue of type T1 can be explicitly converted to an xvalue of
1994 // type T2 using the cast const_cast<T2&&>; and
1995 // -- if T1 is a class type, a prvalue of type T1 can be explicitly
1996 // converted to an xvalue of type T2 using the cast const_cast<T2&&>.
1997
1998 if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) {
1999 // Cannot const_cast non-lvalue to lvalue reference type. But if this
2000 // is C-style, static_cast might find a way, so we simply suggest a
2001 // message and tell the parent to keep searching.
2002 msg = diag::err_bad_cxx_cast_rvalue;
2003 return TC_NotApplicable;
2004 }
2005
2006 if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isPRValue()) {
2007 if (!SrcType->isRecordType()) {
2008 // Cannot const_cast non-class prvalue to rvalue reference type. But if
2009 // this is C-style, static_cast can do this.
2010 msg = diag::err_bad_cxx_cast_rvalue;
2011 return TC_NotApplicable;
2012 }
2013
2014 // Materialize the class prvalue so that the const_cast can bind a
2015 // reference to it.
2016 NeedToMaterializeTemporary = true;
2017 }
2018
2019 // It's not completely clear under the standard whether we can
2020 // const_cast bit-field gl-values. Doing so would not be
2021 // intrinsically complicated, but for now, we say no for
2022 // consistency with other compilers and await the word of the
2023 // committee.
2024 if (SrcExpr.get()->refersToBitField()) {
2025 msg = diag::err_bad_cxx_cast_bitfield;
2026 return TC_NotApplicable;
2027 }
2028
2029 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
2030 SrcType = Self.Context.getPointerType(SrcType);
2031 }
2032
2033 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
2034 // the rules for const_cast are the same as those used for pointers.
2035
2036 if (!DestType->isPointerType() &&
2037 !DestType->isMemberPointerType() &&
2038 !DestType->isObjCObjectPointerType()) {
2039 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
2040 // was a reference type, we converted it to a pointer above.
2041 // The status of rvalue references isn't entirely clear, but it looks like
2042 // conversion to them is simply invalid.
2043 // C++ 5.2.11p3: For two pointer types [...]
2044 if (!CStyle)
2045 msg = diag::err_bad_const_cast_dest;
2046 return TC_NotApplicable;
2047 }
2048 if (DestType->isFunctionPointerType() ||
2049 DestType->isMemberFunctionPointerType()) {
2050 // Cannot cast direct function pointers.
2051 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
2052 // T is the ultimate pointee of source and target type.
2053 if (!CStyle)
2054 msg = diag::err_bad_const_cast_dest;
2055 return TC_NotApplicable;
2056 }
2057
2058 // C++ [expr.const.cast]p3:
2059 // "For two similar types T1 and T2, [...]"
2060 //
2061 // We only allow a const_cast to change cvr-qualifiers, not other kinds of
2062 // type qualifiers. (Likewise, we ignore other changes when determining
2063 // whether a cast casts away constness.)
2064 if (!Self.Context.hasCvrSimilarType(SrcType, DestType))
2065 return TC_NotApplicable;
2066
2067 if (NeedToMaterializeTemporary)
2068 // This is a const_cast from a class prvalue to an rvalue reference type.
2069 // Materialize a temporary to store the result of the conversion.
2070 SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcExpr.get()->getType(),
2071 SrcExpr.get(),
2072 /*IsLValueReference*/ false);
2073
2074 return TC_Success;
2075}
2076
2077// Checks for undefined behavior in reinterpret_cast.
2078// The cases that is checked for is:
2079// *reinterpret_cast<T*>(&a)
2080// reinterpret_cast<T&>(a)
2081// where accessing 'a' as type 'T' will result in undefined behavior.
2083 bool IsDereference,
2084 SourceRange Range) {
2085 unsigned DiagID = IsDereference ?
2086 diag::warn_pointer_indirection_from_incompatible_type :
2087 diag::warn_undefined_reinterpret_cast;
2088
2089 if (Diags.isIgnored(DiagID, Range.getBegin()))
2090 return;
2091
2092 QualType SrcTy, DestTy;
2093 if (IsDereference) {
2094 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
2095 return;
2096 }
2097 SrcTy = SrcType->getPointeeType();
2098 DestTy = DestType->getPointeeType();
2099 } else {
2100 if (!DestType->getAs<ReferenceType>()) {
2101 return;
2102 }
2103 SrcTy = SrcType;
2104 DestTy = DestType->getPointeeType();
2105 }
2106
2107 // Cast is compatible if the types are the same.
2108 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
2109 return;
2110 }
2111 // or one of the types is a char or void type
2112 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
2113 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
2114 return;
2115 }
2116 // or one of the types is a tag type.
2117 if (isa<TagType>(SrcTy.getCanonicalType()) ||
2119 return;
2120
2121 // FIXME: Scoped enums?
2122 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
2123 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
2124 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
2125 return;
2126 }
2127 }
2128
2129 if (SrcTy->isDependentType() || DestTy->isDependentType()) {
2130 return;
2131 }
2132
2133 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
2134}
2135
2136static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
2137 QualType DestType) {
2138 QualType SrcType = SrcExpr.get()->getType();
2139 if (Self.Context.hasSameType(SrcType, DestType))
2140 return;
2141 if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
2142 if (SrcPtrTy->isObjCSelType()) {
2143 QualType DT = DestType;
2144 if (isa<PointerType>(DestType))
2145 DT = DestType->getPointeeType();
2146 if (!DT.getUnqualifiedType()->isVoidType())
2147 Self.Diag(SrcExpr.get()->getExprLoc(),
2148 diag::warn_cast_pointer_from_sel)
2149 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2150 }
2151}
2152
2153/// Diagnose casts that change the calling convention of a pointer to a function
2154/// defined in the current TU.
2155static void DiagnoseCallingConvCast(Sema &Self, const ExprResult &SrcExpr,
2156 QualType DstType,
2157 CastOperation::OpRangeType OpRange) {
2158 // Check if this cast would change the calling convention of a function
2159 // pointer type.
2160 QualType SrcType = SrcExpr.get()->getType();
2161 if (Self.Context.hasSameType(SrcType, DstType) ||
2162 !SrcType->isFunctionPointerType() || !DstType->isFunctionPointerType())
2163 return;
2164 const auto *SrcFTy =
2166 const auto *DstFTy =
2168 CallingConv SrcCC = SrcFTy->getCallConv();
2169 CallingConv DstCC = DstFTy->getCallConv();
2170 if (SrcCC == DstCC)
2171 return;
2172
2173 // We have a calling convention cast. Check if the source is a pointer to a
2174 // known, specific function that has already been defined.
2175 Expr *Src = SrcExpr.get()->IgnoreParenImpCasts();
2176 if (auto *UO = dyn_cast<UnaryOperator>(Src))
2177 if (UO->getOpcode() == UO_AddrOf)
2178 Src = UO->getSubExpr()->IgnoreParenImpCasts();
2179 auto *DRE = dyn_cast<DeclRefExpr>(Src);
2180 if (!DRE)
2181 return;
2182 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
2183 if (!FD)
2184 return;
2185
2186 // Only warn if we are casting from the default convention to a non-default
2187 // convention. This can happen when the programmer forgot to apply the calling
2188 // convention to the function declaration and then inserted this cast to
2189 // satisfy the type system.
2190 CallingConv DefaultCC = Self.getASTContext().getDefaultCallingConvention(
2191 FD->isVariadic(), FD->isCXXInstanceMember());
2192 if (DstCC == DefaultCC || SrcCC != DefaultCC)
2193 return;
2194
2195 // Diagnose this cast, as it is probably bad.
2196 StringRef SrcCCName = FunctionType::getNameForCallConv(SrcCC);
2197 StringRef DstCCName = FunctionType::getNameForCallConv(DstCC);
2198 Self.Diag(OpRange.getBegin(), diag::warn_cast_calling_conv)
2199 << SrcCCName << DstCCName << OpRange;
2200
2201 // The checks above are cheaper than checking if the diagnostic is enabled.
2202 // However, it's worth checking if the warning is enabled before we construct
2203 // a fixit.
2204 if (Self.Diags.isIgnored(diag::warn_cast_calling_conv, OpRange.getBegin()))
2205 return;
2206
2207 // Try to suggest a fixit to change the calling convention of the function
2208 // whose address was taken. Try to use the latest macro for the convention.
2209 // For example, users probably want to write "WINAPI" instead of "__stdcall"
2210 // to match the Windows header declarations.
2211 SourceLocation NameLoc = FD->getFirstDecl()->getNameInfo().getLoc();
2212 Preprocessor &PP = Self.getPreprocessor();
2213 SmallVector<TokenValue, 6> AttrTokens;
2214 SmallString<64> CCAttrText;
2215 llvm::raw_svector_ostream OS(CCAttrText);
2216 if (Self.getLangOpts().MicrosoftExt) {
2217 // __stdcall or __vectorcall
2218 OS << "__" << DstCCName;
2219 IdentifierInfo *II = PP.getIdentifierInfo(OS.str());
2220 AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
2221 ? TokenValue(II->getTokenID())
2222 : TokenValue(II));
2223 } else {
2224 // __attribute__((stdcall)) or __attribute__((vectorcall))
2225 OS << "__attribute__((" << DstCCName << "))";
2226 AttrTokens.push_back(tok::kw___attribute);
2227 AttrTokens.push_back(tok::l_paren);
2228 AttrTokens.push_back(tok::l_paren);
2229 IdentifierInfo *II = PP.getIdentifierInfo(DstCCName);
2230 AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
2231 ? TokenValue(II->getTokenID())
2232 : TokenValue(II));
2233 AttrTokens.push_back(tok::r_paren);
2234 AttrTokens.push_back(tok::r_paren);
2235 }
2236 StringRef AttrSpelling = PP.getLastMacroWithSpelling(NameLoc, AttrTokens);
2237 if (!AttrSpelling.empty())
2238 CCAttrText = AttrSpelling;
2239 OS << ' ';
2240 Self.Diag(NameLoc, diag::note_change_calling_conv_fixit)
2241 << FD << DstCCName << FixItHint::CreateInsertion(NameLoc, CCAttrText);
2242}
2243
2244static void checkIntToPointerCast(bool CStyle, const SourceRange &OpRange,
2245 const Expr *SrcExpr, QualType DestType,
2246 Sema &Self) {
2247 QualType SrcType = SrcExpr->getType();
2248
2249 // Not warning on reinterpret_cast, boolean, constant expressions, etc
2250 // are not explicit design choices, but consistent with GCC's behavior.
2251 // Feel free to modify them if you've reason/evidence for an alternative.
2252 if (CStyle && SrcType->isIntegralType(Self.Context)
2253 && !SrcType->isBooleanType()
2254 && !SrcType->isEnumeralType()
2255 && !SrcExpr->isIntegerConstantExpr(Self.Context)
2256 && Self.Context.getTypeSize(DestType) >
2257 Self.Context.getTypeSize(SrcType)) {
2258 // Separate between casts to void* and non-void* pointers.
2259 // Some APIs use (abuse) void* for something like a user context,
2260 // and often that value is an integer even if it isn't a pointer itself.
2261 // Having a separate warning flag allows users to control the warning
2262 // for their workflow.
2263 unsigned Diag = DestType->isVoidPointerType() ?
2264 diag::warn_int_to_void_pointer_cast
2265 : diag::warn_int_to_pointer_cast;
2266 Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange;
2267 }
2268}
2269
2271 ExprResult &Result) {
2272 // We can only fix an overloaded reinterpret_cast if
2273 // - it is a template with explicit arguments that resolves to an lvalue
2274 // unambiguously, or
2275 // - it is the only function in an overload set that may have its address
2276 // taken.
2277
2278 Expr *E = Result.get();
2279 // TODO: what if this fails because of DiagnoseUseOfDecl or something
2280 // like it?
2281 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
2282 Result,
2283 Expr::getValueKindForType(DestType) ==
2284 VK_PRValue // Convert Fun to Ptr
2285 ) &&
2286 Result.isUsable())
2287 return true;
2288
2289 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
2290 // preserves Result.
2291 Result = E;
2292 if (!Self.resolveAndFixAddressOfSingleOverloadCandidate(
2293 Result, /*DoFunctionPointerConversion=*/true))
2294 return false;
2295 return Result.isUsable();
2296}
2297
2299 QualType DestType, bool CStyle,
2300 CastOperation::OpRangeType OpRange,
2301 unsigned &msg, CastKind &Kind) {
2302 bool IsLValueCast = false;
2303
2304 DestType = Self.Context.getCanonicalType(DestType);
2305 QualType SrcType = SrcExpr.get()->getType();
2306
2307 // Is the source an overloaded name? (i.e. &foo)
2308 // If so, reinterpret_cast generally can not help us here (13.4, p1, bullet 5)
2309 if (SrcType == Self.Context.OverloadTy) {
2310 ExprResult FixedExpr = SrcExpr;
2311 if (!fixOverloadedReinterpretCastExpr(Self, DestType, FixedExpr))
2312 return TC_NotApplicable;
2313
2314 assert(FixedExpr.isUsable() && "Invalid result fixing overloaded expr");
2315 SrcExpr = FixedExpr;
2316 SrcType = SrcExpr.get()->getType();
2317 }
2318
2319 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
2320 if (!SrcExpr.get()->isGLValue()) {
2321 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
2322 // similar comment in const_cast.
2323 msg = diag::err_bad_cxx_cast_rvalue;
2324 return TC_NotApplicable;
2325 }
2326
2327 if (!CStyle) {
2328 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
2329 /*IsDereference=*/false, OpRange);
2330 }
2331
2332 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
2333 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
2334 // built-in & and * operators.
2335
2336 const char *inappropriate = nullptr;
2337 switch (SrcExpr.get()->getObjectKind()) {
2338 case OK_Ordinary:
2339 break;
2340 case OK_BitField:
2341 msg = diag::err_bad_cxx_cast_bitfield;
2342 return TC_NotApplicable;
2343 // FIXME: Use a specific diagnostic for the rest of these cases.
2344 case OK_VectorComponent: inappropriate = "vector element"; break;
2345 case OK_MatrixComponent:
2346 inappropriate = "matrix element";
2347 break;
2348 case OK_ObjCProperty: inappropriate = "property expression"; break;
2349 case OK_ObjCSubscript: inappropriate = "container subscripting expression";
2350 break;
2351 }
2352 if (inappropriate) {
2353 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
2354 << inappropriate << DestType
2355 << OpRange << SrcExpr.get()->getSourceRange();
2356 msg = 0; SrcExpr = ExprError();
2357 return TC_NotApplicable;
2358 }
2359
2360 // This code does this transformation for the checked types.
2361 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
2362 SrcType = Self.Context.getPointerType(SrcType);
2363
2364 IsLValueCast = true;
2365 }
2366
2367 // Canonicalize source for comparison.
2368 SrcType = Self.Context.getCanonicalType(SrcType);
2369
2370 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
2371 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
2372 if (DestMemPtr && SrcMemPtr) {
2373 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
2374 // can be explicitly converted to an rvalue of type "pointer to member
2375 // of Y of type T2" if T1 and T2 are both function types or both object
2376 // types.
2377 if (DestMemPtr->isMemberFunctionPointer() !=
2378 SrcMemPtr->isMemberFunctionPointer())
2379 return TC_NotApplicable;
2380
2381 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2382 // We need to determine the inheritance model that the class will use if
2383 // haven't yet.
2384 (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
2385 (void)Self.isCompleteType(OpRange.getBegin(), DestType);
2386 }
2387
2388 // Don't allow casting between member pointers of different sizes.
2389 if (Self.Context.getTypeSize(DestMemPtr) !=
2390 Self.Context.getTypeSize(SrcMemPtr)) {
2391 msg = diag::err_bad_cxx_cast_member_pointer_size;
2392 return TC_Failed;
2393 }
2394
2395 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
2396 // constness.
2397 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
2398 // we accept it.
2399 if (auto CACK =
2400 CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
2401 /*CheckObjCLifetime=*/CStyle))
2402 return getCastAwayConstnessCastKind(CACK, msg);
2403
2404 // A valid member pointer cast.
2405 assert(!IsLValueCast);
2406 Kind = CK_ReinterpretMemberPointer;
2407 return TC_Success;
2408 }
2409
2410 // See below for the enumeral issue.
2411 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
2412 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
2413 // type large enough to hold it. A value of std::nullptr_t can be
2414 // converted to an integral type; the conversion has the same meaning
2415 // and validity as a conversion of (void*)0 to the integral type.
2416 if (Self.Context.getTypeSize(SrcType) >
2417 Self.Context.getTypeSize(DestType)) {
2418 msg = diag::err_bad_reinterpret_cast_small_int;
2419 return TC_Failed;
2420 }
2421 Kind = CK_PointerToIntegral;
2422 return TC_Success;
2423 }
2424
2425 // Allow reinterpret_casts between vectors of the same size and
2426 // between vectors and integers of the same size.
2427 bool destIsVector = DestType->isVectorType();
2428 bool srcIsVector = SrcType->isVectorType();
2429 if (srcIsVector || destIsVector) {
2430 // Allow bitcasting between SVE VLATs and VLSTs, and vice-versa.
2431 if (Self.isValidSveBitcast(SrcType, DestType)) {
2432 Kind = CK_BitCast;
2433 return TC_Success;
2434 }
2435
2436 // Allow bitcasting between SVE VLATs and VLSTs, and vice-versa.
2437 if (Self.RISCV().isValidRVVBitcast(SrcType, DestType)) {
2438 Kind = CK_BitCast;
2439 return TC_Success;
2440 }
2441
2442 // The non-vector type, if any, must have integral type. This is
2443 // the same rule that C vector casts use; note, however, that enum
2444 // types are not integral in C++.
2445 if ((!destIsVector && !DestType->isIntegralType(Self.Context)) ||
2446 (!srcIsVector && !SrcType->isIntegralType(Self.Context)))
2447 return TC_NotApplicable;
2448
2449 // The size we want to consider is eltCount * eltSize.
2450 // That's exactly what the lax-conversion rules will check.
2451 if (Self.areLaxCompatibleVectorTypes(SrcType, DestType)) {
2452 Kind = CK_BitCast;
2453 return TC_Success;
2454 }
2455
2456 if (Self.LangOpts.OpenCL && !CStyle) {
2457 if (DestType->isExtVectorType() || SrcType->isExtVectorType()) {
2458 // FIXME: Allow for reinterpret cast between 3 and 4 element vectors
2459 if (Self.areVectorTypesSameSize(SrcType, DestType)) {
2460 Kind = CK_BitCast;
2461 return TC_Success;
2462 }
2463 }
2464 }
2465
2466 // Otherwise, pick a reasonable diagnostic.
2467 if (!destIsVector)
2468 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
2469 else if (!srcIsVector)
2470 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
2471 else
2472 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
2473
2474 return TC_Failed;
2475 }
2476
2477 if (SrcType == DestType) {
2478 // C++ 5.2.10p2 has a note that mentions that, subject to all other
2479 // restrictions, a cast to the same type is allowed so long as it does not
2480 // cast away constness. In C++98, the intent was not entirely clear here,
2481 // since all other paragraphs explicitly forbid casts to the same type.
2482 // C++11 clarifies this case with p2.
2483 //
2484 // The only allowed types are: integral, enumeration, pointer, or
2485 // pointer-to-member types. We also won't restrict Obj-C pointers either.
2486 Kind = CK_NoOp;
2488 if (SrcType->isIntegralOrEnumerationType() ||
2489 SrcType->isAnyPointerType() ||
2490 SrcType->isMemberPointerType() ||
2491 SrcType->isBlockPointerType()) {
2493 }
2494 return Result;
2495 }
2496
2497 bool destIsPtr = DestType->isAnyPointerType() ||
2498 DestType->isBlockPointerType();
2499 bool srcIsPtr = SrcType->isAnyPointerType() ||
2500 SrcType->isBlockPointerType();
2501 if (!destIsPtr && !srcIsPtr) {
2502 // Except for std::nullptr_t->integer and lvalue->reference, which are
2503 // handled above, at least one of the two arguments must be a pointer.
2504 return TC_NotApplicable;
2505 }
2506
2507 if (DestType->isIntegralType(Self.Context)) {
2508 assert(srcIsPtr && "One type must be a pointer");
2509 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
2510 // type large enough to hold it; except in Microsoft mode, where the
2511 // integral type size doesn't matter (except we don't allow bool).
2512 if ((Self.Context.getTypeSize(SrcType) >
2513 Self.Context.getTypeSize(DestType))) {
2514 bool MicrosoftException =
2515 Self.getLangOpts().MicrosoftExt && !DestType->isBooleanType();
2516 if (MicrosoftException) {
2517 unsigned Diag = SrcType->isVoidPointerType()
2518 ? diag::warn_void_pointer_to_int_cast
2519 : diag::warn_pointer_to_int_cast;
2520 Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange;
2521 } else {
2522 msg = diag::err_bad_reinterpret_cast_small_int;
2523 return TC_Failed;
2524 }
2525 }
2526 Kind = CK_PointerToIntegral;
2527 return TC_Success;
2528 }
2529
2530 if (SrcType->isIntegralOrEnumerationType()) {
2531 assert(destIsPtr && "One type must be a pointer");
2532 checkIntToPointerCast(CStyle, OpRange, SrcExpr.get(), DestType, Self);
2533 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
2534 // converted to a pointer.
2535 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
2536 // necessarily converted to a null pointer value.]
2537 Kind = CK_IntegralToPointer;
2538 return TC_Success;
2539 }
2540
2541 if (!destIsPtr || !srcIsPtr) {
2542 // With the valid non-pointer conversions out of the way, we can be even
2543 // more stringent.
2544 return TC_NotApplicable;
2545 }
2546
2547 // Cannot convert between block pointers and Objective-C object pointers.
2548 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
2549 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
2550 return TC_NotApplicable;
2551
2552 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
2553 // The C-style cast operator can.
2554 TryCastResult SuccessResult = TC_Success;
2555 if (auto CACK =
2556 CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
2557 /*CheckObjCLifetime=*/CStyle))
2558 SuccessResult = getCastAwayConstnessCastKind(CACK, msg);
2559
2560 if (IsAddressSpaceConversion(SrcType, DestType)) {
2561 Kind = CK_AddressSpaceConversion;
2562 assert(SrcType->isPointerType() && DestType->isPointerType());
2563 if (!CStyle &&
2565 SrcType->getPointeeType().getQualifiers(), Self.getASTContext())) {
2566 SuccessResult = TC_Failed;
2567 }
2568 } else if (IsLValueCast) {
2569 Kind = CK_LValueBitCast;
2570 } else if (DestType->isObjCObjectPointerType()) {
2571 Kind = Self.ObjC().PrepareCastToObjCObjectPointer(SrcExpr);
2572 } else if (DestType->isBlockPointerType()) {
2573 if (!SrcType->isBlockPointerType()) {
2574 Kind = CK_AnyPointerToBlockPointerCast;
2575 } else {
2576 Kind = CK_BitCast;
2577 }
2578 } else {
2579 Kind = CK_BitCast;
2580 }
2581
2582 // Any pointer can be cast to an Objective-C pointer type with a C-style
2583 // cast.
2584 if (CStyle && DestType->isObjCObjectPointerType()) {
2585 return SuccessResult;
2586 }
2587 if (CStyle)
2588 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
2589
2590 DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
2591
2592 // Not casting away constness, so the only remaining check is for compatible
2593 // pointer categories.
2594
2595 if (SrcType->isFunctionPointerType()) {
2596 if (DestType->isFunctionPointerType()) {
2597 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
2598 // a pointer to a function of a different type.
2599 return SuccessResult;
2600 }
2601
2602 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
2603 // an object type or vice versa is conditionally-supported.
2604 // Compilers support it in C++03 too, though, because it's necessary for
2605 // casting the return value of dlsym() and GetProcAddress().
2606 // FIXME: Conditionally-supported behavior should be configurable in the
2607 // TargetInfo or similar.
2608 Self.Diag(OpRange.getBegin(),
2609 Self.getLangOpts().CPlusPlus11 ?
2610 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2611 << OpRange;
2612 return SuccessResult;
2613 }
2614
2615 if (DestType->isFunctionPointerType()) {
2616 // See above.
2617 Self.Diag(OpRange.getBegin(),
2618 Self.getLangOpts().CPlusPlus11 ?
2619 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2620 << OpRange;
2621 return SuccessResult;
2622 }
2623
2624 // Diagnose address space conversion in nested pointers.
2625 QualType DestPtee = DestType->getPointeeType().isNull()
2626 ? DestType->getPointeeType()
2627 : DestType->getPointeeType()->getPointeeType();
2628 QualType SrcPtee = SrcType->getPointeeType().isNull()
2629 ? SrcType->getPointeeType()
2630 : SrcType->getPointeeType()->getPointeeType();
2631 while (!DestPtee.isNull() && !SrcPtee.isNull()) {
2632 if (DestPtee.getAddressSpace() != SrcPtee.getAddressSpace()) {
2633 Self.Diag(OpRange.getBegin(),
2634 diag::warn_bad_cxx_cast_nested_pointer_addr_space)
2635 << CStyle << SrcType << DestType << SrcExpr.get()->getSourceRange();
2636 break;
2637 }
2638 DestPtee = DestPtee->getPointeeType();
2639 SrcPtee = SrcPtee->getPointeeType();
2640 }
2641
2642 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
2643 // a pointer to an object of different type.
2644 // Void pointers are not specified, but supported by every compiler out there.
2645 // So we finish by allowing everything that remains - it's got to be two
2646 // object pointers.
2647 return SuccessResult;
2648}
2649
2651 QualType DestType, bool CStyle,
2652 unsigned &msg, CastKind &Kind) {
2653 if (!Self.getLangOpts().OpenCL && !Self.getLangOpts().SYCLIsDevice)
2654 // FIXME: As compiler doesn't have any information about overlapping addr
2655 // spaces at the moment we have to be permissive here.
2656 return TC_NotApplicable;
2657 // Even though the logic below is general enough and can be applied to
2658 // non-OpenCL mode too, we fast-path above because no other languages
2659 // define overlapping address spaces currently.
2660 auto SrcType = SrcExpr.get()->getType();
2661 // FIXME: Should this be generalized to references? The reference parameter
2662 // however becomes a reference pointee type here and therefore rejected.
2663 // Perhaps this is the right behavior though according to C++.
2664 auto SrcPtrType = SrcType->getAs<PointerType>();
2665 if (!SrcPtrType)
2666 return TC_NotApplicable;
2667 auto DestPtrType = DestType->getAs<PointerType>();
2668 if (!DestPtrType)
2669 return TC_NotApplicable;
2670 auto SrcPointeeType = SrcPtrType->getPointeeType();
2671 auto DestPointeeType = DestPtrType->getPointeeType();
2672 if (!DestPointeeType.isAddressSpaceOverlapping(SrcPointeeType,
2673 Self.getASTContext())) {
2674 msg = diag::err_bad_cxx_cast_addr_space_mismatch;
2675 return TC_Failed;
2676 }
2677 auto SrcPointeeTypeWithoutAS =
2678 Self.Context.removeAddrSpaceQualType(SrcPointeeType.getCanonicalType());
2679 auto DestPointeeTypeWithoutAS =
2680 Self.Context.removeAddrSpaceQualType(DestPointeeType.getCanonicalType());
2681 if (Self.Context.hasSameType(SrcPointeeTypeWithoutAS,
2682 DestPointeeTypeWithoutAS)) {
2683 Kind = SrcPointeeType.getAddressSpace() == DestPointeeType.getAddressSpace()
2684 ? CK_NoOp
2685 : CK_AddressSpaceConversion;
2686 return TC_Success;
2687 } else {
2688 return TC_NotApplicable;
2689 }
2690}
2691
2692void CastOperation::checkAddressSpaceCast(QualType SrcType, QualType DestType) {
2693 // In OpenCL only conversions between pointers to objects in overlapping
2694 // addr spaces are allowed. v2.0 s6.5.5 - Generic addr space overlaps
2695 // with any named one, except for constant.
2696
2697 // Converting the top level pointee addrspace is permitted for compatible
2698 // addrspaces (such as 'generic int *' to 'local int *' or vice versa), but
2699 // if any of the nested pointee addrspaces differ, we emit a warning
2700 // regardless of addrspace compatibility. This makes
2701 // local int ** p;
2702 // return (generic int **) p;
2703 // warn even though local -> generic is permitted.
2704 if (Self.getLangOpts().OpenCL) {
2705 const Type *DestPtr, *SrcPtr;
2706 bool Nested = false;
2707 unsigned DiagID = diag::err_typecheck_incompatible_address_space;
2708 DestPtr = Self.getASTContext().getCanonicalType(DestType.getTypePtr()),
2709 SrcPtr = Self.getASTContext().getCanonicalType(SrcType.getTypePtr());
2710
2711 while (isa<PointerType>(DestPtr) && isa<PointerType>(SrcPtr)) {
2712 const PointerType *DestPPtr = cast<PointerType>(DestPtr);
2713 const PointerType *SrcPPtr = cast<PointerType>(SrcPtr);
2714 QualType DestPPointee = DestPPtr->getPointeeType();
2715 QualType SrcPPointee = SrcPPtr->getPointeeType();
2716 if (Nested
2717 ? DestPPointee.getAddressSpace() != SrcPPointee.getAddressSpace()
2718 : !DestPPointee.isAddressSpaceOverlapping(SrcPPointee,
2719 Self.getASTContext())) {
2720 Self.Diag(OpRange.getBegin(), DiagID)
2721 << SrcType << DestType << AssignmentAction::Casting
2722 << SrcExpr.get()->getSourceRange();
2723 if (!Nested)
2724 SrcExpr = ExprError();
2725 return;
2726 }
2727
2728 DestPtr = DestPPtr->getPointeeType().getTypePtr();
2729 SrcPtr = SrcPPtr->getPointeeType().getTypePtr();
2730 Nested = true;
2731 DiagID = diag::ext_nested_pointer_qualifier_mismatch;
2732 }
2733 }
2734}
2735
2737 bool SrcCompatXL = this->getLangOpts().getAltivecSrcCompat() ==
2739 VectorKind VKind = VecTy->getVectorKind();
2740
2741 if ((VKind == VectorKind::AltiVecVector) ||
2742 (SrcCompatXL && ((VKind == VectorKind::AltiVecBool) ||
2743 (VKind == VectorKind::AltiVecPixel)))) {
2744 return true;
2745 }
2746 return false;
2747}
2748
2750 QualType SrcTy) {
2751 bool SrcCompatGCC = this->getLangOpts().getAltivecSrcCompat() ==
2753 if (this->getLangOpts().AltiVec && SrcCompatGCC) {
2754 this->Diag(R.getBegin(),
2755 diag::err_invalid_conversion_between_vector_and_integer)
2756 << VecTy << SrcTy << R;
2757 return true;
2758 }
2759 return false;
2760}
2761
2762void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
2763 bool ListInitialization) {
2764 assert(Self.getLangOpts().CPlusPlus);
2765
2766 // Handle placeholders.
2767 if (isPlaceholder()) {
2768 // C-style casts can resolve __unknown_any types.
2769 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2770 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2771 SrcExpr.get(), Kind,
2772 ValueKind, BasePath);
2773 return;
2774 }
2775
2776 checkNonOverloadPlaceholders();
2777 if (SrcExpr.isInvalid())
2778 return;
2779 }
2780
2781 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
2782 // This test is outside everything else because it's the only case where
2783 // a non-lvalue-reference target type does not lead to decay.
2784 if (DestType->isVoidType()) {
2785 Kind = CK_ToVoid;
2786
2787 if (claimPlaceholder(BuiltinType::Overload)) {
2788 Self.ResolveAndFixSingleFunctionTemplateSpecialization(
2789 SrcExpr, /* Decay Function to ptr */ false,
2790 /* Complain */ true, DestRange, DestType,
2791 diag::err_bad_cstyle_cast_overload);
2792 if (SrcExpr.isInvalid())
2793 return;
2794 }
2795
2796 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
2797 return;
2798 }
2799
2800 // If the type is dependent, we won't do any other semantic analysis now.
2801 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
2802 SrcExpr.get()->isValueDependent()) {
2803 assert(Kind == CK_Dependent);
2804 return;
2805 }
2806
2807 CheckedConversionKind CCK = FunctionalStyle
2810 if (Self.getLangOpts().HLSL) {
2811 if (CheckHLSLCStyleCast(CCK))
2812 return;
2813 }
2814
2815 if (ValueKind == VK_PRValue && !DestType->isRecordType() &&
2816 !isPlaceholder(BuiltinType::Overload)) {
2817 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
2818 if (SrcExpr.isInvalid())
2819 return;
2820 }
2821
2822 // AltiVec vector initialization with a single literal.
2823 if (const VectorType *vecTy = DestType->getAs<VectorType>()) {
2824 if (Self.CheckAltivecInitFromScalar(OpRange, DestType,
2825 SrcExpr.get()->getType())) {
2826 SrcExpr = ExprError();
2827 return;
2828 }
2829 if (Self.ShouldSplatAltivecScalarInCast(vecTy) &&
2830 (SrcExpr.get()->getType()->isIntegerType() ||
2831 SrcExpr.get()->getType()->isFloatingType())) {
2832 Kind = CK_VectorSplat;
2833 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
2834 return;
2835 }
2836 }
2837
2838 // WebAssembly tables cannot be cast.
2839 QualType SrcType = SrcExpr.get()->getType();
2840 if (SrcType->isWebAssemblyTableType()) {
2841 Self.Diag(OpRange.getBegin(), diag::err_wasm_cast_table)
2842 << 1 << SrcExpr.get()->getSourceRange();
2843 SrcExpr = ExprError();
2844 return;
2845 }
2846
2847 // C++ [expr.cast]p5: The conversions performed by
2848 // - a const_cast,
2849 // - a static_cast,
2850 // - a static_cast followed by a const_cast,
2851 // - a reinterpret_cast, or
2852 // - a reinterpret_cast followed by a const_cast,
2853 // can be performed using the cast notation of explicit type conversion.
2854 // [...] If a conversion can be interpreted in more than one of the ways
2855 // listed above, the interpretation that appears first in the list is used,
2856 // even if a cast resulting from that interpretation is ill-formed.
2857 // In plain language, this means trying a const_cast ...
2858 // Note that for address space we check compatibility after const_cast.
2859 unsigned msg = diag::err_bad_cxx_cast_generic;
2860 TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
2861 /*CStyle*/ true, msg);
2862 if (SrcExpr.isInvalid())
2863 return;
2864 if (isValidCast(tcr))
2865 Kind = CK_NoOp;
2866
2867 if (tcr == TC_NotApplicable) {
2868 tcr = TryAddressSpaceCast(Self, SrcExpr, DestType, /*CStyle*/ true, msg,
2869 Kind);
2870 if (SrcExpr.isInvalid())
2871 return;
2872
2873 if (tcr == TC_NotApplicable) {
2874 // ... or if that is not possible, a static_cast, ignoring const and
2875 // addr space, ...
2876 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange, msg, Kind,
2877 BasePath, ListInitialization);
2878 if (SrcExpr.isInvalid())
2879 return;
2880
2881 if (tcr == TC_NotApplicable) {
2882 // ... and finally a reinterpret_cast, ignoring const and addr space.
2883 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/ true,
2884 OpRange, msg, Kind);
2885 if (SrcExpr.isInvalid())
2886 return;
2887 }
2888 }
2889 }
2890
2891 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
2892 isValidCast(tcr))
2893 checkObjCConversion(CCK);
2894
2895 if (tcr != TC_Success && msg != 0) {
2896 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
2898 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
2899 DestType,
2900 /*Complain*/ true,
2901 Found);
2902 if (Fn) {
2903 // If DestType is a function type (not to be confused with the function
2904 // pointer type), it will be possible to resolve the function address,
2905 // but the type cast should be considered as failure.
2906 OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression;
2907 Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload)
2908 << OE->getName() << DestType << OpRange
2910 Self.NoteAllOverloadCandidates(SrcExpr.get());
2911 }
2912 } else {
2913 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
2914 OpRange, SrcExpr.get(), DestType, ListInitialization);
2915 }
2916 }
2917
2918 if (isValidCast(tcr)) {
2919 if (Kind == CK_BitCast)
2920 checkCastAlign();
2921
2922 if (unsigned DiagID = checkCastFunctionType(Self, SrcExpr, DestType))
2923 Self.Diag(OpRange.getBegin(), DiagID)
2924 << SrcExpr.get()->getType() << DestType << OpRange;
2925
2926 } else {
2927 SrcExpr = ExprError();
2928 }
2929}
2930
2931// CheckHLSLCStyleCast - Returns `true` ihe cast is handled or errored as an
2932// HLSL-specific cast. Returns false if the cast should be checked as a CXX
2933// C-Style cast.
2934bool CastOperation::CheckHLSLCStyleCast(CheckedConversionKind CCK) {
2935 assert(Self.getLangOpts().HLSL && "Must be HLSL!");
2936 QualType SrcTy = SrcExpr.get()->getType();
2937 // HLSL has several unique forms of C-style casts which support aggregate to
2938 // aggregate casting.
2939 // This case should not trigger on regular vector cast, vector truncation
2940 if (Self.HLSL().CanPerformElementwiseCast(SrcExpr.get(), DestType)) {
2941 if (SrcTy->isConstantArrayType())
2942 SrcExpr = Self.ImpCastExprToType(
2943 SrcExpr.get(), Self.Context.getArrayParameterType(SrcTy),
2944 CK_HLSLArrayRValue, VK_PRValue, nullptr, CCK);
2945 else
2946 SrcExpr = Self.DefaultLvalueConversion(SrcExpr.get());
2947 Kind = CK_HLSLElementwiseCast;
2948 return true;
2949 }
2950
2951 // This case should not trigger on regular vector splat
2952 // If the relative order of this and the HLSLElementWise cast checks
2953 // are changed, it might change which cast handles what in a few cases
2954 if (Self.HLSL().CanPerformAggregateSplatCast(SrcExpr.get(), DestType)) {
2955 SrcExpr = Self.DefaultLvalueConversion(SrcExpr.get());
2956 const VectorType *VT = SrcTy->getAs<VectorType>();
2957 const ConstantMatrixType *MT = SrcTy->getAs<ConstantMatrixType>();
2958 // change splat from vec1 case to splat from scalar
2959 if (VT && VT->getNumElements() == 1)
2960 SrcExpr = Self.ImpCastExprToType(
2961 SrcExpr.get(), VT->getElementType(), CK_HLSLVectorTruncation,
2962 SrcExpr.get()->getValueKind(), nullptr, CCK);
2963 // change splat from 1x1 matrix case to splat from scalar
2964 else if (MT && MT->getNumElementsFlattened() == 1)
2965 SrcExpr = Self.ImpCastExprToType(
2966 SrcExpr.get(), MT->getElementType(), CK_HLSLMatrixTruncation,
2967 SrcExpr.get()->getValueKind(), nullptr, CCK);
2968 // Inserting a scalar cast here allows for a simplified codegen in
2969 // the case the destTy is a vector
2970 if (const VectorType *DVT = DestType->getAs<VectorType>())
2971 SrcExpr = Self.ImpCastExprToType(
2972 SrcExpr.get(), DVT->getElementType(),
2973 Self.PrepareScalarCast(SrcExpr, DVT->getElementType()),
2974 SrcExpr.get()->getValueKind(), nullptr, CCK);
2975 Kind = CK_HLSLAggregateSplatCast;
2976 return true;
2977 }
2978
2979 // If the destination is an array, we've exhausted the valid HLSL casts, so we
2980 // should emit a dignostic and stop processing.
2981 if (DestType->isArrayType()) {
2982 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_generic)
2983 << 4 << SrcTy << DestType;
2984 SrcExpr = ExprError();
2985 return true;
2986 }
2987 return false;
2988}
2989
2990/// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
2991/// non-matching type. Such as enum function call to int, int call to
2992/// pointer; etc. Cast to 'void' is an exception.
2993static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
2994 QualType DestType) {
2995 if (Self.Diags.isIgnored(diag::warn_bad_function_cast,
2996 SrcExpr.get()->getExprLoc()))
2997 return;
2998
2999 if (!isa<CallExpr>(SrcExpr.get()))
3000 return;
3001
3002 QualType SrcType = SrcExpr.get()->getType();
3003 if (DestType.getUnqualifiedType()->isVoidType())
3004 return;
3005 if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
3006 && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
3007 return;
3008 if (SrcType->isIntegerType() && DestType->isIntegerType() &&
3009 (SrcType->isBooleanType() == DestType->isBooleanType()) &&
3010 (SrcType->isEnumeralType() == DestType->isEnumeralType()))
3011 return;
3012 if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
3013 return;
3014 if (SrcType->isEnumeralType() && DestType->isEnumeralType())
3015 return;
3016 if (SrcType->isComplexType() && DestType->isComplexType())
3017 return;
3018 if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
3019 return;
3020 if (SrcType->isFixedPointType() && DestType->isFixedPointType())
3021 return;
3022
3023 Self.Diag(SrcExpr.get()->getExprLoc(),
3024 diag::warn_bad_function_cast)
3025 << SrcType << DestType << SrcExpr.get()->getSourceRange();
3026}
3027
3028/// Check the semantics of a C-style cast operation, in C.
3029void CastOperation::CheckCStyleCast() {
3030 assert(!Self.getLangOpts().CPlusPlus);
3031
3032 // C-style casts can resolve __unknown_any types.
3033 if (claimPlaceholder(BuiltinType::UnknownAny)) {
3034 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
3035 SrcExpr.get(), Kind,
3036 ValueKind, BasePath);
3037 return;
3038 }
3039
3040 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3041 // type needs to be scalar.
3042 if (DestType->isVoidType()) {
3043 // We don't necessarily do lvalue-to-rvalue conversions on this.
3044 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
3045 if (SrcExpr.isInvalid())
3046 return;
3047
3048 // Cast to void allows any expr type.
3049 Kind = CK_ToVoid;
3050 return;
3051 }
3052
3053 // If the type is dependent, we won't do any other semantic analysis now.
3054 if (Self.getASTContext().isDependenceAllowed() &&
3055 (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
3056 SrcExpr.get()->isValueDependent())) {
3057 assert((DestType->containsErrors() || SrcExpr.get()->containsErrors() ||
3058 SrcExpr.get()->containsErrors()) &&
3059 "should only occur in error-recovery path.");
3060 assert(Kind == CK_Dependent);
3061 return;
3062 }
3063
3064 // Overloads are allowed with C extensions, so we need to support them.
3065 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
3066 DeclAccessPair DAP;
3067 if (FunctionDecl *FD = Self.ResolveAddressOfOverloadedFunction(
3068 SrcExpr.get(), DestType, /*Complain=*/true, DAP))
3069 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr.get(), DAP, FD);
3070 else
3071 return;
3072 assert(SrcExpr.isUsable());
3073 }
3074 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
3075 if (SrcExpr.isInvalid())
3076 return;
3077 QualType SrcType = SrcExpr.get()->getType();
3078
3079 if (SrcType->isWebAssemblyTableType()) {
3080 Self.Diag(OpRange.getBegin(), diag::err_wasm_cast_table)
3081 << 1 << SrcExpr.get()->getSourceRange();
3082 SrcExpr = ExprError();
3083 return;
3084 }
3085
3086 assert(!SrcType->isPlaceholderType());
3087
3088 checkAddressSpaceCast(SrcType, DestType);
3089 if (SrcExpr.isInvalid())
3090 return;
3091
3092 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
3093 diag::err_typecheck_cast_to_incomplete)) {
3094 SrcExpr = ExprError();
3095 return;
3096 }
3097
3098 // Allow casting a sizeless built-in type to itself.
3099 if (DestType->isSizelessBuiltinType() &&
3100 Self.Context.hasSameUnqualifiedType(DestType, SrcType)) {
3101 Kind = CK_NoOp;
3102 return;
3103 }
3104
3105 // Allow bitcasting between compatible SVE vector types.
3106 if ((SrcType->isVectorType() || DestType->isVectorType()) &&
3107 Self.isValidSveBitcast(SrcType, DestType)) {
3108 Kind = CK_BitCast;
3109 return;
3110 }
3111
3112 // Allow bitcasting between compatible RVV vector types.
3113 if ((SrcType->isVectorType() || DestType->isVectorType()) &&
3114 Self.RISCV().isValidRVVBitcast(SrcType, DestType)) {
3115 Kind = CK_BitCast;
3116 return;
3117 }
3118
3119 if (!DestType->isScalarType() && !DestType->isVectorType() &&
3120 !DestType->isMatrixType()) {
3121 if (const RecordType *DestRecordTy =
3122 DestType->getAsCanonical<RecordType>()) {
3123 if (Self.Context.hasSameUnqualifiedType(DestType, SrcType)) {
3124 // GCC struct/union extension: allow cast to self.
3125 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
3126 << DestType << SrcExpr.get()->getSourceRange();
3127 Kind = CK_NoOp;
3128 return;
3129 }
3130
3131 // GCC's cast to union extension.
3132 if (RecordDecl *RD = DestRecordTy->getDecl(); RD->isUnion()) {
3133 if (CastExpr::getTargetFieldForToUnionCast(RD->getDefinitionOrSelf(),
3134 SrcType)) {
3135 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
3136 << SrcExpr.get()->getSourceRange();
3137 Kind = CK_ToUnion;
3138 return;
3139 }
3140 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3141 << SrcType << SrcExpr.get()->getSourceRange();
3142 SrcExpr = ExprError();
3143 return;
3144 }
3145 }
3146
3147 // OpenCL v2.0 s6.13.10 - Allow casts from '0' to event_t type.
3148 if (Self.getLangOpts().OpenCL && DestType->isEventT()) {
3150 if (SrcExpr.get()->EvaluateAsInt(Result, Self.Context)) {
3151 llvm::APSInt CastInt = Result.Val.getInt();
3152 if (0 == CastInt) {
3153 Kind = CK_ZeroToOCLOpaqueType;
3154 return;
3155 }
3156 Self.Diag(OpRange.getBegin(),
3157 diag::err_opencl_cast_non_zero_to_event_t)
3158 << toString(CastInt, 10) << SrcExpr.get()->getSourceRange();
3159 SrcExpr = ExprError();
3160 return;
3161 }
3162 }
3163
3164 // Reject any other conversions to non-scalar types.
3165 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
3166 << DestType << SrcExpr.get()->getSourceRange();
3167 SrcExpr = ExprError();
3168 return;
3169 }
3170
3171 // The type we're casting to is known to be a scalar, a vector, or a matrix.
3172
3173 // Require the operand to be a scalar, a vector, or a matrix.
3174 if (!SrcType->isScalarType() && !SrcType->isVectorType() &&
3175 !SrcType->isMatrixType()) {
3176 Self.Diag(SrcExpr.get()->getExprLoc(),
3177 diag::err_typecheck_expect_scalar_operand)
3178 << SrcType << SrcExpr.get()->getSourceRange();
3179 SrcExpr = ExprError();
3180 return;
3181 }
3182
3183 // C23 6.5.5p4:
3184 // ... The type nullptr_t shall not be converted to any type other than
3185 // void, bool or a pointer type.If the target type is nullptr_t, the cast
3186 // expression shall be a null pointer constant or have type nullptr_t.
3187 if (SrcType->isNullPtrType()) {
3188 // FIXME: 6.3.2.4p2 says that nullptr_t can be converted to itself, but
3189 // 6.5.4p4 is a constraint check and nullptr_t is not void, bool, or a
3190 // pointer type. We're not going to diagnose that as a constraint violation.
3191 if (!DestType->isVoidType() && !DestType->isBooleanType() &&
3192 !DestType->isPointerType() && !DestType->isNullPtrType()) {
3193 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_nullptr_cast)
3194 << /*nullptr to type*/ 0 << DestType;
3195 SrcExpr = ExprError();
3196 return;
3197 }
3198 if (DestType->isBooleanType()) {
3199 SrcExpr = ImplicitCastExpr::Create(
3200 Self.Context, DestType, CK_PointerToBoolean, SrcExpr.get(), nullptr,
3201 VK_PRValue, Self.CurFPFeatureOverrides());
3202
3203 } else if (!DestType->isNullPtrType()) {
3204 // Implicitly cast from the null pointer type to the type of the
3205 // destination.
3206 CastKind CK = DestType->isPointerType() ? CK_NullToPointer : CK_BitCast;
3207 SrcExpr = ImplicitCastExpr::Create(Self.Context, DestType, CK,
3208 SrcExpr.get(), nullptr, VK_PRValue,
3209 Self.CurFPFeatureOverrides());
3210 }
3211 }
3212
3213 if (DestType->isNullPtrType() && !SrcType->isNullPtrType()) {
3214 if (!SrcExpr.get()->isNullPointerConstant(Self.Context,
3216 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_nullptr_cast)
3217 << /*type to nullptr*/ 1 << SrcType;
3218 SrcExpr = ExprError();
3219 return;
3220 }
3221 // Need to convert the source from whatever its type is to a null pointer
3222 // type first.
3223 SrcExpr = ImplicitCastExpr::Create(Self.Context, DestType, CK_NullToPointer,
3224 SrcExpr.get(), nullptr, VK_PRValue,
3225 Self.CurFPFeatureOverrides());
3226 }
3227
3228 if (DestType->isExtVectorType()) {
3229 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind);
3230 return;
3231 }
3232
3233 if (DestType->getAs<MatrixType>() || SrcType->getAs<MatrixType>()) {
3234 if (Self.CheckMatrixCast(OpRange, DestType, SrcType, Kind))
3235 SrcExpr = ExprError();
3236 return;
3237 }
3238
3239 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
3240 if (Self.CheckAltivecInitFromScalar(OpRange, DestType, SrcType)) {
3241 SrcExpr = ExprError();
3242 return;
3243 }
3244 if (Self.ShouldSplatAltivecScalarInCast(DestVecTy) &&
3245 (SrcType->isIntegerType() || SrcType->isFloatingType())) {
3246 Kind = CK_VectorSplat;
3247 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
3248 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
3249 SrcExpr = ExprError();
3250 }
3251 return;
3252 }
3253
3254 if (SrcType->isVectorType()) {
3255 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
3256 SrcExpr = ExprError();
3257 return;
3258 }
3259
3260 // The source and target types are both scalars, i.e.
3261 // - arithmetic types (fundamental, enum, and complex)
3262 // - all kinds of pointers
3263 // Note that member pointers were filtered out with C++, above.
3264
3265 if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
3266 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
3267 SrcExpr = ExprError();
3268 return;
3269 }
3270
3271 // If either type is a pointer, the other type has to be either an
3272 // integer or a pointer.
3273 if (!DestType->isArithmeticType()) {
3274 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
3275 Self.Diag(SrcExpr.get()->getExprLoc(),
3276 diag::err_cast_pointer_from_non_pointer_int)
3277 << SrcType << SrcExpr.get()->getSourceRange();
3278 SrcExpr = ExprError();
3279 return;
3280 }
3281 checkIntToPointerCast(/* CStyle */ true, OpRange, SrcExpr.get(), DestType,
3282 Self);
3283 } else if (!SrcType->isArithmeticType()) {
3284 if (!DestType->isIntegralType(Self.Context) &&
3285 DestType->isArithmeticType()) {
3286 Self.Diag(SrcExpr.get()->getBeginLoc(),
3287 diag::err_cast_pointer_to_non_pointer_int)
3288 << DestType << SrcExpr.get()->getSourceRange();
3289 SrcExpr = ExprError();
3290 return;
3291 }
3292
3293 if ((Self.Context.getTypeSize(SrcType) >
3294 Self.Context.getTypeSize(DestType)) &&
3295 !DestType->isBooleanType()) {
3296 // C 6.3.2.3p6: Any pointer type may be converted to an integer type.
3297 // Except as previously specified, the result is implementation-defined.
3298 // If the result cannot be represented in the integer type, the behavior
3299 // is undefined. The result need not be in the range of values of any
3300 // integer type.
3301 unsigned Diag;
3302 if (SrcType->isVoidPointerType())
3303 Diag = DestType->isEnumeralType() ? diag::warn_void_pointer_to_enum_cast
3304 : diag::warn_void_pointer_to_int_cast;
3305 else if (DestType->isEnumeralType())
3306 Diag = diag::warn_pointer_to_enum_cast;
3307 else
3308 Diag = diag::warn_pointer_to_int_cast;
3309 Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange;
3310 }
3311 }
3312
3313 if (Self.getLangOpts().OpenCL && !Self.getOpenCLOptions().isAvailableOption(
3314 "cl_khr_fp16", Self.getLangOpts())) {
3315 if (DestType->isHalfType()) {
3316 Self.Diag(SrcExpr.get()->getBeginLoc(), diag::err_opencl_cast_to_half)
3317 << DestType << SrcExpr.get()->getSourceRange();
3318 SrcExpr = ExprError();
3319 return;
3320 }
3321 }
3322
3323 // ARC imposes extra restrictions on casts.
3324 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) {
3325 checkObjCConversion(CheckedConversionKind::CStyleCast);
3326 if (SrcExpr.isInvalid())
3327 return;
3328
3329 const PointerType *CastPtr = DestType->getAs<PointerType>();
3330 if (Self.getLangOpts().ObjCAutoRefCount && CastPtr) {
3331 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
3332 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
3333 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
3334 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
3335 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
3336 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
3337 Self.Diag(SrcExpr.get()->getBeginLoc(),
3338 diag::err_typecheck_incompatible_ownership)
3339 << SrcType << DestType << AssignmentAction::Casting
3340 << SrcExpr.get()->getSourceRange();
3341 return;
3342 }
3343 }
3344 } else if (!Self.ObjC().CheckObjCARCUnavailableWeakConversion(DestType,
3345 SrcType)) {
3346 Self.Diag(SrcExpr.get()->getBeginLoc(),
3347 diag::err_arc_convesion_of_weak_unavailable)
3348 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
3349 SrcExpr = ExprError();
3350 return;
3351 }
3352 }
3353
3354 if (unsigned DiagID = checkCastFunctionType(Self, SrcExpr, DestType))
3355 Self.Diag(OpRange.getBegin(), DiagID) << SrcType << DestType << OpRange;
3356
3357 if (isa<PointerType>(SrcType) && isa<PointerType>(DestType)) {
3358 QualType SrcTy = cast<PointerType>(SrcType)->getPointeeType();
3359 QualType DestTy = cast<PointerType>(DestType)->getPointeeType();
3360
3361 const RecordDecl *SrcRD = SrcTy->getAsRecordDecl();
3362 const RecordDecl *DestRD = DestTy->getAsRecordDecl();
3363
3364 if (SrcRD && DestRD && SrcRD->hasAttr<RandomizeLayoutAttr>() &&
3365 SrcRD != DestRD) {
3366 // The struct we are casting the pointer from was randomized.
3367 Self.Diag(OpRange.getBegin(), diag::err_cast_from_randomized_struct)
3368 << SrcType << DestType;
3369 SrcExpr = ExprError();
3370 return;
3371 }
3372 }
3373
3374 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
3375 DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
3376 DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
3377 Kind = Self.PrepareScalarCast(SrcExpr, DestType);
3378 if (SrcExpr.isInvalid())
3379 return;
3380
3381 if (Kind == CK_BitCast)
3382 checkCastAlign();
3383}
3384
3385void CastOperation::CheckBuiltinBitCast() {
3386 QualType SrcType = SrcExpr.get()->getType();
3387
3388 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
3389 diag::err_typecheck_cast_to_incomplete) ||
3390 Self.RequireCompleteType(OpRange.getBegin(), SrcType,
3391 diag::err_incomplete_type)) {
3392 SrcExpr = ExprError();
3393 return;
3394 }
3395
3396 if (SrcExpr.get()->isPRValue())
3397 SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcType, SrcExpr.get(),
3398 /*IsLValueReference=*/false);
3399
3400 CharUnits DestSize = Self.Context.getTypeSizeInChars(DestType);
3401 CharUnits SourceSize = Self.Context.getTypeSizeInChars(SrcType);
3402 if (DestSize != SourceSize) {
3403 Self.Diag(OpRange.getBegin(), diag::err_bit_cast_type_size_mismatch)
3404 << SrcType << DestType << (int)SourceSize.getQuantity()
3405 << (int)DestSize.getQuantity();
3406 SrcExpr = ExprError();
3407 return;
3408 }
3409
3410 if (!DestType.isTriviallyCopyableType(Self.Context)) {
3411 Self.Diag(OpRange.getBegin(), diag::err_bit_cast_non_trivially_copyable)
3412 << 1;
3413 SrcExpr = ExprError();
3414 return;
3415 }
3416
3417 if (!SrcType.isTriviallyCopyableType(Self.Context)) {
3418 Self.Diag(OpRange.getBegin(), diag::err_bit_cast_non_trivially_copyable)
3419 << 0;
3420 SrcExpr = ExprError();
3421 return;
3422 }
3423
3424 Kind = CK_LValueToRValueBitCast;
3425}
3426
3427/// DiagnoseCastQual - Warn whenever casts discards a qualifiers, be it either
3428/// const, volatile or both.
3429static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
3430 QualType DestType) {
3431 if (SrcExpr.isInvalid())
3432 return;
3433
3434 QualType SrcType = SrcExpr.get()->getType();
3435 if (!((SrcType->isAnyPointerType() && DestType->isAnyPointerType()) ||
3436 DestType->isLValueReferenceType()))
3437 return;
3438
3439 QualType TheOffendingSrcType, TheOffendingDestType;
3440 Qualifiers CastAwayQualifiers;
3441 if (CastsAwayConstness(Self, SrcType, DestType, true, false,
3442 &TheOffendingSrcType, &TheOffendingDestType,
3443 &CastAwayQualifiers) !=
3444 CastAwayConstnessKind::CACK_Similar)
3445 return;
3446
3447 // FIXME: 'restrict' is not properly handled here.
3448 int qualifiers = -1;
3449 if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) {
3450 qualifiers = 0;
3451 } else if (CastAwayQualifiers.hasConst()) {
3452 qualifiers = 1;
3453 } else if (CastAwayQualifiers.hasVolatile()) {
3454 qualifiers = 2;
3455 }
3456 // This is a variant of int **x; const int **y = (const int **)x;
3457 if (qualifiers == -1)
3458 Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual2)
3459 << SrcType << DestType;
3460 else
3461 Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual)
3462 << TheOffendingSrcType << TheOffendingDestType << qualifiers;
3463}
3464
3466 TypeSourceInfo *CastTypeInfo,
3467 SourceLocation RPLoc,
3468 Expr *CastExpr) {
3469 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
3470 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
3471 Op.OpRange = CastOperation::OpRangeType(LPLoc, LPLoc, CastExpr->getEndLoc());
3472
3473 if (getLangOpts().CPlusPlus) {
3474 Op.CheckCXXCStyleCast(/*FunctionalCast=*/ false,
3476 } else {
3477 Op.CheckCStyleCast();
3478 }
3479
3480 if (Op.SrcExpr.isInvalid())
3481 return ExprError();
3482
3483 // -Wcast-qual
3484 DiagnoseCastQual(Op.Self, Op.SrcExpr, Op.DestType);
3485
3486 Op.checkQualifiedDestType();
3487
3488 return Op.complete(CStyleCastExpr::Create(
3489 Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
3490 &Op.BasePath, CurFPFeatureOverrides(), CastTypeInfo, LPLoc, RPLoc));
3491}
3492
3494 QualType Type,
3495 SourceLocation LPLoc,
3496 Expr *CastExpr,
3497 SourceLocation RPLoc) {
3498 assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
3499 CastOperation Op(*this, Type, CastExpr);
3500 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
3501 Op.OpRange =
3502 CastOperation::OpRangeType(Op.DestRange.getBegin(), LPLoc, RPLoc);
3503
3504 Op.CheckCXXCStyleCast(/*FunctionalCast=*/true, /*ListInit=*/false);
3505 if (Op.SrcExpr.isInvalid())
3506 return ExprError();
3507
3508 Op.checkQualifiedDestType();
3509
3510 // -Wcast-qual
3511 DiagnoseCastQual(Op.Self, Op.SrcExpr, Op.DestType);
3512
3513 return Op.complete(CXXFunctionalCastExpr::Create(
3514 Context, Op.ResultType, Op.ValueKind, CastTypeInfo, Op.Kind,
3515 Op.SrcExpr.get(), &Op.BasePath, CurFPFeatureOverrides(), LPLoc, RPLoc));
3516}
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:223
const LangOptions & getLangOpts() const
Definition ASTContext.h:959
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:5472
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:2111
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:913
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:899
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:813
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:925
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2145
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2284
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
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:877
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:787
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:3682
static const FieldDecl * getTargetFieldForToUnionCast(QualType unionType, QualType opType)
Definition Expr.cpp:2040
Expr * getSubExpr()
Definition Expr.h:3732
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition CharUnits.h:53
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4451
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:4260
This represents one expression.
Definition Expr.h:112
bool isIntegerConstantExpr(const ASTContext &Ctx) const
bool isGLValue() const
Definition Expr.h:287
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3099
bool isPRValue() const
Definition Expr.h:285
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition Expr.h:833
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:454
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:479
QualType getType() const
Definition Expr.h:144
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:437
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:141
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:104
Represents a function declaration or definition.
Definition Decl.h:2018
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5371
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4567
static StringRef getNameForCallConv(CallingConv CC)
Definition Type.cpp:3704
CallingConv getCallConv() const
Definition TypeBase.h:4922
QualType getReturnType() const
Definition TypeBase.h:4907
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:2079
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:4401
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3717
bool isMemberFunctionPointer() const
Returns true if the member type (i.e.
Definition TypeBase.h:3739
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:1160
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1376
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:3132
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3193
NestedNameSpecifierLoc getQualifierLoc() const
Fetches the nested-name qualifier with source-location information, if one was given.
Definition ExprCXX.h:3254
DeclarationName getName() const
Gets the name looked up.
Definition ExprCXX.h:3242
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3392
QualType getPointeeType() const
Definition TypeBase.h:3402
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:937
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2966
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3682
bool isAddressSpaceOverlapping(QualType T, const ASTContext &Ctx) const
Returns true if address space qualifiers overlap with T address space qualifiers.
Definition TypeBase.h:1431
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8447
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8573
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8487
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:8632
QualType getCanonicalType() const
Definition TypeBase.h:8499
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8541
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1194
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8493
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1347
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:8612
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
unsigned getCVRQualifiers() const
Definition TypeBase.h:488
void removeObjCLifetime()
Definition TypeBase.h:551
bool hasConst() const
Definition TypeBase.h:457
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition TypeBase.h:727
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:708
void removeObjCGCAttr()
Definition TypeBase.h:523
static Qualifiers fromCVRMask(unsigned CVR)
Definition TypeBase.h:435
bool hasVolatile() const
Definition TypeBase.h:467
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition TypeBase.h:750
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3699
Represents a struct/union/class.
Definition Decl.h:4347
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4531
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3637
QualType getPointeeType() const
Definition TypeBase.h:3655
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:868
ReferenceCompareResult
ReferenceCompareResult - Expresses the result of comparing two types (cv1 T1 and cv2 T2) to determine...
Definition Sema.h:10492
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10495
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10501
@ AR_dependent
Definition Sema.h:1688
@ AR_accessible
Definition Sema.h:1686
@ AR_inaccessible
Definition Sema.h:1687
@ AR_delayed
Definition Sema.h:1689
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:2077
ASTContext & Context
Definition Sema.h:1308
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:932
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:10520
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:1310
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:1805
StringRef getString() const
Definition Expr.h:1873
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3840
bool isUnion() const
Definition Decl.h:3950
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:8418
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:8429
The base class of the type hierarchy.
Definition TypeBase.h:1875
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2545
bool isBlockPointerType() const
Definition TypeBase.h:8704
bool isVoidType() const
Definition TypeBase.h:9050
bool isBooleanType() const
Definition TypeBase.h:9187
bool isFunctionReferenceType() const
Definition TypeBase.h:8758
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:9026
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2266
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:761
bool isRValueReferenceType() const
Definition TypeBase.h:8716
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:8787
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isVoidPointerType() const
Definition Type.cpp:749
bool isArrayType() const
Definition TypeBase.h:8783
bool isFunctionPointerType() const
Definition TypeBase.h:8751
bool isArithmeticType() const
Definition Type.cpp:2422
bool isPointerType() const
Definition TypeBase.h:8684
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9094
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9344
bool isReferenceType() const
Definition TypeBase.h:8708
bool isEnumeralType() const
Definition TypeBase.h:8815
bool isScalarType() const
Definition TypeBase.h:9156
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:1958
bool isSizelessBuiltinType() const
Definition Type.cpp:2623
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2156
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9172
bool isExtVectorType() const
Definition TypeBase.h:8827
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition Type.cpp:2229
bool isLValueReferenceType() const
Definition TypeBase.h:8712
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2846
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9110
bool isHalfType() const
Definition TypeBase.h:9054
const BuiltinType * getAsPlaceholderType() const
Definition TypeBase.h:9032
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2651
bool containsErrors() const
Whether this type is an error type.
Definition TypeBase.h:2840
bool isMemberPointerType() const
Definition TypeBase.h:8765
bool isMatrixType() const
Definition TypeBase.h:8847
EnumDecl * castAsEnumDecl() const
Definition Type.h:59
bool isComplexIntegerType() const
Definition Type.cpp:767
bool isObjCObjectType() const
Definition TypeBase.h:8867
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition Type.cpp:5450
bool isEventT() const
Definition TypeBase.h:8932
bool isFunctionType() const
Definition TypeBase.h:8680
bool isObjCObjectPointerType() const
Definition TypeBase.h:8863
bool isMemberFunctionPointerType() const
Definition TypeBase.h:8769
bool isVectorType() const
Definition TypeBase.h:8823
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2405
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2985
bool isFloatingType() const
Definition Type.cpp:2389
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:2332
bool isAnyPointerType() const
Definition TypeBase.h:8692
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9277
bool isNullPtrType() const
Definition TypeBase.h:9087
bool isRecordType() const
Definition TypeBase.h:8811
bool isFunctionNoProtoType() const
Definition TypeBase.h:2660
Represents a GCC generic vector type.
Definition TypeBase.h:4239
unsigned getNumElements() const
Definition TypeBase.h:4254
VectorKind getVectorKind() const
Definition TypeBase.h:4259
QualType getElementType() const
Definition TypeBase.h:4253
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:25
The JSON file list parser is used to communicate input to InstallAPI.
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:905
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:4209
@ AltiVecVector
is AltiVec vector
Definition TypeBase.h:4203
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4206
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:5984
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:438
@ CStyleCast
A C-style cast.
Definition Sema.h:442
@ OtherCast
A cast other than a C-style cast.
Definition Sema.h:446
@ FunctionalCast
A functional-style cast.
Definition Sema.h:444
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:652