xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaStmt.cpp (revision 297eecfb02bb25902531dbb5c3b9a88caf8adf29)
10b57cec5SDimitry Andric //===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric //  This file implements semantic analysis for statements.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "clang/AST/ASTContext.h"
140b57cec5SDimitry Andric #include "clang/AST/ASTDiagnostic.h"
150b57cec5SDimitry Andric #include "clang/AST/ASTLambda.h"
160b57cec5SDimitry Andric #include "clang/AST/CXXInheritance.h"
17fe6060f1SDimitry Andric #include "clang/AST/CharUnits.h"
180b57cec5SDimitry Andric #include "clang/AST/DeclObjC.h"
190b57cec5SDimitry Andric #include "clang/AST/EvaluatedExprVisitor.h"
200b57cec5SDimitry Andric #include "clang/AST/ExprCXX.h"
210b57cec5SDimitry Andric #include "clang/AST/ExprObjC.h"
22fe6060f1SDimitry Andric #include "clang/AST/IgnoreExpr.h"
230b57cec5SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h"
240b57cec5SDimitry Andric #include "clang/AST/StmtCXX.h"
250b57cec5SDimitry Andric #include "clang/AST/StmtObjC.h"
260b57cec5SDimitry Andric #include "clang/AST/TypeLoc.h"
270b57cec5SDimitry Andric #include "clang/AST/TypeOrdering.h"
280b57cec5SDimitry Andric #include "clang/Basic/TargetInfo.h"
290b57cec5SDimitry Andric #include "clang/Lex/Preprocessor.h"
300b57cec5SDimitry Andric #include "clang/Sema/Initialization.h"
310b57cec5SDimitry Andric #include "clang/Sema/Lookup.h"
32fe6060f1SDimitry Andric #include "clang/Sema/Ownership.h"
330b57cec5SDimitry Andric #include "clang/Sema/Scope.h"
340b57cec5SDimitry Andric #include "clang/Sema/ScopeInfo.h"
35fe6060f1SDimitry Andric #include "clang/Sema/SemaInternal.h"
360b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
370b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
380b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
390b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
400b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
410b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
4206c3fb27SDimitry Andric #include "llvm/ADT/StringExtras.h"
430b57cec5SDimitry Andric 
440b57cec5SDimitry Andric using namespace clang;
450b57cec5SDimitry Andric using namespace sema;
460b57cec5SDimitry Andric 
470b57cec5SDimitry Andric StmtResult Sema::ActOnExprStmt(ExprResult FE, bool DiscardedValue) {
480b57cec5SDimitry Andric   if (FE.isInvalid())
490b57cec5SDimitry Andric     return StmtError();
500b57cec5SDimitry Andric 
510b57cec5SDimitry Andric   FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(), DiscardedValue);
520b57cec5SDimitry Andric   if (FE.isInvalid())
530b57cec5SDimitry Andric     return StmtError();
540b57cec5SDimitry Andric 
550b57cec5SDimitry Andric   // C99 6.8.3p2: The expression in an expression statement is evaluated as a
560b57cec5SDimitry Andric   // void expression for its side effects.  Conversion to void allows any
570b57cec5SDimitry Andric   // operand, even incomplete types.
580b57cec5SDimitry Andric 
590b57cec5SDimitry Andric   // Same thing in for stmt first clause (when expr) and third clause.
600b57cec5SDimitry Andric   return StmtResult(FE.getAs<Stmt>());
610b57cec5SDimitry Andric }
620b57cec5SDimitry Andric 
630b57cec5SDimitry Andric 
640b57cec5SDimitry Andric StmtResult Sema::ActOnExprStmtError() {
650b57cec5SDimitry Andric   DiscardCleanupsInEvaluationContext();
660b57cec5SDimitry Andric   return StmtError();
670b57cec5SDimitry Andric }
680b57cec5SDimitry Andric 
690b57cec5SDimitry Andric StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
700b57cec5SDimitry Andric                                bool HasLeadingEmptyMacro) {
710b57cec5SDimitry Andric   return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
720b57cec5SDimitry Andric }
730b57cec5SDimitry Andric 
740b57cec5SDimitry Andric StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
750b57cec5SDimitry Andric                                SourceLocation EndLoc) {
760b57cec5SDimitry Andric   DeclGroupRef DG = dg.get();
770b57cec5SDimitry Andric 
780b57cec5SDimitry Andric   // If we have an invalid decl, just return an error.
790b57cec5SDimitry Andric   if (DG.isNull()) return StmtError();
800b57cec5SDimitry Andric 
810b57cec5SDimitry Andric   return new (Context) DeclStmt(DG, StartLoc, EndLoc);
820b57cec5SDimitry Andric }
830b57cec5SDimitry Andric 
840b57cec5SDimitry Andric void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
850b57cec5SDimitry Andric   DeclGroupRef DG = dg.get();
860b57cec5SDimitry Andric 
870b57cec5SDimitry Andric   // If we don't have a declaration, or we have an invalid declaration,
880b57cec5SDimitry Andric   // just return.
890b57cec5SDimitry Andric   if (DG.isNull() || !DG.isSingleDecl())
900b57cec5SDimitry Andric     return;
910b57cec5SDimitry Andric 
920b57cec5SDimitry Andric   Decl *decl = DG.getSingleDecl();
930b57cec5SDimitry Andric   if (!decl || decl->isInvalidDecl())
940b57cec5SDimitry Andric     return;
950b57cec5SDimitry Andric 
960b57cec5SDimitry Andric   // Only variable declarations are permitted.
970b57cec5SDimitry Andric   VarDecl *var = dyn_cast<VarDecl>(decl);
980b57cec5SDimitry Andric   if (!var) {
990b57cec5SDimitry Andric     Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
1000b57cec5SDimitry Andric     decl->setInvalidDecl();
1010b57cec5SDimitry Andric     return;
1020b57cec5SDimitry Andric   }
1030b57cec5SDimitry Andric 
1040b57cec5SDimitry Andric   // foreach variables are never actually initialized in the way that
1050b57cec5SDimitry Andric   // the parser came up with.
1060b57cec5SDimitry Andric   var->setInit(nullptr);
1070b57cec5SDimitry Andric 
1080b57cec5SDimitry Andric   // In ARC, we don't need to retain the iteration variable of a fast
1090b57cec5SDimitry Andric   // enumeration loop.  Rather than actually trying to catch that
1100b57cec5SDimitry Andric   // during declaration processing, we remove the consequences here.
1110b57cec5SDimitry Andric   if (getLangOpts().ObjCAutoRefCount) {
1120b57cec5SDimitry Andric     QualType type = var->getType();
1130b57cec5SDimitry Andric 
1140b57cec5SDimitry Andric     // Only do this if we inferred the lifetime.  Inferred lifetime
1150b57cec5SDimitry Andric     // will show up as a local qualifier because explicit lifetime
1160b57cec5SDimitry Andric     // should have shown up as an AttributedType instead.
1170b57cec5SDimitry Andric     if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
1180b57cec5SDimitry Andric       // Add 'const' and mark the variable as pseudo-strong.
1190b57cec5SDimitry Andric       var->setType(type.withConst());
1200b57cec5SDimitry Andric       var->setARCPseudoStrong(true);
1210b57cec5SDimitry Andric     }
1220b57cec5SDimitry Andric   }
1230b57cec5SDimitry Andric }
1240b57cec5SDimitry Andric 
1250b57cec5SDimitry Andric /// Diagnose unused comparisons, both builtin and overloaded operators.
1260b57cec5SDimitry Andric /// For '==' and '!=', suggest fixits for '=' or '|='.
1270b57cec5SDimitry Andric ///
1280b57cec5SDimitry Andric /// Adding a cast to void (or other expression wrappers) will prevent the
1290b57cec5SDimitry Andric /// warning from firing.
1300b57cec5SDimitry Andric static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
1310b57cec5SDimitry Andric   SourceLocation Loc;
1320b57cec5SDimitry Andric   bool CanAssign;
1330b57cec5SDimitry Andric   enum { Equality, Inequality, Relational, ThreeWay } Kind;
1340b57cec5SDimitry Andric 
1350b57cec5SDimitry Andric   if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
1360b57cec5SDimitry Andric     if (!Op->isComparisonOp())
1370b57cec5SDimitry Andric       return false;
1380b57cec5SDimitry Andric 
1390b57cec5SDimitry Andric     if (Op->getOpcode() == BO_EQ)
1400b57cec5SDimitry Andric       Kind = Equality;
1410b57cec5SDimitry Andric     else if (Op->getOpcode() == BO_NE)
1420b57cec5SDimitry Andric       Kind = Inequality;
1430b57cec5SDimitry Andric     else if (Op->getOpcode() == BO_Cmp)
1440b57cec5SDimitry Andric       Kind = ThreeWay;
1450b57cec5SDimitry Andric     else {
1460b57cec5SDimitry Andric       assert(Op->isRelationalOp());
1470b57cec5SDimitry Andric       Kind = Relational;
1480b57cec5SDimitry Andric     }
1490b57cec5SDimitry Andric     Loc = Op->getOperatorLoc();
1500b57cec5SDimitry Andric     CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
1510b57cec5SDimitry Andric   } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
1520b57cec5SDimitry Andric     switch (Op->getOperator()) {
1530b57cec5SDimitry Andric     case OO_EqualEqual:
1540b57cec5SDimitry Andric       Kind = Equality;
1550b57cec5SDimitry Andric       break;
1560b57cec5SDimitry Andric     case OO_ExclaimEqual:
1570b57cec5SDimitry Andric       Kind = Inequality;
1580b57cec5SDimitry Andric       break;
1590b57cec5SDimitry Andric     case OO_Less:
1600b57cec5SDimitry Andric     case OO_Greater:
1610b57cec5SDimitry Andric     case OO_GreaterEqual:
1620b57cec5SDimitry Andric     case OO_LessEqual:
1630b57cec5SDimitry Andric       Kind = Relational;
1640b57cec5SDimitry Andric       break;
1650b57cec5SDimitry Andric     case OO_Spaceship:
1660b57cec5SDimitry Andric       Kind = ThreeWay;
1670b57cec5SDimitry Andric       break;
1680b57cec5SDimitry Andric     default:
1690b57cec5SDimitry Andric       return false;
1700b57cec5SDimitry Andric     }
1710b57cec5SDimitry Andric 
1720b57cec5SDimitry Andric     Loc = Op->getOperatorLoc();
1730b57cec5SDimitry Andric     CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
1740b57cec5SDimitry Andric   } else {
1750b57cec5SDimitry Andric     // Not a typo-prone comparison.
1760b57cec5SDimitry Andric     return false;
1770b57cec5SDimitry Andric   }
1780b57cec5SDimitry Andric 
1790b57cec5SDimitry Andric   // Suppress warnings when the operator, suspicious as it may be, comes from
1800b57cec5SDimitry Andric   // a macro expansion.
1810b57cec5SDimitry Andric   if (S.SourceMgr.isMacroBodyExpansion(Loc))
1820b57cec5SDimitry Andric     return false;
1830b57cec5SDimitry Andric 
1840b57cec5SDimitry Andric   S.Diag(Loc, diag::warn_unused_comparison)
1850b57cec5SDimitry Andric     << (unsigned)Kind << E->getSourceRange();
1860b57cec5SDimitry Andric 
1870b57cec5SDimitry Andric   // If the LHS is a plausible entity to assign to, provide a fixit hint to
1880b57cec5SDimitry Andric   // correct common typos.
1890b57cec5SDimitry Andric   if (CanAssign) {
1900b57cec5SDimitry Andric     if (Kind == Inequality)
1910b57cec5SDimitry Andric       S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
1920b57cec5SDimitry Andric         << FixItHint::CreateReplacement(Loc, "|=");
1930b57cec5SDimitry Andric     else if (Kind == Equality)
1940b57cec5SDimitry Andric       S.Diag(Loc, diag::note_equality_comparison_to_assign)
1950b57cec5SDimitry Andric         << FixItHint::CreateReplacement(Loc, "=");
1960b57cec5SDimitry Andric   }
1970b57cec5SDimitry Andric 
1980b57cec5SDimitry Andric   return true;
1990b57cec5SDimitry Andric }
2000b57cec5SDimitry Andric 
201a7dea167SDimitry Andric static bool DiagnoseNoDiscard(Sema &S, const WarnUnusedResultAttr *A,
202a7dea167SDimitry Andric                               SourceLocation Loc, SourceRange R1,
203a7dea167SDimitry Andric                               SourceRange R2, bool IsCtor) {
204a7dea167SDimitry Andric   if (!A)
205a7dea167SDimitry Andric     return false;
206a7dea167SDimitry Andric   StringRef Msg = A->getMessage();
207a7dea167SDimitry Andric 
208a7dea167SDimitry Andric   if (Msg.empty()) {
209a7dea167SDimitry Andric     if (IsCtor)
210a7dea167SDimitry Andric       return S.Diag(Loc, diag::warn_unused_constructor) << A << R1 << R2;
211a7dea167SDimitry Andric     return S.Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
212a7dea167SDimitry Andric   }
213a7dea167SDimitry Andric 
214a7dea167SDimitry Andric   if (IsCtor)
215a7dea167SDimitry Andric     return S.Diag(Loc, diag::warn_unused_constructor_msg) << A << Msg << R1
216a7dea167SDimitry Andric                                                           << R2;
217a7dea167SDimitry Andric   return S.Diag(Loc, diag::warn_unused_result_msg) << A << Msg << R1 << R2;
218a7dea167SDimitry Andric }
219a7dea167SDimitry Andric 
220349cc55cSDimitry Andric void Sema::DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID) {
2210b57cec5SDimitry Andric   if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
222349cc55cSDimitry Andric     return DiagnoseUnusedExprResult(Label->getSubStmt(), DiagID);
2230b57cec5SDimitry Andric 
2240b57cec5SDimitry Andric   const Expr *E = dyn_cast_or_null<Expr>(S);
2250b57cec5SDimitry Andric   if (!E)
2260b57cec5SDimitry Andric     return;
2270b57cec5SDimitry Andric 
2280b57cec5SDimitry Andric   // If we are in an unevaluated expression context, then there can be no unused
2290b57cec5SDimitry Andric   // results because the results aren't expected to be used in the first place.
2300b57cec5SDimitry Andric   if (isUnevaluatedContext())
2310b57cec5SDimitry Andric     return;
2320b57cec5SDimitry Andric 
2330b57cec5SDimitry Andric   SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc();
2340b57cec5SDimitry Andric   // In most cases, we don't want to warn if the expression is written in a
2350b57cec5SDimitry Andric   // macro body, or if the macro comes from a system header. If the offending
2360b57cec5SDimitry Andric   // expression is a call to a function with the warn_unused_result attribute,
2370b57cec5SDimitry Andric   // we warn no matter the location. Because of the order in which the various
2380b57cec5SDimitry Andric   // checks need to happen, we factor out the macro-related test here.
2390b57cec5SDimitry Andric   bool ShouldSuppress =
2400b57cec5SDimitry Andric       SourceMgr.isMacroBodyExpansion(ExprLoc) ||
2410b57cec5SDimitry Andric       SourceMgr.isInSystemMacro(ExprLoc);
2420b57cec5SDimitry Andric 
2430b57cec5SDimitry Andric   const Expr *WarnExpr;
2440b57cec5SDimitry Andric   SourceLocation Loc;
2450b57cec5SDimitry Andric   SourceRange R1, R2;
2460b57cec5SDimitry Andric   if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
2470b57cec5SDimitry Andric     return;
2480b57cec5SDimitry Andric 
2490b57cec5SDimitry Andric   // If this is a GNU statement expression expanded from a macro, it is probably
2500b57cec5SDimitry Andric   // unused because it is a function-like macro that can be used as either an
2510b57cec5SDimitry Andric   // expression or statement.  Don't warn, because it is almost certainly a
2520b57cec5SDimitry Andric   // false positive.
2530b57cec5SDimitry Andric   if (isa<StmtExpr>(E) && Loc.isMacroID())
2540b57cec5SDimitry Andric     return;
2550b57cec5SDimitry Andric 
2560b57cec5SDimitry Andric   // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers.
2570b57cec5SDimitry Andric   // That macro is frequently used to suppress "unused parameter" warnings,
2580b57cec5SDimitry Andric   // but its implementation makes clang's -Wunused-value fire.  Prevent this.
2590b57cec5SDimitry Andric   if (isa<ParenExpr>(E->IgnoreImpCasts()) && Loc.isMacroID()) {
2600b57cec5SDimitry Andric     SourceLocation SpellLoc = Loc;
2610b57cec5SDimitry Andric     if (findMacroSpelling(SpellLoc, "UNREFERENCED_PARAMETER"))
2620b57cec5SDimitry Andric       return;
2630b57cec5SDimitry Andric   }
2640b57cec5SDimitry Andric 
2650b57cec5SDimitry Andric   // Okay, we have an unused result.  Depending on what the base expression is,
2660b57cec5SDimitry Andric   // we might want to make a more specific diagnostic.  Check for one of these
2670b57cec5SDimitry Andric   // cases now.
2680b57cec5SDimitry Andric   if (const FullExpr *Temps = dyn_cast<FullExpr>(E))
2690b57cec5SDimitry Andric     E = Temps->getSubExpr();
2700b57cec5SDimitry Andric   if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
2710b57cec5SDimitry Andric     E = TempExpr->getSubExpr();
2720b57cec5SDimitry Andric 
2730b57cec5SDimitry Andric   if (DiagnoseUnusedComparison(*this, E))
2740b57cec5SDimitry Andric     return;
2750b57cec5SDimitry Andric 
2760b57cec5SDimitry Andric   E = WarnExpr;
277a7dea167SDimitry Andric   if (const auto *Cast = dyn_cast<CastExpr>(E))
278a7dea167SDimitry Andric     if (Cast->getCastKind() == CK_NoOp ||
279a7dea167SDimitry Andric         Cast->getCastKind() == CK_ConstructorConversion)
280a7dea167SDimitry Andric       E = Cast->getSubExpr()->IgnoreImpCasts();
281a7dea167SDimitry Andric 
2820b57cec5SDimitry Andric   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
2830b57cec5SDimitry Andric     if (E->getType()->isVoidType())
2840b57cec5SDimitry Andric       return;
2850b57cec5SDimitry Andric 
286a7dea167SDimitry Andric     if (DiagnoseNoDiscard(*this, cast_or_null<WarnUnusedResultAttr>(
287a7dea167SDimitry Andric                                      CE->getUnusedResultAttr(Context)),
288a7dea167SDimitry Andric                           Loc, R1, R2, /*isCtor=*/false))
2890b57cec5SDimitry Andric       return;
2900b57cec5SDimitry Andric 
2910b57cec5SDimitry Andric     // If the callee has attribute pure, const, or warn_unused_result, warn with
2920b57cec5SDimitry Andric     // a more specific message to make it clear what is happening. If the call
2930b57cec5SDimitry Andric     // is written in a macro body, only warn if it has the warn_unused_result
2940b57cec5SDimitry Andric     // attribute.
2950b57cec5SDimitry Andric     if (const Decl *FD = CE->getCalleeDecl()) {
2960b57cec5SDimitry Andric       if (ShouldSuppress)
2970b57cec5SDimitry Andric         return;
2980b57cec5SDimitry Andric       if (FD->hasAttr<PureAttr>()) {
2990b57cec5SDimitry Andric         Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
3000b57cec5SDimitry Andric         return;
3010b57cec5SDimitry Andric       }
3020b57cec5SDimitry Andric       if (FD->hasAttr<ConstAttr>()) {
3030b57cec5SDimitry Andric         Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
3040b57cec5SDimitry Andric         return;
3050b57cec5SDimitry Andric       }
3060b57cec5SDimitry Andric     }
307a7dea167SDimitry Andric   } else if (const auto *CE = dyn_cast<CXXConstructExpr>(E)) {
308a7dea167SDimitry Andric     if (const CXXConstructorDecl *Ctor = CE->getConstructor()) {
309a7dea167SDimitry Andric       const auto *A = Ctor->getAttr<WarnUnusedResultAttr>();
310a7dea167SDimitry Andric       A = A ? A : Ctor->getParent()->getAttr<WarnUnusedResultAttr>();
311a7dea167SDimitry Andric       if (DiagnoseNoDiscard(*this, A, Loc, R1, R2, /*isCtor=*/true))
312a7dea167SDimitry Andric         return;
313a7dea167SDimitry Andric     }
314a7dea167SDimitry Andric   } else if (const auto *ILE = dyn_cast<InitListExpr>(E)) {
315a7dea167SDimitry Andric     if (const TagDecl *TD = ILE->getType()->getAsTagDecl()) {
316a7dea167SDimitry Andric 
317a7dea167SDimitry Andric       if (DiagnoseNoDiscard(*this, TD->getAttr<WarnUnusedResultAttr>(), Loc, R1,
318a7dea167SDimitry Andric                             R2, /*isCtor=*/false))
319a7dea167SDimitry Andric         return;
320a7dea167SDimitry Andric     }
3210b57cec5SDimitry Andric   } else if (ShouldSuppress)
3220b57cec5SDimitry Andric     return;
3230b57cec5SDimitry Andric 
324a7dea167SDimitry Andric   E = WarnExpr;
3250b57cec5SDimitry Andric   if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
3260b57cec5SDimitry Andric     if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
3270b57cec5SDimitry Andric       Diag(Loc, diag::err_arc_unused_init_message) << R1;
3280b57cec5SDimitry Andric       return;
3290b57cec5SDimitry Andric     }
3300b57cec5SDimitry Andric     const ObjCMethodDecl *MD = ME->getMethodDecl();
3310b57cec5SDimitry Andric     if (MD) {
332a7dea167SDimitry Andric       if (DiagnoseNoDiscard(*this, MD->getAttr<WarnUnusedResultAttr>(), Loc, R1,
333a7dea167SDimitry Andric                             R2, /*isCtor=*/false))
3340b57cec5SDimitry Andric         return;
3350b57cec5SDimitry Andric     }
3360b57cec5SDimitry Andric   } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
3370b57cec5SDimitry Andric     const Expr *Source = POE->getSyntacticForm();
3385ffd83dbSDimitry Andric     // Handle the actually selected call of an OpenMP specialized call.
3395ffd83dbSDimitry Andric     if (LangOpts.OpenMP && isa<CallExpr>(Source) &&
3405ffd83dbSDimitry Andric         POE->getNumSemanticExprs() == 1 &&
3415ffd83dbSDimitry Andric         isa<CallExpr>(POE->getSemanticExpr(0)))
342349cc55cSDimitry Andric       return DiagnoseUnusedExprResult(POE->getSemanticExpr(0), DiagID);
3430b57cec5SDimitry Andric     if (isa<ObjCSubscriptRefExpr>(Source))
3440b57cec5SDimitry Andric       DiagID = diag::warn_unused_container_subscript_expr;
34581ad6265SDimitry Andric     else if (isa<ObjCPropertyRefExpr>(Source))
3460b57cec5SDimitry Andric       DiagID = diag::warn_unused_property_expr;
3470b57cec5SDimitry Andric   } else if (const CXXFunctionalCastExpr *FC
3480b57cec5SDimitry Andric                                        = dyn_cast<CXXFunctionalCastExpr>(E)) {
3490b57cec5SDimitry Andric     const Expr *E = FC->getSubExpr();
3500b57cec5SDimitry Andric     if (const CXXBindTemporaryExpr *TE = dyn_cast<CXXBindTemporaryExpr>(E))
3510b57cec5SDimitry Andric       E = TE->getSubExpr();
3520b57cec5SDimitry Andric     if (isa<CXXTemporaryObjectExpr>(E))
3530b57cec5SDimitry Andric       return;
3540b57cec5SDimitry Andric     if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
3550b57cec5SDimitry Andric       if (const CXXRecordDecl *RD = CE->getType()->getAsCXXRecordDecl())
3560b57cec5SDimitry Andric         if (!RD->getAttr<WarnUnusedAttr>())
3570b57cec5SDimitry Andric           return;
3580b57cec5SDimitry Andric   }
3590b57cec5SDimitry Andric   // Diagnose "(void*) blah" as a typo for "(void) blah".
3600b57cec5SDimitry Andric   else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
3610b57cec5SDimitry Andric     TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
3620b57cec5SDimitry Andric     QualType T = TI->getType();
3630b57cec5SDimitry Andric 
3640b57cec5SDimitry Andric     // We really do want to use the non-canonical type here.
3650b57cec5SDimitry Andric     if (T == Context.VoidPtrTy) {
3660b57cec5SDimitry Andric       PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
3670b57cec5SDimitry Andric 
3680b57cec5SDimitry Andric       Diag(Loc, diag::warn_unused_voidptr)
3690b57cec5SDimitry Andric         << FixItHint::CreateRemoval(TL.getStarLoc());
3700b57cec5SDimitry Andric       return;
3710b57cec5SDimitry Andric     }
3720b57cec5SDimitry Andric   }
3730b57cec5SDimitry Andric 
3745ffd83dbSDimitry Andric   // Tell the user to assign it into a variable to force a volatile load if this
3755ffd83dbSDimitry Andric   // isn't an array.
3765ffd83dbSDimitry Andric   if (E->isGLValue() && E->getType().isVolatileQualified() &&
3775ffd83dbSDimitry Andric       !E->getType()->isArrayType()) {
3780b57cec5SDimitry Andric     Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
3790b57cec5SDimitry Andric     return;
3800b57cec5SDimitry Andric   }
3810b57cec5SDimitry Andric 
382349cc55cSDimitry Andric   // Do not diagnose use of a comma operator in a SFINAE context because the
383349cc55cSDimitry Andric   // type of the left operand could be used for SFINAE, so technically it is
384349cc55cSDimitry Andric   // *used*.
385349cc55cSDimitry Andric   if (DiagID != diag::warn_unused_comma_left_operand || !isSFINAEContext())
386bdd1243dSDimitry Andric     DiagIfReachable(Loc, S ? llvm::ArrayRef(S) : std::nullopt,
387349cc55cSDimitry Andric                     PDiag(DiagID) << R1 << R2);
3880b57cec5SDimitry Andric }
3890b57cec5SDimitry Andric 
3900b57cec5SDimitry Andric void Sema::ActOnStartOfCompoundStmt(bool IsStmtExpr) {
3910b57cec5SDimitry Andric   PushCompoundScope(IsStmtExpr);
3920b57cec5SDimitry Andric }
3930b57cec5SDimitry Andric 
394e8d8bef9SDimitry Andric void Sema::ActOnAfterCompoundStatementLeadingPragmas() {
395e8d8bef9SDimitry Andric   if (getCurFPFeatures().isFPConstrained()) {
396e8d8bef9SDimitry Andric     FunctionScopeInfo *FSI = getCurFunction();
397e8d8bef9SDimitry Andric     assert(FSI);
398e8d8bef9SDimitry Andric     FSI->setUsesFPIntrin();
399e8d8bef9SDimitry Andric   }
400e8d8bef9SDimitry Andric }
401e8d8bef9SDimitry Andric 
4020b57cec5SDimitry Andric void Sema::ActOnFinishOfCompoundStmt() {
4030b57cec5SDimitry Andric   PopCompoundScope();
4040b57cec5SDimitry Andric }
4050b57cec5SDimitry Andric 
4060b57cec5SDimitry Andric sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
4070b57cec5SDimitry Andric   return getCurFunction()->CompoundScopes.back();
4080b57cec5SDimitry Andric }
4090b57cec5SDimitry Andric 
4100b57cec5SDimitry Andric StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
4110b57cec5SDimitry Andric                                    ArrayRef<Stmt *> Elts, bool isStmtExpr) {
4120b57cec5SDimitry Andric   const unsigned NumElts = Elts.size();
4130b57cec5SDimitry Andric 
41404eeddc0SDimitry Andric   // If we're in C mode, check that we don't have any decls after stmts.  If
41504eeddc0SDimitry Andric   // so, emit an extension diagnostic in C89 and potentially a warning in later
41604eeddc0SDimitry Andric   // versions.
41704eeddc0SDimitry Andric   const unsigned MixedDeclsCodeID = getLangOpts().C99
41804eeddc0SDimitry Andric                                         ? diag::warn_mixed_decls_code
41904eeddc0SDimitry Andric                                         : diag::ext_mixed_decls_code;
42004eeddc0SDimitry Andric   if (!getLangOpts().CPlusPlus && !Diags.isIgnored(MixedDeclsCodeID, L)) {
4210b57cec5SDimitry Andric     // Note that __extension__ can be around a decl.
4220b57cec5SDimitry Andric     unsigned i = 0;
4230b57cec5SDimitry Andric     // Skip over all declarations.
4240b57cec5SDimitry Andric     for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
4250b57cec5SDimitry Andric       /*empty*/;
4260b57cec5SDimitry Andric 
4270b57cec5SDimitry Andric     // We found the end of the list or a statement.  Scan for another declstmt.
4280b57cec5SDimitry Andric     for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
4290b57cec5SDimitry Andric       /*empty*/;
4300b57cec5SDimitry Andric 
4310b57cec5SDimitry Andric     if (i != NumElts) {
4320b57cec5SDimitry Andric       Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
43304eeddc0SDimitry Andric       Diag(D->getLocation(), MixedDeclsCodeID);
4340b57cec5SDimitry Andric     }
4350b57cec5SDimitry Andric   }
4360b57cec5SDimitry Andric 
4370b57cec5SDimitry Andric   // Check for suspicious empty body (null statement) in `for' and `while'
4380b57cec5SDimitry Andric   // statements.  Don't do anything for template instantiations, this just adds
4390b57cec5SDimitry Andric   // noise.
4400b57cec5SDimitry Andric   if (NumElts != 0 && !CurrentInstantiationScope &&
4410b57cec5SDimitry Andric       getCurCompoundScope().HasEmptyLoopBodies) {
4420b57cec5SDimitry Andric     for (unsigned i = 0; i != NumElts - 1; ++i)
4430b57cec5SDimitry Andric       DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
4440b57cec5SDimitry Andric   }
4450b57cec5SDimitry Andric 
44681ad6265SDimitry Andric   // Calculate difference between FP options in this compound statement and in
44781ad6265SDimitry Andric   // the enclosing one. If this is a function body, take the difference against
44881ad6265SDimitry Andric   // default options. In this case the difference will indicate options that are
44981ad6265SDimitry Andric   // changed upon entry to the statement.
45081ad6265SDimitry Andric   FPOptions FPO = (getCurFunction()->CompoundScopes.size() == 1)
45181ad6265SDimitry Andric                       ? FPOptions(getLangOpts())
45281ad6265SDimitry Andric                       : getCurCompoundScope().InitialFPFeatures;
45381ad6265SDimitry Andric   FPOptionsOverride FPDiff = getCurFPFeatures().getChangesFrom(FPO);
45481ad6265SDimitry Andric 
45581ad6265SDimitry Andric   return CompoundStmt::Create(Context, Elts, FPDiff, L, R);
4560b57cec5SDimitry Andric }
4570b57cec5SDimitry Andric 
4580b57cec5SDimitry Andric ExprResult
4590b57cec5SDimitry Andric Sema::ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val) {
4600b57cec5SDimitry Andric   if (!Val.get())
4610b57cec5SDimitry Andric     return Val;
4620b57cec5SDimitry Andric 
4630b57cec5SDimitry Andric   if (DiagnoseUnexpandedParameterPack(Val.get()))
4640b57cec5SDimitry Andric     return ExprError();
4650b57cec5SDimitry Andric 
4660b57cec5SDimitry Andric   // If we're not inside a switch, let the 'case' statement handling diagnose
4670b57cec5SDimitry Andric   // this. Just clean up after the expression as best we can.
468a7dea167SDimitry Andric   if (getCurFunction()->SwitchStack.empty())
469a7dea167SDimitry Andric     return ActOnFinishFullExpr(Val.get(), Val.get()->getExprLoc(), false,
470a7dea167SDimitry Andric                                getLangOpts().CPlusPlus11);
471a7dea167SDimitry Andric 
4720b57cec5SDimitry Andric   Expr *CondExpr =
4730b57cec5SDimitry Andric       getCurFunction()->SwitchStack.back().getPointer()->getCond();
4740b57cec5SDimitry Andric   if (!CondExpr)
4750b57cec5SDimitry Andric     return ExprError();
4760b57cec5SDimitry Andric   QualType CondType = CondExpr->getType();
4770b57cec5SDimitry Andric 
4780b57cec5SDimitry Andric   auto CheckAndFinish = [&](Expr *E) {
4790b57cec5SDimitry Andric     if (CondType->isDependentType() || E->isTypeDependent())
4800b57cec5SDimitry Andric       return ExprResult(E);
4810b57cec5SDimitry Andric 
4820b57cec5SDimitry Andric     if (getLangOpts().CPlusPlus11) {
4830b57cec5SDimitry Andric       // C++11 [stmt.switch]p2: the constant-expression shall be a converted
4840b57cec5SDimitry Andric       // constant expression of the promoted type of the switch condition.
4850b57cec5SDimitry Andric       llvm::APSInt TempVal;
4860b57cec5SDimitry Andric       return CheckConvertedConstantExpression(E, CondType, TempVal,
4870b57cec5SDimitry Andric                                               CCEK_CaseValue);
4880b57cec5SDimitry Andric     }
4890b57cec5SDimitry Andric 
4900b57cec5SDimitry Andric     ExprResult ER = E;
4910b57cec5SDimitry Andric     if (!E->isValueDependent())
492e8d8bef9SDimitry Andric       ER = VerifyIntegerConstantExpression(E, AllowFold);
4930b57cec5SDimitry Andric     if (!ER.isInvalid())
4940b57cec5SDimitry Andric       ER = DefaultLvalueConversion(ER.get());
4950b57cec5SDimitry Andric     if (!ER.isInvalid())
4960b57cec5SDimitry Andric       ER = ImpCastExprToType(ER.get(), CondType, CK_IntegralCast);
497a7dea167SDimitry Andric     if (!ER.isInvalid())
498a7dea167SDimitry Andric       ER = ActOnFinishFullExpr(ER.get(), ER.get()->getExprLoc(), false);
4990b57cec5SDimitry Andric     return ER;
5000b57cec5SDimitry Andric   };
5010b57cec5SDimitry Andric 
5025ffd83dbSDimitry Andric   ExprResult Converted = CorrectDelayedTyposInExpr(
5035ffd83dbSDimitry Andric       Val, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
5045ffd83dbSDimitry Andric       CheckAndFinish);
5050b57cec5SDimitry Andric   if (Converted.get() == Val.get())
5060b57cec5SDimitry Andric     Converted = CheckAndFinish(Val.get());
507a7dea167SDimitry Andric   return Converted;
5080b57cec5SDimitry Andric }
5090b57cec5SDimitry Andric 
5100b57cec5SDimitry Andric StmtResult
5110b57cec5SDimitry Andric Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHSVal,
5120b57cec5SDimitry Andric                     SourceLocation DotDotDotLoc, ExprResult RHSVal,
5130b57cec5SDimitry Andric                     SourceLocation ColonLoc) {
5140b57cec5SDimitry Andric   assert((LHSVal.isInvalid() || LHSVal.get()) && "missing LHS value");
5150b57cec5SDimitry Andric   assert((DotDotDotLoc.isInvalid() ? RHSVal.isUnset()
5160b57cec5SDimitry Andric                                    : RHSVal.isInvalid() || RHSVal.get()) &&
5170b57cec5SDimitry Andric          "missing RHS value");
5180b57cec5SDimitry Andric 
5190b57cec5SDimitry Andric   if (getCurFunction()->SwitchStack.empty()) {
5200b57cec5SDimitry Andric     Diag(CaseLoc, diag::err_case_not_in_switch);
5210b57cec5SDimitry Andric     return StmtError();
5220b57cec5SDimitry Andric   }
5230b57cec5SDimitry Andric 
5240b57cec5SDimitry Andric   if (LHSVal.isInvalid() || RHSVal.isInvalid()) {
5250b57cec5SDimitry Andric     getCurFunction()->SwitchStack.back().setInt(true);
5260b57cec5SDimitry Andric     return StmtError();
5270b57cec5SDimitry Andric   }
5280b57cec5SDimitry Andric 
5290b57cec5SDimitry Andric   auto *CS = CaseStmt::Create(Context, LHSVal.get(), RHSVal.get(),
5300b57cec5SDimitry Andric                               CaseLoc, DotDotDotLoc, ColonLoc);
5310b57cec5SDimitry Andric   getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(CS);
5320b57cec5SDimitry Andric   return CS;
5330b57cec5SDimitry Andric }
5340b57cec5SDimitry Andric 
5350b57cec5SDimitry Andric /// ActOnCaseStmtBody - This installs a statement as the body of a case.
5360b57cec5SDimitry Andric void Sema::ActOnCaseStmtBody(Stmt *S, Stmt *SubStmt) {
5370b57cec5SDimitry Andric   cast<CaseStmt>(S)->setSubStmt(SubStmt);
5380b57cec5SDimitry Andric }
5390b57cec5SDimitry Andric 
5400b57cec5SDimitry Andric StmtResult
5410b57cec5SDimitry Andric Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
5420b57cec5SDimitry Andric                        Stmt *SubStmt, Scope *CurScope) {
5430b57cec5SDimitry Andric   if (getCurFunction()->SwitchStack.empty()) {
5440b57cec5SDimitry Andric     Diag(DefaultLoc, diag::err_default_not_in_switch);
5450b57cec5SDimitry Andric     return SubStmt;
5460b57cec5SDimitry Andric   }
5470b57cec5SDimitry Andric 
5480b57cec5SDimitry Andric   DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
5490b57cec5SDimitry Andric   getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(DS);
5500b57cec5SDimitry Andric   return DS;
5510b57cec5SDimitry Andric }
5520b57cec5SDimitry Andric 
5530b57cec5SDimitry Andric StmtResult
5540b57cec5SDimitry Andric Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
5550b57cec5SDimitry Andric                      SourceLocation ColonLoc, Stmt *SubStmt) {
5560b57cec5SDimitry Andric   // If the label was multiply defined, reject it now.
5570b57cec5SDimitry Andric   if (TheDecl->getStmt()) {
5580b57cec5SDimitry Andric     Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
5590b57cec5SDimitry Andric     Diag(TheDecl->getLocation(), diag::note_previous_definition);
5600b57cec5SDimitry Andric     return SubStmt;
5610b57cec5SDimitry Andric   }
5620b57cec5SDimitry Andric 
563fe6060f1SDimitry Andric   ReservedIdentifierStatus Status = TheDecl->isReserved(getLangOpts());
564349cc55cSDimitry Andric   if (isReservedInAllContexts(Status) &&
565fe6060f1SDimitry Andric       !Context.getSourceManager().isInSystemHeader(IdentLoc))
566fe6060f1SDimitry Andric     Diag(IdentLoc, diag::warn_reserved_extern_symbol)
567fe6060f1SDimitry Andric         << TheDecl << static_cast<int>(Status);
568fe6060f1SDimitry Andric 
5690b57cec5SDimitry Andric   // Otherwise, things are good.  Fill in the declaration and return it.
5700b57cec5SDimitry Andric   LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
5710b57cec5SDimitry Andric   TheDecl->setStmt(LS);
5720b57cec5SDimitry Andric   if (!TheDecl->isGnuLocal()) {
5730b57cec5SDimitry Andric     TheDecl->setLocStart(IdentLoc);
5740b57cec5SDimitry Andric     if (!TheDecl->isMSAsmLabel()) {
5750b57cec5SDimitry Andric       // Don't update the location of MS ASM labels.  These will result in
5760b57cec5SDimitry Andric       // a diagnostic, and changing the location here will mess that up.
5770b57cec5SDimitry Andric       TheDecl->setLocation(IdentLoc);
5780b57cec5SDimitry Andric     }
5790b57cec5SDimitry Andric   }
5800b57cec5SDimitry Andric   return LS;
5810b57cec5SDimitry Andric }
5820b57cec5SDimitry Andric 
583fe6060f1SDimitry Andric StmtResult Sema::BuildAttributedStmt(SourceLocation AttrsLoc,
5840b57cec5SDimitry Andric                                      ArrayRef<const Attr *> Attrs,
5850b57cec5SDimitry Andric                                      Stmt *SubStmt) {
586fe6060f1SDimitry Andric   // FIXME: this code should move when a planned refactoring around statement
587fe6060f1SDimitry Andric   // attributes lands.
588fe6060f1SDimitry Andric   for (const auto *A : Attrs) {
589fe6060f1SDimitry Andric     if (A->getKind() == attr::MustTail) {
590fe6060f1SDimitry Andric       if (!checkAndRewriteMustTailAttr(SubStmt, *A)) {
591fe6060f1SDimitry Andric         return SubStmt;
592fe6060f1SDimitry Andric       }
593fe6060f1SDimitry Andric       setFunctionHasMustTail();
594fe6060f1SDimitry Andric     }
595fe6060f1SDimitry Andric   }
596fe6060f1SDimitry Andric 
597fe6060f1SDimitry Andric   return AttributedStmt::Create(Context, AttrsLoc, Attrs, SubStmt);
598fe6060f1SDimitry Andric }
599fe6060f1SDimitry Andric 
60081ad6265SDimitry Andric StmtResult Sema::ActOnAttributedStmt(const ParsedAttributes &Attrs,
601fe6060f1SDimitry Andric                                      Stmt *SubStmt) {
602fe6060f1SDimitry Andric   SmallVector<const Attr *, 1> SemanticAttrs;
603fe6060f1SDimitry Andric   ProcessStmtAttributes(SubStmt, Attrs, SemanticAttrs);
604fe6060f1SDimitry Andric   if (!SemanticAttrs.empty())
605fe6060f1SDimitry Andric     return BuildAttributedStmt(Attrs.Range.getBegin(), SemanticAttrs, SubStmt);
606fe6060f1SDimitry Andric   // If none of the attributes applied, that's fine, we can recover by
607fe6060f1SDimitry Andric   // returning the substatement directly instead of making an AttributedStmt
608fe6060f1SDimitry Andric   // with no attributes on it.
609fe6060f1SDimitry Andric   return SubStmt;
610fe6060f1SDimitry Andric }
611fe6060f1SDimitry Andric 
612fe6060f1SDimitry Andric bool Sema::checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA) {
613fe6060f1SDimitry Andric   ReturnStmt *R = cast<ReturnStmt>(St);
614fe6060f1SDimitry Andric   Expr *E = R->getRetValue();
615fe6060f1SDimitry Andric 
616fe6060f1SDimitry Andric   if (CurContext->isDependentContext() || (E && E->isInstantiationDependent()))
617fe6060f1SDimitry Andric     // We have to suspend our check until template instantiation time.
618fe6060f1SDimitry Andric     return true;
619fe6060f1SDimitry Andric 
620fe6060f1SDimitry Andric   if (!checkMustTailAttr(St, MTA))
621fe6060f1SDimitry Andric     return false;
622fe6060f1SDimitry Andric 
623fe6060f1SDimitry Andric   // FIXME: Replace Expr::IgnoreImplicitAsWritten() with this function.
624fe6060f1SDimitry Andric   // Currently it does not skip implicit constructors in an initialization
625fe6060f1SDimitry Andric   // context.
626fe6060f1SDimitry Andric   auto IgnoreImplicitAsWritten = [](Expr *E) -> Expr * {
627fe6060f1SDimitry Andric     return IgnoreExprNodes(E, IgnoreImplicitAsWrittenSingleStep,
628fe6060f1SDimitry Andric                            IgnoreElidableImplicitConstructorSingleStep);
629fe6060f1SDimitry Andric   };
630fe6060f1SDimitry Andric 
631fe6060f1SDimitry Andric   // Now that we have verified that 'musttail' is valid here, rewrite the
632fe6060f1SDimitry Andric   // return value to remove all implicit nodes, but retain parentheses.
633fe6060f1SDimitry Andric   R->setRetValue(IgnoreImplicitAsWritten(E));
634fe6060f1SDimitry Andric   return true;
635fe6060f1SDimitry Andric }
636fe6060f1SDimitry Andric 
637fe6060f1SDimitry Andric bool Sema::checkMustTailAttr(const Stmt *St, const Attr &MTA) {
638fe6060f1SDimitry Andric   assert(!CurContext->isDependentContext() &&
639fe6060f1SDimitry Andric          "musttail cannot be checked from a dependent context");
640fe6060f1SDimitry Andric 
641fe6060f1SDimitry Andric   // FIXME: Add Expr::IgnoreParenImplicitAsWritten() with this definition.
642fe6060f1SDimitry Andric   auto IgnoreParenImplicitAsWritten = [](const Expr *E) -> const Expr * {
643fe6060f1SDimitry Andric     return IgnoreExprNodes(const_cast<Expr *>(E), IgnoreParensSingleStep,
644fe6060f1SDimitry Andric                            IgnoreImplicitAsWrittenSingleStep,
645fe6060f1SDimitry Andric                            IgnoreElidableImplicitConstructorSingleStep);
646fe6060f1SDimitry Andric   };
647fe6060f1SDimitry Andric 
648fe6060f1SDimitry Andric   const Expr *E = cast<ReturnStmt>(St)->getRetValue();
649fe6060f1SDimitry Andric   const auto *CE = dyn_cast_or_null<CallExpr>(IgnoreParenImplicitAsWritten(E));
650fe6060f1SDimitry Andric 
651fe6060f1SDimitry Andric   if (!CE) {
652fe6060f1SDimitry Andric     Diag(St->getBeginLoc(), diag::err_musttail_needs_call) << &MTA;
653fe6060f1SDimitry Andric     return false;
654fe6060f1SDimitry Andric   }
655fe6060f1SDimitry Andric 
656fe6060f1SDimitry Andric   if (const auto *EWC = dyn_cast<ExprWithCleanups>(E)) {
657fe6060f1SDimitry Andric     if (EWC->cleanupsHaveSideEffects()) {
658fe6060f1SDimitry Andric       Diag(St->getBeginLoc(), diag::err_musttail_needs_trivial_args) << &MTA;
659fe6060f1SDimitry Andric       return false;
660fe6060f1SDimitry Andric     }
661fe6060f1SDimitry Andric   }
662fe6060f1SDimitry Andric 
663fe6060f1SDimitry Andric   // We need to determine the full function type (including "this" type, if any)
664fe6060f1SDimitry Andric   // for both caller and callee.
665fe6060f1SDimitry Andric   struct FuncType {
666fe6060f1SDimitry Andric     enum {
667fe6060f1SDimitry Andric       ft_non_member,
668fe6060f1SDimitry Andric       ft_static_member,
669fe6060f1SDimitry Andric       ft_non_static_member,
670fe6060f1SDimitry Andric       ft_pointer_to_member,
671fe6060f1SDimitry Andric     } MemberType = ft_non_member;
672fe6060f1SDimitry Andric 
673fe6060f1SDimitry Andric     QualType This;
674fe6060f1SDimitry Andric     const FunctionProtoType *Func;
675fe6060f1SDimitry Andric     const CXXMethodDecl *Method = nullptr;
676fe6060f1SDimitry Andric   } CallerType, CalleeType;
677fe6060f1SDimitry Andric 
678fe6060f1SDimitry Andric   auto GetMethodType = [this, St, MTA](const CXXMethodDecl *CMD, FuncType &Type,
679fe6060f1SDimitry Andric                                        bool IsCallee) -> bool {
680fe6060f1SDimitry Andric     if (isa<CXXConstructorDecl, CXXDestructorDecl>(CMD)) {
681fe6060f1SDimitry Andric       Diag(St->getBeginLoc(), diag::err_musttail_structors_forbidden)
682fe6060f1SDimitry Andric           << IsCallee << isa<CXXDestructorDecl>(CMD);
683fe6060f1SDimitry Andric       if (IsCallee)
684fe6060f1SDimitry Andric         Diag(CMD->getBeginLoc(), diag::note_musttail_structors_forbidden)
685fe6060f1SDimitry Andric             << isa<CXXDestructorDecl>(CMD);
686fe6060f1SDimitry Andric       Diag(MTA.getLocation(), diag::note_tail_call_required) << &MTA;
687fe6060f1SDimitry Andric       return false;
688fe6060f1SDimitry Andric     }
689fe6060f1SDimitry Andric     if (CMD->isStatic())
690fe6060f1SDimitry Andric       Type.MemberType = FuncType::ft_static_member;
691fe6060f1SDimitry Andric     else {
6925f757f3fSDimitry Andric       Type.This = CMD->getFunctionObjectParameterType();
693fe6060f1SDimitry Andric       Type.MemberType = FuncType::ft_non_static_member;
694fe6060f1SDimitry Andric     }
695fe6060f1SDimitry Andric     Type.Func = CMD->getType()->castAs<FunctionProtoType>();
696fe6060f1SDimitry Andric     return true;
697fe6060f1SDimitry Andric   };
698fe6060f1SDimitry Andric 
699fe6060f1SDimitry Andric   const auto *CallerDecl = dyn_cast<FunctionDecl>(CurContext);
700fe6060f1SDimitry Andric 
701fe6060f1SDimitry Andric   // Find caller function signature.
702fe6060f1SDimitry Andric   if (!CallerDecl) {
703fe6060f1SDimitry Andric     int ContextType;
704fe6060f1SDimitry Andric     if (isa<BlockDecl>(CurContext))
705fe6060f1SDimitry Andric       ContextType = 0;
706fe6060f1SDimitry Andric     else if (isa<ObjCMethodDecl>(CurContext))
707fe6060f1SDimitry Andric       ContextType = 1;
708fe6060f1SDimitry Andric     else
709fe6060f1SDimitry Andric       ContextType = 2;
710fe6060f1SDimitry Andric     Diag(St->getBeginLoc(), diag::err_musttail_forbidden_from_this_context)
711fe6060f1SDimitry Andric         << &MTA << ContextType;
712fe6060f1SDimitry Andric     return false;
713fe6060f1SDimitry Andric   } else if (const auto *CMD = dyn_cast<CXXMethodDecl>(CurContext)) {
714fe6060f1SDimitry Andric     // Caller is a class/struct method.
715fe6060f1SDimitry Andric     if (!GetMethodType(CMD, CallerType, false))
716fe6060f1SDimitry Andric       return false;
717fe6060f1SDimitry Andric   } else {
718fe6060f1SDimitry Andric     // Caller is a non-method function.
719fe6060f1SDimitry Andric     CallerType.Func = CallerDecl->getType()->getAs<FunctionProtoType>();
720fe6060f1SDimitry Andric   }
721fe6060f1SDimitry Andric 
722fe6060f1SDimitry Andric   const Expr *CalleeExpr = CE->getCallee()->IgnoreParens();
723fe6060f1SDimitry Andric   const auto *CalleeBinOp = dyn_cast<BinaryOperator>(CalleeExpr);
724fe6060f1SDimitry Andric   SourceLocation CalleeLoc = CE->getCalleeDecl()
725fe6060f1SDimitry Andric                                  ? CE->getCalleeDecl()->getBeginLoc()
726fe6060f1SDimitry Andric                                  : St->getBeginLoc();
727fe6060f1SDimitry Andric 
728fe6060f1SDimitry Andric   // Find callee function signature.
729fe6060f1SDimitry Andric   if (const CXXMethodDecl *CMD =
730fe6060f1SDimitry Andric           dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl())) {
731fe6060f1SDimitry Andric     // Call is: obj.method(), obj->method(), functor(), etc.
732fe6060f1SDimitry Andric     if (!GetMethodType(CMD, CalleeType, true))
733fe6060f1SDimitry Andric       return false;
734fe6060f1SDimitry Andric   } else if (CalleeBinOp && CalleeBinOp->isPtrMemOp()) {
735fe6060f1SDimitry Andric     // Call is: obj->*method_ptr or obj.*method_ptr
736fe6060f1SDimitry Andric     const auto *MPT =
737fe6060f1SDimitry Andric         CalleeBinOp->getRHS()->getType()->castAs<MemberPointerType>();
738fe6060f1SDimitry Andric     CalleeType.This = QualType(MPT->getClass(), 0);
739fe6060f1SDimitry Andric     CalleeType.Func = MPT->getPointeeType()->castAs<FunctionProtoType>();
740fe6060f1SDimitry Andric     CalleeType.MemberType = FuncType::ft_pointer_to_member;
741fe6060f1SDimitry Andric   } else if (isa<CXXPseudoDestructorExpr>(CalleeExpr)) {
742fe6060f1SDimitry Andric     Diag(St->getBeginLoc(), diag::err_musttail_structors_forbidden)
743fe6060f1SDimitry Andric         << /* IsCallee = */ 1 << /* IsDestructor = */ 1;
744fe6060f1SDimitry Andric     Diag(MTA.getLocation(), diag::note_tail_call_required) << &MTA;
745fe6060f1SDimitry Andric     return false;
746fe6060f1SDimitry Andric   } else {
747fe6060f1SDimitry Andric     // Non-method function.
748fe6060f1SDimitry Andric     CalleeType.Func =
749fe6060f1SDimitry Andric         CalleeExpr->getType()->getPointeeType()->getAs<FunctionProtoType>();
750fe6060f1SDimitry Andric   }
751fe6060f1SDimitry Andric 
752fe6060f1SDimitry Andric   // Both caller and callee must have a prototype (no K&R declarations).
753fe6060f1SDimitry Andric   if (!CalleeType.Func || !CallerType.Func) {
754fe6060f1SDimitry Andric     Diag(St->getBeginLoc(), diag::err_musttail_needs_prototype) << &MTA;
755fe6060f1SDimitry Andric     if (!CalleeType.Func && CE->getDirectCallee()) {
756fe6060f1SDimitry Andric       Diag(CE->getDirectCallee()->getBeginLoc(),
757fe6060f1SDimitry Andric            diag::note_musttail_fix_non_prototype);
758fe6060f1SDimitry Andric     }
759fe6060f1SDimitry Andric     if (!CallerType.Func)
760fe6060f1SDimitry Andric       Diag(CallerDecl->getBeginLoc(), diag::note_musttail_fix_non_prototype);
761fe6060f1SDimitry Andric     return false;
762fe6060f1SDimitry Andric   }
763fe6060f1SDimitry Andric 
764fe6060f1SDimitry Andric   // Caller and callee must have matching calling conventions.
765fe6060f1SDimitry Andric   //
766fe6060f1SDimitry Andric   // Some calling conventions are physically capable of supporting tail calls
767fe6060f1SDimitry Andric   // even if the function types don't perfectly match. LLVM is currently too
768fe6060f1SDimitry Andric   // strict to allow this, but if LLVM added support for this in the future, we
769fe6060f1SDimitry Andric   // could exit early here and skip the remaining checks if the functions are
770fe6060f1SDimitry Andric   // using such a calling convention.
771fe6060f1SDimitry Andric   if (CallerType.Func->getCallConv() != CalleeType.Func->getCallConv()) {
772fe6060f1SDimitry Andric     if (const auto *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl()))
773fe6060f1SDimitry Andric       Diag(St->getBeginLoc(), diag::err_musttail_callconv_mismatch)
774fe6060f1SDimitry Andric           << true << ND->getDeclName();
775fe6060f1SDimitry Andric     else
776fe6060f1SDimitry Andric       Diag(St->getBeginLoc(), diag::err_musttail_callconv_mismatch) << false;
777fe6060f1SDimitry Andric     Diag(CalleeLoc, diag::note_musttail_callconv_mismatch)
778fe6060f1SDimitry Andric         << FunctionType::getNameForCallConv(CallerType.Func->getCallConv())
779fe6060f1SDimitry Andric         << FunctionType::getNameForCallConv(CalleeType.Func->getCallConv());
780fe6060f1SDimitry Andric     Diag(MTA.getLocation(), diag::note_tail_call_required) << &MTA;
781fe6060f1SDimitry Andric     return false;
782fe6060f1SDimitry Andric   }
783fe6060f1SDimitry Andric 
784fe6060f1SDimitry Andric   if (CalleeType.Func->isVariadic() || CallerType.Func->isVariadic()) {
785fe6060f1SDimitry Andric     Diag(St->getBeginLoc(), diag::err_musttail_no_variadic) << &MTA;
786fe6060f1SDimitry Andric     return false;
787fe6060f1SDimitry Andric   }
788fe6060f1SDimitry Andric 
789fe6060f1SDimitry Andric   // Caller and callee must match in whether they have a "this" parameter.
790fe6060f1SDimitry Andric   if (CallerType.This.isNull() != CalleeType.This.isNull()) {
791fe6060f1SDimitry Andric     if (const auto *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
792fe6060f1SDimitry Andric       Diag(St->getBeginLoc(), diag::err_musttail_member_mismatch)
793fe6060f1SDimitry Andric           << CallerType.MemberType << CalleeType.MemberType << true
794fe6060f1SDimitry Andric           << ND->getDeclName();
795fe6060f1SDimitry Andric       Diag(CalleeLoc, diag::note_musttail_callee_defined_here)
796fe6060f1SDimitry Andric           << ND->getDeclName();
797fe6060f1SDimitry Andric     } else
798fe6060f1SDimitry Andric       Diag(St->getBeginLoc(), diag::err_musttail_member_mismatch)
799fe6060f1SDimitry Andric           << CallerType.MemberType << CalleeType.MemberType << false;
800fe6060f1SDimitry Andric     Diag(MTA.getLocation(), diag::note_tail_call_required) << &MTA;
801fe6060f1SDimitry Andric     return false;
802fe6060f1SDimitry Andric   }
803fe6060f1SDimitry Andric 
804fe6060f1SDimitry Andric   auto CheckTypesMatch = [this](FuncType CallerType, FuncType CalleeType,
805fe6060f1SDimitry Andric                                 PartialDiagnostic &PD) -> bool {
806fe6060f1SDimitry Andric     enum {
807fe6060f1SDimitry Andric       ft_different_class,
808fe6060f1SDimitry Andric       ft_parameter_arity,
809fe6060f1SDimitry Andric       ft_parameter_mismatch,
810fe6060f1SDimitry Andric       ft_return_type,
811fe6060f1SDimitry Andric     };
812fe6060f1SDimitry Andric 
813fe6060f1SDimitry Andric     auto DoTypesMatch = [this, &PD](QualType A, QualType B,
814fe6060f1SDimitry Andric                                     unsigned Select) -> bool {
815fe6060f1SDimitry Andric       if (!Context.hasSimilarType(A, B)) {
816fe6060f1SDimitry Andric         PD << Select << A.getUnqualifiedType() << B.getUnqualifiedType();
817fe6060f1SDimitry Andric         return false;
818fe6060f1SDimitry Andric       }
819fe6060f1SDimitry Andric       return true;
820fe6060f1SDimitry Andric     };
821fe6060f1SDimitry Andric 
822fe6060f1SDimitry Andric     if (!CallerType.This.isNull() &&
823fe6060f1SDimitry Andric         !DoTypesMatch(CallerType.This, CalleeType.This, ft_different_class))
824fe6060f1SDimitry Andric       return false;
825fe6060f1SDimitry Andric 
826fe6060f1SDimitry Andric     if (!DoTypesMatch(CallerType.Func->getReturnType(),
827fe6060f1SDimitry Andric                       CalleeType.Func->getReturnType(), ft_return_type))
828fe6060f1SDimitry Andric       return false;
829fe6060f1SDimitry Andric 
830fe6060f1SDimitry Andric     if (CallerType.Func->getNumParams() != CalleeType.Func->getNumParams()) {
831fe6060f1SDimitry Andric       PD << ft_parameter_arity << CallerType.Func->getNumParams()
832fe6060f1SDimitry Andric          << CalleeType.Func->getNumParams();
833fe6060f1SDimitry Andric       return false;
834fe6060f1SDimitry Andric     }
835fe6060f1SDimitry Andric 
836fe6060f1SDimitry Andric     ArrayRef<QualType> CalleeParams = CalleeType.Func->getParamTypes();
837fe6060f1SDimitry Andric     ArrayRef<QualType> CallerParams = CallerType.Func->getParamTypes();
838fe6060f1SDimitry Andric     size_t N = CallerType.Func->getNumParams();
839fe6060f1SDimitry Andric     for (size_t I = 0; I < N; I++) {
840fe6060f1SDimitry Andric       if (!DoTypesMatch(CalleeParams[I], CallerParams[I],
841fe6060f1SDimitry Andric                         ft_parameter_mismatch)) {
842fe6060f1SDimitry Andric         PD << static_cast<int>(I) + 1;
843fe6060f1SDimitry Andric         return false;
844fe6060f1SDimitry Andric       }
845fe6060f1SDimitry Andric     }
846fe6060f1SDimitry Andric 
847fe6060f1SDimitry Andric     return true;
848fe6060f1SDimitry Andric   };
849fe6060f1SDimitry Andric 
850fe6060f1SDimitry Andric   PartialDiagnostic PD = PDiag(diag::note_musttail_mismatch);
851fe6060f1SDimitry Andric   if (!CheckTypesMatch(CallerType, CalleeType, PD)) {
852fe6060f1SDimitry Andric     if (const auto *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl()))
853fe6060f1SDimitry Andric       Diag(St->getBeginLoc(), diag::err_musttail_mismatch)
854fe6060f1SDimitry Andric           << true << ND->getDeclName();
855fe6060f1SDimitry Andric     else
856fe6060f1SDimitry Andric       Diag(St->getBeginLoc(), diag::err_musttail_mismatch) << false;
857fe6060f1SDimitry Andric     Diag(CalleeLoc, PD);
858fe6060f1SDimitry Andric     Diag(MTA.getLocation(), diag::note_tail_call_required) << &MTA;
859fe6060f1SDimitry Andric     return false;
860fe6060f1SDimitry Andric   }
861fe6060f1SDimitry Andric 
862fe6060f1SDimitry Andric   return true;
8630b57cec5SDimitry Andric }
8640b57cec5SDimitry Andric 
8650b57cec5SDimitry Andric namespace {
8660b57cec5SDimitry Andric class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
8670b57cec5SDimitry Andric   typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
8680b57cec5SDimitry Andric   Sema &SemaRef;
8690b57cec5SDimitry Andric public:
8700b57cec5SDimitry Andric   CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
8710b57cec5SDimitry Andric   void VisitBinaryOperator(BinaryOperator *E) {
8720b57cec5SDimitry Andric     if (E->getOpcode() == BO_Comma)
8730b57cec5SDimitry Andric       SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc());
8740b57cec5SDimitry Andric     EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E);
8750b57cec5SDimitry Andric   }
8760b57cec5SDimitry Andric };
8770b57cec5SDimitry Andric }
8780b57cec5SDimitry Andric 
879349cc55cSDimitry Andric StmtResult Sema::ActOnIfStmt(SourceLocation IfLoc,
880349cc55cSDimitry Andric                              IfStatementKind StatementKind,
881e8d8bef9SDimitry Andric                              SourceLocation LParenLoc, Stmt *InitStmt,
882e8d8bef9SDimitry Andric                              ConditionResult Cond, SourceLocation RParenLoc,
8830b57cec5SDimitry Andric                              Stmt *thenStmt, SourceLocation ElseLoc,
8840b57cec5SDimitry Andric                              Stmt *elseStmt) {
8850b57cec5SDimitry Andric   if (Cond.isInvalid())
88604eeddc0SDimitry Andric     return StmtError();
8870b57cec5SDimitry Andric 
888349cc55cSDimitry Andric   bool ConstevalOrNegatedConsteval =
889349cc55cSDimitry Andric       StatementKind == IfStatementKind::ConstevalNonNegated ||
890349cc55cSDimitry Andric       StatementKind == IfStatementKind::ConstevalNegated;
891349cc55cSDimitry Andric 
8920b57cec5SDimitry Andric   Expr *CondExpr = Cond.get().second;
893349cc55cSDimitry Andric   assert((CondExpr || ConstevalOrNegatedConsteval) &&
894349cc55cSDimitry Andric          "If statement: missing condition");
8950b57cec5SDimitry Andric   // Only call the CommaVisitor when not C89 due to differences in scope flags.
896349cc55cSDimitry Andric   if (CondExpr && (getLangOpts().C99 || getLangOpts().CPlusPlus) &&
8970b57cec5SDimitry Andric       !Diags.isIgnored(diag::warn_comma_operator, CondExpr->getExprLoc()))
8980b57cec5SDimitry Andric     CommaVisitor(*this).Visit(CondExpr);
8990b57cec5SDimitry Andric 
900349cc55cSDimitry Andric   if (!ConstevalOrNegatedConsteval && !elseStmt)
90181ad6265SDimitry Andric     DiagnoseEmptyStmtBody(RParenLoc, thenStmt, diag::warn_empty_if_body);
9020b57cec5SDimitry Andric 
903349cc55cSDimitry Andric   if (ConstevalOrNegatedConsteval ||
904349cc55cSDimitry Andric       StatementKind == IfStatementKind::Constexpr) {
905e8d8bef9SDimitry Andric     auto DiagnoseLikelihood = [&](const Stmt *S) {
906e8d8bef9SDimitry Andric       if (const Attr *A = Stmt::getLikelihoodAttr(S)) {
907e8d8bef9SDimitry Andric         Diags.Report(A->getLocation(),
908349cc55cSDimitry Andric                      diag::warn_attribute_has_no_effect_on_compile_time_if)
909349cc55cSDimitry Andric             << A << ConstevalOrNegatedConsteval << A->getRange();
910e8d8bef9SDimitry Andric         Diags.Report(IfLoc,
911349cc55cSDimitry Andric                      diag::note_attribute_has_no_effect_on_compile_time_if_here)
912349cc55cSDimitry Andric             << ConstevalOrNegatedConsteval
913349cc55cSDimitry Andric             << SourceRange(IfLoc, (ConstevalOrNegatedConsteval
914349cc55cSDimitry Andric                                        ? thenStmt->getBeginLoc()
915349cc55cSDimitry Andric                                        : LParenLoc)
916349cc55cSDimitry Andric                                       .getLocWithOffset(-1));
917e8d8bef9SDimitry Andric       }
918e8d8bef9SDimitry Andric     };
919e8d8bef9SDimitry Andric     DiagnoseLikelihood(thenStmt);
920e8d8bef9SDimitry Andric     DiagnoseLikelihood(elseStmt);
921e8d8bef9SDimitry Andric   } else {
922e8d8bef9SDimitry Andric     std::tuple<bool, const Attr *, const Attr *> LHC =
923e8d8bef9SDimitry Andric         Stmt::determineLikelihoodConflict(thenStmt, elseStmt);
924e8d8bef9SDimitry Andric     if (std::get<0>(LHC)) {
925e8d8bef9SDimitry Andric       const Attr *ThenAttr = std::get<1>(LHC);
926e8d8bef9SDimitry Andric       const Attr *ElseAttr = std::get<2>(LHC);
927e8d8bef9SDimitry Andric       Diags.Report(ThenAttr->getLocation(),
928e8d8bef9SDimitry Andric                    diag::warn_attributes_likelihood_ifstmt_conflict)
929e8d8bef9SDimitry Andric           << ThenAttr << ThenAttr->getRange();
930e8d8bef9SDimitry Andric       Diags.Report(ElseAttr->getLocation(), diag::note_conflicting_attribute)
931e8d8bef9SDimitry Andric           << ElseAttr << ElseAttr->getRange();
932e8d8bef9SDimitry Andric     }
933e8d8bef9SDimitry Andric   }
934e8d8bef9SDimitry Andric 
935349cc55cSDimitry Andric   if (ConstevalOrNegatedConsteval) {
93606c3fb27SDimitry Andric     bool Immediate = ExprEvalContexts.back().Context ==
93706c3fb27SDimitry Andric                      ExpressionEvaluationContext::ImmediateFunctionContext;
938349cc55cSDimitry Andric     if (CurContext->isFunctionOrMethod()) {
939349cc55cSDimitry Andric       const auto *FD =
940349cc55cSDimitry Andric           dyn_cast<FunctionDecl>(Decl::castFromDeclContext(CurContext));
94106c3fb27SDimitry Andric       if (FD && FD->isImmediateFunction())
942349cc55cSDimitry Andric         Immediate = true;
943349cc55cSDimitry Andric     }
944349cc55cSDimitry Andric     if (isUnevaluatedContext() || Immediate)
945349cc55cSDimitry Andric       Diags.Report(IfLoc, diag::warn_consteval_if_always_true) << Immediate;
946349cc55cSDimitry Andric   }
947349cc55cSDimitry Andric 
948349cc55cSDimitry Andric   return BuildIfStmt(IfLoc, StatementKind, LParenLoc, InitStmt, Cond, RParenLoc,
949e8d8bef9SDimitry Andric                      thenStmt, ElseLoc, elseStmt);
9500b57cec5SDimitry Andric }
9510b57cec5SDimitry Andric 
952349cc55cSDimitry Andric StmtResult Sema::BuildIfStmt(SourceLocation IfLoc,
953349cc55cSDimitry Andric                              IfStatementKind StatementKind,
954e8d8bef9SDimitry Andric                              SourceLocation LParenLoc, Stmt *InitStmt,
955e8d8bef9SDimitry Andric                              ConditionResult Cond, SourceLocation RParenLoc,
9560b57cec5SDimitry Andric                              Stmt *thenStmt, SourceLocation ElseLoc,
9570b57cec5SDimitry Andric                              Stmt *elseStmt) {
9580b57cec5SDimitry Andric   if (Cond.isInvalid())
9590b57cec5SDimitry Andric     return StmtError();
9600b57cec5SDimitry Andric 
961349cc55cSDimitry Andric   if (StatementKind != IfStatementKind::Ordinary ||
962349cc55cSDimitry Andric       isa<ObjCAvailabilityCheckExpr>(Cond.get().second))
9630b57cec5SDimitry Andric     setFunctionHasBranchProtectedScope();
9640b57cec5SDimitry Andric 
965349cc55cSDimitry Andric   return IfStmt::Create(Context, IfLoc, StatementKind, InitStmt,
966349cc55cSDimitry Andric                         Cond.get().first, Cond.get().second, LParenLoc,
967349cc55cSDimitry Andric                         RParenLoc, thenStmt, ElseLoc, elseStmt);
9680b57cec5SDimitry Andric }
9690b57cec5SDimitry Andric 
9700b57cec5SDimitry Andric namespace {
9710b57cec5SDimitry Andric   struct CaseCompareFunctor {
9720b57cec5SDimitry Andric     bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
9730b57cec5SDimitry Andric                     const llvm::APSInt &RHS) {
9740b57cec5SDimitry Andric       return LHS.first < RHS;
9750b57cec5SDimitry Andric     }
9760b57cec5SDimitry Andric     bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
9770b57cec5SDimitry Andric                     const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
9780b57cec5SDimitry Andric       return LHS.first < RHS.first;
9790b57cec5SDimitry Andric     }
9800b57cec5SDimitry Andric     bool operator()(const llvm::APSInt &LHS,
9810b57cec5SDimitry Andric                     const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
9820b57cec5SDimitry Andric       return LHS < RHS.first;
9830b57cec5SDimitry Andric     }
9840b57cec5SDimitry Andric   };
9850b57cec5SDimitry Andric }
9860b57cec5SDimitry Andric 
9870b57cec5SDimitry Andric /// CmpCaseVals - Comparison predicate for sorting case values.
9880b57cec5SDimitry Andric ///
9890b57cec5SDimitry Andric static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
9900b57cec5SDimitry Andric                         const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
9910b57cec5SDimitry Andric   if (lhs.first < rhs.first)
9920b57cec5SDimitry Andric     return true;
9930b57cec5SDimitry Andric 
9940b57cec5SDimitry Andric   if (lhs.first == rhs.first &&
995e8d8bef9SDimitry Andric       lhs.second->getCaseLoc() < rhs.second->getCaseLoc())
9960b57cec5SDimitry Andric     return true;
9970b57cec5SDimitry Andric   return false;
9980b57cec5SDimitry Andric }
9990b57cec5SDimitry Andric 
10000b57cec5SDimitry Andric /// CmpEnumVals - Comparison predicate for sorting enumeration values.
10010b57cec5SDimitry Andric ///
10020b57cec5SDimitry Andric static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
10030b57cec5SDimitry Andric                         const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
10040b57cec5SDimitry Andric {
10050b57cec5SDimitry Andric   return lhs.first < rhs.first;
10060b57cec5SDimitry Andric }
10070b57cec5SDimitry Andric 
10080b57cec5SDimitry Andric /// EqEnumVals - Comparison preficate for uniqing enumeration values.
10090b57cec5SDimitry Andric ///
10100b57cec5SDimitry Andric static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
10110b57cec5SDimitry Andric                        const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
10120b57cec5SDimitry Andric {
10130b57cec5SDimitry Andric   return lhs.first == rhs.first;
10140b57cec5SDimitry Andric }
10150b57cec5SDimitry Andric 
10160b57cec5SDimitry Andric /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
10170b57cec5SDimitry Andric /// potentially integral-promoted expression @p expr.
10180b57cec5SDimitry Andric static QualType GetTypeBeforeIntegralPromotion(const Expr *&E) {
10190b57cec5SDimitry Andric   if (const auto *FE = dyn_cast<FullExpr>(E))
10200b57cec5SDimitry Andric     E = FE->getSubExpr();
10210b57cec5SDimitry Andric   while (const auto *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
10220b57cec5SDimitry Andric     if (ImpCast->getCastKind() != CK_IntegralCast) break;
10230b57cec5SDimitry Andric     E = ImpCast->getSubExpr();
10240b57cec5SDimitry Andric   }
10250b57cec5SDimitry Andric   return E->getType();
10260b57cec5SDimitry Andric }
10270b57cec5SDimitry Andric 
10280b57cec5SDimitry Andric ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) {
10290b57cec5SDimitry Andric   class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
10300b57cec5SDimitry Andric     Expr *Cond;
10310b57cec5SDimitry Andric 
10320b57cec5SDimitry Andric   public:
10330b57cec5SDimitry Andric     SwitchConvertDiagnoser(Expr *Cond)
10340b57cec5SDimitry Andric         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
10350b57cec5SDimitry Andric           Cond(Cond) {}
10360b57cec5SDimitry Andric 
10370b57cec5SDimitry Andric     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10380b57cec5SDimitry Andric                                          QualType T) override {
10390b57cec5SDimitry Andric       return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
10400b57cec5SDimitry Andric     }
10410b57cec5SDimitry Andric 
10420b57cec5SDimitry Andric     SemaDiagnosticBuilder diagnoseIncomplete(
10430b57cec5SDimitry Andric         Sema &S, SourceLocation Loc, QualType T) override {
10440b57cec5SDimitry Andric       return S.Diag(Loc, diag::err_switch_incomplete_class_type)
10450b57cec5SDimitry Andric                << T << Cond->getSourceRange();
10460b57cec5SDimitry Andric     }
10470b57cec5SDimitry Andric 
10480b57cec5SDimitry Andric     SemaDiagnosticBuilder diagnoseExplicitConv(
10490b57cec5SDimitry Andric         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
10500b57cec5SDimitry Andric       return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
10510b57cec5SDimitry Andric     }
10520b57cec5SDimitry Andric 
10530b57cec5SDimitry Andric     SemaDiagnosticBuilder noteExplicitConv(
10540b57cec5SDimitry Andric         Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
10550b57cec5SDimitry Andric       return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
10560b57cec5SDimitry Andric         << ConvTy->isEnumeralType() << ConvTy;
10570b57cec5SDimitry Andric     }
10580b57cec5SDimitry Andric 
10590b57cec5SDimitry Andric     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10600b57cec5SDimitry Andric                                             QualType T) override {
10610b57cec5SDimitry Andric       return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
10620b57cec5SDimitry Andric     }
10630b57cec5SDimitry Andric 
10640b57cec5SDimitry Andric     SemaDiagnosticBuilder noteAmbiguous(
10650b57cec5SDimitry Andric         Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
10660b57cec5SDimitry Andric       return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
10670b57cec5SDimitry Andric       << ConvTy->isEnumeralType() << ConvTy;
10680b57cec5SDimitry Andric     }
10690b57cec5SDimitry Andric 
10700b57cec5SDimitry Andric     SemaDiagnosticBuilder diagnoseConversion(
10710b57cec5SDimitry Andric         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
10720b57cec5SDimitry Andric       llvm_unreachable("conversion functions are permitted");
10730b57cec5SDimitry Andric     }
10740b57cec5SDimitry Andric   } SwitchDiagnoser(Cond);
10750b57cec5SDimitry Andric 
10760b57cec5SDimitry Andric   ExprResult CondResult =
10770b57cec5SDimitry Andric       PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
10780b57cec5SDimitry Andric   if (CondResult.isInvalid())
10790b57cec5SDimitry Andric     return ExprError();
10800b57cec5SDimitry Andric 
10810b57cec5SDimitry Andric   // FIXME: PerformContextualImplicitConversion doesn't always tell us if it
10820b57cec5SDimitry Andric   // failed and produced a diagnostic.
10830b57cec5SDimitry Andric   Cond = CondResult.get();
10840b57cec5SDimitry Andric   if (!Cond->isTypeDependent() &&
10850b57cec5SDimitry Andric       !Cond->getType()->isIntegralOrEnumerationType())
10860b57cec5SDimitry Andric     return ExprError();
10870b57cec5SDimitry Andric 
10880b57cec5SDimitry Andric   // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
10890b57cec5SDimitry Andric   return UsualUnaryConversions(Cond);
10900b57cec5SDimitry Andric }
10910b57cec5SDimitry Andric 
10920b57cec5SDimitry Andric StmtResult Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
1093e8d8bef9SDimitry Andric                                         SourceLocation LParenLoc,
1094e8d8bef9SDimitry Andric                                         Stmt *InitStmt, ConditionResult Cond,
1095e8d8bef9SDimitry Andric                                         SourceLocation RParenLoc) {
10960b57cec5SDimitry Andric   Expr *CondExpr = Cond.get().second;
10970b57cec5SDimitry Andric   assert((Cond.isInvalid() || CondExpr) && "switch with no condition");
10980b57cec5SDimitry Andric 
10990b57cec5SDimitry Andric   if (CondExpr && !CondExpr->isTypeDependent()) {
11000b57cec5SDimitry Andric     // We have already converted the expression to an integral or enumeration
11015ffd83dbSDimitry Andric     // type, when we parsed the switch condition. There are cases where we don't
11025ffd83dbSDimitry Andric     // have an appropriate type, e.g. a typo-expr Cond was corrected to an
11035ffd83dbSDimitry Andric     // inappropriate-type expr, we just return an error.
11045ffd83dbSDimitry Andric     if (!CondExpr->getType()->isIntegralOrEnumerationType())
11055ffd83dbSDimitry Andric       return StmtError();
11060b57cec5SDimitry Andric     if (CondExpr->isKnownToHaveBooleanValue()) {
11070b57cec5SDimitry Andric       // switch(bool_expr) {...} is often a programmer error, e.g.
11080b57cec5SDimitry Andric       //   switch(n && mask) { ... }  // Doh - should be "n & mask".
11090b57cec5SDimitry Andric       // One can always use an if statement instead of switch(bool_expr).
11100b57cec5SDimitry Andric       Diag(SwitchLoc, diag::warn_bool_switch_condition)
11110b57cec5SDimitry Andric           << CondExpr->getSourceRange();
11120b57cec5SDimitry Andric     }
11130b57cec5SDimitry Andric   }
11140b57cec5SDimitry Andric 
11150b57cec5SDimitry Andric   setFunctionHasBranchIntoScope();
11160b57cec5SDimitry Andric 
1117e8d8bef9SDimitry Andric   auto *SS = SwitchStmt::Create(Context, InitStmt, Cond.get().first, CondExpr,
1118e8d8bef9SDimitry Andric                                 LParenLoc, RParenLoc);
11190b57cec5SDimitry Andric   getCurFunction()->SwitchStack.push_back(
11200b57cec5SDimitry Andric       FunctionScopeInfo::SwitchInfo(SS, false));
11210b57cec5SDimitry Andric   return SS;
11220b57cec5SDimitry Andric }
11230b57cec5SDimitry Andric 
11240b57cec5SDimitry Andric static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
11250b57cec5SDimitry Andric   Val = Val.extOrTrunc(BitWidth);
11260b57cec5SDimitry Andric   Val.setIsSigned(IsSigned);
11270b57cec5SDimitry Andric }
11280b57cec5SDimitry Andric 
11290b57cec5SDimitry Andric /// Check the specified case value is in range for the given unpromoted switch
11300b57cec5SDimitry Andric /// type.
11310b57cec5SDimitry Andric static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
11320b57cec5SDimitry Andric                            unsigned UnpromotedWidth, bool UnpromotedSign) {
11330b57cec5SDimitry Andric   // In C++11 onwards, this is checked by the language rules.
11340b57cec5SDimitry Andric   if (S.getLangOpts().CPlusPlus11)
11350b57cec5SDimitry Andric     return;
11360b57cec5SDimitry Andric 
11370b57cec5SDimitry Andric   // If the case value was signed and negative and the switch expression is
11380b57cec5SDimitry Andric   // unsigned, don't bother to warn: this is implementation-defined behavior.
11390b57cec5SDimitry Andric   // FIXME: Introduce a second, default-ignored warning for this case?
11400b57cec5SDimitry Andric   if (UnpromotedWidth < Val.getBitWidth()) {
11410b57cec5SDimitry Andric     llvm::APSInt ConvVal(Val);
11420b57cec5SDimitry Andric     AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
11430b57cec5SDimitry Andric     AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
11440b57cec5SDimitry Andric     // FIXME: Use different diagnostics for overflow  in conversion to promoted
11450b57cec5SDimitry Andric     // type versus "switch expression cannot have this value". Use proper
11460b57cec5SDimitry Andric     // IntRange checking rather than just looking at the unpromoted type here.
11470b57cec5SDimitry Andric     if (ConvVal != Val)
1148fe6060f1SDimitry Andric       S.Diag(Loc, diag::warn_case_value_overflow) << toString(Val, 10)
1149fe6060f1SDimitry Andric                                                   << toString(ConvVal, 10);
11500b57cec5SDimitry Andric   }
11510b57cec5SDimitry Andric }
11520b57cec5SDimitry Andric 
11530b57cec5SDimitry Andric typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
11540b57cec5SDimitry Andric 
11550b57cec5SDimitry Andric /// Returns true if we should emit a diagnostic about this case expression not
11560b57cec5SDimitry Andric /// being a part of the enum used in the switch controlling expression.
11570b57cec5SDimitry Andric static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
11580b57cec5SDimitry Andric                                               const EnumDecl *ED,
11590b57cec5SDimitry Andric                                               const Expr *CaseExpr,
11600b57cec5SDimitry Andric                                               EnumValsTy::iterator &EI,
11610b57cec5SDimitry Andric                                               EnumValsTy::iterator &EIEnd,
11620b57cec5SDimitry Andric                                               const llvm::APSInt &Val) {
11630b57cec5SDimitry Andric   if (!ED->isClosed())
11640b57cec5SDimitry Andric     return false;
11650b57cec5SDimitry Andric 
11660b57cec5SDimitry Andric   if (const DeclRefExpr *DRE =
11670b57cec5SDimitry Andric           dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
11680b57cec5SDimitry Andric     if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
11690b57cec5SDimitry Andric       QualType VarType = VD->getType();
11700b57cec5SDimitry Andric       QualType EnumType = S.Context.getTypeDeclType(ED);
11710b57cec5SDimitry Andric       if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
11720b57cec5SDimitry Andric           S.Context.hasSameUnqualifiedType(EnumType, VarType))
11730b57cec5SDimitry Andric         return false;
11740b57cec5SDimitry Andric     }
11750b57cec5SDimitry Andric   }
11760b57cec5SDimitry Andric 
11770b57cec5SDimitry Andric   if (ED->hasAttr<FlagEnumAttr>())
11780b57cec5SDimitry Andric     return !S.IsValueInFlagEnum(ED, Val, false);
11790b57cec5SDimitry Andric 
11800b57cec5SDimitry Andric   while (EI != EIEnd && EI->first < Val)
11810b57cec5SDimitry Andric     EI++;
11820b57cec5SDimitry Andric 
11830b57cec5SDimitry Andric   if (EI != EIEnd && EI->first == Val)
11840b57cec5SDimitry Andric     return false;
11850b57cec5SDimitry Andric 
11860b57cec5SDimitry Andric   return true;
11870b57cec5SDimitry Andric }
11880b57cec5SDimitry Andric 
11890b57cec5SDimitry Andric static void checkEnumTypesInSwitchStmt(Sema &S, const Expr *Cond,
11900b57cec5SDimitry Andric                                        const Expr *Case) {
11910b57cec5SDimitry Andric   QualType CondType = Cond->getType();
11920b57cec5SDimitry Andric   QualType CaseType = Case->getType();
11930b57cec5SDimitry Andric 
11940b57cec5SDimitry Andric   const EnumType *CondEnumType = CondType->getAs<EnumType>();
11950b57cec5SDimitry Andric   const EnumType *CaseEnumType = CaseType->getAs<EnumType>();
11960b57cec5SDimitry Andric   if (!CondEnumType || !CaseEnumType)
11970b57cec5SDimitry Andric     return;
11980b57cec5SDimitry Andric 
11990b57cec5SDimitry Andric   // Ignore anonymous enums.
12000b57cec5SDimitry Andric   if (!CondEnumType->getDecl()->getIdentifier() &&
12010b57cec5SDimitry Andric       !CondEnumType->getDecl()->getTypedefNameForAnonDecl())
12020b57cec5SDimitry Andric     return;
12030b57cec5SDimitry Andric   if (!CaseEnumType->getDecl()->getIdentifier() &&
12040b57cec5SDimitry Andric       !CaseEnumType->getDecl()->getTypedefNameForAnonDecl())
12050b57cec5SDimitry Andric     return;
12060b57cec5SDimitry Andric 
12070b57cec5SDimitry Andric   if (S.Context.hasSameUnqualifiedType(CondType, CaseType))
12080b57cec5SDimitry Andric     return;
12090b57cec5SDimitry Andric 
12100b57cec5SDimitry Andric   S.Diag(Case->getExprLoc(), diag::warn_comparison_of_mixed_enum_types_switch)
12110b57cec5SDimitry Andric       << CondType << CaseType << Cond->getSourceRange()
12120b57cec5SDimitry Andric       << Case->getSourceRange();
12130b57cec5SDimitry Andric }
12140b57cec5SDimitry Andric 
12150b57cec5SDimitry Andric StmtResult
12160b57cec5SDimitry Andric Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
12170b57cec5SDimitry Andric                             Stmt *BodyStmt) {
12180b57cec5SDimitry Andric   SwitchStmt *SS = cast<SwitchStmt>(Switch);
12190b57cec5SDimitry Andric   bool CaseListIsIncomplete = getCurFunction()->SwitchStack.back().getInt();
12200b57cec5SDimitry Andric   assert(SS == getCurFunction()->SwitchStack.back().getPointer() &&
12210b57cec5SDimitry Andric          "switch stack missing push/pop!");
12220b57cec5SDimitry Andric 
12230b57cec5SDimitry Andric   getCurFunction()->SwitchStack.pop_back();
12240b57cec5SDimitry Andric 
12250b57cec5SDimitry Andric   if (!BodyStmt) return StmtError();
12260b57cec5SDimitry Andric   SS->setBody(BodyStmt, SwitchLoc);
12270b57cec5SDimitry Andric 
12280b57cec5SDimitry Andric   Expr *CondExpr = SS->getCond();
12290b57cec5SDimitry Andric   if (!CondExpr) return StmtError();
12300b57cec5SDimitry Andric 
12310b57cec5SDimitry Andric   QualType CondType = CondExpr->getType();
12320b57cec5SDimitry Andric 
12330b57cec5SDimitry Andric   // C++ 6.4.2.p2:
12340b57cec5SDimitry Andric   // Integral promotions are performed (on the switch condition).
12350b57cec5SDimitry Andric   //
12360b57cec5SDimitry Andric   // A case value unrepresentable by the original switch condition
12370b57cec5SDimitry Andric   // type (before the promotion) doesn't make sense, even when it can
12380b57cec5SDimitry Andric   // be represented by the promoted type.  Therefore we need to find
12390b57cec5SDimitry Andric   // the pre-promotion type of the switch condition.
12400b57cec5SDimitry Andric   const Expr *CondExprBeforePromotion = CondExpr;
12410b57cec5SDimitry Andric   QualType CondTypeBeforePromotion =
12420b57cec5SDimitry Andric       GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
12430b57cec5SDimitry Andric 
12440b57cec5SDimitry Andric   // Get the bitwidth of the switched-on value after promotions. We must
12450b57cec5SDimitry Andric   // convert the integer case values to this width before comparison.
12460b57cec5SDimitry Andric   bool HasDependentValue
12470b57cec5SDimitry Andric     = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
12480b57cec5SDimitry Andric   unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
12490b57cec5SDimitry Andric   bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
12500b57cec5SDimitry Andric 
12510b57cec5SDimitry Andric   // Get the width and signedness that the condition might actually have, for
12520b57cec5SDimitry Andric   // warning purposes.
12530b57cec5SDimitry Andric   // FIXME: Grab an IntRange for the condition rather than using the unpromoted
12540b57cec5SDimitry Andric   // type.
12550b57cec5SDimitry Andric   unsigned CondWidthBeforePromotion
12560b57cec5SDimitry Andric     = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
12570b57cec5SDimitry Andric   bool CondIsSignedBeforePromotion
12580b57cec5SDimitry Andric     = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
12590b57cec5SDimitry Andric 
12600b57cec5SDimitry Andric   // Accumulate all of the case values in a vector so that we can sort them
12610b57cec5SDimitry Andric   // and detect duplicates.  This vector contains the APInt for the case after
12620b57cec5SDimitry Andric   // it has been converted to the condition type.
12630b57cec5SDimitry Andric   typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
12640b57cec5SDimitry Andric   CaseValsTy CaseVals;
12650b57cec5SDimitry Andric 
12660b57cec5SDimitry Andric   // Keep track of any GNU case ranges we see.  The APSInt is the low value.
12670b57cec5SDimitry Andric   typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
12680b57cec5SDimitry Andric   CaseRangesTy CaseRanges;
12690b57cec5SDimitry Andric 
12700b57cec5SDimitry Andric   DefaultStmt *TheDefaultStmt = nullptr;
12710b57cec5SDimitry Andric 
12720b57cec5SDimitry Andric   bool CaseListIsErroneous = false;
12730b57cec5SDimitry Andric 
1274cb14a3feSDimitry Andric   // FIXME: We'd better diagnose missing or duplicate default labels even
1275cb14a3feSDimitry Andric   // in the dependent case. Because default labels themselves are never
1276cb14a3feSDimitry Andric   // dependent.
12770b57cec5SDimitry Andric   for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
12780b57cec5SDimitry Andric        SC = SC->getNextSwitchCase()) {
12790b57cec5SDimitry Andric 
12800b57cec5SDimitry Andric     if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
12810b57cec5SDimitry Andric       if (TheDefaultStmt) {
12820b57cec5SDimitry Andric         Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
12830b57cec5SDimitry Andric         Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
12840b57cec5SDimitry Andric 
12850b57cec5SDimitry Andric         // FIXME: Remove the default statement from the switch block so that
12860b57cec5SDimitry Andric         // we'll return a valid AST.  This requires recursing down the AST and
12870b57cec5SDimitry Andric         // finding it, not something we are set up to do right now.  For now,
12880b57cec5SDimitry Andric         // just lop the entire switch stmt out of the AST.
12890b57cec5SDimitry Andric         CaseListIsErroneous = true;
12900b57cec5SDimitry Andric       }
12910b57cec5SDimitry Andric       TheDefaultStmt = DS;
12920b57cec5SDimitry Andric 
12930b57cec5SDimitry Andric     } else {
12940b57cec5SDimitry Andric       CaseStmt *CS = cast<CaseStmt>(SC);
12950b57cec5SDimitry Andric 
12960b57cec5SDimitry Andric       Expr *Lo = CS->getLHS();
12970b57cec5SDimitry Andric 
12980b57cec5SDimitry Andric       if (Lo->isValueDependent()) {
12990b57cec5SDimitry Andric         HasDependentValue = true;
13000b57cec5SDimitry Andric         break;
13010b57cec5SDimitry Andric       }
13020b57cec5SDimitry Andric 
13030b57cec5SDimitry Andric       // We already verified that the expression has a constant value;
13040b57cec5SDimitry Andric       // get that value (prior to conversions).
13050b57cec5SDimitry Andric       const Expr *LoBeforePromotion = Lo;
13060b57cec5SDimitry Andric       GetTypeBeforeIntegralPromotion(LoBeforePromotion);
13070b57cec5SDimitry Andric       llvm::APSInt LoVal = LoBeforePromotion->EvaluateKnownConstInt(Context);
13080b57cec5SDimitry Andric 
13090b57cec5SDimitry Andric       // Check the unconverted value is within the range of possible values of
13100b57cec5SDimitry Andric       // the switch expression.
13110b57cec5SDimitry Andric       checkCaseValue(*this, Lo->getBeginLoc(), LoVal, CondWidthBeforePromotion,
13120b57cec5SDimitry Andric                      CondIsSignedBeforePromotion);
13130b57cec5SDimitry Andric 
13140b57cec5SDimitry Andric       // FIXME: This duplicates the check performed for warn_not_in_enum below.
13150b57cec5SDimitry Andric       checkEnumTypesInSwitchStmt(*this, CondExprBeforePromotion,
13160b57cec5SDimitry Andric                                  LoBeforePromotion);
13170b57cec5SDimitry Andric 
13180b57cec5SDimitry Andric       // Convert the value to the same width/sign as the condition.
13190b57cec5SDimitry Andric       AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
13200b57cec5SDimitry Andric 
13210b57cec5SDimitry Andric       // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
13220b57cec5SDimitry Andric       if (CS->getRHS()) {
13230b57cec5SDimitry Andric         if (CS->getRHS()->isValueDependent()) {
13240b57cec5SDimitry Andric           HasDependentValue = true;
13250b57cec5SDimitry Andric           break;
13260b57cec5SDimitry Andric         }
13270b57cec5SDimitry Andric         CaseRanges.push_back(std::make_pair(LoVal, CS));
13280b57cec5SDimitry Andric       } else
13290b57cec5SDimitry Andric         CaseVals.push_back(std::make_pair(LoVal, CS));
13300b57cec5SDimitry Andric     }
13310b57cec5SDimitry Andric   }
13320b57cec5SDimitry Andric 
13330b57cec5SDimitry Andric   if (!HasDependentValue) {
13340b57cec5SDimitry Andric     // If we don't have a default statement, check whether the
13350b57cec5SDimitry Andric     // condition is constant.
13360b57cec5SDimitry Andric     llvm::APSInt ConstantCondValue;
13370b57cec5SDimitry Andric     bool HasConstantCond = false;
1338a7dea167SDimitry Andric     if (!TheDefaultStmt) {
13390b57cec5SDimitry Andric       Expr::EvalResult Result;
13400b57cec5SDimitry Andric       HasConstantCond = CondExpr->EvaluateAsInt(Result, Context,
13410b57cec5SDimitry Andric                                                 Expr::SE_AllowSideEffects);
13420b57cec5SDimitry Andric       if (Result.Val.isInt())
13430b57cec5SDimitry Andric         ConstantCondValue = Result.Val.getInt();
13440b57cec5SDimitry Andric       assert(!HasConstantCond ||
13450b57cec5SDimitry Andric              (ConstantCondValue.getBitWidth() == CondWidth &&
13460b57cec5SDimitry Andric               ConstantCondValue.isSigned() == CondIsSigned));
1347cb14a3feSDimitry Andric       Diag(SwitchLoc, diag::warn_switch_default);
13480b57cec5SDimitry Andric     }
13490b57cec5SDimitry Andric     bool ShouldCheckConstantCond = HasConstantCond;
13500b57cec5SDimitry Andric 
13510b57cec5SDimitry Andric     // Sort all the scalar case values so we can easily detect duplicates.
13520b57cec5SDimitry Andric     llvm::stable_sort(CaseVals, CmpCaseVals);
13530b57cec5SDimitry Andric 
13540b57cec5SDimitry Andric     if (!CaseVals.empty()) {
13550b57cec5SDimitry Andric       for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
13560b57cec5SDimitry Andric         if (ShouldCheckConstantCond &&
13570b57cec5SDimitry Andric             CaseVals[i].first == ConstantCondValue)
13580b57cec5SDimitry Andric           ShouldCheckConstantCond = false;
13590b57cec5SDimitry Andric 
13600b57cec5SDimitry Andric         if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
13610b57cec5SDimitry Andric           // If we have a duplicate, report it.
13620b57cec5SDimitry Andric           // First, determine if either case value has a name
13630b57cec5SDimitry Andric           StringRef PrevString, CurrString;
13640b57cec5SDimitry Andric           Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
13650b57cec5SDimitry Andric           Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
13660b57cec5SDimitry Andric           if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
13670b57cec5SDimitry Andric             PrevString = DeclRef->getDecl()->getName();
13680b57cec5SDimitry Andric           }
13690b57cec5SDimitry Andric           if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
13700b57cec5SDimitry Andric             CurrString = DeclRef->getDecl()->getName();
13710b57cec5SDimitry Andric           }
13720b57cec5SDimitry Andric           SmallString<16> CaseValStr;
13730b57cec5SDimitry Andric           CaseVals[i-1].first.toString(CaseValStr);
13740b57cec5SDimitry Andric 
13750b57cec5SDimitry Andric           if (PrevString == CurrString)
13760b57cec5SDimitry Andric             Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
13770b57cec5SDimitry Andric                  diag::err_duplicate_case)
1378fe6060f1SDimitry Andric                 << (PrevString.empty() ? CaseValStr.str() : PrevString);
13790b57cec5SDimitry Andric           else
13800b57cec5SDimitry Andric             Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
13810b57cec5SDimitry Andric                  diag::err_duplicate_case_differing_expr)
1382fe6060f1SDimitry Andric                 << (PrevString.empty() ? CaseValStr.str() : PrevString)
1383fe6060f1SDimitry Andric                 << (CurrString.empty() ? CaseValStr.str() : CurrString)
13840b57cec5SDimitry Andric                 << CaseValStr;
13850b57cec5SDimitry Andric 
13860b57cec5SDimitry Andric           Diag(CaseVals[i - 1].second->getLHS()->getBeginLoc(),
13870b57cec5SDimitry Andric                diag::note_duplicate_case_prev);
13880b57cec5SDimitry Andric           // FIXME: We really want to remove the bogus case stmt from the
13890b57cec5SDimitry Andric           // substmt, but we have no way to do this right now.
13900b57cec5SDimitry Andric           CaseListIsErroneous = true;
13910b57cec5SDimitry Andric         }
13920b57cec5SDimitry Andric       }
13930b57cec5SDimitry Andric     }
13940b57cec5SDimitry Andric 
13950b57cec5SDimitry Andric     // Detect duplicate case ranges, which usually don't exist at all in
13960b57cec5SDimitry Andric     // the first place.
13970b57cec5SDimitry Andric     if (!CaseRanges.empty()) {
13980b57cec5SDimitry Andric       // Sort all the case ranges by their low value so we can easily detect
13990b57cec5SDimitry Andric       // overlaps between ranges.
14000b57cec5SDimitry Andric       llvm::stable_sort(CaseRanges);
14010b57cec5SDimitry Andric 
14020b57cec5SDimitry Andric       // Scan the ranges, computing the high values and removing empty ranges.
14030b57cec5SDimitry Andric       std::vector<llvm::APSInt> HiVals;
14040b57cec5SDimitry Andric       for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
14050b57cec5SDimitry Andric         llvm::APSInt &LoVal = CaseRanges[i].first;
14060b57cec5SDimitry Andric         CaseStmt *CR = CaseRanges[i].second;
14070b57cec5SDimitry Andric         Expr *Hi = CR->getRHS();
14080b57cec5SDimitry Andric 
14090b57cec5SDimitry Andric         const Expr *HiBeforePromotion = Hi;
14100b57cec5SDimitry Andric         GetTypeBeforeIntegralPromotion(HiBeforePromotion);
14110b57cec5SDimitry Andric         llvm::APSInt HiVal = HiBeforePromotion->EvaluateKnownConstInt(Context);
14120b57cec5SDimitry Andric 
14130b57cec5SDimitry Andric         // Check the unconverted value is within the range of possible values of
14140b57cec5SDimitry Andric         // the switch expression.
14150b57cec5SDimitry Andric         checkCaseValue(*this, Hi->getBeginLoc(), HiVal,
14160b57cec5SDimitry Andric                        CondWidthBeforePromotion, CondIsSignedBeforePromotion);
14170b57cec5SDimitry Andric 
14180b57cec5SDimitry Andric         // Convert the value to the same width/sign as the condition.
14190b57cec5SDimitry Andric         AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
14200b57cec5SDimitry Andric 
14210b57cec5SDimitry Andric         // If the low value is bigger than the high value, the case is empty.
14220b57cec5SDimitry Andric         if (LoVal > HiVal) {
14230b57cec5SDimitry Andric           Diag(CR->getLHS()->getBeginLoc(), diag::warn_case_empty_range)
14240b57cec5SDimitry Andric               << SourceRange(CR->getLHS()->getBeginLoc(), Hi->getEndLoc());
14250b57cec5SDimitry Andric           CaseRanges.erase(CaseRanges.begin()+i);
14260b57cec5SDimitry Andric           --i;
14270b57cec5SDimitry Andric           --e;
14280b57cec5SDimitry Andric           continue;
14290b57cec5SDimitry Andric         }
14300b57cec5SDimitry Andric 
14310b57cec5SDimitry Andric         if (ShouldCheckConstantCond &&
14320b57cec5SDimitry Andric             LoVal <= ConstantCondValue &&
14330b57cec5SDimitry Andric             ConstantCondValue <= HiVal)
14340b57cec5SDimitry Andric           ShouldCheckConstantCond = false;
14350b57cec5SDimitry Andric 
14360b57cec5SDimitry Andric         HiVals.push_back(HiVal);
14370b57cec5SDimitry Andric       }
14380b57cec5SDimitry Andric 
14390b57cec5SDimitry Andric       // Rescan the ranges, looking for overlap with singleton values and other
14400b57cec5SDimitry Andric       // ranges.  Since the range list is sorted, we only need to compare case
14410b57cec5SDimitry Andric       // ranges with their neighbors.
14420b57cec5SDimitry Andric       for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
14430b57cec5SDimitry Andric         llvm::APSInt &CRLo = CaseRanges[i].first;
14440b57cec5SDimitry Andric         llvm::APSInt &CRHi = HiVals[i];
14450b57cec5SDimitry Andric         CaseStmt *CR = CaseRanges[i].second;
14460b57cec5SDimitry Andric 
14470b57cec5SDimitry Andric         // Check to see whether the case range overlaps with any
14480b57cec5SDimitry Andric         // singleton cases.
14490b57cec5SDimitry Andric         CaseStmt *OverlapStmt = nullptr;
14500b57cec5SDimitry Andric         llvm::APSInt OverlapVal(32);
14510b57cec5SDimitry Andric 
14520b57cec5SDimitry Andric         // Find the smallest value >= the lower bound.  If I is in the
14530b57cec5SDimitry Andric         // case range, then we have overlap.
14540b57cec5SDimitry Andric         CaseValsTy::iterator I =
14550b57cec5SDimitry Andric             llvm::lower_bound(CaseVals, CRLo, CaseCompareFunctor());
14560b57cec5SDimitry Andric         if (I != CaseVals.end() && I->first < CRHi) {
14570b57cec5SDimitry Andric           OverlapVal  = I->first;   // Found overlap with scalar.
14580b57cec5SDimitry Andric           OverlapStmt = I->second;
14590b57cec5SDimitry Andric         }
14600b57cec5SDimitry Andric 
14610b57cec5SDimitry Andric         // Find the smallest value bigger than the upper bound.
14620b57cec5SDimitry Andric         I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
14630b57cec5SDimitry Andric         if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
14640b57cec5SDimitry Andric           OverlapVal  = (I-1)->first;      // Found overlap with scalar.
14650b57cec5SDimitry Andric           OverlapStmt = (I-1)->second;
14660b57cec5SDimitry Andric         }
14670b57cec5SDimitry Andric 
14680b57cec5SDimitry Andric         // Check to see if this case stmt overlaps with the subsequent
14690b57cec5SDimitry Andric         // case range.
14700b57cec5SDimitry Andric         if (i && CRLo <= HiVals[i-1]) {
14710b57cec5SDimitry Andric           OverlapVal  = HiVals[i-1];       // Found overlap with range.
14720b57cec5SDimitry Andric           OverlapStmt = CaseRanges[i-1].second;
14730b57cec5SDimitry Andric         }
14740b57cec5SDimitry Andric 
14750b57cec5SDimitry Andric         if (OverlapStmt) {
14760b57cec5SDimitry Andric           // If we have a duplicate, report it.
14770b57cec5SDimitry Andric           Diag(CR->getLHS()->getBeginLoc(), diag::err_duplicate_case)
1478fe6060f1SDimitry Andric               << toString(OverlapVal, 10);
14790b57cec5SDimitry Andric           Diag(OverlapStmt->getLHS()->getBeginLoc(),
14800b57cec5SDimitry Andric                diag::note_duplicate_case_prev);
14810b57cec5SDimitry Andric           // FIXME: We really want to remove the bogus case stmt from the
14820b57cec5SDimitry Andric           // substmt, but we have no way to do this right now.
14830b57cec5SDimitry Andric           CaseListIsErroneous = true;
14840b57cec5SDimitry Andric         }
14850b57cec5SDimitry Andric       }
14860b57cec5SDimitry Andric     }
14870b57cec5SDimitry Andric 
14880b57cec5SDimitry Andric     // Complain if we have a constant condition and we didn't find a match.
14890b57cec5SDimitry Andric     if (!CaseListIsErroneous && !CaseListIsIncomplete &&
14900b57cec5SDimitry Andric         ShouldCheckConstantCond) {
14910b57cec5SDimitry Andric       // TODO: it would be nice if we printed enums as enums, chars as
14920b57cec5SDimitry Andric       // chars, etc.
14930b57cec5SDimitry Andric       Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1494fe6060f1SDimitry Andric         << toString(ConstantCondValue, 10)
14950b57cec5SDimitry Andric         << CondExpr->getSourceRange();
14960b57cec5SDimitry Andric     }
14970b57cec5SDimitry Andric 
14980b57cec5SDimitry Andric     // Check to see if switch is over an Enum and handles all of its
14990b57cec5SDimitry Andric     // values.  We only issue a warning if there is not 'default:', but
15000b57cec5SDimitry Andric     // we still do the analysis to preserve this information in the AST
15010b57cec5SDimitry Andric     // (which can be used by flow-based analyes).
15020b57cec5SDimitry Andric     //
15030b57cec5SDimitry Andric     const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
15040b57cec5SDimitry Andric 
15050b57cec5SDimitry Andric     // If switch has default case, then ignore it.
15060b57cec5SDimitry Andric     if (!CaseListIsErroneous && !CaseListIsIncomplete && !HasConstantCond &&
1507fe6060f1SDimitry Andric         ET && ET->getDecl()->isCompleteDefinition() &&
1508bdd1243dSDimitry Andric         !ET->getDecl()->enumerators().empty()) {
15090b57cec5SDimitry Andric       const EnumDecl *ED = ET->getDecl();
15100b57cec5SDimitry Andric       EnumValsTy EnumVals;
15110b57cec5SDimitry Andric 
15120b57cec5SDimitry Andric       // Gather all enum values, set their type and sort them,
15130b57cec5SDimitry Andric       // allowing easier comparison with CaseVals.
15140b57cec5SDimitry Andric       for (auto *EDI : ED->enumerators()) {
15150b57cec5SDimitry Andric         llvm::APSInt Val = EDI->getInitVal();
15160b57cec5SDimitry Andric         AdjustAPSInt(Val, CondWidth, CondIsSigned);
15170b57cec5SDimitry Andric         EnumVals.push_back(std::make_pair(Val, EDI));
15180b57cec5SDimitry Andric       }
15190b57cec5SDimitry Andric       llvm::stable_sort(EnumVals, CmpEnumVals);
15200b57cec5SDimitry Andric       auto EI = EnumVals.begin(), EIEnd =
15210b57cec5SDimitry Andric         std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
15220b57cec5SDimitry Andric 
15230b57cec5SDimitry Andric       // See which case values aren't in enum.
15240b57cec5SDimitry Andric       for (CaseValsTy::const_iterator CI = CaseVals.begin();
15250b57cec5SDimitry Andric           CI != CaseVals.end(); CI++) {
15260b57cec5SDimitry Andric         Expr *CaseExpr = CI->second->getLHS();
15270b57cec5SDimitry Andric         if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
15280b57cec5SDimitry Andric                                               CI->first))
15290b57cec5SDimitry Andric           Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
15300b57cec5SDimitry Andric             << CondTypeBeforePromotion;
15310b57cec5SDimitry Andric       }
15320b57cec5SDimitry Andric 
15330b57cec5SDimitry Andric       // See which of case ranges aren't in enum
15340b57cec5SDimitry Andric       EI = EnumVals.begin();
15350b57cec5SDimitry Andric       for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
15360b57cec5SDimitry Andric           RI != CaseRanges.end(); RI++) {
15370b57cec5SDimitry Andric         Expr *CaseExpr = RI->second->getLHS();
15380b57cec5SDimitry Andric         if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
15390b57cec5SDimitry Andric                                               RI->first))
15400b57cec5SDimitry Andric           Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
15410b57cec5SDimitry Andric             << CondTypeBeforePromotion;
15420b57cec5SDimitry Andric 
15430b57cec5SDimitry Andric         llvm::APSInt Hi =
15440b57cec5SDimitry Andric           RI->second->getRHS()->EvaluateKnownConstInt(Context);
15450b57cec5SDimitry Andric         AdjustAPSInt(Hi, CondWidth, CondIsSigned);
15460b57cec5SDimitry Andric 
15470b57cec5SDimitry Andric         CaseExpr = RI->second->getRHS();
15480b57cec5SDimitry Andric         if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
15490b57cec5SDimitry Andric                                               Hi))
15500b57cec5SDimitry Andric           Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
15510b57cec5SDimitry Andric             << CondTypeBeforePromotion;
15520b57cec5SDimitry Andric       }
15530b57cec5SDimitry Andric 
15540b57cec5SDimitry Andric       // Check which enum vals aren't in switch
15550b57cec5SDimitry Andric       auto CI = CaseVals.begin();
15560b57cec5SDimitry Andric       auto RI = CaseRanges.begin();
15570b57cec5SDimitry Andric       bool hasCasesNotInSwitch = false;
15580b57cec5SDimitry Andric 
15590b57cec5SDimitry Andric       SmallVector<DeclarationName,8> UnhandledNames;
15600b57cec5SDimitry Andric 
15610b57cec5SDimitry Andric       for (EI = EnumVals.begin(); EI != EIEnd; EI++) {
15620b57cec5SDimitry Andric         // Don't warn about omitted unavailable EnumConstantDecls.
15630b57cec5SDimitry Andric         switch (EI->second->getAvailability()) {
15640b57cec5SDimitry Andric         case AR_Deprecated:
15650b57cec5SDimitry Andric           // Omitting a deprecated constant is ok; it should never materialize.
15660b57cec5SDimitry Andric         case AR_Unavailable:
15670b57cec5SDimitry Andric           continue;
15680b57cec5SDimitry Andric 
15690b57cec5SDimitry Andric         case AR_NotYetIntroduced:
15700b57cec5SDimitry Andric           // Partially available enum constants should be present. Note that we
15710b57cec5SDimitry Andric           // suppress -Wunguarded-availability diagnostics for such uses.
15720b57cec5SDimitry Andric         case AR_Available:
15730b57cec5SDimitry Andric           break;
15740b57cec5SDimitry Andric         }
15750b57cec5SDimitry Andric 
15760b57cec5SDimitry Andric         if (EI->second->hasAttr<UnusedAttr>())
15770b57cec5SDimitry Andric           continue;
15780b57cec5SDimitry Andric 
15790b57cec5SDimitry Andric         // Drop unneeded case values
15800b57cec5SDimitry Andric         while (CI != CaseVals.end() && CI->first < EI->first)
15810b57cec5SDimitry Andric           CI++;
15820b57cec5SDimitry Andric 
15830b57cec5SDimitry Andric         if (CI != CaseVals.end() && CI->first == EI->first)
15840b57cec5SDimitry Andric           continue;
15850b57cec5SDimitry Andric 
15860b57cec5SDimitry Andric         // Drop unneeded case ranges
15870b57cec5SDimitry Andric         for (; RI != CaseRanges.end(); RI++) {
15880b57cec5SDimitry Andric           llvm::APSInt Hi =
15890b57cec5SDimitry Andric             RI->second->getRHS()->EvaluateKnownConstInt(Context);
15900b57cec5SDimitry Andric           AdjustAPSInt(Hi, CondWidth, CondIsSigned);
15910b57cec5SDimitry Andric           if (EI->first <= Hi)
15920b57cec5SDimitry Andric             break;
15930b57cec5SDimitry Andric         }
15940b57cec5SDimitry Andric 
15950b57cec5SDimitry Andric         if (RI == CaseRanges.end() || EI->first < RI->first) {
15960b57cec5SDimitry Andric           hasCasesNotInSwitch = true;
15970b57cec5SDimitry Andric           UnhandledNames.push_back(EI->second->getDeclName());
15980b57cec5SDimitry Andric         }
15990b57cec5SDimitry Andric       }
16000b57cec5SDimitry Andric 
16010b57cec5SDimitry Andric       if (TheDefaultStmt && UnhandledNames.empty() && ED->isClosedNonFlag())
16020b57cec5SDimitry Andric         Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
16030b57cec5SDimitry Andric 
16040b57cec5SDimitry Andric       // Produce a nice diagnostic if multiple values aren't handled.
16050b57cec5SDimitry Andric       if (!UnhandledNames.empty()) {
1606e8d8bef9SDimitry Andric         auto DB = Diag(CondExpr->getExprLoc(), TheDefaultStmt
1607e8d8bef9SDimitry Andric                                                    ? diag::warn_def_missing_case
16080b57cec5SDimitry Andric                                                    : diag::warn_missing_case)
1609349cc55cSDimitry Andric                   << CondExpr->getSourceRange() << (int)UnhandledNames.size();
16100b57cec5SDimitry Andric 
16110b57cec5SDimitry Andric         for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
16120b57cec5SDimitry Andric              I != E; ++I)
16130b57cec5SDimitry Andric           DB << UnhandledNames[I];
16140b57cec5SDimitry Andric       }
16150b57cec5SDimitry Andric 
16160b57cec5SDimitry Andric       if (!hasCasesNotInSwitch)
16170b57cec5SDimitry Andric         SS->setAllEnumCasesCovered();
16180b57cec5SDimitry Andric     }
16190b57cec5SDimitry Andric   }
16200b57cec5SDimitry Andric 
16210b57cec5SDimitry Andric   if (BodyStmt)
16220b57cec5SDimitry Andric     DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), BodyStmt,
16230b57cec5SDimitry Andric                           diag::warn_empty_switch_body);
16240b57cec5SDimitry Andric 
16250b57cec5SDimitry Andric   // FIXME: If the case list was broken is some way, we don't have a good system
16260b57cec5SDimitry Andric   // to patch it up.  Instead, just return the whole substmt as broken.
16270b57cec5SDimitry Andric   if (CaseListIsErroneous)
16280b57cec5SDimitry Andric     return StmtError();
16290b57cec5SDimitry Andric 
16300b57cec5SDimitry Andric   return SS;
16310b57cec5SDimitry Andric }
16320b57cec5SDimitry Andric 
16330b57cec5SDimitry Andric void
16340b57cec5SDimitry Andric Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
16350b57cec5SDimitry Andric                              Expr *SrcExpr) {
16360b57cec5SDimitry Andric   if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
16370b57cec5SDimitry Andric     return;
16380b57cec5SDimitry Andric 
16390b57cec5SDimitry Andric   if (const EnumType *ET = DstType->getAs<EnumType>())
16400b57cec5SDimitry Andric     if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
16410b57cec5SDimitry Andric         SrcType->isIntegerType()) {
16420b57cec5SDimitry Andric       if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
16430b57cec5SDimitry Andric           SrcExpr->isIntegerConstantExpr(Context)) {
16440b57cec5SDimitry Andric         // Get the bitwidth of the enum value before promotions.
16450b57cec5SDimitry Andric         unsigned DstWidth = Context.getIntWidth(DstType);
16460b57cec5SDimitry Andric         bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
16470b57cec5SDimitry Andric 
16480b57cec5SDimitry Andric         llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
16490b57cec5SDimitry Andric         AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
16500b57cec5SDimitry Andric         const EnumDecl *ED = ET->getDecl();
16510b57cec5SDimitry Andric 
16520b57cec5SDimitry Andric         if (!ED->isClosed())
16530b57cec5SDimitry Andric           return;
16540b57cec5SDimitry Andric 
16550b57cec5SDimitry Andric         if (ED->hasAttr<FlagEnumAttr>()) {
16560b57cec5SDimitry Andric           if (!IsValueInFlagEnum(ED, RhsVal, true))
16570b57cec5SDimitry Andric             Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
16580b57cec5SDimitry Andric               << DstType.getUnqualifiedType();
16590b57cec5SDimitry Andric         } else {
16600b57cec5SDimitry Andric           typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
16610b57cec5SDimitry Andric               EnumValsTy;
16620b57cec5SDimitry Andric           EnumValsTy EnumVals;
16630b57cec5SDimitry Andric 
16640b57cec5SDimitry Andric           // Gather all enum values, set their type and sort them,
16650b57cec5SDimitry Andric           // allowing easier comparison with rhs constant.
16660b57cec5SDimitry Andric           for (auto *EDI : ED->enumerators()) {
16670b57cec5SDimitry Andric             llvm::APSInt Val = EDI->getInitVal();
16680b57cec5SDimitry Andric             AdjustAPSInt(Val, DstWidth, DstIsSigned);
16690b57cec5SDimitry Andric             EnumVals.push_back(std::make_pair(Val, EDI));
16700b57cec5SDimitry Andric           }
16710b57cec5SDimitry Andric           if (EnumVals.empty())
16720b57cec5SDimitry Andric             return;
16730b57cec5SDimitry Andric           llvm::stable_sort(EnumVals, CmpEnumVals);
16740b57cec5SDimitry Andric           EnumValsTy::iterator EIend =
16750b57cec5SDimitry Andric               std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
16760b57cec5SDimitry Andric 
16770b57cec5SDimitry Andric           // See which values aren't in the enum.
16780b57cec5SDimitry Andric           EnumValsTy::const_iterator EI = EnumVals.begin();
16790b57cec5SDimitry Andric           while (EI != EIend && EI->first < RhsVal)
16800b57cec5SDimitry Andric             EI++;
16810b57cec5SDimitry Andric           if (EI == EIend || EI->first != RhsVal) {
16820b57cec5SDimitry Andric             Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
16830b57cec5SDimitry Andric                 << DstType.getUnqualifiedType();
16840b57cec5SDimitry Andric           }
16850b57cec5SDimitry Andric         }
16860b57cec5SDimitry Andric       }
16870b57cec5SDimitry Andric     }
16880b57cec5SDimitry Andric }
16890b57cec5SDimitry Andric 
16905ffd83dbSDimitry Andric StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc,
16915ffd83dbSDimitry Andric                                 SourceLocation LParenLoc, ConditionResult Cond,
16925ffd83dbSDimitry Andric                                 SourceLocation RParenLoc, Stmt *Body) {
16930b57cec5SDimitry Andric   if (Cond.isInvalid())
16940b57cec5SDimitry Andric     return StmtError();
16950b57cec5SDimitry Andric 
16960b57cec5SDimitry Andric   auto CondVal = Cond.get();
16970b57cec5SDimitry Andric   CheckBreakContinueBinding(CondVal.second);
16980b57cec5SDimitry Andric 
16990b57cec5SDimitry Andric   if (CondVal.second &&
17000b57cec5SDimitry Andric       !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc()))
17010b57cec5SDimitry Andric     CommaVisitor(*this).Visit(CondVal.second);
17020b57cec5SDimitry Andric 
17030b57cec5SDimitry Andric   if (isa<NullStmt>(Body))
17040b57cec5SDimitry Andric     getCurCompoundScope().setHasEmptyLoopBodies();
17050b57cec5SDimitry Andric 
17060b57cec5SDimitry Andric   return WhileStmt::Create(Context, CondVal.first, CondVal.second, Body,
17075ffd83dbSDimitry Andric                            WhileLoc, LParenLoc, RParenLoc);
17080b57cec5SDimitry Andric }
17090b57cec5SDimitry Andric 
17100b57cec5SDimitry Andric StmtResult
17110b57cec5SDimitry Andric Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
17120b57cec5SDimitry Andric                   SourceLocation WhileLoc, SourceLocation CondLParen,
17130b57cec5SDimitry Andric                   Expr *Cond, SourceLocation CondRParen) {
17140b57cec5SDimitry Andric   assert(Cond && "ActOnDoStmt(): missing expression");
17150b57cec5SDimitry Andric 
17160b57cec5SDimitry Andric   CheckBreakContinueBinding(Cond);
17170b57cec5SDimitry Andric   ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond);
17180b57cec5SDimitry Andric   if (CondResult.isInvalid())
17190b57cec5SDimitry Andric     return StmtError();
17200b57cec5SDimitry Andric   Cond = CondResult.get();
17210b57cec5SDimitry Andric 
17220b57cec5SDimitry Andric   CondResult = ActOnFinishFullExpr(Cond, DoLoc, /*DiscardedValue*/ false);
17230b57cec5SDimitry Andric   if (CondResult.isInvalid())
17240b57cec5SDimitry Andric     return StmtError();
17250b57cec5SDimitry Andric   Cond = CondResult.get();
17260b57cec5SDimitry Andric 
17270b57cec5SDimitry Andric   // Only call the CommaVisitor for C89 due to differences in scope flags.
17280b57cec5SDimitry Andric   if (Cond && !getLangOpts().C99 && !getLangOpts().CPlusPlus &&
17290b57cec5SDimitry Andric       !Diags.isIgnored(diag::warn_comma_operator, Cond->getExprLoc()))
17300b57cec5SDimitry Andric     CommaVisitor(*this).Visit(Cond);
17310b57cec5SDimitry Andric 
17320b57cec5SDimitry Andric   return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
17330b57cec5SDimitry Andric }
17340b57cec5SDimitry Andric 
17350b57cec5SDimitry Andric namespace {
17360b57cec5SDimitry Andric   // Use SetVector since the diagnostic cares about the ordering of the Decl's.
173706c3fb27SDimitry Andric   using DeclSetVector = llvm::SmallSetVector<VarDecl *, 8>;
17380b57cec5SDimitry Andric 
17390b57cec5SDimitry Andric   // This visitor will traverse a conditional statement and store all
17400b57cec5SDimitry Andric   // the evaluated decls into a vector.  Simple is set to true if none
17410b57cec5SDimitry Andric   // of the excluded constructs are used.
17420b57cec5SDimitry Andric   class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
17430b57cec5SDimitry Andric     DeclSetVector &Decls;
17440b57cec5SDimitry Andric     SmallVectorImpl<SourceRange> &Ranges;
17450b57cec5SDimitry Andric     bool Simple;
17460b57cec5SDimitry Andric   public:
17470b57cec5SDimitry Andric     typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
17480b57cec5SDimitry Andric 
17490b57cec5SDimitry Andric     DeclExtractor(Sema &S, DeclSetVector &Decls,
17500b57cec5SDimitry Andric                   SmallVectorImpl<SourceRange> &Ranges) :
17510b57cec5SDimitry Andric         Inherited(S.Context),
17520b57cec5SDimitry Andric         Decls(Decls),
17530b57cec5SDimitry Andric         Ranges(Ranges),
17540b57cec5SDimitry Andric         Simple(true) {}
17550b57cec5SDimitry Andric 
17560b57cec5SDimitry Andric     bool isSimple() { return Simple; }
17570b57cec5SDimitry Andric 
17580b57cec5SDimitry Andric     // Replaces the method in EvaluatedExprVisitor.
17590b57cec5SDimitry Andric     void VisitMemberExpr(MemberExpr* E) {
17600b57cec5SDimitry Andric       Simple = false;
17610b57cec5SDimitry Andric     }
17620b57cec5SDimitry Andric 
17635ffd83dbSDimitry Andric     // Any Stmt not explicitly listed will cause the condition to be marked
17645ffd83dbSDimitry Andric     // complex.
17655ffd83dbSDimitry Andric     void VisitStmt(Stmt *S) { Simple = false; }
17660b57cec5SDimitry Andric 
17670b57cec5SDimitry Andric     void VisitBinaryOperator(BinaryOperator *E) {
17680b57cec5SDimitry Andric       Visit(E->getLHS());
17690b57cec5SDimitry Andric       Visit(E->getRHS());
17700b57cec5SDimitry Andric     }
17710b57cec5SDimitry Andric 
17720b57cec5SDimitry Andric     void VisitCastExpr(CastExpr *E) {
17730b57cec5SDimitry Andric       Visit(E->getSubExpr());
17740b57cec5SDimitry Andric     }
17750b57cec5SDimitry Andric 
17760b57cec5SDimitry Andric     void VisitUnaryOperator(UnaryOperator *E) {
17770b57cec5SDimitry Andric       // Skip checking conditionals with derefernces.
17780b57cec5SDimitry Andric       if (E->getOpcode() == UO_Deref)
17790b57cec5SDimitry Andric         Simple = false;
17800b57cec5SDimitry Andric       else
17810b57cec5SDimitry Andric         Visit(E->getSubExpr());
17820b57cec5SDimitry Andric     }
17830b57cec5SDimitry Andric 
17840b57cec5SDimitry Andric     void VisitConditionalOperator(ConditionalOperator *E) {
17850b57cec5SDimitry Andric       Visit(E->getCond());
17860b57cec5SDimitry Andric       Visit(E->getTrueExpr());
17870b57cec5SDimitry Andric       Visit(E->getFalseExpr());
17880b57cec5SDimitry Andric     }
17890b57cec5SDimitry Andric 
17900b57cec5SDimitry Andric     void VisitParenExpr(ParenExpr *E) {
17910b57cec5SDimitry Andric       Visit(E->getSubExpr());
17920b57cec5SDimitry Andric     }
17930b57cec5SDimitry Andric 
17940b57cec5SDimitry Andric     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
17950b57cec5SDimitry Andric       Visit(E->getOpaqueValue()->getSourceExpr());
17960b57cec5SDimitry Andric       Visit(E->getFalseExpr());
17970b57cec5SDimitry Andric     }
17980b57cec5SDimitry Andric 
17990b57cec5SDimitry Andric     void VisitIntegerLiteral(IntegerLiteral *E) { }
18000b57cec5SDimitry Andric     void VisitFloatingLiteral(FloatingLiteral *E) { }
18010b57cec5SDimitry Andric     void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
18020b57cec5SDimitry Andric     void VisitCharacterLiteral(CharacterLiteral *E) { }
18030b57cec5SDimitry Andric     void VisitGNUNullExpr(GNUNullExpr *E) { }
18040b57cec5SDimitry Andric     void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
18050b57cec5SDimitry Andric 
18060b57cec5SDimitry Andric     void VisitDeclRefExpr(DeclRefExpr *E) {
18070b57cec5SDimitry Andric       VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
18080b57cec5SDimitry Andric       if (!VD) {
18090b57cec5SDimitry Andric         // Don't allow unhandled Decl types.
18100b57cec5SDimitry Andric         Simple = false;
18110b57cec5SDimitry Andric         return;
18120b57cec5SDimitry Andric       }
18130b57cec5SDimitry Andric 
18140b57cec5SDimitry Andric       Ranges.push_back(E->getSourceRange());
18150b57cec5SDimitry Andric 
18160b57cec5SDimitry Andric       Decls.insert(VD);
18170b57cec5SDimitry Andric     }
18180b57cec5SDimitry Andric 
18190b57cec5SDimitry Andric   }; // end class DeclExtractor
18200b57cec5SDimitry Andric 
18210b57cec5SDimitry Andric   // DeclMatcher checks to see if the decls are used in a non-evaluated
18220b57cec5SDimitry Andric   // context.
18230b57cec5SDimitry Andric   class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
18240b57cec5SDimitry Andric     DeclSetVector &Decls;
18250b57cec5SDimitry Andric     bool FoundDecl;
18260b57cec5SDimitry Andric 
18270b57cec5SDimitry Andric   public:
18280b57cec5SDimitry Andric     typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
18290b57cec5SDimitry Andric 
18300b57cec5SDimitry Andric     DeclMatcher(Sema &S, DeclSetVector &Decls, Stmt *Statement) :
18310b57cec5SDimitry Andric         Inherited(S.Context), Decls(Decls), FoundDecl(false) {
18320b57cec5SDimitry Andric       if (!Statement) return;
18330b57cec5SDimitry Andric 
18340b57cec5SDimitry Andric       Visit(Statement);
18350b57cec5SDimitry Andric     }
18360b57cec5SDimitry Andric 
18370b57cec5SDimitry Andric     void VisitReturnStmt(ReturnStmt *S) {
18380b57cec5SDimitry Andric       FoundDecl = true;
18390b57cec5SDimitry Andric     }
18400b57cec5SDimitry Andric 
18410b57cec5SDimitry Andric     void VisitBreakStmt(BreakStmt *S) {
18420b57cec5SDimitry Andric       FoundDecl = true;
18430b57cec5SDimitry Andric     }
18440b57cec5SDimitry Andric 
18450b57cec5SDimitry Andric     void VisitGotoStmt(GotoStmt *S) {
18460b57cec5SDimitry Andric       FoundDecl = true;
18470b57cec5SDimitry Andric     }
18480b57cec5SDimitry Andric 
18490b57cec5SDimitry Andric     void VisitCastExpr(CastExpr *E) {
18500b57cec5SDimitry Andric       if (E->getCastKind() == CK_LValueToRValue)
18510b57cec5SDimitry Andric         CheckLValueToRValueCast(E->getSubExpr());
18520b57cec5SDimitry Andric       else
18530b57cec5SDimitry Andric         Visit(E->getSubExpr());
18540b57cec5SDimitry Andric     }
18550b57cec5SDimitry Andric 
18560b57cec5SDimitry Andric     void CheckLValueToRValueCast(Expr *E) {
18570b57cec5SDimitry Andric       E = E->IgnoreParenImpCasts();
18580b57cec5SDimitry Andric 
18590b57cec5SDimitry Andric       if (isa<DeclRefExpr>(E)) {
18600b57cec5SDimitry Andric         return;
18610b57cec5SDimitry Andric       }
18620b57cec5SDimitry Andric 
18630b57cec5SDimitry Andric       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
18640b57cec5SDimitry Andric         Visit(CO->getCond());
18650b57cec5SDimitry Andric         CheckLValueToRValueCast(CO->getTrueExpr());
18660b57cec5SDimitry Andric         CheckLValueToRValueCast(CO->getFalseExpr());
18670b57cec5SDimitry Andric         return;
18680b57cec5SDimitry Andric       }
18690b57cec5SDimitry Andric 
18700b57cec5SDimitry Andric       if (BinaryConditionalOperator *BCO =
18710b57cec5SDimitry Andric               dyn_cast<BinaryConditionalOperator>(E)) {
18720b57cec5SDimitry Andric         CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
18730b57cec5SDimitry Andric         CheckLValueToRValueCast(BCO->getFalseExpr());
18740b57cec5SDimitry Andric         return;
18750b57cec5SDimitry Andric       }
18760b57cec5SDimitry Andric 
18770b57cec5SDimitry Andric       Visit(E);
18780b57cec5SDimitry Andric     }
18790b57cec5SDimitry Andric 
18800b57cec5SDimitry Andric     void VisitDeclRefExpr(DeclRefExpr *E) {
18810b57cec5SDimitry Andric       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
18820b57cec5SDimitry Andric         if (Decls.count(VD))
18830b57cec5SDimitry Andric           FoundDecl = true;
18840b57cec5SDimitry Andric     }
18850b57cec5SDimitry Andric 
18860b57cec5SDimitry Andric     void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
18870b57cec5SDimitry Andric       // Only need to visit the semantics for POE.
18880b57cec5SDimitry Andric       // SyntaticForm doesn't really use the Decal.
18890b57cec5SDimitry Andric       for (auto *S : POE->semantics()) {
18900b57cec5SDimitry Andric         if (auto *OVE = dyn_cast<OpaqueValueExpr>(S))
18910b57cec5SDimitry Andric           // Look past the OVE into the expression it binds.
18920b57cec5SDimitry Andric           Visit(OVE->getSourceExpr());
18930b57cec5SDimitry Andric         else
18940b57cec5SDimitry Andric           Visit(S);
18950b57cec5SDimitry Andric       }
18960b57cec5SDimitry Andric     }
18970b57cec5SDimitry Andric 
18980b57cec5SDimitry Andric     bool FoundDeclInUse() { return FoundDecl; }
18990b57cec5SDimitry Andric 
19000b57cec5SDimitry Andric   };  // end class DeclMatcher
19010b57cec5SDimitry Andric 
19020b57cec5SDimitry Andric   void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
19030b57cec5SDimitry Andric                                         Expr *Third, Stmt *Body) {
19040b57cec5SDimitry Andric     // Condition is empty
19050b57cec5SDimitry Andric     if (!Second) return;
19060b57cec5SDimitry Andric 
19070b57cec5SDimitry Andric     if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
19080b57cec5SDimitry Andric                           Second->getBeginLoc()))
19090b57cec5SDimitry Andric       return;
19100b57cec5SDimitry Andric 
19110b57cec5SDimitry Andric     PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
19120b57cec5SDimitry Andric     DeclSetVector Decls;
19130b57cec5SDimitry Andric     SmallVector<SourceRange, 10> Ranges;
19140b57cec5SDimitry Andric     DeclExtractor DE(S, Decls, Ranges);
19150b57cec5SDimitry Andric     DE.Visit(Second);
19160b57cec5SDimitry Andric 
19170b57cec5SDimitry Andric     // Don't analyze complex conditionals.
19180b57cec5SDimitry Andric     if (!DE.isSimple()) return;
19190b57cec5SDimitry Andric 
19200b57cec5SDimitry Andric     // No decls found.
19210b57cec5SDimitry Andric     if (Decls.size() == 0) return;
19220b57cec5SDimitry Andric 
19230b57cec5SDimitry Andric     // Don't warn on volatile, static, or global variables.
19240b57cec5SDimitry Andric     for (auto *VD : Decls)
19250b57cec5SDimitry Andric       if (VD->getType().isVolatileQualified() || VD->hasGlobalStorage())
19260b57cec5SDimitry Andric         return;
19270b57cec5SDimitry Andric 
19280b57cec5SDimitry Andric     if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
19290b57cec5SDimitry Andric         DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
19300b57cec5SDimitry Andric         DeclMatcher(S, Decls, Body).FoundDeclInUse())
19310b57cec5SDimitry Andric       return;
19320b57cec5SDimitry Andric 
19330b57cec5SDimitry Andric     // Load decl names into diagnostic.
19340b57cec5SDimitry Andric     if (Decls.size() > 4) {
19350b57cec5SDimitry Andric       PDiag << 0;
19360b57cec5SDimitry Andric     } else {
19370b57cec5SDimitry Andric       PDiag << (unsigned)Decls.size();
19380b57cec5SDimitry Andric       for (auto *VD : Decls)
19390b57cec5SDimitry Andric         PDiag << VD->getDeclName();
19400b57cec5SDimitry Andric     }
19410b57cec5SDimitry Andric 
19420b57cec5SDimitry Andric     for (auto Range : Ranges)
19430b57cec5SDimitry Andric       PDiag << Range;
19440b57cec5SDimitry Andric 
19450b57cec5SDimitry Andric     S.Diag(Ranges.begin()->getBegin(), PDiag);
19460b57cec5SDimitry Andric   }
19470b57cec5SDimitry Andric 
19480b57cec5SDimitry Andric   // If Statement is an incemement or decrement, return true and sets the
19490b57cec5SDimitry Andric   // variables Increment and DRE.
19500b57cec5SDimitry Andric   bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
19510b57cec5SDimitry Andric                             DeclRefExpr *&DRE) {
19520b57cec5SDimitry Andric     if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement))
19530b57cec5SDimitry Andric       if (!Cleanups->cleanupsHaveSideEffects())
19540b57cec5SDimitry Andric         Statement = Cleanups->getSubExpr();
19550b57cec5SDimitry Andric 
19560b57cec5SDimitry Andric     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
19570b57cec5SDimitry Andric       switch (UO->getOpcode()) {
19580b57cec5SDimitry Andric         default: return false;
19590b57cec5SDimitry Andric         case UO_PostInc:
19600b57cec5SDimitry Andric         case UO_PreInc:
19610b57cec5SDimitry Andric           Increment = true;
19620b57cec5SDimitry Andric           break;
19630b57cec5SDimitry Andric         case UO_PostDec:
19640b57cec5SDimitry Andric         case UO_PreDec:
19650b57cec5SDimitry Andric           Increment = false;
19660b57cec5SDimitry Andric           break;
19670b57cec5SDimitry Andric       }
19680b57cec5SDimitry Andric       DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
19690b57cec5SDimitry Andric       return DRE;
19700b57cec5SDimitry Andric     }
19710b57cec5SDimitry Andric 
19720b57cec5SDimitry Andric     if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
19730b57cec5SDimitry Andric       FunctionDecl *FD = Call->getDirectCallee();
19740b57cec5SDimitry Andric       if (!FD || !FD->isOverloadedOperator()) return false;
19750b57cec5SDimitry Andric       switch (FD->getOverloadedOperator()) {
19760b57cec5SDimitry Andric         default: return false;
19770b57cec5SDimitry Andric         case OO_PlusPlus:
19780b57cec5SDimitry Andric           Increment = true;
19790b57cec5SDimitry Andric           break;
19800b57cec5SDimitry Andric         case OO_MinusMinus:
19810b57cec5SDimitry Andric           Increment = false;
19820b57cec5SDimitry Andric           break;
19830b57cec5SDimitry Andric       }
19840b57cec5SDimitry Andric       DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
19850b57cec5SDimitry Andric       return DRE;
19860b57cec5SDimitry Andric     }
19870b57cec5SDimitry Andric 
19880b57cec5SDimitry Andric     return false;
19890b57cec5SDimitry Andric   }
19900b57cec5SDimitry Andric 
19910b57cec5SDimitry Andric   // A visitor to determine if a continue or break statement is a
19920b57cec5SDimitry Andric   // subexpression.
19930b57cec5SDimitry Andric   class BreakContinueFinder : public ConstEvaluatedExprVisitor<BreakContinueFinder> {
19940b57cec5SDimitry Andric     SourceLocation BreakLoc;
19950b57cec5SDimitry Andric     SourceLocation ContinueLoc;
19960b57cec5SDimitry Andric     bool InSwitch = false;
19970b57cec5SDimitry Andric 
19980b57cec5SDimitry Andric   public:
19990b57cec5SDimitry Andric     BreakContinueFinder(Sema &S, const Stmt* Body) :
20000b57cec5SDimitry Andric         Inherited(S.Context) {
20010b57cec5SDimitry Andric       Visit(Body);
20020b57cec5SDimitry Andric     }
20030b57cec5SDimitry Andric 
20040b57cec5SDimitry Andric     typedef ConstEvaluatedExprVisitor<BreakContinueFinder> Inherited;
20050b57cec5SDimitry Andric 
20060b57cec5SDimitry Andric     void VisitContinueStmt(const ContinueStmt* E) {
20070b57cec5SDimitry Andric       ContinueLoc = E->getContinueLoc();
20080b57cec5SDimitry Andric     }
20090b57cec5SDimitry Andric 
20100b57cec5SDimitry Andric     void VisitBreakStmt(const BreakStmt* E) {
20110b57cec5SDimitry Andric       if (!InSwitch)
20120b57cec5SDimitry Andric         BreakLoc = E->getBreakLoc();
20130b57cec5SDimitry Andric     }
20140b57cec5SDimitry Andric 
20150b57cec5SDimitry Andric     void VisitSwitchStmt(const SwitchStmt* S) {
20160b57cec5SDimitry Andric       if (const Stmt *Init = S->getInit())
20170b57cec5SDimitry Andric         Visit(Init);
20180b57cec5SDimitry Andric       if (const Stmt *CondVar = S->getConditionVariableDeclStmt())
20190b57cec5SDimitry Andric         Visit(CondVar);
20200b57cec5SDimitry Andric       if (const Stmt *Cond = S->getCond())
20210b57cec5SDimitry Andric         Visit(Cond);
20220b57cec5SDimitry Andric 
20230b57cec5SDimitry Andric       // Don't return break statements from the body of a switch.
20240b57cec5SDimitry Andric       InSwitch = true;
20250b57cec5SDimitry Andric       if (const Stmt *Body = S->getBody())
20260b57cec5SDimitry Andric         Visit(Body);
20270b57cec5SDimitry Andric       InSwitch = false;
20280b57cec5SDimitry Andric     }
20290b57cec5SDimitry Andric 
20300b57cec5SDimitry Andric     void VisitForStmt(const ForStmt *S) {
20310b57cec5SDimitry Andric       // Only visit the init statement of a for loop; the body
20320b57cec5SDimitry Andric       // has a different break/continue scope.
20330b57cec5SDimitry Andric       if (const Stmt *Init = S->getInit())
20340b57cec5SDimitry Andric         Visit(Init);
20350b57cec5SDimitry Andric     }
20360b57cec5SDimitry Andric 
20370b57cec5SDimitry Andric     void VisitWhileStmt(const WhileStmt *) {
20380b57cec5SDimitry Andric       // Do nothing; the children of a while loop have a different
20390b57cec5SDimitry Andric       // break/continue scope.
20400b57cec5SDimitry Andric     }
20410b57cec5SDimitry Andric 
20420b57cec5SDimitry Andric     void VisitDoStmt(const DoStmt *) {
20430b57cec5SDimitry Andric       // Do nothing; the children of a while loop have a different
20440b57cec5SDimitry Andric       // break/continue scope.
20450b57cec5SDimitry Andric     }
20460b57cec5SDimitry Andric 
20470b57cec5SDimitry Andric     void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
20480b57cec5SDimitry Andric       // Only visit the initialization of a for loop; the body
20490b57cec5SDimitry Andric       // has a different break/continue scope.
20500b57cec5SDimitry Andric       if (const Stmt *Init = S->getInit())
20510b57cec5SDimitry Andric         Visit(Init);
20520b57cec5SDimitry Andric       if (const Stmt *Range = S->getRangeStmt())
20530b57cec5SDimitry Andric         Visit(Range);
20540b57cec5SDimitry Andric       if (const Stmt *Begin = S->getBeginStmt())
20550b57cec5SDimitry Andric         Visit(Begin);
20560b57cec5SDimitry Andric       if (const Stmt *End = S->getEndStmt())
20570b57cec5SDimitry Andric         Visit(End);
20580b57cec5SDimitry Andric     }
20590b57cec5SDimitry Andric 
20600b57cec5SDimitry Andric     void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
20610b57cec5SDimitry Andric       // Only visit the initialization of a for loop; the body
20620b57cec5SDimitry Andric       // has a different break/continue scope.
20630b57cec5SDimitry Andric       if (const Stmt *Element = S->getElement())
20640b57cec5SDimitry Andric         Visit(Element);
20650b57cec5SDimitry Andric       if (const Stmt *Collection = S->getCollection())
20660b57cec5SDimitry Andric         Visit(Collection);
20670b57cec5SDimitry Andric     }
20680b57cec5SDimitry Andric 
20690b57cec5SDimitry Andric     bool ContinueFound() { return ContinueLoc.isValid(); }
20700b57cec5SDimitry Andric     bool BreakFound() { return BreakLoc.isValid(); }
20710b57cec5SDimitry Andric     SourceLocation GetContinueLoc() { return ContinueLoc; }
20720b57cec5SDimitry Andric     SourceLocation GetBreakLoc() { return BreakLoc; }
20730b57cec5SDimitry Andric 
20740b57cec5SDimitry Andric   };  // end class BreakContinueFinder
20750b57cec5SDimitry Andric 
20760b57cec5SDimitry Andric   // Emit a warning when a loop increment/decrement appears twice per loop
20770b57cec5SDimitry Andric   // iteration.  The conditions which trigger this warning are:
20780b57cec5SDimitry Andric   // 1) The last statement in the loop body and the third expression in the
20790b57cec5SDimitry Andric   //    for loop are both increment or both decrement of the same variable
20800b57cec5SDimitry Andric   // 2) No continue statements in the loop body.
20810b57cec5SDimitry Andric   void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
20820b57cec5SDimitry Andric     // Return when there is nothing to check.
20830b57cec5SDimitry Andric     if (!Body || !Third) return;
20840b57cec5SDimitry Andric 
20850b57cec5SDimitry Andric     if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
20860b57cec5SDimitry Andric                           Third->getBeginLoc()))
20870b57cec5SDimitry Andric       return;
20880b57cec5SDimitry Andric 
20890b57cec5SDimitry Andric     // Get the last statement from the loop body.
20900b57cec5SDimitry Andric     CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
20910b57cec5SDimitry Andric     if (!CS || CS->body_empty()) return;
20920b57cec5SDimitry Andric     Stmt *LastStmt = CS->body_back();
20930b57cec5SDimitry Andric     if (!LastStmt) return;
20940b57cec5SDimitry Andric 
20950b57cec5SDimitry Andric     bool LoopIncrement, LastIncrement;
20960b57cec5SDimitry Andric     DeclRefExpr *LoopDRE, *LastDRE;
20970b57cec5SDimitry Andric 
20980b57cec5SDimitry Andric     if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
20990b57cec5SDimitry Andric     if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
21000b57cec5SDimitry Andric 
21010b57cec5SDimitry Andric     // Check that the two statements are both increments or both decrements
21020b57cec5SDimitry Andric     // on the same variable.
21030b57cec5SDimitry Andric     if (LoopIncrement != LastIncrement ||
21040b57cec5SDimitry Andric         LoopDRE->getDecl() != LastDRE->getDecl()) return;
21050b57cec5SDimitry Andric 
21060b57cec5SDimitry Andric     if (BreakContinueFinder(S, Body).ContinueFound()) return;
21070b57cec5SDimitry Andric 
21080b57cec5SDimitry Andric     S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
21090b57cec5SDimitry Andric          << LastDRE->getDecl() << LastIncrement;
21100b57cec5SDimitry Andric     S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
21110b57cec5SDimitry Andric          << LoopIncrement;
21120b57cec5SDimitry Andric   }
21130b57cec5SDimitry Andric 
21140b57cec5SDimitry Andric } // end namespace
21150b57cec5SDimitry Andric 
21160b57cec5SDimitry Andric 
21170b57cec5SDimitry Andric void Sema::CheckBreakContinueBinding(Expr *E) {
21180b57cec5SDimitry Andric   if (!E || getLangOpts().CPlusPlus)
21190b57cec5SDimitry Andric     return;
21200b57cec5SDimitry Andric   BreakContinueFinder BCFinder(*this, E);
21210b57cec5SDimitry Andric   Scope *BreakParent = CurScope->getBreakParent();
21220b57cec5SDimitry Andric   if (BCFinder.BreakFound() && BreakParent) {
21230b57cec5SDimitry Andric     if (BreakParent->getFlags() & Scope::SwitchScope) {
21240b57cec5SDimitry Andric       Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
21250b57cec5SDimitry Andric     } else {
21260b57cec5SDimitry Andric       Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
21270b57cec5SDimitry Andric           << "break";
21280b57cec5SDimitry Andric     }
21290b57cec5SDimitry Andric   } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
21300b57cec5SDimitry Andric     Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
21310b57cec5SDimitry Andric         << "continue";
21320b57cec5SDimitry Andric   }
21330b57cec5SDimitry Andric }
21340b57cec5SDimitry Andric 
21350b57cec5SDimitry Andric StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
21360b57cec5SDimitry Andric                               Stmt *First, ConditionResult Second,
21370b57cec5SDimitry Andric                               FullExprArg third, SourceLocation RParenLoc,
21380b57cec5SDimitry Andric                               Stmt *Body) {
21390b57cec5SDimitry Andric   if (Second.isInvalid())
21400b57cec5SDimitry Andric     return StmtError();
21410b57cec5SDimitry Andric 
21420b57cec5SDimitry Andric   if (!getLangOpts().CPlusPlus) {
21430b57cec5SDimitry Andric     if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
21440b57cec5SDimitry Andric       // C99 6.8.5p3: The declaration part of a 'for' statement shall only
21450b57cec5SDimitry Andric       // declare identifiers for objects having storage class 'auto' or
21460b57cec5SDimitry Andric       // 'register'.
2147e8d8bef9SDimitry Andric       const Decl *NonVarSeen = nullptr;
2148e8d8bef9SDimitry Andric       bool VarDeclSeen = false;
21490b57cec5SDimitry Andric       for (auto *DI : DS->decls()) {
2150e8d8bef9SDimitry Andric         if (VarDecl *VD = dyn_cast<VarDecl>(DI)) {
2151e8d8bef9SDimitry Andric           VarDeclSeen = true;
2152e8d8bef9SDimitry Andric           if (VD->isLocalVarDecl() && !VD->hasLocalStorage()) {
21530b57cec5SDimitry Andric             Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
21540b57cec5SDimitry Andric             DI->setInvalidDecl();
21550b57cec5SDimitry Andric           }
2156e8d8bef9SDimitry Andric         } else if (!NonVarSeen) {
2157e8d8bef9SDimitry Andric           // Keep track of the first non-variable declaration we saw so that
2158e8d8bef9SDimitry Andric           // we can diagnose if we don't see any variable declarations. This
2159e8d8bef9SDimitry Andric           // covers a case like declaring a typedef, function, or structure
2160e8d8bef9SDimitry Andric           // type rather than a variable.
2161e8d8bef9SDimitry Andric           NonVarSeen = DI;
21620b57cec5SDimitry Andric         }
21630b57cec5SDimitry Andric       }
2164e8d8bef9SDimitry Andric       // Diagnose if we saw a non-variable declaration but no variable
2165e8d8bef9SDimitry Andric       // declarations.
2166e8d8bef9SDimitry Andric       if (NonVarSeen && !VarDeclSeen)
2167e8d8bef9SDimitry Andric         Diag(NonVarSeen->getLocation(), diag::err_non_variable_decl_in_for);
2168e8d8bef9SDimitry Andric     }
21690b57cec5SDimitry Andric   }
21700b57cec5SDimitry Andric 
21710b57cec5SDimitry Andric   CheckBreakContinueBinding(Second.get().second);
21720b57cec5SDimitry Andric   CheckBreakContinueBinding(third.get());
21730b57cec5SDimitry Andric 
21740b57cec5SDimitry Andric   if (!Second.get().first)
21750b57cec5SDimitry Andric     CheckForLoopConditionalStatement(*this, Second.get().second, third.get(),
21760b57cec5SDimitry Andric                                      Body);
21770b57cec5SDimitry Andric   CheckForRedundantIteration(*this, third.get(), Body);
21780b57cec5SDimitry Andric 
21790b57cec5SDimitry Andric   if (Second.get().second &&
21800b57cec5SDimitry Andric       !Diags.isIgnored(diag::warn_comma_operator,
21810b57cec5SDimitry Andric                        Second.get().second->getExprLoc()))
21820b57cec5SDimitry Andric     CommaVisitor(*this).Visit(Second.get().second);
21830b57cec5SDimitry Andric 
21840b57cec5SDimitry Andric   Expr *Third  = third.release().getAs<Expr>();
21850b57cec5SDimitry Andric   if (isa<NullStmt>(Body))
21860b57cec5SDimitry Andric     getCurCompoundScope().setHasEmptyLoopBodies();
21870b57cec5SDimitry Andric 
21880b57cec5SDimitry Andric   return new (Context)
21890b57cec5SDimitry Andric       ForStmt(Context, First, Second.get().second, Second.get().first, Third,
21900b57cec5SDimitry Andric               Body, ForLoc, LParenLoc, RParenLoc);
21910b57cec5SDimitry Andric }
21920b57cec5SDimitry Andric 
21930b57cec5SDimitry Andric /// In an Objective C collection iteration statement:
21940b57cec5SDimitry Andric ///   for (x in y)
21950b57cec5SDimitry Andric /// x can be an arbitrary l-value expression.  Bind it up as a
21960b57cec5SDimitry Andric /// full-expression.
21970b57cec5SDimitry Andric StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
21980b57cec5SDimitry Andric   // Reduce placeholder expressions here.  Note that this rejects the
21990b57cec5SDimitry Andric   // use of pseudo-object l-values in this position.
22000b57cec5SDimitry Andric   ExprResult result = CheckPlaceholderExpr(E);
22010b57cec5SDimitry Andric   if (result.isInvalid()) return StmtError();
22020b57cec5SDimitry Andric   E = result.get();
22030b57cec5SDimitry Andric 
22040b57cec5SDimitry Andric   ExprResult FullExpr = ActOnFinishFullExpr(E, /*DiscardedValue*/ false);
22050b57cec5SDimitry Andric   if (FullExpr.isInvalid())
22060b57cec5SDimitry Andric     return StmtError();
22070b57cec5SDimitry Andric   return StmtResult(static_cast<Stmt*>(FullExpr.get()));
22080b57cec5SDimitry Andric }
22090b57cec5SDimitry Andric 
22100b57cec5SDimitry Andric ExprResult
22110b57cec5SDimitry Andric Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
22120b57cec5SDimitry Andric   if (!collection)
22130b57cec5SDimitry Andric     return ExprError();
22140b57cec5SDimitry Andric 
22150b57cec5SDimitry Andric   ExprResult result = CorrectDelayedTyposInExpr(collection);
22160b57cec5SDimitry Andric   if (!result.isUsable())
22170b57cec5SDimitry Andric     return ExprError();
22180b57cec5SDimitry Andric   collection = result.get();
22190b57cec5SDimitry Andric 
22200b57cec5SDimitry Andric   // Bail out early if we've got a type-dependent expression.
22210b57cec5SDimitry Andric   if (collection->isTypeDependent()) return collection;
22220b57cec5SDimitry Andric 
22230b57cec5SDimitry Andric   // Perform normal l-value conversion.
22240b57cec5SDimitry Andric   result = DefaultFunctionArrayLvalueConversion(collection);
22250b57cec5SDimitry Andric   if (result.isInvalid())
22260b57cec5SDimitry Andric     return ExprError();
22270b57cec5SDimitry Andric   collection = result.get();
22280b57cec5SDimitry Andric 
22290b57cec5SDimitry Andric   // The operand needs to have object-pointer type.
22300b57cec5SDimitry Andric   // TODO: should we do a contextual conversion?
22310b57cec5SDimitry Andric   const ObjCObjectPointerType *pointerType =
22320b57cec5SDimitry Andric     collection->getType()->getAs<ObjCObjectPointerType>();
22330b57cec5SDimitry Andric   if (!pointerType)
22340b57cec5SDimitry Andric     return Diag(forLoc, diag::err_collection_expr_type)
22350b57cec5SDimitry Andric              << collection->getType() << collection->getSourceRange();
22360b57cec5SDimitry Andric 
22370b57cec5SDimitry Andric   // Check that the operand provides
22380b57cec5SDimitry Andric   //   - countByEnumeratingWithState:objects:count:
22390b57cec5SDimitry Andric   const ObjCObjectType *objectType = pointerType->getObjectType();
22400b57cec5SDimitry Andric   ObjCInterfaceDecl *iface = objectType->getInterface();
22410b57cec5SDimitry Andric 
22420b57cec5SDimitry Andric   // If we have a forward-declared type, we can't do this check.
22430b57cec5SDimitry Andric   // Under ARC, it is an error not to have a forward-declared class.
22440b57cec5SDimitry Andric   if (iface &&
22450b57cec5SDimitry Andric       (getLangOpts().ObjCAutoRefCount
22460b57cec5SDimitry Andric            ? RequireCompleteType(forLoc, QualType(objectType, 0),
22470b57cec5SDimitry Andric                                  diag::err_arc_collection_forward, collection)
22480b57cec5SDimitry Andric            : !isCompleteType(forLoc, QualType(objectType, 0)))) {
22490b57cec5SDimitry Andric     // Otherwise, if we have any useful type information, check that
22500b57cec5SDimitry Andric     // the type declares the appropriate method.
22510b57cec5SDimitry Andric   } else if (iface || !objectType->qual_empty()) {
22520b57cec5SDimitry Andric     IdentifierInfo *selectorIdents[] = {
22530b57cec5SDimitry Andric       &Context.Idents.get("countByEnumeratingWithState"),
22540b57cec5SDimitry Andric       &Context.Idents.get("objects"),
22550b57cec5SDimitry Andric       &Context.Idents.get("count")
22560b57cec5SDimitry Andric     };
22570b57cec5SDimitry Andric     Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
22580b57cec5SDimitry Andric 
22590b57cec5SDimitry Andric     ObjCMethodDecl *method = nullptr;
22600b57cec5SDimitry Andric 
22610b57cec5SDimitry Andric     // If there's an interface, look in both the public and private APIs.
22620b57cec5SDimitry Andric     if (iface) {
22630b57cec5SDimitry Andric       method = iface->lookupInstanceMethod(selector);
22640b57cec5SDimitry Andric       if (!method) method = iface->lookupPrivateMethod(selector);
22650b57cec5SDimitry Andric     }
22660b57cec5SDimitry Andric 
22670b57cec5SDimitry Andric     // Also check protocol qualifiers.
22680b57cec5SDimitry Andric     if (!method)
22690b57cec5SDimitry Andric       method = LookupMethodInQualifiedType(selector, pointerType,
22700b57cec5SDimitry Andric                                            /*instance*/ true);
22710b57cec5SDimitry Andric 
22720b57cec5SDimitry Andric     // If we didn't find it anywhere, give up.
22730b57cec5SDimitry Andric     if (!method) {
22740b57cec5SDimitry Andric       Diag(forLoc, diag::warn_collection_expr_type)
22750b57cec5SDimitry Andric         << collection->getType() << selector << collection->getSourceRange();
22760b57cec5SDimitry Andric     }
22770b57cec5SDimitry Andric 
22780b57cec5SDimitry Andric     // TODO: check for an incompatible signature?
22790b57cec5SDimitry Andric   }
22800b57cec5SDimitry Andric 
22810b57cec5SDimitry Andric   // Wrap up any cleanups in the expression.
22820b57cec5SDimitry Andric   return collection;
22830b57cec5SDimitry Andric }
22840b57cec5SDimitry Andric 
22850b57cec5SDimitry Andric StmtResult
22860b57cec5SDimitry Andric Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
22870b57cec5SDimitry Andric                                  Stmt *First, Expr *collection,
22880b57cec5SDimitry Andric                                  SourceLocation RParenLoc) {
22890b57cec5SDimitry Andric   setFunctionHasBranchProtectedScope();
22900b57cec5SDimitry Andric 
22910b57cec5SDimitry Andric   ExprResult CollectionExprResult =
22920b57cec5SDimitry Andric     CheckObjCForCollectionOperand(ForLoc, collection);
22930b57cec5SDimitry Andric 
22940b57cec5SDimitry Andric   if (First) {
22950b57cec5SDimitry Andric     QualType FirstType;
22960b57cec5SDimitry Andric     if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
22970b57cec5SDimitry Andric       if (!DS->isSingleDecl())
22980b57cec5SDimitry Andric         return StmtError(Diag((*DS->decl_begin())->getLocation(),
22990b57cec5SDimitry Andric                          diag::err_toomany_element_decls));
23000b57cec5SDimitry Andric 
23010b57cec5SDimitry Andric       VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
23020b57cec5SDimitry Andric       if (!D || D->isInvalidDecl())
23030b57cec5SDimitry Andric         return StmtError();
23040b57cec5SDimitry Andric 
23050b57cec5SDimitry Andric       FirstType = D->getType();
23060b57cec5SDimitry Andric       // C99 6.8.5p3: The declaration part of a 'for' statement shall only
23070b57cec5SDimitry Andric       // declare identifiers for objects having storage class 'auto' or
23080b57cec5SDimitry Andric       // 'register'.
23090b57cec5SDimitry Andric       if (!D->hasLocalStorage())
23100b57cec5SDimitry Andric         return StmtError(Diag(D->getLocation(),
23110b57cec5SDimitry Andric                               diag::err_non_local_variable_decl_in_for));
23120b57cec5SDimitry Andric 
23130b57cec5SDimitry Andric       // If the type contained 'auto', deduce the 'auto' to 'id'.
23140b57cec5SDimitry Andric       if (FirstType->getContainedAutoType()) {
2315bdd1243dSDimitry Andric         SourceLocation Loc = D->getLocation();
2316bdd1243dSDimitry Andric         OpaqueValueExpr OpaqueId(Loc, Context.getObjCIdType(), VK_PRValue);
23170b57cec5SDimitry Andric         Expr *DeducedInit = &OpaqueId;
2318bdd1243dSDimitry Andric         TemplateDeductionInfo Info(Loc);
2319bdd1243dSDimitry Andric         FirstType = QualType();
2320bdd1243dSDimitry Andric         TemplateDeductionResult Result = DeduceAutoType(
2321bdd1243dSDimitry Andric             D->getTypeSourceInfo()->getTypeLoc(), DeducedInit, FirstType, Info);
2322bdd1243dSDimitry Andric         if (Result != TDK_Success && Result != TDK_AlreadyDiagnosed)
23230b57cec5SDimitry Andric           DiagnoseAutoDeductionFailure(D, DeducedInit);
23240b57cec5SDimitry Andric         if (FirstType.isNull()) {
23250b57cec5SDimitry Andric           D->setInvalidDecl();
23260b57cec5SDimitry Andric           return StmtError();
23270b57cec5SDimitry Andric         }
23280b57cec5SDimitry Andric 
23290b57cec5SDimitry Andric         D->setType(FirstType);
23300b57cec5SDimitry Andric 
23310b57cec5SDimitry Andric         if (!inTemplateInstantiation()) {
23320b57cec5SDimitry Andric           SourceLocation Loc =
23330b57cec5SDimitry Andric               D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
23340b57cec5SDimitry Andric           Diag(Loc, diag::warn_auto_var_is_id)
23350b57cec5SDimitry Andric             << D->getDeclName();
23360b57cec5SDimitry Andric         }
23370b57cec5SDimitry Andric       }
23380b57cec5SDimitry Andric 
23390b57cec5SDimitry Andric     } else {
23400b57cec5SDimitry Andric       Expr *FirstE = cast<Expr>(First);
23410b57cec5SDimitry Andric       if (!FirstE->isTypeDependent() && !FirstE->isLValue())
23420b57cec5SDimitry Andric         return StmtError(
23430b57cec5SDimitry Andric             Diag(First->getBeginLoc(), diag::err_selector_element_not_lvalue)
23440b57cec5SDimitry Andric             << First->getSourceRange());
23450b57cec5SDimitry Andric 
23460b57cec5SDimitry Andric       FirstType = static_cast<Expr*>(First)->getType();
23470b57cec5SDimitry Andric       if (FirstType.isConstQualified())
23480b57cec5SDimitry Andric         Diag(ForLoc, diag::err_selector_element_const_type)
23490b57cec5SDimitry Andric           << FirstType << First->getSourceRange();
23500b57cec5SDimitry Andric     }
23510b57cec5SDimitry Andric     if (!FirstType->isDependentType() &&
23520b57cec5SDimitry Andric         !FirstType->isObjCObjectPointerType() &&
23530b57cec5SDimitry Andric         !FirstType->isBlockPointerType())
23540b57cec5SDimitry Andric         return StmtError(Diag(ForLoc, diag::err_selector_element_type)
23550b57cec5SDimitry Andric                            << FirstType << First->getSourceRange());
23560b57cec5SDimitry Andric   }
23570b57cec5SDimitry Andric 
23580b57cec5SDimitry Andric   if (CollectionExprResult.isInvalid())
23590b57cec5SDimitry Andric     return StmtError();
23600b57cec5SDimitry Andric 
23610b57cec5SDimitry Andric   CollectionExprResult =
23620b57cec5SDimitry Andric       ActOnFinishFullExpr(CollectionExprResult.get(), /*DiscardedValue*/ false);
23630b57cec5SDimitry Andric   if (CollectionExprResult.isInvalid())
23640b57cec5SDimitry Andric     return StmtError();
23650b57cec5SDimitry Andric 
23660b57cec5SDimitry Andric   return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
23670b57cec5SDimitry Andric                                              nullptr, ForLoc, RParenLoc);
23680b57cec5SDimitry Andric }
23690b57cec5SDimitry Andric 
23700b57cec5SDimitry Andric /// Finish building a variable declaration for a for-range statement.
23710b57cec5SDimitry Andric /// \return true if an error occurs.
23720b57cec5SDimitry Andric static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
23730b57cec5SDimitry Andric                                   SourceLocation Loc, int DiagID) {
23740b57cec5SDimitry Andric   if (Decl->getType()->isUndeducedType()) {
23750b57cec5SDimitry Andric     ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
23760b57cec5SDimitry Andric     if (!Res.isUsable()) {
23770b57cec5SDimitry Andric       Decl->setInvalidDecl();
23780b57cec5SDimitry Andric       return true;
23790b57cec5SDimitry Andric     }
23800b57cec5SDimitry Andric     Init = Res.get();
23810b57cec5SDimitry Andric   }
23820b57cec5SDimitry Andric 
23830b57cec5SDimitry Andric   // Deduce the type for the iterator variable now rather than leaving it to
23840b57cec5SDimitry Andric   // AddInitializerToDecl, so we can produce a more suitable diagnostic.
23850b57cec5SDimitry Andric   QualType InitType;
2386bdd1243dSDimitry Andric   if (!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) {
23870b57cec5SDimitry Andric     SemaRef.Diag(Loc, DiagID) << Init->getType();
2388bdd1243dSDimitry Andric   } else {
2389bdd1243dSDimitry Andric     TemplateDeductionInfo Info(Init->getExprLoc());
2390bdd1243dSDimitry Andric     Sema::TemplateDeductionResult Result = SemaRef.DeduceAutoType(
2391bdd1243dSDimitry Andric         Decl->getTypeSourceInfo()->getTypeLoc(), Init, InitType, Info);
2392bdd1243dSDimitry Andric     if (Result != Sema::TDK_Success && Result != Sema::TDK_AlreadyDiagnosed)
2393bdd1243dSDimitry Andric       SemaRef.Diag(Loc, DiagID) << Init->getType();
2394bdd1243dSDimitry Andric   }
2395bdd1243dSDimitry Andric 
23960b57cec5SDimitry Andric   if (InitType.isNull()) {
23970b57cec5SDimitry Andric     Decl->setInvalidDecl();
23980b57cec5SDimitry Andric     return true;
23990b57cec5SDimitry Andric   }
24000b57cec5SDimitry Andric   Decl->setType(InitType);
24010b57cec5SDimitry Andric 
24020b57cec5SDimitry Andric   // In ARC, infer lifetime.
24030b57cec5SDimitry Andric   // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
24040b57cec5SDimitry Andric   // we're doing the equivalent of fast iteration.
24050b57cec5SDimitry Andric   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
24060b57cec5SDimitry Andric       SemaRef.inferObjCARCLifetime(Decl))
24070b57cec5SDimitry Andric     Decl->setInvalidDecl();
24080b57cec5SDimitry Andric 
24090b57cec5SDimitry Andric   SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false);
24100b57cec5SDimitry Andric   SemaRef.FinalizeDeclaration(Decl);
24110b57cec5SDimitry Andric   SemaRef.CurContext->addHiddenDecl(Decl);
24120b57cec5SDimitry Andric   return false;
24130b57cec5SDimitry Andric }
24140b57cec5SDimitry Andric 
24150b57cec5SDimitry Andric namespace {
24160b57cec5SDimitry Andric // An enum to represent whether something is dealing with a call to begin()
24170b57cec5SDimitry Andric // or a call to end() in a range-based for loop.
24180b57cec5SDimitry Andric enum BeginEndFunction {
24190b57cec5SDimitry Andric   BEF_begin,
24200b57cec5SDimitry Andric   BEF_end
24210b57cec5SDimitry Andric };
24220b57cec5SDimitry Andric 
24230b57cec5SDimitry Andric /// Produce a note indicating which begin/end function was implicitly called
24240b57cec5SDimitry Andric /// by a C++11 for-range statement. This is often not obvious from the code,
24250b57cec5SDimitry Andric /// nor from the diagnostics produced when analysing the implicit expressions
24260b57cec5SDimitry Andric /// required in a for-range statement.
24270b57cec5SDimitry Andric void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
24280b57cec5SDimitry Andric                                   BeginEndFunction BEF) {
24290b57cec5SDimitry Andric   CallExpr *CE = dyn_cast<CallExpr>(E);
24300b57cec5SDimitry Andric   if (!CE)
24310b57cec5SDimitry Andric     return;
24320b57cec5SDimitry Andric   FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
24330b57cec5SDimitry Andric   if (!D)
24340b57cec5SDimitry Andric     return;
24350b57cec5SDimitry Andric   SourceLocation Loc = D->getLocation();
24360b57cec5SDimitry Andric 
24370b57cec5SDimitry Andric   std::string Description;
24380b57cec5SDimitry Andric   bool IsTemplate = false;
24390b57cec5SDimitry Andric   if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
24400b57cec5SDimitry Andric     Description = SemaRef.getTemplateArgumentBindingsText(
24410b57cec5SDimitry Andric       FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
24420b57cec5SDimitry Andric     IsTemplate = true;
24430b57cec5SDimitry Andric   }
24440b57cec5SDimitry Andric 
24450b57cec5SDimitry Andric   SemaRef.Diag(Loc, diag::note_for_range_begin_end)
24460b57cec5SDimitry Andric     << BEF << IsTemplate << Description << E->getType();
24470b57cec5SDimitry Andric }
24480b57cec5SDimitry Andric 
24490b57cec5SDimitry Andric /// Build a variable declaration for a for-range statement.
24500b57cec5SDimitry Andric VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
24510b57cec5SDimitry Andric                               QualType Type, StringRef Name) {
24520b57cec5SDimitry Andric   DeclContext *DC = SemaRef.CurContext;
24530b57cec5SDimitry Andric   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
24540b57cec5SDimitry Andric   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
24550b57cec5SDimitry Andric   VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
24560b57cec5SDimitry Andric                                   TInfo, SC_None);
24570b57cec5SDimitry Andric   Decl->setImplicit();
24580b57cec5SDimitry Andric   return Decl;
24590b57cec5SDimitry Andric }
24600b57cec5SDimitry Andric 
24610b57cec5SDimitry Andric }
24620b57cec5SDimitry Andric 
24630b57cec5SDimitry Andric static bool ObjCEnumerationCollection(Expr *Collection) {
24640b57cec5SDimitry Andric   return !Collection->isTypeDependent()
24650b57cec5SDimitry Andric           && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
24660b57cec5SDimitry Andric }
24670b57cec5SDimitry Andric 
24680b57cec5SDimitry Andric /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
24690b57cec5SDimitry Andric ///
24700b57cec5SDimitry Andric /// C++11 [stmt.ranged]:
24710b57cec5SDimitry Andric ///   A range-based for statement is equivalent to
24720b57cec5SDimitry Andric ///
24730b57cec5SDimitry Andric ///   {
24740b57cec5SDimitry Andric ///     auto && __range = range-init;
24750b57cec5SDimitry Andric ///     for ( auto __begin = begin-expr,
24760b57cec5SDimitry Andric ///           __end = end-expr;
24770b57cec5SDimitry Andric ///           __begin != __end;
24780b57cec5SDimitry Andric ///           ++__begin ) {
24790b57cec5SDimitry Andric ///       for-range-declaration = *__begin;
24800b57cec5SDimitry Andric ///       statement
24810b57cec5SDimitry Andric ///     }
24820b57cec5SDimitry Andric ///   }
24830b57cec5SDimitry Andric ///
24840b57cec5SDimitry Andric /// The body of the loop is not available yet, since it cannot be analysed until
24850b57cec5SDimitry Andric /// we have determined the type of the for-range-declaration.
24860b57cec5SDimitry Andric StmtResult Sema::ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
24870b57cec5SDimitry Andric                                       SourceLocation CoawaitLoc, Stmt *InitStmt,
24880b57cec5SDimitry Andric                                       Stmt *First, SourceLocation ColonLoc,
24890b57cec5SDimitry Andric                                       Expr *Range, SourceLocation RParenLoc,
24900b57cec5SDimitry Andric                                       BuildForRangeKind Kind) {
249104eeddc0SDimitry Andric   // FIXME: recover in order to allow the body to be parsed.
24920b57cec5SDimitry Andric   if (!First)
24930b57cec5SDimitry Andric     return StmtError();
24940b57cec5SDimitry Andric 
24950b57cec5SDimitry Andric   if (Range && ObjCEnumerationCollection(Range)) {
24960b57cec5SDimitry Andric     // FIXME: Support init-statements in Objective-C++20 ranged for statement.
24970b57cec5SDimitry Andric     if (InitStmt)
24980b57cec5SDimitry Andric       return Diag(InitStmt->getBeginLoc(), diag::err_objc_for_range_init_stmt)
24990b57cec5SDimitry Andric                  << InitStmt->getSourceRange();
25000b57cec5SDimitry Andric     return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
25010b57cec5SDimitry Andric   }
25020b57cec5SDimitry Andric 
25030b57cec5SDimitry Andric   DeclStmt *DS = dyn_cast<DeclStmt>(First);
25040b57cec5SDimitry Andric   assert(DS && "first part of for range not a decl stmt");
25050b57cec5SDimitry Andric 
25060b57cec5SDimitry Andric   if (!DS->isSingleDecl()) {
25070b57cec5SDimitry Andric     Diag(DS->getBeginLoc(), diag::err_type_defined_in_for_range);
25080b57cec5SDimitry Andric     return StmtError();
25090b57cec5SDimitry Andric   }
25100b57cec5SDimitry Andric 
25115ffd83dbSDimitry Andric   // This function is responsible for attaching an initializer to LoopVar. We
25125ffd83dbSDimitry Andric   // must call ActOnInitializerError if we fail to do so.
25130b57cec5SDimitry Andric   Decl *LoopVar = DS->getSingleDecl();
25140b57cec5SDimitry Andric   if (LoopVar->isInvalidDecl() || !Range ||
25150b57cec5SDimitry Andric       DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
25165ffd83dbSDimitry Andric     ActOnInitializerError(LoopVar);
25170b57cec5SDimitry Andric     return StmtError();
25180b57cec5SDimitry Andric   }
25190b57cec5SDimitry Andric 
25200b57cec5SDimitry Andric   // Build the coroutine state immediately and not later during template
25210b57cec5SDimitry Andric   // instantiation
25220b57cec5SDimitry Andric   if (!CoawaitLoc.isInvalid()) {
25235ffd83dbSDimitry Andric     if (!ActOnCoroutineBodyStart(S, CoawaitLoc, "co_await")) {
25245ffd83dbSDimitry Andric       ActOnInitializerError(LoopVar);
25250b57cec5SDimitry Andric       return StmtError();
25260b57cec5SDimitry Andric     }
25275ffd83dbSDimitry Andric   }
25280b57cec5SDimitry Andric 
25290b57cec5SDimitry Andric   // Build  auto && __range = range-init
25300b57cec5SDimitry Andric   // Divide by 2, since the variables are in the inner scope (loop body).
25310b57cec5SDimitry Andric   const auto DepthStr = std::to_string(S->getDepth() / 2);
25320b57cec5SDimitry Andric   SourceLocation RangeLoc = Range->getBeginLoc();
25330b57cec5SDimitry Andric   VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
25340b57cec5SDimitry Andric                                            Context.getAutoRRefDeductType(),
25350b57cec5SDimitry Andric                                            std::string("__range") + DepthStr);
25360b57cec5SDimitry Andric   if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
25370b57cec5SDimitry Andric                             diag::err_for_range_deduction_failure)) {
25385ffd83dbSDimitry Andric     ActOnInitializerError(LoopVar);
25390b57cec5SDimitry Andric     return StmtError();
25400b57cec5SDimitry Andric   }
25410b57cec5SDimitry Andric 
25420b57cec5SDimitry Andric   // Claim the type doesn't contain auto: we've already done the checking.
25430b57cec5SDimitry Andric   DeclGroupPtrTy RangeGroup =
25440b57cec5SDimitry Andric       BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1));
25450b57cec5SDimitry Andric   StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
25460b57cec5SDimitry Andric   if (RangeDecl.isInvalid()) {
25475ffd83dbSDimitry Andric     ActOnInitializerError(LoopVar);
25480b57cec5SDimitry Andric     return StmtError();
25490b57cec5SDimitry Andric   }
25500b57cec5SDimitry Andric 
25515ffd83dbSDimitry Andric   StmtResult R = BuildCXXForRangeStmt(
25520b57cec5SDimitry Andric       ForLoc, CoawaitLoc, InitStmt, ColonLoc, RangeDecl.get(),
25530b57cec5SDimitry Andric       /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
25540b57cec5SDimitry Andric       /*Cond=*/nullptr, /*Inc=*/nullptr, DS, RParenLoc, Kind);
25555ffd83dbSDimitry Andric   if (R.isInvalid()) {
25565ffd83dbSDimitry Andric     ActOnInitializerError(LoopVar);
25575ffd83dbSDimitry Andric     return StmtError();
25585ffd83dbSDimitry Andric   }
25595ffd83dbSDimitry Andric 
25605ffd83dbSDimitry Andric   return R;
25610b57cec5SDimitry Andric }
25620b57cec5SDimitry Andric 
25630b57cec5SDimitry Andric /// Create the initialization, compare, and increment steps for
25640b57cec5SDimitry Andric /// the range-based for loop expression.
25650b57cec5SDimitry Andric /// This function does not handle array-based for loops,
25660b57cec5SDimitry Andric /// which are created in Sema::BuildCXXForRangeStmt.
25670b57cec5SDimitry Andric ///
25680b57cec5SDimitry Andric /// \returns a ForRangeStatus indicating success or what kind of error occurred.
25690b57cec5SDimitry Andric /// BeginExpr and EndExpr are set and FRS_Success is returned on success;
25700b57cec5SDimitry Andric /// CandidateSet and BEF are set and some non-success value is returned on
25710b57cec5SDimitry Andric /// failure.
25720b57cec5SDimitry Andric static Sema::ForRangeStatus
25730b57cec5SDimitry Andric BuildNonArrayForRange(Sema &SemaRef, Expr *BeginRange, Expr *EndRange,
25740b57cec5SDimitry Andric                       QualType RangeType, VarDecl *BeginVar, VarDecl *EndVar,
25750b57cec5SDimitry Andric                       SourceLocation ColonLoc, SourceLocation CoawaitLoc,
25760b57cec5SDimitry Andric                       OverloadCandidateSet *CandidateSet, ExprResult *BeginExpr,
25770b57cec5SDimitry Andric                       ExprResult *EndExpr, BeginEndFunction *BEF) {
25780b57cec5SDimitry Andric   DeclarationNameInfo BeginNameInfo(
25790b57cec5SDimitry Andric       &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
25800b57cec5SDimitry Andric   DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
25810b57cec5SDimitry Andric                                   ColonLoc);
25820b57cec5SDimitry Andric 
25830b57cec5SDimitry Andric   LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
25840b57cec5SDimitry Andric                                  Sema::LookupMemberName);
25850b57cec5SDimitry Andric   LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
25860b57cec5SDimitry Andric 
25870b57cec5SDimitry Andric   auto BuildBegin = [&] {
25880b57cec5SDimitry Andric     *BEF = BEF_begin;
25890b57cec5SDimitry Andric     Sema::ForRangeStatus RangeStatus =
25900b57cec5SDimitry Andric         SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
25910b57cec5SDimitry Andric                                           BeginMemberLookup, CandidateSet,
25920b57cec5SDimitry Andric                                           BeginRange, BeginExpr);
25930b57cec5SDimitry Andric 
25940b57cec5SDimitry Andric     if (RangeStatus != Sema::FRS_Success) {
25950b57cec5SDimitry Andric       if (RangeStatus == Sema::FRS_DiagnosticIssued)
25960b57cec5SDimitry Andric         SemaRef.Diag(BeginRange->getBeginLoc(), diag::note_in_for_range)
25970b57cec5SDimitry Andric             << ColonLoc << BEF_begin << BeginRange->getType();
25980b57cec5SDimitry Andric       return RangeStatus;
25990b57cec5SDimitry Andric     }
26000b57cec5SDimitry Andric     if (!CoawaitLoc.isInvalid()) {
26010b57cec5SDimitry Andric       // FIXME: getCurScope() should not be used during template instantiation.
26020b57cec5SDimitry Andric       // We should pick up the set of unqualified lookup results for operator
26030b57cec5SDimitry Andric       // co_await during the initial parse.
26040b57cec5SDimitry Andric       *BeginExpr = SemaRef.ActOnCoawaitExpr(SemaRef.getCurScope(), ColonLoc,
26050b57cec5SDimitry Andric                                             BeginExpr->get());
26060b57cec5SDimitry Andric       if (BeginExpr->isInvalid())
26070b57cec5SDimitry Andric         return Sema::FRS_DiagnosticIssued;
26080b57cec5SDimitry Andric     }
26090b57cec5SDimitry Andric     if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
26100b57cec5SDimitry Andric                               diag::err_for_range_iter_deduction_failure)) {
26110b57cec5SDimitry Andric       NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
26120b57cec5SDimitry Andric       return Sema::FRS_DiagnosticIssued;
26130b57cec5SDimitry Andric     }
26140b57cec5SDimitry Andric     return Sema::FRS_Success;
26150b57cec5SDimitry Andric   };
26160b57cec5SDimitry Andric 
26170b57cec5SDimitry Andric   auto BuildEnd = [&] {
26180b57cec5SDimitry Andric     *BEF = BEF_end;
26190b57cec5SDimitry Andric     Sema::ForRangeStatus RangeStatus =
26200b57cec5SDimitry Andric         SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
26210b57cec5SDimitry Andric                                           EndMemberLookup, CandidateSet,
26220b57cec5SDimitry Andric                                           EndRange, EndExpr);
26230b57cec5SDimitry Andric     if (RangeStatus != Sema::FRS_Success) {
26240b57cec5SDimitry Andric       if (RangeStatus == Sema::FRS_DiagnosticIssued)
26250b57cec5SDimitry Andric         SemaRef.Diag(EndRange->getBeginLoc(), diag::note_in_for_range)
26260b57cec5SDimitry Andric             << ColonLoc << BEF_end << EndRange->getType();
26270b57cec5SDimitry Andric       return RangeStatus;
26280b57cec5SDimitry Andric     }
26290b57cec5SDimitry Andric     if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
26300b57cec5SDimitry Andric                               diag::err_for_range_iter_deduction_failure)) {
26310b57cec5SDimitry Andric       NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
26320b57cec5SDimitry Andric       return Sema::FRS_DiagnosticIssued;
26330b57cec5SDimitry Andric     }
26340b57cec5SDimitry Andric     return Sema::FRS_Success;
26350b57cec5SDimitry Andric   };
26360b57cec5SDimitry Andric 
26370b57cec5SDimitry Andric   if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
26380b57cec5SDimitry Andric     // - if _RangeT is a class type, the unqualified-ids begin and end are
26390b57cec5SDimitry Andric     //   looked up in the scope of class _RangeT as if by class member access
26400b57cec5SDimitry Andric     //   lookup (3.4.5), and if either (or both) finds at least one
26410b57cec5SDimitry Andric     //   declaration, begin-expr and end-expr are __range.begin() and
26420b57cec5SDimitry Andric     //   __range.end(), respectively;
26430b57cec5SDimitry Andric     SemaRef.LookupQualifiedName(BeginMemberLookup, D);
26440b57cec5SDimitry Andric     if (BeginMemberLookup.isAmbiguous())
26450b57cec5SDimitry Andric       return Sema::FRS_DiagnosticIssued;
26460b57cec5SDimitry Andric 
26470b57cec5SDimitry Andric     SemaRef.LookupQualifiedName(EndMemberLookup, D);
26480b57cec5SDimitry Andric     if (EndMemberLookup.isAmbiguous())
26490b57cec5SDimitry Andric       return Sema::FRS_DiagnosticIssued;
26500b57cec5SDimitry Andric 
26510b57cec5SDimitry Andric     if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
26520b57cec5SDimitry Andric       // Look up the non-member form of the member we didn't find, first.
26530b57cec5SDimitry Andric       // This way we prefer a "no viable 'end'" diagnostic over a "i found
26540b57cec5SDimitry Andric       // a 'begin' but ignored it because there was no member 'end'"
26550b57cec5SDimitry Andric       // diagnostic.
26560b57cec5SDimitry Andric       auto BuildNonmember = [&](
26570b57cec5SDimitry Andric           BeginEndFunction BEFFound, LookupResult &Found,
26580b57cec5SDimitry Andric           llvm::function_ref<Sema::ForRangeStatus()> BuildFound,
26590b57cec5SDimitry Andric           llvm::function_ref<Sema::ForRangeStatus()> BuildNotFound) {
26600b57cec5SDimitry Andric         LookupResult OldFound = std::move(Found);
26610b57cec5SDimitry Andric         Found.clear();
26620b57cec5SDimitry Andric 
26630b57cec5SDimitry Andric         if (Sema::ForRangeStatus Result = BuildNotFound())
26640b57cec5SDimitry Andric           return Result;
26650b57cec5SDimitry Andric 
26660b57cec5SDimitry Andric         switch (BuildFound()) {
26670b57cec5SDimitry Andric         case Sema::FRS_Success:
26680b57cec5SDimitry Andric           return Sema::FRS_Success;
26690b57cec5SDimitry Andric 
26700b57cec5SDimitry Andric         case Sema::FRS_NoViableFunction:
26710b57cec5SDimitry Andric           CandidateSet->NoteCandidates(
26720b57cec5SDimitry Andric               PartialDiagnosticAt(BeginRange->getBeginLoc(),
26730b57cec5SDimitry Andric                                   SemaRef.PDiag(diag::err_for_range_invalid)
26740b57cec5SDimitry Andric                                       << BeginRange->getType() << BEFFound),
26750b57cec5SDimitry Andric               SemaRef, OCD_AllCandidates, BeginRange);
2676bdd1243dSDimitry Andric           [[fallthrough]];
26770b57cec5SDimitry Andric 
26780b57cec5SDimitry Andric         case Sema::FRS_DiagnosticIssued:
26790b57cec5SDimitry Andric           for (NamedDecl *D : OldFound) {
26800b57cec5SDimitry Andric             SemaRef.Diag(D->getLocation(),
26810b57cec5SDimitry Andric                          diag::note_for_range_member_begin_end_ignored)
26820b57cec5SDimitry Andric                 << BeginRange->getType() << BEFFound;
26830b57cec5SDimitry Andric           }
26840b57cec5SDimitry Andric           return Sema::FRS_DiagnosticIssued;
26850b57cec5SDimitry Andric         }
26860b57cec5SDimitry Andric         llvm_unreachable("unexpected ForRangeStatus");
26870b57cec5SDimitry Andric       };
26880b57cec5SDimitry Andric       if (BeginMemberLookup.empty())
26890b57cec5SDimitry Andric         return BuildNonmember(BEF_end, EndMemberLookup, BuildEnd, BuildBegin);
26900b57cec5SDimitry Andric       return BuildNonmember(BEF_begin, BeginMemberLookup, BuildBegin, BuildEnd);
26910b57cec5SDimitry Andric     }
26920b57cec5SDimitry Andric   } else {
26930b57cec5SDimitry Andric     // - otherwise, begin-expr and end-expr are begin(__range) and
26940b57cec5SDimitry Andric     //   end(__range), respectively, where begin and end are looked up with
26950b57cec5SDimitry Andric     //   argument-dependent lookup (3.4.2). For the purposes of this name
26960b57cec5SDimitry Andric     //   lookup, namespace std is an associated namespace.
26970b57cec5SDimitry Andric   }
26980b57cec5SDimitry Andric 
26990b57cec5SDimitry Andric   if (Sema::ForRangeStatus Result = BuildBegin())
27000b57cec5SDimitry Andric     return Result;
27010b57cec5SDimitry Andric   return BuildEnd();
27020b57cec5SDimitry Andric }
27030b57cec5SDimitry Andric 
27040b57cec5SDimitry Andric /// Speculatively attempt to dereference an invalid range expression.
27050b57cec5SDimitry Andric /// If the attempt fails, this function will return a valid, null StmtResult
27060b57cec5SDimitry Andric /// and emit no diagnostics.
27070b57cec5SDimitry Andric static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
27080b57cec5SDimitry Andric                                                  SourceLocation ForLoc,
27090b57cec5SDimitry Andric                                                  SourceLocation CoawaitLoc,
27100b57cec5SDimitry Andric                                                  Stmt *InitStmt,
27110b57cec5SDimitry Andric                                                  Stmt *LoopVarDecl,
27120b57cec5SDimitry Andric                                                  SourceLocation ColonLoc,
27130b57cec5SDimitry Andric                                                  Expr *Range,
27140b57cec5SDimitry Andric                                                  SourceLocation RangeLoc,
27150b57cec5SDimitry Andric                                                  SourceLocation RParenLoc) {
27160b57cec5SDimitry Andric   // Determine whether we can rebuild the for-range statement with a
27170b57cec5SDimitry Andric   // dereferenced range expression.
27180b57cec5SDimitry Andric   ExprResult AdjustedRange;
27190b57cec5SDimitry Andric   {
27200b57cec5SDimitry Andric     Sema::SFINAETrap Trap(SemaRef);
27210b57cec5SDimitry Andric 
27220b57cec5SDimitry Andric     AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
27230b57cec5SDimitry Andric     if (AdjustedRange.isInvalid())
27240b57cec5SDimitry Andric       return StmtResult();
27250b57cec5SDimitry Andric 
27260b57cec5SDimitry Andric     StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
27270b57cec5SDimitry Andric         S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
27280b57cec5SDimitry Andric         AdjustedRange.get(), RParenLoc, Sema::BFRK_Check);
27290b57cec5SDimitry Andric     if (SR.isInvalid())
27300b57cec5SDimitry Andric       return StmtResult();
27310b57cec5SDimitry Andric   }
27320b57cec5SDimitry Andric 
27330b57cec5SDimitry Andric   // The attempt to dereference worked well enough that it could produce a valid
27340b57cec5SDimitry Andric   // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
27350b57cec5SDimitry Andric   // case there are any other (non-fatal) problems with it.
27360b57cec5SDimitry Andric   SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
27370b57cec5SDimitry Andric     << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
27380b57cec5SDimitry Andric   return SemaRef.ActOnCXXForRangeStmt(
27390b57cec5SDimitry Andric       S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
27400b57cec5SDimitry Andric       AdjustedRange.get(), RParenLoc, Sema::BFRK_Rebuild);
27410b57cec5SDimitry Andric }
27420b57cec5SDimitry Andric 
27430b57cec5SDimitry Andric /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
27440b57cec5SDimitry Andric StmtResult Sema::BuildCXXForRangeStmt(SourceLocation ForLoc,
27450b57cec5SDimitry Andric                                       SourceLocation CoawaitLoc, Stmt *InitStmt,
27460b57cec5SDimitry Andric                                       SourceLocation ColonLoc, Stmt *RangeDecl,
27470b57cec5SDimitry Andric                                       Stmt *Begin, Stmt *End, Expr *Cond,
27480b57cec5SDimitry Andric                                       Expr *Inc, Stmt *LoopVarDecl,
27490b57cec5SDimitry Andric                                       SourceLocation RParenLoc,
27500b57cec5SDimitry Andric                                       BuildForRangeKind Kind) {
27510b57cec5SDimitry Andric   // FIXME: This should not be used during template instantiation. We should
27520b57cec5SDimitry Andric   // pick up the set of unqualified lookup results for the != and + operators
27530b57cec5SDimitry Andric   // in the initial parse.
27540b57cec5SDimitry Andric   //
27550b57cec5SDimitry Andric   // Testcase (accepts-invalid):
27560b57cec5SDimitry Andric   //   template<typename T> void f() { for (auto x : T()) {} }
27570b57cec5SDimitry Andric   //   namespace N { struct X { X begin(); X end(); int operator*(); }; }
27580b57cec5SDimitry Andric   //   bool operator!=(N::X, N::X); void operator++(N::X);
27590b57cec5SDimitry Andric   //   void g() { f<N::X>(); }
27600b57cec5SDimitry Andric   Scope *S = getCurScope();
27610b57cec5SDimitry Andric 
27620b57cec5SDimitry Andric   DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
27630b57cec5SDimitry Andric   VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
27640b57cec5SDimitry Andric   QualType RangeVarType = RangeVar->getType();
27650b57cec5SDimitry Andric 
27660b57cec5SDimitry Andric   DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
27670b57cec5SDimitry Andric   VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
27680b57cec5SDimitry Andric 
27690b57cec5SDimitry Andric   StmtResult BeginDeclStmt = Begin;
27700b57cec5SDimitry Andric   StmtResult EndDeclStmt = End;
27710b57cec5SDimitry Andric   ExprResult NotEqExpr = Cond, IncrExpr = Inc;
27720b57cec5SDimitry Andric 
27730b57cec5SDimitry Andric   if (RangeVarType->isDependentType()) {
27740b57cec5SDimitry Andric     // The range is implicitly used as a placeholder when it is dependent.
27750b57cec5SDimitry Andric     RangeVar->markUsed(Context);
27760b57cec5SDimitry Andric 
27770b57cec5SDimitry Andric     // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
27780b57cec5SDimitry Andric     // them in properly when we instantiate the loop.
27790b57cec5SDimitry Andric     if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
27800b57cec5SDimitry Andric       if (auto *DD = dyn_cast<DecompositionDecl>(LoopVar))
27810b57cec5SDimitry Andric         for (auto *Binding : DD->bindings())
27820b57cec5SDimitry Andric           Binding->setType(Context.DependentTy);
2783349cc55cSDimitry Andric       LoopVar->setType(SubstAutoTypeDependent(LoopVar->getType()));
27840b57cec5SDimitry Andric     }
27850b57cec5SDimitry Andric   } else if (!BeginDeclStmt.get()) {
27860b57cec5SDimitry Andric     SourceLocation RangeLoc = RangeVar->getLocation();
27870b57cec5SDimitry Andric 
27880b57cec5SDimitry Andric     const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
27890b57cec5SDimitry Andric 
27900b57cec5SDimitry Andric     ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
27910b57cec5SDimitry Andric                                                 VK_LValue, ColonLoc);
27920b57cec5SDimitry Andric     if (BeginRangeRef.isInvalid())
27930b57cec5SDimitry Andric       return StmtError();
27940b57cec5SDimitry Andric 
27950b57cec5SDimitry Andric     ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
27960b57cec5SDimitry Andric                                               VK_LValue, ColonLoc);
27970b57cec5SDimitry Andric     if (EndRangeRef.isInvalid())
27980b57cec5SDimitry Andric       return StmtError();
27990b57cec5SDimitry Andric 
28000b57cec5SDimitry Andric     QualType AutoType = Context.getAutoDeductType();
28010b57cec5SDimitry Andric     Expr *Range = RangeVar->getInit();
28020b57cec5SDimitry Andric     if (!Range)
28030b57cec5SDimitry Andric       return StmtError();
28040b57cec5SDimitry Andric     QualType RangeType = Range->getType();
28050b57cec5SDimitry Andric 
28060b57cec5SDimitry Andric     if (RequireCompleteType(RangeLoc, RangeType,
28070b57cec5SDimitry Andric                             diag::err_for_range_incomplete_type))
28080b57cec5SDimitry Andric       return StmtError();
28090b57cec5SDimitry Andric 
28100b57cec5SDimitry Andric     // Build auto __begin = begin-expr, __end = end-expr.
28110b57cec5SDimitry Andric     // Divide by 2, since the variables are in the inner scope (loop body).
28120b57cec5SDimitry Andric     const auto DepthStr = std::to_string(S->getDepth() / 2);
28130b57cec5SDimitry Andric     VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
28140b57cec5SDimitry Andric                                              std::string("__begin") + DepthStr);
28150b57cec5SDimitry Andric     VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
28160b57cec5SDimitry Andric                                            std::string("__end") + DepthStr);
28170b57cec5SDimitry Andric 
28180b57cec5SDimitry Andric     // Build begin-expr and end-expr and attach to __begin and __end variables.
28190b57cec5SDimitry Andric     ExprResult BeginExpr, EndExpr;
28200b57cec5SDimitry Andric     if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
28210b57cec5SDimitry Andric       // - if _RangeT is an array type, begin-expr and end-expr are __range and
28220b57cec5SDimitry Andric       //   __range + __bound, respectively, where __bound is the array bound. If
28230b57cec5SDimitry Andric       //   _RangeT is an array of unknown size or an array of incomplete type,
28240b57cec5SDimitry Andric       //   the program is ill-formed;
28250b57cec5SDimitry Andric 
28260b57cec5SDimitry Andric       // begin-expr is __range.
28270b57cec5SDimitry Andric       BeginExpr = BeginRangeRef;
28280b57cec5SDimitry Andric       if (!CoawaitLoc.isInvalid()) {
28290b57cec5SDimitry Andric         BeginExpr = ActOnCoawaitExpr(S, ColonLoc, BeginExpr.get());
28300b57cec5SDimitry Andric         if (BeginExpr.isInvalid())
28310b57cec5SDimitry Andric           return StmtError();
28320b57cec5SDimitry Andric       }
28330b57cec5SDimitry Andric       if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
28340b57cec5SDimitry Andric                                 diag::err_for_range_iter_deduction_failure)) {
28350b57cec5SDimitry Andric         NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
28360b57cec5SDimitry Andric         return StmtError();
28370b57cec5SDimitry Andric       }
28380b57cec5SDimitry Andric 
28390b57cec5SDimitry Andric       // Find the array bound.
28400b57cec5SDimitry Andric       ExprResult BoundExpr;
28410b57cec5SDimitry Andric       if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
28420b57cec5SDimitry Andric         BoundExpr = IntegerLiteral::Create(
28430b57cec5SDimitry Andric             Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
28440b57cec5SDimitry Andric       else if (const VariableArrayType *VAT =
28450b57cec5SDimitry Andric                dyn_cast<VariableArrayType>(UnqAT)) {
28460b57cec5SDimitry Andric         // For a variably modified type we can't just use the expression within
28470b57cec5SDimitry Andric         // the array bounds, since we don't want that to be re-evaluated here.
28480b57cec5SDimitry Andric         // Rather, we need to determine what it was when the array was first
28490b57cec5SDimitry Andric         // created - so we resort to using sizeof(vla)/sizeof(element).
28500b57cec5SDimitry Andric         // For e.g.
28510b57cec5SDimitry Andric         //  void f(int b) {
28520b57cec5SDimitry Andric         //    int vla[b];
28530b57cec5SDimitry Andric         //    b = -1;   <-- This should not affect the num of iterations below
28540b57cec5SDimitry Andric         //    for (int &c : vla) { .. }
28550b57cec5SDimitry Andric         //  }
28560b57cec5SDimitry Andric 
28570b57cec5SDimitry Andric         // FIXME: This results in codegen generating IR that recalculates the
28580b57cec5SDimitry Andric         // run-time number of elements (as opposed to just using the IR Value
28590b57cec5SDimitry Andric         // that corresponds to the run-time value of each bound that was
28600b57cec5SDimitry Andric         // generated when the array was created.) If this proves too embarrassing
28610b57cec5SDimitry Andric         // even for unoptimized IR, consider passing a magic-value/cookie to
28620b57cec5SDimitry Andric         // codegen that then knows to simply use that initial llvm::Value (that
28630b57cec5SDimitry Andric         // corresponds to the bound at time of array creation) within
28640b57cec5SDimitry Andric         // getelementptr.  But be prepared to pay the price of increasing a
28650b57cec5SDimitry Andric         // customized form of coupling between the two components - which  could
28660b57cec5SDimitry Andric         // be hard to maintain as the codebase evolves.
28670b57cec5SDimitry Andric 
28680b57cec5SDimitry Andric         ExprResult SizeOfVLAExprR = ActOnUnaryExprOrTypeTraitExpr(
28690b57cec5SDimitry Andric             EndVar->getLocation(), UETT_SizeOf,
28700b57cec5SDimitry Andric             /*IsType=*/true,
28710b57cec5SDimitry Andric             CreateParsedType(VAT->desugar(), Context.getTrivialTypeSourceInfo(
28720b57cec5SDimitry Andric                                                  VAT->desugar(), RangeLoc))
28730b57cec5SDimitry Andric                 .getAsOpaquePtr(),
28740b57cec5SDimitry Andric             EndVar->getSourceRange());
28750b57cec5SDimitry Andric         if (SizeOfVLAExprR.isInvalid())
28760b57cec5SDimitry Andric           return StmtError();
28770b57cec5SDimitry Andric 
28780b57cec5SDimitry Andric         ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr(
28790b57cec5SDimitry Andric             EndVar->getLocation(), UETT_SizeOf,
28800b57cec5SDimitry Andric             /*IsType=*/true,
28810b57cec5SDimitry Andric             CreateParsedType(VAT->desugar(),
28820b57cec5SDimitry Andric                              Context.getTrivialTypeSourceInfo(
28830b57cec5SDimitry Andric                                  VAT->getElementType(), RangeLoc))
28840b57cec5SDimitry Andric                 .getAsOpaquePtr(),
28850b57cec5SDimitry Andric             EndVar->getSourceRange());
28860b57cec5SDimitry Andric         if (SizeOfEachElementExprR.isInvalid())
28870b57cec5SDimitry Andric           return StmtError();
28880b57cec5SDimitry Andric 
28890b57cec5SDimitry Andric         BoundExpr =
28900b57cec5SDimitry Andric             ActOnBinOp(S, EndVar->getLocation(), tok::slash,
28910b57cec5SDimitry Andric                        SizeOfVLAExprR.get(), SizeOfEachElementExprR.get());
28920b57cec5SDimitry Andric         if (BoundExpr.isInvalid())
28930b57cec5SDimitry Andric           return StmtError();
28940b57cec5SDimitry Andric 
28950b57cec5SDimitry Andric       } else {
28960b57cec5SDimitry Andric         // Can't be a DependentSizedArrayType or an IncompleteArrayType since
28970b57cec5SDimitry Andric         // UnqAT is not incomplete and Range is not type-dependent.
28980b57cec5SDimitry Andric         llvm_unreachable("Unexpected array type in for-range");
28990b57cec5SDimitry Andric       }
29000b57cec5SDimitry Andric 
29010b57cec5SDimitry Andric       // end-expr is __range + __bound.
29020b57cec5SDimitry Andric       EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
29030b57cec5SDimitry Andric                            BoundExpr.get());
29040b57cec5SDimitry Andric       if (EndExpr.isInvalid())
29050b57cec5SDimitry Andric         return StmtError();
29060b57cec5SDimitry Andric       if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
29070b57cec5SDimitry Andric                                 diag::err_for_range_iter_deduction_failure)) {
29080b57cec5SDimitry Andric         NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
29090b57cec5SDimitry Andric         return StmtError();
29100b57cec5SDimitry Andric       }
29110b57cec5SDimitry Andric     } else {
29120b57cec5SDimitry Andric       OverloadCandidateSet CandidateSet(RangeLoc,
29130b57cec5SDimitry Andric                                         OverloadCandidateSet::CSK_Normal);
29140b57cec5SDimitry Andric       BeginEndFunction BEFFailure;
29150b57cec5SDimitry Andric       ForRangeStatus RangeStatus = BuildNonArrayForRange(
29160b57cec5SDimitry Andric           *this, BeginRangeRef.get(), EndRangeRef.get(), RangeType, BeginVar,
29170b57cec5SDimitry Andric           EndVar, ColonLoc, CoawaitLoc, &CandidateSet, &BeginExpr, &EndExpr,
29180b57cec5SDimitry Andric           &BEFFailure);
29190b57cec5SDimitry Andric 
29200b57cec5SDimitry Andric       if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
29210b57cec5SDimitry Andric           BEFFailure == BEF_begin) {
29220b57cec5SDimitry Andric         // If the range is being built from an array parameter, emit a
29230b57cec5SDimitry Andric         // a diagnostic that it is being treated as a pointer.
29240b57cec5SDimitry Andric         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
29250b57cec5SDimitry Andric           if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
29260b57cec5SDimitry Andric             QualType ArrayTy = PVD->getOriginalType();
29270b57cec5SDimitry Andric             QualType PointerTy = PVD->getType();
29280b57cec5SDimitry Andric             if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
29290b57cec5SDimitry Andric               Diag(Range->getBeginLoc(), diag::err_range_on_array_parameter)
29300b57cec5SDimitry Andric                   << RangeLoc << PVD << ArrayTy << PointerTy;
29310b57cec5SDimitry Andric               Diag(PVD->getLocation(), diag::note_declared_at);
29320b57cec5SDimitry Andric               return StmtError();
29330b57cec5SDimitry Andric             }
29340b57cec5SDimitry Andric           }
29350b57cec5SDimitry Andric         }
29360b57cec5SDimitry Andric 
29370b57cec5SDimitry Andric         // If building the range failed, try dereferencing the range expression
29380b57cec5SDimitry Andric         // unless a diagnostic was issued or the end function is problematic.
29390b57cec5SDimitry Andric         StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
29400b57cec5SDimitry Andric                                                        CoawaitLoc, InitStmt,
29410b57cec5SDimitry Andric                                                        LoopVarDecl, ColonLoc,
29420b57cec5SDimitry Andric                                                        Range, RangeLoc,
29430b57cec5SDimitry Andric                                                        RParenLoc);
29440b57cec5SDimitry Andric         if (SR.isInvalid() || SR.isUsable())
29450b57cec5SDimitry Andric           return SR;
29460b57cec5SDimitry Andric       }
29470b57cec5SDimitry Andric 
29480b57cec5SDimitry Andric       // Otherwise, emit diagnostics if we haven't already.
29490b57cec5SDimitry Andric       if (RangeStatus == FRS_NoViableFunction) {
29500b57cec5SDimitry Andric         Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
29510b57cec5SDimitry Andric         CandidateSet.NoteCandidates(
29520b57cec5SDimitry Andric             PartialDiagnosticAt(Range->getBeginLoc(),
29530b57cec5SDimitry Andric                                 PDiag(diag::err_for_range_invalid)
29540b57cec5SDimitry Andric                                     << RangeLoc << Range->getType()
29550b57cec5SDimitry Andric                                     << BEFFailure),
29560b57cec5SDimitry Andric             *this, OCD_AllCandidates, Range);
29570b57cec5SDimitry Andric       }
29580b57cec5SDimitry Andric       // Return an error if no fix was discovered.
29590b57cec5SDimitry Andric       if (RangeStatus != FRS_Success)
29600b57cec5SDimitry Andric         return StmtError();
29610b57cec5SDimitry Andric     }
29620b57cec5SDimitry Andric 
29630b57cec5SDimitry Andric     assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
29640b57cec5SDimitry Andric            "invalid range expression in for loop");
29650b57cec5SDimitry Andric 
29660b57cec5SDimitry Andric     // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
29670b57cec5SDimitry Andric     // C++1z removes this restriction.
29680b57cec5SDimitry Andric     QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
29690b57cec5SDimitry Andric     if (!Context.hasSameType(BeginType, EndType)) {
29700b57cec5SDimitry Andric       Diag(RangeLoc, getLangOpts().CPlusPlus17
29710b57cec5SDimitry Andric                          ? diag::warn_for_range_begin_end_types_differ
29720b57cec5SDimitry Andric                          : diag::ext_for_range_begin_end_types_differ)
29730b57cec5SDimitry Andric           << BeginType << EndType;
29740b57cec5SDimitry Andric       NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
29750b57cec5SDimitry Andric       NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
29760b57cec5SDimitry Andric     }
29770b57cec5SDimitry Andric 
29780b57cec5SDimitry Andric     BeginDeclStmt =
29790b57cec5SDimitry Andric         ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
29800b57cec5SDimitry Andric     EndDeclStmt =
29810b57cec5SDimitry Andric         ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
29820b57cec5SDimitry Andric 
29830b57cec5SDimitry Andric     const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
29840b57cec5SDimitry Andric     ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
29850b57cec5SDimitry Andric                                            VK_LValue, ColonLoc);
29860b57cec5SDimitry Andric     if (BeginRef.isInvalid())
29870b57cec5SDimitry Andric       return StmtError();
29880b57cec5SDimitry Andric 
29890b57cec5SDimitry Andric     ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
29900b57cec5SDimitry Andric                                          VK_LValue, ColonLoc);
29910b57cec5SDimitry Andric     if (EndRef.isInvalid())
29920b57cec5SDimitry Andric       return StmtError();
29930b57cec5SDimitry Andric 
29940b57cec5SDimitry Andric     // Build and check __begin != __end expression.
29950b57cec5SDimitry Andric     NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
29960b57cec5SDimitry Andric                            BeginRef.get(), EndRef.get());
29970b57cec5SDimitry Andric     if (!NotEqExpr.isInvalid())
29980b57cec5SDimitry Andric       NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get());
29990b57cec5SDimitry Andric     if (!NotEqExpr.isInvalid())
30000b57cec5SDimitry Andric       NotEqExpr =
30010b57cec5SDimitry Andric           ActOnFinishFullExpr(NotEqExpr.get(), /*DiscardedValue*/ false);
30020b57cec5SDimitry Andric     if (NotEqExpr.isInvalid()) {
30030b57cec5SDimitry Andric       Diag(RangeLoc, diag::note_for_range_invalid_iterator)
30040b57cec5SDimitry Andric         << RangeLoc << 0 << BeginRangeRef.get()->getType();
30050b57cec5SDimitry Andric       NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
30060b57cec5SDimitry Andric       if (!Context.hasSameType(BeginType, EndType))
30070b57cec5SDimitry Andric         NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
30080b57cec5SDimitry Andric       return StmtError();
30090b57cec5SDimitry Andric     }
30100b57cec5SDimitry Andric 
30110b57cec5SDimitry Andric     // Build and check ++__begin expression.
30120b57cec5SDimitry Andric     BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
30130b57cec5SDimitry Andric                                 VK_LValue, ColonLoc);
30140b57cec5SDimitry Andric     if (BeginRef.isInvalid())
30150b57cec5SDimitry Andric       return StmtError();
30160b57cec5SDimitry Andric 
30170b57cec5SDimitry Andric     IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
30180b57cec5SDimitry Andric     if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
30190b57cec5SDimitry Andric       // FIXME: getCurScope() should not be used during template instantiation.
30200b57cec5SDimitry Andric       // We should pick up the set of unqualified lookup results for operator
30210b57cec5SDimitry Andric       // co_await during the initial parse.
30220b57cec5SDimitry Andric       IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
30230b57cec5SDimitry Andric     if (!IncrExpr.isInvalid())
30240b57cec5SDimitry Andric       IncrExpr = ActOnFinishFullExpr(IncrExpr.get(), /*DiscardedValue*/ false);
30250b57cec5SDimitry Andric     if (IncrExpr.isInvalid()) {
30260b57cec5SDimitry Andric       Diag(RangeLoc, diag::note_for_range_invalid_iterator)
30270b57cec5SDimitry Andric         << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
30280b57cec5SDimitry Andric       NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
30290b57cec5SDimitry Andric       return StmtError();
30300b57cec5SDimitry Andric     }
30310b57cec5SDimitry Andric 
30320b57cec5SDimitry Andric     // Build and check *__begin  expression.
30330b57cec5SDimitry Andric     BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
30340b57cec5SDimitry Andric                                 VK_LValue, ColonLoc);
30350b57cec5SDimitry Andric     if (BeginRef.isInvalid())
30360b57cec5SDimitry Andric       return StmtError();
30370b57cec5SDimitry Andric 
30380b57cec5SDimitry Andric     ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
30390b57cec5SDimitry Andric     if (DerefExpr.isInvalid()) {
30400b57cec5SDimitry Andric       Diag(RangeLoc, diag::note_for_range_invalid_iterator)
30410b57cec5SDimitry Andric         << RangeLoc << 1 << BeginRangeRef.get()->getType();
30420b57cec5SDimitry Andric       NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
30430b57cec5SDimitry Andric       return StmtError();
30440b57cec5SDimitry Andric     }
30450b57cec5SDimitry Andric 
30460b57cec5SDimitry Andric     // Attach  *__begin  as initializer for VD. Don't touch it if we're just
30470b57cec5SDimitry Andric     // trying to determine whether this would be a valid range.
30480b57cec5SDimitry Andric     if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
30490b57cec5SDimitry Andric       AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false);
30505ffd83dbSDimitry Andric       if (LoopVar->isInvalidDecl() ||
30515ffd83dbSDimitry Andric           (LoopVar->getInit() && LoopVar->getInit()->containsErrors()))
30520b57cec5SDimitry Andric         NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
30530b57cec5SDimitry Andric     }
30540b57cec5SDimitry Andric   }
30550b57cec5SDimitry Andric 
30560b57cec5SDimitry Andric   // Don't bother to actually allocate the result if we're just trying to
30570b57cec5SDimitry Andric   // determine whether it would be valid.
30580b57cec5SDimitry Andric   if (Kind == BFRK_Check)
30590b57cec5SDimitry Andric     return StmtResult();
30600b57cec5SDimitry Andric 
3061a7dea167SDimitry Andric   // In OpenMP loop region loop control variable must be private. Perform
3062a7dea167SDimitry Andric   // analysis of first part (if any).
3063a7dea167SDimitry Andric   if (getLangOpts().OpenMP >= 50 && BeginDeclStmt.isUsable())
3064a7dea167SDimitry Andric     ActOnOpenMPLoopInitialization(ForLoc, BeginDeclStmt.get());
3065a7dea167SDimitry Andric 
30660b57cec5SDimitry Andric   return new (Context) CXXForRangeStmt(
30670b57cec5SDimitry Andric       InitStmt, RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
30680b57cec5SDimitry Andric       cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
30690b57cec5SDimitry Andric       IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
30700b57cec5SDimitry Andric       ColonLoc, RParenLoc);
30710b57cec5SDimitry Andric }
30720b57cec5SDimitry Andric 
30730b57cec5SDimitry Andric /// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
30740b57cec5SDimitry Andric /// statement.
30750b57cec5SDimitry Andric StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
30760b57cec5SDimitry Andric   if (!S || !B)
30770b57cec5SDimitry Andric     return StmtError();
30780b57cec5SDimitry Andric   ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
30790b57cec5SDimitry Andric 
30800b57cec5SDimitry Andric   ForStmt->setBody(B);
30810b57cec5SDimitry Andric   return S;
30820b57cec5SDimitry Andric }
30830b57cec5SDimitry Andric 
30840b57cec5SDimitry Andric // Warn when the loop variable is a const reference that creates a copy.
30850b57cec5SDimitry Andric // Suggest using the non-reference type for copies.  If a copy can be prevented
30860b57cec5SDimitry Andric // suggest the const reference type that would do so.
30870b57cec5SDimitry Andric // For instance, given "for (const &Foo : Range)", suggest
30880b57cec5SDimitry Andric // "for (const Foo : Range)" to denote a copy is made for the loop.  If
30890b57cec5SDimitry Andric // possible, also suggest "for (const &Bar : Range)" if this type prevents
30900b57cec5SDimitry Andric // the copy altogether.
30910b57cec5SDimitry Andric static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
30920b57cec5SDimitry Andric                                                     const VarDecl *VD,
30930b57cec5SDimitry Andric                                                     QualType RangeInitType) {
30940b57cec5SDimitry Andric   const Expr *InitExpr = VD->getInit();
30950b57cec5SDimitry Andric   if (!InitExpr)
30960b57cec5SDimitry Andric     return;
30970b57cec5SDimitry Andric 
30980b57cec5SDimitry Andric   QualType VariableType = VD->getType();
30990b57cec5SDimitry Andric 
31000b57cec5SDimitry Andric   if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr))
31010b57cec5SDimitry Andric     if (!Cleanups->cleanupsHaveSideEffects())
31020b57cec5SDimitry Andric       InitExpr = Cleanups->getSubExpr();
31030b57cec5SDimitry Andric 
31040b57cec5SDimitry Andric   const MaterializeTemporaryExpr *MTE =
31050b57cec5SDimitry Andric       dyn_cast<MaterializeTemporaryExpr>(InitExpr);
31060b57cec5SDimitry Andric 
31070b57cec5SDimitry Andric   // No copy made.
31080b57cec5SDimitry Andric   if (!MTE)
31090b57cec5SDimitry Andric     return;
31100b57cec5SDimitry Andric 
3111480093f4SDimitry Andric   const Expr *E = MTE->getSubExpr()->IgnoreImpCasts();
31120b57cec5SDimitry Andric 
31130b57cec5SDimitry Andric   // Searching for either UnaryOperator for dereference of a pointer or
31140b57cec5SDimitry Andric   // CXXOperatorCallExpr for handling iterators.
31150b57cec5SDimitry Andric   while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
31160b57cec5SDimitry Andric     if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
31170b57cec5SDimitry Andric       E = CCE->getArg(0);
31180b57cec5SDimitry Andric     } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
31190b57cec5SDimitry Andric       const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
31200b57cec5SDimitry Andric       E = ME->getBase();
31210b57cec5SDimitry Andric     } else {
31220b57cec5SDimitry Andric       const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
3123480093f4SDimitry Andric       E = MTE->getSubExpr();
31240b57cec5SDimitry Andric     }
31250b57cec5SDimitry Andric     E = E->IgnoreImpCasts();
31260b57cec5SDimitry Andric   }
31270b57cec5SDimitry Andric 
31285ffd83dbSDimitry Andric   QualType ReferenceReturnType;
31290b57cec5SDimitry Andric   if (isa<UnaryOperator>(E)) {
31305ffd83dbSDimitry Andric     ReferenceReturnType = SemaRef.Context.getLValueReferenceType(E->getType());
31310b57cec5SDimitry Andric   } else {
31320b57cec5SDimitry Andric     const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
31330b57cec5SDimitry Andric     const FunctionDecl *FD = Call->getDirectCallee();
31340b57cec5SDimitry Andric     QualType ReturnType = FD->getReturnType();
31355ffd83dbSDimitry Andric     if (ReturnType->isReferenceType())
31365ffd83dbSDimitry Andric       ReferenceReturnType = ReturnType;
31370b57cec5SDimitry Andric   }
31380b57cec5SDimitry Andric 
31395ffd83dbSDimitry Andric   if (!ReferenceReturnType.isNull()) {
31400b57cec5SDimitry Andric     // Loop variable creates a temporary.  Suggest either to go with
31410b57cec5SDimitry Andric     // non-reference loop variable to indicate a copy is made, or
31425ffd83dbSDimitry Andric     // the correct type to bind a const reference.
31435ffd83dbSDimitry Andric     SemaRef.Diag(VD->getLocation(),
31445ffd83dbSDimitry Andric                  diag::warn_for_range_const_ref_binds_temp_built_from_ref)
31455ffd83dbSDimitry Andric         << VD << VariableType << ReferenceReturnType;
31460b57cec5SDimitry Andric     QualType NonReferenceType = VariableType.getNonReferenceType();
31470b57cec5SDimitry Andric     NonReferenceType.removeLocalConst();
31480b57cec5SDimitry Andric     QualType NewReferenceType =
31490b57cec5SDimitry Andric         SemaRef.Context.getLValueReferenceType(E->getType().withConst());
31500b57cec5SDimitry Andric     SemaRef.Diag(VD->getBeginLoc(), diag::note_use_type_or_non_reference)
3151480093f4SDimitry Andric         << NonReferenceType << NewReferenceType << VD->getSourceRange()
3152480093f4SDimitry Andric         << FixItHint::CreateRemoval(VD->getTypeSpecEndLoc());
3153480093f4SDimitry Andric   } else if (!VariableType->isRValueReferenceType()) {
31540b57cec5SDimitry Andric     // The range always returns a copy, so a temporary is always created.
31550b57cec5SDimitry Andric     // Suggest removing the reference from the loop variable.
3156480093f4SDimitry Andric     // If the type is a rvalue reference do not warn since that changes the
3157480093f4SDimitry Andric     // semantic of the code.
31585ffd83dbSDimitry Andric     SemaRef.Diag(VD->getLocation(), diag::warn_for_range_ref_binds_ret_temp)
31590b57cec5SDimitry Andric         << VD << RangeInitType;
31600b57cec5SDimitry Andric     QualType NonReferenceType = VariableType.getNonReferenceType();
31610b57cec5SDimitry Andric     NonReferenceType.removeLocalConst();
31620b57cec5SDimitry Andric     SemaRef.Diag(VD->getBeginLoc(), diag::note_use_non_reference_type)
3163480093f4SDimitry Andric         << NonReferenceType << VD->getSourceRange()
3164480093f4SDimitry Andric         << FixItHint::CreateRemoval(VD->getTypeSpecEndLoc());
31650b57cec5SDimitry Andric   }
31660b57cec5SDimitry Andric }
31670b57cec5SDimitry Andric 
3168480093f4SDimitry Andric /// Determines whether the @p VariableType's declaration is a record with the
3169480093f4SDimitry Andric /// clang::trivial_abi attribute.
3170480093f4SDimitry Andric static bool hasTrivialABIAttr(QualType VariableType) {
3171480093f4SDimitry Andric   if (CXXRecordDecl *RD = VariableType->getAsCXXRecordDecl())
3172480093f4SDimitry Andric     return RD->hasAttr<TrivialABIAttr>();
3173480093f4SDimitry Andric 
3174480093f4SDimitry Andric   return false;
3175480093f4SDimitry Andric }
3176480093f4SDimitry Andric 
31770b57cec5SDimitry Andric // Warns when the loop variable can be changed to a reference type to
31780b57cec5SDimitry Andric // prevent a copy.  For instance, if given "for (const Foo x : Range)" suggest
31790b57cec5SDimitry Andric // "for (const Foo &x : Range)" if this form does not make a copy.
31800b57cec5SDimitry Andric static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
31810b57cec5SDimitry Andric                                                 const VarDecl *VD) {
31820b57cec5SDimitry Andric   const Expr *InitExpr = VD->getInit();
31830b57cec5SDimitry Andric   if (!InitExpr)
31840b57cec5SDimitry Andric     return;
31850b57cec5SDimitry Andric 
31860b57cec5SDimitry Andric   QualType VariableType = VD->getType();
31870b57cec5SDimitry Andric 
31880b57cec5SDimitry Andric   if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
31890b57cec5SDimitry Andric     if (!CE->getConstructor()->isCopyConstructor())
31900b57cec5SDimitry Andric       return;
31910b57cec5SDimitry Andric   } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
31920b57cec5SDimitry Andric     if (CE->getCastKind() != CK_LValueToRValue)
31930b57cec5SDimitry Andric       return;
31940b57cec5SDimitry Andric   } else {
31950b57cec5SDimitry Andric     return;
31960b57cec5SDimitry Andric   }
31970b57cec5SDimitry Andric 
3198480093f4SDimitry Andric   // Small trivially copyable types are cheap to copy. Do not emit the
3199480093f4SDimitry Andric   // diagnostic for these instances. 64 bytes is a common size of a cache line.
3200480093f4SDimitry Andric   // (The function `getTypeSize` returns the size in bits.)
3201480093f4SDimitry Andric   ASTContext &Ctx = SemaRef.Context;
3202480093f4SDimitry Andric   if (Ctx.getTypeSize(VariableType) <= 64 * 8 &&
3203*297eecfbSDimitry Andric       (VariableType.isTriviallyCopyConstructibleType(Ctx) ||
3204480093f4SDimitry Andric        hasTrivialABIAttr(VariableType)))
32050b57cec5SDimitry Andric     return;
32060b57cec5SDimitry Andric 
32070b57cec5SDimitry Andric   // Suggest changing from a const variable to a const reference variable
32080b57cec5SDimitry Andric   // if doing so will prevent a copy.
32090b57cec5SDimitry Andric   SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
32105ffd83dbSDimitry Andric       << VD << VariableType;
32110b57cec5SDimitry Andric   SemaRef.Diag(VD->getBeginLoc(), diag::note_use_reference_type)
32120b57cec5SDimitry Andric       << SemaRef.Context.getLValueReferenceType(VariableType)
3213480093f4SDimitry Andric       << VD->getSourceRange()
3214480093f4SDimitry Andric       << FixItHint::CreateInsertion(VD->getLocation(), "&");
32150b57cec5SDimitry Andric }
32160b57cec5SDimitry Andric 
32170b57cec5SDimitry Andric /// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
32180b57cec5SDimitry Andric /// 1) for (const foo &x : foos) where foos only returns a copy.  Suggest
32190b57cec5SDimitry Andric ///    using "const foo x" to show that a copy is made
32200b57cec5SDimitry Andric /// 2) for (const bar &x : foos) where bar is a temporary initialized by bar.
32210b57cec5SDimitry Andric ///    Suggest either "const bar x" to keep the copying or "const foo& x" to
32220b57cec5SDimitry Andric ///    prevent the copy.
32230b57cec5SDimitry Andric /// 3) for (const foo x : foos) where x is constructed from a reference foo.
32240b57cec5SDimitry Andric ///    Suggest "const foo &x" to prevent the copy.
32250b57cec5SDimitry Andric static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
32260b57cec5SDimitry Andric                                            const CXXForRangeStmt *ForStmt) {
322755e4f9d5SDimitry Andric   if (SemaRef.inTemplateInstantiation())
322855e4f9d5SDimitry Andric     return;
322955e4f9d5SDimitry Andric 
32305ffd83dbSDimitry Andric   if (SemaRef.Diags.isIgnored(
32315ffd83dbSDimitry Andric           diag::warn_for_range_const_ref_binds_temp_built_from_ref,
32320b57cec5SDimitry Andric           ForStmt->getBeginLoc()) &&
32335ffd83dbSDimitry Andric       SemaRef.Diags.isIgnored(diag::warn_for_range_ref_binds_ret_temp,
32340b57cec5SDimitry Andric                               ForStmt->getBeginLoc()) &&
32350b57cec5SDimitry Andric       SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
32360b57cec5SDimitry Andric                               ForStmt->getBeginLoc())) {
32370b57cec5SDimitry Andric     return;
32380b57cec5SDimitry Andric   }
32390b57cec5SDimitry Andric 
32400b57cec5SDimitry Andric   const VarDecl *VD = ForStmt->getLoopVariable();
32410b57cec5SDimitry Andric   if (!VD)
32420b57cec5SDimitry Andric     return;
32430b57cec5SDimitry Andric 
32440b57cec5SDimitry Andric   QualType VariableType = VD->getType();
32450b57cec5SDimitry Andric 
32460b57cec5SDimitry Andric   if (VariableType->isIncompleteType())
32470b57cec5SDimitry Andric     return;
32480b57cec5SDimitry Andric 
32490b57cec5SDimitry Andric   const Expr *InitExpr = VD->getInit();
32500b57cec5SDimitry Andric   if (!InitExpr)
32510b57cec5SDimitry Andric     return;
32520b57cec5SDimitry Andric 
325355e4f9d5SDimitry Andric   if (InitExpr->getExprLoc().isMacroID())
325455e4f9d5SDimitry Andric     return;
325555e4f9d5SDimitry Andric 
32560b57cec5SDimitry Andric   if (VariableType->isReferenceType()) {
32570b57cec5SDimitry Andric     DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
32580b57cec5SDimitry Andric                                             ForStmt->getRangeInit()->getType());
32590b57cec5SDimitry Andric   } else if (VariableType.isConstQualified()) {
32600b57cec5SDimitry Andric     DiagnoseForRangeConstVariableCopies(SemaRef, VD);
32610b57cec5SDimitry Andric   }
32620b57cec5SDimitry Andric }
32630b57cec5SDimitry Andric 
32640b57cec5SDimitry Andric /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
32650b57cec5SDimitry Andric /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
32660b57cec5SDimitry Andric /// body cannot be performed until after the type of the range variable is
32670b57cec5SDimitry Andric /// determined.
32680b57cec5SDimitry Andric StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
32690b57cec5SDimitry Andric   if (!S || !B)
32700b57cec5SDimitry Andric     return StmtError();
32710b57cec5SDimitry Andric 
32720b57cec5SDimitry Andric   if (isa<ObjCForCollectionStmt>(S))
32730b57cec5SDimitry Andric     return FinishObjCForCollectionStmt(S, B);
32740b57cec5SDimitry Andric 
32750b57cec5SDimitry Andric   CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
32760b57cec5SDimitry Andric   ForStmt->setBody(B);
32770b57cec5SDimitry Andric 
32780b57cec5SDimitry Andric   DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
32790b57cec5SDimitry Andric                         diag::warn_empty_range_based_for_body);
32800b57cec5SDimitry Andric 
32810b57cec5SDimitry Andric   DiagnoseForRangeVariableCopies(*this, ForStmt);
32820b57cec5SDimitry Andric 
32830b57cec5SDimitry Andric   return S;
32840b57cec5SDimitry Andric }
32850b57cec5SDimitry Andric 
32860b57cec5SDimitry Andric StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
32870b57cec5SDimitry Andric                                SourceLocation LabelLoc,
32880b57cec5SDimitry Andric                                LabelDecl *TheDecl) {
32890b57cec5SDimitry Andric   setFunctionHasBranchIntoScope();
32900b57cec5SDimitry Andric   TheDecl->markUsed(Context);
32910b57cec5SDimitry Andric   return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
32920b57cec5SDimitry Andric }
32930b57cec5SDimitry Andric 
32940b57cec5SDimitry Andric StmtResult
32950b57cec5SDimitry Andric Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
32960b57cec5SDimitry Andric                             Expr *E) {
32970b57cec5SDimitry Andric   // Convert operand to void*
32980b57cec5SDimitry Andric   if (!E->isTypeDependent()) {
32990b57cec5SDimitry Andric     QualType ETy = E->getType();
33000b57cec5SDimitry Andric     QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
33010b57cec5SDimitry Andric     ExprResult ExprRes = E;
33020b57cec5SDimitry Andric     AssignConvertType ConvTy =
33030b57cec5SDimitry Andric       CheckSingleAssignmentConstraints(DestTy, ExprRes);
33040b57cec5SDimitry Andric     if (ExprRes.isInvalid())
33050b57cec5SDimitry Andric       return StmtError();
33060b57cec5SDimitry Andric     E = ExprRes.get();
33070b57cec5SDimitry Andric     if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
33080b57cec5SDimitry Andric       return StmtError();
33090b57cec5SDimitry Andric   }
33100b57cec5SDimitry Andric 
33110b57cec5SDimitry Andric   ExprResult ExprRes = ActOnFinishFullExpr(E, /*DiscardedValue*/ false);
33120b57cec5SDimitry Andric   if (ExprRes.isInvalid())
33130b57cec5SDimitry Andric     return StmtError();
33140b57cec5SDimitry Andric   E = ExprRes.get();
33150b57cec5SDimitry Andric 
33160b57cec5SDimitry Andric   setFunctionHasIndirectGoto();
33170b57cec5SDimitry Andric 
33180b57cec5SDimitry Andric   return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
33190b57cec5SDimitry Andric }
33200b57cec5SDimitry Andric 
33210b57cec5SDimitry Andric static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
33220b57cec5SDimitry Andric                                      const Scope &DestScope) {
33230b57cec5SDimitry Andric   if (!S.CurrentSEHFinally.empty() &&
33240b57cec5SDimitry Andric       DestScope.Contains(*S.CurrentSEHFinally.back())) {
33250b57cec5SDimitry Andric     S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
33260b57cec5SDimitry Andric   }
33270b57cec5SDimitry Andric }
33280b57cec5SDimitry Andric 
33290b57cec5SDimitry Andric StmtResult
33300b57cec5SDimitry Andric Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
33310b57cec5SDimitry Andric   Scope *S = CurScope->getContinueParent();
33320b57cec5SDimitry Andric   if (!S) {
33330b57cec5SDimitry Andric     // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
33340b57cec5SDimitry Andric     return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
33350b57cec5SDimitry Andric   }
333681ad6265SDimitry Andric   if (S->isConditionVarScope()) {
3337fe6060f1SDimitry Andric     // We cannot 'continue;' from within a statement expression in the
3338fe6060f1SDimitry Andric     // initializer of a condition variable because we would jump past the
3339fe6060f1SDimitry Andric     // initialization of that variable.
3340fe6060f1SDimitry Andric     return StmtError(Diag(ContinueLoc, diag::err_continue_from_cond_var_init));
3341fe6060f1SDimitry Andric   }
33420b57cec5SDimitry Andric   CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
33430b57cec5SDimitry Andric 
33440b57cec5SDimitry Andric   return new (Context) ContinueStmt(ContinueLoc);
33450b57cec5SDimitry Andric }
33460b57cec5SDimitry Andric 
33470b57cec5SDimitry Andric StmtResult
33480b57cec5SDimitry Andric Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
33490b57cec5SDimitry Andric   Scope *S = CurScope->getBreakParent();
33500b57cec5SDimitry Andric   if (!S) {
33510b57cec5SDimitry Andric     // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
33520b57cec5SDimitry Andric     return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
33530b57cec5SDimitry Andric   }
33540b57cec5SDimitry Andric   if (S->isOpenMPLoopScope())
33550b57cec5SDimitry Andric     return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
33560b57cec5SDimitry Andric                      << "break");
33570b57cec5SDimitry Andric   CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
33580b57cec5SDimitry Andric 
33590b57cec5SDimitry Andric   return new (Context) BreakStmt(BreakLoc);
33600b57cec5SDimitry Andric }
33610b57cec5SDimitry Andric 
3362fe6060f1SDimitry Andric /// Determine whether the given expression might be move-eligible or
3363fe6060f1SDimitry Andric /// copy-elidable in either a (co_)return statement or throw expression,
3364fe6060f1SDimitry Andric /// without considering function return type, if applicable.
33650b57cec5SDimitry Andric ///
3366fe6060f1SDimitry Andric /// \param E The expression being returned from the function or block,
3367fe6060f1SDimitry Andric /// being thrown, or being co_returned from a coroutine. This expression
3368fe6060f1SDimitry Andric /// might be modified by the implementation.
33690b57cec5SDimitry Andric ///
3370349cc55cSDimitry Andric /// \param Mode Overrides detection of current language mode
337106c3fb27SDimitry Andric /// and uses the rules for C++23.
33720b57cec5SDimitry Andric ///
3373fe6060f1SDimitry Andric /// \returns An aggregate which contains the Candidate and isMoveEligible
3374fe6060f1SDimitry Andric /// and isCopyElidable methods. If Candidate is non-null, it means
3375fe6060f1SDimitry Andric /// isMoveEligible() would be true under the most permissive language standard.
3376fe6060f1SDimitry Andric Sema::NamedReturnInfo Sema::getNamedReturnInfo(Expr *&E,
3377fe6060f1SDimitry Andric                                                SimplerImplicitMoveMode Mode) {
3378fe6060f1SDimitry Andric   if (!E)
3379fe6060f1SDimitry Andric     return NamedReturnInfo();
33800b57cec5SDimitry Andric   // - in a return statement in a function [where] ...
33810b57cec5SDimitry Andric   // ... the expression is the name of a non-volatile automatic object ...
3382fe6060f1SDimitry Andric   const auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
33830b57cec5SDimitry Andric   if (!DR || DR->refersToEnclosingVariableOrCapture())
3384fe6060f1SDimitry Andric     return NamedReturnInfo();
3385fe6060f1SDimitry Andric   const auto *VD = dyn_cast<VarDecl>(DR->getDecl());
33860b57cec5SDimitry Andric   if (!VD)
3387fe6060f1SDimitry Andric     return NamedReturnInfo();
3388fe6060f1SDimitry Andric   NamedReturnInfo Res = getNamedReturnInfo(VD);
3389fe6060f1SDimitry Andric   if (Res.Candidate && !E->isXValue() &&
3390fe6060f1SDimitry Andric       (Mode == SimplerImplicitMoveMode::ForceOn ||
3391fe6060f1SDimitry Andric        (Mode != SimplerImplicitMoveMode::ForceOff &&
339206c3fb27SDimitry Andric         getLangOpts().CPlusPlus23))) {
3393fe6060f1SDimitry Andric     E = ImplicitCastExpr::Create(Context, VD->getType().getNonReferenceType(),
3394fe6060f1SDimitry Andric                                  CK_NoOp, E, nullptr, VK_XValue,
3395fe6060f1SDimitry Andric                                  FPOptionsOverride());
3396fe6060f1SDimitry Andric   }
3397fe6060f1SDimitry Andric   return Res;
33980b57cec5SDimitry Andric }
33990b57cec5SDimitry Andric 
3400fe6060f1SDimitry Andric /// Determine whether the given NRVO candidate variable is move-eligible or
3401fe6060f1SDimitry Andric /// copy-elidable, without considering function return type.
3402fe6060f1SDimitry Andric ///
3403fe6060f1SDimitry Andric /// \param VD The NRVO candidate variable.
3404fe6060f1SDimitry Andric ///
3405fe6060f1SDimitry Andric /// \returns An aggregate which contains the Candidate and isMoveEligible
3406fe6060f1SDimitry Andric /// and isCopyElidable methods. If Candidate is non-null, it means
3407fe6060f1SDimitry Andric /// isMoveEligible() would be true under the most permissive language standard.
3408fe6060f1SDimitry Andric Sema::NamedReturnInfo Sema::getNamedReturnInfo(const VarDecl *VD) {
3409fe6060f1SDimitry Andric   NamedReturnInfo Info{VD, NamedReturnInfo::MoveEligibleAndCopyElidable};
3410fe6060f1SDimitry Andric 
3411fe6060f1SDimitry Andric   // C++20 [class.copy.elision]p3:
34120b57cec5SDimitry Andric   // - in a return statement in a function with ...
3413fe6060f1SDimitry Andric   // (other than a function ... parameter)
3414fe6060f1SDimitry Andric   if (VD->getKind() == Decl::ParmVar)
3415fe6060f1SDimitry Andric     Info.S = NamedReturnInfo::MoveEligible;
3416fe6060f1SDimitry Andric   else if (VD->getKind() != Decl::Var)
3417fe6060f1SDimitry Andric     return NamedReturnInfo();
34180b57cec5SDimitry Andric 
3419fe6060f1SDimitry Andric   // (other than ... a catch-clause parameter)
3420fe6060f1SDimitry Andric   if (VD->isExceptionVariable())
3421fe6060f1SDimitry Andric     Info.S = NamedReturnInfo::MoveEligible;
34220b57cec5SDimitry Andric 
34230b57cec5SDimitry Andric   // ...automatic...
3424fe6060f1SDimitry Andric   if (!VD->hasLocalStorage())
3425fe6060f1SDimitry Andric     return NamedReturnInfo();
34260b57cec5SDimitry Andric 
3427fe6060f1SDimitry Andric   // We don't want to implicitly move out of a __block variable during a return
3428fe6060f1SDimitry Andric   // because we cannot assume the variable will no longer be used.
3429fe6060f1SDimitry Andric   if (VD->hasAttr<BlocksAttr>())
3430fe6060f1SDimitry Andric     return NamedReturnInfo();
34310b57cec5SDimitry Andric 
3432fe6060f1SDimitry Andric   QualType VDType = VD->getType();
3433fe6060f1SDimitry Andric   if (VDType->isObjectType()) {
3434fe6060f1SDimitry Andric     // C++17 [class.copy.elision]p3:
3435fe6060f1SDimitry Andric     // ...non-volatile automatic object...
3436fe6060f1SDimitry Andric     if (VDType.isVolatileQualified())
3437fe6060f1SDimitry Andric       return NamedReturnInfo();
3438fe6060f1SDimitry Andric   } else if (VDType->isRValueReferenceType()) {
3439fe6060f1SDimitry Andric     // C++20 [class.copy.elision]p3:
3440fe6060f1SDimitry Andric     // ...either a non-volatile object or an rvalue reference to a non-volatile
3441fe6060f1SDimitry Andric     // object type...
3442fe6060f1SDimitry Andric     QualType VDReferencedType = VDType.getNonReferenceType();
3443fe6060f1SDimitry Andric     if (VDReferencedType.isVolatileQualified() ||
3444fe6060f1SDimitry Andric         !VDReferencedType->isObjectType())
3445fe6060f1SDimitry Andric       return NamedReturnInfo();
3446fe6060f1SDimitry Andric     Info.S = NamedReturnInfo::MoveEligible;
3447fe6060f1SDimitry Andric   } else {
3448fe6060f1SDimitry Andric     return NamedReturnInfo();
3449fe6060f1SDimitry Andric   }
34500b57cec5SDimitry Andric 
34510b57cec5SDimitry Andric   // Variables with higher required alignment than their type's ABI
34520b57cec5SDimitry Andric   // alignment cannot use NRVO.
3453fe6060f1SDimitry Andric   if (!VD->hasDependentAlignment() &&
3454fe6060f1SDimitry Andric       Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VDType))
3455fe6060f1SDimitry Andric     Info.S = NamedReturnInfo::MoveEligible;
3456fe6060f1SDimitry Andric 
3457fe6060f1SDimitry Andric   return Info;
3458fe6060f1SDimitry Andric }
3459fe6060f1SDimitry Andric 
3460fe6060f1SDimitry Andric /// Updates given NamedReturnInfo's move-eligible and
3461fe6060f1SDimitry Andric /// copy-elidable statuses, considering the function
3462fe6060f1SDimitry Andric /// return type criteria as applicable to return statements.
3463fe6060f1SDimitry Andric ///
3464fe6060f1SDimitry Andric /// \param Info The NamedReturnInfo object to update.
3465fe6060f1SDimitry Andric ///
3466fe6060f1SDimitry Andric /// \param ReturnType This is the return type of the function.
3467fe6060f1SDimitry Andric /// \returns The copy elision candidate, in case the initial return expression
3468fe6060f1SDimitry Andric /// was copy elidable, or nullptr otherwise.
3469fe6060f1SDimitry Andric const VarDecl *Sema::getCopyElisionCandidate(NamedReturnInfo &Info,
3470fe6060f1SDimitry Andric                                              QualType ReturnType) {
3471fe6060f1SDimitry Andric   if (!Info.Candidate)
3472fe6060f1SDimitry Andric     return nullptr;
3473fe6060f1SDimitry Andric 
3474fe6060f1SDimitry Andric   auto invalidNRVO = [&] {
3475fe6060f1SDimitry Andric     Info = NamedReturnInfo();
3476fe6060f1SDimitry Andric     return nullptr;
3477fe6060f1SDimitry Andric   };
3478fe6060f1SDimitry Andric 
3479fe6060f1SDimitry Andric   // If we got a non-deduced auto ReturnType, we are in a dependent context and
3480fe6060f1SDimitry Andric   // there is no point in allowing copy elision since we won't have it deduced
3481fe6060f1SDimitry Andric   // by the point the VardDecl is instantiated, which is the last chance we have
3482fe6060f1SDimitry Andric   // of deciding if the candidate is really copy elidable.
3483fe6060f1SDimitry Andric   if ((ReturnType->getTypeClass() == Type::TypeClass::Auto &&
3484fe6060f1SDimitry Andric        ReturnType->isCanonicalUnqualified()) ||
3485fe6060f1SDimitry Andric       ReturnType->isSpecificBuiltinType(BuiltinType::Dependent))
3486fe6060f1SDimitry Andric     return invalidNRVO();
3487fe6060f1SDimitry Andric 
3488fe6060f1SDimitry Andric   if (!ReturnType->isDependentType()) {
3489fe6060f1SDimitry Andric     // - in a return statement in a function with ...
3490fe6060f1SDimitry Andric     // ... a class return type ...
3491fe6060f1SDimitry Andric     if (!ReturnType->isRecordType())
3492fe6060f1SDimitry Andric       return invalidNRVO();
3493fe6060f1SDimitry Andric 
3494fe6060f1SDimitry Andric     QualType VDType = Info.Candidate->getType();
3495fe6060f1SDimitry Andric     // ... the same cv-unqualified type as the function return type ...
3496fe6060f1SDimitry Andric     // When considering moving this expression out, allow dissimilar types.
3497fe6060f1SDimitry Andric     if (!VDType->isDependentType() &&
3498fe6060f1SDimitry Andric         !Context.hasSameUnqualifiedType(ReturnType, VDType))
3499fe6060f1SDimitry Andric       Info.S = NamedReturnInfo::MoveEligible;
3500fe6060f1SDimitry Andric   }
3501fe6060f1SDimitry Andric   return Info.isCopyElidable() ? Info.Candidate : nullptr;
3502fe6060f1SDimitry Andric }
3503fe6060f1SDimitry Andric 
3504fe6060f1SDimitry Andric /// Verify that the initialization sequence that was picked for the
3505fe6060f1SDimitry Andric /// first overload resolution is permissible under C++98.
3506fe6060f1SDimitry Andric ///
3507349cc55cSDimitry Andric /// Reject (possibly converting) constructors not taking an rvalue reference,
3508fe6060f1SDimitry Andric /// or user conversion operators which are not ref-qualified.
3509fe6060f1SDimitry Andric static bool
3510fe6060f1SDimitry Andric VerifyInitializationSequenceCXX98(const Sema &S,
3511fe6060f1SDimitry Andric                                   const InitializationSequence &Seq) {
3512fe6060f1SDimitry Andric   const auto *Step = llvm::find_if(Seq.steps(), [](const auto &Step) {
3513fe6060f1SDimitry Andric     return Step.Kind == InitializationSequence::SK_ConstructorInitialization ||
3514fe6060f1SDimitry Andric            Step.Kind == InitializationSequence::SK_UserConversion;
3515fe6060f1SDimitry Andric   });
3516fe6060f1SDimitry Andric   if (Step != Seq.step_end()) {
3517fe6060f1SDimitry Andric     const auto *FD = Step->Function.Function;
3518fe6060f1SDimitry Andric     if (isa<CXXConstructorDecl>(FD)
3519fe6060f1SDimitry Andric             ? !FD->getParamDecl(0)->getType()->isRValueReferenceType()
3520fe6060f1SDimitry Andric             : cast<CXXMethodDecl>(FD)->getRefQualifier() == RQ_None)
35210b57cec5SDimitry Andric       return false;
3522fe6060f1SDimitry Andric   }
35230b57cec5SDimitry Andric   return true;
35240b57cec5SDimitry Andric }
35250b57cec5SDimitry Andric 
35260b57cec5SDimitry Andric /// Perform the initialization of a potentially-movable value, which
35270b57cec5SDimitry Andric /// is the result of return value.
35280b57cec5SDimitry Andric ///
3529fe6060f1SDimitry Andric /// This routine implements C++20 [class.copy.elision]p3, which attempts to
3530fe6060f1SDimitry Andric /// treat returned lvalues as rvalues in certain cases (to prefer move
3531fe6060f1SDimitry Andric /// construction), then falls back to treating them as lvalues if that failed.
3532fe6060f1SDimitry Andric ExprResult Sema::PerformMoveOrCopyInitialization(
3533fe6060f1SDimitry Andric     const InitializedEntity &Entity, const NamedReturnInfo &NRInfo, Expr *Value,
3534fe6060f1SDimitry Andric     bool SupressSimplerImplicitMoves) {
35358c6f6c0cSDimitry Andric   if (getLangOpts().CPlusPlus &&
353606c3fb27SDimitry Andric       (!getLangOpts().CPlusPlus23 || SupressSimplerImplicitMoves) &&
3537fe6060f1SDimitry Andric       NRInfo.isMoveEligible()) {
3538fe6060f1SDimitry Andric     ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(),
3539fe6060f1SDimitry Andric                               CK_NoOp, Value, VK_XValue, FPOptionsOverride());
3540fe6060f1SDimitry Andric     Expr *InitExpr = &AsRvalue;
3541fe6060f1SDimitry Andric     auto Kind = InitializationKind::CreateCopy(Value->getBeginLoc(),
3542fe6060f1SDimitry Andric                                                Value->getBeginLoc());
3543fe6060f1SDimitry Andric     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3544fe6060f1SDimitry Andric     auto Res = Seq.getFailedOverloadResult();
3545fe6060f1SDimitry Andric     if ((Res == OR_Success || Res == OR_Deleted) &&
3546fe6060f1SDimitry Andric         (getLangOpts().CPlusPlus11 ||
3547fe6060f1SDimitry Andric          VerifyInitializationSequenceCXX98(*this, Seq))) {
3548fe6060f1SDimitry Andric       // Promote "AsRvalue" to the heap, since we now need this
3549fe6060f1SDimitry Andric       // expression node to persist.
3550fe6060f1SDimitry Andric       Value =
3551fe6060f1SDimitry Andric           ImplicitCastExpr::Create(Context, Value->getType(), CK_NoOp, Value,
3552fe6060f1SDimitry Andric                                    nullptr, VK_XValue, FPOptionsOverride());
3553fe6060f1SDimitry Andric       // Complete type-checking the initialization of the return type
3554fe6060f1SDimitry Andric       // using the constructor we found.
3555fe6060f1SDimitry Andric       return Seq.Perform(*this, Entity, Kind, Value);
35560b57cec5SDimitry Andric     }
35570b57cec5SDimitry Andric   }
35580b57cec5SDimitry Andric   // Either we didn't meet the criteria for treating an lvalue as an rvalue,
35590b57cec5SDimitry Andric   // above, or overload resolution failed. Either way, we need to try
35600b57cec5SDimitry Andric   // (again) now with the return value expression as written.
3561fe6060f1SDimitry Andric   return PerformCopyInitialization(Entity, SourceLocation(), Value);
35620b57cec5SDimitry Andric }
35630b57cec5SDimitry Andric 
35640b57cec5SDimitry Andric /// Determine whether the declared return type of the specified function
35650b57cec5SDimitry Andric /// contains 'auto'.
35660b57cec5SDimitry Andric static bool hasDeducedReturnType(FunctionDecl *FD) {
35670b57cec5SDimitry Andric   const FunctionProtoType *FPT =
35680b57cec5SDimitry Andric       FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
35690b57cec5SDimitry Andric   return FPT->getReturnType()->isUndeducedType();
35700b57cec5SDimitry Andric }
35710b57cec5SDimitry Andric 
35720b57cec5SDimitry Andric /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
35730b57cec5SDimitry Andric /// for capturing scopes.
35740b57cec5SDimitry Andric ///
3575fe6060f1SDimitry Andric StmtResult Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc,
3576fe6060f1SDimitry Andric                                          Expr *RetValExp,
3577fe6060f1SDimitry Andric                                          NamedReturnInfo &NRInfo,
3578fe6060f1SDimitry Andric                                          bool SupressSimplerImplicitMoves) {
35790b57cec5SDimitry Andric   // If this is the first return we've seen, infer the return type.
35800b57cec5SDimitry Andric   // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
35810b57cec5SDimitry Andric   CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
35820b57cec5SDimitry Andric   QualType FnRetType = CurCap->ReturnType;
35830b57cec5SDimitry Andric   LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
35845f757f3fSDimitry Andric   if (CurLambda && CurLambda->CallOperator->getType().isNull())
35855f757f3fSDimitry Andric     return StmtError();
35860b57cec5SDimitry Andric   bool HasDeducedReturnType =
35870b57cec5SDimitry Andric       CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
35880b57cec5SDimitry Andric 
35894824e7fdSDimitry Andric   if (ExprEvalContexts.back().isDiscardedStatementContext() &&
35900b57cec5SDimitry Andric       (HasDeducedReturnType || CurCap->HasImplicitReturnType)) {
35910b57cec5SDimitry Andric     if (RetValExp) {
35920b57cec5SDimitry Andric       ExprResult ER =
35930b57cec5SDimitry Andric           ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
35940b57cec5SDimitry Andric       if (ER.isInvalid())
35950b57cec5SDimitry Andric         return StmtError();
35960b57cec5SDimitry Andric       RetValExp = ER.get();
35970b57cec5SDimitry Andric     }
35980b57cec5SDimitry Andric     return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
35990b57cec5SDimitry Andric                               /* NRVOCandidate=*/nullptr);
36000b57cec5SDimitry Andric   }
36010b57cec5SDimitry Andric 
36020b57cec5SDimitry Andric   if (HasDeducedReturnType) {
3603e8d8bef9SDimitry Andric     FunctionDecl *FD = CurLambda->CallOperator;
3604e8d8bef9SDimitry Andric     // If we've already decided this lambda is invalid, e.g. because
3605e8d8bef9SDimitry Andric     // we saw a `return` whose expression had an error, don't keep
3606e8d8bef9SDimitry Andric     // trying to deduce its return type.
3607e8d8bef9SDimitry Andric     if (FD->isInvalidDecl())
3608e8d8bef9SDimitry Andric       return StmtError();
36090b57cec5SDimitry Andric     // In C++1y, the return type may involve 'auto'.
36100b57cec5SDimitry Andric     // FIXME: Blocks might have a return type of 'auto' explicitly specified.
36110b57cec5SDimitry Andric     if (CurCap->ReturnType.isNull())
36120b57cec5SDimitry Andric       CurCap->ReturnType = FD->getReturnType();
36130b57cec5SDimitry Andric 
36140b57cec5SDimitry Andric     AutoType *AT = CurCap->ReturnType->getContainedAutoType();
36150b57cec5SDimitry Andric     assert(AT && "lost auto type from lambda return type");
36160b57cec5SDimitry Andric     if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
36170b57cec5SDimitry Andric       FD->setInvalidDecl();
36185ffd83dbSDimitry Andric       // FIXME: preserve the ill-formed return expression.
36190b57cec5SDimitry Andric       return StmtError();
36200b57cec5SDimitry Andric     }
36210b57cec5SDimitry Andric     CurCap->ReturnType = FnRetType = FD->getReturnType();
36220b57cec5SDimitry Andric   } else if (CurCap->HasImplicitReturnType) {
36230b57cec5SDimitry Andric     // For blocks/lambdas with implicit return types, we check each return
36240b57cec5SDimitry Andric     // statement individually, and deduce the common return type when the block
36250b57cec5SDimitry Andric     // or lambda is completed.
36260b57cec5SDimitry Andric     // FIXME: Fold this into the 'auto' codepath above.
36270b57cec5SDimitry Andric     if (RetValExp && !isa<InitListExpr>(RetValExp)) {
36280b57cec5SDimitry Andric       ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
36290b57cec5SDimitry Andric       if (Result.isInvalid())
36300b57cec5SDimitry Andric         return StmtError();
36310b57cec5SDimitry Andric       RetValExp = Result.get();
36320b57cec5SDimitry Andric 
36330b57cec5SDimitry Andric       // DR1048: even prior to C++14, we should use the 'auto' deduction rules
36340b57cec5SDimitry Andric       // when deducing a return type for a lambda-expression (or by extension
36350b57cec5SDimitry Andric       // for a block). These rules differ from the stated C++11 rules only in
36360b57cec5SDimitry Andric       // that they remove top-level cv-qualifiers.
36370b57cec5SDimitry Andric       if (!CurContext->isDependentContext())
36380b57cec5SDimitry Andric         FnRetType = RetValExp->getType().getUnqualifiedType();
36390b57cec5SDimitry Andric       else
36400b57cec5SDimitry Andric         FnRetType = CurCap->ReturnType = Context.DependentTy;
36410b57cec5SDimitry Andric     } else {
36420b57cec5SDimitry Andric       if (RetValExp) {
36430b57cec5SDimitry Andric         // C++11 [expr.lambda.prim]p4 bans inferring the result from an
36440b57cec5SDimitry Andric         // initializer list, because it is not an expression (even
36450b57cec5SDimitry Andric         // though we represent it as one). We still deduce 'void'.
36460b57cec5SDimitry Andric         Diag(ReturnLoc, diag::err_lambda_return_init_list)
36470b57cec5SDimitry Andric           << RetValExp->getSourceRange();
36480b57cec5SDimitry Andric       }
36490b57cec5SDimitry Andric 
36500b57cec5SDimitry Andric       FnRetType = Context.VoidTy;
36510b57cec5SDimitry Andric     }
36520b57cec5SDimitry Andric 
36530b57cec5SDimitry Andric     // Although we'll properly infer the type of the block once it's completed,
36540b57cec5SDimitry Andric     // make sure we provide a return type now for better error recovery.
36550b57cec5SDimitry Andric     if (CurCap->ReturnType.isNull())
36560b57cec5SDimitry Andric       CurCap->ReturnType = FnRetType;
36570b57cec5SDimitry Andric   }
3658fe6060f1SDimitry Andric   const VarDecl *NRVOCandidate = getCopyElisionCandidate(NRInfo, FnRetType);
36590b57cec5SDimitry Andric 
3660a7dea167SDimitry Andric   if (auto *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
3661a7dea167SDimitry Andric     if (CurBlock->FunctionType->castAs<FunctionType>()->getNoReturnAttr()) {
36620b57cec5SDimitry Andric       Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
36630b57cec5SDimitry Andric       return StmtError();
36640b57cec5SDimitry Andric     }
3665a7dea167SDimitry Andric   } else if (auto *CurRegion = dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
36660b57cec5SDimitry Andric     Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
36670b57cec5SDimitry Andric     return StmtError();
36680b57cec5SDimitry Andric   } else {
36690b57cec5SDimitry Andric     assert(CurLambda && "unknown kind of captured scope");
3670a7dea167SDimitry Andric     if (CurLambda->CallOperator->getType()
3671a7dea167SDimitry Andric             ->castAs<FunctionType>()
36720b57cec5SDimitry Andric             ->getNoReturnAttr()) {
36730b57cec5SDimitry Andric       Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
36740b57cec5SDimitry Andric       return StmtError();
36750b57cec5SDimitry Andric     }
36760b57cec5SDimitry Andric   }
36770b57cec5SDimitry Andric 
36780b57cec5SDimitry Andric   // Otherwise, verify that this result type matches the previous one.  We are
36790b57cec5SDimitry Andric   // pickier with blocks than for normal functions because we don't have GCC
36800b57cec5SDimitry Andric   // compatibility to worry about here.
36810b57cec5SDimitry Andric   if (FnRetType->isDependentType()) {
36820b57cec5SDimitry Andric     // Delay processing for now.  TODO: there are lots of dependent
36830b57cec5SDimitry Andric     // types we can conclusively prove aren't void.
36840b57cec5SDimitry Andric   } else if (FnRetType->isVoidType()) {
36850b57cec5SDimitry Andric     if (RetValExp && !isa<InitListExpr>(RetValExp) &&
36860b57cec5SDimitry Andric         !(getLangOpts().CPlusPlus &&
36870b57cec5SDimitry Andric           (RetValExp->isTypeDependent() ||
36880b57cec5SDimitry Andric            RetValExp->getType()->isVoidType()))) {
36890b57cec5SDimitry Andric       if (!getLangOpts().CPlusPlus &&
36900b57cec5SDimitry Andric           RetValExp->getType()->isVoidType())
36910b57cec5SDimitry Andric         Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
36920b57cec5SDimitry Andric       else {
36930b57cec5SDimitry Andric         Diag(ReturnLoc, diag::err_return_block_has_expr);
36940b57cec5SDimitry Andric         RetValExp = nullptr;
36950b57cec5SDimitry Andric       }
36960b57cec5SDimitry Andric     }
36970b57cec5SDimitry Andric   } else if (!RetValExp) {
36980b57cec5SDimitry Andric     return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
36990b57cec5SDimitry Andric   } else if (!RetValExp->isTypeDependent()) {
37000b57cec5SDimitry Andric     // we have a non-void block with an expression, continue checking
37010b57cec5SDimitry Andric 
37020b57cec5SDimitry Andric     // C99 6.8.6.4p3(136): The return statement is not an assignment. The
37030b57cec5SDimitry Andric     // overlap restriction of subclause 6.5.16.1 does not apply to the case of
37040b57cec5SDimitry Andric     // function return.
37050b57cec5SDimitry Andric 
37060b57cec5SDimitry Andric     // In C++ the return statement is handled via a copy initialization.
37070b57cec5SDimitry Andric     // the C version of which boils down to CheckSingleAssignmentConstraints.
370828a41182SDimitry Andric     InitializedEntity Entity =
370928a41182SDimitry Andric         InitializedEntity::InitializeResult(ReturnLoc, FnRetType);
3710fe6060f1SDimitry Andric     ExprResult Res = PerformMoveOrCopyInitialization(
3711fe6060f1SDimitry Andric         Entity, NRInfo, RetValExp, SupressSimplerImplicitMoves);
37120b57cec5SDimitry Andric     if (Res.isInvalid()) {
37130b57cec5SDimitry Andric       // FIXME: Cleanup temporaries here, anyway?
37140b57cec5SDimitry Andric       return StmtError();
37150b57cec5SDimitry Andric     }
37160b57cec5SDimitry Andric     RetValExp = Res.get();
37170b57cec5SDimitry Andric     CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
37180b57cec5SDimitry Andric   }
37190b57cec5SDimitry Andric 
37200b57cec5SDimitry Andric   if (RetValExp) {
37210b57cec5SDimitry Andric     ExprResult ER =
37220b57cec5SDimitry Andric         ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
37230b57cec5SDimitry Andric     if (ER.isInvalid())
37240b57cec5SDimitry Andric       return StmtError();
37250b57cec5SDimitry Andric     RetValExp = ER.get();
37260b57cec5SDimitry Andric   }
37270b57cec5SDimitry Andric   auto *Result =
37280b57cec5SDimitry Andric       ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
37290b57cec5SDimitry Andric 
37300b57cec5SDimitry Andric   // If we need to check for the named return value optimization,
37310b57cec5SDimitry Andric   // or if we need to infer the return type,
37320b57cec5SDimitry Andric   // save the return statement in our scope for later processing.
37330b57cec5SDimitry Andric   if (CurCap->HasImplicitReturnType || NRVOCandidate)
37340b57cec5SDimitry Andric     FunctionScopes.back()->Returns.push_back(Result);
37350b57cec5SDimitry Andric 
37360b57cec5SDimitry Andric   if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
37370b57cec5SDimitry Andric     FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
37380b57cec5SDimitry Andric 
373906c3fb27SDimitry Andric   if (auto *CurBlock = dyn_cast<BlockScopeInfo>(CurCap);
374006c3fb27SDimitry Andric       CurBlock && CurCap->HasImplicitReturnType && RetValExp &&
374106c3fb27SDimitry Andric       RetValExp->containsErrors())
374206c3fb27SDimitry Andric     CurBlock->TheDecl->setInvalidDecl();
374306c3fb27SDimitry Andric 
37440b57cec5SDimitry Andric   return Result;
37450b57cec5SDimitry Andric }
37460b57cec5SDimitry Andric 
37470b57cec5SDimitry Andric namespace {
37480b57cec5SDimitry Andric /// Marks all typedefs in all local classes in a type referenced.
37490b57cec5SDimitry Andric ///
37500b57cec5SDimitry Andric /// In a function like
37510b57cec5SDimitry Andric /// auto f() {
37520b57cec5SDimitry Andric ///   struct S { typedef int a; };
37530b57cec5SDimitry Andric ///   return S();
37540b57cec5SDimitry Andric /// }
37550b57cec5SDimitry Andric ///
37560b57cec5SDimitry Andric /// the local type escapes and could be referenced in some TUs but not in
37570b57cec5SDimitry Andric /// others. Pretend that all local typedefs are always referenced, to not warn
37580b57cec5SDimitry Andric /// on this. This isn't necessary if f has internal linkage, or the typedef
37590b57cec5SDimitry Andric /// is private.
37600b57cec5SDimitry Andric class LocalTypedefNameReferencer
37610b57cec5SDimitry Andric     : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
37620b57cec5SDimitry Andric public:
37630b57cec5SDimitry Andric   LocalTypedefNameReferencer(Sema &S) : S(S) {}
37640b57cec5SDimitry Andric   bool VisitRecordType(const RecordType *RT);
37650b57cec5SDimitry Andric private:
37660b57cec5SDimitry Andric   Sema &S;
37670b57cec5SDimitry Andric };
37680b57cec5SDimitry Andric bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
37690b57cec5SDimitry Andric   auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
37700b57cec5SDimitry Andric   if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
37710b57cec5SDimitry Andric       R->isDependentType())
37720b57cec5SDimitry Andric     return true;
37730b57cec5SDimitry Andric   for (auto *TmpD : R->decls())
37740b57cec5SDimitry Andric     if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
37750b57cec5SDimitry Andric       if (T->getAccess() != AS_private || R->hasFriends())
37760b57cec5SDimitry Andric         S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
37770b57cec5SDimitry Andric   return true;
37780b57cec5SDimitry Andric }
37790b57cec5SDimitry Andric }
37800b57cec5SDimitry Andric 
37810b57cec5SDimitry Andric TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
37820b57cec5SDimitry Andric   return FD->getTypeSourceInfo()
37830b57cec5SDimitry Andric       ->getTypeLoc()
37840b57cec5SDimitry Andric       .getAsAdjusted<FunctionProtoTypeLoc>()
37850b57cec5SDimitry Andric       .getReturnLoc();
37860b57cec5SDimitry Andric }
37870b57cec5SDimitry Andric 
37880b57cec5SDimitry Andric /// Deduce the return type for a function from a returned expression, per
37890b57cec5SDimitry Andric /// C++1y [dcl.spec.auto]p6.
37900b57cec5SDimitry Andric bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
37910b57cec5SDimitry Andric                                             SourceLocation ReturnLoc,
3792bdd1243dSDimitry Andric                                             Expr *RetExpr, const AutoType *AT) {
379381ad6265SDimitry Andric   // If this is the conversion function for a lambda, we choose to deduce its
37940b57cec5SDimitry Andric   // type from the corresponding call operator, not from the synthesized return
37950b57cec5SDimitry Andric   // statement within it. See Sema::DeduceReturnType.
37960b57cec5SDimitry Andric   if (isLambdaConversionOperator(FD))
37970b57cec5SDimitry Andric     return false;
37980b57cec5SDimitry Andric 
37990b57cec5SDimitry Andric   if (RetExpr && isa<InitListExpr>(RetExpr)) {
38000b57cec5SDimitry Andric     //  If the deduction is for a return statement and the initializer is
38010b57cec5SDimitry Andric     //  a braced-init-list, the program is ill-formed.
38020b57cec5SDimitry Andric     Diag(RetExpr->getExprLoc(),
38030b57cec5SDimitry Andric          getCurLambda() ? diag::err_lambda_return_init_list
38040b57cec5SDimitry Andric                         : diag::err_auto_fn_return_init_list)
38050b57cec5SDimitry Andric         << RetExpr->getSourceRange();
38060b57cec5SDimitry Andric     return true;
38070b57cec5SDimitry Andric   }
38080b57cec5SDimitry Andric 
38090b57cec5SDimitry Andric   if (FD->isDependentContext()) {
38100b57cec5SDimitry Andric     // C++1y [dcl.spec.auto]p12:
38110b57cec5SDimitry Andric     //   Return type deduction [...] occurs when the definition is
38120b57cec5SDimitry Andric     //   instantiated even if the function body contains a return
38130b57cec5SDimitry Andric     //   statement with a non-type-dependent operand.
38140b57cec5SDimitry Andric     assert(AT->isDeduced() && "should have deduced to dependent type");
38150b57cec5SDimitry Andric     return false;
38160b57cec5SDimitry Andric   }
38170b57cec5SDimitry Andric 
3818bdd1243dSDimitry Andric   TypeLoc OrigResultType = getReturnTypeLoc(FD);
3819bdd1243dSDimitry Andric   //  In the case of a return with no operand, the initializer is considered
3820bdd1243dSDimitry Andric   //  to be void().
3821bdd1243dSDimitry Andric   CXXScalarValueInitExpr VoidVal(Context.VoidTy, nullptr, SourceLocation());
3822bdd1243dSDimitry Andric   if (!RetExpr) {
3823bdd1243dSDimitry Andric     // For a function with a deduced result type to return with omitted
3824bdd1243dSDimitry Andric     // expression, the result type as written must be 'auto' or
3825bdd1243dSDimitry Andric     // 'decltype(auto)', possibly cv-qualified or constrained, but not
3826bdd1243dSDimitry Andric     // ref-qualified.
38270b57cec5SDimitry Andric     if (!OrigResultType.getType()->getAs<AutoType>()) {
38280b57cec5SDimitry Andric       Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
38290b57cec5SDimitry Andric           << OrigResultType.getType();
38300b57cec5SDimitry Andric       return true;
38310b57cec5SDimitry Andric     }
3832bdd1243dSDimitry Andric     RetExpr = &VoidVal;
38330b57cec5SDimitry Andric   }
38340b57cec5SDimitry Andric 
3835bdd1243dSDimitry Andric   QualType Deduced = AT->getDeducedType();
3836bdd1243dSDimitry Andric   {
3837bdd1243dSDimitry Andric     //  Otherwise, [...] deduce a value for U using the rules of template
3838bdd1243dSDimitry Andric     //  argument deduction.
383906c3fb27SDimitry Andric     auto RetExprLoc = RetExpr->getExprLoc();
384006c3fb27SDimitry Andric     TemplateDeductionInfo Info(RetExprLoc);
384106c3fb27SDimitry Andric     SourceLocation TemplateSpecLoc;
384206c3fb27SDimitry Andric     if (RetExpr->getType() == Context.OverloadTy) {
384306c3fb27SDimitry Andric       auto FindResult = OverloadExpr::find(RetExpr);
384406c3fb27SDimitry Andric       if (FindResult.Expression)
384506c3fb27SDimitry Andric         TemplateSpecLoc = FindResult.Expression->getNameLoc();
384606c3fb27SDimitry Andric     }
384706c3fb27SDimitry Andric     TemplateSpecCandidateSet FailedTSC(TemplateSpecLoc);
384806c3fb27SDimitry Andric     TemplateDeductionResult Res = DeduceAutoType(
384906c3fb27SDimitry Andric         OrigResultType, RetExpr, Deduced, Info, /*DependentDeduction=*/false,
385006c3fb27SDimitry Andric         /*IgnoreConstraints=*/false, &FailedTSC);
3851bdd1243dSDimitry Andric     if (Res != TDK_Success && FD->isInvalidDecl())
3852bdd1243dSDimitry Andric       return true;
3853bdd1243dSDimitry Andric     switch (Res) {
3854bdd1243dSDimitry Andric     case TDK_Success:
3855bdd1243dSDimitry Andric       break;
3856bdd1243dSDimitry Andric     case TDK_AlreadyDiagnosed:
3857bdd1243dSDimitry Andric       return true;
3858bdd1243dSDimitry Andric     case TDK_Inconsistent: {
3859bdd1243dSDimitry Andric       //  If a function with a declared return type that contains a placeholder
3860bdd1243dSDimitry Andric       //  type has multiple return statements, the return type is deduced for
3861bdd1243dSDimitry Andric       //  each return statement. [...] if the type deduced is not the same in
3862bdd1243dSDimitry Andric       //  each deduction, the program is ill-formed.
3863bdd1243dSDimitry Andric       const LambdaScopeInfo *LambdaSI = getCurLambda();
3864bdd1243dSDimitry Andric       if (LambdaSI && LambdaSI->HasImplicitReturnType)
3865bdd1243dSDimitry Andric         Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
3866bdd1243dSDimitry Andric             << Info.SecondArg << Info.FirstArg << true /*IsLambda*/;
3867bdd1243dSDimitry Andric       else
3868bdd1243dSDimitry Andric         Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3869bdd1243dSDimitry Andric             << (AT->isDecltypeAuto() ? 1 : 0) << Info.SecondArg
3870bdd1243dSDimitry Andric             << Info.FirstArg;
3871bdd1243dSDimitry Andric       return true;
3872bdd1243dSDimitry Andric     }
3873bdd1243dSDimitry Andric     default:
3874bdd1243dSDimitry Andric       Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3875bdd1243dSDimitry Andric           << OrigResultType.getType() << RetExpr->getType();
387606c3fb27SDimitry Andric       FailedTSC.NoteCandidates(*this, RetExprLoc);
3877bdd1243dSDimitry Andric       return true;
3878bdd1243dSDimitry Andric     }
3879bdd1243dSDimitry Andric   }
3880bdd1243dSDimitry Andric 
3881bdd1243dSDimitry Andric   // If a local type is part of the returned type, mark its fields as
3882bdd1243dSDimitry Andric   // referenced.
3883bdd1243dSDimitry Andric   LocalTypedefNameReferencer(*this).TraverseType(RetExpr->getType());
3884bdd1243dSDimitry Andric 
3885a7dea167SDimitry Andric   // CUDA: Kernel function must have 'void' return type.
3886bdd1243dSDimitry Andric   if (getLangOpts().CUDA && FD->hasAttr<CUDAGlobalAttr>() &&
3887bdd1243dSDimitry Andric       !Deduced->isVoidType()) {
3888a7dea167SDimitry Andric     Diag(FD->getLocation(), diag::err_kern_type_not_void_return)
3889a7dea167SDimitry Andric         << FD->getType() << FD->getSourceRange();
3890a7dea167SDimitry Andric     return true;
3891a7dea167SDimitry Andric   }
3892a7dea167SDimitry Andric 
3893bdd1243dSDimitry Andric   if (!FD->isInvalidDecl() && AT->getDeducedType() != Deduced)
38940b57cec5SDimitry Andric     // Update all declarations of the function to have the deduced return type.
38950b57cec5SDimitry Andric     Context.adjustDeducedFunctionResultType(FD, Deduced);
38960b57cec5SDimitry Andric 
38970b57cec5SDimitry Andric   return false;
38980b57cec5SDimitry Andric }
38990b57cec5SDimitry Andric 
39000b57cec5SDimitry Andric StmtResult
39010b57cec5SDimitry Andric Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
39020b57cec5SDimitry Andric                       Scope *CurScope) {
39030b57cec5SDimitry Andric   // Correct typos, in case the containing function returns 'auto' and
39040b57cec5SDimitry Andric   // RetValExp should determine the deduced type.
3905e8d8bef9SDimitry Andric   ExprResult RetVal = CorrectDelayedTyposInExpr(
3906e8d8bef9SDimitry Andric       RetValExp, nullptr, /*RecoverUncorrectedTypos=*/true);
39070b57cec5SDimitry Andric   if (RetVal.isInvalid())
39080b57cec5SDimitry Andric     return StmtError();
390904eeddc0SDimitry Andric   StmtResult R =
391004eeddc0SDimitry Andric       BuildReturnStmt(ReturnLoc, RetVal.get(), /*AllowRecovery=*/true);
39114824e7fdSDimitry Andric   if (R.isInvalid() || ExprEvalContexts.back().isDiscardedStatementContext())
39120b57cec5SDimitry Andric     return R;
39130b57cec5SDimitry Andric 
3914972a253aSDimitry Andric   VarDecl *VD =
3915972a253aSDimitry Andric       const_cast<VarDecl *>(cast<ReturnStmt>(R.get())->getNRVOCandidate());
3916972a253aSDimitry Andric 
3917972a253aSDimitry Andric   CurScope->updateNRVOCandidate(VD);
39180b57cec5SDimitry Andric 
39190b57cec5SDimitry Andric   CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
39200b57cec5SDimitry Andric 
39210b57cec5SDimitry Andric   return R;
39220b57cec5SDimitry Andric }
39230b57cec5SDimitry Andric 
3924fe6060f1SDimitry Andric static bool CheckSimplerImplicitMovesMSVCWorkaround(const Sema &S,
3925fe6060f1SDimitry Andric                                                     const Expr *E) {
392606c3fb27SDimitry Andric   if (!E || !S.getLangOpts().CPlusPlus23 || !S.getLangOpts().MSVCCompat)
3927fe6060f1SDimitry Andric     return false;
3928fe6060f1SDimitry Andric   const Decl *D = E->getReferencedDeclOfCallee();
3929fe6060f1SDimitry Andric   if (!D || !S.SourceMgr.isInSystemHeader(D->getLocation()))
3930fe6060f1SDimitry Andric     return false;
3931fe6060f1SDimitry Andric   for (const DeclContext *DC = D->getDeclContext(); DC; DC = DC->getParent()) {
3932fe6060f1SDimitry Andric     if (DC->isStdNamespace())
3933fe6060f1SDimitry Andric       return true;
3934fe6060f1SDimitry Andric   }
3935fe6060f1SDimitry Andric   return false;
3936fe6060f1SDimitry Andric }
3937fe6060f1SDimitry Andric 
393804eeddc0SDimitry Andric StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
393904eeddc0SDimitry Andric                                  bool AllowRecovery) {
39400b57cec5SDimitry Andric   // Check for unexpanded parameter packs.
39410b57cec5SDimitry Andric   if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
39420b57cec5SDimitry Andric     return StmtError();
39430b57cec5SDimitry Andric 
3944349cc55cSDimitry Andric   // HACK: We suppress simpler implicit move here in msvc compatibility mode
3945fe6060f1SDimitry Andric   // just as a temporary work around, as the MSVC STL has issues with
3946fe6060f1SDimitry Andric   // this change.
3947fe6060f1SDimitry Andric   bool SupressSimplerImplicitMoves =
3948fe6060f1SDimitry Andric       CheckSimplerImplicitMovesMSVCWorkaround(*this, RetValExp);
3949fe6060f1SDimitry Andric   NamedReturnInfo NRInfo = getNamedReturnInfo(
3950fe6060f1SDimitry Andric       RetValExp, SupressSimplerImplicitMoves ? SimplerImplicitMoveMode::ForceOff
3951fe6060f1SDimitry Andric                                              : SimplerImplicitMoveMode::Normal);
3952fe6060f1SDimitry Andric 
39530b57cec5SDimitry Andric   if (isa<CapturingScopeInfo>(getCurFunction()))
3954fe6060f1SDimitry Andric     return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp, NRInfo,
3955fe6060f1SDimitry Andric                                    SupressSimplerImplicitMoves);
39560b57cec5SDimitry Andric 
39570b57cec5SDimitry Andric   QualType FnRetType;
39580b57cec5SDimitry Andric   QualType RelatedRetType;
39590b57cec5SDimitry Andric   const AttrVec *Attrs = nullptr;
39600b57cec5SDimitry Andric   bool isObjCMethod = false;
39610b57cec5SDimitry Andric 
39620b57cec5SDimitry Andric   if (const FunctionDecl *FD = getCurFunctionDecl()) {
39630b57cec5SDimitry Andric     FnRetType = FD->getReturnType();
39640b57cec5SDimitry Andric     if (FD->hasAttrs())
39650b57cec5SDimitry Andric       Attrs = &FD->getAttrs();
39660b57cec5SDimitry Andric     if (FD->isNoReturn())
3967e8d8bef9SDimitry Andric       Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr) << FD;
39680b57cec5SDimitry Andric     if (FD->isMain() && RetValExp)
39690b57cec5SDimitry Andric       if (isa<CXXBoolLiteralExpr>(RetValExp))
39700b57cec5SDimitry Andric         Diag(ReturnLoc, diag::warn_main_returns_bool_literal)
39710b57cec5SDimitry Andric             << RetValExp->getSourceRange();
39725ffd83dbSDimitry Andric     if (FD->hasAttr<CmseNSEntryAttr>() && RetValExp) {
39735ffd83dbSDimitry Andric       if (const auto *RT = dyn_cast<RecordType>(FnRetType.getCanonicalType())) {
39745ffd83dbSDimitry Andric         if (RT->getDecl()->isOrContainsUnion())
39755ffd83dbSDimitry Andric           Diag(RetValExp->getBeginLoc(), diag::warn_cmse_nonsecure_union) << 1;
39765ffd83dbSDimitry Andric       }
39775ffd83dbSDimitry Andric     }
39780b57cec5SDimitry Andric   } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
39790b57cec5SDimitry Andric     FnRetType = MD->getReturnType();
39800b57cec5SDimitry Andric     isObjCMethod = true;
39810b57cec5SDimitry Andric     if (MD->hasAttrs())
39820b57cec5SDimitry Andric       Attrs = &MD->getAttrs();
39830b57cec5SDimitry Andric     if (MD->hasRelatedResultType() && MD->getClassInterface()) {
39840b57cec5SDimitry Andric       // In the implementation of a method with a related return type, the
39850b57cec5SDimitry Andric       // type used to type-check the validity of return statements within the
39860b57cec5SDimitry Andric       // method body is a pointer to the type of the class being implemented.
39870b57cec5SDimitry Andric       RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
39880b57cec5SDimitry Andric       RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
39890b57cec5SDimitry Andric     }
39900b57cec5SDimitry Andric   } else // If we don't have a function/method context, bail.
39910b57cec5SDimitry Andric     return StmtError();
39920b57cec5SDimitry Andric 
399306c3fb27SDimitry Andric   if (RetValExp) {
399406c3fb27SDimitry Andric     const auto *ATy = dyn_cast<ArrayType>(RetValExp->getType());
399506c3fb27SDimitry Andric     if (ATy && ATy->getElementType().isWebAssemblyReferenceType()) {
399606c3fb27SDimitry Andric       Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
399706c3fb27SDimitry Andric       return StmtError();
399806c3fb27SDimitry Andric     }
399906c3fb27SDimitry Andric   }
400006c3fb27SDimitry Andric 
40010b57cec5SDimitry Andric   // C++1z: discarded return statements are not considered when deducing a
40020b57cec5SDimitry Andric   // return type.
40034824e7fdSDimitry Andric   if (ExprEvalContexts.back().isDiscardedStatementContext() &&
40040b57cec5SDimitry Andric       FnRetType->getContainedAutoType()) {
40050b57cec5SDimitry Andric     if (RetValExp) {
40060b57cec5SDimitry Andric       ExprResult ER =
40070b57cec5SDimitry Andric           ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
40080b57cec5SDimitry Andric       if (ER.isInvalid())
40090b57cec5SDimitry Andric         return StmtError();
40100b57cec5SDimitry Andric       RetValExp = ER.get();
40110b57cec5SDimitry Andric     }
40120b57cec5SDimitry Andric     return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
40130b57cec5SDimitry Andric                               /* NRVOCandidate=*/nullptr);
40140b57cec5SDimitry Andric   }
40150b57cec5SDimitry Andric 
40160b57cec5SDimitry Andric   // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
40170b57cec5SDimitry Andric   // deduction.
40180b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus14) {
40190b57cec5SDimitry Andric     if (AutoType *AT = FnRetType->getContainedAutoType()) {
40200b57cec5SDimitry Andric       FunctionDecl *FD = cast<FunctionDecl>(CurContext);
4021e8d8bef9SDimitry Andric       // If we've already decided this function is invalid, e.g. because
4022e8d8bef9SDimitry Andric       // we saw a `return` whose expression had an error, don't keep
4023e8d8bef9SDimitry Andric       // trying to deduce its return type.
402404eeddc0SDimitry Andric       // (Some return values may be needlessly wrapped in RecoveryExpr).
402504eeddc0SDimitry Andric       if (FD->isInvalidDecl() ||
402604eeddc0SDimitry Andric           DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
40270b57cec5SDimitry Andric         FD->setInvalidDecl();
402804eeddc0SDimitry Andric         if (!AllowRecovery)
40290b57cec5SDimitry Andric           return StmtError();
403004eeddc0SDimitry Andric         // The deduction failure is diagnosed and marked, try to recover.
403104eeddc0SDimitry Andric         if (RetValExp) {
403204eeddc0SDimitry Andric           // Wrap return value with a recovery expression of the previous type.
403304eeddc0SDimitry Andric           // If no deduction yet, use DependentTy.
403404eeddc0SDimitry Andric           auto Recovery = CreateRecoveryExpr(
403504eeddc0SDimitry Andric               RetValExp->getBeginLoc(), RetValExp->getEndLoc(), RetValExp,
403604eeddc0SDimitry Andric               AT->isDeduced() ? FnRetType : QualType());
403704eeddc0SDimitry Andric           if (Recovery.isInvalid())
403804eeddc0SDimitry Andric             return StmtError();
403904eeddc0SDimitry Andric           RetValExp = Recovery.get();
404004eeddc0SDimitry Andric         } else {
404104eeddc0SDimitry Andric           // Nothing to do: a ReturnStmt with no value is fine recovery.
404204eeddc0SDimitry Andric         }
40430b57cec5SDimitry Andric       } else {
40440b57cec5SDimitry Andric         FnRetType = FD->getReturnType();
40450b57cec5SDimitry Andric       }
40460b57cec5SDimitry Andric     }
40470b57cec5SDimitry Andric   }
4048fe6060f1SDimitry Andric   const VarDecl *NRVOCandidate = getCopyElisionCandidate(NRInfo, FnRetType);
40490b57cec5SDimitry Andric 
40500b57cec5SDimitry Andric   bool HasDependentReturnType = FnRetType->isDependentType();
40510b57cec5SDimitry Andric 
40520b57cec5SDimitry Andric   ReturnStmt *Result = nullptr;
40530b57cec5SDimitry Andric   if (FnRetType->isVoidType()) {
40540b57cec5SDimitry Andric     if (RetValExp) {
405504eeddc0SDimitry Andric       if (auto *ILE = dyn_cast<InitListExpr>(RetValExp)) {
40560b57cec5SDimitry Andric         // We simply never allow init lists as the return value of void
40570b57cec5SDimitry Andric         // functions. This is compatible because this was never allowed before,
40580b57cec5SDimitry Andric         // so there's no legacy code to deal with.
40590b57cec5SDimitry Andric         NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
40600b57cec5SDimitry Andric         int FunctionKind = 0;
40610b57cec5SDimitry Andric         if (isa<ObjCMethodDecl>(CurDecl))
40620b57cec5SDimitry Andric           FunctionKind = 1;
40630b57cec5SDimitry Andric         else if (isa<CXXConstructorDecl>(CurDecl))
40640b57cec5SDimitry Andric           FunctionKind = 2;
40650b57cec5SDimitry Andric         else if (isa<CXXDestructorDecl>(CurDecl))
40660b57cec5SDimitry Andric           FunctionKind = 3;
40670b57cec5SDimitry Andric 
40680b57cec5SDimitry Andric         Diag(ReturnLoc, diag::err_return_init_list)
4069e8d8bef9SDimitry Andric             << CurDecl << FunctionKind << RetValExp->getSourceRange();
40700b57cec5SDimitry Andric 
407104eeddc0SDimitry Andric         // Preserve the initializers in the AST.
407204eeddc0SDimitry Andric         RetValExp = AllowRecovery
407304eeddc0SDimitry Andric                         ? CreateRecoveryExpr(ILE->getLBraceLoc(),
407404eeddc0SDimitry Andric                                              ILE->getRBraceLoc(), ILE->inits())
407504eeddc0SDimitry Andric                               .get()
407604eeddc0SDimitry Andric                         : nullptr;
40770b57cec5SDimitry Andric       } else if (!RetValExp->isTypeDependent()) {
40780b57cec5SDimitry Andric         // C99 6.8.6.4p1 (ext_ since GCC warns)
40790b57cec5SDimitry Andric         unsigned D = diag::ext_return_has_expr;
40800b57cec5SDimitry Andric         if (RetValExp->getType()->isVoidType()) {
40810b57cec5SDimitry Andric           NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
40820b57cec5SDimitry Andric           if (isa<CXXConstructorDecl>(CurDecl) ||
40830b57cec5SDimitry Andric               isa<CXXDestructorDecl>(CurDecl))
40840b57cec5SDimitry Andric             D = diag::err_ctor_dtor_returns_void;
40850b57cec5SDimitry Andric           else
40860b57cec5SDimitry Andric             D = diag::ext_return_has_void_expr;
40870b57cec5SDimitry Andric         }
40880b57cec5SDimitry Andric         else {
40890b57cec5SDimitry Andric           ExprResult Result = RetValExp;
40900b57cec5SDimitry Andric           Result = IgnoredValueConversions(Result.get());
40910b57cec5SDimitry Andric           if (Result.isInvalid())
40920b57cec5SDimitry Andric             return StmtError();
40930b57cec5SDimitry Andric           RetValExp = Result.get();
40940b57cec5SDimitry Andric           RetValExp = ImpCastExprToType(RetValExp,
40950b57cec5SDimitry Andric                                         Context.VoidTy, CK_ToVoid).get();
40960b57cec5SDimitry Andric         }
40970b57cec5SDimitry Andric         // return of void in constructor/destructor is illegal in C++.
40980b57cec5SDimitry Andric         if (D == diag::err_ctor_dtor_returns_void) {
40990b57cec5SDimitry Andric           NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
4100e8d8bef9SDimitry Andric           Diag(ReturnLoc, D) << CurDecl << isa<CXXDestructorDecl>(CurDecl)
41010b57cec5SDimitry Andric                              << RetValExp->getSourceRange();
41020b57cec5SDimitry Andric         }
41030b57cec5SDimitry Andric         // return (some void expression); is legal in C++.
41040b57cec5SDimitry Andric         else if (D != diag::ext_return_has_void_expr ||
41050b57cec5SDimitry Andric                  !getLangOpts().CPlusPlus) {
41060b57cec5SDimitry Andric           NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
41070b57cec5SDimitry Andric 
41080b57cec5SDimitry Andric           int FunctionKind = 0;
41090b57cec5SDimitry Andric           if (isa<ObjCMethodDecl>(CurDecl))
41100b57cec5SDimitry Andric             FunctionKind = 1;
41110b57cec5SDimitry Andric           else if (isa<CXXConstructorDecl>(CurDecl))
41120b57cec5SDimitry Andric             FunctionKind = 2;
41130b57cec5SDimitry Andric           else if (isa<CXXDestructorDecl>(CurDecl))
41140b57cec5SDimitry Andric             FunctionKind = 3;
41150b57cec5SDimitry Andric 
41160b57cec5SDimitry Andric           Diag(ReturnLoc, D)
4117e8d8bef9SDimitry Andric               << CurDecl << FunctionKind << RetValExp->getSourceRange();
41180b57cec5SDimitry Andric         }
41190b57cec5SDimitry Andric       }
41200b57cec5SDimitry Andric 
41210b57cec5SDimitry Andric       if (RetValExp) {
41220b57cec5SDimitry Andric         ExprResult ER =
41230b57cec5SDimitry Andric             ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
41240b57cec5SDimitry Andric         if (ER.isInvalid())
41250b57cec5SDimitry Andric           return StmtError();
41260b57cec5SDimitry Andric         RetValExp = ER.get();
41270b57cec5SDimitry Andric       }
41280b57cec5SDimitry Andric     }
41290b57cec5SDimitry Andric 
41300b57cec5SDimitry Andric     Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp,
41310b57cec5SDimitry Andric                                 /* NRVOCandidate=*/nullptr);
41320b57cec5SDimitry Andric   } else if (!RetValExp && !HasDependentReturnType) {
41330b57cec5SDimitry Andric     FunctionDecl *FD = getCurFunctionDecl();
41340b57cec5SDimitry Andric 
413581ad6265SDimitry Andric     if ((FD && FD->isInvalidDecl()) || FnRetType->containsErrors()) {
413681ad6265SDimitry Andric       // The intended return type might have been "void", so don't warn.
413781ad6265SDimitry Andric     } else if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
41380b57cec5SDimitry Andric       // C++11 [stmt.return]p2
4139e8d8bef9SDimitry Andric       Diag(ReturnLoc, diag::err_constexpr_return_missing_expr)
4140e8d8bef9SDimitry Andric           << FD << FD->isConsteval();
41410b57cec5SDimitry Andric       FD->setInvalidDecl();
41420b57cec5SDimitry Andric     } else {
4143e8d8bef9SDimitry Andric       // C99 6.8.6.4p1 (ext_ since GCC warns)
41440b57cec5SDimitry Andric       // C90 6.6.6.4p4
4145e8d8bef9SDimitry Andric       unsigned DiagID = getLangOpts().C99 ? diag::ext_return_missing_expr
4146e8d8bef9SDimitry Andric                                           : diag::warn_return_missing_expr;
4147e8d8bef9SDimitry Andric       // Note that at this point one of getCurFunctionDecl() or
4148e8d8bef9SDimitry Andric       // getCurMethodDecl() must be non-null (see above).
4149e8d8bef9SDimitry Andric       assert((getCurFunctionDecl() || getCurMethodDecl()) &&
4150e8d8bef9SDimitry Andric              "Not in a FunctionDecl or ObjCMethodDecl?");
4151e8d8bef9SDimitry Andric       bool IsMethod = FD == nullptr;
4152e8d8bef9SDimitry Andric       const NamedDecl *ND =
4153e8d8bef9SDimitry Andric           IsMethod ? cast<NamedDecl>(getCurMethodDecl()) : cast<NamedDecl>(FD);
4154e8d8bef9SDimitry Andric       Diag(ReturnLoc, DiagID) << ND << IsMethod;
41550b57cec5SDimitry Andric     }
41560b57cec5SDimitry Andric 
41570b57cec5SDimitry Andric     Result = ReturnStmt::Create(Context, ReturnLoc, /* RetExpr=*/nullptr,
41580b57cec5SDimitry Andric                                 /* NRVOCandidate=*/nullptr);
41590b57cec5SDimitry Andric   } else {
41600b57cec5SDimitry Andric     assert(RetValExp || HasDependentReturnType);
41610b57cec5SDimitry Andric     QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
41620b57cec5SDimitry Andric 
41630b57cec5SDimitry Andric     // C99 6.8.6.4p3(136): The return statement is not an assignment. The
41640b57cec5SDimitry Andric     // overlap restriction of subclause 6.5.16.1 does not apply to the case of
41650b57cec5SDimitry Andric     // function return.
41660b57cec5SDimitry Andric 
41670b57cec5SDimitry Andric     // In C++ the return statement is handled via a copy initialization,
41680b57cec5SDimitry Andric     // the C version of which boils down to CheckSingleAssignmentConstraints.
41690b57cec5SDimitry Andric     if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
41700b57cec5SDimitry Andric       // we have a non-void function with an expression, continue checking
417128a41182SDimitry Andric       InitializedEntity Entity =
417228a41182SDimitry Andric           InitializedEntity::InitializeResult(ReturnLoc, RetType);
4173fe6060f1SDimitry Andric       ExprResult Res = PerformMoveOrCopyInitialization(
4174fe6060f1SDimitry Andric           Entity, NRInfo, RetValExp, SupressSimplerImplicitMoves);
417504eeddc0SDimitry Andric       if (Res.isInvalid() && AllowRecovery)
417604eeddc0SDimitry Andric         Res = CreateRecoveryExpr(RetValExp->getBeginLoc(),
417704eeddc0SDimitry Andric                                  RetValExp->getEndLoc(), RetValExp, RetType);
41780b57cec5SDimitry Andric       if (Res.isInvalid()) {
41790b57cec5SDimitry Andric         // FIXME: Clean up temporaries here anyway?
41800b57cec5SDimitry Andric         return StmtError();
41810b57cec5SDimitry Andric       }
41820b57cec5SDimitry Andric       RetValExp = Res.getAs<Expr>();
41830b57cec5SDimitry Andric 
41840b57cec5SDimitry Andric       // If we have a related result type, we need to implicitly
41850b57cec5SDimitry Andric       // convert back to the formal result type.  We can't pretend to
41860b57cec5SDimitry Andric       // initialize the result again --- we might end double-retaining
41870b57cec5SDimitry Andric       // --- so instead we initialize a notional temporary.
41880b57cec5SDimitry Andric       if (!RelatedRetType.isNull()) {
41890b57cec5SDimitry Andric         Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
41900b57cec5SDimitry Andric                                                             FnRetType);
41910b57cec5SDimitry Andric         Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
41920b57cec5SDimitry Andric         if (Res.isInvalid()) {
41930b57cec5SDimitry Andric           // FIXME: Clean up temporaries here anyway?
41940b57cec5SDimitry Andric           return StmtError();
41950b57cec5SDimitry Andric         }
41960b57cec5SDimitry Andric         RetValExp = Res.getAs<Expr>();
41970b57cec5SDimitry Andric       }
41980b57cec5SDimitry Andric 
41990b57cec5SDimitry Andric       CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
42000b57cec5SDimitry Andric                          getCurFunctionDecl());
42010b57cec5SDimitry Andric     }
42020b57cec5SDimitry Andric 
42030b57cec5SDimitry Andric     if (RetValExp) {
42040b57cec5SDimitry Andric       ExprResult ER =
42050b57cec5SDimitry Andric           ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
42060b57cec5SDimitry Andric       if (ER.isInvalid())
42070b57cec5SDimitry Andric         return StmtError();
42080b57cec5SDimitry Andric       RetValExp = ER.get();
42090b57cec5SDimitry Andric     }
42100b57cec5SDimitry Andric     Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
42110b57cec5SDimitry Andric   }
42120b57cec5SDimitry Andric 
42130b57cec5SDimitry Andric   // If we need to check for the named return value optimization, save the
42140b57cec5SDimitry Andric   // return statement in our scope for later processing.
42150b57cec5SDimitry Andric   if (Result->getNRVOCandidate())
42160b57cec5SDimitry Andric     FunctionScopes.back()->Returns.push_back(Result);
42170b57cec5SDimitry Andric 
42180b57cec5SDimitry Andric   if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
42190b57cec5SDimitry Andric     FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
42200b57cec5SDimitry Andric 
42210b57cec5SDimitry Andric   return Result;
42220b57cec5SDimitry Andric }
42230b57cec5SDimitry Andric 
42240b57cec5SDimitry Andric StmtResult
42250b57cec5SDimitry Andric Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
42260b57cec5SDimitry Andric                            SourceLocation RParen, Decl *Parm,
42270b57cec5SDimitry Andric                            Stmt *Body) {
42280b57cec5SDimitry Andric   VarDecl *Var = cast_or_null<VarDecl>(Parm);
42290b57cec5SDimitry Andric   if (Var && Var->isInvalidDecl())
42300b57cec5SDimitry Andric     return StmtError();
42310b57cec5SDimitry Andric 
42320b57cec5SDimitry Andric   return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
42330b57cec5SDimitry Andric }
42340b57cec5SDimitry Andric 
42350b57cec5SDimitry Andric StmtResult
42360b57cec5SDimitry Andric Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
42370b57cec5SDimitry Andric   return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
42380b57cec5SDimitry Andric }
42390b57cec5SDimitry Andric 
42400b57cec5SDimitry Andric StmtResult
42410b57cec5SDimitry Andric Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
42420b57cec5SDimitry Andric                          MultiStmtArg CatchStmts, Stmt *Finally) {
42430b57cec5SDimitry Andric   if (!getLangOpts().ObjCExceptions)
42440b57cec5SDimitry Andric     Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
42450b57cec5SDimitry Andric 
4246349cc55cSDimitry Andric   // Objective-C try is incompatible with SEH __try.
4247349cc55cSDimitry Andric   sema::FunctionScopeInfo *FSI = getCurFunction();
4248349cc55cSDimitry Andric   if (FSI->FirstSEHTryLoc.isValid()) {
4249349cc55cSDimitry Andric     Diag(AtLoc, diag::err_mixing_cxx_try_seh_try) << 1;
4250349cc55cSDimitry Andric     Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
4251349cc55cSDimitry Andric   }
4252349cc55cSDimitry Andric 
4253349cc55cSDimitry Andric   FSI->setHasObjCTry(AtLoc);
42540b57cec5SDimitry Andric   unsigned NumCatchStmts = CatchStmts.size();
42550b57cec5SDimitry Andric   return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
42560b57cec5SDimitry Andric                                NumCatchStmts, Finally);
42570b57cec5SDimitry Andric }
42580b57cec5SDimitry Andric 
42590b57cec5SDimitry Andric StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
42600b57cec5SDimitry Andric   if (Throw) {
42610b57cec5SDimitry Andric     ExprResult Result = DefaultLvalueConversion(Throw);
42620b57cec5SDimitry Andric     if (Result.isInvalid())
42630b57cec5SDimitry Andric       return StmtError();
42640b57cec5SDimitry Andric 
42650b57cec5SDimitry Andric     Result = ActOnFinishFullExpr(Result.get(), /*DiscardedValue*/ false);
42660b57cec5SDimitry Andric     if (Result.isInvalid())
42670b57cec5SDimitry Andric       return StmtError();
42680b57cec5SDimitry Andric     Throw = Result.get();
42690b57cec5SDimitry Andric 
42700b57cec5SDimitry Andric     QualType ThrowType = Throw->getType();
42710b57cec5SDimitry Andric     // Make sure the expression type is an ObjC pointer or "void *".
42720b57cec5SDimitry Andric     if (!ThrowType->isDependentType() &&
42730b57cec5SDimitry Andric         !ThrowType->isObjCObjectPointerType()) {
42740b57cec5SDimitry Andric       const PointerType *PT = ThrowType->getAs<PointerType>();
42750b57cec5SDimitry Andric       if (!PT || !PT->getPointeeType()->isVoidType())
42760b57cec5SDimitry Andric         return StmtError(Diag(AtLoc, diag::err_objc_throw_expects_object)
42770b57cec5SDimitry Andric                          << Throw->getType() << Throw->getSourceRange());
42780b57cec5SDimitry Andric     }
42790b57cec5SDimitry Andric   }
42800b57cec5SDimitry Andric 
42810b57cec5SDimitry Andric   return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
42820b57cec5SDimitry Andric }
42830b57cec5SDimitry Andric 
42840b57cec5SDimitry Andric StmtResult
42850b57cec5SDimitry Andric Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
42860b57cec5SDimitry Andric                            Scope *CurScope) {
42870b57cec5SDimitry Andric   if (!getLangOpts().ObjCExceptions)
42880b57cec5SDimitry Andric     Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
42890b57cec5SDimitry Andric 
42900b57cec5SDimitry Andric   if (!Throw) {
42910b57cec5SDimitry Andric     // @throw without an expression designates a rethrow (which must occur
42920b57cec5SDimitry Andric     // in the context of an @catch clause).
42930b57cec5SDimitry Andric     Scope *AtCatchParent = CurScope;
42940b57cec5SDimitry Andric     while (AtCatchParent && !AtCatchParent->isAtCatchScope())
42950b57cec5SDimitry Andric       AtCatchParent = AtCatchParent->getParent();
42960b57cec5SDimitry Andric     if (!AtCatchParent)
42970b57cec5SDimitry Andric       return StmtError(Diag(AtLoc, diag::err_rethrow_used_outside_catch));
42980b57cec5SDimitry Andric   }
42990b57cec5SDimitry Andric   return BuildObjCAtThrowStmt(AtLoc, Throw);
43000b57cec5SDimitry Andric }
43010b57cec5SDimitry Andric 
43020b57cec5SDimitry Andric ExprResult
43030b57cec5SDimitry Andric Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
43040b57cec5SDimitry Andric   ExprResult result = DefaultLvalueConversion(operand);
43050b57cec5SDimitry Andric   if (result.isInvalid())
43060b57cec5SDimitry Andric     return ExprError();
43070b57cec5SDimitry Andric   operand = result.get();
43080b57cec5SDimitry Andric 
43090b57cec5SDimitry Andric   // Make sure the expression type is an ObjC pointer or "void *".
43100b57cec5SDimitry Andric   QualType type = operand->getType();
43110b57cec5SDimitry Andric   if (!type->isDependentType() &&
43120b57cec5SDimitry Andric       !type->isObjCObjectPointerType()) {
43130b57cec5SDimitry Andric     const PointerType *pointerType = type->getAs<PointerType>();
43140b57cec5SDimitry Andric     if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
43150b57cec5SDimitry Andric       if (getLangOpts().CPlusPlus) {
43160b57cec5SDimitry Andric         if (RequireCompleteType(atLoc, type,
43170b57cec5SDimitry Andric                                 diag::err_incomplete_receiver_type))
43180b57cec5SDimitry Andric           return Diag(atLoc, diag::err_objc_synchronized_expects_object)
43190b57cec5SDimitry Andric                    << type << operand->getSourceRange();
43200b57cec5SDimitry Andric 
43210b57cec5SDimitry Andric         ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
43220b57cec5SDimitry Andric         if (result.isInvalid())
43230b57cec5SDimitry Andric           return ExprError();
43240b57cec5SDimitry Andric         if (!result.isUsable())
43250b57cec5SDimitry Andric           return Diag(atLoc, diag::err_objc_synchronized_expects_object)
43260b57cec5SDimitry Andric                    << type << operand->getSourceRange();
43270b57cec5SDimitry Andric 
43280b57cec5SDimitry Andric         operand = result.get();
43290b57cec5SDimitry Andric       } else {
43300b57cec5SDimitry Andric           return Diag(atLoc, diag::err_objc_synchronized_expects_object)
43310b57cec5SDimitry Andric                    << type << operand->getSourceRange();
43320b57cec5SDimitry Andric       }
43330b57cec5SDimitry Andric     }
43340b57cec5SDimitry Andric   }
43350b57cec5SDimitry Andric 
43360b57cec5SDimitry Andric   // The operand to @synchronized is a full-expression.
43370b57cec5SDimitry Andric   return ActOnFinishFullExpr(operand, /*DiscardedValue*/ false);
43380b57cec5SDimitry Andric }
43390b57cec5SDimitry Andric 
43400b57cec5SDimitry Andric StmtResult
43410b57cec5SDimitry Andric Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
43420b57cec5SDimitry Andric                                   Stmt *SyncBody) {
43430b57cec5SDimitry Andric   // We can't jump into or indirect-jump out of a @synchronized block.
43440b57cec5SDimitry Andric   setFunctionHasBranchProtectedScope();
43450b57cec5SDimitry Andric   return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
43460b57cec5SDimitry Andric }
43470b57cec5SDimitry Andric 
43480b57cec5SDimitry Andric /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
43490b57cec5SDimitry Andric /// and creates a proper catch handler from them.
43500b57cec5SDimitry Andric StmtResult
43510b57cec5SDimitry Andric Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
43520b57cec5SDimitry Andric                          Stmt *HandlerBlock) {
43530b57cec5SDimitry Andric   // There's nothing to test that ActOnExceptionDecl didn't already test.
43540b57cec5SDimitry Andric   return new (Context)
43550b57cec5SDimitry Andric       CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
43560b57cec5SDimitry Andric }
43570b57cec5SDimitry Andric 
43580b57cec5SDimitry Andric StmtResult
43590b57cec5SDimitry Andric Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
43600b57cec5SDimitry Andric   setFunctionHasBranchProtectedScope();
43610b57cec5SDimitry Andric   return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
43620b57cec5SDimitry Andric }
43630b57cec5SDimitry Andric 
43640b57cec5SDimitry Andric namespace {
43650b57cec5SDimitry Andric class CatchHandlerType {
43660b57cec5SDimitry Andric   QualType QT;
43670b57cec5SDimitry Andric   unsigned IsPointer : 1;
43680b57cec5SDimitry Andric 
43690b57cec5SDimitry Andric   // This is a special constructor to be used only with DenseMapInfo's
43700b57cec5SDimitry Andric   // getEmptyKey() and getTombstoneKey() functions.
43710b57cec5SDimitry Andric   friend struct llvm::DenseMapInfo<CatchHandlerType>;
43720b57cec5SDimitry Andric   enum Unique { ForDenseMap };
43730b57cec5SDimitry Andric   CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
43740b57cec5SDimitry Andric 
43750b57cec5SDimitry Andric public:
43760b57cec5SDimitry Andric   /// Used when creating a CatchHandlerType from a handler type; will determine
43770b57cec5SDimitry Andric   /// whether the type is a pointer or reference and will strip off the top
43780b57cec5SDimitry Andric   /// level pointer and cv-qualifiers.
43790b57cec5SDimitry Andric   CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
43800b57cec5SDimitry Andric     if (QT->isPointerType())
43810b57cec5SDimitry Andric       IsPointer = true;
43820b57cec5SDimitry Andric 
438306c3fb27SDimitry Andric     QT = QT.getUnqualifiedType();
43840b57cec5SDimitry Andric     if (IsPointer || QT->isReferenceType())
43850b57cec5SDimitry Andric       QT = QT->getPointeeType();
43860b57cec5SDimitry Andric   }
43870b57cec5SDimitry Andric 
43880b57cec5SDimitry Andric   /// Used when creating a CatchHandlerType from a base class type; pretends the
43890b57cec5SDimitry Andric   /// type passed in had the pointer qualifier, does not need to get an
43900b57cec5SDimitry Andric   /// unqualified type.
43910b57cec5SDimitry Andric   CatchHandlerType(QualType QT, bool IsPointer)
43920b57cec5SDimitry Andric       : QT(QT), IsPointer(IsPointer) {}
43930b57cec5SDimitry Andric 
43940b57cec5SDimitry Andric   QualType underlying() const { return QT; }
43950b57cec5SDimitry Andric   bool isPointer() const { return IsPointer; }
43960b57cec5SDimitry Andric 
43970b57cec5SDimitry Andric   friend bool operator==(const CatchHandlerType &LHS,
43980b57cec5SDimitry Andric                          const CatchHandlerType &RHS) {
43990b57cec5SDimitry Andric     // If the pointer qualification does not match, we can return early.
44000b57cec5SDimitry Andric     if (LHS.IsPointer != RHS.IsPointer)
44010b57cec5SDimitry Andric       return false;
44020b57cec5SDimitry Andric     // Otherwise, check the underlying type without cv-qualifiers.
44030b57cec5SDimitry Andric     return LHS.QT == RHS.QT;
44040b57cec5SDimitry Andric   }
44050b57cec5SDimitry Andric };
44060b57cec5SDimitry Andric } // namespace
44070b57cec5SDimitry Andric 
44080b57cec5SDimitry Andric namespace llvm {
44090b57cec5SDimitry Andric template <> struct DenseMapInfo<CatchHandlerType> {
44100b57cec5SDimitry Andric   static CatchHandlerType getEmptyKey() {
44110b57cec5SDimitry Andric     return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
44120b57cec5SDimitry Andric                        CatchHandlerType::ForDenseMap);
44130b57cec5SDimitry Andric   }
44140b57cec5SDimitry Andric 
44150b57cec5SDimitry Andric   static CatchHandlerType getTombstoneKey() {
44160b57cec5SDimitry Andric     return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
44170b57cec5SDimitry Andric                        CatchHandlerType::ForDenseMap);
44180b57cec5SDimitry Andric   }
44190b57cec5SDimitry Andric 
44200b57cec5SDimitry Andric   static unsigned getHashValue(const CatchHandlerType &Base) {
44210b57cec5SDimitry Andric     return DenseMapInfo<QualType>::getHashValue(Base.underlying());
44220b57cec5SDimitry Andric   }
44230b57cec5SDimitry Andric 
44240b57cec5SDimitry Andric   static bool isEqual(const CatchHandlerType &LHS,
44250b57cec5SDimitry Andric                       const CatchHandlerType &RHS) {
44260b57cec5SDimitry Andric     return LHS == RHS;
44270b57cec5SDimitry Andric   }
44280b57cec5SDimitry Andric };
44290b57cec5SDimitry Andric }
44300b57cec5SDimitry Andric 
44310b57cec5SDimitry Andric namespace {
44320b57cec5SDimitry Andric class CatchTypePublicBases {
443306c3fb27SDimitry Andric   const llvm::DenseMap<QualType, CXXCatchStmt *> &TypesToCheck;
44340b57cec5SDimitry Andric 
44350b57cec5SDimitry Andric   CXXCatchStmt *FoundHandler;
443606c3fb27SDimitry Andric   QualType FoundHandlerType;
443706c3fb27SDimitry Andric   QualType TestAgainstType;
44380b57cec5SDimitry Andric 
44390b57cec5SDimitry Andric public:
444006c3fb27SDimitry Andric   CatchTypePublicBases(const llvm::DenseMap<QualType, CXXCatchStmt *> &T,
444106c3fb27SDimitry Andric                        QualType QT)
444206c3fb27SDimitry Andric       : TypesToCheck(T), FoundHandler(nullptr), TestAgainstType(QT) {}
44430b57cec5SDimitry Andric 
44440b57cec5SDimitry Andric   CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
444506c3fb27SDimitry Andric   QualType getFoundHandlerType() const { return FoundHandlerType; }
44460b57cec5SDimitry Andric 
44470b57cec5SDimitry Andric   bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
44480b57cec5SDimitry Andric     if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
444906c3fb27SDimitry Andric       QualType Check = S->getType().getCanonicalType();
44500b57cec5SDimitry Andric       const auto &M = TypesToCheck;
44510b57cec5SDimitry Andric       auto I = M.find(Check);
44520b57cec5SDimitry Andric       if (I != M.end()) {
445306c3fb27SDimitry Andric         // We're pretty sure we found what we need to find. However, we still
445406c3fb27SDimitry Andric         // need to make sure that we properly compare for pointers and
445506c3fb27SDimitry Andric         // references, to handle cases like:
445606c3fb27SDimitry Andric         //
445706c3fb27SDimitry Andric         // } catch (Base *b) {
445806c3fb27SDimitry Andric         // } catch (Derived &d) {
445906c3fb27SDimitry Andric         // }
446006c3fb27SDimitry Andric         //
446106c3fb27SDimitry Andric         // where there is a qualification mismatch that disqualifies this
446206c3fb27SDimitry Andric         // handler as a potential problem.
446306c3fb27SDimitry Andric         if (I->second->getCaughtType()->isPointerType() ==
446406c3fb27SDimitry Andric                 TestAgainstType->isPointerType()) {
44650b57cec5SDimitry Andric           FoundHandler = I->second;
446606c3fb27SDimitry Andric           FoundHandlerType = Check;
44670b57cec5SDimitry Andric           return true;
44680b57cec5SDimitry Andric         }
44690b57cec5SDimitry Andric       }
447006c3fb27SDimitry Andric     }
44710b57cec5SDimitry Andric     return false;
44720b57cec5SDimitry Andric   }
44730b57cec5SDimitry Andric };
44740b57cec5SDimitry Andric }
44750b57cec5SDimitry Andric 
44760b57cec5SDimitry Andric /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
44770b57cec5SDimitry Andric /// handlers and creates a try statement from them.
44780b57cec5SDimitry Andric StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
44790b57cec5SDimitry Andric                                   ArrayRef<Stmt *> Handlers) {
44805f757f3fSDimitry Andric   const llvm::Triple &T = Context.getTargetInfo().getTriple();
44815f757f3fSDimitry Andric   const bool IsOpenMPGPUTarget =
44825f757f3fSDimitry Andric       getLangOpts().OpenMPIsTargetDevice && (T.isNVPTX() || T.isAMDGCN());
44835f757f3fSDimitry Andric   // Don't report an error if 'try' is used in system headers or in an OpenMP
44845f757f3fSDimitry Andric   // target region compiled for a GPU architecture.
44855f757f3fSDimitry Andric   if (!IsOpenMPGPUTarget && !getLangOpts().CXXExceptions &&
44860b57cec5SDimitry Andric       !getSourceManager().isInSystemHeader(TryLoc) && !getLangOpts().CUDA) {
44870b57cec5SDimitry Andric     // Delay error emission for the OpenMP device code.
44880b57cec5SDimitry Andric     targetDiag(TryLoc, diag::err_exceptions_disabled) << "try";
44890b57cec5SDimitry Andric   }
44900b57cec5SDimitry Andric 
44915f757f3fSDimitry Andric   // In OpenMP target regions, we assume that catch is never reached on GPU
44925f757f3fSDimitry Andric   // targets.
44935f757f3fSDimitry Andric   if (IsOpenMPGPUTarget)
44945f757f3fSDimitry Andric     targetDiag(TryLoc, diag::warn_try_not_valid_on_target) << T.str();
44955f757f3fSDimitry Andric 
44960b57cec5SDimitry Andric   // Exceptions aren't allowed in CUDA device code.
44970b57cec5SDimitry Andric   if (getLangOpts().CUDA)
44980b57cec5SDimitry Andric     CUDADiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions)
44990b57cec5SDimitry Andric         << "try" << CurrentCUDATarget();
45000b57cec5SDimitry Andric 
45010b57cec5SDimitry Andric   if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
45020b57cec5SDimitry Andric     Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
45030b57cec5SDimitry Andric 
45040b57cec5SDimitry Andric   sema::FunctionScopeInfo *FSI = getCurFunction();
45050b57cec5SDimitry Andric 
45060b57cec5SDimitry Andric   // C++ try is incompatible with SEH __try.
45070b57cec5SDimitry Andric   if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
4508349cc55cSDimitry Andric     Diag(TryLoc, diag::err_mixing_cxx_try_seh_try) << 0;
45090b57cec5SDimitry Andric     Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
45100b57cec5SDimitry Andric   }
45110b57cec5SDimitry Andric 
45120b57cec5SDimitry Andric   const unsigned NumHandlers = Handlers.size();
45130b57cec5SDimitry Andric   assert(!Handlers.empty() &&
45140b57cec5SDimitry Andric          "The parser shouldn't call this if there are no handlers.");
45150b57cec5SDimitry Andric 
451606c3fb27SDimitry Andric   llvm::DenseMap<QualType, CXXCatchStmt *> HandledBaseTypes;
45170b57cec5SDimitry Andric   llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
45180b57cec5SDimitry Andric   for (unsigned i = 0; i < NumHandlers; ++i) {
45190b57cec5SDimitry Andric     CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
45200b57cec5SDimitry Andric 
45210b57cec5SDimitry Andric     // Diagnose when the handler is a catch-all handler, but it isn't the last
45220b57cec5SDimitry Andric     // handler for the try block. [except.handle]p5. Also, skip exception
45230b57cec5SDimitry Andric     // declarations that are invalid, since we can't usefully report on them.
45240b57cec5SDimitry Andric     if (!H->getExceptionDecl()) {
45250b57cec5SDimitry Andric       if (i < NumHandlers - 1)
45260b57cec5SDimitry Andric         return StmtError(Diag(H->getBeginLoc(), diag::err_early_catch_all));
45270b57cec5SDimitry Andric       continue;
45280b57cec5SDimitry Andric     } else if (H->getExceptionDecl()->isInvalidDecl())
45290b57cec5SDimitry Andric       continue;
45300b57cec5SDimitry Andric 
45310b57cec5SDimitry Andric     // Walk the type hierarchy to diagnose when this type has already been
45320b57cec5SDimitry Andric     // handled (duplication), or cannot be handled (derivation inversion). We
45330b57cec5SDimitry Andric     // ignore top-level cv-qualifiers, per [except.handle]p3
453406c3fb27SDimitry Andric     CatchHandlerType HandlerCHT = H->getCaughtType().getCanonicalType();
45350b57cec5SDimitry Andric 
45360b57cec5SDimitry Andric     // We can ignore whether the type is a reference or a pointer; we need the
45370b57cec5SDimitry Andric     // underlying declaration type in order to get at the underlying record
45380b57cec5SDimitry Andric     // decl, if there is one.
45390b57cec5SDimitry Andric     QualType Underlying = HandlerCHT.underlying();
45400b57cec5SDimitry Andric     if (auto *RD = Underlying->getAsCXXRecordDecl()) {
45410b57cec5SDimitry Andric       if (!RD->hasDefinition())
45420b57cec5SDimitry Andric         continue;
45430b57cec5SDimitry Andric       // Check that none of the public, unambiguous base classes are in the
45440b57cec5SDimitry Andric       // map ([except.handle]p1). Give the base classes the same pointer
45450b57cec5SDimitry Andric       // qualification as the original type we are basing off of. This allows
45460b57cec5SDimitry Andric       // comparison against the handler type using the same top-level pointer
45470b57cec5SDimitry Andric       // as the original type.
45480b57cec5SDimitry Andric       CXXBasePaths Paths;
45490b57cec5SDimitry Andric       Paths.setOrigin(RD);
455006c3fb27SDimitry Andric       CatchTypePublicBases CTPB(HandledBaseTypes,
455106c3fb27SDimitry Andric                                 H->getCaughtType().getCanonicalType());
45520b57cec5SDimitry Andric       if (RD->lookupInBases(CTPB, Paths)) {
45530b57cec5SDimitry Andric         const CXXCatchStmt *Problem = CTPB.getFoundHandler();
455406c3fb27SDimitry Andric         if (!Paths.isAmbiguous(
455506c3fb27SDimitry Andric                 CanQualType::CreateUnsafe(CTPB.getFoundHandlerType()))) {
45560b57cec5SDimitry Andric           Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
45570b57cec5SDimitry Andric                diag::warn_exception_caught_by_earlier_handler)
45580b57cec5SDimitry Andric               << H->getCaughtType();
45590b57cec5SDimitry Andric           Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
45600b57cec5SDimitry Andric                 diag::note_previous_exception_handler)
45610b57cec5SDimitry Andric               << Problem->getCaughtType();
45620b57cec5SDimitry Andric         }
45630b57cec5SDimitry Andric       }
456406c3fb27SDimitry Andric       // Strip the qualifiers here because we're going to be comparing this
456506c3fb27SDimitry Andric       // type to the base type specifiers of a class, which are ignored in a
456606c3fb27SDimitry Andric       // base specifier per [class.derived.general]p2.
456706c3fb27SDimitry Andric       HandledBaseTypes[Underlying.getUnqualifiedType()] = H;
45680b57cec5SDimitry Andric     }
45690b57cec5SDimitry Andric 
45700b57cec5SDimitry Andric     // Add the type the list of ones we have handled; diagnose if we've already
45710b57cec5SDimitry Andric     // handled it.
457206c3fb27SDimitry Andric     auto R = HandledTypes.insert(
457306c3fb27SDimitry Andric         std::make_pair(H->getCaughtType().getCanonicalType(), H));
45740b57cec5SDimitry Andric     if (!R.second) {
45750b57cec5SDimitry Andric       const CXXCatchStmt *Problem = R.first->second;
45760b57cec5SDimitry Andric       Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
45770b57cec5SDimitry Andric            diag::warn_exception_caught_by_earlier_handler)
45780b57cec5SDimitry Andric           << H->getCaughtType();
45790b57cec5SDimitry Andric       Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
45800b57cec5SDimitry Andric            diag::note_previous_exception_handler)
45810b57cec5SDimitry Andric           << Problem->getCaughtType();
45820b57cec5SDimitry Andric     }
45830b57cec5SDimitry Andric   }
45840b57cec5SDimitry Andric 
45850b57cec5SDimitry Andric   FSI->setHasCXXTry(TryLoc);
45860b57cec5SDimitry Andric 
458706c3fb27SDimitry Andric   return CXXTryStmt::Create(Context, TryLoc, cast<CompoundStmt>(TryBlock),
458806c3fb27SDimitry Andric                             Handlers);
45890b57cec5SDimitry Andric }
45900b57cec5SDimitry Andric 
45910b57cec5SDimitry Andric StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
45920b57cec5SDimitry Andric                                   Stmt *TryBlock, Stmt *Handler) {
45930b57cec5SDimitry Andric   assert(TryBlock && Handler);
45940b57cec5SDimitry Andric 
45950b57cec5SDimitry Andric   sema::FunctionScopeInfo *FSI = getCurFunction();
45960b57cec5SDimitry Andric 
45970b57cec5SDimitry Andric   // SEH __try is incompatible with C++ try. Borland appears to support this,
45980b57cec5SDimitry Andric   // however.
45990b57cec5SDimitry Andric   if (!getLangOpts().Borland) {
4600349cc55cSDimitry Andric     if (FSI->FirstCXXOrObjCTryLoc.isValid()) {
4601349cc55cSDimitry Andric       Diag(TryLoc, diag::err_mixing_cxx_try_seh_try) << FSI->FirstTryType;
4602349cc55cSDimitry Andric       Diag(FSI->FirstCXXOrObjCTryLoc, diag::note_conflicting_try_here)
4603349cc55cSDimitry Andric           << (FSI->FirstTryType == sema::FunctionScopeInfo::TryLocIsCXX
4604349cc55cSDimitry Andric                   ? "'try'"
4605349cc55cSDimitry Andric                   : "'@try'");
46060b57cec5SDimitry Andric     }
46070b57cec5SDimitry Andric   }
46080b57cec5SDimitry Andric 
46090b57cec5SDimitry Andric   FSI->setHasSEHTry(TryLoc);
46100b57cec5SDimitry Andric 
46110b57cec5SDimitry Andric   // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
46120b57cec5SDimitry Andric   // track if they use SEH.
46130b57cec5SDimitry Andric   DeclContext *DC = CurContext;
46140b57cec5SDimitry Andric   while (DC && !DC->isFunctionOrMethod())
46150b57cec5SDimitry Andric     DC = DC->getParent();
46160b57cec5SDimitry Andric   FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
46170b57cec5SDimitry Andric   if (FD)
46180b57cec5SDimitry Andric     FD->setUsesSEHTry(true);
46190b57cec5SDimitry Andric   else
46200b57cec5SDimitry Andric     Diag(TryLoc, diag::err_seh_try_outside_functions);
46210b57cec5SDimitry Andric 
46220b57cec5SDimitry Andric   // Reject __try on unsupported targets.
46230b57cec5SDimitry Andric   if (!Context.getTargetInfo().isSEHTrySupported())
46240b57cec5SDimitry Andric     Diag(TryLoc, diag::err_seh_try_unsupported);
46250b57cec5SDimitry Andric 
46260b57cec5SDimitry Andric   return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
46270b57cec5SDimitry Andric }
46280b57cec5SDimitry Andric 
4629480093f4SDimitry Andric StmtResult Sema::ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr,
46300b57cec5SDimitry Andric                                      Stmt *Block) {
46310b57cec5SDimitry Andric   assert(FilterExpr && Block);
4632480093f4SDimitry Andric   QualType FTy = FilterExpr->getType();
4633480093f4SDimitry Andric   if (!FTy->isIntegerType() && !FTy->isDependentType()) {
4634480093f4SDimitry Andric     return StmtError(
4635480093f4SDimitry Andric         Diag(FilterExpr->getExprLoc(), diag::err_filter_expression_integral)
4636480093f4SDimitry Andric         << FTy);
46370b57cec5SDimitry Andric   }
46380b57cec5SDimitry Andric   return SEHExceptStmt::Create(Context, Loc, FilterExpr, Block);
46390b57cec5SDimitry Andric }
46400b57cec5SDimitry Andric 
46410b57cec5SDimitry Andric void Sema::ActOnStartSEHFinallyBlock() {
46420b57cec5SDimitry Andric   CurrentSEHFinally.push_back(CurScope);
46430b57cec5SDimitry Andric }
46440b57cec5SDimitry Andric 
46450b57cec5SDimitry Andric void Sema::ActOnAbortSEHFinallyBlock() {
46460b57cec5SDimitry Andric   CurrentSEHFinally.pop_back();
46470b57cec5SDimitry Andric }
46480b57cec5SDimitry Andric 
46490b57cec5SDimitry Andric StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
46500b57cec5SDimitry Andric   assert(Block);
46510b57cec5SDimitry Andric   CurrentSEHFinally.pop_back();
46520b57cec5SDimitry Andric   return SEHFinallyStmt::Create(Context, Loc, Block);
46530b57cec5SDimitry Andric }
46540b57cec5SDimitry Andric 
46550b57cec5SDimitry Andric StmtResult
46560b57cec5SDimitry Andric Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
46570b57cec5SDimitry Andric   Scope *SEHTryParent = CurScope;
46580b57cec5SDimitry Andric   while (SEHTryParent && !SEHTryParent->isSEHTryScope())
46590b57cec5SDimitry Andric     SEHTryParent = SEHTryParent->getParent();
46600b57cec5SDimitry Andric   if (!SEHTryParent)
46610b57cec5SDimitry Andric     return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
46620b57cec5SDimitry Andric   CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
46630b57cec5SDimitry Andric 
46640b57cec5SDimitry Andric   return new (Context) SEHLeaveStmt(Loc);
46650b57cec5SDimitry Andric }
46660b57cec5SDimitry Andric 
46670b57cec5SDimitry Andric StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
46680b57cec5SDimitry Andric                                             bool IsIfExists,
46690b57cec5SDimitry Andric                                             NestedNameSpecifierLoc QualifierLoc,
46700b57cec5SDimitry Andric                                             DeclarationNameInfo NameInfo,
46710b57cec5SDimitry Andric                                             Stmt *Nested)
46720b57cec5SDimitry Andric {
46730b57cec5SDimitry Andric   return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
46740b57cec5SDimitry Andric                                              QualifierLoc, NameInfo,
46750b57cec5SDimitry Andric                                              cast<CompoundStmt>(Nested));
46760b57cec5SDimitry Andric }
46770b57cec5SDimitry Andric 
46780b57cec5SDimitry Andric 
46790b57cec5SDimitry Andric StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
46800b57cec5SDimitry Andric                                             bool IsIfExists,
46810b57cec5SDimitry Andric                                             CXXScopeSpec &SS,
46820b57cec5SDimitry Andric                                             UnqualifiedId &Name,
46830b57cec5SDimitry Andric                                             Stmt *Nested) {
46840b57cec5SDimitry Andric   return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
46850b57cec5SDimitry Andric                                     SS.getWithLocInContext(Context),
46860b57cec5SDimitry Andric                                     GetNameFromUnqualifiedId(Name),
46870b57cec5SDimitry Andric                                     Nested);
46880b57cec5SDimitry Andric }
46890b57cec5SDimitry Andric 
46900b57cec5SDimitry Andric RecordDecl*
46910b57cec5SDimitry Andric Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
46920b57cec5SDimitry Andric                                    unsigned NumParams) {
46930b57cec5SDimitry Andric   DeclContext *DC = CurContext;
46940b57cec5SDimitry Andric   while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
46950b57cec5SDimitry Andric     DC = DC->getParent();
46960b57cec5SDimitry Andric 
46970b57cec5SDimitry Andric   RecordDecl *RD = nullptr;
46980b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus)
46995f757f3fSDimitry Andric     RD = CXXRecordDecl::Create(Context, TagTypeKind::Struct, DC, Loc, Loc,
47000b57cec5SDimitry Andric                                /*Id=*/nullptr);
47010b57cec5SDimitry Andric   else
47025f757f3fSDimitry Andric     RD = RecordDecl::Create(Context, TagTypeKind::Struct, DC, Loc, Loc,
47035f757f3fSDimitry Andric                             /*Id=*/nullptr);
47040b57cec5SDimitry Andric 
47050b57cec5SDimitry Andric   RD->setCapturedRecord();
47060b57cec5SDimitry Andric   DC->addDecl(RD);
47070b57cec5SDimitry Andric   RD->setImplicit();
47080b57cec5SDimitry Andric   RD->startDefinition();
47090b57cec5SDimitry Andric 
47100b57cec5SDimitry Andric   assert(NumParams > 0 && "CapturedStmt requires context parameter");
47110b57cec5SDimitry Andric   CD = CapturedDecl::Create(Context, CurContext, NumParams);
47120b57cec5SDimitry Andric   DC->addDecl(CD);
47130b57cec5SDimitry Andric   return RD;
47140b57cec5SDimitry Andric }
47150b57cec5SDimitry Andric 
47160b57cec5SDimitry Andric static bool
47170b57cec5SDimitry Andric buildCapturedStmtCaptureList(Sema &S, CapturedRegionScopeInfo *RSI,
47180b57cec5SDimitry Andric                              SmallVectorImpl<CapturedStmt::Capture> &Captures,
47190b57cec5SDimitry Andric                              SmallVectorImpl<Expr *> &CaptureInits) {
47200b57cec5SDimitry Andric   for (const sema::Capture &Cap : RSI->Captures) {
47210b57cec5SDimitry Andric     if (Cap.isInvalid())
47220b57cec5SDimitry Andric       continue;
47230b57cec5SDimitry Andric 
47240b57cec5SDimitry Andric     // Form the initializer for the capture.
47250b57cec5SDimitry Andric     ExprResult Init = S.BuildCaptureInit(Cap, Cap.getLocation(),
47260b57cec5SDimitry Andric                                          RSI->CapRegionKind == CR_OpenMP);
47270b57cec5SDimitry Andric 
47280b57cec5SDimitry Andric     // FIXME: Bail out now if the capture is not used and the initializer has
47290b57cec5SDimitry Andric     // no side-effects.
47300b57cec5SDimitry Andric 
47310b57cec5SDimitry Andric     // Create a field for this capture.
47320b57cec5SDimitry Andric     FieldDecl *Field = S.BuildCaptureField(RSI->TheRecordDecl, Cap);
47330b57cec5SDimitry Andric 
47340b57cec5SDimitry Andric     // Add the capture to our list of captures.
47350b57cec5SDimitry Andric     if (Cap.isThisCapture()) {
47360b57cec5SDimitry Andric       Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
47370b57cec5SDimitry Andric                                                CapturedStmt::VCK_This));
47380b57cec5SDimitry Andric     } else if (Cap.isVLATypeCapture()) {
47390b57cec5SDimitry Andric       Captures.push_back(
47400b57cec5SDimitry Andric           CapturedStmt::Capture(Cap.getLocation(), CapturedStmt::VCK_VLAType));
47410b57cec5SDimitry Andric     } else {
47420b57cec5SDimitry Andric       assert(Cap.isVariableCapture() && "unknown kind of capture");
47430b57cec5SDimitry Andric 
47440b57cec5SDimitry Andric       if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
47450b57cec5SDimitry Andric         S.setOpenMPCaptureKind(Field, Cap.getVariable(), RSI->OpenMPLevel);
47460b57cec5SDimitry Andric 
4747bdd1243dSDimitry Andric       Captures.push_back(CapturedStmt::Capture(
4748bdd1243dSDimitry Andric           Cap.getLocation(),
4749bdd1243dSDimitry Andric           Cap.isReferenceCapture() ? CapturedStmt::VCK_ByRef
47500b57cec5SDimitry Andric                                    : CapturedStmt::VCK_ByCopy,
4751bdd1243dSDimitry Andric           cast<VarDecl>(Cap.getVariable())));
47520b57cec5SDimitry Andric     }
47530b57cec5SDimitry Andric     CaptureInits.push_back(Init.get());
47540b57cec5SDimitry Andric   }
47550b57cec5SDimitry Andric   return false;
47560b57cec5SDimitry Andric }
47570b57cec5SDimitry Andric 
47580b57cec5SDimitry Andric void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
47590b57cec5SDimitry Andric                                     CapturedRegionKind Kind,
47600b57cec5SDimitry Andric                                     unsigned NumParams) {
47610b57cec5SDimitry Andric   CapturedDecl *CD = nullptr;
47620b57cec5SDimitry Andric   RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
47630b57cec5SDimitry Andric 
47640b57cec5SDimitry Andric   // Build the context parameter
47650b57cec5SDimitry Andric   DeclContext *DC = CapturedDecl::castToDeclContext(CD);
47660b57cec5SDimitry Andric   IdentifierInfo *ParamName = &Context.Idents.get("__context");
47670b57cec5SDimitry Andric   QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
47680b57cec5SDimitry Andric   auto *Param =
47690b57cec5SDimitry Andric       ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
47705f757f3fSDimitry Andric                                 ImplicitParamKind::CapturedContext);
47710b57cec5SDimitry Andric   DC->addDecl(Param);
47720b57cec5SDimitry Andric 
47730b57cec5SDimitry Andric   CD->setContextParam(0, Param);
47740b57cec5SDimitry Andric 
47750b57cec5SDimitry Andric   // Enter the capturing scope for this captured region.
47760b57cec5SDimitry Andric   PushCapturedRegionScope(CurScope, CD, RD, Kind);
47770b57cec5SDimitry Andric 
47780b57cec5SDimitry Andric   if (CurScope)
47790b57cec5SDimitry Andric     PushDeclContext(CurScope, CD);
47800b57cec5SDimitry Andric   else
47810b57cec5SDimitry Andric     CurContext = CD;
47820b57cec5SDimitry Andric 
47830b57cec5SDimitry Andric   PushExpressionEvaluationContext(
47840b57cec5SDimitry Andric       ExpressionEvaluationContext::PotentiallyEvaluated);
478506c3fb27SDimitry Andric   ExprEvalContexts.back().InImmediateEscalatingFunctionContext = false;
47860b57cec5SDimitry Andric }
47870b57cec5SDimitry Andric 
47880b57cec5SDimitry Andric void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
47890b57cec5SDimitry Andric                                     CapturedRegionKind Kind,
4790a7dea167SDimitry Andric                                     ArrayRef<CapturedParamNameType> Params,
4791a7dea167SDimitry Andric                                     unsigned OpenMPCaptureLevel) {
47920b57cec5SDimitry Andric   CapturedDecl *CD = nullptr;
47930b57cec5SDimitry Andric   RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
47940b57cec5SDimitry Andric 
47950b57cec5SDimitry Andric   // Build the context parameter
47960b57cec5SDimitry Andric   DeclContext *DC = CapturedDecl::castToDeclContext(CD);
47970b57cec5SDimitry Andric   bool ContextIsFound = false;
47980b57cec5SDimitry Andric   unsigned ParamNum = 0;
47990b57cec5SDimitry Andric   for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
48000b57cec5SDimitry Andric                                                  E = Params.end();
48010b57cec5SDimitry Andric        I != E; ++I, ++ParamNum) {
48020b57cec5SDimitry Andric     if (I->second.isNull()) {
48030b57cec5SDimitry Andric       assert(!ContextIsFound &&
48040b57cec5SDimitry Andric              "null type has been found already for '__context' parameter");
48050b57cec5SDimitry Andric       IdentifierInfo *ParamName = &Context.Idents.get("__context");
48060b57cec5SDimitry Andric       QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD))
48070b57cec5SDimitry Andric                                .withConst()
48080b57cec5SDimitry Andric                                .withRestrict();
48090b57cec5SDimitry Andric       auto *Param =
48100b57cec5SDimitry Andric           ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
48115f757f3fSDimitry Andric                                     ImplicitParamKind::CapturedContext);
48120b57cec5SDimitry Andric       DC->addDecl(Param);
48130b57cec5SDimitry Andric       CD->setContextParam(ParamNum, Param);
48140b57cec5SDimitry Andric       ContextIsFound = true;
48150b57cec5SDimitry Andric     } else {
48160b57cec5SDimitry Andric       IdentifierInfo *ParamName = &Context.Idents.get(I->first);
48170b57cec5SDimitry Andric       auto *Param =
48180b57cec5SDimitry Andric           ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second,
48195f757f3fSDimitry Andric                                     ImplicitParamKind::CapturedContext);
48200b57cec5SDimitry Andric       DC->addDecl(Param);
48210b57cec5SDimitry Andric       CD->setParam(ParamNum, Param);
48220b57cec5SDimitry Andric     }
48230b57cec5SDimitry Andric   }
48240b57cec5SDimitry Andric   assert(ContextIsFound && "no null type for '__context' parameter");
48250b57cec5SDimitry Andric   if (!ContextIsFound) {
48260b57cec5SDimitry Andric     // Add __context implicitly if it is not specified.
48270b57cec5SDimitry Andric     IdentifierInfo *ParamName = &Context.Idents.get("__context");
48280b57cec5SDimitry Andric     QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
48290b57cec5SDimitry Andric     auto *Param =
48300b57cec5SDimitry Andric         ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
48315f757f3fSDimitry Andric                                   ImplicitParamKind::CapturedContext);
48320b57cec5SDimitry Andric     DC->addDecl(Param);
48330b57cec5SDimitry Andric     CD->setContextParam(ParamNum, Param);
48340b57cec5SDimitry Andric   }
48350b57cec5SDimitry Andric   // Enter the capturing scope for this captured region.
4836a7dea167SDimitry Andric   PushCapturedRegionScope(CurScope, CD, RD, Kind, OpenMPCaptureLevel);
48370b57cec5SDimitry Andric 
48380b57cec5SDimitry Andric   if (CurScope)
48390b57cec5SDimitry Andric     PushDeclContext(CurScope, CD);
48400b57cec5SDimitry Andric   else
48410b57cec5SDimitry Andric     CurContext = CD;
48420b57cec5SDimitry Andric 
48430b57cec5SDimitry Andric   PushExpressionEvaluationContext(
48440b57cec5SDimitry Andric       ExpressionEvaluationContext::PotentiallyEvaluated);
48450b57cec5SDimitry Andric }
48460b57cec5SDimitry Andric 
48470b57cec5SDimitry Andric void Sema::ActOnCapturedRegionError() {
48480b57cec5SDimitry Andric   DiscardCleanupsInEvaluationContext();
48490b57cec5SDimitry Andric   PopExpressionEvaluationContext();
48500b57cec5SDimitry Andric   PopDeclContext();
48510b57cec5SDimitry Andric   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo();
48520b57cec5SDimitry Andric   CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(ScopeRAII.get());
48530b57cec5SDimitry Andric 
48540b57cec5SDimitry Andric   RecordDecl *Record = RSI->TheRecordDecl;
48550b57cec5SDimitry Andric   Record->setInvalidDecl();
48560b57cec5SDimitry Andric 
48570b57cec5SDimitry Andric   SmallVector<Decl*, 4> Fields(Record->fields());
48580b57cec5SDimitry Andric   ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
48590b57cec5SDimitry Andric               SourceLocation(), SourceLocation(), ParsedAttributesView());
48600b57cec5SDimitry Andric }
48610b57cec5SDimitry Andric 
48620b57cec5SDimitry Andric StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
48630b57cec5SDimitry Andric   // Leave the captured scope before we start creating captures in the
48640b57cec5SDimitry Andric   // enclosing scope.
48650b57cec5SDimitry Andric   DiscardCleanupsInEvaluationContext();
48660b57cec5SDimitry Andric   PopExpressionEvaluationContext();
48670b57cec5SDimitry Andric   PopDeclContext();
48680b57cec5SDimitry Andric   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo();
48690b57cec5SDimitry Andric   CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(ScopeRAII.get());
48700b57cec5SDimitry Andric 
48710b57cec5SDimitry Andric   SmallVector<CapturedStmt::Capture, 4> Captures;
48720b57cec5SDimitry Andric   SmallVector<Expr *, 4> CaptureInits;
48730b57cec5SDimitry Andric   if (buildCapturedStmtCaptureList(*this, RSI, Captures, CaptureInits))
48740b57cec5SDimitry Andric     return StmtError();
48750b57cec5SDimitry Andric 
48760b57cec5SDimitry Andric   CapturedDecl *CD = RSI->TheCapturedDecl;
48770b57cec5SDimitry Andric   RecordDecl *RD = RSI->TheRecordDecl;
48780b57cec5SDimitry Andric 
48790b57cec5SDimitry Andric   CapturedStmt *Res = CapturedStmt::Create(
48800b57cec5SDimitry Andric       getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind),
48810b57cec5SDimitry Andric       Captures, CaptureInits, CD, RD);
48820b57cec5SDimitry Andric 
48830b57cec5SDimitry Andric   CD->setBody(Res->getCapturedStmt());
48840b57cec5SDimitry Andric   RD->completeDefinition();
48850b57cec5SDimitry Andric 
48860b57cec5SDimitry Andric   return Res;
48870b57cec5SDimitry Andric }
4888