1 //===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for statements.
12 //===----------------------------------------------------------------------===//
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 bool Sema::isCurCompoundStmtAStmtExpr() const {
351 return getCurCompoundScope().IsStmtExpr;
354 StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
355 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
356 const unsigned NumElts = Elts.size();
358 // If we're in C89 mode, check that we don't have any decls after stmts. If
359 // so, emit an extension diagnostic.
360 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
361 // Note that __extension__ can be around a decl.
363 // Skip over all declarations.
364 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
367 // We found the end of the list or a statement. Scan for another declstmt.
368 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
372 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
373 Diag(D->getLocation(), diag::ext_mixed_decls_code);
377 // Check for suspicious empty body (null statement) in `for' and `while'
378 // statements. Don't do anything for template instantiations, this just adds
380 if (NumElts != 0 && !CurrentInstantiationScope &&
381 getCurCompoundScope().HasEmptyLoopBodies) {
382 for (unsigned i = 0; i != NumElts - 1; ++i)
383 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
386 return CompoundStmt::Create(Context, Elts, L, R);
390 Sema::ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val) {
394 if (DiagnoseUnexpandedParameterPack(Val.get()))
397 // If we're not inside a switch, let the 'case' statement handling diagnose
398 // this. Just clean up after the expression as best we can.
399 if (!getCurFunction()->SwitchStack.empty()) {
401 getCurFunction()->SwitchStack.back().getPointer()->getCond();
404 QualType CondType = CondExpr->getType();
406 auto CheckAndFinish = [&](Expr *E) {
407 if (CondType->isDependentType() || E->isTypeDependent())
408 return ExprResult(E);
410 if (getLangOpts().CPlusPlus11) {
411 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
412 // constant expression of the promoted type of the switch condition.
413 llvm::APSInt TempVal;
414 return CheckConvertedConstantExpression(E, CondType, TempVal,
419 if (!E->isValueDependent())
420 ER = VerifyIntegerConstantExpression(E);
422 ER = DefaultLvalueConversion(ER.get());
424 ER = ImpCastExprToType(ER.get(), CondType, CK_IntegralCast);
428 ExprResult Converted = CorrectDelayedTyposInExpr(Val, CheckAndFinish);
429 if (Converted.get() == Val.get())
430 Converted = CheckAndFinish(Val.get());
431 if (Converted.isInvalid())
436 return ActOnFinishFullExpr(Val.get(), Val.get()->getExprLoc(), false,
437 getLangOpts().CPlusPlus11);
441 Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHSVal,
442 SourceLocation DotDotDotLoc, ExprResult RHSVal,
443 SourceLocation ColonLoc) {
444 assert((LHSVal.isInvalid() || LHSVal.get()) && "missing LHS value");
445 assert((DotDotDotLoc.isInvalid() ? RHSVal.isUnset()
446 : RHSVal.isInvalid() || RHSVal.get()) &&
447 "missing RHS value");
449 if (getCurFunction()->SwitchStack.empty()) {
450 Diag(CaseLoc, diag::err_case_not_in_switch);
454 if (LHSVal.isInvalid() || RHSVal.isInvalid()) {
455 getCurFunction()->SwitchStack.back().setInt(true);
459 auto *CS = CaseStmt::Create(Context, LHSVal.get(), RHSVal.get(),
460 CaseLoc, DotDotDotLoc, ColonLoc);
461 getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(CS);
465 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
466 void Sema::ActOnCaseStmtBody(Stmt *S, Stmt *SubStmt) {
467 cast<CaseStmt>(S)->setSubStmt(SubStmt);
471 Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
472 Stmt *SubStmt, Scope *CurScope) {
473 if (getCurFunction()->SwitchStack.empty()) {
474 Diag(DefaultLoc, diag::err_default_not_in_switch);
478 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
479 getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(DS);
484 Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
485 SourceLocation ColonLoc, Stmt *SubStmt) {
486 // If the label was multiply defined, reject it now.
487 if (TheDecl->getStmt()) {
488 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
489 Diag(TheDecl->getLocation(), diag::note_previous_definition);
493 // Otherwise, things are good. Fill in the declaration and return it.
494 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
495 TheDecl->setStmt(LS);
496 if (!TheDecl->isGnuLocal()) {
497 TheDecl->setLocStart(IdentLoc);
498 if (!TheDecl->isMSAsmLabel()) {
499 // Don't update the location of MS ASM labels. These will result in
500 // a diagnostic, and changing the location here will mess that up.
501 TheDecl->setLocation(IdentLoc);
507 StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
508 ArrayRef<const Attr*> Attrs,
510 // Fill in the declaration and return it.
511 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
516 class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
517 typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
520 CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
521 void VisitBinaryOperator(BinaryOperator *E) {
522 if (E->getOpcode() == BO_Comma)
523 SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc());
524 EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E);
530 Sema::ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt,
531 ConditionResult Cond,
532 Stmt *thenStmt, SourceLocation ElseLoc,
534 if (Cond.isInvalid())
535 Cond = ConditionResult(
537 MakeFullExpr(new (Context) OpaqueValueExpr(SourceLocation(),
538 Context.BoolTy, VK_RValue),
542 Expr *CondExpr = Cond.get().second;
543 // Only call the CommaVisitor when not C89 due to differences in scope flags.
544 if ((getLangOpts().C99 || getLangOpts().CPlusPlus) &&
545 !Diags.isIgnored(diag::warn_comma_operator, CondExpr->getExprLoc()))
546 CommaVisitor(*this).Visit(CondExpr);
549 DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), thenStmt,
550 diag::warn_empty_if_body);
552 return BuildIfStmt(IfLoc, IsConstexpr, InitStmt, Cond, thenStmt, ElseLoc,
556 StmtResult Sema::BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
557 Stmt *InitStmt, ConditionResult Cond,
558 Stmt *thenStmt, SourceLocation ElseLoc,
560 if (Cond.isInvalid())
563 if (IsConstexpr || isa<ObjCAvailabilityCheckExpr>(Cond.get().second))
564 setFunctionHasBranchProtectedScope();
566 return IfStmt::Create(Context, IfLoc, IsConstexpr, InitStmt, Cond.get().first,
567 Cond.get().second, thenStmt, ElseLoc, elseStmt);
571 struct CaseCompareFunctor {
572 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
573 const llvm::APSInt &RHS) {
574 return LHS.first < RHS;
576 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
577 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
578 return LHS.first < RHS.first;
580 bool operator()(const llvm::APSInt &LHS,
581 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
582 return LHS < RHS.first;
587 /// CmpCaseVals - Comparison predicate for sorting case values.
589 static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
590 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
591 if (lhs.first < rhs.first)
594 if (lhs.first == rhs.first &&
595 lhs.second->getCaseLoc().getRawEncoding()
596 < rhs.second->getCaseLoc().getRawEncoding())
601 /// CmpEnumVals - Comparison predicate for sorting enumeration values.
603 static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
604 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
606 return lhs.first < rhs.first;
609 /// EqEnumVals - Comparison preficate for uniqing enumeration values.
611 static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
612 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
614 return lhs.first == rhs.first;
617 /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
618 /// potentially integral-promoted expression @p expr.
619 static QualType GetTypeBeforeIntegralPromotion(const Expr *&E) {
620 if (const auto *FE = dyn_cast<FullExpr>(E))
621 E = FE->getSubExpr();
622 while (const auto *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
623 if (ImpCast->getCastKind() != CK_IntegralCast) break;
624 E = ImpCast->getSubExpr();
629 ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) {
630 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
634 SwitchConvertDiagnoser(Expr *Cond)
635 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
638 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
639 QualType T) override {
640 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
643 SemaDiagnosticBuilder diagnoseIncomplete(
644 Sema &S, SourceLocation Loc, QualType T) override {
645 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
646 << T << Cond->getSourceRange();
649 SemaDiagnosticBuilder diagnoseExplicitConv(
650 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
651 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
654 SemaDiagnosticBuilder noteExplicitConv(
655 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
656 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
657 << ConvTy->isEnumeralType() << ConvTy;
660 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
661 QualType T) override {
662 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
665 SemaDiagnosticBuilder noteAmbiguous(
666 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
667 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
668 << ConvTy->isEnumeralType() << ConvTy;
671 SemaDiagnosticBuilder diagnoseConversion(
672 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
673 llvm_unreachable("conversion functions are permitted");
675 } SwitchDiagnoser(Cond);
677 ExprResult CondResult =
678 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
679 if (CondResult.isInvalid())
682 // FIXME: PerformContextualImplicitConversion doesn't always tell us if it
683 // failed and produced a diagnostic.
684 Cond = CondResult.get();
685 if (!Cond->isTypeDependent() &&
686 !Cond->getType()->isIntegralOrEnumerationType())
689 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
690 return UsualUnaryConversions(Cond);
693 StmtResult Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
694 Stmt *InitStmt, ConditionResult Cond) {
695 Expr *CondExpr = Cond.get().second;
696 assert((Cond.isInvalid() || CondExpr) && "switch with no condition");
698 if (CondExpr && !CondExpr->isTypeDependent()) {
699 // We have already converted the expression to an integral or enumeration
700 // type, when we parsed the switch condition. If we don't have an
701 // appropriate type now, enter the switch scope but remember that it's
703 assert(CondExpr->getType()->isIntegralOrEnumerationType() &&
704 "invalid condition type");
705 if (CondExpr->isKnownToHaveBooleanValue()) {
706 // switch(bool_expr) {...} is often a programmer error, e.g.
707 // switch(n && mask) { ... } // Doh - should be "n & mask".
708 // One can always use an if statement instead of switch(bool_expr).
709 Diag(SwitchLoc, diag::warn_bool_switch_condition)
710 << CondExpr->getSourceRange();
714 setFunctionHasBranchIntoScope();
716 auto *SS = SwitchStmt::Create(Context, InitStmt, Cond.get().first, CondExpr);
717 getCurFunction()->SwitchStack.push_back(
718 FunctionScopeInfo::SwitchInfo(SS, false));
722 static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
723 Val = Val.extOrTrunc(BitWidth);
724 Val.setIsSigned(IsSigned);
727 /// Check the specified case value is in range for the given unpromoted switch
729 static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
730 unsigned UnpromotedWidth, bool UnpromotedSign) {
731 // In C++11 onwards, this is checked by the language rules.
732 if (S.getLangOpts().CPlusPlus11)
735 // If the case value was signed and negative and the switch expression is
736 // unsigned, don't bother to warn: this is implementation-defined behavior.
737 // FIXME: Introduce a second, default-ignored warning for this case?
738 if (UnpromotedWidth < Val.getBitWidth()) {
739 llvm::APSInt ConvVal(Val);
740 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
741 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
742 // FIXME: Use different diagnostics for overflow in conversion to promoted
743 // type versus "switch expression cannot have this value". Use proper
744 // IntRange checking rather than just looking at the unpromoted type here.
746 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
747 << ConvVal.toString(10);
751 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
753 /// Returns true if we should emit a diagnostic about this case expression not
754 /// being a part of the enum used in the switch controlling expression.
755 static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
757 const Expr *CaseExpr,
758 EnumValsTy::iterator &EI,
759 EnumValsTy::iterator &EIEnd,
760 const llvm::APSInt &Val) {
764 if (const DeclRefExpr *DRE =
765 dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
766 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
767 QualType VarType = VD->getType();
768 QualType EnumType = S.Context.getTypeDeclType(ED);
769 if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
770 S.Context.hasSameUnqualifiedType(EnumType, VarType))
775 if (ED->hasAttr<FlagEnumAttr>())
776 return !S.IsValueInFlagEnum(ED, Val, false);
778 while (EI != EIEnd && EI->first < Val)
781 if (EI != EIEnd && EI->first == Val)
787 static void checkEnumTypesInSwitchStmt(Sema &S, const Expr *Cond,
789 QualType CondType = Cond->getType();
790 QualType CaseType = Case->getType();
792 const EnumType *CondEnumType = CondType->getAs<EnumType>();
793 const EnumType *CaseEnumType = CaseType->getAs<EnumType>();
794 if (!CondEnumType || !CaseEnumType)
797 // Ignore anonymous enums.
798 if (!CondEnumType->getDecl()->getIdentifier() &&
799 !CondEnumType->getDecl()->getTypedefNameForAnonDecl())
801 if (!CaseEnumType->getDecl()->getIdentifier() &&
802 !CaseEnumType->getDecl()->getTypedefNameForAnonDecl())
805 if (S.Context.hasSameUnqualifiedType(CondType, CaseType))
808 S.Diag(Case->getExprLoc(), diag::warn_comparison_of_mixed_enum_types_switch)
809 << CondType << CaseType << Cond->getSourceRange()
810 << Case->getSourceRange();
814 Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
816 SwitchStmt *SS = cast<SwitchStmt>(Switch);
817 bool CaseListIsIncomplete = getCurFunction()->SwitchStack.back().getInt();
818 assert(SS == getCurFunction()->SwitchStack.back().getPointer() &&
819 "switch stack missing push/pop!");
821 getCurFunction()->SwitchStack.pop_back();
823 if (!BodyStmt) return StmtError();
824 SS->setBody(BodyStmt, SwitchLoc);
826 Expr *CondExpr = SS->getCond();
827 if (!CondExpr) return StmtError();
829 QualType CondType = CondExpr->getType();
832 // Integral promotions are performed (on the switch condition).
834 // A case value unrepresentable by the original switch condition
835 // type (before the promotion) doesn't make sense, even when it can
836 // be represented by the promoted type. Therefore we need to find
837 // the pre-promotion type of the switch condition.
838 const Expr *CondExprBeforePromotion = CondExpr;
839 QualType CondTypeBeforePromotion =
840 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
842 // Get the bitwidth of the switched-on value after promotions. We must
843 // convert the integer case values to this width before comparison.
844 bool HasDependentValue
845 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
846 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
847 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
849 // Get the width and signedness that the condition might actually have, for
851 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
853 unsigned CondWidthBeforePromotion
854 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
855 bool CondIsSignedBeforePromotion
856 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
858 // Accumulate all of the case values in a vector so that we can sort them
859 // and detect duplicates. This vector contains the APInt for the case after
860 // it has been converted to the condition type.
861 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
864 // Keep track of any GNU case ranges we see. The APSInt is the low value.
865 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
866 CaseRangesTy CaseRanges;
868 DefaultStmt *TheDefaultStmt = nullptr;
870 bool CaseListIsErroneous = false;
872 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
873 SC = SC->getNextSwitchCase()) {
875 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
876 if (TheDefaultStmt) {
877 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
878 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
880 // FIXME: Remove the default statement from the switch block so that
881 // we'll return a valid AST. This requires recursing down the AST and
882 // finding it, not something we are set up to do right now. For now,
883 // just lop the entire switch stmt out of the AST.
884 CaseListIsErroneous = true;
889 CaseStmt *CS = cast<CaseStmt>(SC);
891 Expr *Lo = CS->getLHS();
893 if (Lo->isValueDependent()) {
894 HasDependentValue = true;
898 // We already verified that the expression has a constant value;
899 // get that value (prior to conversions).
900 const Expr *LoBeforePromotion = Lo;
901 GetTypeBeforeIntegralPromotion(LoBeforePromotion);
902 llvm::APSInt LoVal = LoBeforePromotion->EvaluateKnownConstInt(Context);
904 // Check the unconverted value is within the range of possible values of
905 // the switch expression.
906 checkCaseValue(*this, Lo->getBeginLoc(), LoVal, CondWidthBeforePromotion,
907 CondIsSignedBeforePromotion);
909 // FIXME: This duplicates the check performed for warn_not_in_enum below.
910 checkEnumTypesInSwitchStmt(*this, CondExprBeforePromotion,
913 // Convert the value to the same width/sign as the condition.
914 AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
916 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
918 if (CS->getRHS()->isValueDependent()) {
919 HasDependentValue = true;
922 CaseRanges.push_back(std::make_pair(LoVal, CS));
924 CaseVals.push_back(std::make_pair(LoVal, CS));
928 if (!HasDependentValue) {
929 // If we don't have a default statement, check whether the
930 // condition is constant.
931 llvm::APSInt ConstantCondValue;
932 bool HasConstantCond = false;
933 if (!HasDependentValue && !TheDefaultStmt) {
934 Expr::EvalResult Result;
935 HasConstantCond = CondExpr->EvaluateAsInt(Result, Context,
936 Expr::SE_AllowSideEffects);
937 if (Result.Val.isInt())
938 ConstantCondValue = Result.Val.getInt();
939 assert(!HasConstantCond ||
940 (ConstantCondValue.getBitWidth() == CondWidth &&
941 ConstantCondValue.isSigned() == CondIsSigned));
943 bool ShouldCheckConstantCond = HasConstantCond;
945 // Sort all the scalar case values so we can easily detect duplicates.
946 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
948 if (!CaseVals.empty()) {
949 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
950 if (ShouldCheckConstantCond &&
951 CaseVals[i].first == ConstantCondValue)
952 ShouldCheckConstantCond = false;
954 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
955 // If we have a duplicate, report it.
956 // First, determine if either case value has a name
957 StringRef PrevString, CurrString;
958 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
959 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
960 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
961 PrevString = DeclRef->getDecl()->getName();
963 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
964 CurrString = DeclRef->getDecl()->getName();
966 SmallString<16> CaseValStr;
967 CaseVals[i-1].first.toString(CaseValStr);
969 if (PrevString == CurrString)
970 Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
971 diag::err_duplicate_case)
972 << (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
974 Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
975 diag::err_duplicate_case_differing_expr)
976 << (PrevString.empty() ? StringRef(CaseValStr) : PrevString)
977 << (CurrString.empty() ? StringRef(CaseValStr) : CurrString)
980 Diag(CaseVals[i - 1].second->getLHS()->getBeginLoc(),
981 diag::note_duplicate_case_prev);
982 // FIXME: We really want to remove the bogus case stmt from the
983 // substmt, but we have no way to do this right now.
984 CaseListIsErroneous = true;
989 // Detect duplicate case ranges, which usually don't exist at all in
991 if (!CaseRanges.empty()) {
992 // Sort all the case ranges by their low value so we can easily detect
993 // overlaps between ranges.
994 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
996 // Scan the ranges, computing the high values and removing empty ranges.
997 std::vector<llvm::APSInt> HiVals;
998 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
999 llvm::APSInt &LoVal = CaseRanges[i].first;
1000 CaseStmt *CR = CaseRanges[i].second;
1001 Expr *Hi = CR->getRHS();
1003 const Expr *HiBeforePromotion = Hi;
1004 GetTypeBeforeIntegralPromotion(HiBeforePromotion);
1005 llvm::APSInt HiVal = HiBeforePromotion->EvaluateKnownConstInt(Context);
1007 // Check the unconverted value is within the range of possible values of
1008 // the switch expression.
1009 checkCaseValue(*this, Hi->getBeginLoc(), HiVal,
1010 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
1012 // Convert the value to the same width/sign as the condition.
1013 AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
1015 // If the low value is bigger than the high value, the case is empty.
1016 if (LoVal > HiVal) {
1017 Diag(CR->getLHS()->getBeginLoc(), diag::warn_case_empty_range)
1018 << SourceRange(CR->getLHS()->getBeginLoc(), Hi->getEndLoc());
1019 CaseRanges.erase(CaseRanges.begin()+i);
1025 if (ShouldCheckConstantCond &&
1026 LoVal <= ConstantCondValue &&
1027 ConstantCondValue <= HiVal)
1028 ShouldCheckConstantCond = false;
1030 HiVals.push_back(HiVal);
1033 // Rescan the ranges, looking for overlap with singleton values and other
1034 // ranges. Since the range list is sorted, we only need to compare case
1035 // ranges with their neighbors.
1036 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1037 llvm::APSInt &CRLo = CaseRanges[i].first;
1038 llvm::APSInt &CRHi = HiVals[i];
1039 CaseStmt *CR = CaseRanges[i].second;
1041 // Check to see whether the case range overlaps with any
1043 CaseStmt *OverlapStmt = nullptr;
1044 llvm::APSInt OverlapVal(32);
1046 // Find the smallest value >= the lower bound. If I is in the
1047 // case range, then we have overlap.
1048 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
1049 CaseVals.end(), CRLo,
1050 CaseCompareFunctor());
1051 if (I != CaseVals.end() && I->first < CRHi) {
1052 OverlapVal = I->first; // Found overlap with scalar.
1053 OverlapStmt = I->second;
1056 // Find the smallest value bigger than the upper bound.
1057 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1058 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1059 OverlapVal = (I-1)->first; // Found overlap with scalar.
1060 OverlapStmt = (I-1)->second;
1063 // Check to see if this case stmt overlaps with the subsequent
1065 if (i && CRLo <= HiVals[i-1]) {
1066 OverlapVal = HiVals[i-1]; // Found overlap with range.
1067 OverlapStmt = CaseRanges[i-1].second;
1071 // If we have a duplicate, report it.
1072 Diag(CR->getLHS()->getBeginLoc(), diag::err_duplicate_case)
1073 << OverlapVal.toString(10);
1074 Diag(OverlapStmt->getLHS()->getBeginLoc(),
1075 diag::note_duplicate_case_prev);
1076 // FIXME: We really want to remove the bogus case stmt from the
1077 // substmt, but we have no way to do this right now.
1078 CaseListIsErroneous = true;
1083 // Complain if we have a constant condition and we didn't find a match.
1084 if (!CaseListIsErroneous && !CaseListIsIncomplete &&
1085 ShouldCheckConstantCond) {
1086 // TODO: it would be nice if we printed enums as enums, chars as
1088 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1089 << ConstantCondValue.toString(10)
1090 << CondExpr->getSourceRange();
1093 // Check to see if switch is over an Enum and handles all of its
1094 // values. We only issue a warning if there is not 'default:', but
1095 // we still do the analysis to preserve this information in the AST
1096 // (which can be used by flow-based analyes).
1098 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
1100 // If switch has default case, then ignore it.
1101 if (!CaseListIsErroneous && !CaseListIsIncomplete && !HasConstantCond &&
1102 ET && ET->getDecl()->isCompleteDefinition()) {
1103 const EnumDecl *ED = ET->getDecl();
1104 EnumValsTy EnumVals;
1106 // Gather all enum values, set their type and sort them,
1107 // allowing easier comparison with CaseVals.
1108 for (auto *EDI : ED->enumerators()) {
1109 llvm::APSInt Val = EDI->getInitVal();
1110 AdjustAPSInt(Val, CondWidth, CondIsSigned);
1111 EnumVals.push_back(std::make_pair(Val, EDI));
1113 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1114 auto EI = EnumVals.begin(), EIEnd =
1115 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1117 // See which case values aren't in enum.
1118 for (CaseValsTy::const_iterator CI = CaseVals.begin();
1119 CI != CaseVals.end(); CI++) {
1120 Expr *CaseExpr = CI->second->getLHS();
1121 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1123 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1124 << CondTypeBeforePromotion;
1127 // See which of case ranges aren't in enum
1128 EI = EnumVals.begin();
1129 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1130 RI != CaseRanges.end(); RI++) {
1131 Expr *CaseExpr = RI->second->getLHS();
1132 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1134 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1135 << CondTypeBeforePromotion;
1138 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1139 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1141 CaseExpr = RI->second->getRHS();
1142 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1144 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1145 << CondTypeBeforePromotion;
1148 // Check which enum vals aren't in switch
1149 auto CI = CaseVals.begin();
1150 auto RI = CaseRanges.begin();
1151 bool hasCasesNotInSwitch = false;
1153 SmallVector<DeclarationName,8> UnhandledNames;
1155 for (EI = EnumVals.begin(); EI != EIEnd; EI++) {
1156 // Don't warn about omitted unavailable EnumConstantDecls.
1157 switch (EI->second->getAvailability()) {
1159 // Omitting a deprecated constant is ok; it should never materialize.
1160 case AR_Unavailable:
1163 case AR_NotYetIntroduced:
1164 // Partially available enum constants should be present. Note that we
1165 // suppress -Wunguarded-availability diagnostics for such uses.
1170 // Drop unneeded case values
1171 while (CI != CaseVals.end() && CI->first < EI->first)
1174 if (CI != CaseVals.end() && CI->first == EI->first)
1177 // Drop unneeded case ranges
1178 for (; RI != CaseRanges.end(); RI++) {
1180 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1181 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1182 if (EI->first <= Hi)
1186 if (RI == CaseRanges.end() || EI->first < RI->first) {
1187 hasCasesNotInSwitch = true;
1188 UnhandledNames.push_back(EI->second->getDeclName());
1192 if (TheDefaultStmt && UnhandledNames.empty() && ED->isClosedNonFlag())
1193 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
1195 // Produce a nice diagnostic if multiple values aren't handled.
1196 if (!UnhandledNames.empty()) {
1197 DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
1198 TheDefaultStmt ? diag::warn_def_missing_case
1199 : diag::warn_missing_case)
1200 << (int)UnhandledNames.size();
1202 for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
1204 DB << UnhandledNames[I];
1207 if (!hasCasesNotInSwitch)
1208 SS->setAllEnumCasesCovered();
1213 DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), BodyStmt,
1214 diag::warn_empty_switch_body);
1216 // FIXME: If the case list was broken is some way, we don't have a good system
1217 // to patch it up. Instead, just return the whole substmt as broken.
1218 if (CaseListIsErroneous)
1225 Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1227 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
1230 if (const EnumType *ET = DstType->getAs<EnumType>())
1231 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
1232 SrcType->isIntegerType()) {
1233 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1234 SrcExpr->isIntegerConstantExpr(Context)) {
1235 // Get the bitwidth of the enum value before promotions.
1236 unsigned DstWidth = Context.getIntWidth(DstType);
1237 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1239 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1240 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
1241 const EnumDecl *ED = ET->getDecl();
1243 if (!ED->isClosed())
1246 if (ED->hasAttr<FlagEnumAttr>()) {
1247 if (!IsValueInFlagEnum(ED, RhsVal, true))
1248 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1249 << DstType.getUnqualifiedType();
1251 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1253 EnumValsTy EnumVals;
1255 // Gather all enum values, set their type and sort them,
1256 // allowing easier comparison with rhs constant.
1257 for (auto *EDI : ED->enumerators()) {
1258 llvm::APSInt Val = EDI->getInitVal();
1259 AdjustAPSInt(Val, DstWidth, DstIsSigned);
1260 EnumVals.push_back(std::make_pair(Val, EDI));
1262 if (EnumVals.empty())
1264 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1265 EnumValsTy::iterator EIend =
1266 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1268 // See which values aren't in the enum.
1269 EnumValsTy::const_iterator EI = EnumVals.begin();
1270 while (EI != EIend && EI->first < RhsVal)
1272 if (EI == EIend || EI->first != RhsVal) {
1273 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1274 << DstType.getUnqualifiedType();
1281 StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
1283 if (Cond.isInvalid())
1286 auto CondVal = Cond.get();
1287 CheckBreakContinueBinding(CondVal.second);
1289 if (CondVal.second &&
1290 !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc()))
1291 CommaVisitor(*this).Visit(CondVal.second);
1293 if (isa<NullStmt>(Body))
1294 getCurCompoundScope().setHasEmptyLoopBodies();
1296 return WhileStmt::Create(Context, CondVal.first, CondVal.second, Body,
1301 Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
1302 SourceLocation WhileLoc, SourceLocation CondLParen,
1303 Expr *Cond, SourceLocation CondRParen) {
1304 assert(Cond && "ActOnDoStmt(): missing expression");
1306 CheckBreakContinueBinding(Cond);
1307 ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond);
1308 if (CondResult.isInvalid())
1310 Cond = CondResult.get();
1312 CondResult = ActOnFinishFullExpr(Cond, DoLoc, /*DiscardedValue*/ false);
1313 if (CondResult.isInvalid())
1315 Cond = CondResult.get();
1317 // Only call the CommaVisitor for C89 due to differences in scope flags.
1318 if (Cond && !getLangOpts().C99 && !getLangOpts().CPlusPlus &&
1319 !Diags.isIgnored(diag::warn_comma_operator, Cond->getExprLoc()))
1320 CommaVisitor(*this).Visit(Cond);
1322 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
1326 // Use SetVector since the diagnostic cares about the ordering of the Decl's.
1327 using DeclSetVector =
1328 llvm::SetVector<VarDecl *, llvm::SmallVector<VarDecl *, 8>,
1329 llvm::SmallPtrSet<VarDecl *, 8>>;
1331 // This visitor will traverse a conditional statement and store all
1332 // the evaluated decls into a vector. Simple is set to true if none
1333 // of the excluded constructs are used.
1334 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1335 DeclSetVector &Decls;
1336 SmallVectorImpl<SourceRange> &Ranges;
1339 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1341 DeclExtractor(Sema &S, DeclSetVector &Decls,
1342 SmallVectorImpl<SourceRange> &Ranges) :
1343 Inherited(S.Context),
1348 bool isSimple() { return Simple; }
1350 // Replaces the method in EvaluatedExprVisitor.
1351 void VisitMemberExpr(MemberExpr* E) {
1355 // Any Stmt not whitelisted will cause the condition to be marked complex.
1356 void VisitStmt(Stmt *S) {
1360 void VisitBinaryOperator(BinaryOperator *E) {
1365 void VisitCastExpr(CastExpr *E) {
1366 Visit(E->getSubExpr());
1369 void VisitUnaryOperator(UnaryOperator *E) {
1370 // Skip checking conditionals with derefernces.
1371 if (E->getOpcode() == UO_Deref)
1374 Visit(E->getSubExpr());
1377 void VisitConditionalOperator(ConditionalOperator *E) {
1378 Visit(E->getCond());
1379 Visit(E->getTrueExpr());
1380 Visit(E->getFalseExpr());
1383 void VisitParenExpr(ParenExpr *E) {
1384 Visit(E->getSubExpr());
1387 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1388 Visit(E->getOpaqueValue()->getSourceExpr());
1389 Visit(E->getFalseExpr());
1392 void VisitIntegerLiteral(IntegerLiteral *E) { }
1393 void VisitFloatingLiteral(FloatingLiteral *E) { }
1394 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1395 void VisitCharacterLiteral(CharacterLiteral *E) { }
1396 void VisitGNUNullExpr(GNUNullExpr *E) { }
1397 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1399 void VisitDeclRefExpr(DeclRefExpr *E) {
1400 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1402 // Don't allow unhandled Decl types.
1407 Ranges.push_back(E->getSourceRange());
1412 }; // end class DeclExtractor
1414 // DeclMatcher checks to see if the decls are used in a non-evaluated
1416 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1417 DeclSetVector &Decls;
1421 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1423 DeclMatcher(Sema &S, DeclSetVector &Decls, Stmt *Statement) :
1424 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1425 if (!Statement) return;
1430 void VisitReturnStmt(ReturnStmt *S) {
1434 void VisitBreakStmt(BreakStmt *S) {
1438 void VisitGotoStmt(GotoStmt *S) {
1442 void VisitCastExpr(CastExpr *E) {
1443 if (E->getCastKind() == CK_LValueToRValue)
1444 CheckLValueToRValueCast(E->getSubExpr());
1446 Visit(E->getSubExpr());
1449 void CheckLValueToRValueCast(Expr *E) {
1450 E = E->IgnoreParenImpCasts();
1452 if (isa<DeclRefExpr>(E)) {
1456 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1457 Visit(CO->getCond());
1458 CheckLValueToRValueCast(CO->getTrueExpr());
1459 CheckLValueToRValueCast(CO->getFalseExpr());
1463 if (BinaryConditionalOperator *BCO =
1464 dyn_cast<BinaryConditionalOperator>(E)) {
1465 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1466 CheckLValueToRValueCast(BCO->getFalseExpr());
1473 void VisitDeclRefExpr(DeclRefExpr *E) {
1474 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1475 if (Decls.count(VD))
1479 void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
1480 // Only need to visit the semantics for POE.
1481 // SyntaticForm doesn't really use the Decal.
1482 for (auto *S : POE->semantics()) {
1483 if (auto *OVE = dyn_cast<OpaqueValueExpr>(S))
1484 // Look past the OVE into the expression it binds.
1485 Visit(OVE->getSourceExpr());
1491 bool FoundDeclInUse() { return FoundDecl; }
1493 }; // end class DeclMatcher
1495 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1496 Expr *Third, Stmt *Body) {
1497 // Condition is empty
1498 if (!Second) return;
1500 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1501 Second->getBeginLoc()))
1504 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1505 DeclSetVector Decls;
1506 SmallVector<SourceRange, 10> Ranges;
1507 DeclExtractor DE(S, Decls, Ranges);
1510 // Don't analyze complex conditionals.
1511 if (!DE.isSimple()) return;
1514 if (Decls.size() == 0) return;
1516 // Don't warn on volatile, static, or global variables.
1517 for (auto *VD : Decls)
1518 if (VD->getType().isVolatileQualified() || VD->hasGlobalStorage())
1521 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1522 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1523 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1526 // Load decl names into diagnostic.
1527 if (Decls.size() > 4) {
1530 PDiag << (unsigned)Decls.size();
1531 for (auto *VD : Decls)
1532 PDiag << VD->getDeclName();
1535 for (auto Range : Ranges)
1538 S.Diag(Ranges.begin()->getBegin(), PDiag);
1541 // If Statement is an incemement or decrement, return true and sets the
1542 // variables Increment and DRE.
1543 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1544 DeclRefExpr *&DRE) {
1545 if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement))
1546 if (!Cleanups->cleanupsHaveSideEffects())
1547 Statement = Cleanups->getSubExpr();
1549 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1550 switch (UO->getOpcode()) {
1551 default: return false;
1561 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1565 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1566 FunctionDecl *FD = Call->getDirectCallee();
1567 if (!FD || !FD->isOverloadedOperator()) return false;
1568 switch (FD->getOverloadedOperator()) {
1569 default: return false;
1577 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1584 // A visitor to determine if a continue or break statement is a
1586 class BreakContinueFinder : public ConstEvaluatedExprVisitor<BreakContinueFinder> {
1587 SourceLocation BreakLoc;
1588 SourceLocation ContinueLoc;
1589 bool InSwitch = false;
1592 BreakContinueFinder(Sema &S, const Stmt* Body) :
1593 Inherited(S.Context) {
1597 typedef ConstEvaluatedExprVisitor<BreakContinueFinder> Inherited;
1599 void VisitContinueStmt(const ContinueStmt* E) {
1600 ContinueLoc = E->getContinueLoc();
1603 void VisitBreakStmt(const BreakStmt* E) {
1605 BreakLoc = E->getBreakLoc();
1608 void VisitSwitchStmt(const SwitchStmt* S) {
1609 if (const Stmt *Init = S->getInit())
1611 if (const Stmt *CondVar = S->getConditionVariableDeclStmt())
1613 if (const Stmt *Cond = S->getCond())
1616 // Don't return break statements from the body of a switch.
1618 if (const Stmt *Body = S->getBody())
1623 void VisitForStmt(const ForStmt *S) {
1624 // Only visit the init statement of a for loop; the body
1625 // has a different break/continue scope.
1626 if (const Stmt *Init = S->getInit())
1630 void VisitWhileStmt(const WhileStmt *) {
1631 // Do nothing; the children of a while loop have a different
1632 // break/continue scope.
1635 void VisitDoStmt(const DoStmt *) {
1636 // Do nothing; the children of a while loop have a different
1637 // break/continue scope.
1640 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
1641 // Only visit the initialization of a for loop; the body
1642 // has a different break/continue scope.
1643 if (const Stmt *Init = S->getInit())
1645 if (const Stmt *Range = S->getRangeStmt())
1647 if (const Stmt *Begin = S->getBeginStmt())
1649 if (const Stmt *End = S->getEndStmt())
1653 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
1654 // Only visit the initialization of a for loop; the body
1655 // has a different break/continue scope.
1656 if (const Stmt *Element = S->getElement())
1658 if (const Stmt *Collection = S->getCollection())
1662 bool ContinueFound() { return ContinueLoc.isValid(); }
1663 bool BreakFound() { return BreakLoc.isValid(); }
1664 SourceLocation GetContinueLoc() { return ContinueLoc; }
1665 SourceLocation GetBreakLoc() { return BreakLoc; }
1667 }; // end class BreakContinueFinder
1669 // Emit a warning when a loop increment/decrement appears twice per loop
1670 // iteration. The conditions which trigger this warning are:
1671 // 1) The last statement in the loop body and the third expression in the
1672 // for loop are both increment or both decrement of the same variable
1673 // 2) No continue statements in the loop body.
1674 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1675 // Return when there is nothing to check.
1676 if (!Body || !Third) return;
1678 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1679 Third->getBeginLoc()))
1682 // Get the last statement from the loop body.
1683 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1684 if (!CS || CS->body_empty()) return;
1685 Stmt *LastStmt = CS->body_back();
1686 if (!LastStmt) return;
1688 bool LoopIncrement, LastIncrement;
1689 DeclRefExpr *LoopDRE, *LastDRE;
1691 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1692 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1694 // Check that the two statements are both increments or both decrements
1695 // on the same variable.
1696 if (LoopIncrement != LastIncrement ||
1697 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1699 if (BreakContinueFinder(S, Body).ContinueFound()) return;
1701 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1702 << LastDRE->getDecl() << LastIncrement;
1703 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1710 void Sema::CheckBreakContinueBinding(Expr *E) {
1711 if (!E || getLangOpts().CPlusPlus)
1713 BreakContinueFinder BCFinder(*this, E);
1714 Scope *BreakParent = CurScope->getBreakParent();
1715 if (BCFinder.BreakFound() && BreakParent) {
1716 if (BreakParent->getFlags() & Scope::SwitchScope) {
1717 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1719 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1722 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1723 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1728 StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1729 Stmt *First, ConditionResult Second,
1730 FullExprArg third, SourceLocation RParenLoc,
1732 if (Second.isInvalid())
1735 if (!getLangOpts().CPlusPlus) {
1736 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
1737 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1738 // declare identifiers for objects having storage class 'auto' or
1740 for (auto *DI : DS->decls()) {
1741 VarDecl *VD = dyn_cast<VarDecl>(DI);
1742 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
1745 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1746 DI->setInvalidDecl();
1752 CheckBreakContinueBinding(Second.get().second);
1753 CheckBreakContinueBinding(third.get());
1755 if (!Second.get().first)
1756 CheckForLoopConditionalStatement(*this, Second.get().second, third.get(),
1758 CheckForRedundantIteration(*this, third.get(), Body);
1760 if (Second.get().second &&
1761 !Diags.isIgnored(diag::warn_comma_operator,
1762 Second.get().second->getExprLoc()))
1763 CommaVisitor(*this).Visit(Second.get().second);
1765 Expr *Third = third.release().getAs<Expr>();
1766 if (isa<NullStmt>(Body))
1767 getCurCompoundScope().setHasEmptyLoopBodies();
1769 return new (Context)
1770 ForStmt(Context, First, Second.get().second, Second.get().first, Third,
1771 Body, ForLoc, LParenLoc, RParenLoc);
1774 /// In an Objective C collection iteration statement:
1776 /// x can be an arbitrary l-value expression. Bind it up as a
1777 /// full-expression.
1778 StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
1779 // Reduce placeholder expressions here. Note that this rejects the
1780 // use of pseudo-object l-values in this position.
1781 ExprResult result = CheckPlaceholderExpr(E);
1782 if (result.isInvalid()) return StmtError();
1785 ExprResult FullExpr = ActOnFinishFullExpr(E, /*DiscardedValue*/ false);
1786 if (FullExpr.isInvalid())
1788 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
1792 Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1796 ExprResult result = CorrectDelayedTyposInExpr(collection);
1797 if (!result.isUsable())
1799 collection = result.get();
1801 // Bail out early if we've got a type-dependent expression.
1802 if (collection->isTypeDependent()) return collection;
1804 // Perform normal l-value conversion.
1805 result = DefaultFunctionArrayLvalueConversion(collection);
1806 if (result.isInvalid())
1808 collection = result.get();
1810 // The operand needs to have object-pointer type.
1811 // TODO: should we do a contextual conversion?
1812 const ObjCObjectPointerType *pointerType =
1813 collection->getType()->getAs<ObjCObjectPointerType>();
1815 return Diag(forLoc, diag::err_collection_expr_type)
1816 << collection->getType() << collection->getSourceRange();
1818 // Check that the operand provides
1819 // - countByEnumeratingWithState:objects:count:
1820 const ObjCObjectType *objectType = pointerType->getObjectType();
1821 ObjCInterfaceDecl *iface = objectType->getInterface();
1823 // If we have a forward-declared type, we can't do this check.
1824 // Under ARC, it is an error not to have a forward-declared class.
1826 (getLangOpts().ObjCAutoRefCount
1827 ? RequireCompleteType(forLoc, QualType(objectType, 0),
1828 diag::err_arc_collection_forward, collection)
1829 : !isCompleteType(forLoc, QualType(objectType, 0)))) {
1830 // Otherwise, if we have any useful type information, check that
1831 // the type declares the appropriate method.
1832 } else if (iface || !objectType->qual_empty()) {
1833 IdentifierInfo *selectorIdents[] = {
1834 &Context.Idents.get("countByEnumeratingWithState"),
1835 &Context.Idents.get("objects"),
1836 &Context.Idents.get("count")
1838 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1840 ObjCMethodDecl *method = nullptr;
1842 // If there's an interface, look in both the public and private APIs.
1844 method = iface->lookupInstanceMethod(selector);
1845 if (!method) method = iface->lookupPrivateMethod(selector);
1848 // Also check protocol qualifiers.
1850 method = LookupMethodInQualifiedType(selector, pointerType,
1853 // If we didn't find it anywhere, give up.
1855 Diag(forLoc, diag::warn_collection_expr_type)
1856 << collection->getType() << selector << collection->getSourceRange();
1859 // TODO: check for an incompatible signature?
1862 // Wrap up any cleanups in the expression.
1867 Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1868 Stmt *First, Expr *collection,
1869 SourceLocation RParenLoc) {
1870 setFunctionHasBranchProtectedScope();
1872 ExprResult CollectionExprResult =
1873 CheckObjCForCollectionOperand(ForLoc, collection);
1877 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
1878 if (!DS->isSingleDecl())
1879 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1880 diag::err_toomany_element_decls));
1882 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1883 if (!D || D->isInvalidDecl())
1886 FirstType = D->getType();
1887 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1888 // declare identifiers for objects having storage class 'auto' or
1890 if (!D->hasLocalStorage())
1891 return StmtError(Diag(D->getLocation(),
1892 diag::err_non_local_variable_decl_in_for));
1894 // If the type contained 'auto', deduce the 'auto' to 'id'.
1895 if (FirstType->getContainedAutoType()) {
1896 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1898 Expr *DeducedInit = &OpaqueId;
1899 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1901 DiagnoseAutoDeductionFailure(D, DeducedInit);
1902 if (FirstType.isNull()) {
1903 D->setInvalidDecl();
1907 D->setType(FirstType);
1909 if (!inTemplateInstantiation()) {
1910 SourceLocation Loc =
1911 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
1912 Diag(Loc, diag::warn_auto_var_is_id)
1913 << D->getDeclName();
1918 Expr *FirstE = cast<Expr>(First);
1919 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
1921 Diag(First->getBeginLoc(), diag::err_selector_element_not_lvalue)
1922 << First->getSourceRange());
1924 FirstType = static_cast<Expr*>(First)->getType();
1925 if (FirstType.isConstQualified())
1926 Diag(ForLoc, diag::err_selector_element_const_type)
1927 << FirstType << First->getSourceRange();
1929 if (!FirstType->isDependentType() &&
1930 !FirstType->isObjCObjectPointerType() &&
1931 !FirstType->isBlockPointerType())
1932 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1933 << FirstType << First->getSourceRange());
1936 if (CollectionExprResult.isInvalid())
1939 CollectionExprResult =
1940 ActOnFinishFullExpr(CollectionExprResult.get(), /*DiscardedValue*/ false);
1941 if (CollectionExprResult.isInvalid())
1944 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1945 nullptr, ForLoc, RParenLoc);
1948 /// Finish building a variable declaration for a for-range statement.
1949 /// \return true if an error occurs.
1950 static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1951 SourceLocation Loc, int DiagID) {
1952 if (Decl->getType()->isUndeducedType()) {
1953 ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
1954 if (!Res.isUsable()) {
1955 Decl->setInvalidDecl();
1961 // Deduce the type for the iterator variable now rather than leaving it to
1962 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1964 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
1965 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
1967 SemaRef.Diag(Loc, DiagID) << Init->getType();
1968 if (InitType.isNull()) {
1969 Decl->setInvalidDecl();
1972 Decl->setType(InitType);
1974 // In ARC, infer lifetime.
1975 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1976 // we're doing the equivalent of fast iteration.
1977 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1978 SemaRef.inferObjCARCLifetime(Decl))
1979 Decl->setInvalidDecl();
1981 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false);
1982 SemaRef.FinalizeDeclaration(Decl);
1983 SemaRef.CurContext->addHiddenDecl(Decl);
1988 // An enum to represent whether something is dealing with a call to begin()
1989 // or a call to end() in a range-based for loop.
1990 enum BeginEndFunction {
1995 /// Produce a note indicating which begin/end function was implicitly called
1996 /// by a C++11 for-range statement. This is often not obvious from the code,
1997 /// nor from the diagnostics produced when analysing the implicit expressions
1998 /// required in a for-range statement.
1999 void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
2000 BeginEndFunction BEF) {
2001 CallExpr *CE = dyn_cast<CallExpr>(E);
2004 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
2007 SourceLocation Loc = D->getLocation();
2009 std::string Description;
2010 bool IsTemplate = false;
2011 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
2012 Description = SemaRef.getTemplateArgumentBindingsText(
2013 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
2017 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
2018 << BEF << IsTemplate << Description << E->getType();
2021 /// Build a variable declaration for a for-range statement.
2022 VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
2023 QualType Type, StringRef Name) {
2024 DeclContext *DC = SemaRef.CurContext;
2025 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
2026 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
2027 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
2029 Decl->setImplicit();
2035 static bool ObjCEnumerationCollection(Expr *Collection) {
2036 return !Collection->isTypeDependent()
2037 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
2040 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
2042 /// C++11 [stmt.ranged]:
2043 /// A range-based for statement is equivalent to
2046 /// auto && __range = range-init;
2047 /// for ( auto __begin = begin-expr,
2048 /// __end = end-expr;
2049 /// __begin != __end;
2051 /// for-range-declaration = *__begin;
2056 /// The body of the loop is not available yet, since it cannot be analysed until
2057 /// we have determined the type of the for-range-declaration.
2058 StmtResult Sema::ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
2059 SourceLocation CoawaitLoc, Stmt *InitStmt,
2060 Stmt *First, SourceLocation ColonLoc,
2061 Expr *Range, SourceLocation RParenLoc,
2062 BuildForRangeKind Kind) {
2066 if (Range && ObjCEnumerationCollection(Range)) {
2067 // FIXME: Support init-statements in Objective-C++20 ranged for statement.
2069 return Diag(InitStmt->getBeginLoc(), diag::err_objc_for_range_init_stmt)
2070 << InitStmt->getSourceRange();
2071 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
2074 DeclStmt *DS = dyn_cast<DeclStmt>(First);
2075 assert(DS && "first part of for range not a decl stmt");
2077 if (!DS->isSingleDecl()) {
2078 Diag(DS->getBeginLoc(), diag::err_type_defined_in_for_range);
2082 Decl *LoopVar = DS->getSingleDecl();
2083 if (LoopVar->isInvalidDecl() || !Range ||
2084 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
2085 LoopVar->setInvalidDecl();
2089 // Build the coroutine state immediately and not later during template
2091 if (!CoawaitLoc.isInvalid()) {
2092 if (!ActOnCoroutineBodyStart(S, CoawaitLoc, "co_await"))
2096 // Build auto && __range = range-init
2097 // Divide by 2, since the variables are in the inner scope (loop body).
2098 const auto DepthStr = std::to_string(S->getDepth() / 2);
2099 SourceLocation RangeLoc = Range->getBeginLoc();
2100 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
2101 Context.getAutoRRefDeductType(),
2102 std::string("__range") + DepthStr);
2103 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
2104 diag::err_for_range_deduction_failure)) {
2105 LoopVar->setInvalidDecl();
2109 // Claim the type doesn't contain auto: we've already done the checking.
2110 DeclGroupPtrTy RangeGroup =
2111 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1));
2112 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
2113 if (RangeDecl.isInvalid()) {
2114 LoopVar->setInvalidDecl();
2118 return BuildCXXForRangeStmt(
2119 ForLoc, CoawaitLoc, InitStmt, ColonLoc, RangeDecl.get(),
2120 /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
2121 /*Cond=*/nullptr, /*Inc=*/nullptr, DS, RParenLoc, Kind);
2124 /// Create the initialization, compare, and increment steps for
2125 /// the range-based for loop expression.
2126 /// This function does not handle array-based for loops,
2127 /// which are created in Sema::BuildCXXForRangeStmt.
2129 /// \returns a ForRangeStatus indicating success or what kind of error occurred.
2130 /// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2131 /// CandidateSet and BEF are set and some non-success value is returned on
2133 static Sema::ForRangeStatus
2134 BuildNonArrayForRange(Sema &SemaRef, Expr *BeginRange, Expr *EndRange,
2135 QualType RangeType, VarDecl *BeginVar, VarDecl *EndVar,
2136 SourceLocation ColonLoc, SourceLocation CoawaitLoc,
2137 OverloadCandidateSet *CandidateSet, ExprResult *BeginExpr,
2138 ExprResult *EndExpr, BeginEndFunction *BEF) {
2139 DeclarationNameInfo BeginNameInfo(
2140 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2141 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2144 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2145 Sema::LookupMemberName);
2146 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2148 auto BuildBegin = [&] {
2150 Sema::ForRangeStatus RangeStatus =
2151 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
2152 BeginMemberLookup, CandidateSet,
2153 BeginRange, BeginExpr);
2155 if (RangeStatus != Sema::FRS_Success) {
2156 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2157 SemaRef.Diag(BeginRange->getBeginLoc(), diag::note_in_for_range)
2158 << ColonLoc << BEF_begin << BeginRange->getType();
2161 if (!CoawaitLoc.isInvalid()) {
2162 // FIXME: getCurScope() should not be used during template instantiation.
2163 // We should pick up the set of unqualified lookup results for operator
2164 // co_await during the initial parse.
2165 *BeginExpr = SemaRef.ActOnCoawaitExpr(SemaRef.getCurScope(), ColonLoc,
2167 if (BeginExpr->isInvalid())
2168 return Sema::FRS_DiagnosticIssued;
2170 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2171 diag::err_for_range_iter_deduction_failure)) {
2172 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2173 return Sema::FRS_DiagnosticIssued;
2175 return Sema::FRS_Success;
2178 auto BuildEnd = [&] {
2180 Sema::ForRangeStatus RangeStatus =
2181 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
2182 EndMemberLookup, CandidateSet,
2184 if (RangeStatus != Sema::FRS_Success) {
2185 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2186 SemaRef.Diag(EndRange->getBeginLoc(), diag::note_in_for_range)
2187 << ColonLoc << BEF_end << EndRange->getType();
2190 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2191 diag::err_for_range_iter_deduction_failure)) {
2192 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2193 return Sema::FRS_DiagnosticIssued;
2195 return Sema::FRS_Success;
2198 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2199 // - if _RangeT is a class type, the unqualified-ids begin and end are
2200 // looked up in the scope of class _RangeT as if by class member access
2201 // lookup (3.4.5), and if either (or both) finds at least one
2202 // declaration, begin-expr and end-expr are __range.begin() and
2203 // __range.end(), respectively;
2204 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2205 if (BeginMemberLookup.isAmbiguous())
2206 return Sema::FRS_DiagnosticIssued;
2208 SemaRef.LookupQualifiedName(EndMemberLookup, D);
2209 if (EndMemberLookup.isAmbiguous())
2210 return Sema::FRS_DiagnosticIssued;
2212 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2213 // Look up the non-member form of the member we didn't find, first.
2214 // This way we prefer a "no viable 'end'" diagnostic over a "i found
2215 // a 'begin' but ignored it because there was no member 'end'"
2217 auto BuildNonmember = [&](
2218 BeginEndFunction BEFFound, LookupResult &Found,
2219 llvm::function_ref<Sema::ForRangeStatus()> BuildFound,
2220 llvm::function_ref<Sema::ForRangeStatus()> BuildNotFound) {
2221 LookupResult OldFound = std::move(Found);
2224 if (Sema::ForRangeStatus Result = BuildNotFound())
2227 switch (BuildFound()) {
2228 case Sema::FRS_Success:
2229 return Sema::FRS_Success;
2231 case Sema::FRS_NoViableFunction:
2232 SemaRef.Diag(BeginRange->getBeginLoc(), diag::err_for_range_invalid)
2233 << BeginRange->getType() << BEFFound;
2234 CandidateSet->NoteCandidates(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 Diag(Range->getBeginLoc(), diag::err_for_range_invalid)
2532 << RangeLoc << Range->getType() << BEFFailure;
2533 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
2535 // Return an error if no fix was discovered.
2536 if (RangeStatus != FRS_Success)
2540 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2541 "invalid range expression in for loop");
2543 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
2544 // C++1z removes this restriction.
2545 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2546 if (!Context.hasSameType(BeginType, EndType)) {
2547 Diag(RangeLoc, getLangOpts().CPlusPlus17
2548 ? diag::warn_for_range_begin_end_types_differ
2549 : diag::ext_for_range_begin_end_types_differ)
2550 << BeginType << EndType;
2551 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2552 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2556 ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
2558 ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
2560 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2561 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2562 VK_LValue, ColonLoc);
2563 if (BeginRef.isInvalid())
2566 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2567 VK_LValue, ColonLoc);
2568 if (EndRef.isInvalid())
2571 // Build and check __begin != __end expression.
2572 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2573 BeginRef.get(), EndRef.get());
2574 if (!NotEqExpr.isInvalid())
2575 NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get());
2576 if (!NotEqExpr.isInvalid())
2578 ActOnFinishFullExpr(NotEqExpr.get(), /*DiscardedValue*/ false);
2579 if (NotEqExpr.isInvalid()) {
2580 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2581 << RangeLoc << 0 << BeginRangeRef.get()->getType();
2582 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2583 if (!Context.hasSameType(BeginType, EndType))
2584 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2588 // Build and check ++__begin expression.
2589 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2590 VK_LValue, ColonLoc);
2591 if (BeginRef.isInvalid())
2594 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2595 if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
2596 // FIXME: getCurScope() should not be used during template instantiation.
2597 // We should pick up the set of unqualified lookup results for operator
2598 // co_await during the initial parse.
2599 IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
2600 if (!IncrExpr.isInvalid())
2601 IncrExpr = ActOnFinishFullExpr(IncrExpr.get(), /*DiscardedValue*/ false);
2602 if (IncrExpr.isInvalid()) {
2603 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2604 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
2605 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2609 // Build and check *__begin expression.
2610 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2611 VK_LValue, ColonLoc);
2612 if (BeginRef.isInvalid())
2615 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2616 if (DerefExpr.isInvalid()) {
2617 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2618 << RangeLoc << 1 << BeginRangeRef.get()->getType();
2619 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2623 // Attach *__begin as initializer for VD. Don't touch it if we're just
2624 // trying to determine whether this would be a valid range.
2625 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2626 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false);
2627 if (LoopVar->isInvalidDecl())
2628 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2632 // Don't bother to actually allocate the result if we're just trying to
2633 // determine whether it would be valid.
2634 if (Kind == BFRK_Check)
2635 return StmtResult();
2637 return new (Context) CXXForRangeStmt(
2638 InitStmt, RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
2639 cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
2640 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
2641 ColonLoc, RParenLoc);
2644 /// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
2646 StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2649 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
2651 ForStmt->setBody(B);
2655 // Warn when the loop variable is a const reference that creates a copy.
2656 // Suggest using the non-reference type for copies. If a copy can be prevented
2657 // suggest the const reference type that would do so.
2658 // For instance, given "for (const &Foo : Range)", suggest
2659 // "for (const Foo : Range)" to denote a copy is made for the loop. If
2660 // possible, also suggest "for (const &Bar : Range)" if this type prevents
2661 // the copy altogether.
2662 static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
2664 QualType RangeInitType) {
2665 const Expr *InitExpr = VD->getInit();
2669 QualType VariableType = VD->getType();
2671 if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr))
2672 if (!Cleanups->cleanupsHaveSideEffects())
2673 InitExpr = Cleanups->getSubExpr();
2675 const MaterializeTemporaryExpr *MTE =
2676 dyn_cast<MaterializeTemporaryExpr>(InitExpr);
2682 const Expr *E = MTE->GetTemporaryExpr()->IgnoreImpCasts();
2684 // Searching for either UnaryOperator for dereference of a pointer or
2685 // CXXOperatorCallExpr for handling iterators.
2686 while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
2687 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
2689 } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
2690 const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
2693 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
2694 E = MTE->GetTemporaryExpr();
2696 E = E->IgnoreImpCasts();
2699 bool ReturnsReference = false;
2700 if (isa<UnaryOperator>(E)) {
2701 ReturnsReference = true;
2703 const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
2704 const FunctionDecl *FD = Call->getDirectCallee();
2705 QualType ReturnType = FD->getReturnType();
2706 ReturnsReference = ReturnType->isReferenceType();
2709 if (ReturnsReference) {
2710 // Loop variable creates a temporary. Suggest either to go with
2711 // non-reference loop variable to indicate a copy is made, or
2712 // the correct time to bind a const reference.
2713 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy)
2714 << VD << VariableType << E->getType();
2715 QualType NonReferenceType = VariableType.getNonReferenceType();
2716 NonReferenceType.removeLocalConst();
2717 QualType NewReferenceType =
2718 SemaRef.Context.getLValueReferenceType(E->getType().withConst());
2719 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_type_or_non_reference)
2720 << NonReferenceType << NewReferenceType << VD->getSourceRange();
2722 // The range always returns a copy, so a temporary is always created.
2723 // Suggest removing the reference from the loop variable.
2724 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy)
2725 << VD << RangeInitType;
2726 QualType NonReferenceType = VariableType.getNonReferenceType();
2727 NonReferenceType.removeLocalConst();
2728 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_non_reference_type)
2729 << NonReferenceType << VD->getSourceRange();
2733 // Warns when the loop variable can be changed to a reference type to
2734 // prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
2735 // "for (const Foo &x : Range)" if this form does not make a copy.
2736 static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
2737 const VarDecl *VD) {
2738 const Expr *InitExpr = VD->getInit();
2742 QualType VariableType = VD->getType();
2744 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
2745 if (!CE->getConstructor()->isCopyConstructor())
2747 } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
2748 if (CE->getCastKind() != CK_LValueToRValue)
2754 // TODO: Determine a maximum size that a POD type can be before a diagnostic
2755 // should be emitted. Also, only ignore POD types with trivial copy
2757 if (VariableType.isPODType(SemaRef.Context))
2760 // Suggest changing from a const variable to a const reference variable
2761 // if doing so will prevent a copy.
2762 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
2763 << VD << VariableType << InitExpr->getType();
2764 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_reference_type)
2765 << SemaRef.Context.getLValueReferenceType(VariableType)
2766 << VD->getSourceRange();
2769 /// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
2770 /// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
2771 /// using "const foo x" to show that a copy is made
2772 /// 2) for (const bar &x : foos) where bar is a temporary initialized by bar.
2773 /// Suggest either "const bar x" to keep the copying or "const foo& x" to
2774 /// prevent the copy.
2775 /// 3) for (const foo x : foos) where x is constructed from a reference foo.
2776 /// Suggest "const foo &x" to prevent the copy.
2777 static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
2778 const CXXForRangeStmt *ForStmt) {
2779 if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy,
2780 ForStmt->getBeginLoc()) &&
2781 SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy,
2782 ForStmt->getBeginLoc()) &&
2783 SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
2784 ForStmt->getBeginLoc())) {
2788 const VarDecl *VD = ForStmt->getLoopVariable();
2792 QualType VariableType = VD->getType();
2794 if (VariableType->isIncompleteType())
2797 const Expr *InitExpr = VD->getInit();
2801 if (VariableType->isReferenceType()) {
2802 DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
2803 ForStmt->getRangeInit()->getType());
2804 } else if (VariableType.isConstQualified()) {
2805 DiagnoseForRangeConstVariableCopies(SemaRef, VD);
2809 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2810 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2811 /// body cannot be performed until after the type of the range variable is
2813 StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2817 if (isa<ObjCForCollectionStmt>(S))
2818 return FinishObjCForCollectionStmt(S, B);
2820 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2821 ForStmt->setBody(B);
2823 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2824 diag::warn_empty_range_based_for_body);
2826 DiagnoseForRangeVariableCopies(*this, ForStmt);
2831 StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2832 SourceLocation LabelLoc,
2833 LabelDecl *TheDecl) {
2834 setFunctionHasBranchIntoScope();
2835 TheDecl->markUsed(Context);
2836 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
2840 Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
2842 // Convert operand to void*
2843 if (!E->isTypeDependent()) {
2844 QualType ETy = E->getType();
2845 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
2846 ExprResult ExprRes = E;
2847 AssignConvertType ConvTy =
2848 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2849 if (ExprRes.isInvalid())
2852 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
2856 ExprResult ExprRes = ActOnFinishFullExpr(E, /*DiscardedValue*/ false);
2857 if (ExprRes.isInvalid())
2861 setFunctionHasIndirectGoto();
2863 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
2866 static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
2867 const Scope &DestScope) {
2868 if (!S.CurrentSEHFinally.empty() &&
2869 DestScope.Contains(*S.CurrentSEHFinally.back())) {
2870 S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
2875 Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
2876 Scope *S = CurScope->getContinueParent();
2878 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
2879 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
2881 CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
2883 return new (Context) ContinueStmt(ContinueLoc);
2887 Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
2888 Scope *S = CurScope->getBreakParent();
2890 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
2891 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
2893 if (S->isOpenMPLoopScope())
2894 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2896 CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
2898 return new (Context) BreakStmt(BreakLoc);
2901 /// Determine whether the given expression is a candidate for
2902 /// copy elision in either a return statement or a throw expression.
2904 /// \param ReturnType If we're determining the copy elision candidate for
2905 /// a return statement, this is the return type of the function. If we're
2906 /// determining the copy elision candidate for a throw expression, this will
2909 /// \param E The expression being returned from the function or block, or
2912 /// \param CESK Whether we allow function parameters or
2913 /// id-expressions that could be moved out of the function to be considered NRVO
2914 /// candidates. C++ prohibits these for NRVO itself, but we re-use this logic to
2915 /// determine whether we should try to move as part of a return or throw (which
2916 /// does allow function parameters).
2918 /// \returns The NRVO candidate variable, if the return statement may use the
2919 /// NRVO, or NULL if there is no such candidate.
2920 VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, Expr *E,
2921 CopyElisionSemanticsKind CESK) {
2922 // - in a return statement in a function [where] ...
2923 // ... the expression is the name of a non-volatile automatic object ...
2924 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
2925 if (!DR || DR->refersToEnclosingVariableOrCapture())
2927 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2931 if (isCopyElisionCandidate(ReturnType, VD, CESK))
2936 bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
2937 CopyElisionSemanticsKind CESK) {
2938 QualType VDType = VD->getType();
2939 // - in a return statement in a function with ...
2940 // ... a class return type ...
2941 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
2942 if (!ReturnType->isRecordType())
2944 // ... the same cv-unqualified type as the function return type ...
2945 // When considering moving this expression out, allow dissimilar types.
2946 if (!(CESK & CES_AllowDifferentTypes) && !VDType->isDependentType() &&
2947 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2951 // ...object (other than a function or catch-clause parameter)...
2952 if (VD->getKind() != Decl::Var &&
2953 !((CESK & CES_AllowParameters) && VD->getKind() == Decl::ParmVar))
2955 if (!(CESK & CES_AllowExceptionVariables) && VD->isExceptionVariable())
2959 if (!VD->hasLocalStorage()) return false;
2961 // Return false if VD is a __block variable. We don't want to implicitly move
2962 // out of a __block variable during a return because we cannot assume the
2963 // variable will no longer be used.
2964 if (VD->hasAttr<BlocksAttr>()) return false;
2966 if (CESK & CES_AllowDifferentTypes)
2969 // ...non-volatile...
2970 if (VD->getType().isVolatileQualified()) return false;
2972 // Variables with higher required alignment than their type's ABI
2973 // alignment cannot use NRVO.
2974 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
2975 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2981 /// Try to perform the initialization of a potentially-movable value,
2982 /// which is the operand to a return or throw statement.
2984 /// This routine implements C++14 [class.copy]p32, which attempts to treat
2985 /// returned lvalues as rvalues in certain cases (to prefer move construction),
2986 /// then falls back to treating them as lvalues if that failed.
2988 /// \param ConvertingConstructorsOnly If true, follow [class.copy]p32 and reject
2989 /// resolutions that find non-constructors, such as derived-to-base conversions
2990 /// or `operator T()&&` member functions. If false, do consider such
2991 /// conversion sequences.
2993 /// \param Res We will fill this in if move-initialization was possible.
2994 /// If move-initialization is not possible, such that we must fall back to
2995 /// treating the operand as an lvalue, we will leave Res in its original
2997 static void TryMoveInitialization(Sema& S,
2998 const InitializedEntity &Entity,
2999 const VarDecl *NRVOCandidate,
3000 QualType ResultType,
3002 bool ConvertingConstructorsOnly,
3004 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(),
3005 CK_NoOp, Value, VK_XValue);
3007 Expr *InitExpr = &AsRvalue;
3009 InitializationKind Kind = InitializationKind::CreateCopy(
3010 Value->getBeginLoc(), Value->getBeginLoc());
3012 InitializationSequence Seq(S, Entity, Kind, InitExpr);
3017 for (const InitializationSequence::Step &Step : Seq.steps()) {
3018 if (Step.Kind != InitializationSequence::SK_ConstructorInitialization &&
3019 Step.Kind != InitializationSequence::SK_UserConversion)
3022 FunctionDecl *FD = Step.Function.Function;
3023 if (ConvertingConstructorsOnly) {
3024 if (isa<CXXConstructorDecl>(FD)) {
3025 // C++14 [class.copy]p32:
3026 // [...] If the first overload resolution fails or was not performed,
3027 // or if the type of the first parameter of the selected constructor
3028 // is not an rvalue reference to the object's type (possibly
3029 // cv-qualified), overload resolution is performed again, considering
3030 // the object as an lvalue.
3031 const RValueReferenceType *RRefType =
3032 FD->getParamDecl(0)->getType()->getAs<RValueReferenceType>();
3035 if (!S.Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
3036 NRVOCandidate->getType()))
3042 if (isa<CXXConstructorDecl>(FD)) {
3043 // Check that overload resolution selected a constructor taking an
3044 // rvalue reference. If it selected an lvalue reference, then we
3045 // didn't need to cast this thing to an rvalue in the first place.
3046 if (!isa<RValueReferenceType>(FD->getParamDecl(0)->getType()))
3048 } else if (isa<CXXMethodDecl>(FD)) {
3049 // Check that overload resolution selected a conversion operator
3050 // taking an rvalue reference.
3051 if (cast<CXXMethodDecl>(FD)->getRefQualifier() != RQ_RValue)
3058 // Promote "AsRvalue" to the heap, since we now need this
3059 // expression node to persist.
3060 Value = ImplicitCastExpr::Create(S.Context, Value->getType(), CK_NoOp,
3061 Value, nullptr, VK_XValue);
3063 // Complete type-checking the initialization of the return type
3064 // using the constructor we found.
3065 Res = Seq.Perform(S, Entity, Kind, Value);
3069 /// Perform the initialization of a potentially-movable value, which
3070 /// is the result of return value.
3072 /// This routine implements C++14 [class.copy]p32, which attempts to treat
3073 /// returned lvalues as rvalues in certain cases (to prefer move construction),
3074 /// then falls back to treating them as lvalues if that failed.
3076 Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
3077 const VarDecl *NRVOCandidate,
3078 QualType ResultType,
3081 // C++14 [class.copy]p32:
3082 // When the criteria for elision of a copy/move operation are met, but not for
3083 // an exception-declaration, and the object to be copied is designated by an
3084 // lvalue, or when the expression in a return statement is a (possibly
3085 // parenthesized) id-expression that names an object with automatic storage
3086 // duration declared in the body or parameter-declaration-clause of the
3087 // innermost enclosing function or lambda-expression, overload resolution to
3088 // select the constructor for the copy is first performed as if the object
3089 // were designated by an rvalue.
3090 ExprResult Res = ExprError();
3093 bool AffectedByCWG1579 = false;
3095 if (!NRVOCandidate) {
3096 NRVOCandidate = getCopyElisionCandidate(ResultType, Value, CES_Default);
3097 if (NRVOCandidate &&
3098 !getDiagnostics().isIgnored(diag::warn_return_std_move_in_cxx11,
3099 Value->getExprLoc())) {
3100 const VarDecl *NRVOCandidateInCXX11 =
3101 getCopyElisionCandidate(ResultType, Value, CES_FormerDefault);
3102 AffectedByCWG1579 = (!NRVOCandidateInCXX11);
3106 if (NRVOCandidate) {
3107 TryMoveInitialization(*this, Entity, NRVOCandidate, ResultType, Value,
3111 if (!Res.isInvalid() && AffectedByCWG1579) {
3112 QualType QT = NRVOCandidate->getType();
3113 if (QT.getNonReferenceType()
3114 .getUnqualifiedType()
3115 .isTriviallyCopyableType(Context)) {
3116 // Adding 'std::move' around a trivially copyable variable is probably
3117 // pointless. Don't suggest it.
3119 // Common cases for this are returning unique_ptr<Derived> from a
3120 // function of return type unique_ptr<Base>, or returning T from a
3121 // function of return type Expected<T>. This is totally fine in a
3122 // post-CWG1579 world, but was not fine before.
3123 assert(!ResultType.isNull());
3124 SmallString<32> Str;
3125 Str += "std::move(";
3126 Str += NRVOCandidate->getDeclName().getAsString();
3128 Diag(Value->getExprLoc(), diag::warn_return_std_move_in_cxx11)
3129 << Value->getSourceRange()
3130 << NRVOCandidate->getDeclName() << ResultType << QT;
3131 Diag(Value->getExprLoc(), diag::note_add_std_move_in_cxx11)
3132 << FixItHint::CreateReplacement(Value->getSourceRange(), Str);
3134 } else if (Res.isInvalid() &&
3135 !getDiagnostics().isIgnored(diag::warn_return_std_move,
3136 Value->getExprLoc())) {
3137 const VarDecl *FakeNRVOCandidate =
3138 getCopyElisionCandidate(QualType(), Value, CES_AsIfByStdMove);
3139 if (FakeNRVOCandidate) {
3140 QualType QT = FakeNRVOCandidate->getType();
3141 if (QT->isLValueReferenceType()) {
3142 // Adding 'std::move' around an lvalue reference variable's name is
3143 // dangerous. Don't suggest it.
3144 } else if (QT.getNonReferenceType()
3145 .getUnqualifiedType()
3146 .isTriviallyCopyableType(Context)) {
3147 // Adding 'std::move' around a trivially copyable variable is probably
3148 // pointless. Don't suggest it.
3150 ExprResult FakeRes = ExprError();
3151 Expr *FakeValue = Value;
3152 TryMoveInitialization(*this, Entity, FakeNRVOCandidate, ResultType,
3153 FakeValue, false, FakeRes);
3154 if (!FakeRes.isInvalid()) {
3156 (Entity.getKind() == InitializedEntity::EK_Exception);
3157 SmallString<32> Str;
3158 Str += "std::move(";
3159 Str += FakeNRVOCandidate->getDeclName().getAsString();
3161 Diag(Value->getExprLoc(), diag::warn_return_std_move)
3162 << Value->getSourceRange()
3163 << FakeNRVOCandidate->getDeclName() << IsThrow;
3164 Diag(Value->getExprLoc(), diag::note_add_std_move)
3165 << FixItHint::CreateReplacement(Value->getSourceRange(), Str);
3172 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
3173 // above, or overload resolution failed. Either way, we need to try
3174 // (again) now with the return value expression as written.
3175 if (Res.isInvalid())
3176 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
3181 /// Determine whether the declared return type of the specified function
3182 /// contains 'auto'.
3183 static bool hasDeducedReturnType(FunctionDecl *FD) {
3184 const FunctionProtoType *FPT =
3185 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
3186 return FPT->getReturnType()->isUndeducedType();
3189 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
3190 /// for capturing scopes.
3193 Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
3194 // If this is the first return we've seen, infer the return type.
3195 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
3196 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
3197 QualType FnRetType = CurCap->ReturnType;
3198 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
3199 bool HasDeducedReturnType =
3200 CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
3202 if (ExprEvalContexts.back().Context ==
3203 ExpressionEvaluationContext::DiscardedStatement &&
3204 (HasDeducedReturnType || CurCap->HasImplicitReturnType)) {
3207 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3210 RetValExp = ER.get();
3212 return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3213 /* NRVOCandidate=*/nullptr);
3216 if (HasDeducedReturnType) {
3217 // In C++1y, the return type may involve 'auto'.
3218 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
3219 FunctionDecl *FD = CurLambda->CallOperator;
3220 if (CurCap->ReturnType.isNull())
3221 CurCap->ReturnType = FD->getReturnType();
3223 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
3224 assert(AT && "lost auto type from lambda return type");
3225 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3226 FD->setInvalidDecl();
3229 CurCap->ReturnType = FnRetType = FD->getReturnType();
3230 } else if (CurCap->HasImplicitReturnType) {
3231 // For blocks/lambdas with implicit return types, we check each return
3232 // statement individually, and deduce the common return type when the block
3233 // or lambda is completed.
3234 // FIXME: Fold this into the 'auto' codepath above.
3235 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
3236 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
3237 if (Result.isInvalid())
3239 RetValExp = Result.get();
3241 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
3242 // when deducing a return type for a lambda-expression (or by extension
3243 // for a block). These rules differ from the stated C++11 rules only in
3244 // that they remove top-level cv-qualifiers.
3245 if (!CurContext->isDependentContext())
3246 FnRetType = RetValExp->getType().getUnqualifiedType();
3248 FnRetType = CurCap->ReturnType = Context.DependentTy;
3251 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
3252 // initializer list, because it is not an expression (even
3253 // though we represent it as one). We still deduce 'void'.
3254 Diag(ReturnLoc, diag::err_lambda_return_init_list)
3255 << RetValExp->getSourceRange();
3258 FnRetType = Context.VoidTy;
3261 // Although we'll properly infer the type of the block once it's completed,
3262 // make sure we provide a return type now for better error recovery.
3263 if (CurCap->ReturnType.isNull())
3264 CurCap->ReturnType = FnRetType;
3266 assert(!FnRetType.isNull());
3268 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
3269 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
3270 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
3273 } else if (CapturedRegionScopeInfo *CurRegion =
3274 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
3275 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
3278 assert(CurLambda && "unknown kind of captured scope");
3279 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
3280 ->getNoReturnAttr()) {
3281 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
3286 // Otherwise, verify that this result type matches the previous one. We are
3287 // pickier with blocks than for normal functions because we don't have GCC
3288 // compatibility to worry about here.
3289 const VarDecl *NRVOCandidate = nullptr;
3290 if (FnRetType->isDependentType()) {
3291 // Delay processing for now. TODO: there are lots of dependent
3292 // types we can conclusively prove aren't void.
3293 } else if (FnRetType->isVoidType()) {
3294 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
3295 !(getLangOpts().CPlusPlus &&
3296 (RetValExp->isTypeDependent() ||
3297 RetValExp->getType()->isVoidType()))) {
3298 if (!getLangOpts().CPlusPlus &&
3299 RetValExp->getType()->isVoidType())
3300 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
3302 Diag(ReturnLoc, diag::err_return_block_has_expr);
3303 RetValExp = nullptr;
3306 } else if (!RetValExp) {
3307 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
3308 } else if (!RetValExp->isTypeDependent()) {
3309 // we have a non-void block with an expression, continue checking
3311 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3312 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3315 // In C++ the return statement is handled via a copy initialization.
3316 // the C version of which boils down to CheckSingleAssignmentConstraints.
3317 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
3318 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
3320 NRVOCandidate != nullptr);
3321 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
3322 FnRetType, RetValExp);
3323 if (Res.isInvalid()) {
3324 // FIXME: Cleanup temporaries here, anyway?
3327 RetValExp = Res.get();
3328 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
3330 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
3335 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3338 RetValExp = ER.get();
3341 ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
3343 // If we need to check for the named return value optimization,
3344 // or if we need to infer the return type,
3345 // save the return statement in our scope for later processing.
3346 if (CurCap->HasImplicitReturnType || NRVOCandidate)
3347 FunctionScopes.back()->Returns.push_back(Result);
3349 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3350 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3356 /// Marks all typedefs in all local classes in a type referenced.
3358 /// In a function like
3360 /// struct S { typedef int a; };
3364 /// the local type escapes and could be referenced in some TUs but not in
3365 /// others. Pretend that all local typedefs are always referenced, to not warn
3366 /// on this. This isn't necessary if f has internal linkage, or the typedef
3368 class LocalTypedefNameReferencer
3369 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
3371 LocalTypedefNameReferencer(Sema &S) : S(S) {}
3372 bool VisitRecordType(const RecordType *RT);
3376 bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
3377 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
3378 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
3379 R->isDependentType())
3381 for (auto *TmpD : R->decls())
3382 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
3383 if (T->getAccess() != AS_private || R->hasFriends())
3384 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
3389 TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
3390 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
3391 while (auto ATL = TL.getAs<AttributedTypeLoc>())
3392 TL = ATL.getModifiedLoc().IgnoreParens();
3393 return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc();
3396 /// Deduce the return type for a function from a returned expression, per
3397 /// C++1y [dcl.spec.auto]p6.
3398 bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
3399 SourceLocation ReturnLoc,
3402 // If this is the conversion function for a lambda, we choose to deduce it
3403 // type from the corresponding call operator, not from the synthesized return
3404 // statement within it. See Sema::DeduceReturnType.
3405 if (isLambdaConversionOperator(FD))
3408 TypeLoc OrigResultType = getReturnTypeLoc(FD);
3411 if (RetExpr && isa<InitListExpr>(RetExpr)) {
3412 // If the deduction is for a return statement and the initializer is
3413 // a braced-init-list, the program is ill-formed.
3414 Diag(RetExpr->getExprLoc(),
3415 getCurLambda() ? diag::err_lambda_return_init_list
3416 : diag::err_auto_fn_return_init_list)
3417 << RetExpr->getSourceRange();
3421 if (FD->isDependentContext()) {
3422 // C++1y [dcl.spec.auto]p12:
3423 // Return type deduction [...] occurs when the definition is
3424 // instantiated even if the function body contains a return
3425 // statement with a non-type-dependent operand.
3426 assert(AT->isDeduced() && "should have deduced to dependent type");
3431 // Otherwise, [...] deduce a value for U using the rules of template
3432 // argument deduction.
3433 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
3435 if (DAR == DAR_Failed && !FD->isInvalidDecl())
3436 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3437 << OrigResultType.getType() << RetExpr->getType();
3439 if (DAR != DAR_Succeeded)
3442 // If a local type is part of the returned type, mark its fields as
3444 LocalTypedefNameReferencer Referencer(*this);
3445 Referencer.TraverseType(RetExpr->getType());
3447 // In the case of a return with no operand, the initializer is considered
3450 // Deduction here can only succeed if the return type is exactly 'cv auto'
3451 // or 'decltype(auto)', so just check for that case directly.
3452 if (!OrigResultType.getType()->getAs<AutoType>()) {
3453 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3454 << OrigResultType.getType();
3457 // We always deduce U = void in this case.
3458 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
3459 if (Deduced.isNull())
3463 // If a function with a declared return type that contains a placeholder type
3464 // has multiple return statements, the return type is deduced for each return
3465 // statement. [...] if the type deduced is not the same in each deduction,
3466 // the program is ill-formed.
3467 QualType DeducedT = AT->getDeducedType();
3468 if (!DeducedT.isNull() && !FD->isInvalidDecl()) {
3469 AutoType *NewAT = Deduced->getContainedAutoType();
3470 // It is possible that NewAT->getDeducedType() is null. When that happens,
3471 // we should not crash, instead we ignore this deduction.
3472 if (NewAT->getDeducedType().isNull())
3475 CanQualType OldDeducedType = Context.getCanonicalFunctionResultType(
3477 CanQualType NewDeducedType = Context.getCanonicalFunctionResultType(
3478 NewAT->getDeducedType());
3479 if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) {
3480 const LambdaScopeInfo *LambdaSI = getCurLambda();
3481 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
3482 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
3483 << NewAT->getDeducedType() << DeducedT
3484 << true /*IsLambda*/;
3486 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3487 << (AT->isDecltypeAuto() ? 1 : 0)
3488 << NewAT->getDeducedType() << DeducedT;
3492 } else if (!FD->isInvalidDecl()) {
3493 // Update all declarations of the function to have the deduced return type.
3494 Context.adjustDeducedFunctionResultType(FD, Deduced);
3501 Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3503 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
3504 if (R.isInvalid() || ExprEvalContexts.back().Context ==
3505 ExpressionEvaluationContext::DiscardedStatement)
3509 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
3510 CurScope->addNRVOCandidate(VD);
3512 CurScope->setNoNRVO();
3515 CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3520 StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
3521 // Check for unexpanded parameter packs.
3522 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3525 if (isa<CapturingScopeInfo>(getCurFunction()))
3526 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
3529 QualType RelatedRetType;
3530 const AttrVec *Attrs = nullptr;
3531 bool isObjCMethod = false;
3533 if (const FunctionDecl *FD = getCurFunctionDecl()) {
3534 FnRetType = FD->getReturnType();
3536 Attrs = &FD->getAttrs();
3537 if (FD->isNoReturn())
3538 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
3539 << FD->getDeclName();
3540 if (FD->isMain() && RetValExp)
3541 if (isa<CXXBoolLiteralExpr>(RetValExp))
3542 Diag(ReturnLoc, diag::warn_main_returns_bool_literal)
3543 << RetValExp->getSourceRange();
3544 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
3545 FnRetType = MD->getReturnType();
3546 isObjCMethod = true;
3548 Attrs = &MD->getAttrs();
3549 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3550 // In the implementation of a method with a related return type, the
3551 // type used to type-check the validity of return statements within the
3552 // method body is a pointer to the type of the class being implemented.
3553 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3554 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
3556 } else // If we don't have a function/method context, bail.
3559 // C++1z: discarded return statements are not considered when deducing a
3561 if (ExprEvalContexts.back().Context ==
3562 ExpressionEvaluationContext::DiscardedStatement &&
3563 FnRetType->getContainedAutoType()) {
3566 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3569 RetValExp = ER.get();
3571 return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3572 /* NRVOCandidate=*/nullptr);
3575 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3577 if (getLangOpts().CPlusPlus14) {
3578 if (AutoType *AT = FnRetType->getContainedAutoType()) {
3579 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
3580 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3581 FD->setInvalidDecl();
3584 FnRetType = FD->getReturnType();
3589 bool HasDependentReturnType = FnRetType->isDependentType();
3591 ReturnStmt *Result = nullptr;
3592 if (FnRetType->isVoidType()) {
3594 if (isa<InitListExpr>(RetValExp)) {
3595 // We simply never allow init lists as the return value of void
3596 // functions. This is compatible because this was never allowed before,
3597 // so there's no legacy code to deal with.
3598 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3599 int FunctionKind = 0;
3600 if (isa<ObjCMethodDecl>(CurDecl))
3602 else if (isa<CXXConstructorDecl>(CurDecl))
3604 else if (isa<CXXDestructorDecl>(CurDecl))
3607 Diag(ReturnLoc, diag::err_return_init_list)
3608 << CurDecl->getDeclName() << FunctionKind
3609 << RetValExp->getSourceRange();
3611 // Drop the expression.
3612 RetValExp = nullptr;
3613 } else if (!RetValExp->isTypeDependent()) {
3614 // C99 6.8.6.4p1 (ext_ since GCC warns)
3615 unsigned D = diag::ext_return_has_expr;
3616 if (RetValExp->getType()->isVoidType()) {
3617 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3618 if (isa<CXXConstructorDecl>(CurDecl) ||
3619 isa<CXXDestructorDecl>(CurDecl))
3620 D = diag::err_ctor_dtor_returns_void;
3622 D = diag::ext_return_has_void_expr;
3625 ExprResult Result = RetValExp;
3626 Result = IgnoredValueConversions(Result.get());
3627 if (Result.isInvalid())
3629 RetValExp = Result.get();
3630 RetValExp = ImpCastExprToType(RetValExp,
3631 Context.VoidTy, CK_ToVoid).get();
3633 // return of void in constructor/destructor is illegal in C++.
3634 if (D == diag::err_ctor_dtor_returns_void) {
3635 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3637 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3638 << RetValExp->getSourceRange();
3640 // return (some void expression); is legal in C++.
3641 else if (D != diag::ext_return_has_void_expr ||
3642 !getLangOpts().CPlusPlus) {
3643 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3645 int FunctionKind = 0;
3646 if (isa<ObjCMethodDecl>(CurDecl))
3648 else if (isa<CXXConstructorDecl>(CurDecl))
3650 else if (isa<CXXDestructorDecl>(CurDecl))
3654 << CurDecl->getDeclName() << FunctionKind
3655 << RetValExp->getSourceRange();
3661 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3664 RetValExp = ER.get();
3668 Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3669 /* NRVOCandidate=*/nullptr);
3670 } else if (!RetValExp && !HasDependentReturnType) {
3671 FunctionDecl *FD = getCurFunctionDecl();
3674 if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3675 // C++11 [stmt.return]p2
3676 DiagID = diag::err_constexpr_return_missing_expr;
3677 FD->setInvalidDecl();
3678 } else if (getLangOpts().C99) {
3679 // C99 6.8.6.4p1 (ext_ since GCC warns)
3680 DiagID = diag::ext_return_missing_expr;
3683 DiagID = diag::warn_return_missing_expr;
3687 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
3689 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
3691 Result = ReturnStmt::Create(Context, ReturnLoc, /* RetExpr=*/nullptr,
3692 /* NRVOCandidate=*/nullptr);
3694 assert(RetValExp || HasDependentReturnType);
3695 const VarDecl *NRVOCandidate = nullptr;
3697 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3699 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3700 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3703 // In C++ the return statement is handled via a copy initialization,
3704 // the C version of which boils down to CheckSingleAssignmentConstraints.
3706 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
3707 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
3708 // we have a non-void function with an expression, continue checking
3709 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
3711 NRVOCandidate != nullptr);
3712 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
3713 RetType, RetValExp);
3714 if (Res.isInvalid()) {
3715 // FIXME: Clean up temporaries here anyway?
3718 RetValExp = Res.getAs<Expr>();
3720 // If we have a related result type, we need to implicitly
3721 // convert back to the formal result type. We can't pretend to
3722 // initialize the result again --- we might end double-retaining
3723 // --- so instead we initialize a notional temporary.
3724 if (!RelatedRetType.isNull()) {
3725 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3727 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3728 if (Res.isInvalid()) {
3729 // FIXME: Clean up temporaries here anyway?
3732 RetValExp = Res.getAs<Expr>();
3735 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3736 getCurFunctionDecl());
3741 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3744 RetValExp = ER.get();
3746 Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
3749 // If we need to check for the named return value optimization, save the
3750 // return statement in our scope for later processing.
3751 if (Result->getNRVOCandidate())
3752 FunctionScopes.back()->Returns.push_back(Result);
3754 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3755 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3761 Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
3762 SourceLocation RParen, Decl *Parm,
3764 VarDecl *Var = cast_or_null<VarDecl>(Parm);
3765 if (Var && Var->isInvalidDecl())
3768 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
3772 Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
3773 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
3777 Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3778 MultiStmtArg CatchStmts, Stmt *Finally) {
3779 if (!getLangOpts().ObjCExceptions)
3780 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3782 setFunctionHasBranchProtectedScope();
3783 unsigned NumCatchStmts = CatchStmts.size();
3784 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3785 NumCatchStmts, Finally);
3788 StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
3790 ExprResult Result = DefaultLvalueConversion(Throw);
3791 if (Result.isInvalid())
3794 Result = ActOnFinishFullExpr(Result.get(), /*DiscardedValue*/ false);
3795 if (Result.isInvalid())
3797 Throw = Result.get();
3799 QualType ThrowType = Throw->getType();
3800 // Make sure the expression type is an ObjC pointer or "void *".
3801 if (!ThrowType->isDependentType() &&
3802 !ThrowType->isObjCObjectPointerType()) {
3803 const PointerType *PT = ThrowType->getAs<PointerType>();
3804 if (!PT || !PT->getPointeeType()->isVoidType())
3805 return StmtError(Diag(AtLoc, diag::err_objc_throw_expects_object)
3806 << Throw->getType() << Throw->getSourceRange());
3810 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
3814 Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3816 if (!getLangOpts().ObjCExceptions)
3817 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3820 // @throw without an expression designates a rethrow (which must occur
3821 // in the context of an @catch clause).
3822 Scope *AtCatchParent = CurScope;
3823 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3824 AtCatchParent = AtCatchParent->getParent();
3826 return StmtError(Diag(AtLoc, diag::err_rethrow_used_outside_catch));
3828 return BuildObjCAtThrowStmt(AtLoc, Throw);
3832 Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3833 ExprResult result = DefaultLvalueConversion(operand);
3834 if (result.isInvalid())
3836 operand = result.get();
3838 // Make sure the expression type is an ObjC pointer or "void *".
3839 QualType type = operand->getType();
3840 if (!type->isDependentType() &&
3841 !type->isObjCObjectPointerType()) {
3842 const PointerType *pointerType = type->getAs<PointerType>();
3843 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3844 if (getLangOpts().CPlusPlus) {
3845 if (RequireCompleteType(atLoc, type,
3846 diag::err_incomplete_receiver_type))
3847 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
3848 << type << operand->getSourceRange();
3850 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
3851 if (result.isInvalid())
3853 if (!result.isUsable())
3854 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
3855 << type << operand->getSourceRange();
3857 operand = result.get();
3859 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
3860 << type << operand->getSourceRange();
3865 // The operand to @synchronized is a full-expression.
3866 return ActOnFinishFullExpr(operand, /*DiscardedValue*/ false);
3870 Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3872 // We can't jump into or indirect-jump out of a @synchronized block.
3873 setFunctionHasBranchProtectedScope();
3874 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
3877 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3878 /// and creates a proper catch handler from them.
3880 Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
3881 Stmt *HandlerBlock) {
3882 // There's nothing to test that ActOnExceptionDecl didn't already test.
3883 return new (Context)
3884 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
3888 Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3889 setFunctionHasBranchProtectedScope();
3890 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
3894 class CatchHandlerType {
3896 unsigned IsPointer : 1;
3898 // This is a special constructor to be used only with DenseMapInfo's
3899 // getEmptyKey() and getTombstoneKey() functions.
3900 friend struct llvm::DenseMapInfo<CatchHandlerType>;
3901 enum Unique { ForDenseMap };
3902 CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
3905 /// Used when creating a CatchHandlerType from a handler type; will determine
3906 /// whether the type is a pointer or reference and will strip off the top
3907 /// level pointer and cv-qualifiers.
3908 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
3909 if (QT->isPointerType())
3912 if (IsPointer || QT->isReferenceType())
3913 QT = QT->getPointeeType();
3914 QT = QT.getUnqualifiedType();
3917 /// Used when creating a CatchHandlerType from a base class type; pretends the
3918 /// type passed in had the pointer qualifier, does not need to get an
3919 /// unqualified type.
3920 CatchHandlerType(QualType QT, bool IsPointer)
3921 : QT(QT), IsPointer(IsPointer) {}
3923 QualType underlying() const { return QT; }
3924 bool isPointer() const { return IsPointer; }
3926 friend bool operator==(const CatchHandlerType &LHS,
3927 const CatchHandlerType &RHS) {
3928 // If the pointer qualification does not match, we can return early.
3929 if (LHS.IsPointer != RHS.IsPointer)
3931 // Otherwise, check the underlying type without cv-qualifiers.
3932 return LHS.QT == RHS.QT;
3938 template <> struct DenseMapInfo<CatchHandlerType> {
3939 static CatchHandlerType getEmptyKey() {
3940 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
3941 CatchHandlerType::ForDenseMap);
3944 static CatchHandlerType getTombstoneKey() {
3945 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
3946 CatchHandlerType::ForDenseMap);
3949 static unsigned getHashValue(const CatchHandlerType &Base) {
3950 return DenseMapInfo<QualType>::getHashValue(Base.underlying());
3953 static bool isEqual(const CatchHandlerType &LHS,
3954 const CatchHandlerType &RHS) {
3961 class CatchTypePublicBases {
3963 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
3964 const bool CheckAgainstPointer;
3966 CXXCatchStmt *FoundHandler;
3967 CanQualType FoundHandlerType;
3970 CatchTypePublicBases(
3972 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
3973 : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
3974 FoundHandler(nullptr) {}
3976 CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
3977 CanQualType getFoundHandlerType() const { return FoundHandlerType; }
3979 bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
3980 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
3981 CatchHandlerType Check(S->getType(), CheckAgainstPointer);
3982 const auto &M = TypesToCheck;
3983 auto I = M.find(Check);
3985 FoundHandler = I->second;
3986 FoundHandlerType = Ctx.getCanonicalType(S->getType());
3995 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3996 /// handlers and creates a try statement from them.
3997 StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3998 ArrayRef<Stmt *> Handlers) {
3999 // Don't report an error if 'try' is used in system headers.
4000 if (!getLangOpts().CXXExceptions &&
4001 !getSourceManager().isInSystemHeader(TryLoc) &&
4002 (!getLangOpts().OpenMPIsDevice ||
4003 !getLangOpts().OpenMPHostCXXExceptions ||
4004 isInOpenMPTargetExecutionDirective() ||
4005 isInOpenMPDeclareTargetContext()))
4006 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
4008 // Exceptions aren't allowed in CUDA device code.
4009 if (getLangOpts().CUDA)
4010 CUDADiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions)
4011 << "try" << CurrentCUDATarget();
4013 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
4014 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
4016 sema::FunctionScopeInfo *FSI = getCurFunction();
4018 // C++ try is incompatible with SEH __try.
4019 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
4020 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
4021 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
4024 const unsigned NumHandlers = Handlers.size();
4025 assert(!Handlers.empty() &&
4026 "The parser shouldn't call this if there are no handlers.");
4028 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
4029 for (unsigned i = 0; i < NumHandlers; ++i) {
4030 CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
4032 // Diagnose when the handler is a catch-all handler, but it isn't the last
4033 // handler for the try block. [except.handle]p5. Also, skip exception
4034 // declarations that are invalid, since we can't usefully report on them.
4035 if (!H->getExceptionDecl()) {
4036 if (i < NumHandlers - 1)
4037 return StmtError(Diag(H->getBeginLoc(), diag::err_early_catch_all));
4039 } else if (H->getExceptionDecl()->isInvalidDecl())
4042 // Walk the type hierarchy to diagnose when this type has already been
4043 // handled (duplication), or cannot be handled (derivation inversion). We
4044 // ignore top-level cv-qualifiers, per [except.handle]p3
4045 CatchHandlerType HandlerCHT =
4046 (QualType)Context.getCanonicalType(H->getCaughtType());
4048 // We can ignore whether the type is a reference or a pointer; we need the
4049 // underlying declaration type in order to get at the underlying record
4050 // decl, if there is one.
4051 QualType Underlying = HandlerCHT.underlying();
4052 if (auto *RD = Underlying->getAsCXXRecordDecl()) {
4053 if (!RD->hasDefinition())
4055 // Check that none of the public, unambiguous base classes are in the
4056 // map ([except.handle]p1). Give the base classes the same pointer
4057 // qualification as the original type we are basing off of. This allows
4058 // comparison against the handler type using the same top-level pointer
4059 // as the original type.
4061 Paths.setOrigin(RD);
4062 CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
4063 if (RD->lookupInBases(CTPB, Paths)) {
4064 const CXXCatchStmt *Problem = CTPB.getFoundHandler();
4065 if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
4066 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
4067 diag::warn_exception_caught_by_earlier_handler)
4068 << H->getCaughtType();
4069 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
4070 diag::note_previous_exception_handler)
4071 << Problem->getCaughtType();
4076 // Add the type the list of ones we have handled; diagnose if we've already
4078 auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
4080 const CXXCatchStmt *Problem = R.first->second;
4081 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
4082 diag::warn_exception_caught_by_earlier_handler)
4083 << H->getCaughtType();
4084 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
4085 diag::note_previous_exception_handler)
4086 << Problem->getCaughtType();
4090 FSI->setHasCXXTry(TryLoc);
4092 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
4095 StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
4096 Stmt *TryBlock, Stmt *Handler) {
4097 assert(TryBlock && Handler);
4099 sema::FunctionScopeInfo *FSI = getCurFunction();
4101 // SEH __try is incompatible with C++ try. Borland appears to support this,
4103 if (!getLangOpts().Borland) {
4104 if (FSI->FirstCXXTryLoc.isValid()) {
4105 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
4106 Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
4110 FSI->setHasSEHTry(TryLoc);
4112 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
4113 // track if they use SEH.
4114 DeclContext *DC = CurContext;
4115 while (DC && !DC->isFunctionOrMethod())
4116 DC = DC->getParent();
4117 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
4119 FD->setUsesSEHTry(true);
4121 Diag(TryLoc, diag::err_seh_try_outside_functions);
4123 // Reject __try on unsupported targets.
4124 if (!Context.getTargetInfo().isSEHTrySupported())
4125 Diag(TryLoc, diag::err_seh_try_unsupported);
4127 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
4131 Sema::ActOnSEHExceptBlock(SourceLocation Loc,
4134 assert(FilterExpr && Block);
4136 if(!FilterExpr->getType()->isIntegerType()) {
4137 return StmtError(Diag(FilterExpr->getExprLoc(),
4138 diag::err_filter_expression_integral)
4139 << FilterExpr->getType());
4142 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
4145 void Sema::ActOnStartSEHFinallyBlock() {
4146 CurrentSEHFinally.push_back(CurScope);
4149 void Sema::ActOnAbortSEHFinallyBlock() {
4150 CurrentSEHFinally.pop_back();
4153 StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
4155 CurrentSEHFinally.pop_back();
4156 return SEHFinallyStmt::Create(Context, Loc, Block);
4160 Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
4161 Scope *SEHTryParent = CurScope;
4162 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
4163 SEHTryParent = SEHTryParent->getParent();
4165 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
4166 CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
4168 return new (Context) SEHLeaveStmt(Loc);
4171 StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4173 NestedNameSpecifierLoc QualifierLoc,
4174 DeclarationNameInfo NameInfo,
4177 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
4178 QualifierLoc, NameInfo,
4179 cast<CompoundStmt>(Nested));
4183 StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4186 UnqualifiedId &Name,
4188 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
4189 SS.getWithLocInContext(Context),
4190 GetNameFromUnqualifiedId(Name),
4195 Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
4196 unsigned NumParams) {
4197 DeclContext *DC = CurContext;
4198 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
4199 DC = DC->getParent();
4201 RecordDecl *RD = nullptr;
4202 if (getLangOpts().CPlusPlus)
4203 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
4206 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
4208 RD->setCapturedRecord();
4211 RD->startDefinition();
4213 assert(NumParams > 0 && "CapturedStmt requires context parameter");
4214 CD = CapturedDecl::Create(Context, CurContext, NumParams);
4220 buildCapturedStmtCaptureList(SmallVectorImpl<CapturedStmt::Capture> &Captures,
4221 SmallVectorImpl<Expr *> &CaptureInits,
4222 ArrayRef<sema::Capture> Candidates) {
4223 for (const sema::Capture &Cap : Candidates) {
4224 if (Cap.isThisCapture()) {
4225 Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
4226 CapturedStmt::VCK_This));
4227 CaptureInits.push_back(Cap.getInitExpr());
4229 } else if (Cap.isVLATypeCapture()) {
4231 CapturedStmt::Capture(Cap.getLocation(), CapturedStmt::VCK_VLAType));
4232 CaptureInits.push_back(nullptr);
4236 Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
4237 Cap.isReferenceCapture()
4238 ? CapturedStmt::VCK_ByRef
4239 : CapturedStmt::VCK_ByCopy,
4240 Cap.getVariable()));
4241 CaptureInits.push_back(Cap.getInitExpr());
4245 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4246 CapturedRegionKind Kind,
4247 unsigned NumParams) {
4248 CapturedDecl *CD = nullptr;
4249 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
4251 // Build the context parameter
4252 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4253 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4254 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
4256 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4257 ImplicitParamDecl::CapturedContext);
4260 CD->setContextParam(0, Param);
4262 // Enter the capturing scope for this captured region.
4263 PushCapturedRegionScope(CurScope, CD, RD, Kind);
4266 PushDeclContext(CurScope, CD);
4270 PushExpressionEvaluationContext(
4271 ExpressionEvaluationContext::PotentiallyEvaluated);
4274 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4275 CapturedRegionKind Kind,
4276 ArrayRef<CapturedParamNameType> Params) {
4277 CapturedDecl *CD = nullptr;
4278 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
4280 // Build the context parameter
4281 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4282 bool ContextIsFound = false;
4283 unsigned ParamNum = 0;
4284 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
4286 I != E; ++I, ++ParamNum) {
4287 if (I->second.isNull()) {
4288 assert(!ContextIsFound &&
4289 "null type has been found already for '__context' parameter");
4290 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4291 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD))
4295 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4296 ImplicitParamDecl::CapturedContext);
4298 CD->setContextParam(ParamNum, Param);
4299 ContextIsFound = true;
4301 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
4303 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second,
4304 ImplicitParamDecl::CapturedContext);
4306 CD->setParam(ParamNum, Param);
4309 assert(ContextIsFound && "no null type for '__context' parameter");
4310 if (!ContextIsFound) {
4311 // Add __context implicitly if it is not specified.
4312 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4313 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
4315 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4316 ImplicitParamDecl::CapturedContext);
4318 CD->setContextParam(ParamNum, Param);
4320 // Enter the capturing scope for this captured region.
4321 PushCapturedRegionScope(CurScope, CD, RD, Kind);
4324 PushDeclContext(CurScope, CD);
4328 PushExpressionEvaluationContext(
4329 ExpressionEvaluationContext::PotentiallyEvaluated);
4332 void Sema::ActOnCapturedRegionError() {
4333 DiscardCleanupsInEvaluationContext();
4334 PopExpressionEvaluationContext();
4336 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
4337 RecordDecl *Record = RSI->TheRecordDecl;
4338 Record->setInvalidDecl();
4340 SmallVector<Decl*, 4> Fields(Record->fields());
4341 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
4342 SourceLocation(), SourceLocation(), ParsedAttributesView());
4345 PopFunctionScopeInfo();
4348 StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
4349 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
4351 SmallVector<CapturedStmt::Capture, 4> Captures;
4352 SmallVector<Expr *, 4> CaptureInits;
4353 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
4355 CapturedDecl *CD = RSI->TheCapturedDecl;
4356 RecordDecl *RD = RSI->TheRecordDecl;
4358 CapturedStmt *Res = CapturedStmt::Create(
4359 getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind),
4360 Captures, CaptureInits, CD, RD);
4362 CD->setBody(Res->getCapturedStmt());
4363 RD->completeDefinition();
4365 DiscardCleanupsInEvaluationContext();
4366 PopExpressionEvaluationContext();
4369 PopFunctionScopeInfo();