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