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