1 //===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements semantic analysis for statements.
11 //===----------------------------------------------------------------------===//
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/ASTDiagnostic.h"
15 #include "clang/AST/ASTLambda.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/CharUnits.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/EvaluatedExprVisitor.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/IgnoreExpr.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/AST/TypeOrdering.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Lex/Preprocessor.h"
30 #include "clang/Sema/EnterExpressionEvaluationContext.h"
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/Ownership.h"
34 #include "clang/Sema/Scope.h"
35 #include "clang/Sema/ScopeInfo.h"
36 #include "clang/Sema/SemaCUDA.h"
37 #include "clang/Sema/SemaInternal.h"
38 #include "llvm/ADT/ArrayRef.h"
39 #include "llvm/ADT/DenseMap.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/ADT/STLForwardCompat.h"
42 #include "llvm/ADT/SmallPtrSet.h"
43 #include "llvm/ADT/SmallString.h"
44 #include "llvm/ADT/SmallVector.h"
45 #include "llvm/ADT/StringExtras.h"
47 using namespace clang
;
50 StmtResult
Sema::ActOnExprStmt(ExprResult FE
, bool DiscardedValue
) {
54 FE
= ActOnFinishFullExpr(FE
.get(), FE
.get()->getExprLoc(), DiscardedValue
);
58 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
59 // void expression for its side effects. Conversion to void allows any
60 // operand, even incomplete types.
62 // Same thing in for stmt first clause (when expr) and third clause.
63 return StmtResult(FE
.getAs
<Stmt
>());
67 StmtResult
Sema::ActOnExprStmtError() {
68 DiscardCleanupsInEvaluationContext();
72 StmtResult
Sema::ActOnNullStmt(SourceLocation SemiLoc
,
73 bool HasLeadingEmptyMacro
) {
74 return new (Context
) NullStmt(SemiLoc
, HasLeadingEmptyMacro
);
77 StmtResult
Sema::ActOnDeclStmt(DeclGroupPtrTy dg
, SourceLocation StartLoc
,
78 SourceLocation EndLoc
) {
79 DeclGroupRef DG
= dg
.get();
81 // If we have an invalid decl, just return an error.
82 if (DG
.isNull()) return StmtError();
84 return new (Context
) DeclStmt(DG
, StartLoc
, EndLoc
);
87 void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg
) {
88 DeclGroupRef DG
= dg
.get();
90 // If we don't have a declaration, or we have an invalid declaration,
92 if (DG
.isNull() || !DG
.isSingleDecl())
95 Decl
*decl
= DG
.getSingleDecl();
96 if (!decl
|| decl
->isInvalidDecl())
99 // Only variable declarations are permitted.
100 VarDecl
*var
= dyn_cast
<VarDecl
>(decl
);
102 Diag(decl
->getLocation(), diag::err_non_variable_decl_in_for
);
103 decl
->setInvalidDecl();
107 // foreach variables are never actually initialized in the way that
108 // the parser came up with.
109 var
->setInit(nullptr);
111 // In ARC, we don't need to retain the iteration variable of a fast
112 // enumeration loop. Rather than actually trying to catch that
113 // during declaration processing, we remove the consequences here.
114 if (getLangOpts().ObjCAutoRefCount
) {
115 QualType type
= var
->getType();
117 // Only do this if we inferred the lifetime. Inferred lifetime
118 // will show up as a local qualifier because explicit lifetime
119 // should have shown up as an AttributedType instead.
120 if (type
.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong
) {
121 // Add 'const' and mark the variable as pseudo-strong.
122 var
->setType(type
.withConst());
123 var
->setARCPseudoStrong(true);
128 /// Diagnose unused comparisons, both builtin and overloaded operators.
129 /// For '==' and '!=', suggest fixits for '=' or '|='.
131 /// Adding a cast to void (or other expression wrappers) will prevent the
132 /// warning from firing.
133 static bool DiagnoseUnusedComparison(Sema
&S
, const Expr
*E
) {
136 enum { Equality
, Inequality
, Relational
, ThreeWay
} Kind
;
138 if (const BinaryOperator
*Op
= dyn_cast
<BinaryOperator
>(E
)) {
139 if (!Op
->isComparisonOp())
142 if (Op
->getOpcode() == BO_EQ
)
144 else if (Op
->getOpcode() == BO_NE
)
146 else if (Op
->getOpcode() == BO_Cmp
)
149 assert(Op
->isRelationalOp());
152 Loc
= Op
->getOperatorLoc();
153 CanAssign
= Op
->getLHS()->IgnoreParenImpCasts()->isLValue();
154 } else if (const CXXOperatorCallExpr
*Op
= dyn_cast
<CXXOperatorCallExpr
>(E
)) {
155 switch (Op
->getOperator()) {
159 case OO_ExclaimEqual
:
164 case OO_GreaterEqual
:
175 Loc
= Op
->getOperatorLoc();
176 CanAssign
= Op
->getArg(0)->IgnoreParenImpCasts()->isLValue();
178 // Not a typo-prone comparison.
182 // Suppress warnings when the operator, suspicious as it may be, comes from
183 // a macro expansion.
184 if (S
.SourceMgr
.isMacroBodyExpansion(Loc
))
187 S
.Diag(Loc
, diag::warn_unused_comparison
)
188 << (unsigned)Kind
<< E
->getSourceRange();
190 // If the LHS is a plausible entity to assign to, provide a fixit hint to
191 // correct common typos.
193 if (Kind
== Inequality
)
194 S
.Diag(Loc
, diag::note_inequality_comparison_to_or_assign
)
195 << FixItHint::CreateReplacement(Loc
, "|=");
196 else if (Kind
== Equality
)
197 S
.Diag(Loc
, diag::note_equality_comparison_to_assign
)
198 << FixItHint::CreateReplacement(Loc
, "=");
204 static bool DiagnoseNoDiscard(Sema
&S
, const WarnUnusedResultAttr
*A
,
205 SourceLocation Loc
, SourceRange R1
,
206 SourceRange R2
, bool IsCtor
) {
209 StringRef Msg
= A
->getMessage();
213 return S
.Diag(Loc
, diag::warn_unused_constructor
) << A
<< R1
<< R2
;
214 return S
.Diag(Loc
, diag::warn_unused_result
) << A
<< R1
<< R2
;
218 return S
.Diag(Loc
, diag::warn_unused_constructor_msg
) << A
<< Msg
<< R1
220 return S
.Diag(Loc
, diag::warn_unused_result_msg
) << A
<< Msg
<< R1
<< R2
;
223 void Sema::DiagnoseUnusedExprResult(const Stmt
*S
, unsigned DiagID
) {
224 if (const LabelStmt
*Label
= dyn_cast_or_null
<LabelStmt
>(S
))
225 return DiagnoseUnusedExprResult(Label
->getSubStmt(), DiagID
);
227 const Expr
*E
= dyn_cast_or_null
<Expr
>(S
);
231 // If we are in an unevaluated expression context, then there can be no unused
232 // results because the results aren't expected to be used in the first place.
233 if (isUnevaluatedContext())
236 SourceLocation ExprLoc
= E
->IgnoreParenImpCasts()->getExprLoc();
237 // In most cases, we don't want to warn if the expression is written in a
238 // macro body, or if the macro comes from a system header. If the offending
239 // expression is a call to a function with the warn_unused_result attribute,
240 // we warn no matter the location. Because of the order in which the various
241 // checks need to happen, we factor out the macro-related test here.
242 bool ShouldSuppress
=
243 SourceMgr
.isMacroBodyExpansion(ExprLoc
) ||
244 SourceMgr
.isInSystemMacro(ExprLoc
);
246 const Expr
*WarnExpr
;
249 if (!E
->isUnusedResultAWarning(WarnExpr
, Loc
, R1
, R2
, Context
))
252 // If this is a GNU statement expression expanded from a macro, it is probably
253 // unused because it is a function-like macro that can be used as either an
254 // expression or statement. Don't warn, because it is almost certainly a
256 if (isa
<StmtExpr
>(E
) && Loc
.isMacroID())
259 // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers.
260 // That macro is frequently used to suppress "unused parameter" warnings,
261 // but its implementation makes clang's -Wunused-value fire. Prevent this.
262 if (isa
<ParenExpr
>(E
->IgnoreImpCasts()) && Loc
.isMacroID()) {
263 SourceLocation SpellLoc
= Loc
;
264 if (findMacroSpelling(SpellLoc
, "UNREFERENCED_PARAMETER"))
268 // Okay, we have an unused result. Depending on what the base expression is,
269 // we might want to make a more specific diagnostic. Check for one of these
271 if (const FullExpr
*Temps
= dyn_cast
<FullExpr
>(E
))
272 E
= Temps
->getSubExpr();
273 if (const CXXBindTemporaryExpr
*TempExpr
= dyn_cast
<CXXBindTemporaryExpr
>(E
))
274 E
= TempExpr
->getSubExpr();
276 if (DiagnoseUnusedComparison(*this, E
))
280 if (const auto *Cast
= dyn_cast
<CastExpr
>(E
))
281 if (Cast
->getCastKind() == CK_NoOp
||
282 Cast
->getCastKind() == CK_ConstructorConversion
)
283 E
= Cast
->getSubExpr()->IgnoreImpCasts();
285 if (const CallExpr
*CE
= dyn_cast
<CallExpr
>(E
)) {
286 if (E
->getType()->isVoidType())
289 if (DiagnoseNoDiscard(*this, cast_or_null
<WarnUnusedResultAttr
>(
290 CE
->getUnusedResultAttr(Context
)),
291 Loc
, R1
, R2
, /*isCtor=*/false))
294 // If the callee has attribute pure, const, or warn_unused_result, warn with
295 // a more specific message to make it clear what is happening. If the call
296 // is written in a macro body, only warn if it has the warn_unused_result
298 if (const Decl
*FD
= CE
->getCalleeDecl()) {
301 if (FD
->hasAttr
<PureAttr
>()) {
302 Diag(Loc
, diag::warn_unused_call
) << R1
<< R2
<< "pure";
305 if (FD
->hasAttr
<ConstAttr
>()) {
306 Diag(Loc
, diag::warn_unused_call
) << R1
<< R2
<< "const";
310 } else if (const auto *CE
= dyn_cast
<CXXConstructExpr
>(E
)) {
311 if (const CXXConstructorDecl
*Ctor
= CE
->getConstructor()) {
312 const auto *A
= Ctor
->getAttr
<WarnUnusedResultAttr
>();
313 A
= A
? A
: Ctor
->getParent()->getAttr
<WarnUnusedResultAttr
>();
314 if (DiagnoseNoDiscard(*this, A
, Loc
, R1
, R2
, /*isCtor=*/true))
317 } else if (const auto *ILE
= dyn_cast
<InitListExpr
>(E
)) {
318 if (const TagDecl
*TD
= ILE
->getType()->getAsTagDecl()) {
320 if (DiagnoseNoDiscard(*this, TD
->getAttr
<WarnUnusedResultAttr
>(), Loc
, R1
,
321 R2
, /*isCtor=*/false))
324 } else if (ShouldSuppress
)
328 if (const ObjCMessageExpr
*ME
= dyn_cast
<ObjCMessageExpr
>(E
)) {
329 if (getLangOpts().ObjCAutoRefCount
&& ME
->isDelegateInitCall()) {
330 Diag(Loc
, diag::err_arc_unused_init_message
) << R1
;
333 const ObjCMethodDecl
*MD
= ME
->getMethodDecl();
335 if (DiagnoseNoDiscard(*this, MD
->getAttr
<WarnUnusedResultAttr
>(), Loc
, R1
,
336 R2
, /*isCtor=*/false))
339 } else if (const PseudoObjectExpr
*POE
= dyn_cast
<PseudoObjectExpr
>(E
)) {
340 const Expr
*Source
= POE
->getSyntacticForm();
341 // Handle the actually selected call of an OpenMP specialized call.
342 if (LangOpts
.OpenMP
&& isa
<CallExpr
>(Source
) &&
343 POE
->getNumSemanticExprs() == 1 &&
344 isa
<CallExpr
>(POE
->getSemanticExpr(0)))
345 return DiagnoseUnusedExprResult(POE
->getSemanticExpr(0), DiagID
);
346 if (isa
<ObjCSubscriptRefExpr
>(Source
))
347 DiagID
= diag::warn_unused_container_subscript_expr
;
348 else if (isa
<ObjCPropertyRefExpr
>(Source
))
349 DiagID
= diag::warn_unused_property_expr
;
350 } else if (const CXXFunctionalCastExpr
*FC
351 = dyn_cast
<CXXFunctionalCastExpr
>(E
)) {
352 const Expr
*E
= FC
->getSubExpr();
353 if (const CXXBindTemporaryExpr
*TE
= dyn_cast
<CXXBindTemporaryExpr
>(E
))
354 E
= TE
->getSubExpr();
355 if (isa
<CXXTemporaryObjectExpr
>(E
))
357 if (const CXXConstructExpr
*CE
= dyn_cast
<CXXConstructExpr
>(E
))
358 if (const CXXRecordDecl
*RD
= CE
->getType()->getAsCXXRecordDecl())
359 if (!RD
->getAttr
<WarnUnusedAttr
>())
362 // Diagnose "(void*) blah" as a typo for "(void) blah".
363 else if (const CStyleCastExpr
*CE
= dyn_cast
<CStyleCastExpr
>(E
)) {
364 TypeSourceInfo
*TI
= CE
->getTypeInfoAsWritten();
365 QualType T
= TI
->getType();
367 // We really do want to use the non-canonical type here.
368 if (T
== Context
.VoidPtrTy
) {
369 PointerTypeLoc TL
= TI
->getTypeLoc().castAs
<PointerTypeLoc
>();
371 Diag(Loc
, diag::warn_unused_voidptr
)
372 << FixItHint::CreateRemoval(TL
.getStarLoc());
377 // Tell the user to assign it into a variable to force a volatile load if this
379 if (E
->isGLValue() && E
->getType().isVolatileQualified() &&
380 !E
->getType()->isArrayType()) {
381 Diag(Loc
, diag::warn_unused_volatile
) << R1
<< R2
;
385 // Do not diagnose use of a comma operator in a SFINAE context because the
386 // type of the left operand could be used for SFINAE, so technically it is
388 if (DiagID
!= diag::warn_unused_comma_left_operand
|| !isSFINAEContext())
389 DiagIfReachable(Loc
, S
? llvm::ArrayRef(S
) : std::nullopt
,
390 PDiag(DiagID
) << R1
<< R2
);
393 void Sema::ActOnStartOfCompoundStmt(bool IsStmtExpr
) {
394 PushCompoundScope(IsStmtExpr
);
397 void Sema::ActOnAfterCompoundStatementLeadingPragmas() {
398 if (getCurFPFeatures().isFPConstrained()) {
399 FunctionScopeInfo
*FSI
= getCurFunction();
401 FSI
->setUsesFPIntrin();
405 void Sema::ActOnFinishOfCompoundStmt() {
409 sema::CompoundScopeInfo
&Sema::getCurCompoundScope() const {
410 return getCurFunction()->CompoundScopes
.back();
413 StmtResult
Sema::ActOnCompoundStmt(SourceLocation L
, SourceLocation R
,
414 ArrayRef
<Stmt
*> Elts
, bool isStmtExpr
) {
415 const unsigned NumElts
= Elts
.size();
417 // If we're in C mode, check that we don't have any decls after stmts. If
418 // so, emit an extension diagnostic in C89 and potentially a warning in later
420 const unsigned MixedDeclsCodeID
= getLangOpts().C99
421 ? diag::warn_mixed_decls_code
422 : diag::ext_mixed_decls_code
;
423 if (!getLangOpts().CPlusPlus
&& !Diags
.isIgnored(MixedDeclsCodeID
, L
)) {
424 // Note that __extension__ can be around a decl.
426 // Skip over all declarations.
427 for (; i
!= NumElts
&& isa
<DeclStmt
>(Elts
[i
]); ++i
)
430 // We found the end of the list or a statement. Scan for another declstmt.
431 for (; i
!= NumElts
&& !isa
<DeclStmt
>(Elts
[i
]); ++i
)
435 Decl
*D
= *cast
<DeclStmt
>(Elts
[i
])->decl_begin();
436 Diag(D
->getLocation(), MixedDeclsCodeID
);
440 // Check for suspicious empty body (null statement) in `for' and `while'
441 // statements. Don't do anything for template instantiations, this just adds
443 if (NumElts
!= 0 && !CurrentInstantiationScope
&&
444 getCurCompoundScope().HasEmptyLoopBodies
) {
445 for (unsigned i
= 0; i
!= NumElts
- 1; ++i
)
446 DiagnoseEmptyLoopBody(Elts
[i
], Elts
[i
+ 1]);
449 // Calculate difference between FP options in this compound statement and in
450 // the enclosing one. If this is a function body, take the difference against
451 // default options. In this case the difference will indicate options that are
452 // changed upon entry to the statement.
453 FPOptions FPO
= (getCurFunction()->CompoundScopes
.size() == 1)
454 ? FPOptions(getLangOpts())
455 : getCurCompoundScope().InitialFPFeatures
;
456 FPOptionsOverride FPDiff
= getCurFPFeatures().getChangesFrom(FPO
);
458 return CompoundStmt::Create(Context
, Elts
, FPDiff
, L
, R
);
462 Sema::ActOnCaseExpr(SourceLocation CaseLoc
, ExprResult Val
) {
466 if (DiagnoseUnexpandedParameterPack(Val
.get()))
469 // If we're not inside a switch, let the 'case' statement handling diagnose
470 // this. Just clean up after the expression as best we can.
471 if (getCurFunction()->SwitchStack
.empty())
472 return ActOnFinishFullExpr(Val
.get(), Val
.get()->getExprLoc(), false,
473 getLangOpts().CPlusPlus11
);
476 getCurFunction()->SwitchStack
.back().getPointer()->getCond();
479 QualType CondType
= CondExpr
->getType();
481 auto CheckAndFinish
= [&](Expr
*E
) {
482 if (CondType
->isDependentType() || E
->isTypeDependent())
483 return ExprResult(E
);
485 if (getLangOpts().CPlusPlus11
) {
486 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
487 // constant expression of the promoted type of the switch condition.
488 llvm::APSInt TempVal
;
489 return CheckConvertedConstantExpression(E
, CondType
, TempVal
,
494 if (!E
->isValueDependent())
495 ER
= VerifyIntegerConstantExpression(E
, AllowFold
);
497 ER
= DefaultLvalueConversion(ER
.get());
499 ER
= ImpCastExprToType(ER
.get(), CondType
, CK_IntegralCast
);
501 ER
= ActOnFinishFullExpr(ER
.get(), ER
.get()->getExprLoc(), false);
505 ExprResult Converted
= CorrectDelayedTyposInExpr(
506 Val
, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
508 if (Converted
.get() == Val
.get())
509 Converted
= CheckAndFinish(Val
.get());
514 Sema::ActOnCaseStmt(SourceLocation CaseLoc
, ExprResult LHSVal
,
515 SourceLocation DotDotDotLoc
, ExprResult RHSVal
,
516 SourceLocation ColonLoc
) {
517 assert((LHSVal
.isInvalid() || LHSVal
.get()) && "missing LHS value");
518 assert((DotDotDotLoc
.isInvalid() ? RHSVal
.isUnset()
519 : RHSVal
.isInvalid() || RHSVal
.get()) &&
520 "missing RHS value");
522 if (getCurFunction()->SwitchStack
.empty()) {
523 Diag(CaseLoc
, diag::err_case_not_in_switch
);
527 if (LHSVal
.isInvalid() || RHSVal
.isInvalid()) {
528 getCurFunction()->SwitchStack
.back().setInt(true);
532 if (LangOpts
.OpenACC
&&
533 getCurScope()->isInOpenACCComputeConstructScope(Scope::SwitchScope
)) {
534 Diag(CaseLoc
, diag::err_acc_branch_in_out_compute_construct
)
535 << /*branch*/ 0 << /*into*/ 1;
539 auto *CS
= CaseStmt::Create(Context
, LHSVal
.get(), RHSVal
.get(),
540 CaseLoc
, DotDotDotLoc
, ColonLoc
);
541 getCurFunction()->SwitchStack
.back().getPointer()->addSwitchCase(CS
);
545 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
546 void Sema::ActOnCaseStmtBody(Stmt
*S
, Stmt
*SubStmt
) {
547 cast
<CaseStmt
>(S
)->setSubStmt(SubStmt
);
551 Sema::ActOnDefaultStmt(SourceLocation DefaultLoc
, SourceLocation ColonLoc
,
552 Stmt
*SubStmt
, Scope
*CurScope
) {
553 if (getCurFunction()->SwitchStack
.empty()) {
554 Diag(DefaultLoc
, diag::err_default_not_in_switch
);
558 if (LangOpts
.OpenACC
&&
559 getCurScope()->isInOpenACCComputeConstructScope(Scope::SwitchScope
)) {
560 Diag(DefaultLoc
, diag::err_acc_branch_in_out_compute_construct
)
561 << /*branch*/ 0 << /*into*/ 1;
565 DefaultStmt
*DS
= new (Context
) DefaultStmt(DefaultLoc
, ColonLoc
, SubStmt
);
566 getCurFunction()->SwitchStack
.back().getPointer()->addSwitchCase(DS
);
571 Sema::ActOnLabelStmt(SourceLocation IdentLoc
, LabelDecl
*TheDecl
,
572 SourceLocation ColonLoc
, Stmt
*SubStmt
) {
573 // If the label was multiply defined, reject it now.
574 if (TheDecl
->getStmt()) {
575 Diag(IdentLoc
, diag::err_redefinition_of_label
) << TheDecl
->getDeclName();
576 Diag(TheDecl
->getLocation(), diag::note_previous_definition
);
580 ReservedIdentifierStatus Status
= TheDecl
->isReserved(getLangOpts());
581 if (isReservedInAllContexts(Status
) &&
582 !Context
.getSourceManager().isInSystemHeader(IdentLoc
))
583 Diag(IdentLoc
, diag::warn_reserved_extern_symbol
)
584 << TheDecl
<< static_cast<int>(Status
);
586 // If this label is in a compute construct scope, we need to make sure we
587 // check gotos in/out.
588 if (getCurScope()->isInOpenACCComputeConstructScope())
589 setFunctionHasBranchProtectedScope();
591 // Otherwise, things are good. Fill in the declaration and return it.
592 LabelStmt
*LS
= new (Context
) LabelStmt(IdentLoc
, TheDecl
, SubStmt
);
593 TheDecl
->setStmt(LS
);
594 if (!TheDecl
->isGnuLocal()) {
595 TheDecl
->setLocStart(IdentLoc
);
596 if (!TheDecl
->isMSAsmLabel()) {
597 // Don't update the location of MS ASM labels. These will result in
598 // a diagnostic, and changing the location here will mess that up.
599 TheDecl
->setLocation(IdentLoc
);
605 StmtResult
Sema::BuildAttributedStmt(SourceLocation AttrsLoc
,
606 ArrayRef
<const Attr
*> Attrs
,
608 // FIXME: this code should move when a planned refactoring around statement
610 for (const auto *A
: Attrs
) {
611 if (A
->getKind() == attr::MustTail
) {
612 if (!checkAndRewriteMustTailAttr(SubStmt
, *A
)) {
615 setFunctionHasMustTail();
619 return AttributedStmt::Create(Context
, AttrsLoc
, Attrs
, SubStmt
);
622 StmtResult
Sema::ActOnAttributedStmt(const ParsedAttributes
&Attrs
,
624 SmallVector
<const Attr
*, 1> SemanticAttrs
;
625 ProcessStmtAttributes(SubStmt
, Attrs
, SemanticAttrs
);
626 if (!SemanticAttrs
.empty())
627 return BuildAttributedStmt(Attrs
.Range
.getBegin(), SemanticAttrs
, SubStmt
);
628 // If none of the attributes applied, that's fine, we can recover by
629 // returning the substatement directly instead of making an AttributedStmt
630 // with no attributes on it.
634 bool Sema::checkAndRewriteMustTailAttr(Stmt
*St
, const Attr
&MTA
) {
635 ReturnStmt
*R
= cast
<ReturnStmt
>(St
);
636 Expr
*E
= R
->getRetValue();
638 if (CurContext
->isDependentContext() || (E
&& E
->isInstantiationDependent()))
639 // We have to suspend our check until template instantiation time.
642 if (!checkMustTailAttr(St
, MTA
))
645 // FIXME: Replace Expr::IgnoreImplicitAsWritten() with this function.
646 // Currently it does not skip implicit constructors in an initialization
648 auto IgnoreImplicitAsWritten
= [](Expr
*E
) -> Expr
* {
649 return IgnoreExprNodes(E
, IgnoreImplicitAsWrittenSingleStep
,
650 IgnoreElidableImplicitConstructorSingleStep
);
653 // Now that we have verified that 'musttail' is valid here, rewrite the
654 // return value to remove all implicit nodes, but retain parentheses.
655 R
->setRetValue(IgnoreImplicitAsWritten(E
));
659 bool Sema::checkMustTailAttr(const Stmt
*St
, const Attr
&MTA
) {
660 assert(!CurContext
->isDependentContext() &&
661 "musttail cannot be checked from a dependent context");
663 // FIXME: Add Expr::IgnoreParenImplicitAsWritten() with this definition.
664 auto IgnoreParenImplicitAsWritten
= [](const Expr
*E
) -> const Expr
* {
665 return IgnoreExprNodes(const_cast<Expr
*>(E
), IgnoreParensSingleStep
,
666 IgnoreImplicitAsWrittenSingleStep
,
667 IgnoreElidableImplicitConstructorSingleStep
);
670 const Expr
*E
= cast
<ReturnStmt
>(St
)->getRetValue();
671 const auto *CE
= dyn_cast_or_null
<CallExpr
>(IgnoreParenImplicitAsWritten(E
));
674 Diag(St
->getBeginLoc(), diag::err_musttail_needs_call
) << &MTA
;
678 if (const auto *EWC
= dyn_cast
<ExprWithCleanups
>(E
)) {
679 if (EWC
->cleanupsHaveSideEffects()) {
680 Diag(St
->getBeginLoc(), diag::err_musttail_needs_trivial_args
) << &MTA
;
685 // We need to determine the full function type (including "this" type, if any)
686 // for both caller and callee.
691 ft_non_static_member
,
692 ft_pointer_to_member
,
693 } MemberType
= ft_non_member
;
696 const FunctionProtoType
*Func
;
697 const CXXMethodDecl
*Method
= nullptr;
698 } CallerType
, CalleeType
;
700 auto GetMethodType
= [this, St
, MTA
](const CXXMethodDecl
*CMD
, FuncType
&Type
,
701 bool IsCallee
) -> bool {
702 if (isa
<CXXConstructorDecl
, CXXDestructorDecl
>(CMD
)) {
703 Diag(St
->getBeginLoc(), diag::err_musttail_structors_forbidden
)
704 << IsCallee
<< isa
<CXXDestructorDecl
>(CMD
);
706 Diag(CMD
->getBeginLoc(), diag::note_musttail_structors_forbidden
)
707 << isa
<CXXDestructorDecl
>(CMD
);
708 Diag(MTA
.getLocation(), diag::note_tail_call_required
) << &MTA
;
712 Type
.MemberType
= FuncType::ft_static_member
;
714 Type
.This
= CMD
->getFunctionObjectParameterType();
715 Type
.MemberType
= FuncType::ft_non_static_member
;
717 Type
.Func
= CMD
->getType()->castAs
<FunctionProtoType
>();
721 const auto *CallerDecl
= dyn_cast
<FunctionDecl
>(CurContext
);
723 // Find caller function signature.
726 if (isa
<BlockDecl
>(CurContext
))
728 else if (isa
<ObjCMethodDecl
>(CurContext
))
732 Diag(St
->getBeginLoc(), diag::err_musttail_forbidden_from_this_context
)
733 << &MTA
<< ContextType
;
735 } else if (const auto *CMD
= dyn_cast
<CXXMethodDecl
>(CurContext
)) {
736 // Caller is a class/struct method.
737 if (!GetMethodType(CMD
, CallerType
, false))
740 // Caller is a non-method function.
741 CallerType
.Func
= CallerDecl
->getType()->getAs
<FunctionProtoType
>();
744 const Expr
*CalleeExpr
= CE
->getCallee()->IgnoreParens();
745 const auto *CalleeBinOp
= dyn_cast
<BinaryOperator
>(CalleeExpr
);
746 SourceLocation CalleeLoc
= CE
->getCalleeDecl()
747 ? CE
->getCalleeDecl()->getBeginLoc()
750 // Find callee function signature.
751 if (const CXXMethodDecl
*CMD
=
752 dyn_cast_or_null
<CXXMethodDecl
>(CE
->getCalleeDecl())) {
753 // Call is: obj.method(), obj->method(), functor(), etc.
754 if (!GetMethodType(CMD
, CalleeType
, true))
756 } else if (CalleeBinOp
&& CalleeBinOp
->isPtrMemOp()) {
757 // Call is: obj->*method_ptr or obj.*method_ptr
759 CalleeBinOp
->getRHS()->getType()->castAs
<MemberPointerType
>();
760 CalleeType
.This
= QualType(MPT
->getClass(), 0);
761 CalleeType
.Func
= MPT
->getPointeeType()->castAs
<FunctionProtoType
>();
762 CalleeType
.MemberType
= FuncType::ft_pointer_to_member
;
763 } else if (isa
<CXXPseudoDestructorExpr
>(CalleeExpr
)) {
764 Diag(St
->getBeginLoc(), diag::err_musttail_structors_forbidden
)
765 << /* IsCallee = */ 1 << /* IsDestructor = */ 1;
766 Diag(MTA
.getLocation(), diag::note_tail_call_required
) << &MTA
;
769 // Non-method function.
771 CalleeExpr
->getType()->getPointeeType()->getAs
<FunctionProtoType
>();
774 // Both caller and callee must have a prototype (no K&R declarations).
775 if (!CalleeType
.Func
|| !CallerType
.Func
) {
776 Diag(St
->getBeginLoc(), diag::err_musttail_needs_prototype
) << &MTA
;
777 if (!CalleeType
.Func
&& CE
->getDirectCallee()) {
778 Diag(CE
->getDirectCallee()->getBeginLoc(),
779 diag::note_musttail_fix_non_prototype
);
781 if (!CallerType
.Func
)
782 Diag(CallerDecl
->getBeginLoc(), diag::note_musttail_fix_non_prototype
);
786 // Caller and callee must have matching calling conventions.
788 // Some calling conventions are physically capable of supporting tail calls
789 // even if the function types don't perfectly match. LLVM is currently too
790 // strict to allow this, but if LLVM added support for this in the future, we
791 // could exit early here and skip the remaining checks if the functions are
792 // using such a calling convention.
793 if (CallerType
.Func
->getCallConv() != CalleeType
.Func
->getCallConv()) {
794 if (const auto *ND
= dyn_cast_or_null
<NamedDecl
>(CE
->getCalleeDecl()))
795 Diag(St
->getBeginLoc(), diag::err_musttail_callconv_mismatch
)
796 << true << ND
->getDeclName();
798 Diag(St
->getBeginLoc(), diag::err_musttail_callconv_mismatch
) << false;
799 Diag(CalleeLoc
, diag::note_musttail_callconv_mismatch
)
800 << FunctionType::getNameForCallConv(CallerType
.Func
->getCallConv())
801 << FunctionType::getNameForCallConv(CalleeType
.Func
->getCallConv());
802 Diag(MTA
.getLocation(), diag::note_tail_call_required
) << &MTA
;
806 if (CalleeType
.Func
->isVariadic() || CallerType
.Func
->isVariadic()) {
807 Diag(St
->getBeginLoc(), diag::err_musttail_no_variadic
) << &MTA
;
811 const auto *CalleeDecl
= CE
->getCalleeDecl();
812 if (CalleeDecl
&& CalleeDecl
->hasAttr
<CXX11NoReturnAttr
>()) {
813 Diag(St
->getBeginLoc(), diag::err_musttail_no_return
) << &MTA
;
817 // Caller and callee must match in whether they have a "this" parameter.
818 if (CallerType
.This
.isNull() != CalleeType
.This
.isNull()) {
819 if (const auto *ND
= dyn_cast_or_null
<NamedDecl
>(CE
->getCalleeDecl())) {
820 Diag(St
->getBeginLoc(), diag::err_musttail_member_mismatch
)
821 << CallerType
.MemberType
<< CalleeType
.MemberType
<< true
822 << ND
->getDeclName();
823 Diag(CalleeLoc
, diag::note_musttail_callee_defined_here
)
824 << ND
->getDeclName();
826 Diag(St
->getBeginLoc(), diag::err_musttail_member_mismatch
)
827 << CallerType
.MemberType
<< CalleeType
.MemberType
<< false;
828 Diag(MTA
.getLocation(), diag::note_tail_call_required
) << &MTA
;
832 auto CheckTypesMatch
= [this](FuncType CallerType
, FuncType CalleeType
,
833 PartialDiagnostic
&PD
) -> bool {
837 ft_parameter_mismatch
,
841 auto DoTypesMatch
= [this, &PD
](QualType A
, QualType B
,
842 unsigned Select
) -> bool {
843 if (!Context
.hasSimilarType(A
, B
)) {
844 PD
<< Select
<< A
.getUnqualifiedType() << B
.getUnqualifiedType();
850 if (!CallerType
.This
.isNull() &&
851 !DoTypesMatch(CallerType
.This
, CalleeType
.This
, ft_different_class
))
854 if (!DoTypesMatch(CallerType
.Func
->getReturnType(),
855 CalleeType
.Func
->getReturnType(), ft_return_type
))
858 if (CallerType
.Func
->getNumParams() != CalleeType
.Func
->getNumParams()) {
859 PD
<< ft_parameter_arity
<< CallerType
.Func
->getNumParams()
860 << CalleeType
.Func
->getNumParams();
864 ArrayRef
<QualType
> CalleeParams
= CalleeType
.Func
->getParamTypes();
865 ArrayRef
<QualType
> CallerParams
= CallerType
.Func
->getParamTypes();
866 size_t N
= CallerType
.Func
->getNumParams();
867 for (size_t I
= 0; I
< N
; I
++) {
868 if (!DoTypesMatch(CalleeParams
[I
], CallerParams
[I
],
869 ft_parameter_mismatch
)) {
870 PD
<< static_cast<int>(I
) + 1;
878 PartialDiagnostic PD
= PDiag(diag::note_musttail_mismatch
);
879 if (!CheckTypesMatch(CallerType
, CalleeType
, PD
)) {
880 if (const auto *ND
= dyn_cast_or_null
<NamedDecl
>(CE
->getCalleeDecl()))
881 Diag(St
->getBeginLoc(), diag::err_musttail_mismatch
)
882 << true << ND
->getDeclName();
884 Diag(St
->getBeginLoc(), diag::err_musttail_mismatch
) << false;
886 Diag(MTA
.getLocation(), diag::note_tail_call_required
) << &MTA
;
894 class CommaVisitor
: public EvaluatedExprVisitor
<CommaVisitor
> {
895 typedef EvaluatedExprVisitor
<CommaVisitor
> Inherited
;
898 CommaVisitor(Sema
&SemaRef
) : Inherited(SemaRef
.Context
), SemaRef(SemaRef
) {}
899 void VisitBinaryOperator(BinaryOperator
*E
) {
900 if (E
->getOpcode() == BO_Comma
)
901 SemaRef
.DiagnoseCommaOperator(E
->getLHS(), E
->getExprLoc());
902 EvaluatedExprVisitor
<CommaVisitor
>::VisitBinaryOperator(E
);
907 StmtResult
Sema::ActOnIfStmt(SourceLocation IfLoc
,
908 IfStatementKind StatementKind
,
909 SourceLocation LParenLoc
, Stmt
*InitStmt
,
910 ConditionResult Cond
, SourceLocation RParenLoc
,
911 Stmt
*thenStmt
, SourceLocation ElseLoc
,
913 if (Cond
.isInvalid())
916 bool ConstevalOrNegatedConsteval
=
917 StatementKind
== IfStatementKind::ConstevalNonNegated
||
918 StatementKind
== IfStatementKind::ConstevalNegated
;
920 Expr
*CondExpr
= Cond
.get().second
;
921 assert((CondExpr
|| ConstevalOrNegatedConsteval
) &&
922 "If statement: missing condition");
923 // Only call the CommaVisitor when not C89 due to differences in scope flags.
924 if (CondExpr
&& (getLangOpts().C99
|| getLangOpts().CPlusPlus
) &&
925 !Diags
.isIgnored(diag::warn_comma_operator
, CondExpr
->getExprLoc()))
926 CommaVisitor(*this).Visit(CondExpr
);
928 if (!ConstevalOrNegatedConsteval
&& !elseStmt
)
929 DiagnoseEmptyStmtBody(RParenLoc
, thenStmt
, diag::warn_empty_if_body
);
931 if (ConstevalOrNegatedConsteval
||
932 StatementKind
== IfStatementKind::Constexpr
) {
933 auto DiagnoseLikelihood
= [&](const Stmt
*S
) {
934 if (const Attr
*A
= Stmt::getLikelihoodAttr(S
)) {
935 Diags
.Report(A
->getLocation(),
936 diag::warn_attribute_has_no_effect_on_compile_time_if
)
937 << A
<< ConstevalOrNegatedConsteval
<< A
->getRange();
939 diag::note_attribute_has_no_effect_on_compile_time_if_here
)
940 << ConstevalOrNegatedConsteval
941 << SourceRange(IfLoc
, (ConstevalOrNegatedConsteval
942 ? thenStmt
->getBeginLoc()
944 .getLocWithOffset(-1));
947 DiagnoseLikelihood(thenStmt
);
948 DiagnoseLikelihood(elseStmt
);
950 std::tuple
<bool, const Attr
*, const Attr
*> LHC
=
951 Stmt::determineLikelihoodConflict(thenStmt
, elseStmt
);
952 if (std::get
<0>(LHC
)) {
953 const Attr
*ThenAttr
= std::get
<1>(LHC
);
954 const Attr
*ElseAttr
= std::get
<2>(LHC
);
955 Diags
.Report(ThenAttr
->getLocation(),
956 diag::warn_attributes_likelihood_ifstmt_conflict
)
957 << ThenAttr
<< ThenAttr
->getRange();
958 Diags
.Report(ElseAttr
->getLocation(), diag::note_conflicting_attribute
)
959 << ElseAttr
<< ElseAttr
->getRange();
963 if (ConstevalOrNegatedConsteval
) {
964 bool Immediate
= ExprEvalContexts
.back().Context
==
965 ExpressionEvaluationContext::ImmediateFunctionContext
;
966 if (CurContext
->isFunctionOrMethod()) {
968 dyn_cast
<FunctionDecl
>(Decl::castFromDeclContext(CurContext
));
969 if (FD
&& FD
->isImmediateFunction())
972 if (isUnevaluatedContext() || Immediate
)
973 Diags
.Report(IfLoc
, diag::warn_consteval_if_always_true
) << Immediate
;
976 return BuildIfStmt(IfLoc
, StatementKind
, LParenLoc
, InitStmt
, Cond
, RParenLoc
,
977 thenStmt
, ElseLoc
, elseStmt
);
980 StmtResult
Sema::BuildIfStmt(SourceLocation IfLoc
,
981 IfStatementKind StatementKind
,
982 SourceLocation LParenLoc
, Stmt
*InitStmt
,
983 ConditionResult Cond
, SourceLocation RParenLoc
,
984 Stmt
*thenStmt
, SourceLocation ElseLoc
,
986 if (Cond
.isInvalid())
989 if (StatementKind
!= IfStatementKind::Ordinary
||
990 isa
<ObjCAvailabilityCheckExpr
>(Cond
.get().second
))
991 setFunctionHasBranchProtectedScope();
993 return IfStmt::Create(Context
, IfLoc
, StatementKind
, InitStmt
,
994 Cond
.get().first
, Cond
.get().second
, LParenLoc
,
995 RParenLoc
, thenStmt
, ElseLoc
, elseStmt
);
999 struct CaseCompareFunctor
{
1000 bool operator()(const std::pair
<llvm::APSInt
, CaseStmt
*> &LHS
,
1001 const llvm::APSInt
&RHS
) {
1002 return LHS
.first
< RHS
;
1004 bool operator()(const std::pair
<llvm::APSInt
, CaseStmt
*> &LHS
,
1005 const std::pair
<llvm::APSInt
, CaseStmt
*> &RHS
) {
1006 return LHS
.first
< RHS
.first
;
1008 bool operator()(const llvm::APSInt
&LHS
,
1009 const std::pair
<llvm::APSInt
, CaseStmt
*> &RHS
) {
1010 return LHS
< RHS
.first
;
1015 /// CmpCaseVals - Comparison predicate for sorting case values.
1017 static bool CmpCaseVals(const std::pair
<llvm::APSInt
, CaseStmt
*>& lhs
,
1018 const std::pair
<llvm::APSInt
, CaseStmt
*>& rhs
) {
1019 if (lhs
.first
< rhs
.first
)
1022 if (lhs
.first
== rhs
.first
&&
1023 lhs
.second
->getCaseLoc() < rhs
.second
->getCaseLoc())
1028 /// CmpEnumVals - Comparison predicate for sorting enumeration values.
1030 static bool CmpEnumVals(const std::pair
<llvm::APSInt
, EnumConstantDecl
*>& lhs
,
1031 const std::pair
<llvm::APSInt
, EnumConstantDecl
*>& rhs
)
1033 return lhs
.first
< rhs
.first
;
1036 /// EqEnumVals - Comparison preficate for uniqing enumeration values.
1038 static bool EqEnumVals(const std::pair
<llvm::APSInt
, EnumConstantDecl
*>& lhs
,
1039 const std::pair
<llvm::APSInt
, EnumConstantDecl
*>& rhs
)
1041 return lhs
.first
== rhs
.first
;
1044 /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
1045 /// potentially integral-promoted expression @p expr.
1046 static QualType
GetTypeBeforeIntegralPromotion(const Expr
*&E
) {
1047 if (const auto *FE
= dyn_cast
<FullExpr
>(E
))
1048 E
= FE
->getSubExpr();
1049 while (const auto *ImpCast
= dyn_cast
<ImplicitCastExpr
>(E
)) {
1050 if (ImpCast
->getCastKind() != CK_IntegralCast
) break;
1051 E
= ImpCast
->getSubExpr();
1053 return E
->getType();
1056 ExprResult
Sema::CheckSwitchCondition(SourceLocation SwitchLoc
, Expr
*Cond
) {
1057 class SwitchConvertDiagnoser
: public ICEConvertDiagnoser
{
1061 SwitchConvertDiagnoser(Expr
*Cond
)
1062 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
1065 SemaDiagnosticBuilder
diagnoseNotInt(Sema
&S
, SourceLocation Loc
,
1066 QualType T
) override
{
1067 return S
.Diag(Loc
, diag::err_typecheck_statement_requires_integer
) << T
;
1070 SemaDiagnosticBuilder
diagnoseIncomplete(
1071 Sema
&S
, SourceLocation Loc
, QualType T
) override
{
1072 return S
.Diag(Loc
, diag::err_switch_incomplete_class_type
)
1073 << T
<< Cond
->getSourceRange();
1076 SemaDiagnosticBuilder
diagnoseExplicitConv(
1077 Sema
&S
, SourceLocation Loc
, QualType T
, QualType ConvTy
) override
{
1078 return S
.Diag(Loc
, diag::err_switch_explicit_conversion
) << T
<< ConvTy
;
1081 SemaDiagnosticBuilder
noteExplicitConv(
1082 Sema
&S
, CXXConversionDecl
*Conv
, QualType ConvTy
) override
{
1083 return S
.Diag(Conv
->getLocation(), diag::note_switch_conversion
)
1084 << ConvTy
->isEnumeralType() << ConvTy
;
1087 SemaDiagnosticBuilder
diagnoseAmbiguous(Sema
&S
, SourceLocation Loc
,
1088 QualType T
) override
{
1089 return S
.Diag(Loc
, diag::err_switch_multiple_conversions
) << T
;
1092 SemaDiagnosticBuilder
noteAmbiguous(
1093 Sema
&S
, CXXConversionDecl
*Conv
, QualType ConvTy
) override
{
1094 return S
.Diag(Conv
->getLocation(), diag::note_switch_conversion
)
1095 << ConvTy
->isEnumeralType() << ConvTy
;
1098 SemaDiagnosticBuilder
diagnoseConversion(
1099 Sema
&S
, SourceLocation Loc
, QualType T
, QualType ConvTy
) override
{
1100 llvm_unreachable("conversion functions are permitted");
1102 } SwitchDiagnoser(Cond
);
1104 ExprResult CondResult
=
1105 PerformContextualImplicitConversion(SwitchLoc
, Cond
, SwitchDiagnoser
);
1106 if (CondResult
.isInvalid())
1109 // FIXME: PerformContextualImplicitConversion doesn't always tell us if it
1110 // failed and produced a diagnostic.
1111 Cond
= CondResult
.get();
1112 if (!Cond
->isTypeDependent() &&
1113 !Cond
->getType()->isIntegralOrEnumerationType())
1116 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
1117 return UsualUnaryConversions(Cond
);
1120 StmtResult
Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc
,
1121 SourceLocation LParenLoc
,
1122 Stmt
*InitStmt
, ConditionResult Cond
,
1123 SourceLocation RParenLoc
) {
1124 Expr
*CondExpr
= Cond
.get().second
;
1125 assert((Cond
.isInvalid() || CondExpr
) && "switch with no condition");
1127 if (CondExpr
&& !CondExpr
->isTypeDependent()) {
1128 // We have already converted the expression to an integral or enumeration
1129 // type, when we parsed the switch condition. There are cases where we don't
1130 // have an appropriate type, e.g. a typo-expr Cond was corrected to an
1131 // inappropriate-type expr, we just return an error.
1132 if (!CondExpr
->getType()->isIntegralOrEnumerationType())
1134 if (CondExpr
->isKnownToHaveBooleanValue()) {
1135 // switch(bool_expr) {...} is often a programmer error, e.g.
1136 // switch(n && mask) { ... } // Doh - should be "n & mask".
1137 // One can always use an if statement instead of switch(bool_expr).
1138 Diag(SwitchLoc
, diag::warn_bool_switch_condition
)
1139 << CondExpr
->getSourceRange();
1143 setFunctionHasBranchIntoScope();
1145 auto *SS
= SwitchStmt::Create(Context
, InitStmt
, Cond
.get().first
, CondExpr
,
1146 LParenLoc
, RParenLoc
);
1147 getCurFunction()->SwitchStack
.push_back(
1148 FunctionScopeInfo::SwitchInfo(SS
, false));
1152 static void AdjustAPSInt(llvm::APSInt
&Val
, unsigned BitWidth
, bool IsSigned
) {
1153 Val
= Val
.extOrTrunc(BitWidth
);
1154 Val
.setIsSigned(IsSigned
);
1157 /// Check the specified case value is in range for the given unpromoted switch
1159 static void checkCaseValue(Sema
&S
, SourceLocation Loc
, const llvm::APSInt
&Val
,
1160 unsigned UnpromotedWidth
, bool UnpromotedSign
) {
1161 // In C++11 onwards, this is checked by the language rules.
1162 if (S
.getLangOpts().CPlusPlus11
)
1165 // If the case value was signed and negative and the switch expression is
1166 // unsigned, don't bother to warn: this is implementation-defined behavior.
1167 // FIXME: Introduce a second, default-ignored warning for this case?
1168 if (UnpromotedWidth
< Val
.getBitWidth()) {
1169 llvm::APSInt
ConvVal(Val
);
1170 AdjustAPSInt(ConvVal
, UnpromotedWidth
, UnpromotedSign
);
1171 AdjustAPSInt(ConvVal
, Val
.getBitWidth(), Val
.isSigned());
1172 // FIXME: Use different diagnostics for overflow in conversion to promoted
1173 // type versus "switch expression cannot have this value". Use proper
1174 // IntRange checking rather than just looking at the unpromoted type here.
1176 S
.Diag(Loc
, diag::warn_case_value_overflow
) << toString(Val
, 10)
1177 << toString(ConvVal
, 10);
1181 typedef SmallVector
<std::pair
<llvm::APSInt
, EnumConstantDecl
*>, 64> EnumValsTy
;
1183 /// Returns true if we should emit a diagnostic about this case expression not
1184 /// being a part of the enum used in the switch controlling expression.
1185 static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema
&S
,
1187 const Expr
*CaseExpr
,
1188 EnumValsTy::iterator
&EI
,
1189 EnumValsTy::iterator
&EIEnd
,
1190 const llvm::APSInt
&Val
) {
1191 if (!ED
->isClosed())
1194 if (const DeclRefExpr
*DRE
=
1195 dyn_cast
<DeclRefExpr
>(CaseExpr
->IgnoreParenImpCasts())) {
1196 if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(DRE
->getDecl())) {
1197 QualType VarType
= VD
->getType();
1198 QualType EnumType
= S
.Context
.getTypeDeclType(ED
);
1199 if (VD
->hasGlobalStorage() && VarType
.isConstQualified() &&
1200 S
.Context
.hasSameUnqualifiedType(EnumType
, VarType
))
1205 if (ED
->hasAttr
<FlagEnumAttr
>())
1206 return !S
.IsValueInFlagEnum(ED
, Val
, false);
1208 while (EI
!= EIEnd
&& EI
->first
< Val
)
1211 if (EI
!= EIEnd
&& EI
->first
== Val
)
1217 static void checkEnumTypesInSwitchStmt(Sema
&S
, const Expr
*Cond
,
1219 QualType CondType
= Cond
->getType();
1220 QualType CaseType
= Case
->getType();
1222 const EnumType
*CondEnumType
= CondType
->getAs
<EnumType
>();
1223 const EnumType
*CaseEnumType
= CaseType
->getAs
<EnumType
>();
1224 if (!CondEnumType
|| !CaseEnumType
)
1227 // Ignore anonymous enums.
1228 if (!CondEnumType
->getDecl()->getIdentifier() &&
1229 !CondEnumType
->getDecl()->getTypedefNameForAnonDecl())
1231 if (!CaseEnumType
->getDecl()->getIdentifier() &&
1232 !CaseEnumType
->getDecl()->getTypedefNameForAnonDecl())
1235 if (S
.Context
.hasSameUnqualifiedType(CondType
, CaseType
))
1238 S
.Diag(Case
->getExprLoc(), diag::warn_comparison_of_mixed_enum_types_switch
)
1239 << CondType
<< CaseType
<< Cond
->getSourceRange()
1240 << Case
->getSourceRange();
1244 Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc
, Stmt
*Switch
,
1246 SwitchStmt
*SS
= cast
<SwitchStmt
>(Switch
);
1247 bool CaseListIsIncomplete
= getCurFunction()->SwitchStack
.back().getInt();
1248 assert(SS
== getCurFunction()->SwitchStack
.back().getPointer() &&
1249 "switch stack missing push/pop!");
1251 getCurFunction()->SwitchStack
.pop_back();
1253 if (!BodyStmt
) return StmtError();
1254 SS
->setBody(BodyStmt
, SwitchLoc
);
1256 Expr
*CondExpr
= SS
->getCond();
1257 if (!CondExpr
) return StmtError();
1259 QualType CondType
= CondExpr
->getType();
1262 // Integral promotions are performed (on the switch condition).
1264 // A case value unrepresentable by the original switch condition
1265 // type (before the promotion) doesn't make sense, even when it can
1266 // be represented by the promoted type. Therefore we need to find
1267 // the pre-promotion type of the switch condition.
1268 const Expr
*CondExprBeforePromotion
= CondExpr
;
1269 QualType CondTypeBeforePromotion
=
1270 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion
);
1272 // Get the bitwidth of the switched-on value after promotions. We must
1273 // convert the integer case values to this width before comparison.
1274 bool HasDependentValue
1275 = CondExpr
->isTypeDependent() || CondExpr
->isValueDependent();
1276 unsigned CondWidth
= HasDependentValue
? 0 : Context
.getIntWidth(CondType
);
1277 bool CondIsSigned
= CondType
->isSignedIntegerOrEnumerationType();
1279 // Get the width and signedness that the condition might actually have, for
1280 // warning purposes.
1281 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
1283 unsigned CondWidthBeforePromotion
1284 = HasDependentValue
? 0 : Context
.getIntWidth(CondTypeBeforePromotion
);
1285 bool CondIsSignedBeforePromotion
1286 = CondTypeBeforePromotion
->isSignedIntegerOrEnumerationType();
1288 // Accumulate all of the case values in a vector so that we can sort them
1289 // and detect duplicates. This vector contains the APInt for the case after
1290 // it has been converted to the condition type.
1291 typedef SmallVector
<std::pair
<llvm::APSInt
, CaseStmt
*>, 64> CaseValsTy
;
1292 CaseValsTy CaseVals
;
1294 // Keep track of any GNU case ranges we see. The APSInt is the low value.
1295 typedef std::vector
<std::pair
<llvm::APSInt
, CaseStmt
*> > CaseRangesTy
;
1296 CaseRangesTy CaseRanges
;
1298 DefaultStmt
*TheDefaultStmt
= nullptr;
1300 bool CaseListIsErroneous
= false;
1302 // FIXME: We'd better diagnose missing or duplicate default labels even
1303 // in the dependent case. Because default labels themselves are never
1305 for (SwitchCase
*SC
= SS
->getSwitchCaseList(); SC
&& !HasDependentValue
;
1306 SC
= SC
->getNextSwitchCase()) {
1308 if (DefaultStmt
*DS
= dyn_cast
<DefaultStmt
>(SC
)) {
1309 if (TheDefaultStmt
) {
1310 Diag(DS
->getDefaultLoc(), diag::err_multiple_default_labels_defined
);
1311 Diag(TheDefaultStmt
->getDefaultLoc(), diag::note_duplicate_case_prev
);
1313 // FIXME: Remove the default statement from the switch block so that
1314 // we'll return a valid AST. This requires recursing down the AST and
1315 // finding it, not something we are set up to do right now. For now,
1316 // just lop the entire switch stmt out of the AST.
1317 CaseListIsErroneous
= true;
1319 TheDefaultStmt
= DS
;
1322 CaseStmt
*CS
= cast
<CaseStmt
>(SC
);
1324 Expr
*Lo
= CS
->getLHS();
1326 if (Lo
->isValueDependent()) {
1327 HasDependentValue
= true;
1331 // We already verified that the expression has a constant value;
1332 // get that value (prior to conversions).
1333 const Expr
*LoBeforePromotion
= Lo
;
1334 GetTypeBeforeIntegralPromotion(LoBeforePromotion
);
1335 llvm::APSInt LoVal
= LoBeforePromotion
->EvaluateKnownConstInt(Context
);
1337 // Check the unconverted value is within the range of possible values of
1338 // the switch expression.
1339 checkCaseValue(*this, Lo
->getBeginLoc(), LoVal
, CondWidthBeforePromotion
,
1340 CondIsSignedBeforePromotion
);
1342 // FIXME: This duplicates the check performed for warn_not_in_enum below.
1343 checkEnumTypesInSwitchStmt(*this, CondExprBeforePromotion
,
1346 // Convert the value to the same width/sign as the condition.
1347 AdjustAPSInt(LoVal
, CondWidth
, CondIsSigned
);
1349 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
1351 if (CS
->getRHS()->isValueDependent()) {
1352 HasDependentValue
= true;
1355 CaseRanges
.push_back(std::make_pair(LoVal
, CS
));
1357 CaseVals
.push_back(std::make_pair(LoVal
, CS
));
1361 if (!HasDependentValue
) {
1362 // If we don't have a default statement, check whether the
1363 // condition is constant.
1364 llvm::APSInt ConstantCondValue
;
1365 bool HasConstantCond
= false;
1366 if (!TheDefaultStmt
) {
1367 Expr::EvalResult Result
;
1368 HasConstantCond
= CondExpr
->EvaluateAsInt(Result
, Context
,
1369 Expr::SE_AllowSideEffects
);
1370 if (Result
.Val
.isInt())
1371 ConstantCondValue
= Result
.Val
.getInt();
1372 assert(!HasConstantCond
||
1373 (ConstantCondValue
.getBitWidth() == CondWidth
&&
1374 ConstantCondValue
.isSigned() == CondIsSigned
));
1375 Diag(SwitchLoc
, diag::warn_switch_default
);
1377 bool ShouldCheckConstantCond
= HasConstantCond
;
1379 // Sort all the scalar case values so we can easily detect duplicates.
1380 llvm::stable_sort(CaseVals
, CmpCaseVals
);
1382 if (!CaseVals
.empty()) {
1383 for (unsigned i
= 0, e
= CaseVals
.size(); i
!= e
; ++i
) {
1384 if (ShouldCheckConstantCond
&&
1385 CaseVals
[i
].first
== ConstantCondValue
)
1386 ShouldCheckConstantCond
= false;
1388 if (i
!= 0 && CaseVals
[i
].first
== CaseVals
[i
-1].first
) {
1389 // If we have a duplicate, report it.
1390 // First, determine if either case value has a name
1391 StringRef PrevString
, CurrString
;
1392 Expr
*PrevCase
= CaseVals
[i
-1].second
->getLHS()->IgnoreParenCasts();
1393 Expr
*CurrCase
= CaseVals
[i
].second
->getLHS()->IgnoreParenCasts();
1394 if (DeclRefExpr
*DeclRef
= dyn_cast
<DeclRefExpr
>(PrevCase
)) {
1395 PrevString
= DeclRef
->getDecl()->getName();
1397 if (DeclRefExpr
*DeclRef
= dyn_cast
<DeclRefExpr
>(CurrCase
)) {
1398 CurrString
= DeclRef
->getDecl()->getName();
1400 SmallString
<16> CaseValStr
;
1401 CaseVals
[i
-1].first
.toString(CaseValStr
);
1403 if (PrevString
== CurrString
)
1404 Diag(CaseVals
[i
].second
->getLHS()->getBeginLoc(),
1405 diag::err_duplicate_case
)
1406 << (PrevString
.empty() ? CaseValStr
.str() : PrevString
);
1408 Diag(CaseVals
[i
].second
->getLHS()->getBeginLoc(),
1409 diag::err_duplicate_case_differing_expr
)
1410 << (PrevString
.empty() ? CaseValStr
.str() : PrevString
)
1411 << (CurrString
.empty() ? CaseValStr
.str() : CurrString
)
1414 Diag(CaseVals
[i
- 1].second
->getLHS()->getBeginLoc(),
1415 diag::note_duplicate_case_prev
);
1416 // FIXME: We really want to remove the bogus case stmt from the
1417 // substmt, but we have no way to do this right now.
1418 CaseListIsErroneous
= true;
1423 // Detect duplicate case ranges, which usually don't exist at all in
1425 if (!CaseRanges
.empty()) {
1426 // Sort all the case ranges by their low value so we can easily detect
1427 // overlaps between ranges.
1428 llvm::stable_sort(CaseRanges
);
1430 // Scan the ranges, computing the high values and removing empty ranges.
1431 std::vector
<llvm::APSInt
> HiVals
;
1432 for (unsigned i
= 0, e
= CaseRanges
.size(); i
!= e
; ++i
) {
1433 llvm::APSInt
&LoVal
= CaseRanges
[i
].first
;
1434 CaseStmt
*CR
= CaseRanges
[i
].second
;
1435 Expr
*Hi
= CR
->getRHS();
1437 const Expr
*HiBeforePromotion
= Hi
;
1438 GetTypeBeforeIntegralPromotion(HiBeforePromotion
);
1439 llvm::APSInt HiVal
= HiBeforePromotion
->EvaluateKnownConstInt(Context
);
1441 // Check the unconverted value is within the range of possible values of
1442 // the switch expression.
1443 checkCaseValue(*this, Hi
->getBeginLoc(), HiVal
,
1444 CondWidthBeforePromotion
, CondIsSignedBeforePromotion
);
1446 // Convert the value to the same width/sign as the condition.
1447 AdjustAPSInt(HiVal
, CondWidth
, CondIsSigned
);
1449 // If the low value is bigger than the high value, the case is empty.
1450 if (LoVal
> HiVal
) {
1451 Diag(CR
->getLHS()->getBeginLoc(), diag::warn_case_empty_range
)
1452 << SourceRange(CR
->getLHS()->getBeginLoc(), Hi
->getEndLoc());
1453 CaseRanges
.erase(CaseRanges
.begin()+i
);
1459 if (ShouldCheckConstantCond
&&
1460 LoVal
<= ConstantCondValue
&&
1461 ConstantCondValue
<= HiVal
)
1462 ShouldCheckConstantCond
= false;
1464 HiVals
.push_back(HiVal
);
1467 // Rescan the ranges, looking for overlap with singleton values and other
1468 // ranges. Since the range list is sorted, we only need to compare case
1469 // ranges with their neighbors.
1470 for (unsigned i
= 0, e
= CaseRanges
.size(); i
!= e
; ++i
) {
1471 llvm::APSInt
&CRLo
= CaseRanges
[i
].first
;
1472 llvm::APSInt
&CRHi
= HiVals
[i
];
1473 CaseStmt
*CR
= CaseRanges
[i
].second
;
1475 // Check to see whether the case range overlaps with any
1477 CaseStmt
*OverlapStmt
= nullptr;
1478 llvm::APSInt
OverlapVal(32);
1480 // Find the smallest value >= the lower bound. If I is in the
1481 // case range, then we have overlap.
1482 CaseValsTy::iterator I
=
1483 llvm::lower_bound(CaseVals
, CRLo
, CaseCompareFunctor());
1484 if (I
!= CaseVals
.end() && I
->first
< CRHi
) {
1485 OverlapVal
= I
->first
; // Found overlap with scalar.
1486 OverlapStmt
= I
->second
;
1489 // Find the smallest value bigger than the upper bound.
1490 I
= std::upper_bound(I
, CaseVals
.end(), CRHi
, CaseCompareFunctor());
1491 if (I
!= CaseVals
.begin() && (I
-1)->first
>= CRLo
) {
1492 OverlapVal
= (I
-1)->first
; // Found overlap with scalar.
1493 OverlapStmt
= (I
-1)->second
;
1496 // Check to see if this case stmt overlaps with the subsequent
1498 if (i
&& CRLo
<= HiVals
[i
-1]) {
1499 OverlapVal
= HiVals
[i
-1]; // Found overlap with range.
1500 OverlapStmt
= CaseRanges
[i
-1].second
;
1504 // If we have a duplicate, report it.
1505 Diag(CR
->getLHS()->getBeginLoc(), diag::err_duplicate_case
)
1506 << toString(OverlapVal
, 10);
1507 Diag(OverlapStmt
->getLHS()->getBeginLoc(),
1508 diag::note_duplicate_case_prev
);
1509 // FIXME: We really want to remove the bogus case stmt from the
1510 // substmt, but we have no way to do this right now.
1511 CaseListIsErroneous
= true;
1516 // Complain if we have a constant condition and we didn't find a match.
1517 if (!CaseListIsErroneous
&& !CaseListIsIncomplete
&&
1518 ShouldCheckConstantCond
) {
1519 // TODO: it would be nice if we printed enums as enums, chars as
1521 Diag(CondExpr
->getExprLoc(), diag::warn_missing_case_for_condition
)
1522 << toString(ConstantCondValue
, 10)
1523 << CondExpr
->getSourceRange();
1526 // Check to see if switch is over an Enum and handles all of its
1527 // values. We only issue a warning if there is not 'default:', but
1528 // we still do the analysis to preserve this information in the AST
1529 // (which can be used by flow-based analyes).
1531 const EnumType
*ET
= CondTypeBeforePromotion
->getAs
<EnumType
>();
1533 // If switch has default case, then ignore it.
1534 if (!CaseListIsErroneous
&& !CaseListIsIncomplete
&& !HasConstantCond
&&
1535 ET
&& ET
->getDecl()->isCompleteDefinition() &&
1536 !ET
->getDecl()->enumerators().empty()) {
1537 const EnumDecl
*ED
= ET
->getDecl();
1538 EnumValsTy EnumVals
;
1540 // Gather all enum values, set their type and sort them,
1541 // allowing easier comparison with CaseVals.
1542 for (auto *EDI
: ED
->enumerators()) {
1543 llvm::APSInt Val
= EDI
->getInitVal();
1544 AdjustAPSInt(Val
, CondWidth
, CondIsSigned
);
1545 EnumVals
.push_back(std::make_pair(Val
, EDI
));
1547 llvm::stable_sort(EnumVals
, CmpEnumVals
);
1548 auto EI
= EnumVals
.begin(), EIEnd
=
1549 std::unique(EnumVals
.begin(), EnumVals
.end(), EqEnumVals
);
1551 // See which case values aren't in enum.
1552 for (CaseValsTy::const_iterator CI
= CaseVals
.begin();
1553 CI
!= CaseVals
.end(); CI
++) {
1554 Expr
*CaseExpr
= CI
->second
->getLHS();
1555 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED
, CaseExpr
, EI
, EIEnd
,
1557 Diag(CaseExpr
->getExprLoc(), diag::warn_not_in_enum
)
1558 << CondTypeBeforePromotion
;
1561 // See which of case ranges aren't in enum
1562 EI
= EnumVals
.begin();
1563 for (CaseRangesTy::const_iterator RI
= CaseRanges
.begin();
1564 RI
!= CaseRanges
.end(); RI
++) {
1565 Expr
*CaseExpr
= RI
->second
->getLHS();
1566 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED
, CaseExpr
, EI
, EIEnd
,
1568 Diag(CaseExpr
->getExprLoc(), diag::warn_not_in_enum
)
1569 << CondTypeBeforePromotion
;
1572 RI
->second
->getRHS()->EvaluateKnownConstInt(Context
);
1573 AdjustAPSInt(Hi
, CondWidth
, CondIsSigned
);
1575 CaseExpr
= RI
->second
->getRHS();
1576 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED
, CaseExpr
, EI
, EIEnd
,
1578 Diag(CaseExpr
->getExprLoc(), diag::warn_not_in_enum
)
1579 << CondTypeBeforePromotion
;
1582 // Check which enum vals aren't in switch
1583 auto CI
= CaseVals
.begin();
1584 auto RI
= CaseRanges
.begin();
1585 bool hasCasesNotInSwitch
= false;
1587 SmallVector
<DeclarationName
,8> UnhandledNames
;
1589 for (EI
= EnumVals
.begin(); EI
!= EIEnd
; EI
++) {
1590 // Don't warn about omitted unavailable EnumConstantDecls.
1591 switch (EI
->second
->getAvailability()) {
1593 // Omitting a deprecated constant is ok; it should never materialize.
1594 case AR_Unavailable
:
1597 case AR_NotYetIntroduced
:
1598 // Partially available enum constants should be present. Note that we
1599 // suppress -Wunguarded-availability diagnostics for such uses.
1604 if (EI
->second
->hasAttr
<UnusedAttr
>())
1607 // Drop unneeded case values
1608 while (CI
!= CaseVals
.end() && CI
->first
< EI
->first
)
1611 if (CI
!= CaseVals
.end() && CI
->first
== EI
->first
)
1614 // Drop unneeded case ranges
1615 for (; RI
!= CaseRanges
.end(); RI
++) {
1617 RI
->second
->getRHS()->EvaluateKnownConstInt(Context
);
1618 AdjustAPSInt(Hi
, CondWidth
, CondIsSigned
);
1619 if (EI
->first
<= Hi
)
1623 if (RI
== CaseRanges
.end() || EI
->first
< RI
->first
) {
1624 hasCasesNotInSwitch
= true;
1625 UnhandledNames
.push_back(EI
->second
->getDeclName());
1629 if (TheDefaultStmt
&& UnhandledNames
.empty() && ED
->isClosedNonFlag())
1630 Diag(TheDefaultStmt
->getDefaultLoc(), diag::warn_unreachable_default
);
1632 // Produce a nice diagnostic if multiple values aren't handled.
1633 if (!UnhandledNames
.empty()) {
1634 auto DB
= Diag(CondExpr
->getExprLoc(), TheDefaultStmt
1635 ? diag::warn_def_missing_case
1636 : diag::warn_missing_case
)
1637 << CondExpr
->getSourceRange() << (int)UnhandledNames
.size();
1639 for (size_t I
= 0, E
= std::min(UnhandledNames
.size(), (size_t)3);
1641 DB
<< UnhandledNames
[I
];
1644 if (!hasCasesNotInSwitch
)
1645 SS
->setAllEnumCasesCovered();
1650 DiagnoseEmptyStmtBody(CondExpr
->getEndLoc(), BodyStmt
,
1651 diag::warn_empty_switch_body
);
1653 // FIXME: If the case list was broken is some way, we don't have a good system
1654 // to patch it up. Instead, just return the whole substmt as broken.
1655 if (CaseListIsErroneous
)
1662 Sema::DiagnoseAssignmentEnum(QualType DstType
, QualType SrcType
,
1664 if (Diags
.isIgnored(diag::warn_not_in_enum_assignment
, SrcExpr
->getExprLoc()))
1667 if (const EnumType
*ET
= DstType
->getAs
<EnumType
>())
1668 if (!Context
.hasSameUnqualifiedType(SrcType
, DstType
) &&
1669 SrcType
->isIntegerType()) {
1670 if (!SrcExpr
->isTypeDependent() && !SrcExpr
->isValueDependent() &&
1671 SrcExpr
->isIntegerConstantExpr(Context
)) {
1672 // Get the bitwidth of the enum value before promotions.
1673 unsigned DstWidth
= Context
.getIntWidth(DstType
);
1674 bool DstIsSigned
= DstType
->isSignedIntegerOrEnumerationType();
1676 llvm::APSInt RhsVal
= SrcExpr
->EvaluateKnownConstInt(Context
);
1677 AdjustAPSInt(RhsVal
, DstWidth
, DstIsSigned
);
1678 const EnumDecl
*ED
= ET
->getDecl();
1680 if (!ED
->isClosed())
1683 if (ED
->hasAttr
<FlagEnumAttr
>()) {
1684 if (!IsValueInFlagEnum(ED
, RhsVal
, true))
1685 Diag(SrcExpr
->getExprLoc(), diag::warn_not_in_enum_assignment
)
1686 << DstType
.getUnqualifiedType();
1688 typedef SmallVector
<std::pair
<llvm::APSInt
, EnumConstantDecl
*>, 64>
1690 EnumValsTy EnumVals
;
1692 // Gather all enum values, set their type and sort them,
1693 // allowing easier comparison with rhs constant.
1694 for (auto *EDI
: ED
->enumerators()) {
1695 llvm::APSInt Val
= EDI
->getInitVal();
1696 AdjustAPSInt(Val
, DstWidth
, DstIsSigned
);
1697 EnumVals
.push_back(std::make_pair(Val
, EDI
));
1699 if (EnumVals
.empty())
1701 llvm::stable_sort(EnumVals
, CmpEnumVals
);
1702 EnumValsTy::iterator EIend
=
1703 std::unique(EnumVals
.begin(), EnumVals
.end(), EqEnumVals
);
1705 // See which values aren't in the enum.
1706 EnumValsTy::const_iterator EI
= EnumVals
.begin();
1707 while (EI
!= EIend
&& EI
->first
< RhsVal
)
1709 if (EI
== EIend
|| EI
->first
!= RhsVal
) {
1710 Diag(SrcExpr
->getExprLoc(), diag::warn_not_in_enum_assignment
)
1711 << DstType
.getUnqualifiedType();
1718 StmtResult
Sema::ActOnWhileStmt(SourceLocation WhileLoc
,
1719 SourceLocation LParenLoc
, ConditionResult Cond
,
1720 SourceLocation RParenLoc
, Stmt
*Body
) {
1721 if (Cond
.isInvalid())
1724 auto CondVal
= Cond
.get();
1725 CheckBreakContinueBinding(CondVal
.second
);
1727 if (CondVal
.second
&&
1728 !Diags
.isIgnored(diag::warn_comma_operator
, CondVal
.second
->getExprLoc()))
1729 CommaVisitor(*this).Visit(CondVal
.second
);
1731 if (isa
<NullStmt
>(Body
))
1732 getCurCompoundScope().setHasEmptyLoopBodies();
1734 return WhileStmt::Create(Context
, CondVal
.first
, CondVal
.second
, Body
,
1735 WhileLoc
, LParenLoc
, RParenLoc
);
1739 Sema::ActOnDoStmt(SourceLocation DoLoc
, Stmt
*Body
,
1740 SourceLocation WhileLoc
, SourceLocation CondLParen
,
1741 Expr
*Cond
, SourceLocation CondRParen
) {
1742 assert(Cond
&& "ActOnDoStmt(): missing expression");
1744 CheckBreakContinueBinding(Cond
);
1745 ExprResult CondResult
= CheckBooleanCondition(DoLoc
, Cond
);
1746 if (CondResult
.isInvalid())
1748 Cond
= CondResult
.get();
1750 CondResult
= ActOnFinishFullExpr(Cond
, DoLoc
, /*DiscardedValue*/ false);
1751 if (CondResult
.isInvalid())
1753 Cond
= CondResult
.get();
1755 // Only call the CommaVisitor for C89 due to differences in scope flags.
1756 if (Cond
&& !getLangOpts().C99
&& !getLangOpts().CPlusPlus
&&
1757 !Diags
.isIgnored(diag::warn_comma_operator
, Cond
->getExprLoc()))
1758 CommaVisitor(*this).Visit(Cond
);
1760 return new (Context
) DoStmt(Body
, Cond
, DoLoc
, WhileLoc
, CondRParen
);
1764 // Use SetVector since the diagnostic cares about the ordering of the Decl's.
1765 using DeclSetVector
= llvm::SmallSetVector
<VarDecl
*, 8>;
1767 // This visitor will traverse a conditional statement and store all
1768 // the evaluated decls into a vector. Simple is set to true if none
1769 // of the excluded constructs are used.
1770 class DeclExtractor
: public EvaluatedExprVisitor
<DeclExtractor
> {
1771 DeclSetVector
&Decls
;
1772 SmallVectorImpl
<SourceRange
> &Ranges
;
1775 typedef EvaluatedExprVisitor
<DeclExtractor
> Inherited
;
1777 DeclExtractor(Sema
&S
, DeclSetVector
&Decls
,
1778 SmallVectorImpl
<SourceRange
> &Ranges
) :
1779 Inherited(S
.Context
),
1784 bool isSimple() { return Simple
; }
1786 // Replaces the method in EvaluatedExprVisitor.
1787 void VisitMemberExpr(MemberExpr
* E
) {
1791 // Any Stmt not explicitly listed will cause the condition to be marked
1793 void VisitStmt(Stmt
*S
) { Simple
= false; }
1795 void VisitBinaryOperator(BinaryOperator
*E
) {
1800 void VisitCastExpr(CastExpr
*E
) {
1801 Visit(E
->getSubExpr());
1804 void VisitUnaryOperator(UnaryOperator
*E
) {
1805 // Skip checking conditionals with derefernces.
1806 if (E
->getOpcode() == UO_Deref
)
1809 Visit(E
->getSubExpr());
1812 void VisitConditionalOperator(ConditionalOperator
*E
) {
1813 Visit(E
->getCond());
1814 Visit(E
->getTrueExpr());
1815 Visit(E
->getFalseExpr());
1818 void VisitParenExpr(ParenExpr
*E
) {
1819 Visit(E
->getSubExpr());
1822 void VisitBinaryConditionalOperator(BinaryConditionalOperator
*E
) {
1823 Visit(E
->getOpaqueValue()->getSourceExpr());
1824 Visit(E
->getFalseExpr());
1827 void VisitIntegerLiteral(IntegerLiteral
*E
) { }
1828 void VisitFloatingLiteral(FloatingLiteral
*E
) { }
1829 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr
*E
) { }
1830 void VisitCharacterLiteral(CharacterLiteral
*E
) { }
1831 void VisitGNUNullExpr(GNUNullExpr
*E
) { }
1832 void VisitImaginaryLiteral(ImaginaryLiteral
*E
) { }
1834 void VisitDeclRefExpr(DeclRefExpr
*E
) {
1835 VarDecl
*VD
= dyn_cast
<VarDecl
>(E
->getDecl());
1837 // Don't allow unhandled Decl types.
1842 Ranges
.push_back(E
->getSourceRange());
1847 }; // end class DeclExtractor
1849 // DeclMatcher checks to see if the decls are used in a non-evaluated
1851 class DeclMatcher
: public EvaluatedExprVisitor
<DeclMatcher
> {
1852 DeclSetVector
&Decls
;
1856 typedef EvaluatedExprVisitor
<DeclMatcher
> Inherited
;
1858 DeclMatcher(Sema
&S
, DeclSetVector
&Decls
, Stmt
*Statement
) :
1859 Inherited(S
.Context
), Decls(Decls
), FoundDecl(false) {
1860 if (!Statement
) return;
1865 void VisitReturnStmt(ReturnStmt
*S
) {
1869 void VisitBreakStmt(BreakStmt
*S
) {
1873 void VisitGotoStmt(GotoStmt
*S
) {
1877 void VisitCastExpr(CastExpr
*E
) {
1878 if (E
->getCastKind() == CK_LValueToRValue
)
1879 CheckLValueToRValueCast(E
->getSubExpr());
1881 Visit(E
->getSubExpr());
1884 void CheckLValueToRValueCast(Expr
*E
) {
1885 E
= E
->IgnoreParenImpCasts();
1887 if (isa
<DeclRefExpr
>(E
)) {
1891 if (ConditionalOperator
*CO
= dyn_cast
<ConditionalOperator
>(E
)) {
1892 Visit(CO
->getCond());
1893 CheckLValueToRValueCast(CO
->getTrueExpr());
1894 CheckLValueToRValueCast(CO
->getFalseExpr());
1898 if (BinaryConditionalOperator
*BCO
=
1899 dyn_cast
<BinaryConditionalOperator
>(E
)) {
1900 CheckLValueToRValueCast(BCO
->getOpaqueValue()->getSourceExpr());
1901 CheckLValueToRValueCast(BCO
->getFalseExpr());
1908 void VisitDeclRefExpr(DeclRefExpr
*E
) {
1909 if (VarDecl
*VD
= dyn_cast
<VarDecl
>(E
->getDecl()))
1910 if (Decls
.count(VD
))
1914 void VisitPseudoObjectExpr(PseudoObjectExpr
*POE
) {
1915 // Only need to visit the semantics for POE.
1916 // SyntaticForm doesn't really use the Decal.
1917 for (auto *S
: POE
->semantics()) {
1918 if (auto *OVE
= dyn_cast
<OpaqueValueExpr
>(S
))
1919 // Look past the OVE into the expression it binds.
1920 Visit(OVE
->getSourceExpr());
1926 bool FoundDeclInUse() { return FoundDecl
; }
1928 }; // end class DeclMatcher
1930 void CheckForLoopConditionalStatement(Sema
&S
, Expr
*Second
,
1931 Expr
*Third
, Stmt
*Body
) {
1932 // Condition is empty
1933 if (!Second
) return;
1935 if (S
.Diags
.isIgnored(diag::warn_variables_not_in_loop_body
,
1936 Second
->getBeginLoc()))
1939 PartialDiagnostic PDiag
= S
.PDiag(diag::warn_variables_not_in_loop_body
);
1940 DeclSetVector Decls
;
1941 SmallVector
<SourceRange
, 10> Ranges
;
1942 DeclExtractor
DE(S
, Decls
, Ranges
);
1945 // Don't analyze complex conditionals.
1946 if (!DE
.isSimple()) return;
1949 if (Decls
.size() == 0) return;
1951 // Don't warn on volatile, static, or global variables.
1952 for (auto *VD
: Decls
)
1953 if (VD
->getType().isVolatileQualified() || VD
->hasGlobalStorage())
1956 if (DeclMatcher(S
, Decls
, Second
).FoundDeclInUse() ||
1957 DeclMatcher(S
, Decls
, Third
).FoundDeclInUse() ||
1958 DeclMatcher(S
, Decls
, Body
).FoundDeclInUse())
1961 // Load decl names into diagnostic.
1962 if (Decls
.size() > 4) {
1965 PDiag
<< (unsigned)Decls
.size();
1966 for (auto *VD
: Decls
)
1967 PDiag
<< VD
->getDeclName();
1970 for (auto Range
: Ranges
)
1973 S
.Diag(Ranges
.begin()->getBegin(), PDiag
);
1976 // If Statement is an incemement or decrement, return true and sets the
1977 // variables Increment and DRE.
1978 bool ProcessIterationStmt(Sema
&S
, Stmt
* Statement
, bool &Increment
,
1979 DeclRefExpr
*&DRE
) {
1980 if (auto Cleanups
= dyn_cast
<ExprWithCleanups
>(Statement
))
1981 if (!Cleanups
->cleanupsHaveSideEffects())
1982 Statement
= Cleanups
->getSubExpr();
1984 if (UnaryOperator
*UO
= dyn_cast
<UnaryOperator
>(Statement
)) {
1985 switch (UO
->getOpcode()) {
1986 default: return false;
1996 DRE
= dyn_cast
<DeclRefExpr
>(UO
->getSubExpr());
2000 if (CXXOperatorCallExpr
*Call
= dyn_cast
<CXXOperatorCallExpr
>(Statement
)) {
2001 FunctionDecl
*FD
= Call
->getDirectCallee();
2002 if (!FD
|| !FD
->isOverloadedOperator()) return false;
2003 switch (FD
->getOverloadedOperator()) {
2004 default: return false;
2012 DRE
= dyn_cast
<DeclRefExpr
>(Call
->getArg(0));
2019 // A visitor to determine if a continue or break statement is a
2021 class BreakContinueFinder
: public ConstEvaluatedExprVisitor
<BreakContinueFinder
> {
2022 SourceLocation BreakLoc
;
2023 SourceLocation ContinueLoc
;
2024 bool InSwitch
= false;
2027 BreakContinueFinder(Sema
&S
, const Stmt
* Body
) :
2028 Inherited(S
.Context
) {
2032 typedef ConstEvaluatedExprVisitor
<BreakContinueFinder
> Inherited
;
2034 void VisitContinueStmt(const ContinueStmt
* E
) {
2035 ContinueLoc
= E
->getContinueLoc();
2038 void VisitBreakStmt(const BreakStmt
* E
) {
2040 BreakLoc
= E
->getBreakLoc();
2043 void VisitSwitchStmt(const SwitchStmt
* S
) {
2044 if (const Stmt
*Init
= S
->getInit())
2046 if (const Stmt
*CondVar
= S
->getConditionVariableDeclStmt())
2048 if (const Stmt
*Cond
= S
->getCond())
2051 // Don't return break statements from the body of a switch.
2053 if (const Stmt
*Body
= S
->getBody())
2058 void VisitForStmt(const ForStmt
*S
) {
2059 // Only visit the init statement of a for loop; the body
2060 // has a different break/continue scope.
2061 if (const Stmt
*Init
= S
->getInit())
2065 void VisitWhileStmt(const WhileStmt
*) {
2066 // Do nothing; the children of a while loop have a different
2067 // break/continue scope.
2070 void VisitDoStmt(const DoStmt
*) {
2071 // Do nothing; the children of a while loop have a different
2072 // break/continue scope.
2075 void VisitCXXForRangeStmt(const CXXForRangeStmt
*S
) {
2076 // Only visit the initialization of a for loop; the body
2077 // has a different break/continue scope.
2078 if (const Stmt
*Init
= S
->getInit())
2080 if (const Stmt
*Range
= S
->getRangeStmt())
2082 if (const Stmt
*Begin
= S
->getBeginStmt())
2084 if (const Stmt
*End
= S
->getEndStmt())
2088 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt
*S
) {
2089 // Only visit the initialization of a for loop; the body
2090 // has a different break/continue scope.
2091 if (const Stmt
*Element
= S
->getElement())
2093 if (const Stmt
*Collection
= S
->getCollection())
2097 bool ContinueFound() { return ContinueLoc
.isValid(); }
2098 bool BreakFound() { return BreakLoc
.isValid(); }
2099 SourceLocation
GetContinueLoc() { return ContinueLoc
; }
2100 SourceLocation
GetBreakLoc() { return BreakLoc
; }
2102 }; // end class BreakContinueFinder
2104 // Emit a warning when a loop increment/decrement appears twice per loop
2105 // iteration. The conditions which trigger this warning are:
2106 // 1) The last statement in the loop body and the third expression in the
2107 // for loop are both increment or both decrement of the same variable
2108 // 2) No continue statements in the loop body.
2109 void CheckForRedundantIteration(Sema
&S
, Expr
*Third
, Stmt
*Body
) {
2110 // Return when there is nothing to check.
2111 if (!Body
|| !Third
) return;
2113 if (S
.Diags
.isIgnored(diag::warn_redundant_loop_iteration
,
2114 Third
->getBeginLoc()))
2117 // Get the last statement from the loop body.
2118 CompoundStmt
*CS
= dyn_cast
<CompoundStmt
>(Body
);
2119 if (!CS
|| CS
->body_empty()) return;
2120 Stmt
*LastStmt
= CS
->body_back();
2121 if (!LastStmt
) return;
2123 bool LoopIncrement
, LastIncrement
;
2124 DeclRefExpr
*LoopDRE
, *LastDRE
;
2126 if (!ProcessIterationStmt(S
, Third
, LoopIncrement
, LoopDRE
)) return;
2127 if (!ProcessIterationStmt(S
, LastStmt
, LastIncrement
, LastDRE
)) return;
2129 // Check that the two statements are both increments or both decrements
2130 // on the same variable.
2131 if (LoopIncrement
!= LastIncrement
||
2132 LoopDRE
->getDecl() != LastDRE
->getDecl()) return;
2134 if (BreakContinueFinder(S
, Body
).ContinueFound()) return;
2136 S
.Diag(LastDRE
->getLocation(), diag::warn_redundant_loop_iteration
)
2137 << LastDRE
->getDecl() << LastIncrement
;
2138 S
.Diag(LoopDRE
->getLocation(), diag::note_loop_iteration_here
)
2145 void Sema::CheckBreakContinueBinding(Expr
*E
) {
2146 if (!E
|| getLangOpts().CPlusPlus
)
2148 BreakContinueFinder
BCFinder(*this, E
);
2149 Scope
*BreakParent
= CurScope
->getBreakParent();
2150 if (BCFinder
.BreakFound() && BreakParent
) {
2151 if (BreakParent
->getFlags() & Scope::SwitchScope
) {
2152 Diag(BCFinder
.GetBreakLoc(), diag::warn_break_binds_to_switch
);
2154 Diag(BCFinder
.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner
)
2157 } else if (BCFinder
.ContinueFound() && CurScope
->getContinueParent()) {
2158 Diag(BCFinder
.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner
)
2163 StmtResult
Sema::ActOnForStmt(SourceLocation ForLoc
, SourceLocation LParenLoc
,
2164 Stmt
*First
, ConditionResult Second
,
2165 FullExprArg third
, SourceLocation RParenLoc
,
2167 if (Second
.isInvalid())
2170 if (!getLangOpts().CPlusPlus
) {
2171 if (DeclStmt
*DS
= dyn_cast_or_null
<DeclStmt
>(First
)) {
2172 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
2173 // declare identifiers for objects having storage class 'auto' or
2175 const Decl
*NonVarSeen
= nullptr;
2176 bool VarDeclSeen
= false;
2177 for (auto *DI
: DS
->decls()) {
2178 if (VarDecl
*VD
= dyn_cast
<VarDecl
>(DI
)) {
2180 if (VD
->isLocalVarDecl() && !VD
->hasLocalStorage()) {
2181 Diag(DI
->getLocation(), diag::err_non_local_variable_decl_in_for
);
2182 DI
->setInvalidDecl();
2184 } else if (!NonVarSeen
) {
2185 // Keep track of the first non-variable declaration we saw so that
2186 // we can diagnose if we don't see any variable declarations. This
2187 // covers a case like declaring a typedef, function, or structure
2188 // type rather than a variable.
2192 // Diagnose if we saw a non-variable declaration but no variable
2194 if (NonVarSeen
&& !VarDeclSeen
)
2195 Diag(NonVarSeen
->getLocation(), diag::err_non_variable_decl_in_for
);
2199 CheckBreakContinueBinding(Second
.get().second
);
2200 CheckBreakContinueBinding(third
.get());
2202 if (!Second
.get().first
)
2203 CheckForLoopConditionalStatement(*this, Second
.get().second
, third
.get(),
2205 CheckForRedundantIteration(*this, third
.get(), Body
);
2207 if (Second
.get().second
&&
2208 !Diags
.isIgnored(diag::warn_comma_operator
,
2209 Second
.get().second
->getExprLoc()))
2210 CommaVisitor(*this).Visit(Second
.get().second
);
2212 Expr
*Third
= third
.release().getAs
<Expr
>();
2213 if (isa
<NullStmt
>(Body
))
2214 getCurCompoundScope().setHasEmptyLoopBodies();
2216 return new (Context
)
2217 ForStmt(Context
, First
, Second
.get().second
, Second
.get().first
, Third
,
2218 Body
, ForLoc
, LParenLoc
, RParenLoc
);
2221 /// In an Objective C collection iteration statement:
2223 /// x can be an arbitrary l-value expression. Bind it up as a
2224 /// full-expression.
2225 StmtResult
Sema::ActOnForEachLValueExpr(Expr
*E
) {
2226 // Reduce placeholder expressions here. Note that this rejects the
2227 // use of pseudo-object l-values in this position.
2228 ExprResult result
= CheckPlaceholderExpr(E
);
2229 if (result
.isInvalid()) return StmtError();
2232 ExprResult FullExpr
= ActOnFinishFullExpr(E
, /*DiscardedValue*/ false);
2233 if (FullExpr
.isInvalid())
2235 return StmtResult(static_cast<Stmt
*>(FullExpr
.get()));
2239 Sema::CheckObjCForCollectionOperand(SourceLocation forLoc
, Expr
*collection
) {
2243 ExprResult result
= CorrectDelayedTyposInExpr(collection
);
2244 if (!result
.isUsable())
2246 collection
= result
.get();
2248 // Bail out early if we've got a type-dependent expression.
2249 if (collection
->isTypeDependent()) return collection
;
2251 // Perform normal l-value conversion.
2252 result
= DefaultFunctionArrayLvalueConversion(collection
);
2253 if (result
.isInvalid())
2255 collection
= result
.get();
2257 // The operand needs to have object-pointer type.
2258 // TODO: should we do a contextual conversion?
2259 const ObjCObjectPointerType
*pointerType
=
2260 collection
->getType()->getAs
<ObjCObjectPointerType
>();
2262 return Diag(forLoc
, diag::err_collection_expr_type
)
2263 << collection
->getType() << collection
->getSourceRange();
2265 // Check that the operand provides
2266 // - countByEnumeratingWithState:objects:count:
2267 const ObjCObjectType
*objectType
= pointerType
->getObjectType();
2268 ObjCInterfaceDecl
*iface
= objectType
->getInterface();
2270 // If we have a forward-declared type, we can't do this check.
2271 // Under ARC, it is an error not to have a forward-declared class.
2273 (getLangOpts().ObjCAutoRefCount
2274 ? RequireCompleteType(forLoc
, QualType(objectType
, 0),
2275 diag::err_arc_collection_forward
, collection
)
2276 : !isCompleteType(forLoc
, QualType(objectType
, 0)))) {
2277 // Otherwise, if we have any useful type information, check that
2278 // the type declares the appropriate method.
2279 } else if (iface
|| !objectType
->qual_empty()) {
2280 const IdentifierInfo
*selectorIdents
[] = {
2281 &Context
.Idents
.get("countByEnumeratingWithState"),
2282 &Context
.Idents
.get("objects"), &Context
.Idents
.get("count")};
2283 Selector selector
= Context
.Selectors
.getSelector(3, &selectorIdents
[0]);
2285 ObjCMethodDecl
*method
= nullptr;
2287 // If there's an interface, look in both the public and private APIs.
2289 method
= iface
->lookupInstanceMethod(selector
);
2290 if (!method
) method
= iface
->lookupPrivateMethod(selector
);
2293 // Also check protocol qualifiers.
2295 method
= LookupMethodInQualifiedType(selector
, pointerType
,
2298 // If we didn't find it anywhere, give up.
2300 Diag(forLoc
, diag::warn_collection_expr_type
)
2301 << collection
->getType() << selector
<< collection
->getSourceRange();
2304 // TODO: check for an incompatible signature?
2307 // Wrap up any cleanups in the expression.
2312 Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc
,
2313 Stmt
*First
, Expr
*collection
,
2314 SourceLocation RParenLoc
) {
2315 setFunctionHasBranchProtectedScope();
2317 ExprResult CollectionExprResult
=
2318 CheckObjCForCollectionOperand(ForLoc
, collection
);
2322 if (DeclStmt
*DS
= dyn_cast
<DeclStmt
>(First
)) {
2323 if (!DS
->isSingleDecl())
2324 return StmtError(Diag((*DS
->decl_begin())->getLocation(),
2325 diag::err_toomany_element_decls
));
2327 VarDecl
*D
= dyn_cast
<VarDecl
>(DS
->getSingleDecl());
2328 if (!D
|| D
->isInvalidDecl())
2331 FirstType
= D
->getType();
2332 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
2333 // declare identifiers for objects having storage class 'auto' or
2335 if (!D
->hasLocalStorage())
2336 return StmtError(Diag(D
->getLocation(),
2337 diag::err_non_local_variable_decl_in_for
));
2339 // If the type contained 'auto', deduce the 'auto' to 'id'.
2340 if (FirstType
->getContainedAutoType()) {
2341 SourceLocation Loc
= D
->getLocation();
2342 OpaqueValueExpr
OpaqueId(Loc
, Context
.getObjCIdType(), VK_PRValue
);
2343 Expr
*DeducedInit
= &OpaqueId
;
2344 TemplateDeductionInfo
Info(Loc
);
2345 FirstType
= QualType();
2346 TemplateDeductionResult Result
= DeduceAutoType(
2347 D
->getTypeSourceInfo()->getTypeLoc(), DeducedInit
, FirstType
, Info
);
2348 if (Result
!= TemplateDeductionResult::Success
&&
2349 Result
!= TemplateDeductionResult::AlreadyDiagnosed
)
2350 DiagnoseAutoDeductionFailure(D
, DeducedInit
);
2351 if (FirstType
.isNull()) {
2352 D
->setInvalidDecl();
2356 D
->setType(FirstType
);
2358 if (!inTemplateInstantiation()) {
2359 SourceLocation Loc
=
2360 D
->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
2361 Diag(Loc
, diag::warn_auto_var_is_id
)
2362 << D
->getDeclName();
2367 Expr
*FirstE
= cast
<Expr
>(First
);
2368 if (!FirstE
->isTypeDependent() && !FirstE
->isLValue())
2370 Diag(First
->getBeginLoc(), diag::err_selector_element_not_lvalue
)
2371 << First
->getSourceRange());
2373 FirstType
= static_cast<Expr
*>(First
)->getType();
2374 if (FirstType
.isConstQualified())
2375 Diag(ForLoc
, diag::err_selector_element_const_type
)
2376 << FirstType
<< First
->getSourceRange();
2378 if (!FirstType
->isDependentType() &&
2379 !FirstType
->isObjCObjectPointerType() &&
2380 !FirstType
->isBlockPointerType())
2381 return StmtError(Diag(ForLoc
, diag::err_selector_element_type
)
2382 << FirstType
<< First
->getSourceRange());
2385 if (CollectionExprResult
.isInvalid())
2388 CollectionExprResult
=
2389 ActOnFinishFullExpr(CollectionExprResult
.get(), /*DiscardedValue*/ false);
2390 if (CollectionExprResult
.isInvalid())
2393 return new (Context
) ObjCForCollectionStmt(First
, CollectionExprResult
.get(),
2394 nullptr, ForLoc
, RParenLoc
);
2397 /// Finish building a variable declaration for a for-range statement.
2398 /// \return true if an error occurs.
2399 static bool FinishForRangeVarDecl(Sema
&SemaRef
, VarDecl
*Decl
, Expr
*Init
,
2400 SourceLocation Loc
, int DiagID
) {
2401 if (Decl
->getType()->isUndeducedType()) {
2402 ExprResult Res
= SemaRef
.CorrectDelayedTyposInExpr(Init
);
2403 if (!Res
.isUsable()) {
2404 Decl
->setInvalidDecl();
2410 // Deduce the type for the iterator variable now rather than leaving it to
2411 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
2413 if (!isa
<InitListExpr
>(Init
) && Init
->getType()->isVoidType()) {
2414 SemaRef
.Diag(Loc
, DiagID
) << Init
->getType();
2416 TemplateDeductionInfo
Info(Init
->getExprLoc());
2417 TemplateDeductionResult Result
= SemaRef
.DeduceAutoType(
2418 Decl
->getTypeSourceInfo()->getTypeLoc(), Init
, InitType
, Info
);
2419 if (Result
!= TemplateDeductionResult::Success
&&
2420 Result
!= TemplateDeductionResult::AlreadyDiagnosed
)
2421 SemaRef
.Diag(Loc
, DiagID
) << Init
->getType();
2424 if (InitType
.isNull()) {
2425 Decl
->setInvalidDecl();
2428 Decl
->setType(InitType
);
2430 // In ARC, infer lifetime.
2431 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
2432 // we're doing the equivalent of fast iteration.
2433 if (SemaRef
.getLangOpts().ObjCAutoRefCount
&&
2434 SemaRef
.inferObjCARCLifetime(Decl
))
2435 Decl
->setInvalidDecl();
2437 SemaRef
.AddInitializerToDecl(Decl
, Init
, /*DirectInit=*/false);
2438 SemaRef
.FinalizeDeclaration(Decl
);
2439 SemaRef
.CurContext
->addHiddenDecl(Decl
);
2444 // An enum to represent whether something is dealing with a call to begin()
2445 // or a call to end() in a range-based for loop.
2446 enum BeginEndFunction
{
2451 /// Produce a note indicating which begin/end function was implicitly called
2452 /// by a C++11 for-range statement. This is often not obvious from the code,
2453 /// nor from the diagnostics produced when analysing the implicit expressions
2454 /// required in a for-range statement.
2455 void NoteForRangeBeginEndFunction(Sema
&SemaRef
, Expr
*E
,
2456 BeginEndFunction BEF
) {
2457 CallExpr
*CE
= dyn_cast
<CallExpr
>(E
);
2460 FunctionDecl
*D
= dyn_cast
<FunctionDecl
>(CE
->getCalleeDecl());
2463 SourceLocation Loc
= D
->getLocation();
2465 std::string Description
;
2466 bool IsTemplate
= false;
2467 if (FunctionTemplateDecl
*FunTmpl
= D
->getPrimaryTemplate()) {
2468 Description
= SemaRef
.getTemplateArgumentBindingsText(
2469 FunTmpl
->getTemplateParameters(), *D
->getTemplateSpecializationArgs());
2473 SemaRef
.Diag(Loc
, diag::note_for_range_begin_end
)
2474 << BEF
<< IsTemplate
<< Description
<< E
->getType();
2477 /// Build a variable declaration for a for-range statement.
2478 VarDecl
*BuildForRangeVarDecl(Sema
&SemaRef
, SourceLocation Loc
,
2479 QualType Type
, StringRef Name
) {
2480 DeclContext
*DC
= SemaRef
.CurContext
;
2481 IdentifierInfo
*II
= &SemaRef
.PP
.getIdentifierTable().get(Name
);
2482 TypeSourceInfo
*TInfo
= SemaRef
.Context
.getTrivialTypeSourceInfo(Type
, Loc
);
2483 VarDecl
*Decl
= VarDecl::Create(SemaRef
.Context
, DC
, Loc
, Loc
, II
, Type
,
2485 Decl
->setImplicit();
2491 static bool ObjCEnumerationCollection(Expr
*Collection
) {
2492 return !Collection
->isTypeDependent()
2493 && Collection
->getType()->getAs
<ObjCObjectPointerType
>() != nullptr;
2496 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
2498 /// C++11 [stmt.ranged]:
2499 /// A range-based for statement is equivalent to
2502 /// auto && __range = range-init;
2503 /// for ( auto __begin = begin-expr,
2504 /// __end = end-expr;
2505 /// __begin != __end;
2507 /// for-range-declaration = *__begin;
2512 /// The body of the loop is not available yet, since it cannot be analysed until
2513 /// we have determined the type of the for-range-declaration.
2514 StmtResult
Sema::ActOnCXXForRangeStmt(
2515 Scope
*S
, SourceLocation ForLoc
, SourceLocation CoawaitLoc
, Stmt
*InitStmt
,
2516 Stmt
*First
, SourceLocation ColonLoc
, Expr
*Range
, SourceLocation RParenLoc
,
2517 BuildForRangeKind Kind
,
2518 ArrayRef
<MaterializeTemporaryExpr
*> LifetimeExtendTemps
) {
2519 // FIXME: recover in order to allow the body to be parsed.
2523 if (Range
&& ObjCEnumerationCollection(Range
)) {
2524 // FIXME: Support init-statements in Objective-C++20 ranged for statement.
2526 return Diag(InitStmt
->getBeginLoc(), diag::err_objc_for_range_init_stmt
)
2527 << InitStmt
->getSourceRange();
2528 return ActOnObjCForCollectionStmt(ForLoc
, First
, Range
, RParenLoc
);
2531 DeclStmt
*DS
= dyn_cast
<DeclStmt
>(First
);
2532 assert(DS
&& "first part of for range not a decl stmt");
2534 if (!DS
->isSingleDecl()) {
2535 Diag(DS
->getBeginLoc(), diag::err_type_defined_in_for_range
);
2539 // This function is responsible for attaching an initializer to LoopVar. We
2540 // must call ActOnInitializerError if we fail to do so.
2541 Decl
*LoopVar
= DS
->getSingleDecl();
2542 if (LoopVar
->isInvalidDecl() || !Range
||
2543 DiagnoseUnexpandedParameterPack(Range
, UPPC_Expression
)) {
2544 ActOnInitializerError(LoopVar
);
2548 // Build the coroutine state immediately and not later during template
2550 if (!CoawaitLoc
.isInvalid()) {
2551 if (!ActOnCoroutineBodyStart(S
, CoawaitLoc
, "co_await")) {
2552 ActOnInitializerError(LoopVar
);
2557 // Build auto && __range = range-init
2558 // Divide by 2, since the variables are in the inner scope (loop body).
2559 const auto DepthStr
= std::to_string(S
->getDepth() / 2);
2560 SourceLocation RangeLoc
= Range
->getBeginLoc();
2561 VarDecl
*RangeVar
= BuildForRangeVarDecl(*this, RangeLoc
,
2562 Context
.getAutoRRefDeductType(),
2563 std::string("__range") + DepthStr
);
2564 if (FinishForRangeVarDecl(*this, RangeVar
, Range
, RangeLoc
,
2565 diag::err_for_range_deduction_failure
)) {
2566 ActOnInitializerError(LoopVar
);
2570 // Claim the type doesn't contain auto: we've already done the checking.
2571 DeclGroupPtrTy RangeGroup
=
2572 BuildDeclaratorGroup(MutableArrayRef
<Decl
*>((Decl
**)&RangeVar
, 1));
2573 StmtResult RangeDecl
= ActOnDeclStmt(RangeGroup
, RangeLoc
, RangeLoc
);
2574 if (RangeDecl
.isInvalid()) {
2575 ActOnInitializerError(LoopVar
);
2579 StmtResult R
= BuildCXXForRangeStmt(
2580 ForLoc
, CoawaitLoc
, InitStmt
, ColonLoc
, RangeDecl
.get(),
2581 /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
2582 /*Cond=*/nullptr, /*Inc=*/nullptr, DS
, RParenLoc
, Kind
,
2583 LifetimeExtendTemps
);
2584 if (R
.isInvalid()) {
2585 ActOnInitializerError(LoopVar
);
2592 /// Create the initialization, compare, and increment steps for
2593 /// the range-based for loop expression.
2594 /// This function does not handle array-based for loops,
2595 /// which are created in Sema::BuildCXXForRangeStmt.
2597 /// \returns a ForRangeStatus indicating success or what kind of error occurred.
2598 /// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2599 /// CandidateSet and BEF are set and some non-success value is returned on
2601 static Sema::ForRangeStatus
2602 BuildNonArrayForRange(Sema
&SemaRef
, Expr
*BeginRange
, Expr
*EndRange
,
2603 QualType RangeType
, VarDecl
*BeginVar
, VarDecl
*EndVar
,
2604 SourceLocation ColonLoc
, SourceLocation CoawaitLoc
,
2605 OverloadCandidateSet
*CandidateSet
, ExprResult
*BeginExpr
,
2606 ExprResult
*EndExpr
, BeginEndFunction
*BEF
) {
2607 DeclarationNameInfo
BeginNameInfo(
2608 &SemaRef
.PP
.getIdentifierTable().get("begin"), ColonLoc
);
2609 DeclarationNameInfo
EndNameInfo(&SemaRef
.PP
.getIdentifierTable().get("end"),
2612 LookupResult
BeginMemberLookup(SemaRef
, BeginNameInfo
,
2613 Sema::LookupMemberName
);
2614 LookupResult
EndMemberLookup(SemaRef
, EndNameInfo
, Sema::LookupMemberName
);
2616 auto BuildBegin
= [&] {
2618 Sema::ForRangeStatus RangeStatus
=
2619 SemaRef
.BuildForRangeBeginEndCall(ColonLoc
, ColonLoc
, BeginNameInfo
,
2620 BeginMemberLookup
, CandidateSet
,
2621 BeginRange
, BeginExpr
);
2623 if (RangeStatus
!= Sema::FRS_Success
) {
2624 if (RangeStatus
== Sema::FRS_DiagnosticIssued
)
2625 SemaRef
.Diag(BeginRange
->getBeginLoc(), diag::note_in_for_range
)
2626 << ColonLoc
<< BEF_begin
<< BeginRange
->getType();
2629 if (!CoawaitLoc
.isInvalid()) {
2630 // FIXME: getCurScope() should not be used during template instantiation.
2631 // We should pick up the set of unqualified lookup results for operator
2632 // co_await during the initial parse.
2633 *BeginExpr
= SemaRef
.ActOnCoawaitExpr(SemaRef
.getCurScope(), ColonLoc
,
2635 if (BeginExpr
->isInvalid())
2636 return Sema::FRS_DiagnosticIssued
;
2638 if (FinishForRangeVarDecl(SemaRef
, BeginVar
, BeginExpr
->get(), ColonLoc
,
2639 diag::err_for_range_iter_deduction_failure
)) {
2640 NoteForRangeBeginEndFunction(SemaRef
, BeginExpr
->get(), *BEF
);
2641 return Sema::FRS_DiagnosticIssued
;
2643 return Sema::FRS_Success
;
2646 auto BuildEnd
= [&] {
2648 Sema::ForRangeStatus RangeStatus
=
2649 SemaRef
.BuildForRangeBeginEndCall(ColonLoc
, ColonLoc
, EndNameInfo
,
2650 EndMemberLookup
, CandidateSet
,
2652 if (RangeStatus
!= Sema::FRS_Success
) {
2653 if (RangeStatus
== Sema::FRS_DiagnosticIssued
)
2654 SemaRef
.Diag(EndRange
->getBeginLoc(), diag::note_in_for_range
)
2655 << ColonLoc
<< BEF_end
<< EndRange
->getType();
2658 if (FinishForRangeVarDecl(SemaRef
, EndVar
, EndExpr
->get(), ColonLoc
,
2659 diag::err_for_range_iter_deduction_failure
)) {
2660 NoteForRangeBeginEndFunction(SemaRef
, EndExpr
->get(), *BEF
);
2661 return Sema::FRS_DiagnosticIssued
;
2663 return Sema::FRS_Success
;
2666 if (CXXRecordDecl
*D
= RangeType
->getAsCXXRecordDecl()) {
2667 // - if _RangeT is a class type, the unqualified-ids begin and end are
2668 // looked up in the scope of class _RangeT as if by class member access
2669 // lookup (3.4.5), and if either (or both) finds at least one
2670 // declaration, begin-expr and end-expr are __range.begin() and
2671 // __range.end(), respectively;
2672 SemaRef
.LookupQualifiedName(BeginMemberLookup
, D
);
2673 if (BeginMemberLookup
.isAmbiguous())
2674 return Sema::FRS_DiagnosticIssued
;
2676 SemaRef
.LookupQualifiedName(EndMemberLookup
, D
);
2677 if (EndMemberLookup
.isAmbiguous())
2678 return Sema::FRS_DiagnosticIssued
;
2680 if (BeginMemberLookup
.empty() != EndMemberLookup
.empty()) {
2681 // Look up the non-member form of the member we didn't find, first.
2682 // This way we prefer a "no viable 'end'" diagnostic over a "i found
2683 // a 'begin' but ignored it because there was no member 'end'"
2685 auto BuildNonmember
= [&](
2686 BeginEndFunction BEFFound
, LookupResult
&Found
,
2687 llvm::function_ref
<Sema::ForRangeStatus()> BuildFound
,
2688 llvm::function_ref
<Sema::ForRangeStatus()> BuildNotFound
) {
2689 LookupResult OldFound
= std::move(Found
);
2692 if (Sema::ForRangeStatus Result
= BuildNotFound())
2695 switch (BuildFound()) {
2696 case Sema::FRS_Success
:
2697 return Sema::FRS_Success
;
2699 case Sema::FRS_NoViableFunction
:
2700 CandidateSet
->NoteCandidates(
2701 PartialDiagnosticAt(BeginRange
->getBeginLoc(),
2702 SemaRef
.PDiag(diag::err_for_range_invalid
)
2703 << BeginRange
->getType() << BEFFound
),
2704 SemaRef
, OCD_AllCandidates
, BeginRange
);
2707 case Sema::FRS_DiagnosticIssued
:
2708 for (NamedDecl
*D
: OldFound
) {
2709 SemaRef
.Diag(D
->getLocation(),
2710 diag::note_for_range_member_begin_end_ignored
)
2711 << BeginRange
->getType() << BEFFound
;
2713 return Sema::FRS_DiagnosticIssued
;
2715 llvm_unreachable("unexpected ForRangeStatus");
2717 if (BeginMemberLookup
.empty())
2718 return BuildNonmember(BEF_end
, EndMemberLookup
, BuildEnd
, BuildBegin
);
2719 return BuildNonmember(BEF_begin
, BeginMemberLookup
, BuildBegin
, BuildEnd
);
2722 // - otherwise, begin-expr and end-expr are begin(__range) and
2723 // end(__range), respectively, where begin and end are looked up with
2724 // argument-dependent lookup (3.4.2). For the purposes of this name
2725 // lookup, namespace std is an associated namespace.
2728 if (Sema::ForRangeStatus Result
= BuildBegin())
2733 /// Speculatively attempt to dereference an invalid range expression.
2734 /// If the attempt fails, this function will return a valid, null StmtResult
2735 /// and emit no diagnostics.
2736 static StmtResult
RebuildForRangeWithDereference(Sema
&SemaRef
, Scope
*S
,
2737 SourceLocation ForLoc
,
2738 SourceLocation CoawaitLoc
,
2741 SourceLocation ColonLoc
,
2743 SourceLocation RangeLoc
,
2744 SourceLocation RParenLoc
) {
2745 // Determine whether we can rebuild the for-range statement with a
2746 // dereferenced range expression.
2747 ExprResult AdjustedRange
;
2749 Sema::SFINAETrap
Trap(SemaRef
);
2751 AdjustedRange
= SemaRef
.BuildUnaryOp(S
, RangeLoc
, UO_Deref
, Range
);
2752 if (AdjustedRange
.isInvalid())
2753 return StmtResult();
2755 StmtResult SR
= SemaRef
.ActOnCXXForRangeStmt(
2756 S
, ForLoc
, CoawaitLoc
, InitStmt
, LoopVarDecl
, ColonLoc
,
2757 AdjustedRange
.get(), RParenLoc
, Sema::BFRK_Check
);
2759 return StmtResult();
2762 // The attempt to dereference worked well enough that it could produce a valid
2763 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2764 // case there are any other (non-fatal) problems with it.
2765 SemaRef
.Diag(RangeLoc
, diag::err_for_range_dereference
)
2766 << Range
->getType() << FixItHint::CreateInsertion(RangeLoc
, "*");
2767 return SemaRef
.ActOnCXXForRangeStmt(
2768 S
, ForLoc
, CoawaitLoc
, InitStmt
, LoopVarDecl
, ColonLoc
,
2769 AdjustedRange
.get(), RParenLoc
, Sema::BFRK_Rebuild
);
2772 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
2773 StmtResult
Sema::BuildCXXForRangeStmt(
2774 SourceLocation ForLoc
, SourceLocation CoawaitLoc
, Stmt
*InitStmt
,
2775 SourceLocation ColonLoc
, Stmt
*RangeDecl
, Stmt
*Begin
, Stmt
*End
,
2776 Expr
*Cond
, Expr
*Inc
, Stmt
*LoopVarDecl
, SourceLocation RParenLoc
,
2777 BuildForRangeKind Kind
,
2778 ArrayRef
<MaterializeTemporaryExpr
*> LifetimeExtendTemps
) {
2779 // FIXME: This should not be used during template instantiation. We should
2780 // pick up the set of unqualified lookup results for the != and + operators
2781 // in the initial parse.
2783 // Testcase (accepts-invalid):
2784 // template<typename T> void f() { for (auto x : T()) {} }
2785 // namespace N { struct X { X begin(); X end(); int operator*(); }; }
2786 // bool operator!=(N::X, N::X); void operator++(N::X);
2787 // void g() { f<N::X>(); }
2788 Scope
*S
= getCurScope();
2790 DeclStmt
*RangeDS
= cast
<DeclStmt
>(RangeDecl
);
2791 VarDecl
*RangeVar
= cast
<VarDecl
>(RangeDS
->getSingleDecl());
2792 QualType RangeVarType
= RangeVar
->getType();
2794 DeclStmt
*LoopVarDS
= cast
<DeclStmt
>(LoopVarDecl
);
2795 VarDecl
*LoopVar
= cast
<VarDecl
>(LoopVarDS
->getSingleDecl());
2797 StmtResult BeginDeclStmt
= Begin
;
2798 StmtResult EndDeclStmt
= End
;
2799 ExprResult NotEqExpr
= Cond
, IncrExpr
= Inc
;
2801 if (RangeVarType
->isDependentType()) {
2802 // The range is implicitly used as a placeholder when it is dependent.
2803 RangeVar
->markUsed(Context
);
2805 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2806 // them in properly when we instantiate the loop.
2807 if (!LoopVar
->isInvalidDecl() && Kind
!= BFRK_Check
) {
2808 if (auto *DD
= dyn_cast
<DecompositionDecl
>(LoopVar
))
2809 for (auto *Binding
: DD
->bindings())
2810 Binding
->setType(Context
.DependentTy
);
2811 LoopVar
->setType(SubstAutoTypeDependent(LoopVar
->getType()));
2813 } else if (!BeginDeclStmt
.get()) {
2814 SourceLocation RangeLoc
= RangeVar
->getLocation();
2816 const QualType RangeVarNonRefType
= RangeVarType
.getNonReferenceType();
2818 ExprResult BeginRangeRef
= BuildDeclRefExpr(RangeVar
, RangeVarNonRefType
,
2819 VK_LValue
, ColonLoc
);
2820 if (BeginRangeRef
.isInvalid())
2823 ExprResult EndRangeRef
= BuildDeclRefExpr(RangeVar
, RangeVarNonRefType
,
2824 VK_LValue
, ColonLoc
);
2825 if (EndRangeRef
.isInvalid())
2828 QualType AutoType
= Context
.getAutoDeductType();
2829 Expr
*Range
= RangeVar
->getInit();
2832 QualType RangeType
= Range
->getType();
2834 if (RequireCompleteType(RangeLoc
, RangeType
,
2835 diag::err_for_range_incomplete_type
))
2838 // P2718R0 - Lifetime extension in range-based for loops.
2839 if (getLangOpts().CPlusPlus23
&& !LifetimeExtendTemps
.empty()) {
2840 InitializedEntity Entity
=
2841 InitializedEntity::InitializeVariable(RangeVar
);
2842 for (auto *MTE
: LifetimeExtendTemps
)
2843 MTE
->setExtendingDecl(RangeVar
, Entity
.allocateManglingNumber());
2846 // Build auto __begin = begin-expr, __end = end-expr.
2847 // Divide by 2, since the variables are in the inner scope (loop body).
2848 const auto DepthStr
= std::to_string(S
->getDepth() / 2);
2849 VarDecl
*BeginVar
= BuildForRangeVarDecl(*this, ColonLoc
, AutoType
,
2850 std::string("__begin") + DepthStr
);
2851 VarDecl
*EndVar
= BuildForRangeVarDecl(*this, ColonLoc
, AutoType
,
2852 std::string("__end") + DepthStr
);
2854 // Build begin-expr and end-expr and attach to __begin and __end variables.
2855 ExprResult BeginExpr
, EndExpr
;
2856 if (const ArrayType
*UnqAT
= RangeType
->getAsArrayTypeUnsafe()) {
2857 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2858 // __range + __bound, respectively, where __bound is the array bound. If
2859 // _RangeT is an array of unknown size or an array of incomplete type,
2860 // the program is ill-formed;
2862 // begin-expr is __range.
2863 BeginExpr
= BeginRangeRef
;
2864 if (!CoawaitLoc
.isInvalid()) {
2865 BeginExpr
= ActOnCoawaitExpr(S
, ColonLoc
, BeginExpr
.get());
2866 if (BeginExpr
.isInvalid())
2869 if (FinishForRangeVarDecl(*this, BeginVar
, BeginRangeRef
.get(), ColonLoc
,
2870 diag::err_for_range_iter_deduction_failure
)) {
2871 NoteForRangeBeginEndFunction(*this, BeginExpr
.get(), BEF_begin
);
2875 // Find the array bound.
2876 ExprResult BoundExpr
;
2877 if (const ConstantArrayType
*CAT
= dyn_cast
<ConstantArrayType
>(UnqAT
))
2878 BoundExpr
= IntegerLiteral::Create(
2879 Context
, CAT
->getSize(), Context
.getPointerDiffType(), RangeLoc
);
2880 else if (const VariableArrayType
*VAT
=
2881 dyn_cast
<VariableArrayType
>(UnqAT
)) {
2882 // For a variably modified type we can't just use the expression within
2883 // the array bounds, since we don't want that to be re-evaluated here.
2884 // Rather, we need to determine what it was when the array was first
2885 // created - so we resort to using sizeof(vla)/sizeof(element).
2889 // b = -1; <-- This should not affect the num of iterations below
2890 // for (int &c : vla) { .. }
2893 // FIXME: This results in codegen generating IR that recalculates the
2894 // run-time number of elements (as opposed to just using the IR Value
2895 // that corresponds to the run-time value of each bound that was
2896 // generated when the array was created.) If this proves too embarrassing
2897 // even for unoptimized IR, consider passing a magic-value/cookie to
2898 // codegen that then knows to simply use that initial llvm::Value (that
2899 // corresponds to the bound at time of array creation) within
2900 // getelementptr. But be prepared to pay the price of increasing a
2901 // customized form of coupling between the two components - which could
2902 // be hard to maintain as the codebase evolves.
2904 ExprResult SizeOfVLAExprR
= ActOnUnaryExprOrTypeTraitExpr(
2905 EndVar
->getLocation(), UETT_SizeOf
,
2907 CreateParsedType(VAT
->desugar(), Context
.getTrivialTypeSourceInfo(
2908 VAT
->desugar(), RangeLoc
))
2910 EndVar
->getSourceRange());
2911 if (SizeOfVLAExprR
.isInvalid())
2914 ExprResult SizeOfEachElementExprR
= ActOnUnaryExprOrTypeTraitExpr(
2915 EndVar
->getLocation(), UETT_SizeOf
,
2917 CreateParsedType(VAT
->desugar(),
2918 Context
.getTrivialTypeSourceInfo(
2919 VAT
->getElementType(), RangeLoc
))
2921 EndVar
->getSourceRange());
2922 if (SizeOfEachElementExprR
.isInvalid())
2926 ActOnBinOp(S
, EndVar
->getLocation(), tok::slash
,
2927 SizeOfVLAExprR
.get(), SizeOfEachElementExprR
.get());
2928 if (BoundExpr
.isInvalid())
2932 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2933 // UnqAT is not incomplete and Range is not type-dependent.
2934 llvm_unreachable("Unexpected array type in for-range");
2937 // end-expr is __range + __bound.
2938 EndExpr
= ActOnBinOp(S
, ColonLoc
, tok::plus
, EndRangeRef
.get(),
2940 if (EndExpr
.isInvalid())
2942 if (FinishForRangeVarDecl(*this, EndVar
, EndExpr
.get(), ColonLoc
,
2943 diag::err_for_range_iter_deduction_failure
)) {
2944 NoteForRangeBeginEndFunction(*this, EndExpr
.get(), BEF_end
);
2948 OverloadCandidateSet
CandidateSet(RangeLoc
,
2949 OverloadCandidateSet::CSK_Normal
);
2950 BeginEndFunction BEFFailure
;
2951 ForRangeStatus RangeStatus
= BuildNonArrayForRange(
2952 *this, BeginRangeRef
.get(), EndRangeRef
.get(), RangeType
, BeginVar
,
2953 EndVar
, ColonLoc
, CoawaitLoc
, &CandidateSet
, &BeginExpr
, &EndExpr
,
2956 if (Kind
== BFRK_Build
&& RangeStatus
== FRS_NoViableFunction
&&
2957 BEFFailure
== BEF_begin
) {
2958 // If the range is being built from an array parameter, emit a
2959 // a diagnostic that it is being treated as a pointer.
2960 if (DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(Range
)) {
2961 if (ParmVarDecl
*PVD
= dyn_cast
<ParmVarDecl
>(DRE
->getDecl())) {
2962 QualType ArrayTy
= PVD
->getOriginalType();
2963 QualType PointerTy
= PVD
->getType();
2964 if (PointerTy
->isPointerType() && ArrayTy
->isArrayType()) {
2965 Diag(Range
->getBeginLoc(), diag::err_range_on_array_parameter
)
2966 << RangeLoc
<< PVD
<< ArrayTy
<< PointerTy
;
2967 Diag(PVD
->getLocation(), diag::note_declared_at
);
2973 // If building the range failed, try dereferencing the range expression
2974 // unless a diagnostic was issued or the end function is problematic.
2975 StmtResult SR
= RebuildForRangeWithDereference(*this, S
, ForLoc
,
2976 CoawaitLoc
, InitStmt
,
2977 LoopVarDecl
, ColonLoc
,
2980 if (SR
.isInvalid() || SR
.isUsable())
2984 // Otherwise, emit diagnostics if we haven't already.
2985 if (RangeStatus
== FRS_NoViableFunction
) {
2986 Expr
*Range
= BEFFailure
? EndRangeRef
.get() : BeginRangeRef
.get();
2987 CandidateSet
.NoteCandidates(
2988 PartialDiagnosticAt(Range
->getBeginLoc(),
2989 PDiag(diag::err_for_range_invalid
)
2990 << RangeLoc
<< Range
->getType()
2992 *this, OCD_AllCandidates
, Range
);
2994 // Return an error if no fix was discovered.
2995 if (RangeStatus
!= FRS_Success
)
2999 assert(!BeginExpr
.isInvalid() && !EndExpr
.isInvalid() &&
3000 "invalid range expression in for loop");
3002 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
3003 // C++1z removes this restriction.
3004 QualType BeginType
= BeginVar
->getType(), EndType
= EndVar
->getType();
3005 if (!Context
.hasSameType(BeginType
, EndType
)) {
3006 Diag(RangeLoc
, getLangOpts().CPlusPlus17
3007 ? diag::warn_for_range_begin_end_types_differ
3008 : diag::ext_for_range_begin_end_types_differ
)
3009 << BeginType
<< EndType
;
3010 NoteForRangeBeginEndFunction(*this, BeginExpr
.get(), BEF_begin
);
3011 NoteForRangeBeginEndFunction(*this, EndExpr
.get(), BEF_end
);
3015 ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar
), ColonLoc
, ColonLoc
);
3017 ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar
), ColonLoc
, ColonLoc
);
3019 const QualType BeginRefNonRefType
= BeginType
.getNonReferenceType();
3020 ExprResult BeginRef
= BuildDeclRefExpr(BeginVar
, BeginRefNonRefType
,
3021 VK_LValue
, ColonLoc
);
3022 if (BeginRef
.isInvalid())
3025 ExprResult EndRef
= BuildDeclRefExpr(EndVar
, EndType
.getNonReferenceType(),
3026 VK_LValue
, ColonLoc
);
3027 if (EndRef
.isInvalid())
3030 // Build and check __begin != __end expression.
3031 NotEqExpr
= ActOnBinOp(S
, ColonLoc
, tok::exclaimequal
,
3032 BeginRef
.get(), EndRef
.get());
3033 if (!NotEqExpr
.isInvalid())
3034 NotEqExpr
= CheckBooleanCondition(ColonLoc
, NotEqExpr
.get());
3035 if (!NotEqExpr
.isInvalid())
3037 ActOnFinishFullExpr(NotEqExpr
.get(), /*DiscardedValue*/ false);
3038 if (NotEqExpr
.isInvalid()) {
3039 Diag(RangeLoc
, diag::note_for_range_invalid_iterator
)
3040 << RangeLoc
<< 0 << BeginRangeRef
.get()->getType();
3041 NoteForRangeBeginEndFunction(*this, BeginExpr
.get(), BEF_begin
);
3042 if (!Context
.hasSameType(BeginType
, EndType
))
3043 NoteForRangeBeginEndFunction(*this, EndExpr
.get(), BEF_end
);
3047 // Build and check ++__begin expression.
3048 BeginRef
= BuildDeclRefExpr(BeginVar
, BeginRefNonRefType
,
3049 VK_LValue
, ColonLoc
);
3050 if (BeginRef
.isInvalid())
3053 IncrExpr
= ActOnUnaryOp(S
, ColonLoc
, tok::plusplus
, BeginRef
.get());
3054 if (!IncrExpr
.isInvalid() && CoawaitLoc
.isValid())
3055 // FIXME: getCurScope() should not be used during template instantiation.
3056 // We should pick up the set of unqualified lookup results for operator
3057 // co_await during the initial parse.
3058 IncrExpr
= ActOnCoawaitExpr(S
, CoawaitLoc
, IncrExpr
.get());
3059 if (!IncrExpr
.isInvalid())
3060 IncrExpr
= ActOnFinishFullExpr(IncrExpr
.get(), /*DiscardedValue*/ false);
3061 if (IncrExpr
.isInvalid()) {
3062 Diag(RangeLoc
, diag::note_for_range_invalid_iterator
)
3063 << RangeLoc
<< 2 << BeginRangeRef
.get()->getType() ;
3064 NoteForRangeBeginEndFunction(*this, BeginExpr
.get(), BEF_begin
);
3068 // Build and check *__begin expression.
3069 BeginRef
= BuildDeclRefExpr(BeginVar
, BeginRefNonRefType
,
3070 VK_LValue
, ColonLoc
);
3071 if (BeginRef
.isInvalid())
3074 ExprResult DerefExpr
= ActOnUnaryOp(S
, ColonLoc
, tok::star
, BeginRef
.get());
3075 if (DerefExpr
.isInvalid()) {
3076 Diag(RangeLoc
, diag::note_for_range_invalid_iterator
)
3077 << RangeLoc
<< 1 << BeginRangeRef
.get()->getType();
3078 NoteForRangeBeginEndFunction(*this, BeginExpr
.get(), BEF_begin
);
3082 // Attach *__begin as initializer for VD. Don't touch it if we're just
3083 // trying to determine whether this would be a valid range.
3084 if (!LoopVar
->isInvalidDecl() && Kind
!= BFRK_Check
) {
3085 AddInitializerToDecl(LoopVar
, DerefExpr
.get(), /*DirectInit=*/false);
3086 if (LoopVar
->isInvalidDecl() ||
3087 (LoopVar
->getInit() && LoopVar
->getInit()->containsErrors()))
3088 NoteForRangeBeginEndFunction(*this, BeginExpr
.get(), BEF_begin
);
3092 // Don't bother to actually allocate the result if we're just trying to
3093 // determine whether it would be valid.
3094 if (Kind
== BFRK_Check
)
3095 return StmtResult();
3097 // In OpenMP loop region loop control variable must be private. Perform
3098 // analysis of first part (if any).
3099 if (getLangOpts().OpenMP
>= 50 && BeginDeclStmt
.isUsable())
3100 ActOnOpenMPLoopInitialization(ForLoc
, BeginDeclStmt
.get());
3102 return new (Context
) CXXForRangeStmt(
3103 InitStmt
, RangeDS
, cast_or_null
<DeclStmt
>(BeginDeclStmt
.get()),
3104 cast_or_null
<DeclStmt
>(EndDeclStmt
.get()), NotEqExpr
.get(),
3105 IncrExpr
.get(), LoopVarDS
, /*Body=*/nullptr, ForLoc
, CoawaitLoc
,
3106 ColonLoc
, RParenLoc
);
3109 /// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
3111 StmtResult
Sema::FinishObjCForCollectionStmt(Stmt
*S
, Stmt
*B
) {
3114 ObjCForCollectionStmt
* ForStmt
= cast
<ObjCForCollectionStmt
>(S
);
3116 ForStmt
->setBody(B
);
3120 // Warn when the loop variable is a const reference that creates a copy.
3121 // Suggest using the non-reference type for copies. If a copy can be prevented
3122 // suggest the const reference type that would do so.
3123 // For instance, given "for (const &Foo : Range)", suggest
3124 // "for (const Foo : Range)" to denote a copy is made for the loop. If
3125 // possible, also suggest "for (const &Bar : Range)" if this type prevents
3126 // the copy altogether.
3127 static void DiagnoseForRangeReferenceVariableCopies(Sema
&SemaRef
,
3129 QualType RangeInitType
) {
3130 const Expr
*InitExpr
= VD
->getInit();
3134 QualType VariableType
= VD
->getType();
3136 if (auto Cleanups
= dyn_cast
<ExprWithCleanups
>(InitExpr
))
3137 if (!Cleanups
->cleanupsHaveSideEffects())
3138 InitExpr
= Cleanups
->getSubExpr();
3140 const MaterializeTemporaryExpr
*MTE
=
3141 dyn_cast
<MaterializeTemporaryExpr
>(InitExpr
);
3147 const Expr
*E
= MTE
->getSubExpr()->IgnoreImpCasts();
3149 // Searching for either UnaryOperator for dereference of a pointer or
3150 // CXXOperatorCallExpr for handling iterators.
3151 while (!isa
<CXXOperatorCallExpr
>(E
) && !isa
<UnaryOperator
>(E
)) {
3152 if (const CXXConstructExpr
*CCE
= dyn_cast
<CXXConstructExpr
>(E
)) {
3154 } else if (const CXXMemberCallExpr
*Call
= dyn_cast
<CXXMemberCallExpr
>(E
)) {
3155 const MemberExpr
*ME
= cast
<MemberExpr
>(Call
->getCallee());
3158 const MaterializeTemporaryExpr
*MTE
= cast
<MaterializeTemporaryExpr
>(E
);
3159 E
= MTE
->getSubExpr();
3161 E
= E
->IgnoreImpCasts();
3164 QualType ReferenceReturnType
;
3165 if (isa
<UnaryOperator
>(E
)) {
3166 ReferenceReturnType
= SemaRef
.Context
.getLValueReferenceType(E
->getType());
3168 const CXXOperatorCallExpr
*Call
= cast
<CXXOperatorCallExpr
>(E
);
3169 const FunctionDecl
*FD
= Call
->getDirectCallee();
3170 QualType ReturnType
= FD
->getReturnType();
3171 if (ReturnType
->isReferenceType())
3172 ReferenceReturnType
= ReturnType
;
3175 if (!ReferenceReturnType
.isNull()) {
3176 // Loop variable creates a temporary. Suggest either to go with
3177 // non-reference loop variable to indicate a copy is made, or
3178 // the correct type to bind a const reference.
3179 SemaRef
.Diag(VD
->getLocation(),
3180 diag::warn_for_range_const_ref_binds_temp_built_from_ref
)
3181 << VD
<< VariableType
<< ReferenceReturnType
;
3182 QualType NonReferenceType
= VariableType
.getNonReferenceType();
3183 NonReferenceType
.removeLocalConst();
3184 QualType NewReferenceType
=
3185 SemaRef
.Context
.getLValueReferenceType(E
->getType().withConst());
3186 SemaRef
.Diag(VD
->getBeginLoc(), diag::note_use_type_or_non_reference
)
3187 << NonReferenceType
<< NewReferenceType
<< VD
->getSourceRange()
3188 << FixItHint::CreateRemoval(VD
->getTypeSpecEndLoc());
3189 } else if (!VariableType
->isRValueReferenceType()) {
3190 // The range always returns a copy, so a temporary is always created.
3191 // Suggest removing the reference from the loop variable.
3192 // If the type is a rvalue reference do not warn since that changes the
3193 // semantic of the code.
3194 SemaRef
.Diag(VD
->getLocation(), diag::warn_for_range_ref_binds_ret_temp
)
3195 << VD
<< RangeInitType
;
3196 QualType NonReferenceType
= VariableType
.getNonReferenceType();
3197 NonReferenceType
.removeLocalConst();
3198 SemaRef
.Diag(VD
->getBeginLoc(), diag::note_use_non_reference_type
)
3199 << NonReferenceType
<< VD
->getSourceRange()
3200 << FixItHint::CreateRemoval(VD
->getTypeSpecEndLoc());
3204 /// Determines whether the @p VariableType's declaration is a record with the
3205 /// clang::trivial_abi attribute.
3206 static bool hasTrivialABIAttr(QualType VariableType
) {
3207 if (CXXRecordDecl
*RD
= VariableType
->getAsCXXRecordDecl())
3208 return RD
->hasAttr
<TrivialABIAttr
>();
3213 // Warns when the loop variable can be changed to a reference type to
3214 // prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
3215 // "for (const Foo &x : Range)" if this form does not make a copy.
3216 static void DiagnoseForRangeConstVariableCopies(Sema
&SemaRef
,
3217 const VarDecl
*VD
) {
3218 const Expr
*InitExpr
= VD
->getInit();
3222 QualType VariableType
= VD
->getType();
3224 if (const CXXConstructExpr
*CE
= dyn_cast
<CXXConstructExpr
>(InitExpr
)) {
3225 if (!CE
->getConstructor()->isCopyConstructor())
3227 } else if (const CastExpr
*CE
= dyn_cast
<CastExpr
>(InitExpr
)) {
3228 if (CE
->getCastKind() != CK_LValueToRValue
)
3234 // Small trivially copyable types are cheap to copy. Do not emit the
3235 // diagnostic for these instances. 64 bytes is a common size of a cache line.
3236 // (The function `getTypeSize` returns the size in bits.)
3237 ASTContext
&Ctx
= SemaRef
.Context
;
3238 if (Ctx
.getTypeSize(VariableType
) <= 64 * 8 &&
3239 (VariableType
.isTriviallyCopyConstructibleType(Ctx
) ||
3240 hasTrivialABIAttr(VariableType
)))
3243 // Suggest changing from a const variable to a const reference variable
3244 // if doing so will prevent a copy.
3245 SemaRef
.Diag(VD
->getLocation(), diag::warn_for_range_copy
)
3246 << VD
<< VariableType
;
3247 SemaRef
.Diag(VD
->getBeginLoc(), diag::note_use_reference_type
)
3248 << SemaRef
.Context
.getLValueReferenceType(VariableType
)
3249 << VD
->getSourceRange()
3250 << FixItHint::CreateInsertion(VD
->getLocation(), "&");
3253 /// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
3254 /// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
3255 /// using "const foo x" to show that a copy is made
3256 /// 2) for (const bar &x : foos) where bar is a temporary initialized by bar.
3257 /// Suggest either "const bar x" to keep the copying or "const foo& x" to
3258 /// prevent the copy.
3259 /// 3) for (const foo x : foos) where x is constructed from a reference foo.
3260 /// Suggest "const foo &x" to prevent the copy.
3261 static void DiagnoseForRangeVariableCopies(Sema
&SemaRef
,
3262 const CXXForRangeStmt
*ForStmt
) {
3263 if (SemaRef
.inTemplateInstantiation())
3266 if (SemaRef
.Diags
.isIgnored(
3267 diag::warn_for_range_const_ref_binds_temp_built_from_ref
,
3268 ForStmt
->getBeginLoc()) &&
3269 SemaRef
.Diags
.isIgnored(diag::warn_for_range_ref_binds_ret_temp
,
3270 ForStmt
->getBeginLoc()) &&
3271 SemaRef
.Diags
.isIgnored(diag::warn_for_range_copy
,
3272 ForStmt
->getBeginLoc())) {
3276 const VarDecl
*VD
= ForStmt
->getLoopVariable();
3280 QualType VariableType
= VD
->getType();
3282 if (VariableType
->isIncompleteType())
3285 const Expr
*InitExpr
= VD
->getInit();
3289 if (InitExpr
->getExprLoc().isMacroID())
3292 if (VariableType
->isReferenceType()) {
3293 DiagnoseForRangeReferenceVariableCopies(SemaRef
, VD
,
3294 ForStmt
->getRangeInit()->getType());
3295 } else if (VariableType
.isConstQualified()) {
3296 DiagnoseForRangeConstVariableCopies(SemaRef
, VD
);
3300 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
3301 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
3302 /// body cannot be performed until after the type of the range variable is
3304 StmtResult
Sema::FinishCXXForRangeStmt(Stmt
*S
, Stmt
*B
) {
3308 if (isa
<ObjCForCollectionStmt
>(S
))
3309 return FinishObjCForCollectionStmt(S
, B
);
3311 CXXForRangeStmt
*ForStmt
= cast
<CXXForRangeStmt
>(S
);
3312 ForStmt
->setBody(B
);
3314 DiagnoseEmptyStmtBody(ForStmt
->getRParenLoc(), B
,
3315 diag::warn_empty_range_based_for_body
);
3317 DiagnoseForRangeVariableCopies(*this, ForStmt
);
3322 StmtResult
Sema::ActOnGotoStmt(SourceLocation GotoLoc
,
3323 SourceLocation LabelLoc
,
3324 LabelDecl
*TheDecl
) {
3325 setFunctionHasBranchIntoScope();
3327 // If this goto is in a compute construct scope, we need to make sure we check
3329 if (getCurScope()->isInOpenACCComputeConstructScope())
3330 setFunctionHasBranchProtectedScope();
3332 TheDecl
->markUsed(Context
);
3333 return new (Context
) GotoStmt(TheDecl
, GotoLoc
, LabelLoc
);
3337 Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc
, SourceLocation StarLoc
,
3339 // Convert operand to void*
3340 if (!E
->isTypeDependent()) {
3341 QualType ETy
= E
->getType();
3342 QualType DestTy
= Context
.getPointerType(Context
.VoidTy
.withConst());
3343 ExprResult ExprRes
= E
;
3344 AssignConvertType ConvTy
=
3345 CheckSingleAssignmentConstraints(DestTy
, ExprRes
);
3346 if (ExprRes
.isInvalid())
3349 if (DiagnoseAssignmentResult(ConvTy
, StarLoc
, DestTy
, ETy
, E
, AA_Passing
))
3353 ExprResult ExprRes
= ActOnFinishFullExpr(E
, /*DiscardedValue*/ false);
3354 if (ExprRes
.isInvalid())
3358 setFunctionHasIndirectGoto();
3360 // If this goto is in a compute construct scope, we need to make sure we
3361 // check gotos in/out.
3362 if (getCurScope()->isInOpenACCComputeConstructScope())
3363 setFunctionHasBranchProtectedScope();
3365 return new (Context
) IndirectGotoStmt(GotoLoc
, StarLoc
, E
);
3368 static void CheckJumpOutOfSEHFinally(Sema
&S
, SourceLocation Loc
,
3369 const Scope
&DestScope
) {
3370 if (!S
.CurrentSEHFinally
.empty() &&
3371 DestScope
.Contains(*S
.CurrentSEHFinally
.back())) {
3372 S
.Diag(Loc
, diag::warn_jump_out_of_seh_finally
);
3377 Sema::ActOnContinueStmt(SourceLocation ContinueLoc
, Scope
*CurScope
) {
3378 Scope
*S
= CurScope
->getContinueParent();
3380 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
3381 return StmtError(Diag(ContinueLoc
, diag::err_continue_not_in_loop
));
3383 if (S
->isConditionVarScope()) {
3384 // We cannot 'continue;' from within a statement expression in the
3385 // initializer of a condition variable because we would jump past the
3386 // initialization of that variable.
3387 return StmtError(Diag(ContinueLoc
, diag::err_continue_from_cond_var_init
));
3390 // A 'continue' that would normally have execution continue on a block outside
3391 // of a compute construct counts as 'branching out of' the compute construct,
3392 // so diagnose here.
3393 if (S
->isOpenACCComputeConstructScope())
3395 Diag(ContinueLoc
, diag::err_acc_branch_in_out_compute_construct
)
3396 << /*branch*/ 0 << /*out of */ 0);
3398 CheckJumpOutOfSEHFinally(*this, ContinueLoc
, *S
);
3400 return new (Context
) ContinueStmt(ContinueLoc
);
3404 Sema::ActOnBreakStmt(SourceLocation BreakLoc
, Scope
*CurScope
) {
3405 Scope
*S
= CurScope
->getBreakParent();
3407 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
3408 return StmtError(Diag(BreakLoc
, diag::err_break_not_in_loop_or_switch
));
3410 if (S
->isOpenMPLoopScope())
3411 return StmtError(Diag(BreakLoc
, diag::err_omp_loop_cannot_use_stmt
)
3414 // OpenACC doesn't allow 'break'ing from a compute construct, so diagnose if
3415 // we are trying to do so. This can come in 2 flavors: 1-the break'able thing
3416 // (besides the compute construct) 'contains' the compute construct, at which
3417 // point the 'break' scope will be the compute construct. Else it could be a
3418 // loop of some sort that has a direct parent of the compute construct.
3419 // However, a 'break' in a 'switch' marked as a compute construct doesn't
3420 // count as 'branch out of' the compute construct.
3421 if (S
->isOpenACCComputeConstructScope() ||
3422 (S
->isLoopScope() && S
->getParent() &&
3423 S
->getParent()->isOpenACCComputeConstructScope()))
3425 Diag(BreakLoc
, diag::err_acc_branch_in_out_compute_construct
)
3426 << /*branch*/ 0 << /*out of */ 0);
3428 CheckJumpOutOfSEHFinally(*this, BreakLoc
, *S
);
3430 return new (Context
) BreakStmt(BreakLoc
);
3433 /// Determine whether the given expression might be move-eligible or
3434 /// copy-elidable in either a (co_)return statement or throw expression,
3435 /// without considering function return type, if applicable.
3437 /// \param E The expression being returned from the function or block,
3438 /// being thrown, or being co_returned from a coroutine. This expression
3439 /// might be modified by the implementation.
3441 /// \param Mode Overrides detection of current language mode
3442 /// and uses the rules for C++23.
3444 /// \returns An aggregate which contains the Candidate and isMoveEligible
3445 /// and isCopyElidable methods. If Candidate is non-null, it means
3446 /// isMoveEligible() would be true under the most permissive language standard.
3447 Sema::NamedReturnInfo
Sema::getNamedReturnInfo(Expr
*&E
,
3448 SimplerImplicitMoveMode Mode
) {
3450 return NamedReturnInfo();
3451 // - in a return statement in a function [where] ...
3452 // ... the expression is the name of a non-volatile automatic object ...
3453 const auto *DR
= dyn_cast
<DeclRefExpr
>(E
->IgnoreParens());
3454 if (!DR
|| DR
->refersToEnclosingVariableOrCapture())
3455 return NamedReturnInfo();
3456 const auto *VD
= dyn_cast
<VarDecl
>(DR
->getDecl());
3458 return NamedReturnInfo();
3459 if (VD
->getInit() && VD
->getInit()->containsErrors())
3460 return NamedReturnInfo();
3461 NamedReturnInfo Res
= getNamedReturnInfo(VD
);
3462 if (Res
.Candidate
&& !E
->isXValue() &&
3463 (Mode
== SimplerImplicitMoveMode::ForceOn
||
3464 (Mode
!= SimplerImplicitMoveMode::ForceOff
&&
3465 getLangOpts().CPlusPlus23
))) {
3466 E
= ImplicitCastExpr::Create(Context
, VD
->getType().getNonReferenceType(),
3467 CK_NoOp
, E
, nullptr, VK_XValue
,
3468 FPOptionsOverride());
3473 /// Determine whether the given NRVO candidate variable is move-eligible or
3474 /// copy-elidable, without considering function return type.
3476 /// \param VD The NRVO candidate variable.
3478 /// \returns An aggregate which contains the Candidate and isMoveEligible
3479 /// and isCopyElidable methods. If Candidate is non-null, it means
3480 /// isMoveEligible() would be true under the most permissive language standard.
3481 Sema::NamedReturnInfo
Sema::getNamedReturnInfo(const VarDecl
*VD
) {
3482 NamedReturnInfo Info
{VD
, NamedReturnInfo::MoveEligibleAndCopyElidable
};
3484 // C++20 [class.copy.elision]p3:
3485 // - in a return statement in a function with ...
3486 // (other than a function ... parameter)
3487 if (VD
->getKind() == Decl::ParmVar
)
3488 Info
.S
= NamedReturnInfo::MoveEligible
;
3489 else if (VD
->getKind() != Decl::Var
)
3490 return NamedReturnInfo();
3492 // (other than ... a catch-clause parameter)
3493 if (VD
->isExceptionVariable())
3494 Info
.S
= NamedReturnInfo::MoveEligible
;
3497 if (!VD
->hasLocalStorage())
3498 return NamedReturnInfo();
3500 // We don't want to implicitly move out of a __block variable during a return
3501 // because we cannot assume the variable will no longer be used.
3502 if (VD
->hasAttr
<BlocksAttr
>())
3503 return NamedReturnInfo();
3505 QualType VDType
= VD
->getType();
3506 if (VDType
->isObjectType()) {
3507 // C++17 [class.copy.elision]p3:
3508 // ...non-volatile automatic object...
3509 if (VDType
.isVolatileQualified())
3510 return NamedReturnInfo();
3511 } else if (VDType
->isRValueReferenceType()) {
3512 // C++20 [class.copy.elision]p3:
3513 // ...either a non-volatile object or an rvalue reference to a non-volatile
3515 QualType VDReferencedType
= VDType
.getNonReferenceType();
3516 if (VDReferencedType
.isVolatileQualified() ||
3517 !VDReferencedType
->isObjectType())
3518 return NamedReturnInfo();
3519 Info
.S
= NamedReturnInfo::MoveEligible
;
3521 return NamedReturnInfo();
3524 // Variables with higher required alignment than their type's ABI
3525 // alignment cannot use NRVO.
3526 if (!VD
->hasDependentAlignment() &&
3527 Context
.getDeclAlign(VD
) > Context
.getTypeAlignInChars(VDType
))
3528 Info
.S
= NamedReturnInfo::MoveEligible
;
3533 /// Updates given NamedReturnInfo's move-eligible and
3534 /// copy-elidable statuses, considering the function
3535 /// return type criteria as applicable to return statements.
3537 /// \param Info The NamedReturnInfo object to update.
3539 /// \param ReturnType This is the return type of the function.
3540 /// \returns The copy elision candidate, in case the initial return expression
3541 /// was copy elidable, or nullptr otherwise.
3542 const VarDecl
*Sema::getCopyElisionCandidate(NamedReturnInfo
&Info
,
3543 QualType ReturnType
) {
3544 if (!Info
.Candidate
)
3547 auto invalidNRVO
= [&] {
3548 Info
= NamedReturnInfo();
3552 // If we got a non-deduced auto ReturnType, we are in a dependent context and
3553 // there is no point in allowing copy elision since we won't have it deduced
3554 // by the point the VardDecl is instantiated, which is the last chance we have
3555 // of deciding if the candidate is really copy elidable.
3556 if ((ReturnType
->getTypeClass() == Type::TypeClass::Auto
&&
3557 ReturnType
->isCanonicalUnqualified()) ||
3558 ReturnType
->isSpecificBuiltinType(BuiltinType::Dependent
))
3559 return invalidNRVO();
3561 if (!ReturnType
->isDependentType()) {
3562 // - in a return statement in a function with ...
3563 // ... a class return type ...
3564 if (!ReturnType
->isRecordType())
3565 return invalidNRVO();
3567 QualType VDType
= Info
.Candidate
->getType();
3568 // ... the same cv-unqualified type as the function return type ...
3569 // When considering moving this expression out, allow dissimilar types.
3570 if (!VDType
->isDependentType() &&
3571 !Context
.hasSameUnqualifiedType(ReturnType
, VDType
))
3572 Info
.S
= NamedReturnInfo::MoveEligible
;
3574 return Info
.isCopyElidable() ? Info
.Candidate
: nullptr;
3577 /// Verify that the initialization sequence that was picked for the
3578 /// first overload resolution is permissible under C++98.
3580 /// Reject (possibly converting) constructors not taking an rvalue reference,
3581 /// or user conversion operators which are not ref-qualified.
3583 VerifyInitializationSequenceCXX98(const Sema
&S
,
3584 const InitializationSequence
&Seq
) {
3585 const auto *Step
= llvm::find_if(Seq
.steps(), [](const auto &Step
) {
3586 return Step
.Kind
== InitializationSequence::SK_ConstructorInitialization
||
3587 Step
.Kind
== InitializationSequence::SK_UserConversion
;
3589 if (Step
!= Seq
.step_end()) {
3590 const auto *FD
= Step
->Function
.Function
;
3591 if (isa
<CXXConstructorDecl
>(FD
)
3592 ? !FD
->getParamDecl(0)->getType()->isRValueReferenceType()
3593 : cast
<CXXMethodDecl
>(FD
)->getRefQualifier() == RQ_None
)
3599 /// Perform the initialization of a potentially-movable value, which
3600 /// is the result of return value.
3602 /// This routine implements C++20 [class.copy.elision]p3, which attempts to
3603 /// treat returned lvalues as rvalues in certain cases (to prefer move
3604 /// construction), then falls back to treating them as lvalues if that failed.
3605 ExprResult
Sema::PerformMoveOrCopyInitialization(
3606 const InitializedEntity
&Entity
, const NamedReturnInfo
&NRInfo
, Expr
*Value
,
3607 bool SupressSimplerImplicitMoves
) {
3608 if (getLangOpts().CPlusPlus
&&
3609 (!getLangOpts().CPlusPlus23
|| SupressSimplerImplicitMoves
) &&
3610 NRInfo
.isMoveEligible()) {
3611 ImplicitCastExpr
AsRvalue(ImplicitCastExpr::OnStack
, Value
->getType(),
3612 CK_NoOp
, Value
, VK_XValue
, FPOptionsOverride());
3613 Expr
*InitExpr
= &AsRvalue
;
3614 auto Kind
= InitializationKind::CreateCopy(Value
->getBeginLoc(),
3615 Value
->getBeginLoc());
3616 InitializationSequence
Seq(*this, Entity
, Kind
, InitExpr
);
3617 auto Res
= Seq
.getFailedOverloadResult();
3618 if ((Res
== OR_Success
|| Res
== OR_Deleted
) &&
3619 (getLangOpts().CPlusPlus11
||
3620 VerifyInitializationSequenceCXX98(*this, Seq
))) {
3621 // Promote "AsRvalue" to the heap, since we now need this
3622 // expression node to persist.
3624 ImplicitCastExpr::Create(Context
, Value
->getType(), CK_NoOp
, Value
,
3625 nullptr, VK_XValue
, FPOptionsOverride());
3626 // Complete type-checking the initialization of the return type
3627 // using the constructor we found.
3628 return Seq
.Perform(*this, Entity
, Kind
, Value
);
3631 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
3632 // above, or overload resolution failed. Either way, we need to try
3633 // (again) now with the return value expression as written.
3634 return PerformCopyInitialization(Entity
, SourceLocation(), Value
);
3637 /// Determine whether the declared return type of the specified function
3638 /// contains 'auto'.
3639 static bool hasDeducedReturnType(FunctionDecl
*FD
) {
3640 const FunctionProtoType
*FPT
=
3641 FD
->getTypeSourceInfo()->getType()->castAs
<FunctionProtoType
>();
3642 return FPT
->getReturnType()->isUndeducedType();
3645 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
3646 /// for capturing scopes.
3648 StmtResult
Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc
,
3650 NamedReturnInfo
&NRInfo
,
3651 bool SupressSimplerImplicitMoves
) {
3652 // If this is the first return we've seen, infer the return type.
3653 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
3654 CapturingScopeInfo
*CurCap
= cast
<CapturingScopeInfo
>(getCurFunction());
3655 QualType FnRetType
= CurCap
->ReturnType
;
3656 LambdaScopeInfo
*CurLambda
= dyn_cast
<LambdaScopeInfo
>(CurCap
);
3657 if (CurLambda
&& CurLambda
->CallOperator
->getType().isNull())
3659 bool HasDeducedReturnType
=
3660 CurLambda
&& hasDeducedReturnType(CurLambda
->CallOperator
);
3662 if (ExprEvalContexts
.back().isDiscardedStatementContext() &&
3663 (HasDeducedReturnType
|| CurCap
->HasImplicitReturnType
)) {
3666 ActOnFinishFullExpr(RetValExp
, ReturnLoc
, /*DiscardedValue*/ false);
3669 RetValExp
= ER
.get();
3671 return ReturnStmt::Create(Context
, ReturnLoc
, RetValExp
,
3672 /* NRVOCandidate=*/nullptr);
3675 if (HasDeducedReturnType
) {
3676 FunctionDecl
*FD
= CurLambda
->CallOperator
;
3677 // If we've already decided this lambda is invalid, e.g. because
3678 // we saw a `return` whose expression had an error, don't keep
3679 // trying to deduce its return type.
3680 if (FD
->isInvalidDecl())
3682 // In C++1y, the return type may involve 'auto'.
3683 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
3684 if (CurCap
->ReturnType
.isNull())
3685 CurCap
->ReturnType
= FD
->getReturnType();
3687 AutoType
*AT
= CurCap
->ReturnType
->getContainedAutoType();
3688 assert(AT
&& "lost auto type from lambda return type");
3689 if (DeduceFunctionTypeFromReturnExpr(FD
, ReturnLoc
, RetValExp
, AT
)) {
3690 FD
->setInvalidDecl();
3691 // FIXME: preserve the ill-formed return expression.
3694 CurCap
->ReturnType
= FnRetType
= FD
->getReturnType();
3695 } else if (CurCap
->HasImplicitReturnType
) {
3696 // For blocks/lambdas with implicit return types, we check each return
3697 // statement individually, and deduce the common return type when the block
3698 // or lambda is completed.
3699 // FIXME: Fold this into the 'auto' codepath above.
3700 if (RetValExp
&& !isa
<InitListExpr
>(RetValExp
)) {
3701 ExprResult Result
= DefaultFunctionArrayLvalueConversion(RetValExp
);
3702 if (Result
.isInvalid())
3704 RetValExp
= Result
.get();
3706 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
3707 // when deducing a return type for a lambda-expression (or by extension
3708 // for a block). These rules differ from the stated C++11 rules only in
3709 // that they remove top-level cv-qualifiers.
3710 if (!CurContext
->isDependentContext())
3711 FnRetType
= RetValExp
->getType().getUnqualifiedType();
3713 FnRetType
= CurCap
->ReturnType
= Context
.DependentTy
;
3716 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
3717 // initializer list, because it is not an expression (even
3718 // though we represent it as one). We still deduce 'void'.
3719 Diag(ReturnLoc
, diag::err_lambda_return_init_list
)
3720 << RetValExp
->getSourceRange();
3723 FnRetType
= Context
.VoidTy
;
3726 // Although we'll properly infer the type of the block once it's completed,
3727 // make sure we provide a return type now for better error recovery.
3728 if (CurCap
->ReturnType
.isNull())
3729 CurCap
->ReturnType
= FnRetType
;
3731 const VarDecl
*NRVOCandidate
= getCopyElisionCandidate(NRInfo
, FnRetType
);
3733 if (auto *CurBlock
= dyn_cast
<BlockScopeInfo
>(CurCap
)) {
3734 if (CurBlock
->FunctionType
->castAs
<FunctionType
>()->getNoReturnAttr()) {
3735 Diag(ReturnLoc
, diag::err_noreturn_block_has_return_expr
);
3738 } else if (auto *CurRegion
= dyn_cast
<CapturedRegionScopeInfo
>(CurCap
)) {
3739 Diag(ReturnLoc
, diag::err_return_in_captured_stmt
) << CurRegion
->getRegionName();
3742 assert(CurLambda
&& "unknown kind of captured scope");
3743 if (CurLambda
->CallOperator
->getType()
3744 ->castAs
<FunctionType
>()
3745 ->getNoReturnAttr()) {
3746 Diag(ReturnLoc
, diag::err_noreturn_lambda_has_return_expr
);
3751 // Otherwise, verify that this result type matches the previous one. We are
3752 // pickier with blocks than for normal functions because we don't have GCC
3753 // compatibility to worry about here.
3754 if (FnRetType
->isDependentType()) {
3755 // Delay processing for now. TODO: there are lots of dependent
3756 // types we can conclusively prove aren't void.
3757 } else if (FnRetType
->isVoidType()) {
3758 if (RetValExp
&& !isa
<InitListExpr
>(RetValExp
) &&
3759 !(getLangOpts().CPlusPlus
&&
3760 (RetValExp
->isTypeDependent() ||
3761 RetValExp
->getType()->isVoidType()))) {
3762 if (!getLangOpts().CPlusPlus
&&
3763 RetValExp
->getType()->isVoidType())
3764 Diag(ReturnLoc
, diag::ext_return_has_void_expr
) << "literal" << 2;
3766 Diag(ReturnLoc
, diag::err_return_block_has_expr
);
3767 RetValExp
= nullptr;
3770 } else if (!RetValExp
) {
3771 return StmtError(Diag(ReturnLoc
, diag::err_block_return_missing_expr
));
3772 } else if (!RetValExp
->isTypeDependent()) {
3773 // we have a non-void block with an expression, continue checking
3775 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3776 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3779 // In C++ the return statement is handled via a copy initialization.
3780 // the C version of which boils down to CheckSingleAssignmentConstraints.
3781 InitializedEntity Entity
=
3782 InitializedEntity::InitializeResult(ReturnLoc
, FnRetType
);
3783 ExprResult Res
= PerformMoveOrCopyInitialization(
3784 Entity
, NRInfo
, RetValExp
, SupressSimplerImplicitMoves
);
3785 if (Res
.isInvalid()) {
3786 // FIXME: Cleanup temporaries here, anyway?
3789 RetValExp
= Res
.get();
3790 CheckReturnValExpr(RetValExp
, FnRetType
, ReturnLoc
);
3795 ActOnFinishFullExpr(RetValExp
, ReturnLoc
, /*DiscardedValue*/ false);
3798 RetValExp
= ER
.get();
3801 ReturnStmt::Create(Context
, ReturnLoc
, RetValExp
, NRVOCandidate
);
3803 // If we need to check for the named return value optimization,
3804 // or if we need to infer the return type,
3805 // save the return statement in our scope for later processing.
3806 if (CurCap
->HasImplicitReturnType
|| NRVOCandidate
)
3807 FunctionScopes
.back()->Returns
.push_back(Result
);
3809 if (FunctionScopes
.back()->FirstReturnLoc
.isInvalid())
3810 FunctionScopes
.back()->FirstReturnLoc
= ReturnLoc
;
3812 if (auto *CurBlock
= dyn_cast
<BlockScopeInfo
>(CurCap
);
3813 CurBlock
&& CurCap
->HasImplicitReturnType
&& RetValExp
&&
3814 RetValExp
->containsErrors())
3815 CurBlock
->TheDecl
->setInvalidDecl();
3821 /// Marks all typedefs in all local classes in a type referenced.
3823 /// In a function like
3825 /// struct S { typedef int a; };
3829 /// the local type escapes and could be referenced in some TUs but not in
3830 /// others. Pretend that all local typedefs are always referenced, to not warn
3831 /// on this. This isn't necessary if f has internal linkage, or the typedef
3833 class LocalTypedefNameReferencer
3834 : public RecursiveASTVisitor
<LocalTypedefNameReferencer
> {
3836 LocalTypedefNameReferencer(Sema
&S
) : S(S
) {}
3837 bool VisitRecordType(const RecordType
*RT
);
3841 bool LocalTypedefNameReferencer::VisitRecordType(const RecordType
*RT
) {
3842 auto *R
= dyn_cast
<CXXRecordDecl
>(RT
->getDecl());
3843 if (!R
|| !R
->isLocalClass() || !R
->isLocalClass()->isExternallyVisible() ||
3844 R
->isDependentType())
3846 for (auto *TmpD
: R
->decls())
3847 if (auto *T
= dyn_cast
<TypedefNameDecl
>(TmpD
))
3848 if (T
->getAccess() != AS_private
|| R
->hasFriends())
3849 S
.MarkAnyDeclReferenced(T
->getLocation(), T
, /*OdrUse=*/false);
3854 TypeLoc
Sema::getReturnTypeLoc(FunctionDecl
*FD
) const {
3855 return FD
->getTypeSourceInfo()
3857 .getAsAdjusted
<FunctionProtoTypeLoc
>()
3861 /// Deduce the return type for a function from a returned expression, per
3862 /// C++1y [dcl.spec.auto]p6.
3863 bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl
*FD
,
3864 SourceLocation ReturnLoc
,
3865 Expr
*RetExpr
, const AutoType
*AT
) {
3866 // If this is the conversion function for a lambda, we choose to deduce its
3867 // type from the corresponding call operator, not from the synthesized return
3868 // statement within it. See Sema::DeduceReturnType.
3869 if (isLambdaConversionOperator(FD
))
3872 if (RetExpr
&& isa
<InitListExpr
>(RetExpr
)) {
3873 // If the deduction is for a return statement and the initializer is
3874 // a braced-init-list, the program is ill-formed.
3875 Diag(RetExpr
->getExprLoc(),
3876 getCurLambda() ? diag::err_lambda_return_init_list
3877 : diag::err_auto_fn_return_init_list
)
3878 << RetExpr
->getSourceRange();
3882 if (FD
->isDependentContext()) {
3883 // C++1y [dcl.spec.auto]p12:
3884 // Return type deduction [...] occurs when the definition is
3885 // instantiated even if the function body contains a return
3886 // statement with a non-type-dependent operand.
3887 assert(AT
->isDeduced() && "should have deduced to dependent type");
3891 TypeLoc OrigResultType
= getReturnTypeLoc(FD
);
3892 // In the case of a return with no operand, the initializer is considered
3894 CXXScalarValueInitExpr
VoidVal(Context
.VoidTy
, nullptr, SourceLocation());
3896 // For a function with a deduced result type to return with omitted
3897 // expression, the result type as written must be 'auto' or
3898 // 'decltype(auto)', possibly cv-qualified or constrained, but not
3900 if (!OrigResultType
.getType()->getAs
<AutoType
>()) {
3901 Diag(ReturnLoc
, diag::err_auto_fn_return_void_but_not_auto
)
3902 << OrigResultType
.getType();
3908 QualType Deduced
= AT
->getDeducedType();
3910 // Otherwise, [...] deduce a value for U using the rules of template
3911 // argument deduction.
3912 auto RetExprLoc
= RetExpr
->getExprLoc();
3913 TemplateDeductionInfo
Info(RetExprLoc
);
3914 SourceLocation TemplateSpecLoc
;
3915 if (RetExpr
->getType() == Context
.OverloadTy
) {
3916 auto FindResult
= OverloadExpr::find(RetExpr
);
3917 if (FindResult
.Expression
)
3918 TemplateSpecLoc
= FindResult
.Expression
->getNameLoc();
3920 TemplateSpecCandidateSet
FailedTSC(TemplateSpecLoc
);
3921 TemplateDeductionResult Res
= DeduceAutoType(
3922 OrigResultType
, RetExpr
, Deduced
, Info
, /*DependentDeduction=*/false,
3923 /*IgnoreConstraints=*/false, &FailedTSC
);
3924 if (Res
!= TemplateDeductionResult::Success
&& FD
->isInvalidDecl())
3927 case TemplateDeductionResult::Success
:
3929 case TemplateDeductionResult::AlreadyDiagnosed
:
3931 case TemplateDeductionResult::Inconsistent
: {
3932 // If a function with a declared return type that contains a placeholder
3933 // type has multiple return statements, the return type is deduced for
3934 // each return statement. [...] if the type deduced is not the same in
3935 // each deduction, the program is ill-formed.
3936 const LambdaScopeInfo
*LambdaSI
= getCurLambda();
3937 if (LambdaSI
&& LambdaSI
->HasImplicitReturnType
)
3938 Diag(ReturnLoc
, diag::err_typecheck_missing_return_type_incompatible
)
3939 << Info
.SecondArg
<< Info
.FirstArg
<< true /*IsLambda*/;
3941 Diag(ReturnLoc
, diag::err_auto_fn_different_deductions
)
3942 << (AT
->isDecltypeAuto() ? 1 : 0) << Info
.SecondArg
3947 Diag(RetExpr
->getExprLoc(), diag::err_auto_fn_deduction_failure
)
3948 << OrigResultType
.getType() << RetExpr
->getType();
3949 FailedTSC
.NoteCandidates(*this, RetExprLoc
);
3954 // If a local type is part of the returned type, mark its fields as
3956 LocalTypedefNameReferencer(*this).TraverseType(RetExpr
->getType());
3958 // CUDA: Kernel function must have 'void' return type.
3959 if (getLangOpts().CUDA
&& FD
->hasAttr
<CUDAGlobalAttr
>() &&
3960 !Deduced
->isVoidType()) {
3961 Diag(FD
->getLocation(), diag::err_kern_type_not_void_return
)
3962 << FD
->getType() << FD
->getSourceRange();
3966 if (!FD
->isInvalidDecl() && AT
->getDeducedType() != Deduced
)
3967 // Update all declarations of the function to have the deduced return type.
3968 Context
.adjustDeducedFunctionResultType(FD
, Deduced
);
3974 Sema::ActOnReturnStmt(SourceLocation ReturnLoc
, Expr
*RetValExp
,
3976 // Correct typos, in case the containing function returns 'auto' and
3977 // RetValExp should determine the deduced type.
3978 ExprResult RetVal
= CorrectDelayedTyposInExpr(
3979 RetValExp
, nullptr, /*RecoverUncorrectedTypos=*/true);
3980 if (RetVal
.isInvalid())
3983 if (getCurScope()->isInOpenACCComputeConstructScope())
3985 Diag(ReturnLoc
, diag::err_acc_branch_in_out_compute_construct
)
3986 << /*return*/ 1 << /*out of */ 0);
3989 BuildReturnStmt(ReturnLoc
, RetVal
.get(), /*AllowRecovery=*/true);
3990 if (R
.isInvalid() || ExprEvalContexts
.back().isDiscardedStatementContext())
3994 const_cast<VarDecl
*>(cast
<ReturnStmt
>(R
.get())->getNRVOCandidate());
3996 CurScope
->updateNRVOCandidate(VD
);
3998 CheckJumpOutOfSEHFinally(*this, ReturnLoc
, *CurScope
->getFnParent());
4003 static bool CheckSimplerImplicitMovesMSVCWorkaround(const Sema
&S
,
4005 if (!E
|| !S
.getLangOpts().CPlusPlus23
|| !S
.getLangOpts().MSVCCompat
)
4007 const Decl
*D
= E
->getReferencedDeclOfCallee();
4008 if (!D
|| !S
.SourceMgr
.isInSystemHeader(D
->getLocation()))
4010 for (const DeclContext
*DC
= D
->getDeclContext(); DC
; DC
= DC
->getParent()) {
4011 if (DC
->isStdNamespace())
4017 StmtResult
Sema::BuildReturnStmt(SourceLocation ReturnLoc
, Expr
*RetValExp
,
4018 bool AllowRecovery
) {
4019 // Check for unexpanded parameter packs.
4020 if (RetValExp
&& DiagnoseUnexpandedParameterPack(RetValExp
))
4023 // HACK: We suppress simpler implicit move here in msvc compatibility mode
4024 // just as a temporary work around, as the MSVC STL has issues with
4026 bool SupressSimplerImplicitMoves
=
4027 CheckSimplerImplicitMovesMSVCWorkaround(*this, RetValExp
);
4028 NamedReturnInfo NRInfo
= getNamedReturnInfo(
4029 RetValExp
, SupressSimplerImplicitMoves
? SimplerImplicitMoveMode::ForceOff
4030 : SimplerImplicitMoveMode::Normal
);
4032 if (isa
<CapturingScopeInfo
>(getCurFunction()))
4033 return ActOnCapScopeReturnStmt(ReturnLoc
, RetValExp
, NRInfo
,
4034 SupressSimplerImplicitMoves
);
4037 QualType RelatedRetType
;
4038 const AttrVec
*Attrs
= nullptr;
4039 bool isObjCMethod
= false;
4041 if (const FunctionDecl
*FD
= getCurFunctionDecl()) {
4042 FnRetType
= FD
->getReturnType();
4044 Attrs
= &FD
->getAttrs();
4045 if (FD
->isNoReturn())
4046 Diag(ReturnLoc
, diag::warn_noreturn_function_has_return_expr
) << FD
;
4047 if (FD
->isMain() && RetValExp
)
4048 if (isa
<CXXBoolLiteralExpr
>(RetValExp
))
4049 Diag(ReturnLoc
, diag::warn_main_returns_bool_literal
)
4050 << RetValExp
->getSourceRange();
4051 if (FD
->hasAttr
<CmseNSEntryAttr
>() && RetValExp
) {
4052 if (const auto *RT
= dyn_cast
<RecordType
>(FnRetType
.getCanonicalType())) {
4053 if (RT
->getDecl()->isOrContainsUnion())
4054 Diag(RetValExp
->getBeginLoc(), diag::warn_cmse_nonsecure_union
) << 1;
4057 } else if (ObjCMethodDecl
*MD
= getCurMethodDecl()) {
4058 FnRetType
= MD
->getReturnType();
4059 isObjCMethod
= true;
4061 Attrs
= &MD
->getAttrs();
4062 if (MD
->hasRelatedResultType() && MD
->getClassInterface()) {
4063 // In the implementation of a method with a related return type, the
4064 // type used to type-check the validity of return statements within the
4065 // method body is a pointer to the type of the class being implemented.
4066 RelatedRetType
= Context
.getObjCInterfaceType(MD
->getClassInterface());
4067 RelatedRetType
= Context
.getObjCObjectPointerType(RelatedRetType
);
4069 } else // If we don't have a function/method context, bail.
4073 const auto *ATy
= dyn_cast
<ArrayType
>(RetValExp
->getType());
4074 if (ATy
&& ATy
->getElementType().isWebAssemblyReferenceType()) {
4075 Diag(ReturnLoc
, diag::err_wasm_table_art
) << 1;
4080 // C++1z: discarded return statements are not considered when deducing a
4082 if (ExprEvalContexts
.back().isDiscardedStatementContext() &&
4083 FnRetType
->getContainedAutoType()) {
4086 ActOnFinishFullExpr(RetValExp
, ReturnLoc
, /*DiscardedValue*/ false);
4089 RetValExp
= ER
.get();
4091 return ReturnStmt::Create(Context
, ReturnLoc
, RetValExp
,
4092 /* NRVOCandidate=*/nullptr);
4095 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
4097 if (getLangOpts().CPlusPlus14
) {
4098 if (AutoType
*AT
= FnRetType
->getContainedAutoType()) {
4099 FunctionDecl
*FD
= cast
<FunctionDecl
>(CurContext
);
4100 // If we've already decided this function is invalid, e.g. because
4101 // we saw a `return` whose expression had an error, don't keep
4102 // trying to deduce its return type.
4103 // (Some return values may be needlessly wrapped in RecoveryExpr).
4104 if (FD
->isInvalidDecl() ||
4105 DeduceFunctionTypeFromReturnExpr(FD
, ReturnLoc
, RetValExp
, AT
)) {
4106 FD
->setInvalidDecl();
4109 // The deduction failure is diagnosed and marked, try to recover.
4111 // Wrap return value with a recovery expression of the previous type.
4112 // If no deduction yet, use DependentTy.
4113 auto Recovery
= CreateRecoveryExpr(
4114 RetValExp
->getBeginLoc(), RetValExp
->getEndLoc(), RetValExp
,
4115 AT
->isDeduced() ? FnRetType
: QualType());
4116 if (Recovery
.isInvalid())
4118 RetValExp
= Recovery
.get();
4120 // Nothing to do: a ReturnStmt with no value is fine recovery.
4123 FnRetType
= FD
->getReturnType();
4127 const VarDecl
*NRVOCandidate
= getCopyElisionCandidate(NRInfo
, FnRetType
);
4129 bool HasDependentReturnType
= FnRetType
->isDependentType();
4131 ReturnStmt
*Result
= nullptr;
4132 if (FnRetType
->isVoidType()) {
4134 if (auto *ILE
= dyn_cast
<InitListExpr
>(RetValExp
)) {
4135 // We simply never allow init lists as the return value of void
4136 // functions. This is compatible because this was never allowed before,
4137 // so there's no legacy code to deal with.
4138 NamedDecl
*CurDecl
= getCurFunctionOrMethodDecl();
4139 int FunctionKind
= 0;
4140 if (isa
<ObjCMethodDecl
>(CurDecl
))
4142 else if (isa
<CXXConstructorDecl
>(CurDecl
))
4144 else if (isa
<CXXDestructorDecl
>(CurDecl
))
4147 Diag(ReturnLoc
, diag::err_return_init_list
)
4148 << CurDecl
<< FunctionKind
<< RetValExp
->getSourceRange();
4150 // Preserve the initializers in the AST.
4151 RetValExp
= AllowRecovery
4152 ? CreateRecoveryExpr(ILE
->getLBraceLoc(),
4153 ILE
->getRBraceLoc(), ILE
->inits())
4156 } else if (!RetValExp
->isTypeDependent()) {
4157 // C99 6.8.6.4p1 (ext_ since GCC warns)
4158 unsigned D
= diag::ext_return_has_expr
;
4159 if (RetValExp
->getType()->isVoidType()) {
4160 NamedDecl
*CurDecl
= getCurFunctionOrMethodDecl();
4161 if (isa
<CXXConstructorDecl
>(CurDecl
) ||
4162 isa
<CXXDestructorDecl
>(CurDecl
))
4163 D
= diag::err_ctor_dtor_returns_void
;
4165 D
= diag::ext_return_has_void_expr
;
4168 ExprResult Result
= RetValExp
;
4169 Result
= IgnoredValueConversions(Result
.get());
4170 if (Result
.isInvalid())
4172 RetValExp
= Result
.get();
4173 RetValExp
= ImpCastExprToType(RetValExp
,
4174 Context
.VoidTy
, CK_ToVoid
).get();
4176 // return of void in constructor/destructor is illegal in C++.
4177 if (D
== diag::err_ctor_dtor_returns_void
) {
4178 NamedDecl
*CurDecl
= getCurFunctionOrMethodDecl();
4179 Diag(ReturnLoc
, D
) << CurDecl
<< isa
<CXXDestructorDecl
>(CurDecl
)
4180 << RetValExp
->getSourceRange();
4182 // return (some void expression); is legal in C++.
4183 else if (D
!= diag::ext_return_has_void_expr
||
4184 !getLangOpts().CPlusPlus
) {
4185 NamedDecl
*CurDecl
= getCurFunctionOrMethodDecl();
4187 int FunctionKind
= 0;
4188 if (isa
<ObjCMethodDecl
>(CurDecl
))
4190 else if (isa
<CXXConstructorDecl
>(CurDecl
))
4192 else if (isa
<CXXDestructorDecl
>(CurDecl
))
4196 << CurDecl
<< FunctionKind
<< RetValExp
->getSourceRange();
4202 ActOnFinishFullExpr(RetValExp
, ReturnLoc
, /*DiscardedValue*/ false);
4205 RetValExp
= ER
.get();
4209 Result
= ReturnStmt::Create(Context
, ReturnLoc
, RetValExp
,
4210 /* NRVOCandidate=*/nullptr);
4211 } else if (!RetValExp
&& !HasDependentReturnType
) {
4212 FunctionDecl
*FD
= getCurFunctionDecl();
4214 if ((FD
&& FD
->isInvalidDecl()) || FnRetType
->containsErrors()) {
4215 // The intended return type might have been "void", so don't warn.
4216 } else if (getLangOpts().CPlusPlus11
&& FD
&& FD
->isConstexpr()) {
4217 // C++11 [stmt.return]p2
4218 Diag(ReturnLoc
, diag::err_constexpr_return_missing_expr
)
4219 << FD
<< FD
->isConsteval();
4220 FD
->setInvalidDecl();
4222 // C99 6.8.6.4p1 (ext_ since GCC warns)
4224 unsigned DiagID
= getLangOpts().C99
? diag::ext_return_missing_expr
4225 : diag::warn_return_missing_expr
;
4226 // Note that at this point one of getCurFunctionDecl() or
4227 // getCurMethodDecl() must be non-null (see above).
4228 assert((getCurFunctionDecl() || getCurMethodDecl()) &&
4229 "Not in a FunctionDecl or ObjCMethodDecl?");
4230 bool IsMethod
= FD
== nullptr;
4231 const NamedDecl
*ND
=
4232 IsMethod
? cast
<NamedDecl
>(getCurMethodDecl()) : cast
<NamedDecl
>(FD
);
4233 Diag(ReturnLoc
, DiagID
) << ND
<< IsMethod
;
4236 Result
= ReturnStmt::Create(Context
, ReturnLoc
, /* RetExpr=*/nullptr,
4237 /* NRVOCandidate=*/nullptr);
4239 assert(RetValExp
|| HasDependentReturnType
);
4240 QualType RetType
= RelatedRetType
.isNull() ? FnRetType
: RelatedRetType
;
4242 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
4243 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
4246 // In C++ the return statement is handled via a copy initialization,
4247 // the C version of which boils down to CheckSingleAssignmentConstraints.
4248 if (!HasDependentReturnType
&& !RetValExp
->isTypeDependent()) {
4249 // we have a non-void function with an expression, continue checking
4250 InitializedEntity Entity
=
4251 InitializedEntity::InitializeResult(ReturnLoc
, RetType
);
4252 ExprResult Res
= PerformMoveOrCopyInitialization(
4253 Entity
, NRInfo
, RetValExp
, SupressSimplerImplicitMoves
);
4254 if (Res
.isInvalid() && AllowRecovery
)
4255 Res
= CreateRecoveryExpr(RetValExp
->getBeginLoc(),
4256 RetValExp
->getEndLoc(), RetValExp
, RetType
);
4257 if (Res
.isInvalid()) {
4258 // FIXME: Clean up temporaries here anyway?
4261 RetValExp
= Res
.getAs
<Expr
>();
4263 // If we have a related result type, we need to implicitly
4264 // convert back to the formal result type. We can't pretend to
4265 // initialize the result again --- we might end double-retaining
4266 // --- so instead we initialize a notional temporary.
4267 if (!RelatedRetType
.isNull()) {
4268 Entity
= InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
4270 Res
= PerformCopyInitialization(Entity
, ReturnLoc
, RetValExp
);
4271 if (Res
.isInvalid()) {
4272 // FIXME: Clean up temporaries here anyway?
4275 RetValExp
= Res
.getAs
<Expr
>();
4278 CheckReturnValExpr(RetValExp
, FnRetType
, ReturnLoc
, isObjCMethod
, Attrs
,
4279 getCurFunctionDecl());
4284 ActOnFinishFullExpr(RetValExp
, ReturnLoc
, /*DiscardedValue*/ false);
4287 RetValExp
= ER
.get();
4289 Result
= ReturnStmt::Create(Context
, ReturnLoc
, RetValExp
, NRVOCandidate
);
4292 // If we need to check for the named return value optimization, save the
4293 // return statement in our scope for later processing.
4294 if (Result
->getNRVOCandidate())
4295 FunctionScopes
.back()->Returns
.push_back(Result
);
4297 if (FunctionScopes
.back()->FirstReturnLoc
.isInvalid())
4298 FunctionScopes
.back()->FirstReturnLoc
= ReturnLoc
;
4304 Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc
,
4305 SourceLocation RParen
, Decl
*Parm
,
4307 VarDecl
*Var
= cast_or_null
<VarDecl
>(Parm
);
4308 if (Var
&& Var
->isInvalidDecl())
4311 return new (Context
) ObjCAtCatchStmt(AtLoc
, RParen
, Var
, Body
);
4315 Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc
, Stmt
*Body
) {
4316 return new (Context
) ObjCAtFinallyStmt(AtLoc
, Body
);
4320 Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc
, Stmt
*Try
,
4321 MultiStmtArg CatchStmts
, Stmt
*Finally
) {
4322 if (!getLangOpts().ObjCExceptions
)
4323 Diag(AtLoc
, diag::err_objc_exceptions_disabled
) << "@try";
4325 // Objective-C try is incompatible with SEH __try.
4326 sema::FunctionScopeInfo
*FSI
= getCurFunction();
4327 if (FSI
->FirstSEHTryLoc
.isValid()) {
4328 Diag(AtLoc
, diag::err_mixing_cxx_try_seh_try
) << 1;
4329 Diag(FSI
->FirstSEHTryLoc
, diag::note_conflicting_try_here
) << "'__try'";
4332 FSI
->setHasObjCTry(AtLoc
);
4333 unsigned NumCatchStmts
= CatchStmts
.size();
4334 return ObjCAtTryStmt::Create(Context
, AtLoc
, Try
, CatchStmts
.data(),
4335 NumCatchStmts
, Finally
);
4338 StmtResult
Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc
, Expr
*Throw
) {
4340 ExprResult Result
= DefaultLvalueConversion(Throw
);
4341 if (Result
.isInvalid())
4344 Result
= ActOnFinishFullExpr(Result
.get(), /*DiscardedValue*/ false);
4345 if (Result
.isInvalid())
4347 Throw
= Result
.get();
4349 QualType ThrowType
= Throw
->getType();
4350 // Make sure the expression type is an ObjC pointer or "void *".
4351 if (!ThrowType
->isDependentType() &&
4352 !ThrowType
->isObjCObjectPointerType()) {
4353 const PointerType
*PT
= ThrowType
->getAs
<PointerType
>();
4354 if (!PT
|| !PT
->getPointeeType()->isVoidType())
4355 return StmtError(Diag(AtLoc
, diag::err_objc_throw_expects_object
)
4356 << Throw
->getType() << Throw
->getSourceRange());
4360 return new (Context
) ObjCAtThrowStmt(AtLoc
, Throw
);
4364 Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc
, Expr
*Throw
,
4366 if (!getLangOpts().ObjCExceptions
)
4367 Diag(AtLoc
, diag::err_objc_exceptions_disabled
) << "@throw";
4370 // @throw without an expression designates a rethrow (which must occur
4371 // in the context of an @catch clause).
4372 Scope
*AtCatchParent
= CurScope
;
4373 while (AtCatchParent
&& !AtCatchParent
->isAtCatchScope())
4374 AtCatchParent
= AtCatchParent
->getParent();
4376 return StmtError(Diag(AtLoc
, diag::err_rethrow_used_outside_catch
));
4378 return BuildObjCAtThrowStmt(AtLoc
, Throw
);
4382 Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc
, Expr
*operand
) {
4383 ExprResult result
= DefaultLvalueConversion(operand
);
4384 if (result
.isInvalid())
4386 operand
= result
.get();
4388 // Make sure the expression type is an ObjC pointer or "void *".
4389 QualType type
= operand
->getType();
4390 if (!type
->isDependentType() &&
4391 !type
->isObjCObjectPointerType()) {
4392 const PointerType
*pointerType
= type
->getAs
<PointerType
>();
4393 if (!pointerType
|| !pointerType
->getPointeeType()->isVoidType()) {
4394 if (getLangOpts().CPlusPlus
) {
4395 if (RequireCompleteType(atLoc
, type
,
4396 diag::err_incomplete_receiver_type
))
4397 return Diag(atLoc
, diag::err_objc_synchronized_expects_object
)
4398 << type
<< operand
->getSourceRange();
4400 ExprResult result
= PerformContextuallyConvertToObjCPointer(operand
);
4401 if (result
.isInvalid())
4403 if (!result
.isUsable())
4404 return Diag(atLoc
, diag::err_objc_synchronized_expects_object
)
4405 << type
<< operand
->getSourceRange();
4407 operand
= result
.get();
4409 return Diag(atLoc
, diag::err_objc_synchronized_expects_object
)
4410 << type
<< operand
->getSourceRange();
4415 // The operand to @synchronized is a full-expression.
4416 return ActOnFinishFullExpr(operand
, /*DiscardedValue*/ false);
4420 Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc
, Expr
*SyncExpr
,
4422 // We can't jump into or indirect-jump out of a @synchronized block.
4423 setFunctionHasBranchProtectedScope();
4424 return new (Context
) ObjCAtSynchronizedStmt(AtLoc
, SyncExpr
, SyncBody
);
4427 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
4428 /// and creates a proper catch handler from them.
4430 Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc
, Decl
*ExDecl
,
4431 Stmt
*HandlerBlock
) {
4432 // There's nothing to test that ActOnExceptionDecl didn't already test.
4433 return new (Context
)
4434 CXXCatchStmt(CatchLoc
, cast_or_null
<VarDecl
>(ExDecl
), HandlerBlock
);
4438 Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc
, Stmt
*Body
) {
4439 setFunctionHasBranchProtectedScope();
4440 return new (Context
) ObjCAutoreleasePoolStmt(AtLoc
, Body
);
4444 class CatchHandlerType
{
4446 LLVM_PREFERRED_TYPE(bool)
4447 unsigned IsPointer
: 1;
4449 // This is a special constructor to be used only with DenseMapInfo's
4450 // getEmptyKey() and getTombstoneKey() functions.
4451 friend struct llvm::DenseMapInfo
<CatchHandlerType
>;
4452 enum Unique
{ ForDenseMap
};
4453 CatchHandlerType(QualType QT
, Unique
) : QT(QT
), IsPointer(false) {}
4456 /// Used when creating a CatchHandlerType from a handler type; will determine
4457 /// whether the type is a pointer or reference and will strip off the top
4458 /// level pointer and cv-qualifiers.
4459 CatchHandlerType(QualType Q
) : QT(Q
), IsPointer(false) {
4460 if (QT
->isPointerType())
4463 QT
= QT
.getUnqualifiedType();
4464 if (IsPointer
|| QT
->isReferenceType())
4465 QT
= QT
->getPointeeType();
4468 /// Used when creating a CatchHandlerType from a base class type; pretends the
4469 /// type passed in had the pointer qualifier, does not need to get an
4470 /// unqualified type.
4471 CatchHandlerType(QualType QT
, bool IsPointer
)
4472 : QT(QT
), IsPointer(IsPointer
) {}
4474 QualType
underlying() const { return QT
; }
4475 bool isPointer() const { return IsPointer
; }
4477 friend bool operator==(const CatchHandlerType
&LHS
,
4478 const CatchHandlerType
&RHS
) {
4479 // If the pointer qualification does not match, we can return early.
4480 if (LHS
.IsPointer
!= RHS
.IsPointer
)
4482 // Otherwise, check the underlying type without cv-qualifiers.
4483 return LHS
.QT
== RHS
.QT
;
4489 template <> struct DenseMapInfo
<CatchHandlerType
> {
4490 static CatchHandlerType
getEmptyKey() {
4491 return CatchHandlerType(DenseMapInfo
<QualType
>::getEmptyKey(),
4492 CatchHandlerType::ForDenseMap
);
4495 static CatchHandlerType
getTombstoneKey() {
4496 return CatchHandlerType(DenseMapInfo
<QualType
>::getTombstoneKey(),
4497 CatchHandlerType::ForDenseMap
);
4500 static unsigned getHashValue(const CatchHandlerType
&Base
) {
4501 return DenseMapInfo
<QualType
>::getHashValue(Base
.underlying());
4504 static bool isEqual(const CatchHandlerType
&LHS
,
4505 const CatchHandlerType
&RHS
) {
4512 class CatchTypePublicBases
{
4513 const llvm::DenseMap
<QualType
, CXXCatchStmt
*> &TypesToCheck
;
4515 CXXCatchStmt
*FoundHandler
;
4516 QualType FoundHandlerType
;
4517 QualType TestAgainstType
;
4520 CatchTypePublicBases(const llvm::DenseMap
<QualType
, CXXCatchStmt
*> &T
,
4522 : TypesToCheck(T
), FoundHandler(nullptr), TestAgainstType(QT
) {}
4524 CXXCatchStmt
*getFoundHandler() const { return FoundHandler
; }
4525 QualType
getFoundHandlerType() const { return FoundHandlerType
; }
4527 bool operator()(const CXXBaseSpecifier
*S
, CXXBasePath
&) {
4528 if (S
->getAccessSpecifier() == AccessSpecifier::AS_public
) {
4529 QualType Check
= S
->getType().getCanonicalType();
4530 const auto &M
= TypesToCheck
;
4531 auto I
= M
.find(Check
);
4533 // We're pretty sure we found what we need to find. However, we still
4534 // need to make sure that we properly compare for pointers and
4535 // references, to handle cases like:
4537 // } catch (Base *b) {
4538 // } catch (Derived &d) {
4541 // where there is a qualification mismatch that disqualifies this
4542 // handler as a potential problem.
4543 if (I
->second
->getCaughtType()->isPointerType() ==
4544 TestAgainstType
->isPointerType()) {
4545 FoundHandler
= I
->second
;
4546 FoundHandlerType
= Check
;
4556 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
4557 /// handlers and creates a try statement from them.
4558 StmtResult
Sema::ActOnCXXTryBlock(SourceLocation TryLoc
, Stmt
*TryBlock
,
4559 ArrayRef
<Stmt
*> Handlers
) {
4560 const llvm::Triple
&T
= Context
.getTargetInfo().getTriple();
4561 const bool IsOpenMPGPUTarget
=
4562 getLangOpts().OpenMPIsTargetDevice
&& (T
.isNVPTX() || T
.isAMDGCN());
4563 // Don't report an error if 'try' is used in system headers or in an OpenMP
4564 // target region compiled for a GPU architecture.
4565 if (!IsOpenMPGPUTarget
&& !getLangOpts().CXXExceptions
&&
4566 !getSourceManager().isInSystemHeader(TryLoc
) && !getLangOpts().CUDA
) {
4567 // Delay error emission for the OpenMP device code.
4568 targetDiag(TryLoc
, diag::err_exceptions_disabled
) << "try";
4571 // In OpenMP target regions, we assume that catch is never reached on GPU
4573 if (IsOpenMPGPUTarget
)
4574 targetDiag(TryLoc
, diag::warn_try_not_valid_on_target
) << T
.str();
4576 // Exceptions aren't allowed in CUDA device code.
4577 if (getLangOpts().CUDA
)
4578 CUDA().DiagIfDeviceCode(TryLoc
, diag::err_cuda_device_exceptions
)
4579 << "try" << llvm::to_underlying(CUDA().CurrentTarget());
4581 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
4582 Diag(TryLoc
, diag::err_omp_simd_region_cannot_use_stmt
) << "try";
4584 sema::FunctionScopeInfo
*FSI
= getCurFunction();
4586 // C++ try is incompatible with SEH __try.
4587 if (!getLangOpts().Borland
&& FSI
->FirstSEHTryLoc
.isValid()) {
4588 Diag(TryLoc
, diag::err_mixing_cxx_try_seh_try
) << 0;
4589 Diag(FSI
->FirstSEHTryLoc
, diag::note_conflicting_try_here
) << "'__try'";
4592 const unsigned NumHandlers
= Handlers
.size();
4593 assert(!Handlers
.empty() &&
4594 "The parser shouldn't call this if there are no handlers.");
4596 llvm::DenseMap
<QualType
, CXXCatchStmt
*> HandledBaseTypes
;
4597 llvm::DenseMap
<CatchHandlerType
, CXXCatchStmt
*> HandledTypes
;
4598 for (unsigned i
= 0; i
< NumHandlers
; ++i
) {
4599 CXXCatchStmt
*H
= cast
<CXXCatchStmt
>(Handlers
[i
]);
4601 // Diagnose when the handler is a catch-all handler, but it isn't the last
4602 // handler for the try block. [except.handle]p5. Also, skip exception
4603 // declarations that are invalid, since we can't usefully report on them.
4604 if (!H
->getExceptionDecl()) {
4605 if (i
< NumHandlers
- 1)
4606 return StmtError(Diag(H
->getBeginLoc(), diag::err_early_catch_all
));
4608 } else if (H
->getExceptionDecl()->isInvalidDecl())
4611 // Walk the type hierarchy to diagnose when this type has already been
4612 // handled (duplication), or cannot be handled (derivation inversion). We
4613 // ignore top-level cv-qualifiers, per [except.handle]p3
4614 CatchHandlerType HandlerCHT
= H
->getCaughtType().getCanonicalType();
4616 // We can ignore whether the type is a reference or a pointer; we need the
4617 // underlying declaration type in order to get at the underlying record
4618 // decl, if there is one.
4619 QualType Underlying
= HandlerCHT
.underlying();
4620 if (auto *RD
= Underlying
->getAsCXXRecordDecl()) {
4621 if (!RD
->hasDefinition())
4623 // Check that none of the public, unambiguous base classes are in the
4624 // map ([except.handle]p1). Give the base classes the same pointer
4625 // qualification as the original type we are basing off of. This allows
4626 // comparison against the handler type using the same top-level pointer
4627 // as the original type.
4629 Paths
.setOrigin(RD
);
4630 CatchTypePublicBases
CTPB(HandledBaseTypes
,
4631 H
->getCaughtType().getCanonicalType());
4632 if (RD
->lookupInBases(CTPB
, Paths
)) {
4633 const CXXCatchStmt
*Problem
= CTPB
.getFoundHandler();
4634 if (!Paths
.isAmbiguous(
4635 CanQualType::CreateUnsafe(CTPB
.getFoundHandlerType()))) {
4636 Diag(H
->getExceptionDecl()->getTypeSpecStartLoc(),
4637 diag::warn_exception_caught_by_earlier_handler
)
4638 << H
->getCaughtType();
4639 Diag(Problem
->getExceptionDecl()->getTypeSpecStartLoc(),
4640 diag::note_previous_exception_handler
)
4641 << Problem
->getCaughtType();
4644 // Strip the qualifiers here because we're going to be comparing this
4645 // type to the base type specifiers of a class, which are ignored in a
4646 // base specifier per [class.derived.general]p2.
4647 HandledBaseTypes
[Underlying
.getUnqualifiedType()] = H
;
4650 // Add the type the list of ones we have handled; diagnose if we've already
4652 auto R
= HandledTypes
.insert(
4653 std::make_pair(H
->getCaughtType().getCanonicalType(), H
));
4655 const CXXCatchStmt
*Problem
= R
.first
->second
;
4656 Diag(H
->getExceptionDecl()->getTypeSpecStartLoc(),
4657 diag::warn_exception_caught_by_earlier_handler
)
4658 << H
->getCaughtType();
4659 Diag(Problem
->getExceptionDecl()->getTypeSpecStartLoc(),
4660 diag::note_previous_exception_handler
)
4661 << Problem
->getCaughtType();
4665 FSI
->setHasCXXTry(TryLoc
);
4667 return CXXTryStmt::Create(Context
, TryLoc
, cast
<CompoundStmt
>(TryBlock
),
4671 StmtResult
Sema::ActOnSEHTryBlock(bool IsCXXTry
, SourceLocation TryLoc
,
4672 Stmt
*TryBlock
, Stmt
*Handler
) {
4673 assert(TryBlock
&& Handler
);
4675 sema::FunctionScopeInfo
*FSI
= getCurFunction();
4677 // SEH __try is incompatible with C++ try. Borland appears to support this,
4679 if (!getLangOpts().Borland
) {
4680 if (FSI
->FirstCXXOrObjCTryLoc
.isValid()) {
4681 Diag(TryLoc
, diag::err_mixing_cxx_try_seh_try
) << FSI
->FirstTryType
;
4682 Diag(FSI
->FirstCXXOrObjCTryLoc
, diag::note_conflicting_try_here
)
4683 << (FSI
->FirstTryType
== sema::FunctionScopeInfo::TryLocIsCXX
4689 FSI
->setHasSEHTry(TryLoc
);
4691 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
4692 // track if they use SEH.
4693 DeclContext
*DC
= CurContext
;
4694 while (DC
&& !DC
->isFunctionOrMethod())
4695 DC
= DC
->getParent();
4696 FunctionDecl
*FD
= dyn_cast_or_null
<FunctionDecl
>(DC
);
4698 FD
->setUsesSEHTry(true);
4700 Diag(TryLoc
, diag::err_seh_try_outside_functions
);
4702 // Reject __try on unsupported targets.
4703 if (!Context
.getTargetInfo().isSEHTrySupported())
4704 Diag(TryLoc
, diag::err_seh_try_unsupported
);
4706 return SEHTryStmt::Create(Context
, IsCXXTry
, TryLoc
, TryBlock
, Handler
);
4709 StmtResult
Sema::ActOnSEHExceptBlock(SourceLocation Loc
, Expr
*FilterExpr
,
4711 assert(FilterExpr
&& Block
);
4712 QualType FTy
= FilterExpr
->getType();
4713 if (!FTy
->isIntegerType() && !FTy
->isDependentType()) {
4715 Diag(FilterExpr
->getExprLoc(), diag::err_filter_expression_integral
)
4718 return SEHExceptStmt::Create(Context
, Loc
, FilterExpr
, Block
);
4721 void Sema::ActOnStartSEHFinallyBlock() {
4722 CurrentSEHFinally
.push_back(CurScope
);
4725 void Sema::ActOnAbortSEHFinallyBlock() {
4726 CurrentSEHFinally
.pop_back();
4729 StmtResult
Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc
, Stmt
*Block
) {
4731 CurrentSEHFinally
.pop_back();
4732 return SEHFinallyStmt::Create(Context
, Loc
, Block
);
4736 Sema::ActOnSEHLeaveStmt(SourceLocation Loc
, Scope
*CurScope
) {
4737 Scope
*SEHTryParent
= CurScope
;
4738 while (SEHTryParent
&& !SEHTryParent
->isSEHTryScope())
4739 SEHTryParent
= SEHTryParent
->getParent();
4741 return StmtError(Diag(Loc
, diag::err_ms___leave_not_in___try
));
4742 CheckJumpOutOfSEHFinally(*this, Loc
, *SEHTryParent
);
4744 return new (Context
) SEHLeaveStmt(Loc
);
4747 StmtResult
Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc
,
4749 NestedNameSpecifierLoc QualifierLoc
,
4750 DeclarationNameInfo NameInfo
,
4753 return new (Context
) MSDependentExistsStmt(KeywordLoc
, IsIfExists
,
4754 QualifierLoc
, NameInfo
,
4755 cast
<CompoundStmt
>(Nested
));
4759 StmtResult
Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc
,
4762 UnqualifiedId
&Name
,
4764 return BuildMSDependentExistsStmt(KeywordLoc
, IsIfExists
,
4765 SS
.getWithLocInContext(Context
),
4766 GetNameFromUnqualifiedId(Name
),
4771 Sema::CreateCapturedStmtRecordDecl(CapturedDecl
*&CD
, SourceLocation Loc
,
4772 unsigned NumParams
) {
4773 DeclContext
*DC
= CurContext
;
4774 while (!(DC
->isFunctionOrMethod() || DC
->isRecord() || DC
->isFileContext()))
4775 DC
= DC
->getParent();
4777 RecordDecl
*RD
= nullptr;
4778 if (getLangOpts().CPlusPlus
)
4779 RD
= CXXRecordDecl::Create(Context
, TagTypeKind::Struct
, DC
, Loc
, Loc
,
4782 RD
= RecordDecl::Create(Context
, TagTypeKind::Struct
, DC
, Loc
, Loc
,
4785 RD
->setCapturedRecord();
4788 RD
->startDefinition();
4790 assert(NumParams
> 0 && "CapturedStmt requires context parameter");
4791 CD
= CapturedDecl::Create(Context
, CurContext
, NumParams
);
4797 buildCapturedStmtCaptureList(Sema
&S
, CapturedRegionScopeInfo
*RSI
,
4798 SmallVectorImpl
<CapturedStmt::Capture
> &Captures
,
4799 SmallVectorImpl
<Expr
*> &CaptureInits
) {
4800 for (const sema::Capture
&Cap
: RSI
->Captures
) {
4801 if (Cap
.isInvalid())
4804 // Form the initializer for the capture.
4805 ExprResult Init
= S
.BuildCaptureInit(Cap
, Cap
.getLocation(),
4806 RSI
->CapRegionKind
== CR_OpenMP
);
4808 // FIXME: Bail out now if the capture is not used and the initializer has
4811 // Create a field for this capture.
4812 FieldDecl
*Field
= S
.BuildCaptureField(RSI
->TheRecordDecl
, Cap
);
4814 // Add the capture to our list of captures.
4815 if (Cap
.isThisCapture()) {
4816 Captures
.push_back(CapturedStmt::Capture(Cap
.getLocation(),
4817 CapturedStmt::VCK_This
));
4818 } else if (Cap
.isVLATypeCapture()) {
4820 CapturedStmt::Capture(Cap
.getLocation(), CapturedStmt::VCK_VLAType
));
4822 assert(Cap
.isVariableCapture() && "unknown kind of capture");
4824 if (S
.getLangOpts().OpenMP
&& RSI
->CapRegionKind
== CR_OpenMP
)
4825 S
.setOpenMPCaptureKind(Field
, Cap
.getVariable(), RSI
->OpenMPLevel
);
4827 Captures
.push_back(CapturedStmt::Capture(
4829 Cap
.isReferenceCapture() ? CapturedStmt::VCK_ByRef
4830 : CapturedStmt::VCK_ByCopy
,
4831 cast
<VarDecl
>(Cap
.getVariable())));
4833 CaptureInits
.push_back(Init
.get());
4838 void Sema::ActOnCapturedRegionStart(SourceLocation Loc
, Scope
*CurScope
,
4839 CapturedRegionKind Kind
,
4840 unsigned NumParams
) {
4841 CapturedDecl
*CD
= nullptr;
4842 RecordDecl
*RD
= CreateCapturedStmtRecordDecl(CD
, Loc
, NumParams
);
4844 // Build the context parameter
4845 DeclContext
*DC
= CapturedDecl::castToDeclContext(CD
);
4846 IdentifierInfo
*ParamName
= &Context
.Idents
.get("__context");
4847 QualType ParamType
= Context
.getPointerType(Context
.getTagDeclType(RD
));
4849 ImplicitParamDecl::Create(Context
, DC
, Loc
, ParamName
, ParamType
,
4850 ImplicitParamKind::CapturedContext
);
4853 CD
->setContextParam(0, Param
);
4855 // Enter the capturing scope for this captured region.
4856 PushCapturedRegionScope(CurScope
, CD
, RD
, Kind
);
4859 PushDeclContext(CurScope
, CD
);
4863 PushExpressionEvaluationContext(
4864 ExpressionEvaluationContext::PotentiallyEvaluated
);
4865 ExprEvalContexts
.back().InImmediateEscalatingFunctionContext
= false;
4868 void Sema::ActOnCapturedRegionStart(SourceLocation Loc
, Scope
*CurScope
,
4869 CapturedRegionKind Kind
,
4870 ArrayRef
<CapturedParamNameType
> Params
,
4871 unsigned OpenMPCaptureLevel
) {
4872 CapturedDecl
*CD
= nullptr;
4873 RecordDecl
*RD
= CreateCapturedStmtRecordDecl(CD
, Loc
, Params
.size());
4875 // Build the context parameter
4876 DeclContext
*DC
= CapturedDecl::castToDeclContext(CD
);
4877 bool ContextIsFound
= false;
4878 unsigned ParamNum
= 0;
4879 for (ArrayRef
<CapturedParamNameType
>::iterator I
= Params
.begin(),
4881 I
!= E
; ++I
, ++ParamNum
) {
4882 if (I
->second
.isNull()) {
4883 assert(!ContextIsFound
&&
4884 "null type has been found already for '__context' parameter");
4885 IdentifierInfo
*ParamName
= &Context
.Idents
.get("__context");
4886 QualType ParamType
= Context
.getPointerType(Context
.getTagDeclType(RD
))
4890 ImplicitParamDecl::Create(Context
, DC
, Loc
, ParamName
, ParamType
,
4891 ImplicitParamKind::CapturedContext
);
4893 CD
->setContextParam(ParamNum
, Param
);
4894 ContextIsFound
= true;
4896 IdentifierInfo
*ParamName
= &Context
.Idents
.get(I
->first
);
4898 ImplicitParamDecl::Create(Context
, DC
, Loc
, ParamName
, I
->second
,
4899 ImplicitParamKind::CapturedContext
);
4901 CD
->setParam(ParamNum
, Param
);
4904 assert(ContextIsFound
&& "no null type for '__context' parameter");
4905 if (!ContextIsFound
) {
4906 // Add __context implicitly if it is not specified.
4907 IdentifierInfo
*ParamName
= &Context
.Idents
.get("__context");
4908 QualType ParamType
= Context
.getPointerType(Context
.getTagDeclType(RD
));
4910 ImplicitParamDecl::Create(Context
, DC
, Loc
, ParamName
, ParamType
,
4911 ImplicitParamKind::CapturedContext
);
4913 CD
->setContextParam(ParamNum
, Param
);
4915 // Enter the capturing scope for this captured region.
4916 PushCapturedRegionScope(CurScope
, CD
, RD
, Kind
, OpenMPCaptureLevel
);
4919 PushDeclContext(CurScope
, CD
);
4923 PushExpressionEvaluationContext(
4924 ExpressionEvaluationContext::PotentiallyEvaluated
);
4927 void Sema::ActOnCapturedRegionError() {
4928 DiscardCleanupsInEvaluationContext();
4929 PopExpressionEvaluationContext();
4931 PoppedFunctionScopePtr ScopeRAII
= PopFunctionScopeInfo();
4932 CapturedRegionScopeInfo
*RSI
= cast
<CapturedRegionScopeInfo
>(ScopeRAII
.get());
4934 RecordDecl
*Record
= RSI
->TheRecordDecl
;
4935 Record
->setInvalidDecl();
4937 SmallVector
<Decl
*, 4> Fields(Record
->fields());
4938 ActOnFields(/*Scope=*/nullptr, Record
->getLocation(), Record
, Fields
,
4939 SourceLocation(), SourceLocation(), ParsedAttributesView());
4942 StmtResult
Sema::ActOnCapturedRegionEnd(Stmt
*S
) {
4943 // Leave the captured scope before we start creating captures in the
4945 DiscardCleanupsInEvaluationContext();
4946 PopExpressionEvaluationContext();
4948 PoppedFunctionScopePtr ScopeRAII
= PopFunctionScopeInfo();
4949 CapturedRegionScopeInfo
*RSI
= cast
<CapturedRegionScopeInfo
>(ScopeRAII
.get());
4951 SmallVector
<CapturedStmt::Capture
, 4> Captures
;
4952 SmallVector
<Expr
*, 4> CaptureInits
;
4953 if (buildCapturedStmtCaptureList(*this, RSI
, Captures
, CaptureInits
))
4956 CapturedDecl
*CD
= RSI
->TheCapturedDecl
;
4957 RecordDecl
*RD
= RSI
->TheRecordDecl
;
4959 CapturedStmt
*Res
= CapturedStmt::Create(
4960 getASTContext(), S
, static_cast<CapturedRegionKind
>(RSI
->CapRegionKind
),
4961 Captures
, CaptureInits
, CD
, RD
);
4963 CD
->setBody(Res
->getCapturedStmt());
4964 RD
->completeDefinition();