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/Sema/Ownership.h"
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTDiagnostic.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/EvaluatedExprVisitor.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/ExprObjC.h"
24 #include "clang/AST/RecursiveASTVisitor.h"
25 #include "clang/AST/StmtCXX.h"
26 #include "clang/AST/StmtObjC.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/AST/TypeOrdering.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/Scope.h"
34 #include "clang/Sema/ScopeInfo.h"
35 #include "llvm/ADT/ArrayRef.h"
36 #include "llvm/ADT/DenseMap.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/ADT/SmallPtrSet.h"
39 #include "llvm/ADT/SmallString.h"
40 #include "llvm/ADT/SmallVector.h"
42 using namespace clang;
45 StmtResult Sema::ActOnExprStmt(ExprResult FE, bool DiscardedValue) {
49 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(), DiscardedValue);
53 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
54 // void expression for its side effects. Conversion to void allows any
55 // operand, even incomplete types.
57 // Same thing in for stmt first clause (when expr) and third clause.
58 return StmtResult(FE.getAs<Stmt>());
62 StmtResult Sema::ActOnExprStmtError() {
63 DiscardCleanupsInEvaluationContext();
67 StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
68 bool HasLeadingEmptyMacro) {
69 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
72 StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
73 SourceLocation EndLoc) {
74 DeclGroupRef DG = dg.get();
76 // If we have an invalid decl, just return an error.
77 if (DG.isNull()) return StmtError();
79 return new (Context) DeclStmt(DG, StartLoc, EndLoc);
82 void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
83 DeclGroupRef DG = dg.get();
85 // If we don't have a declaration, or we have an invalid declaration,
87 if (DG.isNull() || !DG.isSingleDecl())
90 Decl *decl = DG.getSingleDecl();
91 if (!decl || decl->isInvalidDecl())
94 // Only variable declarations are permitted.
95 VarDecl *var = dyn_cast<VarDecl>(decl);
97 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
98 decl->setInvalidDecl();
102 // foreach variables are never actually initialized in the way that
103 // the parser came up with.
104 var->setInit(nullptr);
106 // In ARC, we don't need to retain the iteration variable of a fast
107 // enumeration loop. Rather than actually trying to catch that
108 // during declaration processing, we remove the consequences here.
109 if (getLangOpts().ObjCAutoRefCount) {
110 QualType type = var->getType();
112 // Only do this if we inferred the lifetime. Inferred lifetime
113 // will show up as a local qualifier because explicit lifetime
114 // should have shown up as an AttributedType instead.
115 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
116 // Add 'const' and mark the variable as pseudo-strong.
117 var->setType(type.withConst());
118 var->setARCPseudoStrong(true);
123 /// Diagnose unused comparisons, both builtin and overloaded operators.
124 /// For '==' and '!=', suggest fixits for '=' or '|='.
126 /// Adding a cast to void (or other expression wrappers) will prevent the
127 /// warning from firing.
128 static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
131 enum { Equality, Inequality, Relational, ThreeWay } Kind;
133 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
134 if (!Op->isComparisonOp())
137 if (Op->getOpcode() == BO_EQ)
139 else if (Op->getOpcode() == BO_NE)
141 else if (Op->getOpcode() == BO_Cmp)
144 assert(Op->isRelationalOp());
147 Loc = Op->getOperatorLoc();
148 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
149 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
150 switch (Op->getOperator()) {
154 case OO_ExclaimEqual:
159 case OO_GreaterEqual:
170 Loc = Op->getOperatorLoc();
171 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
173 // Not a typo-prone comparison.
177 // Suppress warnings when the operator, suspicious as it may be, comes from
178 // a macro expansion.
179 if (S.SourceMgr.isMacroBodyExpansion(Loc))
182 S.Diag(Loc, diag::warn_unused_comparison)
183 << (unsigned)Kind << E->getSourceRange();
185 // If the LHS is a plausible entity to assign to, provide a fixit hint to
186 // correct common typos.
188 if (Kind == Inequality)
189 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
190 << FixItHint::CreateReplacement(Loc, "|=");
191 else if (Kind == Equality)
192 S.Diag(Loc, diag::note_equality_comparison_to_assign)
193 << FixItHint::CreateReplacement(Loc, "=");
199 void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
200 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
201 return DiagnoseUnusedExprResult(Label->getSubStmt());
203 const Expr *E = dyn_cast_or_null<Expr>(S);
207 // If we are in an unevaluated expression context, then there can be no unused
208 // results because the results aren't expected to be used in the first place.
209 if (isUnevaluatedContext())
212 SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc();
213 // In most cases, we don't want to warn if the expression is written in a
214 // macro body, or if the macro comes from a system header. If the offending
215 // expression is a call to a function with the warn_unused_result attribute,
216 // we warn no matter the location. Because of the order in which the various
217 // checks need to happen, we factor out the macro-related test here.
218 bool ShouldSuppress =
219 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
220 SourceMgr.isInSystemMacro(ExprLoc);
222 const Expr *WarnExpr;
225 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
228 // If this is a GNU statement expression expanded from a macro, it is probably
229 // unused because it is a function-like macro that can be used as either an
230 // expression or statement. Don't warn, because it is almost certainly a
232 if (isa<StmtExpr>(E) && Loc.isMacroID())
235 // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers.
236 // That macro is frequently used to suppress "unused parameter" warnings,
237 // but its implementation makes clang's -Wunused-value fire. Prevent this.
238 if (isa<ParenExpr>(E->IgnoreImpCasts()) && Loc.isMacroID()) {
239 SourceLocation SpellLoc = Loc;
240 if (findMacroSpelling(SpellLoc, "UNREFERENCED_PARAMETER"))
244 // Okay, we have an unused result. Depending on what the base expression is,
245 // we might want to make a more specific diagnostic. Check for one of these
247 unsigned DiagID = diag::warn_unused_expr;
248 if (const FullExpr *Temps = dyn_cast<FullExpr>(E))
249 E = Temps->getSubExpr();
250 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
251 E = TempExpr->getSubExpr();
253 if (DiagnoseUnusedComparison(*this, E))
257 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
258 if (E->getType()->isVoidType())
261 if (const Attr *A = CE->getUnusedResultAttr(Context)) {
262 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
266 // If the callee has attribute pure, const, or warn_unused_result, warn with
267 // a more specific message to make it clear what is happening. If the call
268 // is written in a macro body, only warn if it has the warn_unused_result
270 if (const Decl *FD = CE->getCalleeDecl()) {
273 if (FD->hasAttr<PureAttr>()) {
274 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
277 if (FD->hasAttr<ConstAttr>()) {
278 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
282 } else if (ShouldSuppress)
285 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
286 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
287 Diag(Loc, diag::err_arc_unused_init_message) << R1;
290 const ObjCMethodDecl *MD = ME->getMethodDecl();
292 if (const auto *A = MD->getAttr<WarnUnusedResultAttr>()) {
293 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
297 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
298 const Expr *Source = POE->getSyntacticForm();
299 if (isa<ObjCSubscriptRefExpr>(Source))
300 DiagID = diag::warn_unused_container_subscript_expr;
302 DiagID = diag::warn_unused_property_expr;
303 } else if (const CXXFunctionalCastExpr *FC
304 = dyn_cast<CXXFunctionalCastExpr>(E)) {
305 const Expr *E = FC->getSubExpr();
306 if (const CXXBindTemporaryExpr *TE = dyn_cast<CXXBindTemporaryExpr>(E))
307 E = TE->getSubExpr();
308 if (isa<CXXTemporaryObjectExpr>(E))
310 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
311 if (const CXXRecordDecl *RD = CE->getType()->getAsCXXRecordDecl())
312 if (!RD->getAttr<WarnUnusedAttr>())
315 // Diagnose "(void*) blah" as a typo for "(void) blah".
316 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
317 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
318 QualType T = TI->getType();
320 // We really do want to use the non-canonical type here.
321 if (T == Context.VoidPtrTy) {
322 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
324 Diag(Loc, diag::warn_unused_voidptr)
325 << FixItHint::CreateRemoval(TL.getStarLoc());
330 if (E->isGLValue() && E->getType().isVolatileQualified()) {
331 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
335 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
338 void Sema::ActOnStartOfCompoundStmt(bool IsStmtExpr) {
339 PushCompoundScope(IsStmtExpr);
342 void Sema::ActOnFinishOfCompoundStmt() {
346 sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
347 return getCurFunction()->CompoundScopes.back();
350 StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
351 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
352 const unsigned NumElts = Elts.size();
354 // If we're in C89 mode, check that we don't have any decls after stmts. If
355 // so, emit an extension diagnostic.
356 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
357 // Note that __extension__ can be around a decl.
359 // Skip over all declarations.
360 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
363 // We found the end of the list or a statement. Scan for another declstmt.
364 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
368 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
369 Diag(D->getLocation(), diag::ext_mixed_decls_code);
373 // Check for suspicious empty body (null statement) in `for' and `while'
374 // statements. Don't do anything for template instantiations, this just adds
376 if (NumElts != 0 && !CurrentInstantiationScope &&
377 getCurCompoundScope().HasEmptyLoopBodies) {
378 for (unsigned i = 0; i != NumElts - 1; ++i)
379 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
382 return CompoundStmt::Create(Context, Elts, L, R);
386 Sema::ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val) {
390 if (DiagnoseUnexpandedParameterPack(Val.get()))
393 // If we're not inside a switch, let the 'case' statement handling diagnose
394 // this. Just clean up after the expression as best we can.
395 if (!getCurFunction()->SwitchStack.empty()) {
397 getCurFunction()->SwitchStack.back().getPointer()->getCond();
400 QualType CondType = CondExpr->getType();
402 auto CheckAndFinish = [&](Expr *E) {
403 if (CondType->isDependentType() || E->isTypeDependent())
404 return ExprResult(E);
406 if (getLangOpts().CPlusPlus11) {
407 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
408 // constant expression of the promoted type of the switch condition.
409 llvm::APSInt TempVal;
410 return CheckConvertedConstantExpression(E, CondType, TempVal,
415 if (!E->isValueDependent())
416 ER = VerifyIntegerConstantExpression(E);
418 ER = DefaultLvalueConversion(ER.get());
420 ER = ImpCastExprToType(ER.get(), CondType, CK_IntegralCast);
424 ExprResult Converted = CorrectDelayedTyposInExpr(Val, CheckAndFinish);
425 if (Converted.get() == Val.get())
426 Converted = CheckAndFinish(Val.get());
427 if (Converted.isInvalid())
432 return ActOnFinishFullExpr(Val.get(), Val.get()->getExprLoc(), false,
433 getLangOpts().CPlusPlus11);
437 Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHSVal,
438 SourceLocation DotDotDotLoc, ExprResult RHSVal,
439 SourceLocation ColonLoc) {
440 assert((LHSVal.isInvalid() || LHSVal.get()) && "missing LHS value");
441 assert((DotDotDotLoc.isInvalid() ? RHSVal.isUnset()
442 : RHSVal.isInvalid() || RHSVal.get()) &&
443 "missing RHS value");
445 if (getCurFunction()->SwitchStack.empty()) {
446 Diag(CaseLoc, diag::err_case_not_in_switch);
450 if (LHSVal.isInvalid() || RHSVal.isInvalid()) {
451 getCurFunction()->SwitchStack.back().setInt(true);
455 auto *CS = CaseStmt::Create(Context, LHSVal.get(), RHSVal.get(),
456 CaseLoc, DotDotDotLoc, ColonLoc);
457 getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(CS);
461 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
462 void Sema::ActOnCaseStmtBody(Stmt *S, Stmt *SubStmt) {
463 cast<CaseStmt>(S)->setSubStmt(SubStmt);
467 Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
468 Stmt *SubStmt, Scope *CurScope) {
469 if (getCurFunction()->SwitchStack.empty()) {
470 Diag(DefaultLoc, diag::err_default_not_in_switch);
474 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
475 getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(DS);
480 Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
481 SourceLocation ColonLoc, Stmt *SubStmt) {
482 // If the label was multiply defined, reject it now.
483 if (TheDecl->getStmt()) {
484 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
485 Diag(TheDecl->getLocation(), diag::note_previous_definition);
489 // Otherwise, things are good. Fill in the declaration and return it.
490 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
491 TheDecl->setStmt(LS);
492 if (!TheDecl->isGnuLocal()) {
493 TheDecl->setLocStart(IdentLoc);
494 if (!TheDecl->isMSAsmLabel()) {
495 // Don't update the location of MS ASM labels. These will result in
496 // a diagnostic, and changing the location here will mess that up.
497 TheDecl->setLocation(IdentLoc);
503 StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
504 ArrayRef<const Attr*> Attrs,
506 // Fill in the declaration and return it.
507 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
512 class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
513 typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
516 CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
517 void VisitBinaryOperator(BinaryOperator *E) {
518 if (E->getOpcode() == BO_Comma)
519 SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc());
520 EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E);
526 Sema::ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt,
527 ConditionResult Cond,
528 Stmt *thenStmt, SourceLocation ElseLoc,
530 if (Cond.isInvalid())
531 Cond = ConditionResult(
533 MakeFullExpr(new (Context) OpaqueValueExpr(SourceLocation(),
534 Context.BoolTy, VK_RValue),
538 Expr *CondExpr = Cond.get().second;
539 // Only call the CommaVisitor when not C89 due to differences in scope flags.
540 if ((getLangOpts().C99 || getLangOpts().CPlusPlus) &&
541 !Diags.isIgnored(diag::warn_comma_operator, CondExpr->getExprLoc()))
542 CommaVisitor(*this).Visit(CondExpr);
545 DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), thenStmt,
546 diag::warn_empty_if_body);
548 return BuildIfStmt(IfLoc, IsConstexpr, InitStmt, Cond, thenStmt, ElseLoc,
552 StmtResult Sema::BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
553 Stmt *InitStmt, ConditionResult Cond,
554 Stmt *thenStmt, SourceLocation ElseLoc,
556 if (Cond.isInvalid())
559 if (IsConstexpr || isa<ObjCAvailabilityCheckExpr>(Cond.get().second))
560 setFunctionHasBranchProtectedScope();
562 return IfStmt::Create(Context, IfLoc, IsConstexpr, InitStmt, Cond.get().first,
563 Cond.get().second, thenStmt, ElseLoc, elseStmt);
567 struct CaseCompareFunctor {
568 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
569 const llvm::APSInt &RHS) {
570 return LHS.first < RHS;
572 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
573 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
574 return LHS.first < RHS.first;
576 bool operator()(const llvm::APSInt &LHS,
577 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
578 return LHS < RHS.first;
583 /// CmpCaseVals - Comparison predicate for sorting case values.
585 static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
586 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
587 if (lhs.first < rhs.first)
590 if (lhs.first == rhs.first &&
591 lhs.second->getCaseLoc().getRawEncoding()
592 < rhs.second->getCaseLoc().getRawEncoding())
597 /// CmpEnumVals - Comparison predicate for sorting enumeration values.
599 static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
600 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
602 return lhs.first < rhs.first;
605 /// EqEnumVals - Comparison preficate for uniqing enumeration values.
607 static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
608 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
610 return lhs.first == rhs.first;
613 /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
614 /// potentially integral-promoted expression @p expr.
615 static QualType GetTypeBeforeIntegralPromotion(const Expr *&E) {
616 if (const auto *FE = dyn_cast<FullExpr>(E))
617 E = FE->getSubExpr();
618 while (const auto *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
619 if (ImpCast->getCastKind() != CK_IntegralCast) break;
620 E = ImpCast->getSubExpr();
625 ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) {
626 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
630 SwitchConvertDiagnoser(Expr *Cond)
631 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
634 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
635 QualType T) override {
636 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
639 SemaDiagnosticBuilder diagnoseIncomplete(
640 Sema &S, SourceLocation Loc, QualType T) override {
641 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
642 << T << Cond->getSourceRange();
645 SemaDiagnosticBuilder diagnoseExplicitConv(
646 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
647 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
650 SemaDiagnosticBuilder noteExplicitConv(
651 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
652 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
653 << ConvTy->isEnumeralType() << ConvTy;
656 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
657 QualType T) override {
658 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
661 SemaDiagnosticBuilder noteAmbiguous(
662 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
663 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
664 << ConvTy->isEnumeralType() << ConvTy;
667 SemaDiagnosticBuilder diagnoseConversion(
668 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
669 llvm_unreachable("conversion functions are permitted");
671 } SwitchDiagnoser(Cond);
673 ExprResult CondResult =
674 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
675 if (CondResult.isInvalid())
678 // FIXME: PerformContextualImplicitConversion doesn't always tell us if it
679 // failed and produced a diagnostic.
680 Cond = CondResult.get();
681 if (!Cond->isTypeDependent() &&
682 !Cond->getType()->isIntegralOrEnumerationType())
685 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
686 return UsualUnaryConversions(Cond);
689 StmtResult Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
690 Stmt *InitStmt, ConditionResult Cond) {
691 Expr *CondExpr = Cond.get().second;
692 assert((Cond.isInvalid() || CondExpr) && "switch with no condition");
694 if (CondExpr && !CondExpr->isTypeDependent()) {
695 // We have already converted the expression to an integral or enumeration
696 // type, when we parsed the switch condition. If we don't have an
697 // appropriate type now, enter the switch scope but remember that it's
699 assert(CondExpr->getType()->isIntegralOrEnumerationType() &&
700 "invalid condition type");
701 if (CondExpr->isKnownToHaveBooleanValue()) {
702 // switch(bool_expr) {...} is often a programmer error, e.g.
703 // switch(n && mask) { ... } // Doh - should be "n & mask".
704 // One can always use an if statement instead of switch(bool_expr).
705 Diag(SwitchLoc, diag::warn_bool_switch_condition)
706 << CondExpr->getSourceRange();
710 setFunctionHasBranchIntoScope();
712 auto *SS = SwitchStmt::Create(Context, InitStmt, Cond.get().first, CondExpr);
713 getCurFunction()->SwitchStack.push_back(
714 FunctionScopeInfo::SwitchInfo(SS, false));
718 static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
719 Val = Val.extOrTrunc(BitWidth);
720 Val.setIsSigned(IsSigned);
723 /// Check the specified case value is in range for the given unpromoted switch
725 static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
726 unsigned UnpromotedWidth, bool UnpromotedSign) {
727 // In C++11 onwards, this is checked by the language rules.
728 if (S.getLangOpts().CPlusPlus11)
731 // If the case value was signed and negative and the switch expression is
732 // unsigned, don't bother to warn: this is implementation-defined behavior.
733 // FIXME: Introduce a second, default-ignored warning for this case?
734 if (UnpromotedWidth < Val.getBitWidth()) {
735 llvm::APSInt ConvVal(Val);
736 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
737 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
738 // FIXME: Use different diagnostics for overflow in conversion to promoted
739 // type versus "switch expression cannot have this value". Use proper
740 // IntRange checking rather than just looking at the unpromoted type here.
742 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
743 << ConvVal.toString(10);
747 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
749 /// Returns true if we should emit a diagnostic about this case expression not
750 /// being a part of the enum used in the switch controlling expression.
751 static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
753 const Expr *CaseExpr,
754 EnumValsTy::iterator &EI,
755 EnumValsTy::iterator &EIEnd,
756 const llvm::APSInt &Val) {
760 if (const DeclRefExpr *DRE =
761 dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
762 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
763 QualType VarType = VD->getType();
764 QualType EnumType = S.Context.getTypeDeclType(ED);
765 if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
766 S.Context.hasSameUnqualifiedType(EnumType, VarType))
771 if (ED->hasAttr<FlagEnumAttr>())
772 return !S.IsValueInFlagEnum(ED, Val, false);
774 while (EI != EIEnd && EI->first < Val)
777 if (EI != EIEnd && EI->first == Val)
783 static void checkEnumTypesInSwitchStmt(Sema &S, const Expr *Cond,
785 QualType CondType = Cond->getType();
786 QualType CaseType = Case->getType();
788 const EnumType *CondEnumType = CondType->getAs<EnumType>();
789 const EnumType *CaseEnumType = CaseType->getAs<EnumType>();
790 if (!CondEnumType || !CaseEnumType)
793 // Ignore anonymous enums.
794 if (!CondEnumType->getDecl()->getIdentifier() &&
795 !CondEnumType->getDecl()->getTypedefNameForAnonDecl())
797 if (!CaseEnumType->getDecl()->getIdentifier() &&
798 !CaseEnumType->getDecl()->getTypedefNameForAnonDecl())
801 if (S.Context.hasSameUnqualifiedType(CondType, CaseType))
804 S.Diag(Case->getExprLoc(), diag::warn_comparison_of_mixed_enum_types_switch)
805 << CondType << CaseType << Cond->getSourceRange()
806 << Case->getSourceRange();
810 Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
812 SwitchStmt *SS = cast<SwitchStmt>(Switch);
813 bool CaseListIsIncomplete = getCurFunction()->SwitchStack.back().getInt();
814 assert(SS == getCurFunction()->SwitchStack.back().getPointer() &&
815 "switch stack missing push/pop!");
817 getCurFunction()->SwitchStack.pop_back();
819 if (!BodyStmt) return StmtError();
820 SS->setBody(BodyStmt, SwitchLoc);
822 Expr *CondExpr = SS->getCond();
823 if (!CondExpr) return StmtError();
825 QualType CondType = CondExpr->getType();
828 // Integral promotions are performed (on the switch condition).
830 // A case value unrepresentable by the original switch condition
831 // type (before the promotion) doesn't make sense, even when it can
832 // be represented by the promoted type. Therefore we need to find
833 // the pre-promotion type of the switch condition.
834 const Expr *CondExprBeforePromotion = CondExpr;
835 QualType CondTypeBeforePromotion =
836 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
838 // Get the bitwidth of the switched-on value after promotions. We must
839 // convert the integer case values to this width before comparison.
840 bool HasDependentValue
841 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
842 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
843 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
845 // Get the width and signedness that the condition might actually have, for
847 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
849 unsigned CondWidthBeforePromotion
850 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
851 bool CondIsSignedBeforePromotion
852 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
854 // Accumulate all of the case values in a vector so that we can sort them
855 // and detect duplicates. This vector contains the APInt for the case after
856 // it has been converted to the condition type.
857 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
860 // Keep track of any GNU case ranges we see. The APSInt is the low value.
861 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
862 CaseRangesTy CaseRanges;
864 DefaultStmt *TheDefaultStmt = nullptr;
866 bool CaseListIsErroneous = false;
868 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
869 SC = SC->getNextSwitchCase()) {
871 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
872 if (TheDefaultStmt) {
873 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
874 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
876 // FIXME: Remove the default statement from the switch block so that
877 // we'll return a valid AST. This requires recursing down the AST and
878 // finding it, not something we are set up to do right now. For now,
879 // just lop the entire switch stmt out of the AST.
880 CaseListIsErroneous = true;
885 CaseStmt *CS = cast<CaseStmt>(SC);
887 Expr *Lo = CS->getLHS();
889 if (Lo->isValueDependent()) {
890 HasDependentValue = true;
894 // We already verified that the expression has a constant value;
895 // get that value (prior to conversions).
896 const Expr *LoBeforePromotion = Lo;
897 GetTypeBeforeIntegralPromotion(LoBeforePromotion);
898 llvm::APSInt LoVal = LoBeforePromotion->EvaluateKnownConstInt(Context);
900 // Check the unconverted value is within the range of possible values of
901 // the switch expression.
902 checkCaseValue(*this, Lo->getBeginLoc(), LoVal, CondWidthBeforePromotion,
903 CondIsSignedBeforePromotion);
905 // FIXME: This duplicates the check performed for warn_not_in_enum below.
906 checkEnumTypesInSwitchStmt(*this, CondExprBeforePromotion,
909 // Convert the value to the same width/sign as the condition.
910 AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
912 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
914 if (CS->getRHS()->isValueDependent()) {
915 HasDependentValue = true;
918 CaseRanges.push_back(std::make_pair(LoVal, CS));
920 CaseVals.push_back(std::make_pair(LoVal, CS));
924 if (!HasDependentValue) {
925 // If we don't have a default statement, check whether the
926 // condition is constant.
927 llvm::APSInt ConstantCondValue;
928 bool HasConstantCond = false;
929 if (!HasDependentValue && !TheDefaultStmt) {
930 Expr::EvalResult Result;
931 HasConstantCond = CondExpr->EvaluateAsInt(Result, Context,
932 Expr::SE_AllowSideEffects);
933 if (Result.Val.isInt())
934 ConstantCondValue = Result.Val.getInt();
935 assert(!HasConstantCond ||
936 (ConstantCondValue.getBitWidth() == CondWidth &&
937 ConstantCondValue.isSigned() == CondIsSigned));
939 bool ShouldCheckConstantCond = HasConstantCond;
941 // Sort all the scalar case values so we can easily detect duplicates.
942 llvm::stable_sort(CaseVals, CmpCaseVals);
944 if (!CaseVals.empty()) {
945 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
946 if (ShouldCheckConstantCond &&
947 CaseVals[i].first == ConstantCondValue)
948 ShouldCheckConstantCond = false;
950 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
951 // If we have a duplicate, report it.
952 // First, determine if either case value has a name
953 StringRef PrevString, CurrString;
954 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
955 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
956 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
957 PrevString = DeclRef->getDecl()->getName();
959 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
960 CurrString = DeclRef->getDecl()->getName();
962 SmallString<16> CaseValStr;
963 CaseVals[i-1].first.toString(CaseValStr);
965 if (PrevString == CurrString)
966 Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
967 diag::err_duplicate_case)
968 << (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
970 Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
971 diag::err_duplicate_case_differing_expr)
972 << (PrevString.empty() ? StringRef(CaseValStr) : PrevString)
973 << (CurrString.empty() ? StringRef(CaseValStr) : CurrString)
976 Diag(CaseVals[i - 1].second->getLHS()->getBeginLoc(),
977 diag::note_duplicate_case_prev);
978 // FIXME: We really want to remove the bogus case stmt from the
979 // substmt, but we have no way to do this right now.
980 CaseListIsErroneous = true;
985 // Detect duplicate case ranges, which usually don't exist at all in
987 if (!CaseRanges.empty()) {
988 // Sort all the case ranges by their low value so we can easily detect
989 // overlaps between ranges.
990 llvm::stable_sort(CaseRanges);
992 // Scan the ranges, computing the high values and removing empty ranges.
993 std::vector<llvm::APSInt> HiVals;
994 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
995 llvm::APSInt &LoVal = CaseRanges[i].first;
996 CaseStmt *CR = CaseRanges[i].second;
997 Expr *Hi = CR->getRHS();
999 const Expr *HiBeforePromotion = Hi;
1000 GetTypeBeforeIntegralPromotion(HiBeforePromotion);
1001 llvm::APSInt HiVal = HiBeforePromotion->EvaluateKnownConstInt(Context);
1003 // Check the unconverted value is within the range of possible values of
1004 // the switch expression.
1005 checkCaseValue(*this, Hi->getBeginLoc(), HiVal,
1006 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
1008 // Convert the value to the same width/sign as the condition.
1009 AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
1011 // If the low value is bigger than the high value, the case is empty.
1012 if (LoVal > HiVal) {
1013 Diag(CR->getLHS()->getBeginLoc(), diag::warn_case_empty_range)
1014 << SourceRange(CR->getLHS()->getBeginLoc(), Hi->getEndLoc());
1015 CaseRanges.erase(CaseRanges.begin()+i);
1021 if (ShouldCheckConstantCond &&
1022 LoVal <= ConstantCondValue &&
1023 ConstantCondValue <= HiVal)
1024 ShouldCheckConstantCond = false;
1026 HiVals.push_back(HiVal);
1029 // Rescan the ranges, looking for overlap with singleton values and other
1030 // ranges. Since the range list is sorted, we only need to compare case
1031 // ranges with their neighbors.
1032 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1033 llvm::APSInt &CRLo = CaseRanges[i].first;
1034 llvm::APSInt &CRHi = HiVals[i];
1035 CaseStmt *CR = CaseRanges[i].second;
1037 // Check to see whether the case range overlaps with any
1039 CaseStmt *OverlapStmt = nullptr;
1040 llvm::APSInt OverlapVal(32);
1042 // Find the smallest value >= the lower bound. If I is in the
1043 // case range, then we have overlap.
1044 CaseValsTy::iterator I =
1045 llvm::lower_bound(CaseVals, CRLo, CaseCompareFunctor());
1046 if (I != CaseVals.end() && I->first < CRHi) {
1047 OverlapVal = I->first; // Found overlap with scalar.
1048 OverlapStmt = I->second;
1051 // Find the smallest value bigger than the upper bound.
1052 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1053 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1054 OverlapVal = (I-1)->first; // Found overlap with scalar.
1055 OverlapStmt = (I-1)->second;
1058 // Check to see if this case stmt overlaps with the subsequent
1060 if (i && CRLo <= HiVals[i-1]) {
1061 OverlapVal = HiVals[i-1]; // Found overlap with range.
1062 OverlapStmt = CaseRanges[i-1].second;
1066 // If we have a duplicate, report it.
1067 Diag(CR->getLHS()->getBeginLoc(), diag::err_duplicate_case)
1068 << OverlapVal.toString(10);
1069 Diag(OverlapStmt->getLHS()->getBeginLoc(),
1070 diag::note_duplicate_case_prev);
1071 // FIXME: We really want to remove the bogus case stmt from the
1072 // substmt, but we have no way to do this right now.
1073 CaseListIsErroneous = true;
1078 // Complain if we have a constant condition and we didn't find a match.
1079 if (!CaseListIsErroneous && !CaseListIsIncomplete &&
1080 ShouldCheckConstantCond) {
1081 // TODO: it would be nice if we printed enums as enums, chars as
1083 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1084 << ConstantCondValue.toString(10)
1085 << CondExpr->getSourceRange();
1088 // Check to see if switch is over an Enum and handles all of its
1089 // values. We only issue a warning if there is not 'default:', but
1090 // we still do the analysis to preserve this information in the AST
1091 // (which can be used by flow-based analyes).
1093 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
1095 // If switch has default case, then ignore it.
1096 if (!CaseListIsErroneous && !CaseListIsIncomplete && !HasConstantCond &&
1097 ET && ET->getDecl()->isCompleteDefinition()) {
1098 const EnumDecl *ED = ET->getDecl();
1099 EnumValsTy EnumVals;
1101 // Gather all enum values, set their type and sort them,
1102 // allowing easier comparison with CaseVals.
1103 for (auto *EDI : ED->enumerators()) {
1104 llvm::APSInt Val = EDI->getInitVal();
1105 AdjustAPSInt(Val, CondWidth, CondIsSigned);
1106 EnumVals.push_back(std::make_pair(Val, EDI));
1108 llvm::stable_sort(EnumVals, CmpEnumVals);
1109 auto EI = EnumVals.begin(), EIEnd =
1110 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1112 // See which case values aren't in enum.
1113 for (CaseValsTy::const_iterator CI = CaseVals.begin();
1114 CI != CaseVals.end(); CI++) {
1115 Expr *CaseExpr = CI->second->getLHS();
1116 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1118 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1119 << CondTypeBeforePromotion;
1122 // See which of case ranges aren't in enum
1123 EI = EnumVals.begin();
1124 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1125 RI != CaseRanges.end(); RI++) {
1126 Expr *CaseExpr = RI->second->getLHS();
1127 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1129 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1130 << CondTypeBeforePromotion;
1133 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1134 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1136 CaseExpr = RI->second->getRHS();
1137 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1139 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1140 << CondTypeBeforePromotion;
1143 // Check which enum vals aren't in switch
1144 auto CI = CaseVals.begin();
1145 auto RI = CaseRanges.begin();
1146 bool hasCasesNotInSwitch = false;
1148 SmallVector<DeclarationName,8> UnhandledNames;
1150 for (EI = EnumVals.begin(); EI != EIEnd; EI++) {
1151 // Don't warn about omitted unavailable EnumConstantDecls.
1152 switch (EI->second->getAvailability()) {
1154 // Omitting a deprecated constant is ok; it should never materialize.
1155 case AR_Unavailable:
1158 case AR_NotYetIntroduced:
1159 // Partially available enum constants should be present. Note that we
1160 // suppress -Wunguarded-availability diagnostics for such uses.
1165 if (EI->second->hasAttr<UnusedAttr>())
1168 // Drop unneeded case values
1169 while (CI != CaseVals.end() && CI->first < EI->first)
1172 if (CI != CaseVals.end() && CI->first == EI->first)
1175 // Drop unneeded case ranges
1176 for (; RI != CaseRanges.end(); RI++) {
1178 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1179 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1180 if (EI->first <= Hi)
1184 if (RI == CaseRanges.end() || EI->first < RI->first) {
1185 hasCasesNotInSwitch = true;
1186 UnhandledNames.push_back(EI->second->getDeclName());
1190 if (TheDefaultStmt && UnhandledNames.empty() && ED->isClosedNonFlag())
1191 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
1193 // Produce a nice diagnostic if multiple values aren't handled.
1194 if (!UnhandledNames.empty()) {
1195 DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
1196 TheDefaultStmt ? diag::warn_def_missing_case
1197 : diag::warn_missing_case)
1198 << (int)UnhandledNames.size();
1200 for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
1202 DB << UnhandledNames[I];
1205 if (!hasCasesNotInSwitch)
1206 SS->setAllEnumCasesCovered();
1211 DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), BodyStmt,
1212 diag::warn_empty_switch_body);
1214 // FIXME: If the case list was broken is some way, we don't have a good system
1215 // to patch it up. Instead, just return the whole substmt as broken.
1216 if (CaseListIsErroneous)
1223 Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1225 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
1228 if (const EnumType *ET = DstType->getAs<EnumType>())
1229 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
1230 SrcType->isIntegerType()) {
1231 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1232 SrcExpr->isIntegerConstantExpr(Context)) {
1233 // Get the bitwidth of the enum value before promotions.
1234 unsigned DstWidth = Context.getIntWidth(DstType);
1235 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1237 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1238 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
1239 const EnumDecl *ED = ET->getDecl();
1241 if (!ED->isClosed())
1244 if (ED->hasAttr<FlagEnumAttr>()) {
1245 if (!IsValueInFlagEnum(ED, RhsVal, true))
1246 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1247 << DstType.getUnqualifiedType();
1249 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1251 EnumValsTy EnumVals;
1253 // Gather all enum values, set their type and sort them,
1254 // allowing easier comparison with rhs constant.
1255 for (auto *EDI : ED->enumerators()) {
1256 llvm::APSInt Val = EDI->getInitVal();
1257 AdjustAPSInt(Val, DstWidth, DstIsSigned);
1258 EnumVals.push_back(std::make_pair(Val, EDI));
1260 if (EnumVals.empty())
1262 llvm::stable_sort(EnumVals, CmpEnumVals);
1263 EnumValsTy::iterator EIend =
1264 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1266 // See which values aren't in the enum.
1267 EnumValsTy::const_iterator EI = EnumVals.begin();
1268 while (EI != EIend && EI->first < RhsVal)
1270 if (EI == EIend || EI->first != RhsVal) {
1271 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1272 << DstType.getUnqualifiedType();
1279 StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
1281 if (Cond.isInvalid())
1284 auto CondVal = Cond.get();
1285 CheckBreakContinueBinding(CondVal.second);
1287 if (CondVal.second &&
1288 !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc()))
1289 CommaVisitor(*this).Visit(CondVal.second);
1291 if (isa<NullStmt>(Body))
1292 getCurCompoundScope().setHasEmptyLoopBodies();
1294 return WhileStmt::Create(Context, CondVal.first, CondVal.second, Body,
1299 Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
1300 SourceLocation WhileLoc, SourceLocation CondLParen,
1301 Expr *Cond, SourceLocation CondRParen) {
1302 assert(Cond && "ActOnDoStmt(): missing expression");
1304 CheckBreakContinueBinding(Cond);
1305 ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond);
1306 if (CondResult.isInvalid())
1308 Cond = CondResult.get();
1310 CondResult = ActOnFinishFullExpr(Cond, DoLoc, /*DiscardedValue*/ false);
1311 if (CondResult.isInvalid())
1313 Cond = CondResult.get();
1315 // Only call the CommaVisitor for C89 due to differences in scope flags.
1316 if (Cond && !getLangOpts().C99 && !getLangOpts().CPlusPlus &&
1317 !Diags.isIgnored(diag::warn_comma_operator, Cond->getExprLoc()))
1318 CommaVisitor(*this).Visit(Cond);
1320 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
1324 // Use SetVector since the diagnostic cares about the ordering of the Decl's.
1325 using DeclSetVector =
1326 llvm::SetVector<VarDecl *, llvm::SmallVector<VarDecl *, 8>,
1327 llvm::SmallPtrSet<VarDecl *, 8>>;
1329 // This visitor will traverse a conditional statement and store all
1330 // the evaluated decls into a vector. Simple is set to true if none
1331 // of the excluded constructs are used.
1332 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1333 DeclSetVector &Decls;
1334 SmallVectorImpl<SourceRange> &Ranges;
1337 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1339 DeclExtractor(Sema &S, DeclSetVector &Decls,
1340 SmallVectorImpl<SourceRange> &Ranges) :
1341 Inherited(S.Context),
1346 bool isSimple() { return Simple; }
1348 // Replaces the method in EvaluatedExprVisitor.
1349 void VisitMemberExpr(MemberExpr* E) {
1353 // Any Stmt not whitelisted will cause the condition to be marked complex.
1354 void VisitStmt(Stmt *S) {
1358 void VisitBinaryOperator(BinaryOperator *E) {
1363 void VisitCastExpr(CastExpr *E) {
1364 Visit(E->getSubExpr());
1367 void VisitUnaryOperator(UnaryOperator *E) {
1368 // Skip checking conditionals with derefernces.
1369 if (E->getOpcode() == UO_Deref)
1372 Visit(E->getSubExpr());
1375 void VisitConditionalOperator(ConditionalOperator *E) {
1376 Visit(E->getCond());
1377 Visit(E->getTrueExpr());
1378 Visit(E->getFalseExpr());
1381 void VisitParenExpr(ParenExpr *E) {
1382 Visit(E->getSubExpr());
1385 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1386 Visit(E->getOpaqueValue()->getSourceExpr());
1387 Visit(E->getFalseExpr());
1390 void VisitIntegerLiteral(IntegerLiteral *E) { }
1391 void VisitFloatingLiteral(FloatingLiteral *E) { }
1392 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1393 void VisitCharacterLiteral(CharacterLiteral *E) { }
1394 void VisitGNUNullExpr(GNUNullExpr *E) { }
1395 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1397 void VisitDeclRefExpr(DeclRefExpr *E) {
1398 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1400 // Don't allow unhandled Decl types.
1405 Ranges.push_back(E->getSourceRange());
1410 }; // end class DeclExtractor
1412 // DeclMatcher checks to see if the decls are used in a non-evaluated
1414 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1415 DeclSetVector &Decls;
1419 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1421 DeclMatcher(Sema &S, DeclSetVector &Decls, Stmt *Statement) :
1422 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1423 if (!Statement) return;
1428 void VisitReturnStmt(ReturnStmt *S) {
1432 void VisitBreakStmt(BreakStmt *S) {
1436 void VisitGotoStmt(GotoStmt *S) {
1440 void VisitCastExpr(CastExpr *E) {
1441 if (E->getCastKind() == CK_LValueToRValue)
1442 CheckLValueToRValueCast(E->getSubExpr());
1444 Visit(E->getSubExpr());
1447 void CheckLValueToRValueCast(Expr *E) {
1448 E = E->IgnoreParenImpCasts();
1450 if (isa<DeclRefExpr>(E)) {
1454 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1455 Visit(CO->getCond());
1456 CheckLValueToRValueCast(CO->getTrueExpr());
1457 CheckLValueToRValueCast(CO->getFalseExpr());
1461 if (BinaryConditionalOperator *BCO =
1462 dyn_cast<BinaryConditionalOperator>(E)) {
1463 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1464 CheckLValueToRValueCast(BCO->getFalseExpr());
1471 void VisitDeclRefExpr(DeclRefExpr *E) {
1472 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1473 if (Decls.count(VD))
1477 void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
1478 // Only need to visit the semantics for POE.
1479 // SyntaticForm doesn't really use the Decal.
1480 for (auto *S : POE->semantics()) {
1481 if (auto *OVE = dyn_cast<OpaqueValueExpr>(S))
1482 // Look past the OVE into the expression it binds.
1483 Visit(OVE->getSourceExpr());
1489 bool FoundDeclInUse() { return FoundDecl; }
1491 }; // end class DeclMatcher
1493 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1494 Expr *Third, Stmt *Body) {
1495 // Condition is empty
1496 if (!Second) return;
1498 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1499 Second->getBeginLoc()))
1502 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1503 DeclSetVector Decls;
1504 SmallVector<SourceRange, 10> Ranges;
1505 DeclExtractor DE(S, Decls, Ranges);
1508 // Don't analyze complex conditionals.
1509 if (!DE.isSimple()) return;
1512 if (Decls.size() == 0) return;
1514 // Don't warn on volatile, static, or global variables.
1515 for (auto *VD : Decls)
1516 if (VD->getType().isVolatileQualified() || VD->hasGlobalStorage())
1519 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1520 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1521 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1524 // Load decl names into diagnostic.
1525 if (Decls.size() > 4) {
1528 PDiag << (unsigned)Decls.size();
1529 for (auto *VD : Decls)
1530 PDiag << VD->getDeclName();
1533 for (auto Range : Ranges)
1536 S.Diag(Ranges.begin()->getBegin(), PDiag);
1539 // If Statement is an incemement or decrement, return true and sets the
1540 // variables Increment and DRE.
1541 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1542 DeclRefExpr *&DRE) {
1543 if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement))
1544 if (!Cleanups->cleanupsHaveSideEffects())
1545 Statement = Cleanups->getSubExpr();
1547 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1548 switch (UO->getOpcode()) {
1549 default: return false;
1559 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1563 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1564 FunctionDecl *FD = Call->getDirectCallee();
1565 if (!FD || !FD->isOverloadedOperator()) return false;
1566 switch (FD->getOverloadedOperator()) {
1567 default: return false;
1575 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1582 // A visitor to determine if a continue or break statement is a
1584 class BreakContinueFinder : public ConstEvaluatedExprVisitor<BreakContinueFinder> {
1585 SourceLocation BreakLoc;
1586 SourceLocation ContinueLoc;
1587 bool InSwitch = false;
1590 BreakContinueFinder(Sema &S, const Stmt* Body) :
1591 Inherited(S.Context) {
1595 typedef ConstEvaluatedExprVisitor<BreakContinueFinder> Inherited;
1597 void VisitContinueStmt(const ContinueStmt* E) {
1598 ContinueLoc = E->getContinueLoc();
1601 void VisitBreakStmt(const BreakStmt* E) {
1603 BreakLoc = E->getBreakLoc();
1606 void VisitSwitchStmt(const SwitchStmt* S) {
1607 if (const Stmt *Init = S->getInit())
1609 if (const Stmt *CondVar = S->getConditionVariableDeclStmt())
1611 if (const Stmt *Cond = S->getCond())
1614 // Don't return break statements from the body of a switch.
1616 if (const Stmt *Body = S->getBody())
1621 void VisitForStmt(const ForStmt *S) {
1622 // Only visit the init statement of a for loop; the body
1623 // has a different break/continue scope.
1624 if (const Stmt *Init = S->getInit())
1628 void VisitWhileStmt(const WhileStmt *) {
1629 // Do nothing; the children of a while loop have a different
1630 // break/continue scope.
1633 void VisitDoStmt(const DoStmt *) {
1634 // Do nothing; the children of a while loop have a different
1635 // break/continue scope.
1638 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
1639 // Only visit the initialization of a for loop; the body
1640 // has a different break/continue scope.
1641 if (const Stmt *Init = S->getInit())
1643 if (const Stmt *Range = S->getRangeStmt())
1645 if (const Stmt *Begin = S->getBeginStmt())
1647 if (const Stmt *End = S->getEndStmt())
1651 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
1652 // Only visit the initialization of a for loop; the body
1653 // has a different break/continue scope.
1654 if (const Stmt *Element = S->getElement())
1656 if (const Stmt *Collection = S->getCollection())
1660 bool ContinueFound() { return ContinueLoc.isValid(); }
1661 bool BreakFound() { return BreakLoc.isValid(); }
1662 SourceLocation GetContinueLoc() { return ContinueLoc; }
1663 SourceLocation GetBreakLoc() { return BreakLoc; }
1665 }; // end class BreakContinueFinder
1667 // Emit a warning when a loop increment/decrement appears twice per loop
1668 // iteration. The conditions which trigger this warning are:
1669 // 1) The last statement in the loop body and the third expression in the
1670 // for loop are both increment or both decrement of the same variable
1671 // 2) No continue statements in the loop body.
1672 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1673 // Return when there is nothing to check.
1674 if (!Body || !Third) return;
1676 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1677 Third->getBeginLoc()))
1680 // Get the last statement from the loop body.
1681 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1682 if (!CS || CS->body_empty()) return;
1683 Stmt *LastStmt = CS->body_back();
1684 if (!LastStmt) return;
1686 bool LoopIncrement, LastIncrement;
1687 DeclRefExpr *LoopDRE, *LastDRE;
1689 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1690 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1692 // Check that the two statements are both increments or both decrements
1693 // on the same variable.
1694 if (LoopIncrement != LastIncrement ||
1695 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1697 if (BreakContinueFinder(S, Body).ContinueFound()) return;
1699 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1700 << LastDRE->getDecl() << LastIncrement;
1701 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1708 void Sema::CheckBreakContinueBinding(Expr *E) {
1709 if (!E || getLangOpts().CPlusPlus)
1711 BreakContinueFinder BCFinder(*this, E);
1712 Scope *BreakParent = CurScope->getBreakParent();
1713 if (BCFinder.BreakFound() && BreakParent) {
1714 if (BreakParent->getFlags() & Scope::SwitchScope) {
1715 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1717 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1720 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1721 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1726 StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1727 Stmt *First, ConditionResult Second,
1728 FullExprArg third, SourceLocation RParenLoc,
1730 if (Second.isInvalid())
1733 if (!getLangOpts().CPlusPlus) {
1734 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
1735 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1736 // declare identifiers for objects having storage class 'auto' or
1738 for (auto *DI : DS->decls()) {
1739 VarDecl *VD = dyn_cast<VarDecl>(DI);
1740 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
1743 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1744 DI->setInvalidDecl();
1750 CheckBreakContinueBinding(Second.get().second);
1751 CheckBreakContinueBinding(third.get());
1753 if (!Second.get().first)
1754 CheckForLoopConditionalStatement(*this, Second.get().second, third.get(),
1756 CheckForRedundantIteration(*this, third.get(), Body);
1758 if (Second.get().second &&
1759 !Diags.isIgnored(diag::warn_comma_operator,
1760 Second.get().second->getExprLoc()))
1761 CommaVisitor(*this).Visit(Second.get().second);
1763 Expr *Third = third.release().getAs<Expr>();
1764 if (isa<NullStmt>(Body))
1765 getCurCompoundScope().setHasEmptyLoopBodies();
1767 return new (Context)
1768 ForStmt(Context, First, Second.get().second, Second.get().first, Third,
1769 Body, ForLoc, LParenLoc, RParenLoc);
1772 /// In an Objective C collection iteration statement:
1774 /// x can be an arbitrary l-value expression. Bind it up as a
1775 /// full-expression.
1776 StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
1777 // Reduce placeholder expressions here. Note that this rejects the
1778 // use of pseudo-object l-values in this position.
1779 ExprResult result = CheckPlaceholderExpr(E);
1780 if (result.isInvalid()) return StmtError();
1783 ExprResult FullExpr = ActOnFinishFullExpr(E, /*DiscardedValue*/ false);
1784 if (FullExpr.isInvalid())
1786 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
1790 Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1794 ExprResult result = CorrectDelayedTyposInExpr(collection);
1795 if (!result.isUsable())
1797 collection = result.get();
1799 // Bail out early if we've got a type-dependent expression.
1800 if (collection->isTypeDependent()) return collection;
1802 // Perform normal l-value conversion.
1803 result = DefaultFunctionArrayLvalueConversion(collection);
1804 if (result.isInvalid())
1806 collection = result.get();
1808 // The operand needs to have object-pointer type.
1809 // TODO: should we do a contextual conversion?
1810 const ObjCObjectPointerType *pointerType =
1811 collection->getType()->getAs<ObjCObjectPointerType>();
1813 return Diag(forLoc, diag::err_collection_expr_type)
1814 << collection->getType() << collection->getSourceRange();
1816 // Check that the operand provides
1817 // - countByEnumeratingWithState:objects:count:
1818 const ObjCObjectType *objectType = pointerType->getObjectType();
1819 ObjCInterfaceDecl *iface = objectType->getInterface();
1821 // If we have a forward-declared type, we can't do this check.
1822 // Under ARC, it is an error not to have a forward-declared class.
1824 (getLangOpts().ObjCAutoRefCount
1825 ? RequireCompleteType(forLoc, QualType(objectType, 0),
1826 diag::err_arc_collection_forward, collection)
1827 : !isCompleteType(forLoc, QualType(objectType, 0)))) {
1828 // Otherwise, if we have any useful type information, check that
1829 // the type declares the appropriate method.
1830 } else if (iface || !objectType->qual_empty()) {
1831 IdentifierInfo *selectorIdents[] = {
1832 &Context.Idents.get("countByEnumeratingWithState"),
1833 &Context.Idents.get("objects"),
1834 &Context.Idents.get("count")
1836 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1838 ObjCMethodDecl *method = nullptr;
1840 // If there's an interface, look in both the public and private APIs.
1842 method = iface->lookupInstanceMethod(selector);
1843 if (!method) method = iface->lookupPrivateMethod(selector);
1846 // Also check protocol qualifiers.
1848 method = LookupMethodInQualifiedType(selector, pointerType,
1851 // If we didn't find it anywhere, give up.
1853 Diag(forLoc, diag::warn_collection_expr_type)
1854 << collection->getType() << selector << collection->getSourceRange();
1857 // TODO: check for an incompatible signature?
1860 // Wrap up any cleanups in the expression.
1865 Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1866 Stmt *First, Expr *collection,
1867 SourceLocation RParenLoc) {
1868 setFunctionHasBranchProtectedScope();
1870 ExprResult CollectionExprResult =
1871 CheckObjCForCollectionOperand(ForLoc, collection);
1875 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
1876 if (!DS->isSingleDecl())
1877 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1878 diag::err_toomany_element_decls));
1880 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1881 if (!D || D->isInvalidDecl())
1884 FirstType = D->getType();
1885 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1886 // declare identifiers for objects having storage class 'auto' or
1888 if (!D->hasLocalStorage())
1889 return StmtError(Diag(D->getLocation(),
1890 diag::err_non_local_variable_decl_in_for));
1892 // If the type contained 'auto', deduce the 'auto' to 'id'.
1893 if (FirstType->getContainedAutoType()) {
1894 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1896 Expr *DeducedInit = &OpaqueId;
1897 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1899 DiagnoseAutoDeductionFailure(D, DeducedInit);
1900 if (FirstType.isNull()) {
1901 D->setInvalidDecl();
1905 D->setType(FirstType);
1907 if (!inTemplateInstantiation()) {
1908 SourceLocation Loc =
1909 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
1910 Diag(Loc, diag::warn_auto_var_is_id)
1911 << D->getDeclName();
1916 Expr *FirstE = cast<Expr>(First);
1917 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
1919 Diag(First->getBeginLoc(), diag::err_selector_element_not_lvalue)
1920 << First->getSourceRange());
1922 FirstType = static_cast<Expr*>(First)->getType();
1923 if (FirstType.isConstQualified())
1924 Diag(ForLoc, diag::err_selector_element_const_type)
1925 << FirstType << First->getSourceRange();
1927 if (!FirstType->isDependentType() &&
1928 !FirstType->isObjCObjectPointerType() &&
1929 !FirstType->isBlockPointerType())
1930 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1931 << FirstType << First->getSourceRange());
1934 if (CollectionExprResult.isInvalid())
1937 CollectionExprResult =
1938 ActOnFinishFullExpr(CollectionExprResult.get(), /*DiscardedValue*/ false);
1939 if (CollectionExprResult.isInvalid())
1942 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1943 nullptr, ForLoc, RParenLoc);
1946 /// Finish building a variable declaration for a for-range statement.
1947 /// \return true if an error occurs.
1948 static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1949 SourceLocation Loc, int DiagID) {
1950 if (Decl->getType()->isUndeducedType()) {
1951 ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
1952 if (!Res.isUsable()) {
1953 Decl->setInvalidDecl();
1959 // Deduce the type for the iterator variable now rather than leaving it to
1960 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1962 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
1963 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
1965 SemaRef.Diag(Loc, DiagID) << Init->getType();
1966 if (InitType.isNull()) {
1967 Decl->setInvalidDecl();
1970 Decl->setType(InitType);
1972 // In ARC, infer lifetime.
1973 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1974 // we're doing the equivalent of fast iteration.
1975 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1976 SemaRef.inferObjCARCLifetime(Decl))
1977 Decl->setInvalidDecl();
1979 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false);
1980 SemaRef.FinalizeDeclaration(Decl);
1981 SemaRef.CurContext->addHiddenDecl(Decl);
1986 // An enum to represent whether something is dealing with a call to begin()
1987 // or a call to end() in a range-based for loop.
1988 enum BeginEndFunction {
1993 /// Produce a note indicating which begin/end function was implicitly called
1994 /// by a C++11 for-range statement. This is often not obvious from the code,
1995 /// nor from the diagnostics produced when analysing the implicit expressions
1996 /// required in a for-range statement.
1997 void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
1998 BeginEndFunction BEF) {
1999 CallExpr *CE = dyn_cast<CallExpr>(E);
2002 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
2005 SourceLocation Loc = D->getLocation();
2007 std::string Description;
2008 bool IsTemplate = false;
2009 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
2010 Description = SemaRef.getTemplateArgumentBindingsText(
2011 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
2015 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
2016 << BEF << IsTemplate << Description << E->getType();
2019 /// Build a variable declaration for a for-range statement.
2020 VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
2021 QualType Type, StringRef Name) {
2022 DeclContext *DC = SemaRef.CurContext;
2023 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
2024 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
2025 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
2027 Decl->setImplicit();
2033 static bool ObjCEnumerationCollection(Expr *Collection) {
2034 return !Collection->isTypeDependent()
2035 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
2038 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
2040 /// C++11 [stmt.ranged]:
2041 /// A range-based for statement is equivalent to
2044 /// auto && __range = range-init;
2045 /// for ( auto __begin = begin-expr,
2046 /// __end = end-expr;
2047 /// __begin != __end;
2049 /// for-range-declaration = *__begin;
2054 /// The body of the loop is not available yet, since it cannot be analysed until
2055 /// we have determined the type of the for-range-declaration.
2056 StmtResult Sema::ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
2057 SourceLocation CoawaitLoc, Stmt *InitStmt,
2058 Stmt *First, SourceLocation ColonLoc,
2059 Expr *Range, SourceLocation RParenLoc,
2060 BuildForRangeKind Kind) {
2064 if (Range && ObjCEnumerationCollection(Range)) {
2065 // FIXME: Support init-statements in Objective-C++20 ranged for statement.
2067 return Diag(InitStmt->getBeginLoc(), diag::err_objc_for_range_init_stmt)
2068 << InitStmt->getSourceRange();
2069 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
2072 DeclStmt *DS = dyn_cast<DeclStmt>(First);
2073 assert(DS && "first part of for range not a decl stmt");
2075 if (!DS->isSingleDecl()) {
2076 Diag(DS->getBeginLoc(), diag::err_type_defined_in_for_range);
2080 Decl *LoopVar = DS->getSingleDecl();
2081 if (LoopVar->isInvalidDecl() || !Range ||
2082 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
2083 LoopVar->setInvalidDecl();
2087 // Build the coroutine state immediately and not later during template
2089 if (!CoawaitLoc.isInvalid()) {
2090 if (!ActOnCoroutineBodyStart(S, CoawaitLoc, "co_await"))
2094 // Build auto && __range = range-init
2095 // Divide by 2, since the variables are in the inner scope (loop body).
2096 const auto DepthStr = std::to_string(S->getDepth() / 2);
2097 SourceLocation RangeLoc = Range->getBeginLoc();
2098 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
2099 Context.getAutoRRefDeductType(),
2100 std::string("__range") + DepthStr);
2101 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
2102 diag::err_for_range_deduction_failure)) {
2103 LoopVar->setInvalidDecl();
2107 // Claim the type doesn't contain auto: we've already done the checking.
2108 DeclGroupPtrTy RangeGroup =
2109 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1));
2110 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
2111 if (RangeDecl.isInvalid()) {
2112 LoopVar->setInvalidDecl();
2116 return BuildCXXForRangeStmt(
2117 ForLoc, CoawaitLoc, InitStmt, ColonLoc, RangeDecl.get(),
2118 /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
2119 /*Cond=*/nullptr, /*Inc=*/nullptr, DS, RParenLoc, Kind);
2122 /// Create the initialization, compare, and increment steps for
2123 /// the range-based for loop expression.
2124 /// This function does not handle array-based for loops,
2125 /// which are created in Sema::BuildCXXForRangeStmt.
2127 /// \returns a ForRangeStatus indicating success or what kind of error occurred.
2128 /// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2129 /// CandidateSet and BEF are set and some non-success value is returned on
2131 static Sema::ForRangeStatus
2132 BuildNonArrayForRange(Sema &SemaRef, Expr *BeginRange, Expr *EndRange,
2133 QualType RangeType, VarDecl *BeginVar, VarDecl *EndVar,
2134 SourceLocation ColonLoc, SourceLocation CoawaitLoc,
2135 OverloadCandidateSet *CandidateSet, ExprResult *BeginExpr,
2136 ExprResult *EndExpr, BeginEndFunction *BEF) {
2137 DeclarationNameInfo BeginNameInfo(
2138 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2139 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2142 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2143 Sema::LookupMemberName);
2144 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2146 auto BuildBegin = [&] {
2148 Sema::ForRangeStatus RangeStatus =
2149 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
2150 BeginMemberLookup, CandidateSet,
2151 BeginRange, BeginExpr);
2153 if (RangeStatus != Sema::FRS_Success) {
2154 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2155 SemaRef.Diag(BeginRange->getBeginLoc(), diag::note_in_for_range)
2156 << ColonLoc << BEF_begin << BeginRange->getType();
2159 if (!CoawaitLoc.isInvalid()) {
2160 // FIXME: getCurScope() should not be used during template instantiation.
2161 // We should pick up the set of unqualified lookup results for operator
2162 // co_await during the initial parse.
2163 *BeginExpr = SemaRef.ActOnCoawaitExpr(SemaRef.getCurScope(), ColonLoc,
2165 if (BeginExpr->isInvalid())
2166 return Sema::FRS_DiagnosticIssued;
2168 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2169 diag::err_for_range_iter_deduction_failure)) {
2170 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2171 return Sema::FRS_DiagnosticIssued;
2173 return Sema::FRS_Success;
2176 auto BuildEnd = [&] {
2178 Sema::ForRangeStatus RangeStatus =
2179 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
2180 EndMemberLookup, CandidateSet,
2182 if (RangeStatus != Sema::FRS_Success) {
2183 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2184 SemaRef.Diag(EndRange->getBeginLoc(), diag::note_in_for_range)
2185 << ColonLoc << BEF_end << EndRange->getType();
2188 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2189 diag::err_for_range_iter_deduction_failure)) {
2190 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2191 return Sema::FRS_DiagnosticIssued;
2193 return Sema::FRS_Success;
2196 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2197 // - if _RangeT is a class type, the unqualified-ids begin and end are
2198 // looked up in the scope of class _RangeT as if by class member access
2199 // lookup (3.4.5), and if either (or both) finds at least one
2200 // declaration, begin-expr and end-expr are __range.begin() and
2201 // __range.end(), respectively;
2202 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2203 if (BeginMemberLookup.isAmbiguous())
2204 return Sema::FRS_DiagnosticIssued;
2206 SemaRef.LookupQualifiedName(EndMemberLookup, D);
2207 if (EndMemberLookup.isAmbiguous())
2208 return Sema::FRS_DiagnosticIssued;
2210 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2211 // Look up the non-member form of the member we didn't find, first.
2212 // This way we prefer a "no viable 'end'" diagnostic over a "i found
2213 // a 'begin' but ignored it because there was no member 'end'"
2215 auto BuildNonmember = [&](
2216 BeginEndFunction BEFFound, LookupResult &Found,
2217 llvm::function_ref<Sema::ForRangeStatus()> BuildFound,
2218 llvm::function_ref<Sema::ForRangeStatus()> BuildNotFound) {
2219 LookupResult OldFound = std::move(Found);
2222 if (Sema::ForRangeStatus Result = BuildNotFound())
2225 switch (BuildFound()) {
2226 case Sema::FRS_Success:
2227 return Sema::FRS_Success;
2229 case Sema::FRS_NoViableFunction:
2230 CandidateSet->NoteCandidates(
2231 PartialDiagnosticAt(BeginRange->getBeginLoc(),
2232 SemaRef.PDiag(diag::err_for_range_invalid)
2233 << BeginRange->getType() << BEFFound),
2234 SemaRef, OCD_AllCandidates, BeginRange);
2237 case Sema::FRS_DiagnosticIssued:
2238 for (NamedDecl *D : OldFound) {
2239 SemaRef.Diag(D->getLocation(),
2240 diag::note_for_range_member_begin_end_ignored)
2241 << BeginRange->getType() << BEFFound;
2243 return Sema::FRS_DiagnosticIssued;
2245 llvm_unreachable("unexpected ForRangeStatus");
2247 if (BeginMemberLookup.empty())
2248 return BuildNonmember(BEF_end, EndMemberLookup, BuildEnd, BuildBegin);
2249 return BuildNonmember(BEF_begin, BeginMemberLookup, BuildBegin, BuildEnd);
2252 // - otherwise, begin-expr and end-expr are begin(__range) and
2253 // end(__range), respectively, where begin and end are looked up with
2254 // argument-dependent lookup (3.4.2). For the purposes of this name
2255 // lookup, namespace std is an associated namespace.
2258 if (Sema::ForRangeStatus Result = BuildBegin())
2263 /// Speculatively attempt to dereference an invalid range expression.
2264 /// If the attempt fails, this function will return a valid, null StmtResult
2265 /// and emit no diagnostics.
2266 static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2267 SourceLocation ForLoc,
2268 SourceLocation CoawaitLoc,
2271 SourceLocation ColonLoc,
2273 SourceLocation RangeLoc,
2274 SourceLocation RParenLoc) {
2275 // Determine whether we can rebuild the for-range statement with a
2276 // dereferenced range expression.
2277 ExprResult AdjustedRange;
2279 Sema::SFINAETrap Trap(SemaRef);
2281 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2282 if (AdjustedRange.isInvalid())
2283 return StmtResult();
2285 StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
2286 S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
2287 AdjustedRange.get(), RParenLoc, Sema::BFRK_Check);
2289 return StmtResult();
2292 // The attempt to dereference worked well enough that it could produce a valid
2293 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2294 // case there are any other (non-fatal) problems with it.
2295 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2296 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
2297 return SemaRef.ActOnCXXForRangeStmt(
2298 S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
2299 AdjustedRange.get(), RParenLoc, Sema::BFRK_Rebuild);
2303 /// RAII object to automatically invalidate a declaration if an error occurs.
2304 struct InvalidateOnErrorScope {
2305 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2306 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2307 ~InvalidateOnErrorScope() {
2308 if (Enabled && Trap.hasErrorOccurred())
2309 D->setInvalidDecl();
2312 DiagnosticErrorTrap Trap;
2318 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
2319 StmtResult Sema::BuildCXXForRangeStmt(SourceLocation ForLoc,
2320 SourceLocation CoawaitLoc, Stmt *InitStmt,
2321 SourceLocation ColonLoc, Stmt *RangeDecl,
2322 Stmt *Begin, Stmt *End, Expr *Cond,
2323 Expr *Inc, Stmt *LoopVarDecl,
2324 SourceLocation RParenLoc,
2325 BuildForRangeKind Kind) {
2326 // FIXME: This should not be used during template instantiation. We should
2327 // pick up the set of unqualified lookup results for the != and + operators
2328 // in the initial parse.
2330 // Testcase (accepts-invalid):
2331 // template<typename T> void f() { for (auto x : T()) {} }
2332 // namespace N { struct X { X begin(); X end(); int operator*(); }; }
2333 // bool operator!=(N::X, N::X); void operator++(N::X);
2334 // void g() { f<N::X>(); }
2335 Scope *S = getCurScope();
2337 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2338 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2339 QualType RangeVarType = RangeVar->getType();
2341 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2342 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2344 // If we hit any errors, mark the loop variable as invalid if its type
2346 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2347 LoopVar->getType()->isUndeducedType());
2349 StmtResult BeginDeclStmt = Begin;
2350 StmtResult EndDeclStmt = End;
2351 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2353 if (RangeVarType->isDependentType()) {
2354 // The range is implicitly used as a placeholder when it is dependent.
2355 RangeVar->markUsed(Context);
2357 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2358 // them in properly when we instantiate the loop.
2359 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2360 if (auto *DD = dyn_cast<DecompositionDecl>(LoopVar))
2361 for (auto *Binding : DD->bindings())
2362 Binding->setType(Context.DependentTy);
2363 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
2365 } else if (!BeginDeclStmt.get()) {
2366 SourceLocation RangeLoc = RangeVar->getLocation();
2368 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2370 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2371 VK_LValue, ColonLoc);
2372 if (BeginRangeRef.isInvalid())
2375 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2376 VK_LValue, ColonLoc);
2377 if (EndRangeRef.isInvalid())
2380 QualType AutoType = Context.getAutoDeductType();
2381 Expr *Range = RangeVar->getInit();
2384 QualType RangeType = Range->getType();
2386 if (RequireCompleteType(RangeLoc, RangeType,
2387 diag::err_for_range_incomplete_type))
2390 // Build auto __begin = begin-expr, __end = end-expr.
2391 // Divide by 2, since the variables are in the inner scope (loop body).
2392 const auto DepthStr = std::to_string(S->getDepth() / 2);
2393 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2394 std::string("__begin") + DepthStr);
2395 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2396 std::string("__end") + DepthStr);
2398 // Build begin-expr and end-expr and attach to __begin and __end variables.
2399 ExprResult BeginExpr, EndExpr;
2400 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2401 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2402 // __range + __bound, respectively, where __bound is the array bound. If
2403 // _RangeT is an array of unknown size or an array of incomplete type,
2404 // the program is ill-formed;
2406 // begin-expr is __range.
2407 BeginExpr = BeginRangeRef;
2408 if (!CoawaitLoc.isInvalid()) {
2409 BeginExpr = ActOnCoawaitExpr(S, ColonLoc, BeginExpr.get());
2410 if (BeginExpr.isInvalid())
2413 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
2414 diag::err_for_range_iter_deduction_failure)) {
2415 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2419 // Find the array bound.
2420 ExprResult BoundExpr;
2421 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
2422 BoundExpr = IntegerLiteral::Create(
2423 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
2424 else if (const VariableArrayType *VAT =
2425 dyn_cast<VariableArrayType>(UnqAT)) {
2426 // For a variably modified type we can't just use the expression within
2427 // the array bounds, since we don't want that to be re-evaluated here.
2428 // Rather, we need to determine what it was when the array was first
2429 // created - so we resort to using sizeof(vla)/sizeof(element).
2433 // b = -1; <-- This should not affect the num of iterations below
2434 // for (int &c : vla) { .. }
2437 // FIXME: This results in codegen generating IR that recalculates the
2438 // run-time number of elements (as opposed to just using the IR Value
2439 // that corresponds to the run-time value of each bound that was
2440 // generated when the array was created.) If this proves too embarrassing
2441 // even for unoptimized IR, consider passing a magic-value/cookie to
2442 // codegen that then knows to simply use that initial llvm::Value (that
2443 // corresponds to the bound at time of array creation) within
2444 // getelementptr. But be prepared to pay the price of increasing a
2445 // customized form of coupling between the two components - which could
2446 // be hard to maintain as the codebase evolves.
2448 ExprResult SizeOfVLAExprR = ActOnUnaryExprOrTypeTraitExpr(
2449 EndVar->getLocation(), UETT_SizeOf,
2451 CreateParsedType(VAT->desugar(), Context.getTrivialTypeSourceInfo(
2452 VAT->desugar(), RangeLoc))
2454 EndVar->getSourceRange());
2455 if (SizeOfVLAExprR.isInvalid())
2458 ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr(
2459 EndVar->getLocation(), UETT_SizeOf,
2461 CreateParsedType(VAT->desugar(),
2462 Context.getTrivialTypeSourceInfo(
2463 VAT->getElementType(), RangeLoc))
2465 EndVar->getSourceRange());
2466 if (SizeOfEachElementExprR.isInvalid())
2470 ActOnBinOp(S, EndVar->getLocation(), tok::slash,
2471 SizeOfVLAExprR.get(), SizeOfEachElementExprR.get());
2472 if (BoundExpr.isInvalid())
2476 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2477 // UnqAT is not incomplete and Range is not type-dependent.
2478 llvm_unreachable("Unexpected array type in for-range");
2481 // end-expr is __range + __bound.
2482 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
2484 if (EndExpr.isInvalid())
2486 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2487 diag::err_for_range_iter_deduction_failure)) {
2488 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2492 OverloadCandidateSet CandidateSet(RangeLoc,
2493 OverloadCandidateSet::CSK_Normal);
2494 BeginEndFunction BEFFailure;
2495 ForRangeStatus RangeStatus = BuildNonArrayForRange(
2496 *this, BeginRangeRef.get(), EndRangeRef.get(), RangeType, BeginVar,
2497 EndVar, ColonLoc, CoawaitLoc, &CandidateSet, &BeginExpr, &EndExpr,
2500 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
2501 BEFFailure == BEF_begin) {
2502 // If the range is being built from an array parameter, emit a
2503 // a diagnostic that it is being treated as a pointer.
2504 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2505 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2506 QualType ArrayTy = PVD->getOriginalType();
2507 QualType PointerTy = PVD->getType();
2508 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2509 Diag(Range->getBeginLoc(), diag::err_range_on_array_parameter)
2510 << RangeLoc << PVD << ArrayTy << PointerTy;
2511 Diag(PVD->getLocation(), diag::note_declared_at);
2517 // If building the range failed, try dereferencing the range expression
2518 // unless a diagnostic was issued or the end function is problematic.
2519 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2520 CoawaitLoc, InitStmt,
2521 LoopVarDecl, ColonLoc,
2524 if (SR.isInvalid() || SR.isUsable())
2528 // Otherwise, emit diagnostics if we haven't already.
2529 if (RangeStatus == FRS_NoViableFunction) {
2530 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
2531 CandidateSet.NoteCandidates(
2532 PartialDiagnosticAt(Range->getBeginLoc(),
2533 PDiag(diag::err_for_range_invalid)
2534 << RangeLoc << Range->getType()
2536 *this, OCD_AllCandidates, Range);
2538 // Return an error if no fix was discovered.
2539 if (RangeStatus != FRS_Success)
2543 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2544 "invalid range expression in for loop");
2546 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
2547 // C++1z removes this restriction.
2548 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2549 if (!Context.hasSameType(BeginType, EndType)) {
2550 Diag(RangeLoc, getLangOpts().CPlusPlus17
2551 ? diag::warn_for_range_begin_end_types_differ
2552 : diag::ext_for_range_begin_end_types_differ)
2553 << BeginType << EndType;
2554 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2555 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2559 ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
2561 ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
2563 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2564 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2565 VK_LValue, ColonLoc);
2566 if (BeginRef.isInvalid())
2569 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2570 VK_LValue, ColonLoc);
2571 if (EndRef.isInvalid())
2574 // Build and check __begin != __end expression.
2575 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2576 BeginRef.get(), EndRef.get());
2577 if (!NotEqExpr.isInvalid())
2578 NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get());
2579 if (!NotEqExpr.isInvalid())
2581 ActOnFinishFullExpr(NotEqExpr.get(), /*DiscardedValue*/ false);
2582 if (NotEqExpr.isInvalid()) {
2583 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2584 << RangeLoc << 0 << BeginRangeRef.get()->getType();
2585 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2586 if (!Context.hasSameType(BeginType, EndType))
2587 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2591 // Build and check ++__begin expression.
2592 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2593 VK_LValue, ColonLoc);
2594 if (BeginRef.isInvalid())
2597 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2598 if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
2599 // FIXME: getCurScope() should not be used during template instantiation.
2600 // We should pick up the set of unqualified lookup results for operator
2601 // co_await during the initial parse.
2602 IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
2603 if (!IncrExpr.isInvalid())
2604 IncrExpr = ActOnFinishFullExpr(IncrExpr.get(), /*DiscardedValue*/ false);
2605 if (IncrExpr.isInvalid()) {
2606 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2607 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
2608 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2612 // Build and check *__begin expression.
2613 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2614 VK_LValue, ColonLoc);
2615 if (BeginRef.isInvalid())
2618 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2619 if (DerefExpr.isInvalid()) {
2620 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2621 << RangeLoc << 1 << BeginRangeRef.get()->getType();
2622 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2626 // Attach *__begin as initializer for VD. Don't touch it if we're just
2627 // trying to determine whether this would be a valid range.
2628 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2629 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false);
2630 if (LoopVar->isInvalidDecl())
2631 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2635 // Don't bother to actually allocate the result if we're just trying to
2636 // determine whether it would be valid.
2637 if (Kind == BFRK_Check)
2638 return StmtResult();
2640 return new (Context) CXXForRangeStmt(
2641 InitStmt, RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
2642 cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
2643 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
2644 ColonLoc, RParenLoc);
2647 /// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
2649 StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2652 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
2654 ForStmt->setBody(B);
2658 // Warn when the loop variable is a const reference that creates a copy.
2659 // Suggest using the non-reference type for copies. If a copy can be prevented
2660 // suggest the const reference type that would do so.
2661 // For instance, given "for (const &Foo : Range)", suggest
2662 // "for (const Foo : Range)" to denote a copy is made for the loop. If
2663 // possible, also suggest "for (const &Bar : Range)" if this type prevents
2664 // the copy altogether.
2665 static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
2667 QualType RangeInitType) {
2668 const Expr *InitExpr = VD->getInit();
2672 QualType VariableType = VD->getType();
2674 if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr))
2675 if (!Cleanups->cleanupsHaveSideEffects())
2676 InitExpr = Cleanups->getSubExpr();
2678 const MaterializeTemporaryExpr *MTE =
2679 dyn_cast<MaterializeTemporaryExpr>(InitExpr);
2685 const Expr *E = MTE->GetTemporaryExpr()->IgnoreImpCasts();
2687 // Searching for either UnaryOperator for dereference of a pointer or
2688 // CXXOperatorCallExpr for handling iterators.
2689 while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
2690 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
2692 } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
2693 const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
2696 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
2697 E = MTE->GetTemporaryExpr();
2699 E = E->IgnoreImpCasts();
2702 bool ReturnsReference = false;
2703 if (isa<UnaryOperator>(E)) {
2704 ReturnsReference = true;
2706 const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
2707 const FunctionDecl *FD = Call->getDirectCallee();
2708 QualType ReturnType = FD->getReturnType();
2709 ReturnsReference = ReturnType->isReferenceType();
2712 if (ReturnsReference) {
2713 // Loop variable creates a temporary. Suggest either to go with
2714 // non-reference loop variable to indicate a copy is made, or
2715 // the correct time to bind a const reference.
2716 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy)
2717 << VD << VariableType << E->getType();
2718 QualType NonReferenceType = VariableType.getNonReferenceType();
2719 NonReferenceType.removeLocalConst();
2720 QualType NewReferenceType =
2721 SemaRef.Context.getLValueReferenceType(E->getType().withConst());
2722 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_type_or_non_reference)
2723 << NonReferenceType << NewReferenceType << VD->getSourceRange();
2725 // The range always returns a copy, so a temporary is always created.
2726 // Suggest removing the reference from the loop variable.
2727 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy)
2728 << VD << RangeInitType;
2729 QualType NonReferenceType = VariableType.getNonReferenceType();
2730 NonReferenceType.removeLocalConst();
2731 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_non_reference_type)
2732 << NonReferenceType << VD->getSourceRange();
2736 // Warns when the loop variable can be changed to a reference type to
2737 // prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
2738 // "for (const Foo &x : Range)" if this form does not make a copy.
2739 static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
2740 const VarDecl *VD) {
2741 const Expr *InitExpr = VD->getInit();
2745 QualType VariableType = VD->getType();
2747 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
2748 if (!CE->getConstructor()->isCopyConstructor())
2750 } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
2751 if (CE->getCastKind() != CK_LValueToRValue)
2757 // TODO: Determine a maximum size that a POD type can be before a diagnostic
2758 // should be emitted. Also, only ignore POD types with trivial copy
2760 if (VariableType.isPODType(SemaRef.Context))
2763 // Suggest changing from a const variable to a const reference variable
2764 // if doing so will prevent a copy.
2765 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
2766 << VD << VariableType << InitExpr->getType();
2767 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_reference_type)
2768 << SemaRef.Context.getLValueReferenceType(VariableType)
2769 << VD->getSourceRange();
2772 /// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
2773 /// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
2774 /// using "const foo x" to show that a copy is made
2775 /// 2) for (const bar &x : foos) where bar is a temporary initialized by bar.
2776 /// Suggest either "const bar x" to keep the copying or "const foo& x" to
2777 /// prevent the copy.
2778 /// 3) for (const foo x : foos) where x is constructed from a reference foo.
2779 /// Suggest "const foo &x" to prevent the copy.
2780 static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
2781 const CXXForRangeStmt *ForStmt) {
2782 if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy,
2783 ForStmt->getBeginLoc()) &&
2784 SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy,
2785 ForStmt->getBeginLoc()) &&
2786 SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
2787 ForStmt->getBeginLoc())) {
2791 const VarDecl *VD = ForStmt->getLoopVariable();
2795 QualType VariableType = VD->getType();
2797 if (VariableType->isIncompleteType())
2800 const Expr *InitExpr = VD->getInit();
2804 if (VariableType->isReferenceType()) {
2805 DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
2806 ForStmt->getRangeInit()->getType());
2807 } else if (VariableType.isConstQualified()) {
2808 DiagnoseForRangeConstVariableCopies(SemaRef, VD);
2812 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2813 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2814 /// body cannot be performed until after the type of the range variable is
2816 StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2820 if (isa<ObjCForCollectionStmt>(S))
2821 return FinishObjCForCollectionStmt(S, B);
2823 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2824 ForStmt->setBody(B);
2826 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2827 diag::warn_empty_range_based_for_body);
2829 DiagnoseForRangeVariableCopies(*this, ForStmt);
2834 StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2835 SourceLocation LabelLoc,
2836 LabelDecl *TheDecl) {
2837 setFunctionHasBranchIntoScope();
2838 TheDecl->markUsed(Context);
2839 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
2843 Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
2845 // Convert operand to void*
2846 if (!E->isTypeDependent()) {
2847 QualType ETy = E->getType();
2848 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
2849 ExprResult ExprRes = E;
2850 AssignConvertType ConvTy =
2851 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2852 if (ExprRes.isInvalid())
2855 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
2859 ExprResult ExprRes = ActOnFinishFullExpr(E, /*DiscardedValue*/ false);
2860 if (ExprRes.isInvalid())
2864 setFunctionHasIndirectGoto();
2866 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
2869 static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
2870 const Scope &DestScope) {
2871 if (!S.CurrentSEHFinally.empty() &&
2872 DestScope.Contains(*S.CurrentSEHFinally.back())) {
2873 S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
2878 Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
2879 Scope *S = CurScope->getContinueParent();
2881 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
2882 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
2884 CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
2886 return new (Context) ContinueStmt(ContinueLoc);
2890 Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
2891 Scope *S = CurScope->getBreakParent();
2893 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
2894 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
2896 if (S->isOpenMPLoopScope())
2897 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2899 CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
2901 return new (Context) BreakStmt(BreakLoc);
2904 /// Determine whether the given expression is a candidate for
2905 /// copy elision in either a return statement or a throw expression.
2907 /// \param ReturnType If we're determining the copy elision candidate for
2908 /// a return statement, this is the return type of the function. If we're
2909 /// determining the copy elision candidate for a throw expression, this will
2912 /// \param E The expression being returned from the function or block, or
2915 /// \param CESK Whether we allow function parameters or
2916 /// id-expressions that could be moved out of the function to be considered NRVO
2917 /// candidates. C++ prohibits these for NRVO itself, but we re-use this logic to
2918 /// determine whether we should try to move as part of a return or throw (which
2919 /// does allow function parameters).
2921 /// \returns The NRVO candidate variable, if the return statement may use the
2922 /// NRVO, or NULL if there is no such candidate.
2923 VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, Expr *E,
2924 CopyElisionSemanticsKind CESK) {
2925 // - in a return statement in a function [where] ...
2926 // ... the expression is the name of a non-volatile automatic object ...
2927 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
2928 if (!DR || DR->refersToEnclosingVariableOrCapture())
2930 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2934 if (isCopyElisionCandidate(ReturnType, VD, CESK))
2939 bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
2940 CopyElisionSemanticsKind CESK) {
2941 QualType VDType = VD->getType();
2942 // - in a return statement in a function with ...
2943 // ... a class return type ...
2944 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
2945 if (!ReturnType->isRecordType())
2947 // ... the same cv-unqualified type as the function return type ...
2948 // When considering moving this expression out, allow dissimilar types.
2949 if (!(CESK & CES_AllowDifferentTypes) && !VDType->isDependentType() &&
2950 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2954 // ...object (other than a function or catch-clause parameter)...
2955 if (VD->getKind() != Decl::Var &&
2956 !((CESK & CES_AllowParameters) && VD->getKind() == Decl::ParmVar))
2958 if (!(CESK & CES_AllowExceptionVariables) && VD->isExceptionVariable())
2962 if (!VD->hasLocalStorage()) return false;
2964 // Return false if VD is a __block variable. We don't want to implicitly move
2965 // out of a __block variable during a return because we cannot assume the
2966 // variable will no longer be used.
2967 if (VD->hasAttr<BlocksAttr>()) return false;
2969 if (CESK & CES_AllowDifferentTypes)
2972 // ...non-volatile...
2973 if (VD->getType().isVolatileQualified()) return false;
2975 // Variables with higher required alignment than their type's ABI
2976 // alignment cannot use NRVO.
2977 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
2978 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2984 /// Try to perform the initialization of a potentially-movable value,
2985 /// which is the operand to a return or throw statement.
2987 /// This routine implements C++14 [class.copy]p32, which attempts to treat
2988 /// returned lvalues as rvalues in certain cases (to prefer move construction),
2989 /// then falls back to treating them as lvalues if that failed.
2991 /// \param ConvertingConstructorsOnly If true, follow [class.copy]p32 and reject
2992 /// resolutions that find non-constructors, such as derived-to-base conversions
2993 /// or `operator T()&&` member functions. If false, do consider such
2994 /// conversion sequences.
2996 /// \param Res We will fill this in if move-initialization was possible.
2997 /// If move-initialization is not possible, such that we must fall back to
2998 /// treating the operand as an lvalue, we will leave Res in its original
3000 static void TryMoveInitialization(Sema& S,
3001 const InitializedEntity &Entity,
3002 const VarDecl *NRVOCandidate,
3003 QualType ResultType,
3005 bool ConvertingConstructorsOnly,
3007 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(),
3008 CK_NoOp, Value, VK_XValue);
3010 Expr *InitExpr = &AsRvalue;
3012 InitializationKind Kind = InitializationKind::CreateCopy(
3013 Value->getBeginLoc(), Value->getBeginLoc());
3015 InitializationSequence Seq(S, Entity, Kind, InitExpr);
3020 for (const InitializationSequence::Step &Step : Seq.steps()) {
3021 if (Step.Kind != InitializationSequence::SK_ConstructorInitialization &&
3022 Step.Kind != InitializationSequence::SK_UserConversion)
3025 FunctionDecl *FD = Step.Function.Function;
3026 if (ConvertingConstructorsOnly) {
3027 if (isa<CXXConstructorDecl>(FD)) {
3028 // C++14 [class.copy]p32:
3029 // [...] If the first overload resolution fails or was not performed,
3030 // or if the type of the first parameter of the selected constructor
3031 // is not an rvalue reference to the object's type (possibly
3032 // cv-qualified), overload resolution is performed again, considering
3033 // the object as an lvalue.
3034 const RValueReferenceType *RRefType =
3035 FD->getParamDecl(0)->getType()->getAs<RValueReferenceType>();
3038 if (!S.Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
3039 NRVOCandidate->getType()))
3045 if (isa<CXXConstructorDecl>(FD)) {
3046 // Check that overload resolution selected a constructor taking an
3047 // rvalue reference. If it selected an lvalue reference, then we
3048 // didn't need to cast this thing to an rvalue in the first place.
3049 if (!isa<RValueReferenceType>(FD->getParamDecl(0)->getType()))
3051 } else if (isa<CXXMethodDecl>(FD)) {
3052 // Check that overload resolution selected a conversion operator
3053 // taking an rvalue reference.
3054 if (cast<CXXMethodDecl>(FD)->getRefQualifier() != RQ_RValue)
3061 // Promote "AsRvalue" to the heap, since we now need this
3062 // expression node to persist.
3063 Value = ImplicitCastExpr::Create(S.Context, Value->getType(), CK_NoOp,
3064 Value, nullptr, VK_XValue);
3066 // Complete type-checking the initialization of the return type
3067 // using the constructor we found.
3068 Res = Seq.Perform(S, Entity, Kind, Value);
3072 /// Perform the initialization of a potentially-movable value, which
3073 /// is the result of return value.
3075 /// This routine implements C++14 [class.copy]p32, which attempts to treat
3076 /// returned lvalues as rvalues in certain cases (to prefer move construction),
3077 /// then falls back to treating them as lvalues if that failed.
3079 Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
3080 const VarDecl *NRVOCandidate,
3081 QualType ResultType,
3084 // C++14 [class.copy]p32:
3085 // When the criteria for elision of a copy/move operation are met, but not for
3086 // an exception-declaration, and the object to be copied is designated by an
3087 // lvalue, or when the expression in a return statement is a (possibly
3088 // parenthesized) id-expression that names an object with automatic storage
3089 // duration declared in the body or parameter-declaration-clause of the
3090 // innermost enclosing function or lambda-expression, overload resolution to
3091 // select the constructor for the copy is first performed as if the object
3092 // were designated by an rvalue.
3093 ExprResult Res = ExprError();
3096 bool AffectedByCWG1579 = false;
3098 if (!NRVOCandidate) {
3099 NRVOCandidate = getCopyElisionCandidate(ResultType, Value, CES_Default);
3100 if (NRVOCandidate &&
3101 !getDiagnostics().isIgnored(diag::warn_return_std_move_in_cxx11,
3102 Value->getExprLoc())) {
3103 const VarDecl *NRVOCandidateInCXX11 =
3104 getCopyElisionCandidate(ResultType, Value, CES_FormerDefault);
3105 AffectedByCWG1579 = (!NRVOCandidateInCXX11);
3109 if (NRVOCandidate) {
3110 TryMoveInitialization(*this, Entity, NRVOCandidate, ResultType, Value,
3114 if (!Res.isInvalid() && AffectedByCWG1579) {
3115 QualType QT = NRVOCandidate->getType();
3116 if (QT.getNonReferenceType()
3117 .getUnqualifiedType()
3118 .isTriviallyCopyableType(Context)) {
3119 // Adding 'std::move' around a trivially copyable variable is probably
3120 // pointless. Don't suggest it.
3122 // Common cases for this are returning unique_ptr<Derived> from a
3123 // function of return type unique_ptr<Base>, or returning T from a
3124 // function of return type Expected<T>. This is totally fine in a
3125 // post-CWG1579 world, but was not fine before.
3126 assert(!ResultType.isNull());
3127 SmallString<32> Str;
3128 Str += "std::move(";
3129 Str += NRVOCandidate->getDeclName().getAsString();
3131 Diag(Value->getExprLoc(), diag::warn_return_std_move_in_cxx11)
3132 << Value->getSourceRange()
3133 << NRVOCandidate->getDeclName() << ResultType << QT;
3134 Diag(Value->getExprLoc(), diag::note_add_std_move_in_cxx11)
3135 << FixItHint::CreateReplacement(Value->getSourceRange(), Str);
3137 } else if (Res.isInvalid() &&
3138 !getDiagnostics().isIgnored(diag::warn_return_std_move,
3139 Value->getExprLoc())) {
3140 const VarDecl *FakeNRVOCandidate =
3141 getCopyElisionCandidate(QualType(), Value, CES_AsIfByStdMove);
3142 if (FakeNRVOCandidate) {
3143 QualType QT = FakeNRVOCandidate->getType();
3144 if (QT->isLValueReferenceType()) {
3145 // Adding 'std::move' around an lvalue reference variable's name is
3146 // dangerous. Don't suggest it.
3147 } else if (QT.getNonReferenceType()
3148 .getUnqualifiedType()
3149 .isTriviallyCopyableType(Context)) {
3150 // Adding 'std::move' around a trivially copyable variable is probably
3151 // pointless. Don't suggest it.
3153 ExprResult FakeRes = ExprError();
3154 Expr *FakeValue = Value;
3155 TryMoveInitialization(*this, Entity, FakeNRVOCandidate, ResultType,
3156 FakeValue, false, FakeRes);
3157 if (!FakeRes.isInvalid()) {
3159 (Entity.getKind() == InitializedEntity::EK_Exception);
3160 SmallString<32> Str;
3161 Str += "std::move(";
3162 Str += FakeNRVOCandidate->getDeclName().getAsString();
3164 Diag(Value->getExprLoc(), diag::warn_return_std_move)
3165 << Value->getSourceRange()
3166 << FakeNRVOCandidate->getDeclName() << IsThrow;
3167 Diag(Value->getExprLoc(), diag::note_add_std_move)
3168 << FixItHint::CreateReplacement(Value->getSourceRange(), Str);
3175 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
3176 // above, or overload resolution failed. Either way, we need to try
3177 // (again) now with the return value expression as written.
3178 if (Res.isInvalid())
3179 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
3184 /// Determine whether the declared return type of the specified function
3185 /// contains 'auto'.
3186 static bool hasDeducedReturnType(FunctionDecl *FD) {
3187 const FunctionProtoType *FPT =
3188 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
3189 return FPT->getReturnType()->isUndeducedType();
3192 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
3193 /// for capturing scopes.
3196 Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
3197 // If this is the first return we've seen, infer the return type.
3198 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
3199 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
3200 QualType FnRetType = CurCap->ReturnType;
3201 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
3202 bool HasDeducedReturnType =
3203 CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
3205 if (ExprEvalContexts.back().Context ==
3206 ExpressionEvaluationContext::DiscardedStatement &&
3207 (HasDeducedReturnType || CurCap->HasImplicitReturnType)) {
3210 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3213 RetValExp = ER.get();
3215 return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3216 /* NRVOCandidate=*/nullptr);
3219 if (HasDeducedReturnType) {
3220 // In C++1y, the return type may involve 'auto'.
3221 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
3222 FunctionDecl *FD = CurLambda->CallOperator;
3223 if (CurCap->ReturnType.isNull())
3224 CurCap->ReturnType = FD->getReturnType();
3226 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
3227 assert(AT && "lost auto type from lambda return type");
3228 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3229 FD->setInvalidDecl();
3232 CurCap->ReturnType = FnRetType = FD->getReturnType();
3233 } else if (CurCap->HasImplicitReturnType) {
3234 // For blocks/lambdas with implicit return types, we check each return
3235 // statement individually, and deduce the common return type when the block
3236 // or lambda is completed.
3237 // FIXME: Fold this into the 'auto' codepath above.
3238 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
3239 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
3240 if (Result.isInvalid())
3242 RetValExp = Result.get();
3244 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
3245 // when deducing a return type for a lambda-expression (or by extension
3246 // for a block). These rules differ from the stated C++11 rules only in
3247 // that they remove top-level cv-qualifiers.
3248 if (!CurContext->isDependentContext())
3249 FnRetType = RetValExp->getType().getUnqualifiedType();
3251 FnRetType = CurCap->ReturnType = Context.DependentTy;
3254 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
3255 // initializer list, because it is not an expression (even
3256 // though we represent it as one). We still deduce 'void'.
3257 Diag(ReturnLoc, diag::err_lambda_return_init_list)
3258 << RetValExp->getSourceRange();
3261 FnRetType = Context.VoidTy;
3264 // Although we'll properly infer the type of the block once it's completed,
3265 // make sure we provide a return type now for better error recovery.
3266 if (CurCap->ReturnType.isNull())
3267 CurCap->ReturnType = FnRetType;
3269 assert(!FnRetType.isNull());
3271 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
3272 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
3273 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
3276 } else if (CapturedRegionScopeInfo *CurRegion =
3277 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
3278 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
3281 assert(CurLambda && "unknown kind of captured scope");
3282 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
3283 ->getNoReturnAttr()) {
3284 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
3289 // Otherwise, verify that this result type matches the previous one. We are
3290 // pickier with blocks than for normal functions because we don't have GCC
3291 // compatibility to worry about here.
3292 const VarDecl *NRVOCandidate = nullptr;
3293 if (FnRetType->isDependentType()) {
3294 // Delay processing for now. TODO: there are lots of dependent
3295 // types we can conclusively prove aren't void.
3296 } else if (FnRetType->isVoidType()) {
3297 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
3298 !(getLangOpts().CPlusPlus &&
3299 (RetValExp->isTypeDependent() ||
3300 RetValExp->getType()->isVoidType()))) {
3301 if (!getLangOpts().CPlusPlus &&
3302 RetValExp->getType()->isVoidType())
3303 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
3305 Diag(ReturnLoc, diag::err_return_block_has_expr);
3306 RetValExp = nullptr;
3309 } else if (!RetValExp) {
3310 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
3311 } else if (!RetValExp->isTypeDependent()) {
3312 // we have a non-void block with an expression, continue checking
3314 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3315 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3318 // In C++ the return statement is handled via a copy initialization.
3319 // the C version of which boils down to CheckSingleAssignmentConstraints.
3320 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
3321 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
3323 NRVOCandidate != nullptr);
3324 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
3325 FnRetType, RetValExp);
3326 if (Res.isInvalid()) {
3327 // FIXME: Cleanup temporaries here, anyway?
3330 RetValExp = Res.get();
3331 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
3333 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
3338 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3341 RetValExp = ER.get();
3344 ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
3346 // If we need to check for the named return value optimization,
3347 // or if we need to infer the return type,
3348 // save the return statement in our scope for later processing.
3349 if (CurCap->HasImplicitReturnType || NRVOCandidate)
3350 FunctionScopes.back()->Returns.push_back(Result);
3352 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3353 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3359 /// Marks all typedefs in all local classes in a type referenced.
3361 /// In a function like
3363 /// struct S { typedef int a; };
3367 /// the local type escapes and could be referenced in some TUs but not in
3368 /// others. Pretend that all local typedefs are always referenced, to not warn
3369 /// on this. This isn't necessary if f has internal linkage, or the typedef
3371 class LocalTypedefNameReferencer
3372 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
3374 LocalTypedefNameReferencer(Sema &S) : S(S) {}
3375 bool VisitRecordType(const RecordType *RT);
3379 bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
3380 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
3381 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
3382 R->isDependentType())
3384 for (auto *TmpD : R->decls())
3385 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
3386 if (T->getAccess() != AS_private || R->hasFriends())
3387 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
3392 TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
3393 return FD->getTypeSourceInfo()
3395 .getAsAdjusted<FunctionProtoTypeLoc>()
3399 /// Deduce the return type for a function from a returned expression, per
3400 /// C++1y [dcl.spec.auto]p6.
3401 bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
3402 SourceLocation ReturnLoc,
3405 // If this is the conversion function for a lambda, we choose to deduce it
3406 // type from the corresponding call operator, not from the synthesized return
3407 // statement within it. See Sema::DeduceReturnType.
3408 if (isLambdaConversionOperator(FD))
3411 TypeLoc OrigResultType = getReturnTypeLoc(FD);
3414 if (RetExpr && isa<InitListExpr>(RetExpr)) {
3415 // If the deduction is for a return statement and the initializer is
3416 // a braced-init-list, the program is ill-formed.
3417 Diag(RetExpr->getExprLoc(),
3418 getCurLambda() ? diag::err_lambda_return_init_list
3419 : diag::err_auto_fn_return_init_list)
3420 << RetExpr->getSourceRange();
3424 if (FD->isDependentContext()) {
3425 // C++1y [dcl.spec.auto]p12:
3426 // Return type deduction [...] occurs when the definition is
3427 // instantiated even if the function body contains a return
3428 // statement with a non-type-dependent operand.
3429 assert(AT->isDeduced() && "should have deduced to dependent type");
3434 // Otherwise, [...] deduce a value for U using the rules of template
3435 // argument deduction.
3436 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
3438 if (DAR == DAR_Failed && !FD->isInvalidDecl())
3439 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3440 << OrigResultType.getType() << RetExpr->getType();
3442 if (DAR != DAR_Succeeded)
3445 // If a local type is part of the returned type, mark its fields as
3447 LocalTypedefNameReferencer Referencer(*this);
3448 Referencer.TraverseType(RetExpr->getType());
3450 // In the case of a return with no operand, the initializer is considered
3453 // Deduction here can only succeed if the return type is exactly 'cv auto'
3454 // or 'decltype(auto)', so just check for that case directly.
3455 if (!OrigResultType.getType()->getAs<AutoType>()) {
3456 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3457 << OrigResultType.getType();
3460 // We always deduce U = void in this case.
3461 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
3462 if (Deduced.isNull())
3466 // If a function with a declared return type that contains a placeholder type
3467 // has multiple return statements, the return type is deduced for each return
3468 // statement. [...] if the type deduced is not the same in each deduction,
3469 // the program is ill-formed.
3470 QualType DeducedT = AT->getDeducedType();
3471 if (!DeducedT.isNull() && !FD->isInvalidDecl()) {
3472 AutoType *NewAT = Deduced->getContainedAutoType();
3473 // It is possible that NewAT->getDeducedType() is null. When that happens,
3474 // we should not crash, instead we ignore this deduction.
3475 if (NewAT->getDeducedType().isNull())
3478 CanQualType OldDeducedType = Context.getCanonicalFunctionResultType(
3480 CanQualType NewDeducedType = Context.getCanonicalFunctionResultType(
3481 NewAT->getDeducedType());
3482 if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) {
3483 const LambdaScopeInfo *LambdaSI = getCurLambda();
3484 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
3485 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
3486 << NewAT->getDeducedType() << DeducedT
3487 << true /*IsLambda*/;
3489 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3490 << (AT->isDecltypeAuto() ? 1 : 0)
3491 << NewAT->getDeducedType() << DeducedT;
3495 } else if (!FD->isInvalidDecl()) {
3496 // Update all declarations of the function to have the deduced return type.
3497 Context.adjustDeducedFunctionResultType(FD, Deduced);
3504 Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3506 // Correct typos, in case the containing function returns 'auto' and
3507 // RetValExp should determine the deduced type.
3508 ExprResult RetVal = CorrectDelayedTyposInExpr(RetValExp);
3509 if (RetVal.isInvalid())
3511 StmtResult R = BuildReturnStmt(ReturnLoc, RetVal.get());
3512 if (R.isInvalid() || ExprEvalContexts.back().Context ==
3513 ExpressionEvaluationContext::DiscardedStatement)
3517 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
3518 CurScope->addNRVOCandidate(VD);
3520 CurScope->setNoNRVO();
3523 CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3528 StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
3529 // Check for unexpanded parameter packs.
3530 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3533 if (isa<CapturingScopeInfo>(getCurFunction()))
3534 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
3537 QualType RelatedRetType;
3538 const AttrVec *Attrs = nullptr;
3539 bool isObjCMethod = false;
3541 if (const FunctionDecl *FD = getCurFunctionDecl()) {
3542 FnRetType = FD->getReturnType();
3544 Attrs = &FD->getAttrs();
3545 if (FD->isNoReturn())
3546 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
3547 << FD->getDeclName();
3548 if (FD->isMain() && RetValExp)
3549 if (isa<CXXBoolLiteralExpr>(RetValExp))
3550 Diag(ReturnLoc, diag::warn_main_returns_bool_literal)
3551 << RetValExp->getSourceRange();
3552 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
3553 FnRetType = MD->getReturnType();
3554 isObjCMethod = true;
3556 Attrs = &MD->getAttrs();
3557 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3558 // In the implementation of a method with a related return type, the
3559 // type used to type-check the validity of return statements within the
3560 // method body is a pointer to the type of the class being implemented.
3561 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3562 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
3564 } else // If we don't have a function/method context, bail.
3567 // C++1z: discarded return statements are not considered when deducing a
3569 if (ExprEvalContexts.back().Context ==
3570 ExpressionEvaluationContext::DiscardedStatement &&
3571 FnRetType->getContainedAutoType()) {
3574 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3577 RetValExp = ER.get();
3579 return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3580 /* NRVOCandidate=*/nullptr);
3583 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3585 if (getLangOpts().CPlusPlus14) {
3586 if (AutoType *AT = FnRetType->getContainedAutoType()) {
3587 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
3588 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3589 FD->setInvalidDecl();
3592 FnRetType = FD->getReturnType();
3597 bool HasDependentReturnType = FnRetType->isDependentType();
3599 ReturnStmt *Result = nullptr;
3600 if (FnRetType->isVoidType()) {
3602 if (isa<InitListExpr>(RetValExp)) {
3603 // We simply never allow init lists as the return value of void
3604 // functions. This is compatible because this was never allowed before,
3605 // so there's no legacy code to deal with.
3606 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3607 int FunctionKind = 0;
3608 if (isa<ObjCMethodDecl>(CurDecl))
3610 else if (isa<CXXConstructorDecl>(CurDecl))
3612 else if (isa<CXXDestructorDecl>(CurDecl))
3615 Diag(ReturnLoc, diag::err_return_init_list)
3616 << CurDecl->getDeclName() << FunctionKind
3617 << RetValExp->getSourceRange();
3619 // Drop the expression.
3620 RetValExp = nullptr;
3621 } else if (!RetValExp->isTypeDependent()) {
3622 // C99 6.8.6.4p1 (ext_ since GCC warns)
3623 unsigned D = diag::ext_return_has_expr;
3624 if (RetValExp->getType()->isVoidType()) {
3625 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3626 if (isa<CXXConstructorDecl>(CurDecl) ||
3627 isa<CXXDestructorDecl>(CurDecl))
3628 D = diag::err_ctor_dtor_returns_void;
3630 D = diag::ext_return_has_void_expr;
3633 ExprResult Result = RetValExp;
3634 Result = IgnoredValueConversions(Result.get());
3635 if (Result.isInvalid())
3637 RetValExp = Result.get();
3638 RetValExp = ImpCastExprToType(RetValExp,
3639 Context.VoidTy, CK_ToVoid).get();
3641 // return of void in constructor/destructor is illegal in C++.
3642 if (D == diag::err_ctor_dtor_returns_void) {
3643 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3645 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3646 << RetValExp->getSourceRange();
3648 // return (some void expression); is legal in C++.
3649 else if (D != diag::ext_return_has_void_expr ||
3650 !getLangOpts().CPlusPlus) {
3651 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3653 int FunctionKind = 0;
3654 if (isa<ObjCMethodDecl>(CurDecl))
3656 else if (isa<CXXConstructorDecl>(CurDecl))
3658 else if (isa<CXXDestructorDecl>(CurDecl))
3662 << CurDecl->getDeclName() << FunctionKind
3663 << RetValExp->getSourceRange();
3669 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3672 RetValExp = ER.get();
3676 Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3677 /* NRVOCandidate=*/nullptr);
3678 } else if (!RetValExp && !HasDependentReturnType) {
3679 FunctionDecl *FD = getCurFunctionDecl();
3682 if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3683 // C++11 [stmt.return]p2
3684 DiagID = diag::err_constexpr_return_missing_expr;
3685 FD->setInvalidDecl();
3686 } else if (getLangOpts().C99) {
3687 // C99 6.8.6.4p1 (ext_ since GCC warns)
3688 DiagID = diag::ext_return_missing_expr;
3691 DiagID = diag::warn_return_missing_expr;
3695 Diag(ReturnLoc, DiagID)
3696 << FD->getIdentifier() << 0 /*fn*/ << FD->isConsteval();
3698 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
3700 Result = ReturnStmt::Create(Context, ReturnLoc, /* RetExpr=*/nullptr,
3701 /* NRVOCandidate=*/nullptr);
3703 assert(RetValExp || HasDependentReturnType);
3704 const VarDecl *NRVOCandidate = nullptr;
3706 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3708 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3709 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3712 // In C++ the return statement is handled via a copy initialization,
3713 // the C version of which boils down to CheckSingleAssignmentConstraints.
3715 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
3716 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
3717 // we have a non-void function with an expression, continue checking
3718 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
3720 NRVOCandidate != nullptr);
3721 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
3722 RetType, RetValExp);
3723 if (Res.isInvalid()) {
3724 // FIXME: Clean up temporaries here anyway?
3727 RetValExp = Res.getAs<Expr>();
3729 // If we have a related result type, we need to implicitly
3730 // convert back to the formal result type. We can't pretend to
3731 // initialize the result again --- we might end double-retaining
3732 // --- so instead we initialize a notional temporary.
3733 if (!RelatedRetType.isNull()) {
3734 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3736 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3737 if (Res.isInvalid()) {
3738 // FIXME: Clean up temporaries here anyway?
3741 RetValExp = Res.getAs<Expr>();
3744 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3745 getCurFunctionDecl());
3750 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3753 RetValExp = ER.get();
3755 Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
3758 // If we need to check for the named return value optimization, save the
3759 // return statement in our scope for later processing.
3760 if (Result->getNRVOCandidate())
3761 FunctionScopes.back()->Returns.push_back(Result);
3763 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3764 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3770 Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
3771 SourceLocation RParen, Decl *Parm,
3773 VarDecl *Var = cast_or_null<VarDecl>(Parm);
3774 if (Var && Var->isInvalidDecl())
3777 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
3781 Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
3782 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
3786 Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3787 MultiStmtArg CatchStmts, Stmt *Finally) {
3788 if (!getLangOpts().ObjCExceptions)
3789 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3791 setFunctionHasBranchProtectedScope();
3792 unsigned NumCatchStmts = CatchStmts.size();
3793 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3794 NumCatchStmts, Finally);
3797 StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
3799 ExprResult Result = DefaultLvalueConversion(Throw);
3800 if (Result.isInvalid())
3803 Result = ActOnFinishFullExpr(Result.get(), /*DiscardedValue*/ false);
3804 if (Result.isInvalid())
3806 Throw = Result.get();
3808 QualType ThrowType = Throw->getType();
3809 // Make sure the expression type is an ObjC pointer or "void *".
3810 if (!ThrowType->isDependentType() &&
3811 !ThrowType->isObjCObjectPointerType()) {
3812 const PointerType *PT = ThrowType->getAs<PointerType>();
3813 if (!PT || !PT->getPointeeType()->isVoidType())
3814 return StmtError(Diag(AtLoc, diag::err_objc_throw_expects_object)
3815 << Throw->getType() << Throw->getSourceRange());
3819 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
3823 Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3825 if (!getLangOpts().ObjCExceptions)
3826 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3829 // @throw without an expression designates a rethrow (which must occur
3830 // in the context of an @catch clause).
3831 Scope *AtCatchParent = CurScope;
3832 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3833 AtCatchParent = AtCatchParent->getParent();
3835 return StmtError(Diag(AtLoc, diag::err_rethrow_used_outside_catch));
3837 return BuildObjCAtThrowStmt(AtLoc, Throw);
3841 Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3842 ExprResult result = DefaultLvalueConversion(operand);
3843 if (result.isInvalid())
3845 operand = result.get();
3847 // Make sure the expression type is an ObjC pointer or "void *".
3848 QualType type = operand->getType();
3849 if (!type->isDependentType() &&
3850 !type->isObjCObjectPointerType()) {
3851 const PointerType *pointerType = type->getAs<PointerType>();
3852 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3853 if (getLangOpts().CPlusPlus) {
3854 if (RequireCompleteType(atLoc, type,
3855 diag::err_incomplete_receiver_type))
3856 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
3857 << type << operand->getSourceRange();
3859 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
3860 if (result.isInvalid())
3862 if (!result.isUsable())
3863 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
3864 << type << operand->getSourceRange();
3866 operand = result.get();
3868 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
3869 << type << operand->getSourceRange();
3874 // The operand to @synchronized is a full-expression.
3875 return ActOnFinishFullExpr(operand, /*DiscardedValue*/ false);
3879 Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3881 // We can't jump into or indirect-jump out of a @synchronized block.
3882 setFunctionHasBranchProtectedScope();
3883 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
3886 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3887 /// and creates a proper catch handler from them.
3889 Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
3890 Stmt *HandlerBlock) {
3891 // There's nothing to test that ActOnExceptionDecl didn't already test.
3892 return new (Context)
3893 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
3897 Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3898 setFunctionHasBranchProtectedScope();
3899 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
3903 class CatchHandlerType {
3905 unsigned IsPointer : 1;
3907 // This is a special constructor to be used only with DenseMapInfo's
3908 // getEmptyKey() and getTombstoneKey() functions.
3909 friend struct llvm::DenseMapInfo<CatchHandlerType>;
3910 enum Unique { ForDenseMap };
3911 CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
3914 /// Used when creating a CatchHandlerType from a handler type; will determine
3915 /// whether the type is a pointer or reference and will strip off the top
3916 /// level pointer and cv-qualifiers.
3917 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
3918 if (QT->isPointerType())
3921 if (IsPointer || QT->isReferenceType())
3922 QT = QT->getPointeeType();
3923 QT = QT.getUnqualifiedType();
3926 /// Used when creating a CatchHandlerType from a base class type; pretends the
3927 /// type passed in had the pointer qualifier, does not need to get an
3928 /// unqualified type.
3929 CatchHandlerType(QualType QT, bool IsPointer)
3930 : QT(QT), IsPointer(IsPointer) {}
3932 QualType underlying() const { return QT; }
3933 bool isPointer() const { return IsPointer; }
3935 friend bool operator==(const CatchHandlerType &LHS,
3936 const CatchHandlerType &RHS) {
3937 // If the pointer qualification does not match, we can return early.
3938 if (LHS.IsPointer != RHS.IsPointer)
3940 // Otherwise, check the underlying type without cv-qualifiers.
3941 return LHS.QT == RHS.QT;
3947 template <> struct DenseMapInfo<CatchHandlerType> {
3948 static CatchHandlerType getEmptyKey() {
3949 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
3950 CatchHandlerType::ForDenseMap);
3953 static CatchHandlerType getTombstoneKey() {
3954 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
3955 CatchHandlerType::ForDenseMap);
3958 static unsigned getHashValue(const CatchHandlerType &Base) {
3959 return DenseMapInfo<QualType>::getHashValue(Base.underlying());
3962 static bool isEqual(const CatchHandlerType &LHS,
3963 const CatchHandlerType &RHS) {
3970 class CatchTypePublicBases {
3972 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
3973 const bool CheckAgainstPointer;
3975 CXXCatchStmt *FoundHandler;
3976 CanQualType FoundHandlerType;
3979 CatchTypePublicBases(
3981 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
3982 : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
3983 FoundHandler(nullptr) {}
3985 CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
3986 CanQualType getFoundHandlerType() const { return FoundHandlerType; }
3988 bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
3989 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
3990 CatchHandlerType Check(S->getType(), CheckAgainstPointer);
3991 const auto &M = TypesToCheck;
3992 auto I = M.find(Check);
3994 FoundHandler = I->second;
3995 FoundHandlerType = Ctx.getCanonicalType(S->getType());
4004 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
4005 /// handlers and creates a try statement from them.
4006 StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
4007 ArrayRef<Stmt *> Handlers) {
4008 // Don't report an error if 'try' is used in system headers.
4009 if (!getLangOpts().CXXExceptions &&
4010 !getSourceManager().isInSystemHeader(TryLoc) && !getLangOpts().CUDA) {
4011 // Delay error emission for the OpenMP device code.
4012 targetDiag(TryLoc, diag::err_exceptions_disabled) << "try";
4015 // Exceptions aren't allowed in CUDA device code.
4016 if (getLangOpts().CUDA)
4017 CUDADiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions)
4018 << "try" << CurrentCUDATarget();
4020 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
4021 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
4023 sema::FunctionScopeInfo *FSI = getCurFunction();
4025 // C++ try is incompatible with SEH __try.
4026 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
4027 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
4028 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
4031 const unsigned NumHandlers = Handlers.size();
4032 assert(!Handlers.empty() &&
4033 "The parser shouldn't call this if there are no handlers.");
4035 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
4036 for (unsigned i = 0; i < NumHandlers; ++i) {
4037 CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
4039 // Diagnose when the handler is a catch-all handler, but it isn't the last
4040 // handler for the try block. [except.handle]p5. Also, skip exception
4041 // declarations that are invalid, since we can't usefully report on them.
4042 if (!H->getExceptionDecl()) {
4043 if (i < NumHandlers - 1)
4044 return StmtError(Diag(H->getBeginLoc(), diag::err_early_catch_all));
4046 } else if (H->getExceptionDecl()->isInvalidDecl())
4049 // Walk the type hierarchy to diagnose when this type has already been
4050 // handled (duplication), or cannot be handled (derivation inversion). We
4051 // ignore top-level cv-qualifiers, per [except.handle]p3
4052 CatchHandlerType HandlerCHT =
4053 (QualType)Context.getCanonicalType(H->getCaughtType());
4055 // We can ignore whether the type is a reference or a pointer; we need the
4056 // underlying declaration type in order to get at the underlying record
4057 // decl, if there is one.
4058 QualType Underlying = HandlerCHT.underlying();
4059 if (auto *RD = Underlying->getAsCXXRecordDecl()) {
4060 if (!RD->hasDefinition())
4062 // Check that none of the public, unambiguous base classes are in the
4063 // map ([except.handle]p1). Give the base classes the same pointer
4064 // qualification as the original type we are basing off of. This allows
4065 // comparison against the handler type using the same top-level pointer
4066 // as the original type.
4068 Paths.setOrigin(RD);
4069 CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
4070 if (RD->lookupInBases(CTPB, Paths)) {
4071 const CXXCatchStmt *Problem = CTPB.getFoundHandler();
4072 if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
4073 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
4074 diag::warn_exception_caught_by_earlier_handler)
4075 << H->getCaughtType();
4076 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
4077 diag::note_previous_exception_handler)
4078 << Problem->getCaughtType();
4083 // Add the type the list of ones we have handled; diagnose if we've already
4085 auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
4087 const CXXCatchStmt *Problem = R.first->second;
4088 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
4089 diag::warn_exception_caught_by_earlier_handler)
4090 << H->getCaughtType();
4091 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
4092 diag::note_previous_exception_handler)
4093 << Problem->getCaughtType();
4097 FSI->setHasCXXTry(TryLoc);
4099 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
4102 StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
4103 Stmt *TryBlock, Stmt *Handler) {
4104 assert(TryBlock && Handler);
4106 sema::FunctionScopeInfo *FSI = getCurFunction();
4108 // SEH __try is incompatible with C++ try. Borland appears to support this,
4110 if (!getLangOpts().Borland) {
4111 if (FSI->FirstCXXTryLoc.isValid()) {
4112 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
4113 Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
4117 FSI->setHasSEHTry(TryLoc);
4119 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
4120 // track if they use SEH.
4121 DeclContext *DC = CurContext;
4122 while (DC && !DC->isFunctionOrMethod())
4123 DC = DC->getParent();
4124 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
4126 FD->setUsesSEHTry(true);
4128 Diag(TryLoc, diag::err_seh_try_outside_functions);
4130 // Reject __try on unsupported targets.
4131 if (!Context.getTargetInfo().isSEHTrySupported())
4132 Diag(TryLoc, diag::err_seh_try_unsupported);
4134 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
4138 Sema::ActOnSEHExceptBlock(SourceLocation Loc,
4141 assert(FilterExpr && Block);
4143 if(!FilterExpr->getType()->isIntegerType()) {
4144 return StmtError(Diag(FilterExpr->getExprLoc(),
4145 diag::err_filter_expression_integral)
4146 << FilterExpr->getType());
4149 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
4152 void Sema::ActOnStartSEHFinallyBlock() {
4153 CurrentSEHFinally.push_back(CurScope);
4156 void Sema::ActOnAbortSEHFinallyBlock() {
4157 CurrentSEHFinally.pop_back();
4160 StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
4162 CurrentSEHFinally.pop_back();
4163 return SEHFinallyStmt::Create(Context, Loc, Block);
4167 Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
4168 Scope *SEHTryParent = CurScope;
4169 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
4170 SEHTryParent = SEHTryParent->getParent();
4172 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
4173 CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
4175 return new (Context) SEHLeaveStmt(Loc);
4178 StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4180 NestedNameSpecifierLoc QualifierLoc,
4181 DeclarationNameInfo NameInfo,
4184 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
4185 QualifierLoc, NameInfo,
4186 cast<CompoundStmt>(Nested));
4190 StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4193 UnqualifiedId &Name,
4195 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
4196 SS.getWithLocInContext(Context),
4197 GetNameFromUnqualifiedId(Name),
4202 Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
4203 unsigned NumParams) {
4204 DeclContext *DC = CurContext;
4205 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
4206 DC = DC->getParent();
4208 RecordDecl *RD = nullptr;
4209 if (getLangOpts().CPlusPlus)
4210 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
4213 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
4215 RD->setCapturedRecord();
4218 RD->startDefinition();
4220 assert(NumParams > 0 && "CapturedStmt requires context parameter");
4221 CD = CapturedDecl::Create(Context, CurContext, NumParams);
4227 buildCapturedStmtCaptureList(Sema &S, CapturedRegionScopeInfo *RSI,
4228 SmallVectorImpl<CapturedStmt::Capture> &Captures,
4229 SmallVectorImpl<Expr *> &CaptureInits) {
4230 for (const sema::Capture &Cap : RSI->Captures) {
4231 if (Cap.isInvalid())
4234 // Form the initializer for the capture.
4235 ExprResult Init = S.BuildCaptureInit(Cap, Cap.getLocation(),
4236 RSI->CapRegionKind == CR_OpenMP);
4238 // FIXME: Bail out now if the capture is not used and the initializer has
4241 // Create a field for this capture.
4242 FieldDecl *Field = S.BuildCaptureField(RSI->TheRecordDecl, Cap);
4244 // Add the capture to our list of captures.
4245 if (Cap.isThisCapture()) {
4246 Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
4247 CapturedStmt::VCK_This));
4248 } else if (Cap.isVLATypeCapture()) {
4250 CapturedStmt::Capture(Cap.getLocation(), CapturedStmt::VCK_VLAType));
4252 assert(Cap.isVariableCapture() && "unknown kind of capture");
4254 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
4255 S.setOpenMPCaptureKind(Field, Cap.getVariable(), RSI->OpenMPLevel);
4257 Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
4258 Cap.isReferenceCapture()
4259 ? CapturedStmt::VCK_ByRef
4260 : CapturedStmt::VCK_ByCopy,
4261 Cap.getVariable()));
4263 CaptureInits.push_back(Init.get());
4268 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4269 CapturedRegionKind Kind,
4270 unsigned NumParams) {
4271 CapturedDecl *CD = nullptr;
4272 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
4274 // Build the context parameter
4275 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4276 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4277 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
4279 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4280 ImplicitParamDecl::CapturedContext);
4283 CD->setContextParam(0, Param);
4285 // Enter the capturing scope for this captured region.
4286 PushCapturedRegionScope(CurScope, CD, RD, Kind);
4289 PushDeclContext(CurScope, CD);
4293 PushExpressionEvaluationContext(
4294 ExpressionEvaluationContext::PotentiallyEvaluated);
4297 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4298 CapturedRegionKind Kind,
4299 ArrayRef<CapturedParamNameType> Params) {
4300 CapturedDecl *CD = nullptr;
4301 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
4303 // Build the context parameter
4304 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4305 bool ContextIsFound = false;
4306 unsigned ParamNum = 0;
4307 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
4309 I != E; ++I, ++ParamNum) {
4310 if (I->second.isNull()) {
4311 assert(!ContextIsFound &&
4312 "null type has been found already for '__context' parameter");
4313 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4314 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD))
4318 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4319 ImplicitParamDecl::CapturedContext);
4321 CD->setContextParam(ParamNum, Param);
4322 ContextIsFound = true;
4324 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
4326 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second,
4327 ImplicitParamDecl::CapturedContext);
4329 CD->setParam(ParamNum, Param);
4332 assert(ContextIsFound && "no null type for '__context' parameter");
4333 if (!ContextIsFound) {
4334 // Add __context implicitly if it is not specified.
4335 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4336 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
4338 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4339 ImplicitParamDecl::CapturedContext);
4341 CD->setContextParam(ParamNum, Param);
4343 // Enter the capturing scope for this captured region.
4344 PushCapturedRegionScope(CurScope, CD, RD, Kind);
4347 PushDeclContext(CurScope, CD);
4351 PushExpressionEvaluationContext(
4352 ExpressionEvaluationContext::PotentiallyEvaluated);
4355 void Sema::ActOnCapturedRegionError() {
4356 DiscardCleanupsInEvaluationContext();
4357 PopExpressionEvaluationContext();
4359 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo();
4360 CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(ScopeRAII.get());
4362 RecordDecl *Record = RSI->TheRecordDecl;
4363 Record->setInvalidDecl();
4365 SmallVector<Decl*, 4> Fields(Record->fields());
4366 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
4367 SourceLocation(), SourceLocation(), ParsedAttributesView());
4370 StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
4371 // Leave the captured scope before we start creating captures in the
4373 DiscardCleanupsInEvaluationContext();
4374 PopExpressionEvaluationContext();
4376 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo();
4377 CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(ScopeRAII.get());
4379 SmallVector<CapturedStmt::Capture, 4> Captures;
4380 SmallVector<Expr *, 4> CaptureInits;
4381 if (buildCapturedStmtCaptureList(*this, RSI, Captures, CaptureInits))
4384 CapturedDecl *CD = RSI->TheCapturedDecl;
4385 RecordDecl *RD = RSI->TheRecordDecl;
4387 CapturedStmt *Res = CapturedStmt::Create(
4388 getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind),
4389 Captures, CaptureInits, CD, RD);
4391 CD->setBody(Res->getCapturedStmt());
4392 RD->completeDefinition();