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) {
49 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
50 /*DiscardedValue*/ true);
54 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
55 // void expression for its side effects. Conversion to void allows any
56 // operand, even incomplete types.
58 // Same thing in for stmt first clause (when expr) and third clause.
59 return StmtResult(FE.getAs<Stmt>());
63 StmtResult Sema::ActOnExprStmtError() {
64 DiscardCleanupsInEvaluationContext();
68 StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
69 bool HasLeadingEmptyMacro) {
70 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
73 StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
74 SourceLocation EndLoc) {
75 DeclGroupRef DG = dg.get();
77 // If we have an invalid decl, just return an error.
78 if (DG.isNull()) return StmtError();
80 return new (Context) DeclStmt(DG, StartLoc, EndLoc);
83 void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
84 DeclGroupRef DG = dg.get();
86 // If we don't have a declaration, or we have an invalid declaration,
88 if (DG.isNull() || !DG.isSingleDecl())
91 Decl *decl = DG.getSingleDecl();
92 if (!decl || decl->isInvalidDecl())
95 // Only variable declarations are permitted.
96 VarDecl *var = dyn_cast<VarDecl>(decl);
98 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
99 decl->setInvalidDecl();
103 // foreach variables are never actually initialized in the way that
104 // the parser came up with.
105 var->setInit(nullptr);
107 // In ARC, we don't need to retain the iteration variable of a fast
108 // enumeration loop. Rather than actually trying to catch that
109 // during declaration processing, we remove the consequences here.
110 if (getLangOpts().ObjCAutoRefCount) {
111 QualType type = var->getType();
113 // Only do this if we inferred the lifetime. Inferred lifetime
114 // will show up as a local qualifier because explicit lifetime
115 // should have shown up as an AttributedType instead.
116 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
117 // Add 'const' and mark the variable as pseudo-strong.
118 var->setType(type.withConst());
119 var->setARCPseudoStrong(true);
124 /// Diagnose unused comparisons, both builtin and overloaded operators.
125 /// For '==' and '!=', suggest fixits for '=' or '|='.
127 /// Adding a cast to void (or other expression wrappers) will prevent the
128 /// warning from firing.
129 static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
132 enum { Equality, Inequality, Relational, ThreeWay } Kind;
134 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
135 if (!Op->isComparisonOp())
138 if (Op->getOpcode() == BO_EQ)
140 else if (Op->getOpcode() == BO_NE)
142 else if (Op->getOpcode() == BO_Cmp)
145 assert(Op->isRelationalOp());
148 Loc = Op->getOperatorLoc();
149 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
150 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
151 switch (Op->getOperator()) {
155 case OO_ExclaimEqual:
160 case OO_GreaterEqual:
171 Loc = Op->getOperatorLoc();
172 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
174 // Not a typo-prone comparison.
178 // Suppress warnings when the operator, suspicious as it may be, comes from
179 // a macro expansion.
180 if (S.SourceMgr.isMacroBodyExpansion(Loc))
183 S.Diag(Loc, diag::warn_unused_comparison)
184 << (unsigned)Kind << E->getSourceRange();
186 // If the LHS is a plausible entity to assign to, provide a fixit hint to
187 // correct common typos.
189 if (Kind == Inequality)
190 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
191 << FixItHint::CreateReplacement(Loc, "|=");
192 else if (Kind == Equality)
193 S.Diag(Loc, diag::note_equality_comparison_to_assign)
194 << FixItHint::CreateReplacement(Loc, "=");
200 void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
201 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
202 return DiagnoseUnusedExprResult(Label->getSubStmt());
204 const Expr *E = dyn_cast_or_null<Expr>(S);
208 // If we are in an unevaluated expression context, then there can be no unused
209 // results because the results aren't expected to be used in the first place.
210 if (isUnevaluatedContext())
213 SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc();
214 // In most cases, we don't want to warn if the expression is written in a
215 // macro body, or if the macro comes from a system header. If the offending
216 // expression is a call to a function with the warn_unused_result attribute,
217 // we warn no matter the location. Because of the order in which the various
218 // checks need to happen, we factor out the macro-related test here.
219 bool ShouldSuppress =
220 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
221 SourceMgr.isInSystemMacro(ExprLoc);
223 const Expr *WarnExpr;
226 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
229 // If this is a GNU statement expression expanded from a macro, it is probably
230 // unused because it is a function-like macro that can be used as either an
231 // expression or statement. Don't warn, because it is almost certainly a
233 if (isa<StmtExpr>(E) && Loc.isMacroID())
236 // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers.
237 // That macro is frequently used to suppress "unused parameter" warnings,
238 // but its implementation makes clang's -Wunused-value fire. Prevent this.
239 if (isa<ParenExpr>(E->IgnoreImpCasts()) && Loc.isMacroID()) {
240 SourceLocation SpellLoc = Loc;
241 if (findMacroSpelling(SpellLoc, "UNREFERENCED_PARAMETER"))
245 // Okay, we have an unused result. Depending on what the base expression is,
246 // we might want to make a more specific diagnostic. Check for one of these
248 unsigned DiagID = diag::warn_unused_expr;
249 if (const FullExpr *Temps = dyn_cast<FullExpr>(E))
250 E = Temps->getSubExpr();
251 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
252 E = TempExpr->getSubExpr();
254 if (DiagnoseUnusedComparison(*this, E))
258 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
259 if (E->getType()->isVoidType())
262 if (const Attr *A = CE->getUnusedResultAttr(Context)) {
263 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
267 // If the callee has attribute pure, const, or warn_unused_result, warn with
268 // a more specific message to make it clear what is happening. If the call
269 // is written in a macro body, only warn if it has the warn_unused_result
271 if (const Decl *FD = CE->getCalleeDecl()) {
274 if (FD->hasAttr<PureAttr>()) {
275 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
278 if (FD->hasAttr<ConstAttr>()) {
279 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
283 } else if (ShouldSuppress)
286 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
287 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
288 Diag(Loc, diag::err_arc_unused_init_message) << R1;
291 const ObjCMethodDecl *MD = ME->getMethodDecl();
293 if (const auto *A = MD->getAttr<WarnUnusedResultAttr>()) {
294 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
298 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
299 const Expr *Source = POE->getSyntacticForm();
300 if (isa<ObjCSubscriptRefExpr>(Source))
301 DiagID = diag::warn_unused_container_subscript_expr;
303 DiagID = diag::warn_unused_property_expr;
304 } else if (const CXXFunctionalCastExpr *FC
305 = dyn_cast<CXXFunctionalCastExpr>(E)) {
306 const Expr *E = FC->getSubExpr();
307 if (const CXXBindTemporaryExpr *TE = dyn_cast<CXXBindTemporaryExpr>(E))
308 E = TE->getSubExpr();
309 if (isa<CXXTemporaryObjectExpr>(E))
311 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
312 if (const CXXRecordDecl *RD = CE->getType()->getAsCXXRecordDecl())
313 if (!RD->getAttr<WarnUnusedAttr>())
316 // Diagnose "(void*) blah" as a typo for "(void) blah".
317 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
318 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
319 QualType T = TI->getType();
321 // We really do want to use the non-canonical type here.
322 if (T == Context.VoidPtrTy) {
323 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
325 Diag(Loc, diag::warn_unused_voidptr)
326 << FixItHint::CreateRemoval(TL.getStarLoc());
331 if (E->isGLValue() && E->getType().isVolatileQualified()) {
332 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
336 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
339 void Sema::ActOnStartOfCompoundStmt(bool IsStmtExpr) {
340 PushCompoundScope(IsStmtExpr);
343 void Sema::ActOnFinishOfCompoundStmt() {
347 sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
348 return getCurFunction()->CompoundScopes.back();
351 StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
352 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
353 const unsigned NumElts = Elts.size();
355 // If we're in C89 mode, check that we don't have any decls after stmts. If
356 // so, emit an extension diagnostic.
357 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
358 // Note that __extension__ can be around a decl.
360 // Skip over all declarations.
361 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
364 // We found the end of the list or a statement. Scan for another declstmt.
365 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
369 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
370 Diag(D->getLocation(), diag::ext_mixed_decls_code);
373 // Warn about unused expressions in statements.
374 for (unsigned i = 0; i != NumElts; ++i) {
375 // Ignore statements that are last in a statement expression.
376 if (isStmtExpr && i == NumElts - 1)
379 DiagnoseUnusedExprResult(Elts[i]);
382 // Check for suspicious empty body (null statement) in `for' and `while'
383 // statements. Don't do anything for template instantiations, this just adds
385 if (NumElts != 0 && !CurrentInstantiationScope &&
386 getCurCompoundScope().HasEmptyLoopBodies) {
387 for (unsigned i = 0; i != NumElts - 1; ++i)
388 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
391 return CompoundStmt::Create(Context, Elts, L, R);
395 Sema::ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val) {
399 if (DiagnoseUnexpandedParameterPack(Val.get()))
402 // If we're not inside a switch, let the 'case' statement handling diagnose
403 // this. Just clean up after the expression as best we can.
404 if (!getCurFunction()->SwitchStack.empty()) {
406 getCurFunction()->SwitchStack.back().getPointer()->getCond();
409 QualType CondType = CondExpr->getType();
411 auto CheckAndFinish = [&](Expr *E) {
412 if (CondType->isDependentType() || E->isTypeDependent())
413 return ExprResult(E);
415 if (getLangOpts().CPlusPlus11) {
416 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
417 // constant expression of the promoted type of the switch condition.
418 llvm::APSInt TempVal;
419 return CheckConvertedConstantExpression(E, CondType, TempVal,
424 if (!E->isValueDependent())
425 ER = VerifyIntegerConstantExpression(E);
427 ER = DefaultLvalueConversion(ER.get());
429 ER = ImpCastExprToType(ER.get(), CondType, CK_IntegralCast);
433 ExprResult Converted = CorrectDelayedTyposInExpr(Val, CheckAndFinish);
434 if (Converted.get() == Val.get())
435 Converted = CheckAndFinish(Val.get());
436 if (Converted.isInvalid())
441 return ActOnFinishFullExpr(Val.get(), Val.get()->getExprLoc(), false,
442 getLangOpts().CPlusPlus11);
446 Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHSVal,
447 SourceLocation DotDotDotLoc, ExprResult RHSVal,
448 SourceLocation ColonLoc) {
449 assert((LHSVal.isInvalid() || LHSVal.get()) && "missing LHS value");
450 assert((DotDotDotLoc.isInvalid() ? RHSVal.isUnset()
451 : RHSVal.isInvalid() || RHSVal.get()) &&
452 "missing RHS value");
454 if (getCurFunction()->SwitchStack.empty()) {
455 Diag(CaseLoc, diag::err_case_not_in_switch);
459 if (LHSVal.isInvalid() || RHSVal.isInvalid()) {
460 getCurFunction()->SwitchStack.back().setInt(true);
464 auto *CS = CaseStmt::Create(Context, LHSVal.get(), RHSVal.get(),
465 CaseLoc, DotDotDotLoc, ColonLoc);
466 getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(CS);
470 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
471 void Sema::ActOnCaseStmtBody(Stmt *S, Stmt *SubStmt) {
472 DiagnoseUnusedExprResult(SubStmt);
473 cast<CaseStmt>(S)->setSubStmt(SubStmt);
477 Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
478 Stmt *SubStmt, Scope *CurScope) {
479 DiagnoseUnusedExprResult(SubStmt);
481 if (getCurFunction()->SwitchStack.empty()) {
482 Diag(DefaultLoc, diag::err_default_not_in_switch);
486 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
487 getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(DS);
492 Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
493 SourceLocation ColonLoc, Stmt *SubStmt) {
494 // If the label was multiply defined, reject it now.
495 if (TheDecl->getStmt()) {
496 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
497 Diag(TheDecl->getLocation(), diag::note_previous_definition);
501 // Otherwise, things are good. Fill in the declaration and return it.
502 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
503 TheDecl->setStmt(LS);
504 if (!TheDecl->isGnuLocal()) {
505 TheDecl->setLocStart(IdentLoc);
506 if (!TheDecl->isMSAsmLabel()) {
507 // Don't update the location of MS ASM labels. These will result in
508 // a diagnostic, and changing the location here will mess that up.
509 TheDecl->setLocation(IdentLoc);
515 StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
516 ArrayRef<const Attr*> Attrs,
518 // Fill in the declaration and return it.
519 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
524 class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
525 typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
528 CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
529 void VisitBinaryOperator(BinaryOperator *E) {
530 if (E->getOpcode() == BO_Comma)
531 SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc());
532 EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E);
538 Sema::ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt,
539 ConditionResult Cond,
540 Stmt *thenStmt, SourceLocation ElseLoc,
542 if (Cond.isInvalid())
543 Cond = ConditionResult(
545 MakeFullExpr(new (Context) OpaqueValueExpr(SourceLocation(),
546 Context.BoolTy, VK_RValue),
550 Expr *CondExpr = Cond.get().second;
551 // Only call the CommaVisitor when not C89 due to differences in scope flags.
552 if ((getLangOpts().C99 || getLangOpts().CPlusPlus) &&
553 !Diags.isIgnored(diag::warn_comma_operator, CondExpr->getExprLoc()))
554 CommaVisitor(*this).Visit(CondExpr);
557 DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), thenStmt,
558 diag::warn_empty_if_body);
560 return BuildIfStmt(IfLoc, IsConstexpr, InitStmt, Cond, thenStmt, ElseLoc,
564 StmtResult Sema::BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
565 Stmt *InitStmt, ConditionResult Cond,
566 Stmt *thenStmt, SourceLocation ElseLoc,
568 if (Cond.isInvalid())
571 if (IsConstexpr || isa<ObjCAvailabilityCheckExpr>(Cond.get().second))
572 setFunctionHasBranchProtectedScope();
574 DiagnoseUnusedExprResult(thenStmt);
575 DiagnoseUnusedExprResult(elseStmt);
577 return IfStmt::Create(Context, IfLoc, IsConstexpr, InitStmt, Cond.get().first,
578 Cond.get().second, thenStmt, ElseLoc, elseStmt);
582 struct CaseCompareFunctor {
583 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
584 const llvm::APSInt &RHS) {
585 return LHS.first < RHS;
587 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
588 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
589 return LHS.first < RHS.first;
591 bool operator()(const llvm::APSInt &LHS,
592 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
593 return LHS < RHS.first;
598 /// CmpCaseVals - Comparison predicate for sorting case values.
600 static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
601 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
602 if (lhs.first < rhs.first)
605 if (lhs.first == rhs.first &&
606 lhs.second->getCaseLoc().getRawEncoding()
607 < rhs.second->getCaseLoc().getRawEncoding())
612 /// CmpEnumVals - Comparison predicate for sorting enumeration values.
614 static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
615 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
617 return lhs.first < rhs.first;
620 /// EqEnumVals - Comparison preficate for uniqing enumeration values.
622 static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
623 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
625 return lhs.first == rhs.first;
628 /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
629 /// potentially integral-promoted expression @p expr.
630 static QualType GetTypeBeforeIntegralPromotion(const Expr *&E) {
631 if (const auto *FE = dyn_cast<FullExpr>(E))
632 E = FE->getSubExpr();
633 while (const auto *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
634 if (ImpCast->getCastKind() != CK_IntegralCast) break;
635 E = ImpCast->getSubExpr();
640 ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) {
641 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
645 SwitchConvertDiagnoser(Expr *Cond)
646 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
649 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
650 QualType T) override {
651 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
654 SemaDiagnosticBuilder diagnoseIncomplete(
655 Sema &S, SourceLocation Loc, QualType T) override {
656 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
657 << T << Cond->getSourceRange();
660 SemaDiagnosticBuilder diagnoseExplicitConv(
661 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
662 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
665 SemaDiagnosticBuilder noteExplicitConv(
666 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
667 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
668 << ConvTy->isEnumeralType() << ConvTy;
671 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
672 QualType T) override {
673 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
676 SemaDiagnosticBuilder noteAmbiguous(
677 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
678 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
679 << ConvTy->isEnumeralType() << ConvTy;
682 SemaDiagnosticBuilder diagnoseConversion(
683 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
684 llvm_unreachable("conversion functions are permitted");
686 } SwitchDiagnoser(Cond);
688 ExprResult CondResult =
689 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
690 if (CondResult.isInvalid())
693 // FIXME: PerformContextualImplicitConversion doesn't always tell us if it
694 // failed and produced a diagnostic.
695 Cond = CondResult.get();
696 if (!Cond->isTypeDependent() &&
697 !Cond->getType()->isIntegralOrEnumerationType())
700 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
701 return UsualUnaryConversions(Cond);
704 StmtResult Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
705 Stmt *InitStmt, ConditionResult Cond) {
706 Expr *CondExpr = Cond.get().second;
707 assert((Cond.isInvalid() || CondExpr) && "switch with no condition");
709 if (CondExpr && !CondExpr->isTypeDependent()) {
710 // We have already converted the expression to an integral or enumeration
711 // type, when we parsed the switch condition. If we don't have an
712 // appropriate type now, enter the switch scope but remember that it's
714 assert(CondExpr->getType()->isIntegralOrEnumerationType() &&
715 "invalid condition type");
716 if (CondExpr->isKnownToHaveBooleanValue()) {
717 // switch(bool_expr) {...} is often a programmer error, e.g.
718 // switch(n && mask) { ... } // Doh - should be "n & mask".
719 // One can always use an if statement instead of switch(bool_expr).
720 Diag(SwitchLoc, diag::warn_bool_switch_condition)
721 << CondExpr->getSourceRange();
725 setFunctionHasBranchIntoScope();
727 auto *SS = SwitchStmt::Create(Context, InitStmt, Cond.get().first, CondExpr);
728 getCurFunction()->SwitchStack.push_back(
729 FunctionScopeInfo::SwitchInfo(SS, false));
733 static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
734 Val = Val.extOrTrunc(BitWidth);
735 Val.setIsSigned(IsSigned);
738 /// Check the specified case value is in range for the given unpromoted switch
740 static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
741 unsigned UnpromotedWidth, bool UnpromotedSign) {
742 // In C++11 onwards, this is checked by the language rules.
743 if (S.getLangOpts().CPlusPlus11)
746 // If the case value was signed and negative and the switch expression is
747 // unsigned, don't bother to warn: this is implementation-defined behavior.
748 // FIXME: Introduce a second, default-ignored warning for this case?
749 if (UnpromotedWidth < Val.getBitWidth()) {
750 llvm::APSInt ConvVal(Val);
751 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
752 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
753 // FIXME: Use different diagnostics for overflow in conversion to promoted
754 // type versus "switch expression cannot have this value". Use proper
755 // IntRange checking rather than just looking at the unpromoted type here.
757 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
758 << ConvVal.toString(10);
762 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
764 /// Returns true if we should emit a diagnostic about this case expression not
765 /// being a part of the enum used in the switch controlling expression.
766 static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
768 const Expr *CaseExpr,
769 EnumValsTy::iterator &EI,
770 EnumValsTy::iterator &EIEnd,
771 const llvm::APSInt &Val) {
775 if (const DeclRefExpr *DRE =
776 dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
777 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
778 QualType VarType = VD->getType();
779 QualType EnumType = S.Context.getTypeDeclType(ED);
780 if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
781 S.Context.hasSameUnqualifiedType(EnumType, VarType))
786 if (ED->hasAttr<FlagEnumAttr>())
787 return !S.IsValueInFlagEnum(ED, Val, false);
789 while (EI != EIEnd && EI->first < Val)
792 if (EI != EIEnd && EI->first == Val)
798 static void checkEnumTypesInSwitchStmt(Sema &S, const Expr *Cond,
800 QualType CondType = Cond->getType();
801 QualType CaseType = Case->getType();
803 const EnumType *CondEnumType = CondType->getAs<EnumType>();
804 const EnumType *CaseEnumType = CaseType->getAs<EnumType>();
805 if (!CondEnumType || !CaseEnumType)
808 // Ignore anonymous enums.
809 if (!CondEnumType->getDecl()->getIdentifier() &&
810 !CondEnumType->getDecl()->getTypedefNameForAnonDecl())
812 if (!CaseEnumType->getDecl()->getIdentifier() &&
813 !CaseEnumType->getDecl()->getTypedefNameForAnonDecl())
816 if (S.Context.hasSameUnqualifiedType(CondType, CaseType))
819 S.Diag(Case->getExprLoc(), diag::warn_comparison_of_mixed_enum_types_switch)
820 << CondType << CaseType << Cond->getSourceRange()
821 << Case->getSourceRange();
825 Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
827 SwitchStmt *SS = cast<SwitchStmt>(Switch);
828 bool CaseListIsIncomplete = getCurFunction()->SwitchStack.back().getInt();
829 assert(SS == getCurFunction()->SwitchStack.back().getPointer() &&
830 "switch stack missing push/pop!");
832 getCurFunction()->SwitchStack.pop_back();
834 if (!BodyStmt) return StmtError();
835 SS->setBody(BodyStmt, SwitchLoc);
837 Expr *CondExpr = SS->getCond();
838 if (!CondExpr) return StmtError();
840 QualType CondType = CondExpr->getType();
843 // Integral promotions are performed (on the switch condition).
845 // A case value unrepresentable by the original switch condition
846 // type (before the promotion) doesn't make sense, even when it can
847 // be represented by the promoted type. Therefore we need to find
848 // the pre-promotion type of the switch condition.
849 const Expr *CondExprBeforePromotion = CondExpr;
850 QualType CondTypeBeforePromotion =
851 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
853 // Get the bitwidth of the switched-on value after promotions. We must
854 // convert the integer case values to this width before comparison.
855 bool HasDependentValue
856 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
857 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
858 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
860 // Get the width and signedness that the condition might actually have, for
862 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
864 unsigned CondWidthBeforePromotion
865 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
866 bool CondIsSignedBeforePromotion
867 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
869 // Accumulate all of the case values in a vector so that we can sort them
870 // and detect duplicates. This vector contains the APInt for the case after
871 // it has been converted to the condition type.
872 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
875 // Keep track of any GNU case ranges we see. The APSInt is the low value.
876 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
877 CaseRangesTy CaseRanges;
879 DefaultStmt *TheDefaultStmt = nullptr;
881 bool CaseListIsErroneous = false;
883 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
884 SC = SC->getNextSwitchCase()) {
886 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
887 if (TheDefaultStmt) {
888 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
889 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
891 // FIXME: Remove the default statement from the switch block so that
892 // we'll return a valid AST. This requires recursing down the AST and
893 // finding it, not something we are set up to do right now. For now,
894 // just lop the entire switch stmt out of the AST.
895 CaseListIsErroneous = true;
900 CaseStmt *CS = cast<CaseStmt>(SC);
902 Expr *Lo = CS->getLHS();
904 if (Lo->isValueDependent()) {
905 HasDependentValue = true;
909 // We already verified that the expression has a constant value;
910 // get that value (prior to conversions).
911 const Expr *LoBeforePromotion = Lo;
912 GetTypeBeforeIntegralPromotion(LoBeforePromotion);
913 llvm::APSInt LoVal = LoBeforePromotion->EvaluateKnownConstInt(Context);
915 // Check the unconverted value is within the range of possible values of
916 // the switch expression.
917 checkCaseValue(*this, Lo->getBeginLoc(), LoVal, CondWidthBeforePromotion,
918 CondIsSignedBeforePromotion);
920 // FIXME: This duplicates the check performed for warn_not_in_enum below.
921 checkEnumTypesInSwitchStmt(*this, CondExprBeforePromotion,
924 // Convert the value to the same width/sign as the condition.
925 AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
927 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
929 if (CS->getRHS()->isValueDependent()) {
930 HasDependentValue = true;
933 CaseRanges.push_back(std::make_pair(LoVal, CS));
935 CaseVals.push_back(std::make_pair(LoVal, CS));
939 if (!HasDependentValue) {
940 // If we don't have a default statement, check whether the
941 // condition is constant.
942 llvm::APSInt ConstantCondValue;
943 bool HasConstantCond = false;
944 if (!HasDependentValue && !TheDefaultStmt) {
945 Expr::EvalResult Result;
946 HasConstantCond = CondExpr->EvaluateAsInt(Result, Context,
947 Expr::SE_AllowSideEffects);
948 if (Result.Val.isInt())
949 ConstantCondValue = Result.Val.getInt();
950 assert(!HasConstantCond ||
951 (ConstantCondValue.getBitWidth() == CondWidth &&
952 ConstantCondValue.isSigned() == CondIsSigned));
954 bool ShouldCheckConstantCond = HasConstantCond;
956 // Sort all the scalar case values so we can easily detect duplicates.
957 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
959 if (!CaseVals.empty()) {
960 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
961 if (ShouldCheckConstantCond &&
962 CaseVals[i].first == ConstantCondValue)
963 ShouldCheckConstantCond = false;
965 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
966 // If we have a duplicate, report it.
967 // First, determine if either case value has a name
968 StringRef PrevString, CurrString;
969 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
970 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
971 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
972 PrevString = DeclRef->getDecl()->getName();
974 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
975 CurrString = DeclRef->getDecl()->getName();
977 SmallString<16> CaseValStr;
978 CaseVals[i-1].first.toString(CaseValStr);
980 if (PrevString == CurrString)
981 Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
982 diag::err_duplicate_case)
983 << (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
985 Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
986 diag::err_duplicate_case_differing_expr)
987 << (PrevString.empty() ? StringRef(CaseValStr) : PrevString)
988 << (CurrString.empty() ? StringRef(CaseValStr) : CurrString)
991 Diag(CaseVals[i - 1].second->getLHS()->getBeginLoc(),
992 diag::note_duplicate_case_prev);
993 // FIXME: We really want to remove the bogus case stmt from the
994 // substmt, but we have no way to do this right now.
995 CaseListIsErroneous = true;
1000 // Detect duplicate case ranges, which usually don't exist at all in
1002 if (!CaseRanges.empty()) {
1003 // Sort all the case ranges by their low value so we can easily detect
1004 // overlaps between ranges.
1005 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
1007 // Scan the ranges, computing the high values and removing empty ranges.
1008 std::vector<llvm::APSInt> HiVals;
1009 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1010 llvm::APSInt &LoVal = CaseRanges[i].first;
1011 CaseStmt *CR = CaseRanges[i].second;
1012 Expr *Hi = CR->getRHS();
1014 const Expr *HiBeforePromotion = Hi;
1015 GetTypeBeforeIntegralPromotion(HiBeforePromotion);
1016 llvm::APSInt HiVal = HiBeforePromotion->EvaluateKnownConstInt(Context);
1018 // Check the unconverted value is within the range of possible values of
1019 // the switch expression.
1020 checkCaseValue(*this, Hi->getBeginLoc(), HiVal,
1021 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
1023 // Convert the value to the same width/sign as the condition.
1024 AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
1026 // If the low value is bigger than the high value, the case is empty.
1027 if (LoVal > HiVal) {
1028 Diag(CR->getLHS()->getBeginLoc(), diag::warn_case_empty_range)
1029 << SourceRange(CR->getLHS()->getBeginLoc(), Hi->getEndLoc());
1030 CaseRanges.erase(CaseRanges.begin()+i);
1036 if (ShouldCheckConstantCond &&
1037 LoVal <= ConstantCondValue &&
1038 ConstantCondValue <= HiVal)
1039 ShouldCheckConstantCond = false;
1041 HiVals.push_back(HiVal);
1044 // Rescan the ranges, looking for overlap with singleton values and other
1045 // ranges. Since the range list is sorted, we only need to compare case
1046 // ranges with their neighbors.
1047 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1048 llvm::APSInt &CRLo = CaseRanges[i].first;
1049 llvm::APSInt &CRHi = HiVals[i];
1050 CaseStmt *CR = CaseRanges[i].second;
1052 // Check to see whether the case range overlaps with any
1054 CaseStmt *OverlapStmt = nullptr;
1055 llvm::APSInt OverlapVal(32);
1057 // Find the smallest value >= the lower bound. If I is in the
1058 // case range, then we have overlap.
1059 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
1060 CaseVals.end(), CRLo,
1061 CaseCompareFunctor());
1062 if (I != CaseVals.end() && I->first < CRHi) {
1063 OverlapVal = I->first; // Found overlap with scalar.
1064 OverlapStmt = I->second;
1067 // Find the smallest value bigger than the upper bound.
1068 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1069 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1070 OverlapVal = (I-1)->first; // Found overlap with scalar.
1071 OverlapStmt = (I-1)->second;
1074 // Check to see if this case stmt overlaps with the subsequent
1076 if (i && CRLo <= HiVals[i-1]) {
1077 OverlapVal = HiVals[i-1]; // Found overlap with range.
1078 OverlapStmt = CaseRanges[i-1].second;
1082 // If we have a duplicate, report it.
1083 Diag(CR->getLHS()->getBeginLoc(), diag::err_duplicate_case)
1084 << OverlapVal.toString(10);
1085 Diag(OverlapStmt->getLHS()->getBeginLoc(),
1086 diag::note_duplicate_case_prev);
1087 // FIXME: We really want to remove the bogus case stmt from the
1088 // substmt, but we have no way to do this right now.
1089 CaseListIsErroneous = true;
1094 // Complain if we have a constant condition and we didn't find a match.
1095 if (!CaseListIsErroneous && !CaseListIsIncomplete &&
1096 ShouldCheckConstantCond) {
1097 // TODO: it would be nice if we printed enums as enums, chars as
1099 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1100 << ConstantCondValue.toString(10)
1101 << CondExpr->getSourceRange();
1104 // Check to see if switch is over an Enum and handles all of its
1105 // values. We only issue a warning if there is not 'default:', but
1106 // we still do the analysis to preserve this information in the AST
1107 // (which can be used by flow-based analyes).
1109 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
1111 // If switch has default case, then ignore it.
1112 if (!CaseListIsErroneous && !CaseListIsIncomplete && !HasConstantCond &&
1113 ET && ET->getDecl()->isCompleteDefinition()) {
1114 const EnumDecl *ED = ET->getDecl();
1115 EnumValsTy EnumVals;
1117 // Gather all enum values, set their type and sort them,
1118 // allowing easier comparison with CaseVals.
1119 for (auto *EDI : ED->enumerators()) {
1120 llvm::APSInt Val = EDI->getInitVal();
1121 AdjustAPSInt(Val, CondWidth, CondIsSigned);
1122 EnumVals.push_back(std::make_pair(Val, EDI));
1124 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1125 auto EI = EnumVals.begin(), EIEnd =
1126 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1128 // See which case values aren't in enum.
1129 for (CaseValsTy::const_iterator CI = CaseVals.begin();
1130 CI != CaseVals.end(); CI++) {
1131 Expr *CaseExpr = CI->second->getLHS();
1132 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1134 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1135 << CondTypeBeforePromotion;
1138 // See which of case ranges aren't in enum
1139 EI = EnumVals.begin();
1140 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1141 RI != CaseRanges.end(); RI++) {
1142 Expr *CaseExpr = RI->second->getLHS();
1143 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1145 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1146 << CondTypeBeforePromotion;
1149 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1150 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1152 CaseExpr = RI->second->getRHS();
1153 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1155 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1156 << CondTypeBeforePromotion;
1159 // Check which enum vals aren't in switch
1160 auto CI = CaseVals.begin();
1161 auto RI = CaseRanges.begin();
1162 bool hasCasesNotInSwitch = false;
1164 SmallVector<DeclarationName,8> UnhandledNames;
1166 for (EI = EnumVals.begin(); EI != EIEnd; EI++) {
1167 // Don't warn about omitted unavailable EnumConstantDecls.
1168 switch (EI->second->getAvailability()) {
1170 // Omitting a deprecated constant is ok; it should never materialize.
1171 case AR_Unavailable:
1174 case AR_NotYetIntroduced:
1175 // Partially available enum constants should be present. Note that we
1176 // suppress -Wunguarded-availability diagnostics for such uses.
1181 // Drop unneeded case values
1182 while (CI != CaseVals.end() && CI->first < EI->first)
1185 if (CI != CaseVals.end() && CI->first == EI->first)
1188 // Drop unneeded case ranges
1189 for (; RI != CaseRanges.end(); RI++) {
1191 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1192 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1193 if (EI->first <= Hi)
1197 if (RI == CaseRanges.end() || EI->first < RI->first) {
1198 hasCasesNotInSwitch = true;
1199 UnhandledNames.push_back(EI->second->getDeclName());
1203 if (TheDefaultStmt && UnhandledNames.empty() && ED->isClosedNonFlag())
1204 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
1206 // Produce a nice diagnostic if multiple values aren't handled.
1207 if (!UnhandledNames.empty()) {
1208 DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
1209 TheDefaultStmt ? diag::warn_def_missing_case
1210 : diag::warn_missing_case)
1211 << (int)UnhandledNames.size();
1213 for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
1215 DB << UnhandledNames[I];
1218 if (!hasCasesNotInSwitch)
1219 SS->setAllEnumCasesCovered();
1224 DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), BodyStmt,
1225 diag::warn_empty_switch_body);
1227 // FIXME: If the case list was broken is some way, we don't have a good system
1228 // to patch it up. Instead, just return the whole substmt as broken.
1229 if (CaseListIsErroneous)
1236 Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1238 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
1241 if (const EnumType *ET = DstType->getAs<EnumType>())
1242 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
1243 SrcType->isIntegerType()) {
1244 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1245 SrcExpr->isIntegerConstantExpr(Context)) {
1246 // Get the bitwidth of the enum value before promotions.
1247 unsigned DstWidth = Context.getIntWidth(DstType);
1248 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1250 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1251 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
1252 const EnumDecl *ED = ET->getDecl();
1254 if (!ED->isClosed())
1257 if (ED->hasAttr<FlagEnumAttr>()) {
1258 if (!IsValueInFlagEnum(ED, RhsVal, true))
1259 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1260 << DstType.getUnqualifiedType();
1262 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1264 EnumValsTy EnumVals;
1266 // Gather all enum values, set their type and sort them,
1267 // allowing easier comparison with rhs constant.
1268 for (auto *EDI : ED->enumerators()) {
1269 llvm::APSInt Val = EDI->getInitVal();
1270 AdjustAPSInt(Val, DstWidth, DstIsSigned);
1271 EnumVals.push_back(std::make_pair(Val, EDI));
1273 if (EnumVals.empty())
1275 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1276 EnumValsTy::iterator EIend =
1277 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1279 // See which values aren't in the enum.
1280 EnumValsTy::const_iterator EI = EnumVals.begin();
1281 while (EI != EIend && EI->first < RhsVal)
1283 if (EI == EIend || EI->first != RhsVal) {
1284 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1285 << DstType.getUnqualifiedType();
1292 StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
1294 if (Cond.isInvalid())
1297 auto CondVal = Cond.get();
1298 CheckBreakContinueBinding(CondVal.second);
1300 if (CondVal.second &&
1301 !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc()))
1302 CommaVisitor(*this).Visit(CondVal.second);
1304 DiagnoseUnusedExprResult(Body);
1306 if (isa<NullStmt>(Body))
1307 getCurCompoundScope().setHasEmptyLoopBodies();
1309 return WhileStmt::Create(Context, CondVal.first, CondVal.second, Body,
1314 Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
1315 SourceLocation WhileLoc, SourceLocation CondLParen,
1316 Expr *Cond, SourceLocation CondRParen) {
1317 assert(Cond && "ActOnDoStmt(): missing expression");
1319 CheckBreakContinueBinding(Cond);
1320 ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond);
1321 if (CondResult.isInvalid())
1323 Cond = CondResult.get();
1325 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
1326 if (CondResult.isInvalid())
1328 Cond = CondResult.get();
1330 // Only call the CommaVisitor for C89 due to differences in scope flags.
1331 if (Cond && !getLangOpts().C99 && !getLangOpts().CPlusPlus &&
1332 !Diags.isIgnored(diag::warn_comma_operator, Cond->getExprLoc()))
1333 CommaVisitor(*this).Visit(Cond);
1335 DiagnoseUnusedExprResult(Body);
1337 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
1341 // Use SetVector since the diagnostic cares about the ordering of the Decl's.
1342 using DeclSetVector =
1343 llvm::SetVector<VarDecl *, llvm::SmallVector<VarDecl *, 8>,
1344 llvm::SmallPtrSet<VarDecl *, 8>>;
1346 // This visitor will traverse a conditional statement and store all
1347 // the evaluated decls into a vector. Simple is set to true if none
1348 // of the excluded constructs are used.
1349 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1350 DeclSetVector &Decls;
1351 SmallVectorImpl<SourceRange> &Ranges;
1354 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1356 DeclExtractor(Sema &S, DeclSetVector &Decls,
1357 SmallVectorImpl<SourceRange> &Ranges) :
1358 Inherited(S.Context),
1363 bool isSimple() { return Simple; }
1365 // Replaces the method in EvaluatedExprVisitor.
1366 void VisitMemberExpr(MemberExpr* E) {
1370 // Any Stmt not whitelisted will cause the condition to be marked complex.
1371 void VisitStmt(Stmt *S) {
1375 void VisitBinaryOperator(BinaryOperator *E) {
1380 void VisitCastExpr(CastExpr *E) {
1381 Visit(E->getSubExpr());
1384 void VisitUnaryOperator(UnaryOperator *E) {
1385 // Skip checking conditionals with derefernces.
1386 if (E->getOpcode() == UO_Deref)
1389 Visit(E->getSubExpr());
1392 void VisitConditionalOperator(ConditionalOperator *E) {
1393 Visit(E->getCond());
1394 Visit(E->getTrueExpr());
1395 Visit(E->getFalseExpr());
1398 void VisitParenExpr(ParenExpr *E) {
1399 Visit(E->getSubExpr());
1402 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1403 Visit(E->getOpaqueValue()->getSourceExpr());
1404 Visit(E->getFalseExpr());
1407 void VisitIntegerLiteral(IntegerLiteral *E) { }
1408 void VisitFloatingLiteral(FloatingLiteral *E) { }
1409 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1410 void VisitCharacterLiteral(CharacterLiteral *E) { }
1411 void VisitGNUNullExpr(GNUNullExpr *E) { }
1412 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1414 void VisitDeclRefExpr(DeclRefExpr *E) {
1415 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1417 // Don't allow unhandled Decl types.
1422 Ranges.push_back(E->getSourceRange());
1427 }; // end class DeclExtractor
1429 // DeclMatcher checks to see if the decls are used in a non-evaluated
1431 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1432 DeclSetVector &Decls;
1436 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1438 DeclMatcher(Sema &S, DeclSetVector &Decls, Stmt *Statement) :
1439 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1440 if (!Statement) return;
1445 void VisitReturnStmt(ReturnStmt *S) {
1449 void VisitBreakStmt(BreakStmt *S) {
1453 void VisitGotoStmt(GotoStmt *S) {
1457 void VisitCastExpr(CastExpr *E) {
1458 if (E->getCastKind() == CK_LValueToRValue)
1459 CheckLValueToRValueCast(E->getSubExpr());
1461 Visit(E->getSubExpr());
1464 void CheckLValueToRValueCast(Expr *E) {
1465 E = E->IgnoreParenImpCasts();
1467 if (isa<DeclRefExpr>(E)) {
1471 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1472 Visit(CO->getCond());
1473 CheckLValueToRValueCast(CO->getTrueExpr());
1474 CheckLValueToRValueCast(CO->getFalseExpr());
1478 if (BinaryConditionalOperator *BCO =
1479 dyn_cast<BinaryConditionalOperator>(E)) {
1480 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1481 CheckLValueToRValueCast(BCO->getFalseExpr());
1488 void VisitDeclRefExpr(DeclRefExpr *E) {
1489 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1490 if (Decls.count(VD))
1494 void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
1495 // Only need to visit the semantics for POE.
1496 // SyntaticForm doesn't really use the Decal.
1497 for (auto *S : POE->semantics()) {
1498 if (auto *OVE = dyn_cast<OpaqueValueExpr>(S))
1499 // Look past the OVE into the expression it binds.
1500 Visit(OVE->getSourceExpr());
1506 bool FoundDeclInUse() { return FoundDecl; }
1508 }; // end class DeclMatcher
1510 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1511 Expr *Third, Stmt *Body) {
1512 // Condition is empty
1513 if (!Second) return;
1515 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1516 Second->getBeginLoc()))
1519 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1520 DeclSetVector Decls;
1521 SmallVector<SourceRange, 10> Ranges;
1522 DeclExtractor DE(S, Decls, Ranges);
1525 // Don't analyze complex conditionals.
1526 if (!DE.isSimple()) return;
1529 if (Decls.size() == 0) return;
1531 // Don't warn on volatile, static, or global variables.
1532 for (auto *VD : Decls)
1533 if (VD->getType().isVolatileQualified() || VD->hasGlobalStorage())
1536 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1537 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1538 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1541 // Load decl names into diagnostic.
1542 if (Decls.size() > 4) {
1545 PDiag << (unsigned)Decls.size();
1546 for (auto *VD : Decls)
1547 PDiag << VD->getDeclName();
1550 for (auto Range : Ranges)
1553 S.Diag(Ranges.begin()->getBegin(), PDiag);
1556 // If Statement is an incemement or decrement, return true and sets the
1557 // variables Increment and DRE.
1558 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1559 DeclRefExpr *&DRE) {
1560 if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement))
1561 if (!Cleanups->cleanupsHaveSideEffects())
1562 Statement = Cleanups->getSubExpr();
1564 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1565 switch (UO->getOpcode()) {
1566 default: return false;
1576 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1580 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1581 FunctionDecl *FD = Call->getDirectCallee();
1582 if (!FD || !FD->isOverloadedOperator()) return false;
1583 switch (FD->getOverloadedOperator()) {
1584 default: return false;
1592 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1599 // A visitor to determine if a continue or break statement is a
1601 class BreakContinueFinder : public ConstEvaluatedExprVisitor<BreakContinueFinder> {
1602 SourceLocation BreakLoc;
1603 SourceLocation ContinueLoc;
1604 bool InSwitch = false;
1607 BreakContinueFinder(Sema &S, const Stmt* Body) :
1608 Inherited(S.Context) {
1612 typedef ConstEvaluatedExprVisitor<BreakContinueFinder> Inherited;
1614 void VisitContinueStmt(const ContinueStmt* E) {
1615 ContinueLoc = E->getContinueLoc();
1618 void VisitBreakStmt(const BreakStmt* E) {
1620 BreakLoc = E->getBreakLoc();
1623 void VisitSwitchStmt(const SwitchStmt* S) {
1624 if (const Stmt *Init = S->getInit())
1626 if (const Stmt *CondVar = S->getConditionVariableDeclStmt())
1628 if (const Stmt *Cond = S->getCond())
1631 // Don't return break statements from the body of a switch.
1633 if (const Stmt *Body = S->getBody())
1638 void VisitForStmt(const ForStmt *S) {
1639 // Only visit the init statement of a for loop; the body
1640 // has a different break/continue scope.
1641 if (const Stmt *Init = S->getInit())
1645 void VisitWhileStmt(const WhileStmt *) {
1646 // Do nothing; the children of a while loop have a different
1647 // break/continue scope.
1650 void VisitDoStmt(const DoStmt *) {
1651 // Do nothing; the children of a while loop have a different
1652 // break/continue scope.
1655 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
1656 // Only visit the initialization of a for loop; the body
1657 // has a different break/continue scope.
1658 if (const Stmt *Init = S->getInit())
1660 if (const Stmt *Range = S->getRangeStmt())
1662 if (const Stmt *Begin = S->getBeginStmt())
1664 if (const Stmt *End = S->getEndStmt())
1668 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
1669 // Only visit the initialization of a for loop; the body
1670 // has a different break/continue scope.
1671 if (const Stmt *Element = S->getElement())
1673 if (const Stmt *Collection = S->getCollection())
1677 bool ContinueFound() { return ContinueLoc.isValid(); }
1678 bool BreakFound() { return BreakLoc.isValid(); }
1679 SourceLocation GetContinueLoc() { return ContinueLoc; }
1680 SourceLocation GetBreakLoc() { return BreakLoc; }
1682 }; // end class BreakContinueFinder
1684 // Emit a warning when a loop increment/decrement appears twice per loop
1685 // iteration. The conditions which trigger this warning are:
1686 // 1) The last statement in the loop body and the third expression in the
1687 // for loop are both increment or both decrement of the same variable
1688 // 2) No continue statements in the loop body.
1689 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1690 // Return when there is nothing to check.
1691 if (!Body || !Third) return;
1693 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1694 Third->getBeginLoc()))
1697 // Get the last statement from the loop body.
1698 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1699 if (!CS || CS->body_empty()) return;
1700 Stmt *LastStmt = CS->body_back();
1701 if (!LastStmt) return;
1703 bool LoopIncrement, LastIncrement;
1704 DeclRefExpr *LoopDRE, *LastDRE;
1706 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1707 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1709 // Check that the two statements are both increments or both decrements
1710 // on the same variable.
1711 if (LoopIncrement != LastIncrement ||
1712 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1714 if (BreakContinueFinder(S, Body).ContinueFound()) return;
1716 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1717 << LastDRE->getDecl() << LastIncrement;
1718 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1725 void Sema::CheckBreakContinueBinding(Expr *E) {
1726 if (!E || getLangOpts().CPlusPlus)
1728 BreakContinueFinder BCFinder(*this, E);
1729 Scope *BreakParent = CurScope->getBreakParent();
1730 if (BCFinder.BreakFound() && BreakParent) {
1731 if (BreakParent->getFlags() & Scope::SwitchScope) {
1732 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1734 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1737 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1738 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1743 StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1744 Stmt *First, ConditionResult Second,
1745 FullExprArg third, SourceLocation RParenLoc,
1747 if (Second.isInvalid())
1750 if (!getLangOpts().CPlusPlus) {
1751 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
1752 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1753 // declare identifiers for objects having storage class 'auto' or
1755 for (auto *DI : DS->decls()) {
1756 VarDecl *VD = dyn_cast<VarDecl>(DI);
1757 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
1760 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1761 DI->setInvalidDecl();
1767 CheckBreakContinueBinding(Second.get().second);
1768 CheckBreakContinueBinding(third.get());
1770 if (!Second.get().first)
1771 CheckForLoopConditionalStatement(*this, Second.get().second, third.get(),
1773 CheckForRedundantIteration(*this, third.get(), Body);
1775 if (Second.get().second &&
1776 !Diags.isIgnored(diag::warn_comma_operator,
1777 Second.get().second->getExprLoc()))
1778 CommaVisitor(*this).Visit(Second.get().second);
1780 Expr *Third = third.release().getAs<Expr>();
1782 DiagnoseUnusedExprResult(First);
1783 DiagnoseUnusedExprResult(Third);
1784 DiagnoseUnusedExprResult(Body);
1786 if (isa<NullStmt>(Body))
1787 getCurCompoundScope().setHasEmptyLoopBodies();
1789 return new (Context)
1790 ForStmt(Context, First, Second.get().second, Second.get().first, Third,
1791 Body, ForLoc, LParenLoc, RParenLoc);
1794 /// In an Objective C collection iteration statement:
1796 /// x can be an arbitrary l-value expression. Bind it up as a
1797 /// full-expression.
1798 StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
1799 // Reduce placeholder expressions here. Note that this rejects the
1800 // use of pseudo-object l-values in this position.
1801 ExprResult result = CheckPlaceholderExpr(E);
1802 if (result.isInvalid()) return StmtError();
1805 ExprResult FullExpr = ActOnFinishFullExpr(E);
1806 if (FullExpr.isInvalid())
1808 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
1812 Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1816 ExprResult result = CorrectDelayedTyposInExpr(collection);
1817 if (!result.isUsable())
1819 collection = result.get();
1821 // Bail out early if we've got a type-dependent expression.
1822 if (collection->isTypeDependent()) return collection;
1824 // Perform normal l-value conversion.
1825 result = DefaultFunctionArrayLvalueConversion(collection);
1826 if (result.isInvalid())
1828 collection = result.get();
1830 // The operand needs to have object-pointer type.
1831 // TODO: should we do a contextual conversion?
1832 const ObjCObjectPointerType *pointerType =
1833 collection->getType()->getAs<ObjCObjectPointerType>();
1835 return Diag(forLoc, diag::err_collection_expr_type)
1836 << collection->getType() << collection->getSourceRange();
1838 // Check that the operand provides
1839 // - countByEnumeratingWithState:objects:count:
1840 const ObjCObjectType *objectType = pointerType->getObjectType();
1841 ObjCInterfaceDecl *iface = objectType->getInterface();
1843 // If we have a forward-declared type, we can't do this check.
1844 // Under ARC, it is an error not to have a forward-declared class.
1846 (getLangOpts().ObjCAutoRefCount
1847 ? RequireCompleteType(forLoc, QualType(objectType, 0),
1848 diag::err_arc_collection_forward, collection)
1849 : !isCompleteType(forLoc, QualType(objectType, 0)))) {
1850 // Otherwise, if we have any useful type information, check that
1851 // the type declares the appropriate method.
1852 } else if (iface || !objectType->qual_empty()) {
1853 IdentifierInfo *selectorIdents[] = {
1854 &Context.Idents.get("countByEnumeratingWithState"),
1855 &Context.Idents.get("objects"),
1856 &Context.Idents.get("count")
1858 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1860 ObjCMethodDecl *method = nullptr;
1862 // If there's an interface, look in both the public and private APIs.
1864 method = iface->lookupInstanceMethod(selector);
1865 if (!method) method = iface->lookupPrivateMethod(selector);
1868 // Also check protocol qualifiers.
1870 method = LookupMethodInQualifiedType(selector, pointerType,
1873 // If we didn't find it anywhere, give up.
1875 Diag(forLoc, diag::warn_collection_expr_type)
1876 << collection->getType() << selector << collection->getSourceRange();
1879 // TODO: check for an incompatible signature?
1882 // Wrap up any cleanups in the expression.
1887 Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1888 Stmt *First, Expr *collection,
1889 SourceLocation RParenLoc) {
1890 setFunctionHasBranchProtectedScope();
1892 ExprResult CollectionExprResult =
1893 CheckObjCForCollectionOperand(ForLoc, collection);
1897 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
1898 if (!DS->isSingleDecl())
1899 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1900 diag::err_toomany_element_decls));
1902 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1903 if (!D || D->isInvalidDecl())
1906 FirstType = D->getType();
1907 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1908 // declare identifiers for objects having storage class 'auto' or
1910 if (!D->hasLocalStorage())
1911 return StmtError(Diag(D->getLocation(),
1912 diag::err_non_local_variable_decl_in_for));
1914 // If the type contained 'auto', deduce the 'auto' to 'id'.
1915 if (FirstType->getContainedAutoType()) {
1916 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1918 Expr *DeducedInit = &OpaqueId;
1919 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1921 DiagnoseAutoDeductionFailure(D, DeducedInit);
1922 if (FirstType.isNull()) {
1923 D->setInvalidDecl();
1927 D->setType(FirstType);
1929 if (!inTemplateInstantiation()) {
1930 SourceLocation Loc =
1931 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
1932 Diag(Loc, diag::warn_auto_var_is_id)
1933 << D->getDeclName();
1938 Expr *FirstE = cast<Expr>(First);
1939 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
1941 Diag(First->getBeginLoc(), diag::err_selector_element_not_lvalue)
1942 << First->getSourceRange());
1944 FirstType = static_cast<Expr*>(First)->getType();
1945 if (FirstType.isConstQualified())
1946 Diag(ForLoc, diag::err_selector_element_const_type)
1947 << FirstType << First->getSourceRange();
1949 if (!FirstType->isDependentType() &&
1950 !FirstType->isObjCObjectPointerType() &&
1951 !FirstType->isBlockPointerType())
1952 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1953 << FirstType << First->getSourceRange());
1956 if (CollectionExprResult.isInvalid())
1959 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
1960 if (CollectionExprResult.isInvalid())
1963 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1964 nullptr, ForLoc, RParenLoc);
1967 /// Finish building a variable declaration for a for-range statement.
1968 /// \return true if an error occurs.
1969 static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1970 SourceLocation Loc, int DiagID) {
1971 if (Decl->getType()->isUndeducedType()) {
1972 ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
1973 if (!Res.isUsable()) {
1974 Decl->setInvalidDecl();
1980 // Deduce the type for the iterator variable now rather than leaving it to
1981 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1983 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
1984 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
1986 SemaRef.Diag(Loc, DiagID) << Init->getType();
1987 if (InitType.isNull()) {
1988 Decl->setInvalidDecl();
1991 Decl->setType(InitType);
1993 // In ARC, infer lifetime.
1994 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1995 // we're doing the equivalent of fast iteration.
1996 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1997 SemaRef.inferObjCARCLifetime(Decl))
1998 Decl->setInvalidDecl();
2000 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false);
2001 SemaRef.FinalizeDeclaration(Decl);
2002 SemaRef.CurContext->addHiddenDecl(Decl);
2007 // An enum to represent whether something is dealing with a call to begin()
2008 // or a call to end() in a range-based for loop.
2009 enum BeginEndFunction {
2014 /// Produce a note indicating which begin/end function was implicitly called
2015 /// by a C++11 for-range statement. This is often not obvious from the code,
2016 /// nor from the diagnostics produced when analysing the implicit expressions
2017 /// required in a for-range statement.
2018 void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
2019 BeginEndFunction BEF) {
2020 CallExpr *CE = dyn_cast<CallExpr>(E);
2023 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
2026 SourceLocation Loc = D->getLocation();
2028 std::string Description;
2029 bool IsTemplate = false;
2030 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
2031 Description = SemaRef.getTemplateArgumentBindingsText(
2032 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
2036 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
2037 << BEF << IsTemplate << Description << E->getType();
2040 /// Build a variable declaration for a for-range statement.
2041 VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
2042 QualType Type, StringRef Name) {
2043 DeclContext *DC = SemaRef.CurContext;
2044 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
2045 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
2046 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
2048 Decl->setImplicit();
2054 static bool ObjCEnumerationCollection(Expr *Collection) {
2055 return !Collection->isTypeDependent()
2056 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
2059 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
2061 /// C++11 [stmt.ranged]:
2062 /// A range-based for statement is equivalent to
2065 /// auto && __range = range-init;
2066 /// for ( auto __begin = begin-expr,
2067 /// __end = end-expr;
2068 /// __begin != __end;
2070 /// for-range-declaration = *__begin;
2075 /// The body of the loop is not available yet, since it cannot be analysed until
2076 /// we have determined the type of the for-range-declaration.
2077 StmtResult Sema::ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
2078 SourceLocation CoawaitLoc, Stmt *InitStmt,
2079 Stmt *First, SourceLocation ColonLoc,
2080 Expr *Range, SourceLocation RParenLoc,
2081 BuildForRangeKind Kind) {
2085 if (Range && ObjCEnumerationCollection(Range)) {
2086 // FIXME: Support init-statements in Objective-C++20 ranged for statement.
2088 return Diag(InitStmt->getBeginLoc(), diag::err_objc_for_range_init_stmt)
2089 << InitStmt->getSourceRange();
2090 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
2093 DeclStmt *DS = dyn_cast<DeclStmt>(First);
2094 assert(DS && "first part of for range not a decl stmt");
2096 if (!DS->isSingleDecl()) {
2097 Diag(DS->getBeginLoc(), diag::err_type_defined_in_for_range);
2101 Decl *LoopVar = DS->getSingleDecl();
2102 if (LoopVar->isInvalidDecl() || !Range ||
2103 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
2104 LoopVar->setInvalidDecl();
2108 // Build the coroutine state immediately and not later during template
2110 if (!CoawaitLoc.isInvalid()) {
2111 if (!ActOnCoroutineBodyStart(S, CoawaitLoc, "co_await"))
2115 // Build auto && __range = range-init
2116 // Divide by 2, since the variables are in the inner scope (loop body).
2117 const auto DepthStr = std::to_string(S->getDepth() / 2);
2118 SourceLocation RangeLoc = Range->getBeginLoc();
2119 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
2120 Context.getAutoRRefDeductType(),
2121 std::string("__range") + DepthStr);
2122 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
2123 diag::err_for_range_deduction_failure)) {
2124 LoopVar->setInvalidDecl();
2128 // Claim the type doesn't contain auto: we've already done the checking.
2129 DeclGroupPtrTy RangeGroup =
2130 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1));
2131 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
2132 if (RangeDecl.isInvalid()) {
2133 LoopVar->setInvalidDecl();
2137 return BuildCXXForRangeStmt(
2138 ForLoc, CoawaitLoc, InitStmt, ColonLoc, RangeDecl.get(),
2139 /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
2140 /*Cond=*/nullptr, /*Inc=*/nullptr, DS, RParenLoc, Kind);
2143 /// Create the initialization, compare, and increment steps for
2144 /// the range-based for loop expression.
2145 /// This function does not handle array-based for loops,
2146 /// which are created in Sema::BuildCXXForRangeStmt.
2148 /// \returns a ForRangeStatus indicating success or what kind of error occurred.
2149 /// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2150 /// CandidateSet and BEF are set and some non-success value is returned on
2152 static Sema::ForRangeStatus
2153 BuildNonArrayForRange(Sema &SemaRef, Expr *BeginRange, Expr *EndRange,
2154 QualType RangeType, VarDecl *BeginVar, VarDecl *EndVar,
2155 SourceLocation ColonLoc, SourceLocation CoawaitLoc,
2156 OverloadCandidateSet *CandidateSet, ExprResult *BeginExpr,
2157 ExprResult *EndExpr, BeginEndFunction *BEF) {
2158 DeclarationNameInfo BeginNameInfo(
2159 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2160 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2163 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2164 Sema::LookupMemberName);
2165 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2167 auto BuildBegin = [&] {
2169 Sema::ForRangeStatus RangeStatus =
2170 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
2171 BeginMemberLookup, CandidateSet,
2172 BeginRange, BeginExpr);
2174 if (RangeStatus != Sema::FRS_Success) {
2175 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2176 SemaRef.Diag(BeginRange->getBeginLoc(), diag::note_in_for_range)
2177 << ColonLoc << BEF_begin << BeginRange->getType();
2180 if (!CoawaitLoc.isInvalid()) {
2181 // FIXME: getCurScope() should not be used during template instantiation.
2182 // We should pick up the set of unqualified lookup results for operator
2183 // co_await during the initial parse.
2184 *BeginExpr = SemaRef.ActOnCoawaitExpr(SemaRef.getCurScope(), ColonLoc,
2186 if (BeginExpr->isInvalid())
2187 return Sema::FRS_DiagnosticIssued;
2189 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2190 diag::err_for_range_iter_deduction_failure)) {
2191 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2192 return Sema::FRS_DiagnosticIssued;
2194 return Sema::FRS_Success;
2197 auto BuildEnd = [&] {
2199 Sema::ForRangeStatus RangeStatus =
2200 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
2201 EndMemberLookup, CandidateSet,
2203 if (RangeStatus != Sema::FRS_Success) {
2204 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2205 SemaRef.Diag(EndRange->getBeginLoc(), diag::note_in_for_range)
2206 << ColonLoc << BEF_end << EndRange->getType();
2209 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2210 diag::err_for_range_iter_deduction_failure)) {
2211 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2212 return Sema::FRS_DiagnosticIssued;
2214 return Sema::FRS_Success;
2217 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2218 // - if _RangeT is a class type, the unqualified-ids begin and end are
2219 // looked up in the scope of class _RangeT as if by class member access
2220 // lookup (3.4.5), and if either (or both) finds at least one
2221 // declaration, begin-expr and end-expr are __range.begin() and
2222 // __range.end(), respectively;
2223 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2224 if (BeginMemberLookup.isAmbiguous())
2225 return Sema::FRS_DiagnosticIssued;
2227 SemaRef.LookupQualifiedName(EndMemberLookup, D);
2228 if (EndMemberLookup.isAmbiguous())
2229 return Sema::FRS_DiagnosticIssued;
2231 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2232 // Look up the non-member form of the member we didn't find, first.
2233 // This way we prefer a "no viable 'end'" diagnostic over a "i found
2234 // a 'begin' but ignored it because there was no member 'end'"
2236 auto BuildNonmember = [&](
2237 BeginEndFunction BEFFound, LookupResult &Found,
2238 llvm::function_ref<Sema::ForRangeStatus()> BuildFound,
2239 llvm::function_ref<Sema::ForRangeStatus()> BuildNotFound) {
2240 LookupResult OldFound = std::move(Found);
2243 if (Sema::ForRangeStatus Result = BuildNotFound())
2246 switch (BuildFound()) {
2247 case Sema::FRS_Success:
2248 return Sema::FRS_Success;
2250 case Sema::FRS_NoViableFunction:
2251 SemaRef.Diag(BeginRange->getBeginLoc(), diag::err_for_range_invalid)
2252 << BeginRange->getType() << BEFFound;
2253 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, BeginRange);
2256 case Sema::FRS_DiagnosticIssued:
2257 for (NamedDecl *D : OldFound) {
2258 SemaRef.Diag(D->getLocation(),
2259 diag::note_for_range_member_begin_end_ignored)
2260 << BeginRange->getType() << BEFFound;
2262 return Sema::FRS_DiagnosticIssued;
2264 llvm_unreachable("unexpected ForRangeStatus");
2266 if (BeginMemberLookup.empty())
2267 return BuildNonmember(BEF_end, EndMemberLookup, BuildEnd, BuildBegin);
2268 return BuildNonmember(BEF_begin, BeginMemberLookup, BuildBegin, BuildEnd);
2271 // - otherwise, begin-expr and end-expr are begin(__range) and
2272 // end(__range), respectively, where begin and end are looked up with
2273 // argument-dependent lookup (3.4.2). For the purposes of this name
2274 // lookup, namespace std is an associated namespace.
2277 if (Sema::ForRangeStatus Result = BuildBegin())
2282 /// Speculatively attempt to dereference an invalid range expression.
2283 /// If the attempt fails, this function will return a valid, null StmtResult
2284 /// and emit no diagnostics.
2285 static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2286 SourceLocation ForLoc,
2287 SourceLocation CoawaitLoc,
2290 SourceLocation ColonLoc,
2292 SourceLocation RangeLoc,
2293 SourceLocation RParenLoc) {
2294 // Determine whether we can rebuild the for-range statement with a
2295 // dereferenced range expression.
2296 ExprResult AdjustedRange;
2298 Sema::SFINAETrap Trap(SemaRef);
2300 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2301 if (AdjustedRange.isInvalid())
2302 return StmtResult();
2304 StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
2305 S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
2306 AdjustedRange.get(), RParenLoc, Sema::BFRK_Check);
2308 return StmtResult();
2311 // The attempt to dereference worked well enough that it could produce a valid
2312 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2313 // case there are any other (non-fatal) problems with it.
2314 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2315 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
2316 return SemaRef.ActOnCXXForRangeStmt(
2317 S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
2318 AdjustedRange.get(), RParenLoc, Sema::BFRK_Rebuild);
2322 /// RAII object to automatically invalidate a declaration if an error occurs.
2323 struct InvalidateOnErrorScope {
2324 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2325 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2326 ~InvalidateOnErrorScope() {
2327 if (Enabled && Trap.hasErrorOccurred())
2328 D->setInvalidDecl();
2331 DiagnosticErrorTrap Trap;
2337 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
2338 StmtResult Sema::BuildCXXForRangeStmt(SourceLocation ForLoc,
2339 SourceLocation CoawaitLoc, Stmt *InitStmt,
2340 SourceLocation ColonLoc, Stmt *RangeDecl,
2341 Stmt *Begin, Stmt *End, Expr *Cond,
2342 Expr *Inc, Stmt *LoopVarDecl,
2343 SourceLocation RParenLoc,
2344 BuildForRangeKind Kind) {
2345 // FIXME: This should not be used during template instantiation. We should
2346 // pick up the set of unqualified lookup results for the != and + operators
2347 // in the initial parse.
2349 // Testcase (accepts-invalid):
2350 // template<typename T> void f() { for (auto x : T()) {} }
2351 // namespace N { struct X { X begin(); X end(); int operator*(); }; }
2352 // bool operator!=(N::X, N::X); void operator++(N::X);
2353 // void g() { f<N::X>(); }
2354 Scope *S = getCurScope();
2356 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2357 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2358 QualType RangeVarType = RangeVar->getType();
2360 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2361 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2363 // If we hit any errors, mark the loop variable as invalid if its type
2365 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2366 LoopVar->getType()->isUndeducedType());
2368 StmtResult BeginDeclStmt = Begin;
2369 StmtResult EndDeclStmt = End;
2370 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2372 if (RangeVarType->isDependentType()) {
2373 // The range is implicitly used as a placeholder when it is dependent.
2374 RangeVar->markUsed(Context);
2376 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2377 // them in properly when we instantiate the loop.
2378 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2379 if (auto *DD = dyn_cast<DecompositionDecl>(LoopVar))
2380 for (auto *Binding : DD->bindings())
2381 Binding->setType(Context.DependentTy);
2382 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
2384 } else if (!BeginDeclStmt.get()) {
2385 SourceLocation RangeLoc = RangeVar->getLocation();
2387 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2389 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2390 VK_LValue, ColonLoc);
2391 if (BeginRangeRef.isInvalid())
2394 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2395 VK_LValue, ColonLoc);
2396 if (EndRangeRef.isInvalid())
2399 QualType AutoType = Context.getAutoDeductType();
2400 Expr *Range = RangeVar->getInit();
2403 QualType RangeType = Range->getType();
2405 if (RequireCompleteType(RangeLoc, RangeType,
2406 diag::err_for_range_incomplete_type))
2409 // Build auto __begin = begin-expr, __end = end-expr.
2410 // Divide by 2, since the variables are in the inner scope (loop body).
2411 const auto DepthStr = std::to_string(S->getDepth() / 2);
2412 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2413 std::string("__begin") + DepthStr);
2414 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2415 std::string("__end") + DepthStr);
2417 // Build begin-expr and end-expr and attach to __begin and __end variables.
2418 ExprResult BeginExpr, EndExpr;
2419 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2420 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2421 // __range + __bound, respectively, where __bound is the array bound. If
2422 // _RangeT is an array of unknown size or an array of incomplete type,
2423 // the program is ill-formed;
2425 // begin-expr is __range.
2426 BeginExpr = BeginRangeRef;
2427 if (!CoawaitLoc.isInvalid()) {
2428 BeginExpr = ActOnCoawaitExpr(S, ColonLoc, BeginExpr.get());
2429 if (BeginExpr.isInvalid())
2432 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
2433 diag::err_for_range_iter_deduction_failure)) {
2434 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2438 // Find the array bound.
2439 ExprResult BoundExpr;
2440 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
2441 BoundExpr = IntegerLiteral::Create(
2442 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
2443 else if (const VariableArrayType *VAT =
2444 dyn_cast<VariableArrayType>(UnqAT)) {
2445 // For a variably modified type we can't just use the expression within
2446 // the array bounds, since we don't want that to be re-evaluated here.
2447 // Rather, we need to determine what it was when the array was first
2448 // created - so we resort to using sizeof(vla)/sizeof(element).
2452 // b = -1; <-- This should not affect the num of iterations below
2453 // for (int &c : vla) { .. }
2456 // FIXME: This results in codegen generating IR that recalculates the
2457 // run-time number of elements (as opposed to just using the IR Value
2458 // that corresponds to the run-time value of each bound that was
2459 // generated when the array was created.) If this proves too embarrassing
2460 // even for unoptimized IR, consider passing a magic-value/cookie to
2461 // codegen that then knows to simply use that initial llvm::Value (that
2462 // corresponds to the bound at time of array creation) within
2463 // getelementptr. But be prepared to pay the price of increasing a
2464 // customized form of coupling between the two components - which could
2465 // be hard to maintain as the codebase evolves.
2467 ExprResult SizeOfVLAExprR = ActOnUnaryExprOrTypeTraitExpr(
2468 EndVar->getLocation(), UETT_SizeOf,
2470 CreateParsedType(VAT->desugar(), Context.getTrivialTypeSourceInfo(
2471 VAT->desugar(), RangeLoc))
2473 EndVar->getSourceRange());
2474 if (SizeOfVLAExprR.isInvalid())
2477 ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr(
2478 EndVar->getLocation(), UETT_SizeOf,
2480 CreateParsedType(VAT->desugar(),
2481 Context.getTrivialTypeSourceInfo(
2482 VAT->getElementType(), RangeLoc))
2484 EndVar->getSourceRange());
2485 if (SizeOfEachElementExprR.isInvalid())
2489 ActOnBinOp(S, EndVar->getLocation(), tok::slash,
2490 SizeOfVLAExprR.get(), SizeOfEachElementExprR.get());
2491 if (BoundExpr.isInvalid())
2495 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2496 // UnqAT is not incomplete and Range is not type-dependent.
2497 llvm_unreachable("Unexpected array type in for-range");
2500 // end-expr is __range + __bound.
2501 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
2503 if (EndExpr.isInvalid())
2505 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2506 diag::err_for_range_iter_deduction_failure)) {
2507 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2511 OverloadCandidateSet CandidateSet(RangeLoc,
2512 OverloadCandidateSet::CSK_Normal);
2513 BeginEndFunction BEFFailure;
2514 ForRangeStatus RangeStatus = BuildNonArrayForRange(
2515 *this, BeginRangeRef.get(), EndRangeRef.get(), RangeType, BeginVar,
2516 EndVar, ColonLoc, CoawaitLoc, &CandidateSet, &BeginExpr, &EndExpr,
2519 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
2520 BEFFailure == BEF_begin) {
2521 // If the range is being built from an array parameter, emit a
2522 // a diagnostic that it is being treated as a pointer.
2523 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2524 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2525 QualType ArrayTy = PVD->getOriginalType();
2526 QualType PointerTy = PVD->getType();
2527 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2528 Diag(Range->getBeginLoc(), diag::err_range_on_array_parameter)
2529 << RangeLoc << PVD << ArrayTy << PointerTy;
2530 Diag(PVD->getLocation(), diag::note_declared_at);
2536 // If building the range failed, try dereferencing the range expression
2537 // unless a diagnostic was issued or the end function is problematic.
2538 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2539 CoawaitLoc, InitStmt,
2540 LoopVarDecl, ColonLoc,
2543 if (SR.isInvalid() || SR.isUsable())
2547 // Otherwise, emit diagnostics if we haven't already.
2548 if (RangeStatus == FRS_NoViableFunction) {
2549 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
2550 Diag(Range->getBeginLoc(), diag::err_for_range_invalid)
2551 << RangeLoc << Range->getType() << BEFFailure;
2552 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
2554 // Return an error if no fix was discovered.
2555 if (RangeStatus != FRS_Success)
2559 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2560 "invalid range expression in for loop");
2562 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
2563 // C++1z removes this restriction.
2564 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2565 if (!Context.hasSameType(BeginType, EndType)) {
2566 Diag(RangeLoc, getLangOpts().CPlusPlus17
2567 ? diag::warn_for_range_begin_end_types_differ
2568 : diag::ext_for_range_begin_end_types_differ)
2569 << BeginType << EndType;
2570 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2571 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2575 ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
2577 ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
2579 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2580 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2581 VK_LValue, ColonLoc);
2582 if (BeginRef.isInvalid())
2585 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2586 VK_LValue, ColonLoc);
2587 if (EndRef.isInvalid())
2590 // Build and check __begin != __end expression.
2591 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2592 BeginRef.get(), EndRef.get());
2593 if (!NotEqExpr.isInvalid())
2594 NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get());
2595 if (!NotEqExpr.isInvalid())
2596 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2597 if (NotEqExpr.isInvalid()) {
2598 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2599 << RangeLoc << 0 << BeginRangeRef.get()->getType();
2600 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2601 if (!Context.hasSameType(BeginType, EndType))
2602 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2606 // Build and check ++__begin expression.
2607 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2608 VK_LValue, ColonLoc);
2609 if (BeginRef.isInvalid())
2612 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2613 if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
2614 // FIXME: getCurScope() should not be used during template instantiation.
2615 // We should pick up the set of unqualified lookup results for operator
2616 // co_await during the initial parse.
2617 IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
2618 if (!IncrExpr.isInvalid())
2619 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2620 if (IncrExpr.isInvalid()) {
2621 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2622 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
2623 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2627 // Build and check *__begin expression.
2628 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2629 VK_LValue, ColonLoc);
2630 if (BeginRef.isInvalid())
2633 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2634 if (DerefExpr.isInvalid()) {
2635 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2636 << RangeLoc << 1 << BeginRangeRef.get()->getType();
2637 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2641 // Attach *__begin as initializer for VD. Don't touch it if we're just
2642 // trying to determine whether this would be a valid range.
2643 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2644 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false);
2645 if (LoopVar->isInvalidDecl())
2646 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2650 // Don't bother to actually allocate the result if we're just trying to
2651 // determine whether it would be valid.
2652 if (Kind == BFRK_Check)
2653 return StmtResult();
2655 return new (Context) CXXForRangeStmt(
2656 InitStmt, RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
2657 cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
2658 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
2659 ColonLoc, RParenLoc);
2662 /// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
2664 StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2667 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
2669 ForStmt->setBody(B);
2673 // Warn when the loop variable is a const reference that creates a copy.
2674 // Suggest using the non-reference type for copies. If a copy can be prevented
2675 // suggest the const reference type that would do so.
2676 // For instance, given "for (const &Foo : Range)", suggest
2677 // "for (const Foo : Range)" to denote a copy is made for the loop. If
2678 // possible, also suggest "for (const &Bar : Range)" if this type prevents
2679 // the copy altogether.
2680 static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
2682 QualType RangeInitType) {
2683 const Expr *InitExpr = VD->getInit();
2687 QualType VariableType = VD->getType();
2689 if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr))
2690 if (!Cleanups->cleanupsHaveSideEffects())
2691 InitExpr = Cleanups->getSubExpr();
2693 const MaterializeTemporaryExpr *MTE =
2694 dyn_cast<MaterializeTemporaryExpr>(InitExpr);
2700 const Expr *E = MTE->GetTemporaryExpr()->IgnoreImpCasts();
2702 // Searching for either UnaryOperator for dereference of a pointer or
2703 // CXXOperatorCallExpr for handling iterators.
2704 while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
2705 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
2707 } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
2708 const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
2711 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
2712 E = MTE->GetTemporaryExpr();
2714 E = E->IgnoreImpCasts();
2717 bool ReturnsReference = false;
2718 if (isa<UnaryOperator>(E)) {
2719 ReturnsReference = true;
2721 const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
2722 const FunctionDecl *FD = Call->getDirectCallee();
2723 QualType ReturnType = FD->getReturnType();
2724 ReturnsReference = ReturnType->isReferenceType();
2727 if (ReturnsReference) {
2728 // Loop variable creates a temporary. Suggest either to go with
2729 // non-reference loop variable to indicate a copy is made, or
2730 // the correct time to bind a const reference.
2731 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy)
2732 << VD << VariableType << E->getType();
2733 QualType NonReferenceType = VariableType.getNonReferenceType();
2734 NonReferenceType.removeLocalConst();
2735 QualType NewReferenceType =
2736 SemaRef.Context.getLValueReferenceType(E->getType().withConst());
2737 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_type_or_non_reference)
2738 << NonReferenceType << NewReferenceType << VD->getSourceRange();
2740 // The range always returns a copy, so a temporary is always created.
2741 // Suggest removing the reference from the loop variable.
2742 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy)
2743 << VD << RangeInitType;
2744 QualType NonReferenceType = VariableType.getNonReferenceType();
2745 NonReferenceType.removeLocalConst();
2746 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_non_reference_type)
2747 << NonReferenceType << VD->getSourceRange();
2751 // Warns when the loop variable can be changed to a reference type to
2752 // prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
2753 // "for (const Foo &x : Range)" if this form does not make a copy.
2754 static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
2755 const VarDecl *VD) {
2756 const Expr *InitExpr = VD->getInit();
2760 QualType VariableType = VD->getType();
2762 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
2763 if (!CE->getConstructor()->isCopyConstructor())
2765 } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
2766 if (CE->getCastKind() != CK_LValueToRValue)
2772 // TODO: Determine a maximum size that a POD type can be before a diagnostic
2773 // should be emitted. Also, only ignore POD types with trivial copy
2775 if (VariableType.isPODType(SemaRef.Context))
2778 // Suggest changing from a const variable to a const reference variable
2779 // if doing so will prevent a copy.
2780 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
2781 << VD << VariableType << InitExpr->getType();
2782 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_reference_type)
2783 << SemaRef.Context.getLValueReferenceType(VariableType)
2784 << VD->getSourceRange();
2787 /// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
2788 /// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
2789 /// using "const foo x" to show that a copy is made
2790 /// 2) for (const bar &x : foos) where bar is a temporary initialized by bar.
2791 /// Suggest either "const bar x" to keep the copying or "const foo& x" to
2792 /// prevent the copy.
2793 /// 3) for (const foo x : foos) where x is constructed from a reference foo.
2794 /// Suggest "const foo &x" to prevent the copy.
2795 static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
2796 const CXXForRangeStmt *ForStmt) {
2797 if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy,
2798 ForStmt->getBeginLoc()) &&
2799 SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy,
2800 ForStmt->getBeginLoc()) &&
2801 SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
2802 ForStmt->getBeginLoc())) {
2806 const VarDecl *VD = ForStmt->getLoopVariable();
2810 QualType VariableType = VD->getType();
2812 if (VariableType->isIncompleteType())
2815 const Expr *InitExpr = VD->getInit();
2819 if (VariableType->isReferenceType()) {
2820 DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
2821 ForStmt->getRangeInit()->getType());
2822 } else if (VariableType.isConstQualified()) {
2823 DiagnoseForRangeConstVariableCopies(SemaRef, VD);
2827 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2828 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2829 /// body cannot be performed until after the type of the range variable is
2831 StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2835 if (isa<ObjCForCollectionStmt>(S))
2836 return FinishObjCForCollectionStmt(S, B);
2838 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2839 ForStmt->setBody(B);
2841 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2842 diag::warn_empty_range_based_for_body);
2844 DiagnoseForRangeVariableCopies(*this, ForStmt);
2849 StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2850 SourceLocation LabelLoc,
2851 LabelDecl *TheDecl) {
2852 setFunctionHasBranchIntoScope();
2853 TheDecl->markUsed(Context);
2854 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
2858 Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
2860 // Convert operand to void*
2861 if (!E->isTypeDependent()) {
2862 QualType ETy = E->getType();
2863 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
2864 ExprResult ExprRes = E;
2865 AssignConvertType ConvTy =
2866 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2867 if (ExprRes.isInvalid())
2870 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
2874 ExprResult ExprRes = ActOnFinishFullExpr(E);
2875 if (ExprRes.isInvalid())
2879 setFunctionHasIndirectGoto();
2881 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
2884 static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
2885 const Scope &DestScope) {
2886 if (!S.CurrentSEHFinally.empty() &&
2887 DestScope.Contains(*S.CurrentSEHFinally.back())) {
2888 S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
2893 Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
2894 Scope *S = CurScope->getContinueParent();
2896 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
2897 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
2899 CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
2901 return new (Context) ContinueStmt(ContinueLoc);
2905 Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
2906 Scope *S = CurScope->getBreakParent();
2908 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
2909 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
2911 if (S->isOpenMPLoopScope())
2912 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2914 CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
2916 return new (Context) BreakStmt(BreakLoc);
2919 /// Determine whether the given expression is a candidate for
2920 /// copy elision in either a return statement or a throw expression.
2922 /// \param ReturnType If we're determining the copy elision candidate for
2923 /// a return statement, this is the return type of the function. If we're
2924 /// determining the copy elision candidate for a throw expression, this will
2927 /// \param E The expression being returned from the function or block, or
2930 /// \param CESK Whether we allow function parameters or
2931 /// id-expressions that could be moved out of the function to be considered NRVO
2932 /// candidates. C++ prohibits these for NRVO itself, but we re-use this logic to
2933 /// determine whether we should try to move as part of a return or throw (which
2934 /// does allow function parameters).
2936 /// \returns The NRVO candidate variable, if the return statement may use the
2937 /// NRVO, or NULL if there is no such candidate.
2938 VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, Expr *E,
2939 CopyElisionSemanticsKind CESK) {
2940 // - in a return statement in a function [where] ...
2941 // ... the expression is the name of a non-volatile automatic object ...
2942 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
2943 if (!DR || DR->refersToEnclosingVariableOrCapture())
2945 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2949 if (isCopyElisionCandidate(ReturnType, VD, CESK))
2954 bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
2955 CopyElisionSemanticsKind CESK) {
2956 QualType VDType = VD->getType();
2957 // - in a return statement in a function with ...
2958 // ... a class return type ...
2959 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
2960 if (!ReturnType->isRecordType())
2962 // ... the same cv-unqualified type as the function return type ...
2963 // When considering moving this expression out, allow dissimilar types.
2964 if (!(CESK & CES_AllowDifferentTypes) && !VDType->isDependentType() &&
2965 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2969 // ...object (other than a function or catch-clause parameter)...
2970 if (VD->getKind() != Decl::Var &&
2971 !((CESK & CES_AllowParameters) && VD->getKind() == Decl::ParmVar))
2973 if (!(CESK & CES_AllowExceptionVariables) && VD->isExceptionVariable())
2977 if (!VD->hasLocalStorage()) return false;
2979 // Return false if VD is a __block variable. We don't want to implicitly move
2980 // out of a __block variable during a return because we cannot assume the
2981 // variable will no longer be used.
2982 if (VD->hasAttr<BlocksAttr>()) return false;
2984 if (CESK & CES_AllowDifferentTypes)
2987 // ...non-volatile...
2988 if (VD->getType().isVolatileQualified()) return false;
2990 // Variables with higher required alignment than their type's ABI
2991 // alignment cannot use NRVO.
2992 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
2993 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2999 /// Try to perform the initialization of a potentially-movable value,
3000 /// which is the operand to a return or throw statement.
3002 /// This routine implements C++14 [class.copy]p32, which attempts to treat
3003 /// returned lvalues as rvalues in certain cases (to prefer move construction),
3004 /// then falls back to treating them as lvalues if that failed.
3006 /// \param ConvertingConstructorsOnly If true, follow [class.copy]p32 and reject
3007 /// resolutions that find non-constructors, such as derived-to-base conversions
3008 /// or `operator T()&&` member functions. If false, do consider such
3009 /// conversion sequences.
3011 /// \param Res We will fill this in if move-initialization was possible.
3012 /// If move-initialization is not possible, such that we must fall back to
3013 /// treating the operand as an lvalue, we will leave Res in its original
3015 static void TryMoveInitialization(Sema& S,
3016 const InitializedEntity &Entity,
3017 const VarDecl *NRVOCandidate,
3018 QualType ResultType,
3020 bool ConvertingConstructorsOnly,
3022 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(),
3023 CK_NoOp, Value, VK_XValue);
3025 Expr *InitExpr = &AsRvalue;
3027 InitializationKind Kind = InitializationKind::CreateCopy(
3028 Value->getBeginLoc(), Value->getBeginLoc());
3030 InitializationSequence Seq(S, Entity, Kind, InitExpr);
3035 for (const InitializationSequence::Step &Step : Seq.steps()) {
3036 if (Step.Kind != InitializationSequence::SK_ConstructorInitialization &&
3037 Step.Kind != InitializationSequence::SK_UserConversion)
3040 FunctionDecl *FD = Step.Function.Function;
3041 if (ConvertingConstructorsOnly) {
3042 if (isa<CXXConstructorDecl>(FD)) {
3043 // C++14 [class.copy]p32:
3044 // [...] If the first overload resolution fails or was not performed,
3045 // or if the type of the first parameter of the selected constructor
3046 // is not an rvalue reference to the object's type (possibly
3047 // cv-qualified), overload resolution is performed again, considering
3048 // the object as an lvalue.
3049 const RValueReferenceType *RRefType =
3050 FD->getParamDecl(0)->getType()->getAs<RValueReferenceType>();
3053 if (!S.Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
3054 NRVOCandidate->getType()))
3060 if (isa<CXXConstructorDecl>(FD)) {
3061 // Check that overload resolution selected a constructor taking an
3062 // rvalue reference. If it selected an lvalue reference, then we
3063 // didn't need to cast this thing to an rvalue in the first place.
3064 if (!isa<RValueReferenceType>(FD->getParamDecl(0)->getType()))
3066 } else if (isa<CXXMethodDecl>(FD)) {
3067 // Check that overload resolution selected a conversion operator
3068 // taking an rvalue reference.
3069 if (cast<CXXMethodDecl>(FD)->getRefQualifier() != RQ_RValue)
3076 // Promote "AsRvalue" to the heap, since we now need this
3077 // expression node to persist.
3078 Value = ImplicitCastExpr::Create(S.Context, Value->getType(), CK_NoOp,
3079 Value, nullptr, VK_XValue);
3081 // Complete type-checking the initialization of the return type
3082 // using the constructor we found.
3083 Res = Seq.Perform(S, Entity, Kind, Value);
3087 /// Perform the initialization of a potentially-movable value, which
3088 /// is the result of return value.
3090 /// This routine implements C++14 [class.copy]p32, which attempts to treat
3091 /// returned lvalues as rvalues in certain cases (to prefer move construction),
3092 /// then falls back to treating them as lvalues if that failed.
3094 Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
3095 const VarDecl *NRVOCandidate,
3096 QualType ResultType,
3099 // C++14 [class.copy]p32:
3100 // When the criteria for elision of a copy/move operation are met, but not for
3101 // an exception-declaration, and the object to be copied is designated by an
3102 // lvalue, or when the expression in a return statement is a (possibly
3103 // parenthesized) id-expression that names an object with automatic storage
3104 // duration declared in the body or parameter-declaration-clause of the
3105 // innermost enclosing function or lambda-expression, overload resolution to
3106 // select the constructor for the copy is first performed as if the object
3107 // were designated by an rvalue.
3108 ExprResult Res = ExprError();
3111 bool AffectedByCWG1579 = false;
3113 if (!NRVOCandidate) {
3114 NRVOCandidate = getCopyElisionCandidate(ResultType, Value, CES_Default);
3115 if (NRVOCandidate &&
3116 !getDiagnostics().isIgnored(diag::warn_return_std_move_in_cxx11,
3117 Value->getExprLoc())) {
3118 const VarDecl *NRVOCandidateInCXX11 =
3119 getCopyElisionCandidate(ResultType, Value, CES_FormerDefault);
3120 AffectedByCWG1579 = (!NRVOCandidateInCXX11);
3124 if (NRVOCandidate) {
3125 TryMoveInitialization(*this, Entity, NRVOCandidate, ResultType, Value,
3129 if (!Res.isInvalid() && AffectedByCWG1579) {
3130 QualType QT = NRVOCandidate->getType();
3131 if (QT.getNonReferenceType()
3132 .getUnqualifiedType()
3133 .isTriviallyCopyableType(Context)) {
3134 // Adding 'std::move' around a trivially copyable variable is probably
3135 // pointless. Don't suggest it.
3137 // Common cases for this are returning unique_ptr<Derived> from a
3138 // function of return type unique_ptr<Base>, or returning T from a
3139 // function of return type Expected<T>. This is totally fine in a
3140 // post-CWG1579 world, but was not fine before.
3141 assert(!ResultType.isNull());
3142 SmallString<32> Str;
3143 Str += "std::move(";
3144 Str += NRVOCandidate->getDeclName().getAsString();
3146 Diag(Value->getExprLoc(), diag::warn_return_std_move_in_cxx11)
3147 << Value->getSourceRange()
3148 << NRVOCandidate->getDeclName() << ResultType << QT;
3149 Diag(Value->getExprLoc(), diag::note_add_std_move_in_cxx11)
3150 << FixItHint::CreateReplacement(Value->getSourceRange(), Str);
3152 } else if (Res.isInvalid() &&
3153 !getDiagnostics().isIgnored(diag::warn_return_std_move,
3154 Value->getExprLoc())) {
3155 const VarDecl *FakeNRVOCandidate =
3156 getCopyElisionCandidate(QualType(), Value, CES_AsIfByStdMove);
3157 if (FakeNRVOCandidate) {
3158 QualType QT = FakeNRVOCandidate->getType();
3159 if (QT->isLValueReferenceType()) {
3160 // Adding 'std::move' around an lvalue reference variable's name is
3161 // dangerous. Don't suggest it.
3162 } else if (QT.getNonReferenceType()
3163 .getUnqualifiedType()
3164 .isTriviallyCopyableType(Context)) {
3165 // Adding 'std::move' around a trivially copyable variable is probably
3166 // pointless. Don't suggest it.
3168 ExprResult FakeRes = ExprError();
3169 Expr *FakeValue = Value;
3170 TryMoveInitialization(*this, Entity, FakeNRVOCandidate, ResultType,
3171 FakeValue, false, FakeRes);
3172 if (!FakeRes.isInvalid()) {
3174 (Entity.getKind() == InitializedEntity::EK_Exception);
3175 SmallString<32> Str;
3176 Str += "std::move(";
3177 Str += FakeNRVOCandidate->getDeclName().getAsString();
3179 Diag(Value->getExprLoc(), diag::warn_return_std_move)
3180 << Value->getSourceRange()
3181 << FakeNRVOCandidate->getDeclName() << IsThrow;
3182 Diag(Value->getExprLoc(), diag::note_add_std_move)
3183 << FixItHint::CreateReplacement(Value->getSourceRange(), Str);
3190 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
3191 // above, or overload resolution failed. Either way, we need to try
3192 // (again) now with the return value expression as written.
3193 if (Res.isInvalid())
3194 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
3199 /// Determine whether the declared return type of the specified function
3200 /// contains 'auto'.
3201 static bool hasDeducedReturnType(FunctionDecl *FD) {
3202 const FunctionProtoType *FPT =
3203 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
3204 return FPT->getReturnType()->isUndeducedType();
3207 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
3208 /// for capturing scopes.
3211 Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
3212 // If this is the first return we've seen, infer the return type.
3213 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
3214 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
3215 QualType FnRetType = CurCap->ReturnType;
3216 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
3217 bool HasDeducedReturnType =
3218 CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
3220 if (ExprEvalContexts.back().Context ==
3221 ExpressionEvaluationContext::DiscardedStatement &&
3222 (HasDeducedReturnType || CurCap->HasImplicitReturnType)) {
3224 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3227 RetValExp = ER.get();
3229 return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3230 /* NRVOCandidate=*/nullptr);
3233 if (HasDeducedReturnType) {
3234 // In C++1y, the return type may involve 'auto'.
3235 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
3236 FunctionDecl *FD = CurLambda->CallOperator;
3237 if (CurCap->ReturnType.isNull())
3238 CurCap->ReturnType = FD->getReturnType();
3240 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
3241 assert(AT && "lost auto type from lambda return type");
3242 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3243 FD->setInvalidDecl();
3246 CurCap->ReturnType = FnRetType = FD->getReturnType();
3247 } else if (CurCap->HasImplicitReturnType) {
3248 // For blocks/lambdas with implicit return types, we check each return
3249 // statement individually, and deduce the common return type when the block
3250 // or lambda is completed.
3251 // FIXME: Fold this into the 'auto' codepath above.
3252 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
3253 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
3254 if (Result.isInvalid())
3256 RetValExp = Result.get();
3258 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
3259 // when deducing a return type for a lambda-expression (or by extension
3260 // for a block). These rules differ from the stated C++11 rules only in
3261 // that they remove top-level cv-qualifiers.
3262 if (!CurContext->isDependentContext())
3263 FnRetType = RetValExp->getType().getUnqualifiedType();
3265 FnRetType = CurCap->ReturnType = Context.DependentTy;
3268 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
3269 // initializer list, because it is not an expression (even
3270 // though we represent it as one). We still deduce 'void'.
3271 Diag(ReturnLoc, diag::err_lambda_return_init_list)
3272 << RetValExp->getSourceRange();
3275 FnRetType = Context.VoidTy;
3278 // Although we'll properly infer the type of the block once it's completed,
3279 // make sure we provide a return type now for better error recovery.
3280 if (CurCap->ReturnType.isNull())
3281 CurCap->ReturnType = FnRetType;
3283 assert(!FnRetType.isNull());
3285 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
3286 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
3287 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
3290 } else if (CapturedRegionScopeInfo *CurRegion =
3291 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
3292 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
3295 assert(CurLambda && "unknown kind of captured scope");
3296 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
3297 ->getNoReturnAttr()) {
3298 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
3303 // Otherwise, verify that this result type matches the previous one. We are
3304 // pickier with blocks than for normal functions because we don't have GCC
3305 // compatibility to worry about here.
3306 const VarDecl *NRVOCandidate = nullptr;
3307 if (FnRetType->isDependentType()) {
3308 // Delay processing for now. TODO: there are lots of dependent
3309 // types we can conclusively prove aren't void.
3310 } else if (FnRetType->isVoidType()) {
3311 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
3312 !(getLangOpts().CPlusPlus &&
3313 (RetValExp->isTypeDependent() ||
3314 RetValExp->getType()->isVoidType()))) {
3315 if (!getLangOpts().CPlusPlus &&
3316 RetValExp->getType()->isVoidType())
3317 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
3319 Diag(ReturnLoc, diag::err_return_block_has_expr);
3320 RetValExp = nullptr;
3323 } else if (!RetValExp) {
3324 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
3325 } else if (!RetValExp->isTypeDependent()) {
3326 // we have a non-void block with an expression, continue checking
3328 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3329 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3332 // In C++ the return statement is handled via a copy initialization.
3333 // the C version of which boils down to CheckSingleAssignmentConstraints.
3334 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
3335 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
3337 NRVOCandidate != nullptr);
3338 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
3339 FnRetType, RetValExp);
3340 if (Res.isInvalid()) {
3341 // FIXME: Cleanup temporaries here, anyway?
3344 RetValExp = Res.get();
3345 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
3347 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
3351 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3354 RetValExp = ER.get();
3357 ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
3359 // If we need to check for the named return value optimization,
3360 // or if we need to infer the return type,
3361 // save the return statement in our scope for later processing.
3362 if (CurCap->HasImplicitReturnType || NRVOCandidate)
3363 FunctionScopes.back()->Returns.push_back(Result);
3365 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3366 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3372 /// Marks all typedefs in all local classes in a type referenced.
3374 /// In a function like
3376 /// struct S { typedef int a; };
3380 /// the local type escapes and could be referenced in some TUs but not in
3381 /// others. Pretend that all local typedefs are always referenced, to not warn
3382 /// on this. This isn't necessary if f has internal linkage, or the typedef
3384 class LocalTypedefNameReferencer
3385 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
3387 LocalTypedefNameReferencer(Sema &S) : S(S) {}
3388 bool VisitRecordType(const RecordType *RT);
3392 bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
3393 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
3394 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
3395 R->isDependentType())
3397 for (auto *TmpD : R->decls())
3398 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
3399 if (T->getAccess() != AS_private || R->hasFriends())
3400 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
3405 TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
3406 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
3407 while (auto ATL = TL.getAs<AttributedTypeLoc>())
3408 TL = ATL.getModifiedLoc().IgnoreParens();
3409 return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc();
3412 /// Deduce the return type for a function from a returned expression, per
3413 /// C++1y [dcl.spec.auto]p6.
3414 bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
3415 SourceLocation ReturnLoc,
3418 // If this is the conversion function for a lambda, we choose to deduce it
3419 // type from the corresponding call operator, not from the synthesized return
3420 // statement within it. See Sema::DeduceReturnType.
3421 if (isLambdaConversionOperator(FD))
3424 TypeLoc OrigResultType = getReturnTypeLoc(FD);
3427 if (RetExpr && isa<InitListExpr>(RetExpr)) {
3428 // If the deduction is for a return statement and the initializer is
3429 // a braced-init-list, the program is ill-formed.
3430 Diag(RetExpr->getExprLoc(),
3431 getCurLambda() ? diag::err_lambda_return_init_list
3432 : diag::err_auto_fn_return_init_list)
3433 << RetExpr->getSourceRange();
3437 if (FD->isDependentContext()) {
3438 // C++1y [dcl.spec.auto]p12:
3439 // Return type deduction [...] occurs when the definition is
3440 // instantiated even if the function body contains a return
3441 // statement with a non-type-dependent operand.
3442 assert(AT->isDeduced() && "should have deduced to dependent type");
3447 // Otherwise, [...] deduce a value for U using the rules of template
3448 // argument deduction.
3449 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
3451 if (DAR == DAR_Failed && !FD->isInvalidDecl())
3452 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3453 << OrigResultType.getType() << RetExpr->getType();
3455 if (DAR != DAR_Succeeded)
3458 // If a local type is part of the returned type, mark its fields as
3460 LocalTypedefNameReferencer Referencer(*this);
3461 Referencer.TraverseType(RetExpr->getType());
3463 // In the case of a return with no operand, the initializer is considered
3466 // Deduction here can only succeed if the return type is exactly 'cv auto'
3467 // or 'decltype(auto)', so just check for that case directly.
3468 if (!OrigResultType.getType()->getAs<AutoType>()) {
3469 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3470 << OrigResultType.getType();
3473 // We always deduce U = void in this case.
3474 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
3475 if (Deduced.isNull())
3479 // If a function with a declared return type that contains a placeholder type
3480 // has multiple return statements, the return type is deduced for each return
3481 // statement. [...] if the type deduced is not the same in each deduction,
3482 // the program is ill-formed.
3483 QualType DeducedT = AT->getDeducedType();
3484 if (!DeducedT.isNull() && !FD->isInvalidDecl()) {
3485 AutoType *NewAT = Deduced->getContainedAutoType();
3486 // It is possible that NewAT->getDeducedType() is null. When that happens,
3487 // we should not crash, instead we ignore this deduction.
3488 if (NewAT->getDeducedType().isNull())
3491 CanQualType OldDeducedType = Context.getCanonicalFunctionResultType(
3493 CanQualType NewDeducedType = Context.getCanonicalFunctionResultType(
3494 NewAT->getDeducedType());
3495 if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) {
3496 const LambdaScopeInfo *LambdaSI = getCurLambda();
3497 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
3498 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
3499 << NewAT->getDeducedType() << DeducedT
3500 << true /*IsLambda*/;
3502 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3503 << (AT->isDecltypeAuto() ? 1 : 0)
3504 << NewAT->getDeducedType() << DeducedT;
3508 } else if (!FD->isInvalidDecl()) {
3509 // Update all declarations of the function to have the deduced return type.
3510 Context.adjustDeducedFunctionResultType(FD, Deduced);
3517 Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3519 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
3520 if (R.isInvalid() || ExprEvalContexts.back().Context ==
3521 ExpressionEvaluationContext::DiscardedStatement)
3525 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
3526 CurScope->addNRVOCandidate(VD);
3528 CurScope->setNoNRVO();
3531 CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3536 StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
3537 // Check for unexpanded parameter packs.
3538 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3541 if (isa<CapturingScopeInfo>(getCurFunction()))
3542 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
3545 QualType RelatedRetType;
3546 const AttrVec *Attrs = nullptr;
3547 bool isObjCMethod = false;
3549 if (const FunctionDecl *FD = getCurFunctionDecl()) {
3550 FnRetType = FD->getReturnType();
3552 Attrs = &FD->getAttrs();
3553 if (FD->isNoReturn())
3554 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
3555 << FD->getDeclName();
3556 if (FD->isMain() && RetValExp)
3557 if (isa<CXXBoolLiteralExpr>(RetValExp))
3558 Diag(ReturnLoc, diag::warn_main_returns_bool_literal)
3559 << RetValExp->getSourceRange();
3560 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
3561 FnRetType = MD->getReturnType();
3562 isObjCMethod = true;
3564 Attrs = &MD->getAttrs();
3565 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3566 // In the implementation of a method with a related return type, the
3567 // type used to type-check the validity of return statements within the
3568 // method body is a pointer to the type of the class being implemented.
3569 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3570 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
3572 } else // If we don't have a function/method context, bail.
3575 // C++1z: discarded return statements are not considered when deducing a
3577 if (ExprEvalContexts.back().Context ==
3578 ExpressionEvaluationContext::DiscardedStatement &&
3579 FnRetType->getContainedAutoType()) {
3581 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3584 RetValExp = ER.get();
3586 return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3587 /* NRVOCandidate=*/nullptr);
3590 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3592 if (getLangOpts().CPlusPlus14) {
3593 if (AutoType *AT = FnRetType->getContainedAutoType()) {
3594 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
3595 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3596 FD->setInvalidDecl();
3599 FnRetType = FD->getReturnType();
3604 bool HasDependentReturnType = FnRetType->isDependentType();
3606 ReturnStmt *Result = nullptr;
3607 if (FnRetType->isVoidType()) {
3609 if (isa<InitListExpr>(RetValExp)) {
3610 // We simply never allow init lists as the return value of void
3611 // functions. This is compatible because this was never allowed before,
3612 // so there's no legacy code to deal with.
3613 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3614 int FunctionKind = 0;
3615 if (isa<ObjCMethodDecl>(CurDecl))
3617 else if (isa<CXXConstructorDecl>(CurDecl))
3619 else if (isa<CXXDestructorDecl>(CurDecl))
3622 Diag(ReturnLoc, diag::err_return_init_list)
3623 << CurDecl->getDeclName() << FunctionKind
3624 << RetValExp->getSourceRange();
3626 // Drop the expression.
3627 RetValExp = nullptr;
3628 } else if (!RetValExp->isTypeDependent()) {
3629 // C99 6.8.6.4p1 (ext_ since GCC warns)
3630 unsigned D = diag::ext_return_has_expr;
3631 if (RetValExp->getType()->isVoidType()) {
3632 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3633 if (isa<CXXConstructorDecl>(CurDecl) ||
3634 isa<CXXDestructorDecl>(CurDecl))
3635 D = diag::err_ctor_dtor_returns_void;
3637 D = diag::ext_return_has_void_expr;
3640 ExprResult Result = RetValExp;
3641 Result = IgnoredValueConversions(Result.get());
3642 if (Result.isInvalid())
3644 RetValExp = Result.get();
3645 RetValExp = ImpCastExprToType(RetValExp,
3646 Context.VoidTy, CK_ToVoid).get();
3648 // return of void in constructor/destructor is illegal in C++.
3649 if (D == diag::err_ctor_dtor_returns_void) {
3650 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3652 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3653 << RetValExp->getSourceRange();
3655 // return (some void expression); is legal in C++.
3656 else if (D != diag::ext_return_has_void_expr ||
3657 !getLangOpts().CPlusPlus) {
3658 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3660 int FunctionKind = 0;
3661 if (isa<ObjCMethodDecl>(CurDecl))
3663 else if (isa<CXXConstructorDecl>(CurDecl))
3665 else if (isa<CXXDestructorDecl>(CurDecl))
3669 << CurDecl->getDeclName() << FunctionKind
3670 << RetValExp->getSourceRange();
3675 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3678 RetValExp = ER.get();
3682 Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3683 /* NRVOCandidate=*/nullptr);
3684 } else if (!RetValExp && !HasDependentReturnType) {
3685 FunctionDecl *FD = getCurFunctionDecl();
3688 if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3689 // C++11 [stmt.return]p2
3690 DiagID = diag::err_constexpr_return_missing_expr;
3691 FD->setInvalidDecl();
3692 } else if (getLangOpts().C99) {
3693 // C99 6.8.6.4p1 (ext_ since GCC warns)
3694 DiagID = diag::ext_return_missing_expr;
3697 DiagID = diag::warn_return_missing_expr;
3701 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
3703 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
3705 Result = ReturnStmt::Create(Context, ReturnLoc, /* RetExpr=*/nullptr,
3706 /* NRVOCandidate=*/nullptr);
3708 assert(RetValExp || HasDependentReturnType);
3709 const VarDecl *NRVOCandidate = nullptr;
3711 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3713 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3714 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3717 // In C++ the return statement is handled via a copy initialization,
3718 // the C version of which boils down to CheckSingleAssignmentConstraints.
3720 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, CES_Strict);
3721 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
3722 // we have a non-void function with an expression, continue checking
3723 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
3725 NRVOCandidate != nullptr);
3726 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
3727 RetType, RetValExp);
3728 if (Res.isInvalid()) {
3729 // FIXME: Clean up temporaries here anyway?
3732 RetValExp = Res.getAs<Expr>();
3734 // If we have a related result type, we need to implicitly
3735 // convert back to the formal result type. We can't pretend to
3736 // initialize the result again --- we might end double-retaining
3737 // --- so instead we initialize a notional temporary.
3738 if (!RelatedRetType.isNull()) {
3739 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3741 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3742 if (Res.isInvalid()) {
3743 // FIXME: Clean up temporaries here anyway?
3746 RetValExp = Res.getAs<Expr>();
3749 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3750 getCurFunctionDecl());
3754 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3757 RetValExp = ER.get();
3759 Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
3762 // If we need to check for the named return value optimization, save the
3763 // return statement in our scope for later processing.
3764 if (Result->getNRVOCandidate())
3765 FunctionScopes.back()->Returns.push_back(Result);
3767 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3768 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3774 Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
3775 SourceLocation RParen, Decl *Parm,
3777 VarDecl *Var = cast_or_null<VarDecl>(Parm);
3778 if (Var && Var->isInvalidDecl())
3781 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
3785 Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
3786 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
3790 Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3791 MultiStmtArg CatchStmts, Stmt *Finally) {
3792 if (!getLangOpts().ObjCExceptions)
3793 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3795 setFunctionHasBranchProtectedScope();
3796 unsigned NumCatchStmts = CatchStmts.size();
3797 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3798 NumCatchStmts, Finally);
3801 StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
3803 ExprResult Result = DefaultLvalueConversion(Throw);
3804 if (Result.isInvalid())
3807 Result = ActOnFinishFullExpr(Result.get());
3808 if (Result.isInvalid())
3810 Throw = Result.get();
3812 QualType ThrowType = Throw->getType();
3813 // Make sure the expression type is an ObjC pointer or "void *".
3814 if (!ThrowType->isDependentType() &&
3815 !ThrowType->isObjCObjectPointerType()) {
3816 const PointerType *PT = ThrowType->getAs<PointerType>();
3817 if (!PT || !PT->getPointeeType()->isVoidType())
3818 return StmtError(Diag(AtLoc, diag::err_objc_throw_expects_object)
3819 << Throw->getType() << Throw->getSourceRange());
3823 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
3827 Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3829 if (!getLangOpts().ObjCExceptions)
3830 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3833 // @throw without an expression designates a rethrow (which must occur
3834 // in the context of an @catch clause).
3835 Scope *AtCatchParent = CurScope;
3836 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3837 AtCatchParent = AtCatchParent->getParent();
3839 return StmtError(Diag(AtLoc, diag::err_rethrow_used_outside_catch));
3841 return BuildObjCAtThrowStmt(AtLoc, Throw);
3845 Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3846 ExprResult result = DefaultLvalueConversion(operand);
3847 if (result.isInvalid())
3849 operand = result.get();
3851 // Make sure the expression type is an ObjC pointer or "void *".
3852 QualType type = operand->getType();
3853 if (!type->isDependentType() &&
3854 !type->isObjCObjectPointerType()) {
3855 const PointerType *pointerType = type->getAs<PointerType>();
3856 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3857 if (getLangOpts().CPlusPlus) {
3858 if (RequireCompleteType(atLoc, type,
3859 diag::err_incomplete_receiver_type))
3860 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
3861 << type << operand->getSourceRange();
3863 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
3864 if (result.isInvalid())
3866 if (!result.isUsable())
3867 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
3868 << type << operand->getSourceRange();
3870 operand = result.get();
3872 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
3873 << type << operand->getSourceRange();
3878 // The operand to @synchronized is a full-expression.
3879 return ActOnFinishFullExpr(operand);
3883 Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3885 // We can't jump into or indirect-jump out of a @synchronized block.
3886 setFunctionHasBranchProtectedScope();
3887 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
3890 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3891 /// and creates a proper catch handler from them.
3893 Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
3894 Stmt *HandlerBlock) {
3895 // There's nothing to test that ActOnExceptionDecl didn't already test.
3896 return new (Context)
3897 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
3901 Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3902 setFunctionHasBranchProtectedScope();
3903 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
3907 class CatchHandlerType {
3909 unsigned IsPointer : 1;
3911 // This is a special constructor to be used only with DenseMapInfo's
3912 // getEmptyKey() and getTombstoneKey() functions.
3913 friend struct llvm::DenseMapInfo<CatchHandlerType>;
3914 enum Unique { ForDenseMap };
3915 CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
3918 /// Used when creating a CatchHandlerType from a handler type; will determine
3919 /// whether the type is a pointer or reference and will strip off the top
3920 /// level pointer and cv-qualifiers.
3921 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
3922 if (QT->isPointerType())
3925 if (IsPointer || QT->isReferenceType())
3926 QT = QT->getPointeeType();
3927 QT = QT.getUnqualifiedType();
3930 /// Used when creating a CatchHandlerType from a base class type; pretends the
3931 /// type passed in had the pointer qualifier, does not need to get an
3932 /// unqualified type.
3933 CatchHandlerType(QualType QT, bool IsPointer)
3934 : QT(QT), IsPointer(IsPointer) {}
3936 QualType underlying() const { return QT; }
3937 bool isPointer() const { return IsPointer; }
3939 friend bool operator==(const CatchHandlerType &LHS,
3940 const CatchHandlerType &RHS) {
3941 // If the pointer qualification does not match, we can return early.
3942 if (LHS.IsPointer != RHS.IsPointer)
3944 // Otherwise, check the underlying type without cv-qualifiers.
3945 return LHS.QT == RHS.QT;
3951 template <> struct DenseMapInfo<CatchHandlerType> {
3952 static CatchHandlerType getEmptyKey() {
3953 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
3954 CatchHandlerType::ForDenseMap);
3957 static CatchHandlerType getTombstoneKey() {
3958 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
3959 CatchHandlerType::ForDenseMap);
3962 static unsigned getHashValue(const CatchHandlerType &Base) {
3963 return DenseMapInfo<QualType>::getHashValue(Base.underlying());
3966 static bool isEqual(const CatchHandlerType &LHS,
3967 const CatchHandlerType &RHS) {
3974 class CatchTypePublicBases {
3976 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
3977 const bool CheckAgainstPointer;
3979 CXXCatchStmt *FoundHandler;
3980 CanQualType FoundHandlerType;
3983 CatchTypePublicBases(
3985 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
3986 : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
3987 FoundHandler(nullptr) {}
3989 CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
3990 CanQualType getFoundHandlerType() const { return FoundHandlerType; }
3992 bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
3993 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
3994 CatchHandlerType Check(S->getType(), CheckAgainstPointer);
3995 const auto &M = TypesToCheck;
3996 auto I = M.find(Check);
3998 FoundHandler = I->second;
3999 FoundHandlerType = Ctx.getCanonicalType(S->getType());
4008 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
4009 /// handlers and creates a try statement from them.
4010 StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
4011 ArrayRef<Stmt *> Handlers) {
4012 // Don't report an error if 'try' is used in system headers.
4013 if (!getLangOpts().CXXExceptions &&
4014 !getSourceManager().isInSystemHeader(TryLoc) &&
4015 (!getLangOpts().OpenMPIsDevice ||
4016 !getLangOpts().OpenMPHostCXXExceptions ||
4017 isInOpenMPTargetExecutionDirective() ||
4018 isInOpenMPDeclareTargetContext()))
4019 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
4021 // Exceptions aren't allowed in CUDA device code.
4022 if (getLangOpts().CUDA)
4023 CUDADiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions)
4024 << "try" << CurrentCUDATarget();
4026 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
4027 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
4029 sema::FunctionScopeInfo *FSI = getCurFunction();
4031 // C++ try is incompatible with SEH __try.
4032 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
4033 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
4034 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
4037 const unsigned NumHandlers = Handlers.size();
4038 assert(!Handlers.empty() &&
4039 "The parser shouldn't call this if there are no handlers.");
4041 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
4042 for (unsigned i = 0; i < NumHandlers; ++i) {
4043 CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
4045 // Diagnose when the handler is a catch-all handler, but it isn't the last
4046 // handler for the try block. [except.handle]p5. Also, skip exception
4047 // declarations that are invalid, since we can't usefully report on them.
4048 if (!H->getExceptionDecl()) {
4049 if (i < NumHandlers - 1)
4050 return StmtError(Diag(H->getBeginLoc(), diag::err_early_catch_all));
4052 } else if (H->getExceptionDecl()->isInvalidDecl())
4055 // Walk the type hierarchy to diagnose when this type has already been
4056 // handled (duplication), or cannot be handled (derivation inversion). We
4057 // ignore top-level cv-qualifiers, per [except.handle]p3
4058 CatchHandlerType HandlerCHT =
4059 (QualType)Context.getCanonicalType(H->getCaughtType());
4061 // We can ignore whether the type is a reference or a pointer; we need the
4062 // underlying declaration type in order to get at the underlying record
4063 // decl, if there is one.
4064 QualType Underlying = HandlerCHT.underlying();
4065 if (auto *RD = Underlying->getAsCXXRecordDecl()) {
4066 if (!RD->hasDefinition())
4068 // Check that none of the public, unambiguous base classes are in the
4069 // map ([except.handle]p1). Give the base classes the same pointer
4070 // qualification as the original type we are basing off of. This allows
4071 // comparison against the handler type using the same top-level pointer
4072 // as the original type.
4074 Paths.setOrigin(RD);
4075 CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
4076 if (RD->lookupInBases(CTPB, Paths)) {
4077 const CXXCatchStmt *Problem = CTPB.getFoundHandler();
4078 if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
4079 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
4080 diag::warn_exception_caught_by_earlier_handler)
4081 << H->getCaughtType();
4082 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
4083 diag::note_previous_exception_handler)
4084 << Problem->getCaughtType();
4089 // Add the type the list of ones we have handled; diagnose if we've already
4091 auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
4093 const CXXCatchStmt *Problem = R.first->second;
4094 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
4095 diag::warn_exception_caught_by_earlier_handler)
4096 << H->getCaughtType();
4097 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
4098 diag::note_previous_exception_handler)
4099 << Problem->getCaughtType();
4103 FSI->setHasCXXTry(TryLoc);
4105 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
4108 StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
4109 Stmt *TryBlock, Stmt *Handler) {
4110 assert(TryBlock && Handler);
4112 sema::FunctionScopeInfo *FSI = getCurFunction();
4114 // SEH __try is incompatible with C++ try. Borland appears to support this,
4116 if (!getLangOpts().Borland) {
4117 if (FSI->FirstCXXTryLoc.isValid()) {
4118 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
4119 Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
4123 FSI->setHasSEHTry(TryLoc);
4125 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
4126 // track if they use SEH.
4127 DeclContext *DC = CurContext;
4128 while (DC && !DC->isFunctionOrMethod())
4129 DC = DC->getParent();
4130 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
4132 FD->setUsesSEHTry(true);
4134 Diag(TryLoc, diag::err_seh_try_outside_functions);
4136 // Reject __try on unsupported targets.
4137 if (!Context.getTargetInfo().isSEHTrySupported())
4138 Diag(TryLoc, diag::err_seh_try_unsupported);
4140 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
4144 Sema::ActOnSEHExceptBlock(SourceLocation Loc,
4147 assert(FilterExpr && Block);
4149 if(!FilterExpr->getType()->isIntegerType()) {
4150 return StmtError(Diag(FilterExpr->getExprLoc(),
4151 diag::err_filter_expression_integral)
4152 << FilterExpr->getType());
4155 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
4158 void Sema::ActOnStartSEHFinallyBlock() {
4159 CurrentSEHFinally.push_back(CurScope);
4162 void Sema::ActOnAbortSEHFinallyBlock() {
4163 CurrentSEHFinally.pop_back();
4166 StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
4168 CurrentSEHFinally.pop_back();
4169 return SEHFinallyStmt::Create(Context, Loc, Block);
4173 Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
4174 Scope *SEHTryParent = CurScope;
4175 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
4176 SEHTryParent = SEHTryParent->getParent();
4178 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
4179 CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
4181 return new (Context) SEHLeaveStmt(Loc);
4184 StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4186 NestedNameSpecifierLoc QualifierLoc,
4187 DeclarationNameInfo NameInfo,
4190 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
4191 QualifierLoc, NameInfo,
4192 cast<CompoundStmt>(Nested));
4196 StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4199 UnqualifiedId &Name,
4201 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
4202 SS.getWithLocInContext(Context),
4203 GetNameFromUnqualifiedId(Name),
4208 Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
4209 unsigned NumParams) {
4210 DeclContext *DC = CurContext;
4211 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
4212 DC = DC->getParent();
4214 RecordDecl *RD = nullptr;
4215 if (getLangOpts().CPlusPlus)
4216 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
4219 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
4221 RD->setCapturedRecord();
4224 RD->startDefinition();
4226 assert(NumParams > 0 && "CapturedStmt requires context parameter");
4227 CD = CapturedDecl::Create(Context, CurContext, NumParams);
4233 buildCapturedStmtCaptureList(SmallVectorImpl<CapturedStmt::Capture> &Captures,
4234 SmallVectorImpl<Expr *> &CaptureInits,
4235 ArrayRef<sema::Capture> Candidates) {
4236 for (const sema::Capture &Cap : Candidates) {
4237 if (Cap.isThisCapture()) {
4238 Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
4239 CapturedStmt::VCK_This));
4240 CaptureInits.push_back(Cap.getInitExpr());
4242 } else if (Cap.isVLATypeCapture()) {
4244 CapturedStmt::Capture(Cap.getLocation(), CapturedStmt::VCK_VLAType));
4245 CaptureInits.push_back(nullptr);
4249 Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
4250 Cap.isReferenceCapture()
4251 ? CapturedStmt::VCK_ByRef
4252 : CapturedStmt::VCK_ByCopy,
4253 Cap.getVariable()));
4254 CaptureInits.push_back(Cap.getInitExpr());
4258 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4259 CapturedRegionKind Kind,
4260 unsigned NumParams) {
4261 CapturedDecl *CD = nullptr;
4262 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
4264 // Build the context parameter
4265 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4266 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4267 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
4269 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4270 ImplicitParamDecl::CapturedContext);
4273 CD->setContextParam(0, Param);
4275 // Enter the capturing scope for this captured region.
4276 PushCapturedRegionScope(CurScope, CD, RD, Kind);
4279 PushDeclContext(CurScope, CD);
4283 PushExpressionEvaluationContext(
4284 ExpressionEvaluationContext::PotentiallyEvaluated);
4287 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4288 CapturedRegionKind Kind,
4289 ArrayRef<CapturedParamNameType> Params) {
4290 CapturedDecl *CD = nullptr;
4291 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
4293 // Build the context parameter
4294 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4295 bool ContextIsFound = false;
4296 unsigned ParamNum = 0;
4297 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
4299 I != E; ++I, ++ParamNum) {
4300 if (I->second.isNull()) {
4301 assert(!ContextIsFound &&
4302 "null type has been found already for '__context' parameter");
4303 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4304 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD))
4308 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4309 ImplicitParamDecl::CapturedContext);
4311 CD->setContextParam(ParamNum, Param);
4312 ContextIsFound = true;
4314 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
4316 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second,
4317 ImplicitParamDecl::CapturedContext);
4319 CD->setParam(ParamNum, Param);
4322 assert(ContextIsFound && "no null type for '__context' parameter");
4323 if (!ContextIsFound) {
4324 // Add __context implicitly if it is not specified.
4325 IdentifierInfo *ParamName = &Context.Idents.get("__context");
4326 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
4328 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4329 ImplicitParamDecl::CapturedContext);
4331 CD->setContextParam(ParamNum, Param);
4333 // Enter the capturing scope for this captured region.
4334 PushCapturedRegionScope(CurScope, CD, RD, Kind);
4337 PushDeclContext(CurScope, CD);
4341 PushExpressionEvaluationContext(
4342 ExpressionEvaluationContext::PotentiallyEvaluated);
4345 void Sema::ActOnCapturedRegionError() {
4346 DiscardCleanupsInEvaluationContext();
4347 PopExpressionEvaluationContext();
4349 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
4350 RecordDecl *Record = RSI->TheRecordDecl;
4351 Record->setInvalidDecl();
4353 SmallVector<Decl*, 4> Fields(Record->fields());
4354 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
4355 SourceLocation(), SourceLocation(), ParsedAttributesView());
4358 PopFunctionScopeInfo();
4361 StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
4362 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
4364 SmallVector<CapturedStmt::Capture, 4> Captures;
4365 SmallVector<Expr *, 4> CaptureInits;
4366 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
4368 CapturedDecl *CD = RSI->TheCapturedDecl;
4369 RecordDecl *RD = RSI->TheRecordDecl;
4371 CapturedStmt *Res = CapturedStmt::Create(
4372 getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind),
4373 Captures, CaptureInits, CD, RD);
4375 CD->setBody(Res->getCapturedStmt());
4376 RD->completeDefinition();
4378 DiscardCleanupsInEvaluationContext();
4379 PopExpressionEvaluationContext();
4382 PopFunctionScopeInfo();