xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaStmt.cpp (revision e64bea71c21eb42e97aa615188ba91f6cce0d36d)
1 //===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for statements.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CheckExprLifetime.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTLambda.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/CharUnits.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DynamicRecursiveASTVisitor.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/AST/IgnoreExpr.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/AST/TypeOrdering.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Lex/Preprocessor.h"
30 #include "clang/Sema/EnterExpressionEvaluationContext.h"
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/Ownership.h"
34 #include "clang/Sema/Scope.h"
35 #include "clang/Sema/ScopeInfo.h"
36 #include "clang/Sema/SemaCUDA.h"
37 #include "clang/Sema/SemaObjC.h"
38 #include "clang/Sema/SemaOpenMP.h"
39 #include "llvm/ADT/ArrayRef.h"
40 #include "llvm/ADT/DenseMap.h"
41 #include "llvm/ADT/STLExtras.h"
42 #include "llvm/ADT/SmallVector.h"
43 #include "llvm/ADT/StringExtras.h"
44 
45 using namespace clang;
46 using namespace sema;
47 
ActOnExprStmt(ExprResult FE,bool DiscardedValue)48 StmtResult Sema::ActOnExprStmt(ExprResult FE, bool DiscardedValue) {
49   if (FE.isInvalid())
50     return StmtError();
51 
52   FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(), DiscardedValue);
53   if (FE.isInvalid())
54     return StmtError();
55 
56   // C99 6.8.3p2: The expression in an expression statement is evaluated as a
57   // void expression for its side effects.  Conversion to void allows any
58   // operand, even incomplete types.
59 
60   // Same thing in for stmt first clause (when expr) and third clause.
61   return StmtResult(FE.getAs<Stmt>());
62 }
63 
64 
ActOnExprStmtError()65 StmtResult Sema::ActOnExprStmtError() {
66   DiscardCleanupsInEvaluationContext();
67   return StmtError();
68 }
69 
ActOnNullStmt(SourceLocation SemiLoc,bool HasLeadingEmptyMacro)70 StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
71                                bool HasLeadingEmptyMacro) {
72   return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
73 }
74 
ActOnDeclStmt(DeclGroupPtrTy dg,SourceLocation StartLoc,SourceLocation EndLoc)75 StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
76                                SourceLocation EndLoc) {
77   DeclGroupRef DG = dg.get();
78 
79   // If we have an invalid decl, just return an error.
80   if (DG.isNull()) return StmtError();
81 
82   return new (Context) DeclStmt(DG, StartLoc, EndLoc);
83 }
84 
ActOnForEachDeclStmt(DeclGroupPtrTy dg)85 void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
86   DeclGroupRef DG = dg.get();
87 
88   // If we don't have a declaration, or we have an invalid declaration,
89   // just return.
90   if (DG.isNull() || !DG.isSingleDecl())
91     return;
92 
93   Decl *decl = DG.getSingleDecl();
94   if (!decl || decl->isInvalidDecl())
95     return;
96 
97   // Only variable declarations are permitted.
98   VarDecl *var = dyn_cast<VarDecl>(decl);
99   if (!var) {
100     Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
101     decl->setInvalidDecl();
102     return;
103   }
104 
105   // foreach variables are never actually initialized in the way that
106   // the parser came up with.
107   var->setInit(nullptr);
108 
109   // In ARC, we don't need to retain the iteration variable of a fast
110   // enumeration loop.  Rather than actually trying to catch that
111   // during declaration processing, we remove the consequences here.
112   if (getLangOpts().ObjCAutoRefCount) {
113     QualType type = var->getType();
114 
115     // Only do this if we inferred the lifetime.  Inferred lifetime
116     // will show up as a local qualifier because explicit lifetime
117     // should have shown up as an AttributedType instead.
118     if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
119       // Add 'const' and mark the variable as pseudo-strong.
120       var->setType(type.withConst());
121       var->setARCPseudoStrong(true);
122     }
123   }
124 }
125 
126 /// Diagnose unused comparisons, both builtin and overloaded operators.
127 /// For '==' and '!=', suggest fixits for '=' or '|='.
128 ///
129 /// Adding a cast to void (or other expression wrappers) will prevent the
130 /// warning from firing.
DiagnoseUnusedComparison(Sema & S,const Expr * E)131 static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
132   SourceLocation Loc;
133   bool CanAssign;
134   enum { Equality, Inequality, Relational, ThreeWay } Kind;
135 
136   if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
137     if (!Op->isComparisonOp())
138       return false;
139 
140     if (Op->getOpcode() == BO_EQ)
141       Kind = Equality;
142     else if (Op->getOpcode() == BO_NE)
143       Kind = Inequality;
144     else if (Op->getOpcode() == BO_Cmp)
145       Kind = ThreeWay;
146     else {
147       assert(Op->isRelationalOp());
148       Kind = Relational;
149     }
150     Loc = Op->getOperatorLoc();
151     CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
152   } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
153     switch (Op->getOperator()) {
154     case OO_EqualEqual:
155       Kind = Equality;
156       break;
157     case OO_ExclaimEqual:
158       Kind = Inequality;
159       break;
160     case OO_Less:
161     case OO_Greater:
162     case OO_GreaterEqual:
163     case OO_LessEqual:
164       Kind = Relational;
165       break;
166     case OO_Spaceship:
167       Kind = ThreeWay;
168       break;
169     default:
170       return false;
171     }
172 
173     Loc = Op->getOperatorLoc();
174     CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
175   } else {
176     // Not a typo-prone comparison.
177     return false;
178   }
179 
180   // Suppress warnings when the operator, suspicious as it may be, comes from
181   // a macro expansion.
182   if (S.SourceMgr.isMacroBodyExpansion(Loc))
183     return false;
184 
185   S.Diag(Loc, diag::warn_unused_comparison)
186     << (unsigned)Kind << E->getSourceRange();
187 
188   // If the LHS is a plausible entity to assign to, provide a fixit hint to
189   // correct common typos.
190   if (CanAssign) {
191     if (Kind == Inequality)
192       S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
193         << FixItHint::CreateReplacement(Loc, "|=");
194     else if (Kind == Equality)
195       S.Diag(Loc, diag::note_equality_comparison_to_assign)
196         << FixItHint::CreateReplacement(Loc, "=");
197   }
198 
199   return true;
200 }
201 
DiagnoseNoDiscard(Sema & S,const NamedDecl * OffendingDecl,const WarnUnusedResultAttr * A,SourceLocation Loc,SourceRange R1,SourceRange R2,bool IsCtor)202 static bool DiagnoseNoDiscard(Sema &S, const NamedDecl *OffendingDecl,
203                               const WarnUnusedResultAttr *A, SourceLocation Loc,
204                               SourceRange R1, SourceRange R2, bool IsCtor) {
205   if (!A)
206     return false;
207   StringRef Msg = A->getMessage();
208 
209   if (Msg.empty()) {
210     if (OffendingDecl)
211       return S.Diag(Loc, diag::warn_unused_return_type)
212              << IsCtor << A << OffendingDecl << false << R1 << R2;
213     if (IsCtor)
214       return S.Diag(Loc, diag::warn_unused_constructor)
215              << A << false << R1 << R2;
216     return S.Diag(Loc, diag::warn_unused_result) << A << false << R1 << R2;
217   }
218 
219   if (OffendingDecl)
220     return S.Diag(Loc, diag::warn_unused_return_type)
221            << IsCtor << A << OffendingDecl << true << Msg << R1 << R2;
222   if (IsCtor)
223     return S.Diag(Loc, diag::warn_unused_constructor)
224            << A << true << Msg << R1 << R2;
225   return S.Diag(Loc, diag::warn_unused_result) << A << true << Msg << R1 << R2;
226 }
227 
228 namespace {
229 
230 // Diagnoses unused expressions that call functions marked [[nodiscard]],
231 // [[gnu::warn_unused_result]] and similar.
232 // Additionally, a DiagID can be provided to emit a warning in additional
233 // contexts (such as for an unused LHS of a comma expression)
DiagnoseUnused(Sema & S,const Expr * E,std::optional<unsigned> DiagID)234 void DiagnoseUnused(Sema &S, const Expr *E, std::optional<unsigned> DiagID) {
235   bool NoDiscardOnly = !DiagID.has_value();
236 
237   // If we are in an unevaluated expression context, then there can be no unused
238   // results because the results aren't expected to be used in the first place.
239   if (S.isUnevaluatedContext())
240     return;
241 
242   SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc();
243   // In most cases, we don't want to warn if the expression is written in a
244   // macro body, or if the macro comes from a system header. If the offending
245   // expression is a call to a function with the warn_unused_result attribute,
246   // we warn no matter the location. Because of the order in which the various
247   // checks need to happen, we factor out the macro-related test here.
248   bool ShouldSuppress = S.SourceMgr.isMacroBodyExpansion(ExprLoc) ||
249                         S.SourceMgr.isInSystemMacro(ExprLoc);
250 
251   const Expr *WarnExpr;
252   SourceLocation Loc;
253   SourceRange R1, R2;
254   if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, S.Context))
255     return;
256 
257   if (!NoDiscardOnly) {
258     // If this is a GNU statement expression expanded from a macro, it is
259     // probably unused because it is a function-like macro that can be used as
260     // either an expression or statement. Don't warn, because it is almost
261     // certainly a false positive.
262     if (isa<StmtExpr>(E) && Loc.isMacroID())
263       return;
264 
265     // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers.
266     // That macro is frequently used to suppress "unused parameter" warnings,
267     // but its implementation makes clang's -Wunused-value fire. Prevent this.
268     if (isa<ParenExpr>(E->IgnoreImpCasts()) && Loc.isMacroID()) {
269       SourceLocation SpellLoc = Loc;
270       if (S.findMacroSpelling(SpellLoc, "UNREFERENCED_PARAMETER"))
271         return;
272     }
273   }
274 
275   // Okay, we have an unused result.  Depending on what the base expression is,
276   // we might want to make a more specific diagnostic.  Check for one of these
277   // cases now.
278   if (const FullExpr *Temps = dyn_cast<FullExpr>(E))
279     E = Temps->getSubExpr();
280   if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
281     E = TempExpr->getSubExpr();
282 
283   if (DiagnoseUnusedComparison(S, E))
284     return;
285 
286   E = WarnExpr;
287   if (const auto *Cast = dyn_cast<CastExpr>(E))
288     if (Cast->getCastKind() == CK_NoOp ||
289         Cast->getCastKind() == CK_ConstructorConversion ||
290         Cast->getCastKind() == CK_IntegralCast)
291       E = Cast->getSubExpr()->IgnoreImpCasts();
292 
293   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
294     if (E->getType()->isVoidType())
295       return;
296 
297     auto [OffendingDecl, A] = CE->getUnusedResultAttr(S.Context);
298     if (DiagnoseNoDiscard(S, OffendingDecl,
299                           cast_or_null<WarnUnusedResultAttr>(A), Loc, R1, R2,
300                           /*isCtor=*/false))
301       return;
302 
303     // If the callee has attribute pure, const, or warn_unused_result, warn with
304     // a more specific message to make it clear what is happening. If the call
305     // is written in a macro body, only warn if it has the warn_unused_result
306     // attribute.
307     if (const Decl *FD = CE->getCalleeDecl()) {
308       if (ShouldSuppress)
309         return;
310       if (FD->hasAttr<PureAttr>()) {
311         S.Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
312         return;
313       }
314       if (FD->hasAttr<ConstAttr>()) {
315         S.Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
316         return;
317       }
318     }
319   } else if (const auto *CE = dyn_cast<CXXConstructExpr>(E)) {
320     if (const CXXConstructorDecl *Ctor = CE->getConstructor()) {
321       const NamedDecl *OffendingDecl = nullptr;
322       const auto *A = Ctor->getAttr<WarnUnusedResultAttr>();
323       if (!A) {
324         OffendingDecl = Ctor->getParent();
325         A = OffendingDecl->getAttr<WarnUnusedResultAttr>();
326       }
327       if (DiagnoseNoDiscard(S, OffendingDecl, A, Loc, R1, R2,
328                             /*isCtor=*/true))
329         return;
330     }
331   } else if (const auto *ILE = dyn_cast<InitListExpr>(E)) {
332     if (const TagDecl *TD = ILE->getType()->getAsTagDecl()) {
333 
334       if (DiagnoseNoDiscard(S, TD, TD->getAttr<WarnUnusedResultAttr>(), Loc, R1,
335                             R2, /*isCtor=*/false))
336         return;
337     }
338   } else if (ShouldSuppress)
339     return;
340 
341   E = WarnExpr;
342   if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
343     if (S.getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
344       S.Diag(Loc, diag::err_arc_unused_init_message) << R1;
345       return;
346     }
347     const ObjCMethodDecl *MD = ME->getMethodDecl();
348     if (MD) {
349       if (DiagnoseNoDiscard(S, nullptr, MD->getAttr<WarnUnusedResultAttr>(),
350                             Loc, R1, R2,
351                             /*isCtor=*/false))
352         return;
353     }
354   } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
355     const Expr *Source = POE->getSyntacticForm();
356     // Handle the actually selected call of an OpenMP specialized call.
357     if (S.LangOpts.OpenMP && isa<CallExpr>(Source) &&
358         POE->getNumSemanticExprs() == 1 &&
359         isa<CallExpr>(POE->getSemanticExpr(0)))
360       return DiagnoseUnused(S, POE->getSemanticExpr(0), DiagID);
361     if (isa<ObjCSubscriptRefExpr>(Source))
362       DiagID = diag::warn_unused_container_subscript_expr;
363     else if (isa<ObjCPropertyRefExpr>(Source))
364       DiagID = diag::warn_unused_property_expr;
365   } else if (const CXXFunctionalCastExpr *FC
366                                        = dyn_cast<CXXFunctionalCastExpr>(E)) {
367     const Expr *E = FC->getSubExpr();
368     if (const CXXBindTemporaryExpr *TE = dyn_cast<CXXBindTemporaryExpr>(E))
369       E = TE->getSubExpr();
370     if (isa<CXXTemporaryObjectExpr>(E))
371       return;
372     if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E))
373       if (const CXXRecordDecl *RD = CE->getType()->getAsCXXRecordDecl())
374         if (!RD->getAttr<WarnUnusedAttr>())
375           return;
376   }
377 
378   if (NoDiscardOnly)
379     return;
380 
381   // Diagnose "(void*) blah" as a typo for "(void) blah".
382   if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
383     TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
384     QualType T = TI->getType();
385 
386     // We really do want to use the non-canonical type here.
387     if (T == S.Context.VoidPtrTy) {
388       PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
389 
390       S.Diag(Loc, diag::warn_unused_voidptr)
391           << FixItHint::CreateRemoval(TL.getStarLoc());
392       return;
393     }
394   }
395 
396   // Tell the user to assign it into a variable to force a volatile load if this
397   // isn't an array.
398   if (E->isGLValue() && E->getType().isVolatileQualified() &&
399       !E->getType()->isArrayType()) {
400     S.Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
401     return;
402   }
403 
404   // Do not diagnose use of a comma operator in a SFINAE context because the
405   // type of the left operand could be used for SFINAE, so technically it is
406   // *used*.
407   if (DiagID == diag::warn_unused_comma_left_operand && S.isSFINAEContext())
408     return;
409 
410   S.DiagIfReachable(Loc, llvm::ArrayRef<const Stmt *>(E),
411                     S.PDiag(*DiagID) << R1 << R2);
412 }
413 } // namespace
414 
DiagnoseUnusedExprResult(const Stmt * S,unsigned DiagID)415 void Sema::DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID) {
416   if (const LabelStmt *Label = dyn_cast_if_present<LabelStmt>(S))
417     S = Label->getSubStmt();
418 
419   const Expr *E = dyn_cast_if_present<Expr>(S);
420   if (!E)
421     return;
422 
423   DiagnoseUnused(*this, E, DiagID);
424 }
425 
ActOnStartOfCompoundStmt(bool IsStmtExpr)426 void Sema::ActOnStartOfCompoundStmt(bool IsStmtExpr) {
427   PushCompoundScope(IsStmtExpr);
428 }
429 
ActOnAfterCompoundStatementLeadingPragmas()430 void Sema::ActOnAfterCompoundStatementLeadingPragmas() {
431   if (getCurFPFeatures().isFPConstrained()) {
432     FunctionScopeInfo *FSI = getCurFunction();
433     assert(FSI);
434     FSI->setUsesFPIntrin();
435   }
436 }
437 
ActOnFinishOfCompoundStmt()438 void Sema::ActOnFinishOfCompoundStmt() {
439   PopCompoundScope();
440 }
441 
getCurCompoundScope() const442 sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
443   return getCurFunction()->CompoundScopes.back();
444 }
445 
ActOnCompoundStmt(SourceLocation L,SourceLocation R,ArrayRef<Stmt * > Elts,bool isStmtExpr)446 StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
447                                    ArrayRef<Stmt *> Elts, bool isStmtExpr) {
448   const unsigned NumElts = Elts.size();
449 
450   // If we're in C mode, check that we don't have any decls after stmts.  If
451   // so, emit an extension diagnostic in C89 and potentially a warning in later
452   // versions.
453   const unsigned MixedDeclsCodeID = getLangOpts().C99
454                                         ? diag::warn_mixed_decls_code
455                                         : diag::ext_mixed_decls_code;
456   if (!getLangOpts().CPlusPlus && !Diags.isIgnored(MixedDeclsCodeID, L)) {
457     // Note that __extension__ can be around a decl.
458     unsigned i = 0;
459     // Skip over all declarations.
460     for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
461       /*empty*/;
462 
463     // We found the end of the list or a statement.  Scan for another declstmt.
464     for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
465       /*empty*/;
466 
467     if (i != NumElts) {
468       Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
469       Diag(D->getLocation(), MixedDeclsCodeID);
470     }
471   }
472 
473   // Check for suspicious empty body (null statement) in `for' and `while'
474   // statements.  Don't do anything for template instantiations, this just adds
475   // noise.
476   if (NumElts != 0 && !CurrentInstantiationScope &&
477       getCurCompoundScope().HasEmptyLoopBodies) {
478     for (unsigned i = 0; i != NumElts - 1; ++i)
479       DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
480   }
481 
482   // Calculate difference between FP options in this compound statement and in
483   // the enclosing one. If this is a function body, take the difference against
484   // default options. In this case the difference will indicate options that are
485   // changed upon entry to the statement.
486   FPOptions FPO = (getCurFunction()->CompoundScopes.size() == 1)
487                       ? FPOptions(getLangOpts())
488                       : getCurCompoundScope().InitialFPFeatures;
489   FPOptionsOverride FPDiff = getCurFPFeatures().getChangesFrom(FPO);
490 
491   return CompoundStmt::Create(Context, Elts, FPDiff, L, R);
492 }
493 
494 ExprResult
ActOnCaseExpr(SourceLocation CaseLoc,ExprResult Val)495 Sema::ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val) {
496   if (!Val.get())
497     return Val;
498 
499   if (DiagnoseUnexpandedParameterPack(Val.get()))
500     return ExprError();
501 
502   // If we're not inside a switch, let the 'case' statement handling diagnose
503   // this. Just clean up after the expression as best we can.
504   if (getCurFunction()->SwitchStack.empty())
505     return ActOnFinishFullExpr(Val.get(), Val.get()->getExprLoc(), false,
506                                getLangOpts().CPlusPlus11);
507 
508   Expr *CondExpr =
509       getCurFunction()->SwitchStack.back().getPointer()->getCond();
510   if (!CondExpr)
511     return ExprError();
512   QualType CondType = CondExpr->getType();
513 
514   auto CheckAndFinish = [&](Expr *E) {
515     if (CondType->isDependentType() || E->isTypeDependent())
516       return ExprResult(E);
517 
518     if (getLangOpts().CPlusPlus11) {
519       // C++11 [stmt.switch]p2: the constant-expression shall be a converted
520       // constant expression of the promoted type of the switch condition.
521       llvm::APSInt TempVal;
522       return CheckConvertedConstantExpression(E, CondType, TempVal,
523                                               CCEKind::CaseValue);
524     }
525 
526     ExprResult ER = E;
527     if (!E->isValueDependent())
528       ER = VerifyIntegerConstantExpression(E, AllowFoldKind::Allow);
529     if (!ER.isInvalid())
530       ER = DefaultLvalueConversion(ER.get());
531     if (!ER.isInvalid())
532       ER = ImpCastExprToType(ER.get(), CondType, CK_IntegralCast);
533     if (!ER.isInvalid())
534       ER = ActOnFinishFullExpr(ER.get(), ER.get()->getExprLoc(), false);
535     return ER;
536   };
537 
538   return CheckAndFinish(Val.get());
539 }
540 
541 StmtResult
ActOnCaseStmt(SourceLocation CaseLoc,ExprResult LHSVal,SourceLocation DotDotDotLoc,ExprResult RHSVal,SourceLocation ColonLoc)542 Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHSVal,
543                     SourceLocation DotDotDotLoc, ExprResult RHSVal,
544                     SourceLocation ColonLoc) {
545   assert((LHSVal.isInvalid() || LHSVal.get()) && "missing LHS value");
546   assert((DotDotDotLoc.isInvalid() ? RHSVal.isUnset()
547                                    : RHSVal.isInvalid() || RHSVal.get()) &&
548          "missing RHS value");
549 
550   if (getCurFunction()->SwitchStack.empty()) {
551     Diag(CaseLoc, diag::err_case_not_in_switch);
552     return StmtError();
553   }
554 
555   if (LHSVal.isInvalid() || RHSVal.isInvalid()) {
556     getCurFunction()->SwitchStack.back().setInt(true);
557     return StmtError();
558   }
559 
560   if (LangOpts.OpenACC &&
561       getCurScope()->isInOpenACCComputeConstructScope(Scope::SwitchScope)) {
562     Diag(CaseLoc, diag::err_acc_branch_in_out_compute_construct)
563         << /*branch*/ 0 << /*into*/ 1;
564     return StmtError();
565   }
566 
567   auto *CS = CaseStmt::Create(Context, LHSVal.get(), RHSVal.get(),
568                               CaseLoc, DotDotDotLoc, ColonLoc);
569   getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(CS);
570   return CS;
571 }
572 
ActOnCaseStmtBody(Stmt * S,Stmt * SubStmt)573 void Sema::ActOnCaseStmtBody(Stmt *S, Stmt *SubStmt) {
574   cast<CaseStmt>(S)->setSubStmt(SubStmt);
575 }
576 
577 StmtResult
ActOnDefaultStmt(SourceLocation DefaultLoc,SourceLocation ColonLoc,Stmt * SubStmt,Scope * CurScope)578 Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
579                        Stmt *SubStmt, Scope *CurScope) {
580   if (getCurFunction()->SwitchStack.empty()) {
581     Diag(DefaultLoc, diag::err_default_not_in_switch);
582     return SubStmt;
583   }
584 
585   if (LangOpts.OpenACC &&
586       getCurScope()->isInOpenACCComputeConstructScope(Scope::SwitchScope)) {
587     Diag(DefaultLoc, diag::err_acc_branch_in_out_compute_construct)
588         << /*branch*/ 0 << /*into*/ 1;
589     return StmtError();
590   }
591 
592   DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
593   getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(DS);
594   return DS;
595 }
596 
597 StmtResult
ActOnLabelStmt(SourceLocation IdentLoc,LabelDecl * TheDecl,SourceLocation ColonLoc,Stmt * SubStmt)598 Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
599                      SourceLocation ColonLoc, Stmt *SubStmt) {
600   // If the label was multiply defined, reject it now.
601   if (TheDecl->getStmt()) {
602     Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
603     Diag(TheDecl->getLocation(), diag::note_previous_definition);
604     return SubStmt;
605   }
606 
607   ReservedIdentifierStatus Status = TheDecl->isReserved(getLangOpts());
608   if (isReservedInAllContexts(Status) &&
609       !Context.getSourceManager().isInSystemHeader(IdentLoc))
610     Diag(IdentLoc, diag::warn_reserved_extern_symbol)
611         << TheDecl << static_cast<int>(Status);
612 
613   // If this label is in a compute construct scope, we need to make sure we
614   // check gotos in/out.
615   if (getCurScope()->isInOpenACCComputeConstructScope())
616     setFunctionHasBranchProtectedScope();
617 
618   // OpenACC3.3 2.14.4:
619   // The update directive is executable.  It must not appear in place of the
620   // statement following an 'if', 'while', 'do', 'switch', or 'label' in C or
621   // C++.
622   if (isa<OpenACCUpdateConstruct>(SubStmt)) {
623     Diag(SubStmt->getBeginLoc(), diag::err_acc_update_as_body) << /*Label*/ 4;
624     SubStmt = new (Context) NullStmt(SubStmt->getBeginLoc());
625   }
626 
627   // Otherwise, things are good.  Fill in the declaration and return it.
628   LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
629   TheDecl->setStmt(LS);
630   if (!TheDecl->isGnuLocal()) {
631     TheDecl->setLocStart(IdentLoc);
632     if (!TheDecl->isMSAsmLabel()) {
633       // Don't update the location of MS ASM labels.  These will result in
634       // a diagnostic, and changing the location here will mess that up.
635       TheDecl->setLocation(IdentLoc);
636     }
637   }
638   return LS;
639 }
640 
BuildAttributedStmt(SourceLocation AttrsLoc,ArrayRef<const Attr * > Attrs,Stmt * SubStmt)641 StmtResult Sema::BuildAttributedStmt(SourceLocation AttrsLoc,
642                                      ArrayRef<const Attr *> Attrs,
643                                      Stmt *SubStmt) {
644   // FIXME: this code should move when a planned refactoring around statement
645   // attributes lands.
646   for (const auto *A : Attrs) {
647     if (A->getKind() == attr::MustTail) {
648       if (!checkAndRewriteMustTailAttr(SubStmt, *A)) {
649         return SubStmt;
650       }
651       setFunctionHasMustTail();
652     }
653   }
654 
655   return AttributedStmt::Create(Context, AttrsLoc, Attrs, SubStmt);
656 }
657 
ActOnAttributedStmt(const ParsedAttributes & Attrs,Stmt * SubStmt)658 StmtResult Sema::ActOnAttributedStmt(const ParsedAttributes &Attrs,
659                                      Stmt *SubStmt) {
660   SmallVector<const Attr *, 1> SemanticAttrs;
661   ProcessStmtAttributes(SubStmt, Attrs, SemanticAttrs);
662   if (!SemanticAttrs.empty())
663     return BuildAttributedStmt(Attrs.Range.getBegin(), SemanticAttrs, SubStmt);
664   // If none of the attributes applied, that's fine, we can recover by
665   // returning the substatement directly instead of making an AttributedStmt
666   // with no attributes on it.
667   return SubStmt;
668 }
669 
checkAndRewriteMustTailAttr(Stmt * St,const Attr & MTA)670 bool Sema::checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA) {
671   ReturnStmt *R = cast<ReturnStmt>(St);
672   Expr *E = R->getRetValue();
673 
674   if (CurContext->isDependentContext() || (E && E->isInstantiationDependent()))
675     // We have to suspend our check until template instantiation time.
676     return true;
677 
678   if (!checkMustTailAttr(St, MTA))
679     return false;
680 
681   // FIXME: Replace Expr::IgnoreImplicitAsWritten() with this function.
682   // Currently it does not skip implicit constructors in an initialization
683   // context.
684   auto IgnoreImplicitAsWritten = [](Expr *E) -> Expr * {
685     return IgnoreExprNodes(E, IgnoreImplicitAsWrittenSingleStep,
686                            IgnoreElidableImplicitConstructorSingleStep);
687   };
688 
689   // Now that we have verified that 'musttail' is valid here, rewrite the
690   // return value to remove all implicit nodes, but retain parentheses.
691   R->setRetValue(IgnoreImplicitAsWritten(E));
692   return true;
693 }
694 
checkMustTailAttr(const Stmt * St,const Attr & MTA)695 bool Sema::checkMustTailAttr(const Stmt *St, const Attr &MTA) {
696   assert(!CurContext->isDependentContext() &&
697          "musttail cannot be checked from a dependent context");
698 
699   // FIXME: Add Expr::IgnoreParenImplicitAsWritten() with this definition.
700   auto IgnoreParenImplicitAsWritten = [](const Expr *E) -> const Expr * {
701     return IgnoreExprNodes(const_cast<Expr *>(E), IgnoreParensSingleStep,
702                            IgnoreImplicitAsWrittenSingleStep,
703                            IgnoreElidableImplicitConstructorSingleStep);
704   };
705 
706   const Expr *E = cast<ReturnStmt>(St)->getRetValue();
707   const auto *CE = dyn_cast_or_null<CallExpr>(IgnoreParenImplicitAsWritten(E));
708 
709   if (!CE) {
710     Diag(St->getBeginLoc(), diag::err_musttail_needs_call) << &MTA;
711     return false;
712   }
713 
714   if (const FunctionDecl *CalleeDecl = CE->getDirectCallee();
715       CalleeDecl && CalleeDecl->hasAttr<NotTailCalledAttr>()) {
716     Diag(St->getBeginLoc(), diag::err_musttail_mismatch) << /*show-function-callee=*/true << CalleeDecl;
717     Diag(CalleeDecl->getLocation(), diag::note_musttail_disabled_by_not_tail_called);
718     return false;
719   }
720 
721   if (const auto *EWC = dyn_cast<ExprWithCleanups>(E)) {
722     if (EWC->cleanupsHaveSideEffects()) {
723       Diag(St->getBeginLoc(), diag::err_musttail_needs_trivial_args) << &MTA;
724       return false;
725     }
726   }
727 
728   // We need to determine the full function type (including "this" type, if any)
729   // for both caller and callee.
730   struct FuncType {
731     enum {
732       ft_non_member,
733       ft_static_member,
734       ft_non_static_member,
735       ft_pointer_to_member,
736     } MemberType = ft_non_member;
737 
738     QualType This;
739     const FunctionProtoType *Func;
740     const CXXMethodDecl *Method = nullptr;
741   } CallerType, CalleeType;
742 
743   auto GetMethodType = [this, St, MTA](const CXXMethodDecl *CMD, FuncType &Type,
744                                        bool IsCallee) -> bool {
745     if (isa<CXXConstructorDecl, CXXDestructorDecl>(CMD)) {
746       Diag(St->getBeginLoc(), diag::err_musttail_structors_forbidden)
747           << IsCallee << isa<CXXDestructorDecl>(CMD);
748       if (IsCallee)
749         Diag(CMD->getBeginLoc(), diag::note_musttail_structors_forbidden)
750             << isa<CXXDestructorDecl>(CMD);
751       Diag(MTA.getLocation(), diag::note_tail_call_required) << &MTA;
752       return false;
753     }
754     if (CMD->isStatic())
755       Type.MemberType = FuncType::ft_static_member;
756     else {
757       Type.This = CMD->getFunctionObjectParameterType();
758       Type.MemberType = FuncType::ft_non_static_member;
759     }
760     Type.Func = CMD->getType()->castAs<FunctionProtoType>();
761     return true;
762   };
763 
764   const auto *CallerDecl = dyn_cast<FunctionDecl>(CurContext);
765 
766   // Find caller function signature.
767   if (!CallerDecl) {
768     int ContextType;
769     if (isa<BlockDecl>(CurContext))
770       ContextType = 0;
771     else if (isa<ObjCMethodDecl>(CurContext))
772       ContextType = 1;
773     else
774       ContextType = 2;
775     Diag(St->getBeginLoc(), diag::err_musttail_forbidden_from_this_context)
776         << &MTA << ContextType;
777     return false;
778   } else if (const auto *CMD = dyn_cast<CXXMethodDecl>(CurContext)) {
779     // Caller is a class/struct method.
780     if (!GetMethodType(CMD, CallerType, false))
781       return false;
782   } else {
783     // Caller is a non-method function.
784     CallerType.Func = CallerDecl->getType()->getAs<FunctionProtoType>();
785   }
786 
787   const Expr *CalleeExpr = CE->getCallee()->IgnoreParens();
788   const auto *CalleeBinOp = dyn_cast<BinaryOperator>(CalleeExpr);
789   SourceLocation CalleeLoc = CE->getCalleeDecl()
790                                  ? CE->getCalleeDecl()->getBeginLoc()
791                                  : St->getBeginLoc();
792 
793   // Find callee function signature.
794   if (const CXXMethodDecl *CMD =
795           dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl())) {
796     // Call is: obj.method(), obj->method(), functor(), etc.
797     if (!GetMethodType(CMD, CalleeType, true))
798       return false;
799   } else if (CalleeBinOp && CalleeBinOp->isPtrMemOp()) {
800     // Call is: obj->*method_ptr or obj.*method_ptr
801     const auto *MPT =
802         CalleeBinOp->getRHS()->getType()->castAs<MemberPointerType>();
803     CalleeType.This =
804         Context.getTypeDeclType(MPT->getMostRecentCXXRecordDecl());
805     CalleeType.Func = MPT->getPointeeType()->castAs<FunctionProtoType>();
806     CalleeType.MemberType = FuncType::ft_pointer_to_member;
807   } else if (isa<CXXPseudoDestructorExpr>(CalleeExpr)) {
808     Diag(St->getBeginLoc(), diag::err_musttail_structors_forbidden)
809         << /* IsCallee = */ 1 << /* IsDestructor = */ 1;
810     Diag(MTA.getLocation(), diag::note_tail_call_required) << &MTA;
811     return false;
812   } else {
813     // Non-method function.
814     CalleeType.Func =
815         CalleeExpr->getType()->getPointeeType()->getAs<FunctionProtoType>();
816   }
817 
818   // Both caller and callee must have a prototype (no K&R declarations).
819   if (!CalleeType.Func || !CallerType.Func) {
820     Diag(St->getBeginLoc(), diag::err_musttail_needs_prototype) << &MTA;
821     if (!CalleeType.Func && CE->getDirectCallee()) {
822       Diag(CE->getDirectCallee()->getBeginLoc(),
823            diag::note_musttail_fix_non_prototype);
824     }
825     if (!CallerType.Func)
826       Diag(CallerDecl->getBeginLoc(), diag::note_musttail_fix_non_prototype);
827     return false;
828   }
829 
830   // Caller and callee must have matching calling conventions.
831   //
832   // Some calling conventions are physically capable of supporting tail calls
833   // even if the function types don't perfectly match. LLVM is currently too
834   // strict to allow this, but if LLVM added support for this in the future, we
835   // could exit early here and skip the remaining checks if the functions are
836   // using such a calling convention.
837   if (CallerType.Func->getCallConv() != CalleeType.Func->getCallConv()) {
838     if (const auto *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl()))
839       Diag(St->getBeginLoc(), diag::err_musttail_callconv_mismatch)
840           << true << ND->getDeclName();
841     else
842       Diag(St->getBeginLoc(), diag::err_musttail_callconv_mismatch) << false;
843     Diag(CalleeLoc, diag::note_musttail_callconv_mismatch)
844         << FunctionType::getNameForCallConv(CallerType.Func->getCallConv())
845         << FunctionType::getNameForCallConv(CalleeType.Func->getCallConv());
846     Diag(MTA.getLocation(), diag::note_tail_call_required) << &MTA;
847     return false;
848   }
849 
850   if (CalleeType.Func->isVariadic() || CallerType.Func->isVariadic()) {
851     Diag(St->getBeginLoc(), diag::err_musttail_no_variadic) << &MTA;
852     return false;
853   }
854 
855   const auto *CalleeDecl = CE->getCalleeDecl();
856   if (CalleeDecl && CalleeDecl->hasAttr<CXX11NoReturnAttr>()) {
857     Diag(St->getBeginLoc(), diag::err_musttail_no_return) << &MTA;
858     return false;
859   }
860 
861   // Caller and callee must match in whether they have a "this" parameter.
862   if (CallerType.This.isNull() != CalleeType.This.isNull()) {
863     if (const auto *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
864       Diag(St->getBeginLoc(), diag::err_musttail_member_mismatch)
865           << CallerType.MemberType << CalleeType.MemberType << true
866           << ND->getDeclName();
867       Diag(CalleeLoc, diag::note_musttail_callee_defined_here)
868           << ND->getDeclName();
869     } else
870       Diag(St->getBeginLoc(), diag::err_musttail_member_mismatch)
871           << CallerType.MemberType << CalleeType.MemberType << false;
872     Diag(MTA.getLocation(), diag::note_tail_call_required) << &MTA;
873     return false;
874   }
875 
876   auto CheckTypesMatch = [this](FuncType CallerType, FuncType CalleeType,
877                                 PartialDiagnostic &PD) -> bool {
878     enum {
879       ft_different_class,
880       ft_parameter_arity,
881       ft_parameter_mismatch,
882       ft_return_type,
883     };
884 
885     auto DoTypesMatch = [this, &PD](QualType A, QualType B,
886                                     unsigned Select) -> bool {
887       if (!Context.hasSimilarType(A, B)) {
888         PD << Select << A.getUnqualifiedType() << B.getUnqualifiedType();
889         return false;
890       }
891       return true;
892     };
893 
894     if (!CallerType.This.isNull() &&
895         !DoTypesMatch(CallerType.This, CalleeType.This, ft_different_class))
896       return false;
897 
898     if (!DoTypesMatch(CallerType.Func->getReturnType(),
899                       CalleeType.Func->getReturnType(), ft_return_type))
900       return false;
901 
902     if (CallerType.Func->getNumParams() != CalleeType.Func->getNumParams()) {
903       PD << ft_parameter_arity << CallerType.Func->getNumParams()
904          << CalleeType.Func->getNumParams();
905       return false;
906     }
907 
908     ArrayRef<QualType> CalleeParams = CalleeType.Func->getParamTypes();
909     ArrayRef<QualType> CallerParams = CallerType.Func->getParamTypes();
910     size_t N = CallerType.Func->getNumParams();
911     for (size_t I = 0; I < N; I++) {
912       if (!DoTypesMatch(CalleeParams[I], CallerParams[I],
913                         ft_parameter_mismatch)) {
914         PD << static_cast<int>(I) + 1;
915         return false;
916       }
917     }
918 
919     return true;
920   };
921 
922   PartialDiagnostic PD = PDiag(diag::note_musttail_mismatch);
923   if (!CheckTypesMatch(CallerType, CalleeType, PD)) {
924     if (const auto *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl()))
925       Diag(St->getBeginLoc(), diag::err_musttail_mismatch)
926           << true << ND->getDeclName();
927     else
928       Diag(St->getBeginLoc(), diag::err_musttail_mismatch) << false;
929     Diag(CalleeLoc, PD);
930     Diag(MTA.getLocation(), diag::note_tail_call_required) << &MTA;
931     return false;
932   }
933 
934   // The lifetimes of locals and incoming function parameters must end before
935   // the call, because we can't have a stack frame to store them, so diagnose
936   // any pointers or references to them passed into the musttail call.
937   for (auto ArgExpr : CE->arguments()) {
938     InitializedEntity Entity = InitializedEntity::InitializeParameter(
939         Context, ArgExpr->getType(), false);
940     checkExprLifetimeMustTailArg(*this, Entity, const_cast<Expr *>(ArgExpr));
941   }
942 
943   return true;
944 }
945 
946 namespace {
947 class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
948   typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
949   Sema &SemaRef;
950 public:
CommaVisitor(Sema & SemaRef)951   CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
VisitBinaryOperator(BinaryOperator * E)952   void VisitBinaryOperator(BinaryOperator *E) {
953     if (E->getOpcode() == BO_Comma)
954       SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc());
955     EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E);
956   }
957 };
958 }
959 
ActOnIfStmt(SourceLocation IfLoc,IfStatementKind StatementKind,SourceLocation LParenLoc,Stmt * InitStmt,ConditionResult Cond,SourceLocation RParenLoc,Stmt * thenStmt,SourceLocation ElseLoc,Stmt * elseStmt)960 StmtResult Sema::ActOnIfStmt(SourceLocation IfLoc,
961                              IfStatementKind StatementKind,
962                              SourceLocation LParenLoc, Stmt *InitStmt,
963                              ConditionResult Cond, SourceLocation RParenLoc,
964                              Stmt *thenStmt, SourceLocation ElseLoc,
965                              Stmt *elseStmt) {
966   if (Cond.isInvalid())
967     return StmtError();
968 
969   bool ConstevalOrNegatedConsteval =
970       StatementKind == IfStatementKind::ConstevalNonNegated ||
971       StatementKind == IfStatementKind::ConstevalNegated;
972 
973   Expr *CondExpr = Cond.get().second;
974   assert((CondExpr || ConstevalOrNegatedConsteval) &&
975          "If statement: missing condition");
976   // Only call the CommaVisitor when not C89 due to differences in scope flags.
977   if (CondExpr && (getLangOpts().C99 || getLangOpts().CPlusPlus) &&
978       !Diags.isIgnored(diag::warn_comma_operator, CondExpr->getExprLoc()))
979     CommaVisitor(*this).Visit(CondExpr);
980 
981   if (!ConstevalOrNegatedConsteval && !elseStmt)
982     DiagnoseEmptyStmtBody(RParenLoc, thenStmt, diag::warn_empty_if_body);
983 
984   if (ConstevalOrNegatedConsteval ||
985       StatementKind == IfStatementKind::Constexpr) {
986     auto DiagnoseLikelihood = [&](const Stmt *S) {
987       if (const Attr *A = Stmt::getLikelihoodAttr(S)) {
988         Diags.Report(A->getLocation(),
989                      diag::warn_attribute_has_no_effect_on_compile_time_if)
990             << A << ConstevalOrNegatedConsteval << A->getRange();
991         Diags.Report(IfLoc,
992                      diag::note_attribute_has_no_effect_on_compile_time_if_here)
993             << ConstevalOrNegatedConsteval
994             << SourceRange(IfLoc, (ConstevalOrNegatedConsteval
995                                        ? thenStmt->getBeginLoc()
996                                        : LParenLoc)
997                                       .getLocWithOffset(-1));
998       }
999     };
1000     DiagnoseLikelihood(thenStmt);
1001     DiagnoseLikelihood(elseStmt);
1002   } else {
1003     std::tuple<bool, const Attr *, const Attr *> LHC =
1004         Stmt::determineLikelihoodConflict(thenStmt, elseStmt);
1005     if (std::get<0>(LHC)) {
1006       const Attr *ThenAttr = std::get<1>(LHC);
1007       const Attr *ElseAttr = std::get<2>(LHC);
1008       Diags.Report(ThenAttr->getLocation(),
1009                    diag::warn_attributes_likelihood_ifstmt_conflict)
1010           << ThenAttr << ThenAttr->getRange();
1011       Diags.Report(ElseAttr->getLocation(), diag::note_conflicting_attribute)
1012           << ElseAttr << ElseAttr->getRange();
1013     }
1014   }
1015 
1016   if (ConstevalOrNegatedConsteval) {
1017     bool Immediate = ExprEvalContexts.back().Context ==
1018                      ExpressionEvaluationContext::ImmediateFunctionContext;
1019     if (CurContext->isFunctionOrMethod()) {
1020       const auto *FD =
1021           dyn_cast<FunctionDecl>(Decl::castFromDeclContext(CurContext));
1022       if (FD && FD->isImmediateFunction())
1023         Immediate = true;
1024     }
1025     if (isUnevaluatedContext() || Immediate)
1026       Diags.Report(IfLoc, diag::warn_consteval_if_always_true) << Immediate;
1027   }
1028 
1029   // OpenACC3.3 2.14.4:
1030   // The update directive is executable.  It must not appear in place of the
1031   // statement following an 'if', 'while', 'do', 'switch', or 'label' in C or
1032   // C++.
1033   if (isa<OpenACCUpdateConstruct>(thenStmt)) {
1034     Diag(thenStmt->getBeginLoc(), diag::err_acc_update_as_body) << /*if*/ 0;
1035     thenStmt = new (Context) NullStmt(thenStmt->getBeginLoc());
1036   }
1037 
1038   return BuildIfStmt(IfLoc, StatementKind, LParenLoc, InitStmt, Cond, RParenLoc,
1039                      thenStmt, ElseLoc, elseStmt);
1040 }
1041 
BuildIfStmt(SourceLocation IfLoc,IfStatementKind StatementKind,SourceLocation LParenLoc,Stmt * InitStmt,ConditionResult Cond,SourceLocation RParenLoc,Stmt * thenStmt,SourceLocation ElseLoc,Stmt * elseStmt)1042 StmtResult Sema::BuildIfStmt(SourceLocation IfLoc,
1043                              IfStatementKind StatementKind,
1044                              SourceLocation LParenLoc, Stmt *InitStmt,
1045                              ConditionResult Cond, SourceLocation RParenLoc,
1046                              Stmt *thenStmt, SourceLocation ElseLoc,
1047                              Stmt *elseStmt) {
1048   if (Cond.isInvalid())
1049     return StmtError();
1050 
1051   if (StatementKind != IfStatementKind::Ordinary ||
1052       isa<ObjCAvailabilityCheckExpr>(Cond.get().second))
1053     setFunctionHasBranchProtectedScope();
1054 
1055   return IfStmt::Create(Context, IfLoc, StatementKind, InitStmt,
1056                         Cond.get().first, Cond.get().second, LParenLoc,
1057                         RParenLoc, thenStmt, ElseLoc, elseStmt);
1058 }
1059 
1060 namespace {
1061   struct CaseCompareFunctor {
operator ()__anon4f6f6e9d0d11::CaseCompareFunctor1062     bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
1063                     const llvm::APSInt &RHS) {
1064       return LHS.first < RHS;
1065     }
operator ()__anon4f6f6e9d0d11::CaseCompareFunctor1066     bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
1067                     const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
1068       return LHS.first < RHS.first;
1069     }
operator ()__anon4f6f6e9d0d11::CaseCompareFunctor1070     bool operator()(const llvm::APSInt &LHS,
1071                     const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
1072       return LHS < RHS.first;
1073     }
1074   };
1075 }
1076 
1077 /// CmpCaseVals - Comparison predicate for sorting case values.
1078 ///
CmpCaseVals(const std::pair<llvm::APSInt,CaseStmt * > & lhs,const std::pair<llvm::APSInt,CaseStmt * > & rhs)1079 static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
1080                         const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
1081   if (lhs.first < rhs.first)
1082     return true;
1083 
1084   if (lhs.first == rhs.first &&
1085       lhs.second->getCaseLoc() < rhs.second->getCaseLoc())
1086     return true;
1087   return false;
1088 }
1089 
1090 /// CmpEnumVals - Comparison predicate for sorting enumeration values.
1091 ///
CmpEnumVals(const std::pair<llvm::APSInt,EnumConstantDecl * > & lhs,const std::pair<llvm::APSInt,EnumConstantDecl * > & rhs)1092 static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
1093                         const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
1094 {
1095   return lhs.first < rhs.first;
1096 }
1097 
1098 /// EqEnumVals - Comparison preficate for uniqing enumeration values.
1099 ///
EqEnumVals(const std::pair<llvm::APSInt,EnumConstantDecl * > & lhs,const std::pair<llvm::APSInt,EnumConstantDecl * > & rhs)1100 static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
1101                        const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
1102 {
1103   return lhs.first == rhs.first;
1104 }
1105 
1106 /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
1107 /// potentially integral-promoted expression @p expr.
GetTypeBeforeIntegralPromotion(const Expr * & E)1108 static QualType GetTypeBeforeIntegralPromotion(const Expr *&E) {
1109   if (const auto *FE = dyn_cast<FullExpr>(E))
1110     E = FE->getSubExpr();
1111   while (const auto *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
1112     if (ImpCast->getCastKind() != CK_IntegralCast) break;
1113     E = ImpCast->getSubExpr();
1114   }
1115   return E->getType();
1116 }
1117 
CheckSwitchCondition(SourceLocation SwitchLoc,Expr * Cond)1118 ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) {
1119   class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
1120     Expr *Cond;
1121 
1122   public:
1123     SwitchConvertDiagnoser(Expr *Cond)
1124         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
1125           Cond(Cond) {}
1126 
1127     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1128                                          QualType T) override {
1129       return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
1130     }
1131 
1132     SemaDiagnosticBuilder diagnoseIncomplete(
1133         Sema &S, SourceLocation Loc, QualType T) override {
1134       return S.Diag(Loc, diag::err_switch_incomplete_class_type)
1135                << T << Cond->getSourceRange();
1136     }
1137 
1138     SemaDiagnosticBuilder diagnoseExplicitConv(
1139         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
1140       return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
1141     }
1142 
1143     SemaDiagnosticBuilder noteExplicitConv(
1144         Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1145       return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
1146         << ConvTy->isEnumeralType() << ConvTy;
1147     }
1148 
1149     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
1150                                             QualType T) override {
1151       return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
1152     }
1153 
1154     SemaDiagnosticBuilder noteAmbiguous(
1155         Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1156       return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
1157       << ConvTy->isEnumeralType() << ConvTy;
1158     }
1159 
1160     SemaDiagnosticBuilder diagnoseConversion(
1161         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
1162       llvm_unreachable("conversion functions are permitted");
1163     }
1164   } SwitchDiagnoser(Cond);
1165 
1166   ExprResult CondResult =
1167       PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
1168   if (CondResult.isInvalid())
1169     return ExprError();
1170 
1171   // FIXME: PerformContextualImplicitConversion doesn't always tell us if it
1172   // failed and produced a diagnostic.
1173   Cond = CondResult.get();
1174   if (!Cond->isTypeDependent() &&
1175       !Cond->getType()->isIntegralOrEnumerationType())
1176     return ExprError();
1177 
1178   // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
1179   return UsualUnaryConversions(Cond);
1180 }
1181 
ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,SourceLocation LParenLoc,Stmt * InitStmt,ConditionResult Cond,SourceLocation RParenLoc)1182 StmtResult Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
1183                                         SourceLocation LParenLoc,
1184                                         Stmt *InitStmt, ConditionResult Cond,
1185                                         SourceLocation RParenLoc) {
1186   Expr *CondExpr = Cond.get().second;
1187   assert((Cond.isInvalid() || CondExpr) && "switch with no condition");
1188 
1189   if (CondExpr && !CondExpr->isTypeDependent()) {
1190     // We have already converted the expression to an integral or enumeration
1191     // type, when we parsed the switch condition. There are cases where we don't
1192     // have an appropriate type, e.g. a typo-expr Cond was corrected to an
1193     // inappropriate-type expr, we just return an error.
1194     if (!CondExpr->getType()->isIntegralOrEnumerationType())
1195       return StmtError();
1196     if (CondExpr->isKnownToHaveBooleanValue()) {
1197       // switch(bool_expr) {...} is often a programmer error, e.g.
1198       //   switch(n && mask) { ... }  // Doh - should be "n & mask".
1199       // One can always use an if statement instead of switch(bool_expr).
1200       Diag(SwitchLoc, diag::warn_bool_switch_condition)
1201           << CondExpr->getSourceRange();
1202     }
1203   }
1204 
1205   setFunctionHasBranchIntoScope();
1206 
1207   auto *SS = SwitchStmt::Create(Context, InitStmt, Cond.get().first, CondExpr,
1208                                 LParenLoc, RParenLoc);
1209   getCurFunction()->SwitchStack.push_back(
1210       FunctionScopeInfo::SwitchInfo(SS, false));
1211   return SS;
1212 }
1213 
AdjustAPSInt(llvm::APSInt & Val,unsigned BitWidth,bool IsSigned)1214 static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
1215   Val = Val.extOrTrunc(BitWidth);
1216   Val.setIsSigned(IsSigned);
1217 }
1218 
1219 /// Check the specified case value is in range for the given unpromoted switch
1220 /// type.
checkCaseValue(Sema & S,SourceLocation Loc,const llvm::APSInt & Val,unsigned UnpromotedWidth,bool UnpromotedSign)1221 static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
1222                            unsigned UnpromotedWidth, bool UnpromotedSign) {
1223   // In C++11 onwards, this is checked by the language rules.
1224   if (S.getLangOpts().CPlusPlus11)
1225     return;
1226 
1227   // If the case value was signed and negative and the switch expression is
1228   // unsigned, don't bother to warn: this is implementation-defined behavior.
1229   // FIXME: Introduce a second, default-ignored warning for this case?
1230   if (UnpromotedWidth < Val.getBitWidth()) {
1231     llvm::APSInt ConvVal(Val);
1232     AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
1233     AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
1234     // FIXME: Use different diagnostics for overflow  in conversion to promoted
1235     // type versus "switch expression cannot have this value". Use proper
1236     // IntRange checking rather than just looking at the unpromoted type here.
1237     if (ConvVal != Val)
1238       S.Diag(Loc, diag::warn_case_value_overflow) << toString(Val, 10)
1239                                                   << toString(ConvVal, 10);
1240   }
1241 }
1242 
1243 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
1244 
1245 /// Returns true if we should emit a diagnostic about this case expression not
1246 /// being a part of the enum used in the switch controlling expression.
ShouldDiagnoseSwitchCaseNotInEnum(const Sema & S,const EnumDecl * ED,const Expr * CaseExpr,EnumValsTy::iterator & EI,EnumValsTy::iterator & EIEnd,const llvm::APSInt & Val)1247 static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
1248                                               const EnumDecl *ED,
1249                                               const Expr *CaseExpr,
1250                                               EnumValsTy::iterator &EI,
1251                                               EnumValsTy::iterator &EIEnd,
1252                                               const llvm::APSInt &Val) {
1253   if (!ED->isClosed())
1254     return false;
1255 
1256   if (const DeclRefExpr *DRE =
1257           dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
1258     if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
1259       QualType VarType = VD->getType();
1260       QualType EnumType = S.Context.getTypeDeclType(ED);
1261       if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
1262           S.Context.hasSameUnqualifiedType(EnumType, VarType))
1263         return false;
1264     }
1265   }
1266 
1267   if (ED->hasAttr<FlagEnumAttr>())
1268     return !S.IsValueInFlagEnum(ED, Val, false);
1269 
1270   while (EI != EIEnd && EI->first < Val)
1271     EI++;
1272 
1273   if (EI != EIEnd && EI->first == Val)
1274     return false;
1275 
1276   return true;
1277 }
1278 
checkEnumTypesInSwitchStmt(Sema & S,const Expr * Cond,const Expr * Case)1279 static void checkEnumTypesInSwitchStmt(Sema &S, const Expr *Cond,
1280                                        const Expr *Case) {
1281   QualType CondType = Cond->getType();
1282   QualType CaseType = Case->getType();
1283 
1284   const EnumType *CondEnumType = CondType->getAs<EnumType>();
1285   const EnumType *CaseEnumType = CaseType->getAs<EnumType>();
1286   if (!CondEnumType || !CaseEnumType)
1287     return;
1288 
1289   // Ignore anonymous enums.
1290   if (!CondEnumType->getDecl()->getIdentifier() &&
1291       !CondEnumType->getDecl()->getTypedefNameForAnonDecl())
1292     return;
1293   if (!CaseEnumType->getDecl()->getIdentifier() &&
1294       !CaseEnumType->getDecl()->getTypedefNameForAnonDecl())
1295     return;
1296 
1297   if (S.Context.hasSameUnqualifiedType(CondType, CaseType))
1298     return;
1299 
1300   S.Diag(Case->getExprLoc(), diag::warn_comparison_of_mixed_enum_types_switch)
1301       << CondType << CaseType << Cond->getSourceRange()
1302       << Case->getSourceRange();
1303 }
1304 
1305 StmtResult
ActOnFinishSwitchStmt(SourceLocation SwitchLoc,Stmt * Switch,Stmt * BodyStmt)1306 Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
1307                             Stmt *BodyStmt) {
1308   SwitchStmt *SS = cast<SwitchStmt>(Switch);
1309   bool CaseListIsIncomplete = getCurFunction()->SwitchStack.back().getInt();
1310   assert(SS == getCurFunction()->SwitchStack.back().getPointer() &&
1311          "switch stack missing push/pop!");
1312 
1313   getCurFunction()->SwitchStack.pop_back();
1314 
1315   if (!BodyStmt) return StmtError();
1316 
1317   // OpenACC3.3 2.14.4:
1318   // The update directive is executable.  It must not appear in place of the
1319   // statement following an 'if', 'while', 'do', 'switch', or 'label' in C or
1320   // C++.
1321   if (isa<OpenACCUpdateConstruct>(BodyStmt)) {
1322     Diag(BodyStmt->getBeginLoc(), diag::err_acc_update_as_body) << /*switch*/ 3;
1323     BodyStmt = new (Context) NullStmt(BodyStmt->getBeginLoc());
1324   }
1325 
1326   SS->setBody(BodyStmt, SwitchLoc);
1327 
1328   Expr *CondExpr = SS->getCond();
1329   if (!CondExpr) return StmtError();
1330 
1331   QualType CondType = CondExpr->getType();
1332 
1333   // C++ 6.4.2.p2:
1334   // Integral promotions are performed (on the switch condition).
1335   //
1336   // A case value unrepresentable by the original switch condition
1337   // type (before the promotion) doesn't make sense, even when it can
1338   // be represented by the promoted type.  Therefore we need to find
1339   // the pre-promotion type of the switch condition.
1340   const Expr *CondExprBeforePromotion = CondExpr;
1341   QualType CondTypeBeforePromotion =
1342       GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
1343 
1344   // Get the bitwidth of the switched-on value after promotions. We must
1345   // convert the integer case values to this width before comparison.
1346   bool HasDependentValue
1347     = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
1348   unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
1349   bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
1350 
1351   // Get the width and signedness that the condition might actually have, for
1352   // warning purposes.
1353   // FIXME: Grab an IntRange for the condition rather than using the unpromoted
1354   // type.
1355   unsigned CondWidthBeforePromotion
1356     = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
1357   bool CondIsSignedBeforePromotion
1358     = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
1359 
1360   // Accumulate all of the case values in a vector so that we can sort them
1361   // and detect duplicates.  This vector contains the APInt for the case after
1362   // it has been converted to the condition type.
1363   typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
1364   CaseValsTy CaseVals;
1365 
1366   // Keep track of any GNU case ranges we see.  The APSInt is the low value.
1367   typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
1368   CaseRangesTy CaseRanges;
1369 
1370   DefaultStmt *TheDefaultStmt = nullptr;
1371 
1372   bool CaseListIsErroneous = false;
1373 
1374   // FIXME: We'd better diagnose missing or duplicate default labels even
1375   // in the dependent case. Because default labels themselves are never
1376   // dependent.
1377   for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
1378        SC = SC->getNextSwitchCase()) {
1379 
1380     if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
1381       if (TheDefaultStmt) {
1382         Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
1383         Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
1384 
1385         // FIXME: Remove the default statement from the switch block so that
1386         // we'll return a valid AST.  This requires recursing down the AST and
1387         // finding it, not something we are set up to do right now.  For now,
1388         // just lop the entire switch stmt out of the AST.
1389         CaseListIsErroneous = true;
1390       }
1391       TheDefaultStmt = DS;
1392 
1393     } else {
1394       CaseStmt *CS = cast<CaseStmt>(SC);
1395 
1396       Expr *Lo = CS->getLHS();
1397 
1398       if (Lo->isValueDependent()) {
1399         HasDependentValue = true;
1400         break;
1401       }
1402 
1403       // We already verified that the expression has a constant value;
1404       // get that value (prior to conversions).
1405       const Expr *LoBeforePromotion = Lo;
1406       GetTypeBeforeIntegralPromotion(LoBeforePromotion);
1407       llvm::APSInt LoVal = LoBeforePromotion->EvaluateKnownConstInt(Context);
1408 
1409       // Check the unconverted value is within the range of possible values of
1410       // the switch expression.
1411       checkCaseValue(*this, Lo->getBeginLoc(), LoVal, CondWidthBeforePromotion,
1412                      CondIsSignedBeforePromotion);
1413 
1414       // FIXME: This duplicates the check performed for warn_not_in_enum below.
1415       checkEnumTypesInSwitchStmt(*this, CondExprBeforePromotion,
1416                                  LoBeforePromotion);
1417 
1418       // Convert the value to the same width/sign as the condition.
1419       AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
1420 
1421       // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
1422       if (CS->getRHS()) {
1423         if (CS->getRHS()->isValueDependent()) {
1424           HasDependentValue = true;
1425           break;
1426         }
1427         CaseRanges.push_back(std::make_pair(LoVal, CS));
1428       } else
1429         CaseVals.push_back(std::make_pair(LoVal, CS));
1430     }
1431   }
1432 
1433   if (!HasDependentValue) {
1434     // If we don't have a default statement, check whether the
1435     // condition is constant.
1436     llvm::APSInt ConstantCondValue;
1437     bool HasConstantCond = false;
1438     if (!TheDefaultStmt) {
1439       Expr::EvalResult Result;
1440       HasConstantCond = CondExpr->EvaluateAsInt(Result, Context,
1441                                                 Expr::SE_AllowSideEffects);
1442       if (Result.Val.isInt())
1443         ConstantCondValue = Result.Val.getInt();
1444       assert(!HasConstantCond ||
1445              (ConstantCondValue.getBitWidth() == CondWidth &&
1446               ConstantCondValue.isSigned() == CondIsSigned));
1447       Diag(SwitchLoc, diag::warn_switch_default);
1448     }
1449     bool ShouldCheckConstantCond = HasConstantCond;
1450 
1451     // Sort all the scalar case values so we can easily detect duplicates.
1452     llvm::stable_sort(CaseVals, CmpCaseVals);
1453 
1454     if (!CaseVals.empty()) {
1455       for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
1456         if (ShouldCheckConstantCond &&
1457             CaseVals[i].first == ConstantCondValue)
1458           ShouldCheckConstantCond = false;
1459 
1460         if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
1461           // If we have a duplicate, report it.
1462           // First, determine if either case value has a name
1463           StringRef PrevString, CurrString;
1464           Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
1465           Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
1466           if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
1467             PrevString = DeclRef->getDecl()->getName();
1468           }
1469           if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
1470             CurrString = DeclRef->getDecl()->getName();
1471           }
1472           SmallString<16> CaseValStr;
1473           CaseVals[i-1].first.toString(CaseValStr);
1474 
1475           if (PrevString == CurrString)
1476             Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
1477                  diag::err_duplicate_case)
1478                 << (PrevString.empty() ? CaseValStr.str() : PrevString);
1479           else
1480             Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
1481                  diag::err_duplicate_case_differing_expr)
1482                 << (PrevString.empty() ? CaseValStr.str() : PrevString)
1483                 << (CurrString.empty() ? CaseValStr.str() : CurrString)
1484                 << CaseValStr;
1485 
1486           Diag(CaseVals[i - 1].second->getLHS()->getBeginLoc(),
1487                diag::note_duplicate_case_prev);
1488           // FIXME: We really want to remove the bogus case stmt from the
1489           // substmt, but we have no way to do this right now.
1490           CaseListIsErroneous = true;
1491         }
1492       }
1493     }
1494 
1495     // Detect duplicate case ranges, which usually don't exist at all in
1496     // the first place.
1497     if (!CaseRanges.empty()) {
1498       // Sort all the case ranges by their low value so we can easily detect
1499       // overlaps between ranges.
1500       llvm::stable_sort(CaseRanges);
1501 
1502       // Scan the ranges, computing the high values and removing empty ranges.
1503       std::vector<llvm::APSInt> HiVals;
1504       for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1505         llvm::APSInt &LoVal = CaseRanges[i].first;
1506         CaseStmt *CR = CaseRanges[i].second;
1507         Expr *Hi = CR->getRHS();
1508 
1509         const Expr *HiBeforePromotion = Hi;
1510         GetTypeBeforeIntegralPromotion(HiBeforePromotion);
1511         llvm::APSInt HiVal = HiBeforePromotion->EvaluateKnownConstInt(Context);
1512 
1513         // Check the unconverted value is within the range of possible values of
1514         // the switch expression.
1515         checkCaseValue(*this, Hi->getBeginLoc(), HiVal,
1516                        CondWidthBeforePromotion, CondIsSignedBeforePromotion);
1517 
1518         // Convert the value to the same width/sign as the condition.
1519         AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
1520 
1521         // If the low value is bigger than the high value, the case is empty.
1522         if (LoVal > HiVal) {
1523           Diag(CR->getLHS()->getBeginLoc(), diag::warn_case_empty_range)
1524               << SourceRange(CR->getLHS()->getBeginLoc(), Hi->getEndLoc());
1525           CaseRanges.erase(CaseRanges.begin()+i);
1526           --i;
1527           --e;
1528           continue;
1529         }
1530 
1531         if (ShouldCheckConstantCond &&
1532             LoVal <= ConstantCondValue &&
1533             ConstantCondValue <= HiVal)
1534           ShouldCheckConstantCond = false;
1535 
1536         HiVals.push_back(HiVal);
1537       }
1538 
1539       // Rescan the ranges, looking for overlap with singleton values and other
1540       // ranges.  Since the range list is sorted, we only need to compare case
1541       // ranges with their neighbors.
1542       for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1543         llvm::APSInt &CRLo = CaseRanges[i].first;
1544         llvm::APSInt &CRHi = HiVals[i];
1545         CaseStmt *CR = CaseRanges[i].second;
1546 
1547         // Check to see whether the case range overlaps with any
1548         // singleton cases.
1549         CaseStmt *OverlapStmt = nullptr;
1550         llvm::APSInt OverlapVal(32);
1551 
1552         // Find the smallest value >= the lower bound.  If I is in the
1553         // case range, then we have overlap.
1554         CaseValsTy::iterator I =
1555             llvm::lower_bound(CaseVals, CRLo, CaseCompareFunctor());
1556         if (I != CaseVals.end() && I->first < CRHi) {
1557           OverlapVal  = I->first;   // Found overlap with scalar.
1558           OverlapStmt = I->second;
1559         }
1560 
1561         // Find the smallest value bigger than the upper bound.
1562         I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1563         if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1564           OverlapVal  = (I-1)->first;      // Found overlap with scalar.
1565           OverlapStmt = (I-1)->second;
1566         }
1567 
1568         // Check to see if this case stmt overlaps with the subsequent
1569         // case range.
1570         if (i && CRLo <= HiVals[i-1]) {
1571           OverlapVal  = HiVals[i-1];       // Found overlap with range.
1572           OverlapStmt = CaseRanges[i-1].second;
1573         }
1574 
1575         if (OverlapStmt) {
1576           // If we have a duplicate, report it.
1577           Diag(CR->getLHS()->getBeginLoc(), diag::err_duplicate_case)
1578               << toString(OverlapVal, 10);
1579           Diag(OverlapStmt->getLHS()->getBeginLoc(),
1580                diag::note_duplicate_case_prev);
1581           // FIXME: We really want to remove the bogus case stmt from the
1582           // substmt, but we have no way to do this right now.
1583           CaseListIsErroneous = true;
1584         }
1585       }
1586     }
1587 
1588     // Complain if we have a constant condition and we didn't find a match.
1589     if (!CaseListIsErroneous && !CaseListIsIncomplete &&
1590         ShouldCheckConstantCond) {
1591       // TODO: it would be nice if we printed enums as enums, chars as
1592       // chars, etc.
1593       Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1594         << toString(ConstantCondValue, 10)
1595         << CondExpr->getSourceRange();
1596     }
1597 
1598     // Check to see if switch is over an Enum and handles all of its
1599     // values.  We only issue a warning if there is not 'default:', but
1600     // we still do the analysis to preserve this information in the AST
1601     // (which can be used by flow-based analyes).
1602     //
1603     const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
1604 
1605     // If switch has default case, then ignore it.
1606     if (!CaseListIsErroneous && !CaseListIsIncomplete && !HasConstantCond &&
1607         ET && ET->getDecl()->isCompleteDefinition() &&
1608         !ET->getDecl()->enumerators().empty()) {
1609       const EnumDecl *ED = ET->getDecl();
1610       EnumValsTy EnumVals;
1611 
1612       // Gather all enum values, set their type and sort them,
1613       // allowing easier comparison with CaseVals.
1614       for (auto *EDI : ED->enumerators()) {
1615         llvm::APSInt Val = EDI->getInitVal();
1616         AdjustAPSInt(Val, CondWidth, CondIsSigned);
1617         EnumVals.push_back(std::make_pair(Val, EDI));
1618       }
1619       llvm::stable_sort(EnumVals, CmpEnumVals);
1620       auto EI = EnumVals.begin(), EIEnd = llvm::unique(EnumVals, EqEnumVals);
1621 
1622       // See which case values aren't in enum.
1623       for (CaseValsTy::const_iterator CI = CaseVals.begin();
1624           CI != CaseVals.end(); CI++) {
1625         Expr *CaseExpr = CI->second->getLHS();
1626         if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1627                                               CI->first))
1628           Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1629             << CondTypeBeforePromotion;
1630       }
1631 
1632       // See which of case ranges aren't in enum
1633       EI = EnumVals.begin();
1634       for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1635           RI != CaseRanges.end(); RI++) {
1636         Expr *CaseExpr = RI->second->getLHS();
1637         if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1638                                               RI->first))
1639           Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1640             << CondTypeBeforePromotion;
1641 
1642         llvm::APSInt Hi =
1643           RI->second->getRHS()->EvaluateKnownConstInt(Context);
1644         AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1645 
1646         CaseExpr = RI->second->getRHS();
1647         if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1648                                               Hi))
1649           Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1650             << CondTypeBeforePromotion;
1651       }
1652 
1653       // Check which enum vals aren't in switch
1654       auto CI = CaseVals.begin();
1655       auto RI = CaseRanges.begin();
1656       bool hasCasesNotInSwitch = false;
1657 
1658       SmallVector<DeclarationName,8> UnhandledNames;
1659 
1660       for (EI = EnumVals.begin(); EI != EIEnd; EI++) {
1661         // Don't warn about omitted unavailable EnumConstantDecls.
1662         switch (EI->second->getAvailability()) {
1663         case AR_Deprecated:
1664           // Deprecated enumerators need to be handled: they may be deprecated,
1665           // but can still occur.
1666           break;
1667 
1668         case AR_Unavailable:
1669           // Omitting an unavailable enumerator is ok; it should never occur.
1670           continue;
1671 
1672         case AR_NotYetIntroduced:
1673           // Partially available enum constants should be present. Note that we
1674           // suppress -Wunguarded-availability diagnostics for such uses.
1675         case AR_Available:
1676           break;
1677         }
1678 
1679         if (EI->second->hasAttr<UnusedAttr>())
1680           continue;
1681 
1682         // Drop unneeded case values
1683         while (CI != CaseVals.end() && CI->first < EI->first)
1684           CI++;
1685 
1686         if (CI != CaseVals.end() && CI->first == EI->first)
1687           continue;
1688 
1689         // Drop unneeded case ranges
1690         for (; RI != CaseRanges.end(); RI++) {
1691           llvm::APSInt Hi =
1692             RI->second->getRHS()->EvaluateKnownConstInt(Context);
1693           AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1694           if (EI->first <= Hi)
1695             break;
1696         }
1697 
1698         if (RI == CaseRanges.end() || EI->first < RI->first) {
1699           hasCasesNotInSwitch = true;
1700           UnhandledNames.push_back(EI->second->getDeclName());
1701         }
1702       }
1703 
1704       if (TheDefaultStmt && UnhandledNames.empty() && ED->isClosedNonFlag())
1705         Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
1706 
1707       // Produce a nice diagnostic if multiple values aren't handled.
1708       if (!UnhandledNames.empty()) {
1709         auto DB = Diag(CondExpr->getExprLoc(), TheDefaultStmt
1710                                                    ? diag::warn_def_missing_case
1711                                                    : diag::warn_missing_case)
1712                   << CondExpr->getSourceRange() << (int)UnhandledNames.size();
1713 
1714         for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
1715              I != E; ++I)
1716           DB << UnhandledNames[I];
1717       }
1718 
1719       if (!hasCasesNotInSwitch)
1720         SS->setAllEnumCasesCovered();
1721     }
1722   }
1723 
1724   if (BodyStmt)
1725     DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), BodyStmt,
1726                           diag::warn_empty_switch_body);
1727 
1728   // FIXME: If the case list was broken is some way, we don't have a good system
1729   // to patch it up.  Instead, just return the whole substmt as broken.
1730   if (CaseListIsErroneous)
1731     return StmtError();
1732 
1733   return SS;
1734 }
1735 
1736 void
DiagnoseAssignmentEnum(QualType DstType,QualType SrcType,Expr * SrcExpr)1737 Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1738                              Expr *SrcExpr) {
1739 
1740   const auto *ET = DstType->getAs<EnumType>();
1741   if (!ET)
1742     return;
1743 
1744   if (!SrcType->isIntegerType() ||
1745       Context.hasSameUnqualifiedType(SrcType, DstType))
1746     return;
1747 
1748   if (SrcExpr->isTypeDependent() || SrcExpr->isValueDependent())
1749     return;
1750 
1751   const EnumDecl *ED = ET->getDecl();
1752   if (!ED->isClosed())
1753     return;
1754 
1755   if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
1756     return;
1757 
1758   std::optional<llvm::APSInt> RHSVal = SrcExpr->getIntegerConstantExpr(Context);
1759   if (!RHSVal)
1760     return;
1761 
1762   // Get the bitwidth of the enum value before promotions.
1763   unsigned DstWidth = Context.getIntWidth(DstType);
1764   bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1765   AdjustAPSInt(*RHSVal, DstWidth, DstIsSigned);
1766 
1767   if (ED->hasAttr<FlagEnumAttr>()) {
1768     if (!IsValueInFlagEnum(ED, *RHSVal, /*AllowMask=*/true))
1769       Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1770           << DstType.getUnqualifiedType();
1771     return;
1772   }
1773 
1774   typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1775       EnumValsTy;
1776   EnumValsTy EnumVals;
1777 
1778   // Gather all enum values, set their type and sort them,
1779   // allowing easier comparison with rhs constant.
1780   for (auto *EDI : ED->enumerators()) {
1781     llvm::APSInt Val = EDI->getInitVal();
1782     AdjustAPSInt(Val, DstWidth, DstIsSigned);
1783     EnumVals.emplace_back(Val, EDI);
1784   }
1785   if (EnumVals.empty())
1786     return;
1787   llvm::stable_sort(EnumVals, CmpEnumVals);
1788   EnumValsTy::iterator EIend = llvm::unique(EnumVals, EqEnumVals);
1789 
1790   // See which values aren't in the enum.
1791   EnumValsTy::const_iterator EI = EnumVals.begin();
1792   while (EI != EIend && EI->first < *RHSVal)
1793     EI++;
1794   if (EI == EIend || EI->first != *RHSVal) {
1795     Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1796         << DstType.getUnqualifiedType();
1797   }
1798 }
1799 
ActOnWhileStmt(SourceLocation WhileLoc,SourceLocation LParenLoc,ConditionResult Cond,SourceLocation RParenLoc,Stmt * Body)1800 StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc,
1801                                 SourceLocation LParenLoc, ConditionResult Cond,
1802                                 SourceLocation RParenLoc, Stmt *Body) {
1803   if (Cond.isInvalid())
1804     return StmtError();
1805 
1806   auto CondVal = Cond.get();
1807   CheckBreakContinueBinding(CondVal.second);
1808 
1809   if (CondVal.second &&
1810       !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc()))
1811     CommaVisitor(*this).Visit(CondVal.second);
1812 
1813   // OpenACC3.3 2.14.4:
1814   // The update directive is executable.  It must not appear in place of the
1815   // statement following an 'if', 'while', 'do', 'switch', or 'label' in C or
1816   // C++.
1817   if (isa<OpenACCUpdateConstruct>(Body)) {
1818     Diag(Body->getBeginLoc(), diag::err_acc_update_as_body) << /*while*/ 1;
1819     Body = new (Context) NullStmt(Body->getBeginLoc());
1820   }
1821 
1822   if (isa<NullStmt>(Body))
1823     getCurCompoundScope().setHasEmptyLoopBodies();
1824 
1825   return WhileStmt::Create(Context, CondVal.first, CondVal.second, Body,
1826                            WhileLoc, LParenLoc, RParenLoc);
1827 }
1828 
1829 StmtResult
ActOnDoStmt(SourceLocation DoLoc,Stmt * Body,SourceLocation WhileLoc,SourceLocation CondLParen,Expr * Cond,SourceLocation CondRParen)1830 Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
1831                   SourceLocation WhileLoc, SourceLocation CondLParen,
1832                   Expr *Cond, SourceLocation CondRParen) {
1833   assert(Cond && "ActOnDoStmt(): missing expression");
1834 
1835   CheckBreakContinueBinding(Cond);
1836   ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond);
1837   if (CondResult.isInvalid())
1838     return StmtError();
1839   Cond = CondResult.get();
1840 
1841   CondResult = ActOnFinishFullExpr(Cond, DoLoc, /*DiscardedValue*/ false);
1842   if (CondResult.isInvalid())
1843     return StmtError();
1844   Cond = CondResult.get();
1845 
1846   // Only call the CommaVisitor for C89 due to differences in scope flags.
1847   if (Cond && !getLangOpts().C99 && !getLangOpts().CPlusPlus &&
1848       !Diags.isIgnored(diag::warn_comma_operator, Cond->getExprLoc()))
1849     CommaVisitor(*this).Visit(Cond);
1850 
1851   // OpenACC3.3 2.14.4:
1852   // The update directive is executable.  It must not appear in place of the
1853   // statement following an 'if', 'while', 'do', 'switch', or 'label' in C or
1854   // C++.
1855   if (isa<OpenACCUpdateConstruct>(Body)) {
1856     Diag(Body->getBeginLoc(), diag::err_acc_update_as_body) << /*do*/ 2;
1857     Body = new (Context) NullStmt(Body->getBeginLoc());
1858   }
1859 
1860   return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
1861 }
1862 
1863 namespace {
1864   // Use SetVector since the diagnostic cares about the ordering of the Decl's.
1865   using DeclSetVector = llvm::SmallSetVector<VarDecl *, 8>;
1866 
1867   // This visitor will traverse a conditional statement and store all
1868   // the evaluated decls into a vector.  Simple is set to true if none
1869   // of the excluded constructs are used.
1870   class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1871     DeclSetVector &Decls;
1872     SmallVectorImpl<SourceRange> &Ranges;
1873     bool Simple;
1874   public:
1875     typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1876 
DeclExtractor(Sema & S,DeclSetVector & Decls,SmallVectorImpl<SourceRange> & Ranges)1877     DeclExtractor(Sema &S, DeclSetVector &Decls,
1878                   SmallVectorImpl<SourceRange> &Ranges) :
1879         Inherited(S.Context),
1880         Decls(Decls),
1881         Ranges(Ranges),
1882         Simple(true) {}
1883 
isSimple()1884     bool isSimple() { return Simple; }
1885 
1886     // Replaces the method in EvaluatedExprVisitor.
VisitMemberExpr(MemberExpr * E)1887     void VisitMemberExpr(MemberExpr* E) {
1888       Simple = false;
1889     }
1890 
1891     // Any Stmt not explicitly listed will cause the condition to be marked
1892     // complex.
VisitStmt(Stmt * S)1893     void VisitStmt(Stmt *S) { Simple = false; }
1894 
VisitBinaryOperator(BinaryOperator * E)1895     void VisitBinaryOperator(BinaryOperator *E) {
1896       Visit(E->getLHS());
1897       Visit(E->getRHS());
1898     }
1899 
VisitCastExpr(CastExpr * E)1900     void VisitCastExpr(CastExpr *E) {
1901       Visit(E->getSubExpr());
1902     }
1903 
VisitUnaryOperator(UnaryOperator * E)1904     void VisitUnaryOperator(UnaryOperator *E) {
1905       // Skip checking conditionals with derefernces.
1906       if (E->getOpcode() == UO_Deref)
1907         Simple = false;
1908       else
1909         Visit(E->getSubExpr());
1910     }
1911 
VisitConditionalOperator(ConditionalOperator * E)1912     void VisitConditionalOperator(ConditionalOperator *E) {
1913       Visit(E->getCond());
1914       Visit(E->getTrueExpr());
1915       Visit(E->getFalseExpr());
1916     }
1917 
VisitParenExpr(ParenExpr * E)1918     void VisitParenExpr(ParenExpr *E) {
1919       Visit(E->getSubExpr());
1920     }
1921 
VisitBinaryConditionalOperator(BinaryConditionalOperator * E)1922     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1923       Visit(E->getOpaqueValue()->getSourceExpr());
1924       Visit(E->getFalseExpr());
1925     }
1926 
VisitIntegerLiteral(IntegerLiteral * E)1927     void VisitIntegerLiteral(IntegerLiteral *E) { }
VisitFloatingLiteral(FloatingLiteral * E)1928     void VisitFloatingLiteral(FloatingLiteral *E) { }
VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr * E)1929     void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
VisitCharacterLiteral(CharacterLiteral * E)1930     void VisitCharacterLiteral(CharacterLiteral *E) { }
VisitGNUNullExpr(GNUNullExpr * E)1931     void VisitGNUNullExpr(GNUNullExpr *E) { }
VisitImaginaryLiteral(ImaginaryLiteral * E)1932     void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1933 
VisitDeclRefExpr(DeclRefExpr * E)1934     void VisitDeclRefExpr(DeclRefExpr *E) {
1935       VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1936       if (!VD) {
1937         // Don't allow unhandled Decl types.
1938         Simple = false;
1939         return;
1940       }
1941 
1942       Ranges.push_back(E->getSourceRange());
1943 
1944       Decls.insert(VD);
1945     }
1946 
1947   }; // end class DeclExtractor
1948 
1949   // DeclMatcher checks to see if the decls are used in a non-evaluated
1950   // context.
1951   class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1952     DeclSetVector &Decls;
1953     bool FoundDecl;
1954 
1955   public:
1956     typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1957 
DeclMatcher(Sema & S,DeclSetVector & Decls,Stmt * Statement)1958     DeclMatcher(Sema &S, DeclSetVector &Decls, Stmt *Statement) :
1959         Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1960       if (!Statement) return;
1961 
1962       Visit(Statement);
1963     }
1964 
VisitReturnStmt(ReturnStmt * S)1965     void VisitReturnStmt(ReturnStmt *S) {
1966       FoundDecl = true;
1967     }
1968 
VisitBreakStmt(BreakStmt * S)1969     void VisitBreakStmt(BreakStmt *S) {
1970       FoundDecl = true;
1971     }
1972 
VisitGotoStmt(GotoStmt * S)1973     void VisitGotoStmt(GotoStmt *S) {
1974       FoundDecl = true;
1975     }
1976 
VisitCastExpr(CastExpr * E)1977     void VisitCastExpr(CastExpr *E) {
1978       if (E->getCastKind() == CK_LValueToRValue)
1979         CheckLValueToRValueCast(E->getSubExpr());
1980       else
1981         Visit(E->getSubExpr());
1982     }
1983 
CheckLValueToRValueCast(Expr * E)1984     void CheckLValueToRValueCast(Expr *E) {
1985       E = E->IgnoreParenImpCasts();
1986 
1987       if (isa<DeclRefExpr>(E)) {
1988         return;
1989       }
1990 
1991       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1992         Visit(CO->getCond());
1993         CheckLValueToRValueCast(CO->getTrueExpr());
1994         CheckLValueToRValueCast(CO->getFalseExpr());
1995         return;
1996       }
1997 
1998       if (BinaryConditionalOperator *BCO =
1999               dyn_cast<BinaryConditionalOperator>(E)) {
2000         CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
2001         CheckLValueToRValueCast(BCO->getFalseExpr());
2002         return;
2003       }
2004 
2005       Visit(E);
2006     }
2007 
VisitDeclRefExpr(DeclRefExpr * E)2008     void VisitDeclRefExpr(DeclRefExpr *E) {
2009       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
2010         if (Decls.count(VD))
2011           FoundDecl = true;
2012     }
2013 
VisitPseudoObjectExpr(PseudoObjectExpr * POE)2014     void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
2015       // Only need to visit the semantics for POE.
2016       // SyntaticForm doesn't really use the Decal.
2017       for (auto *S : POE->semantics()) {
2018         if (auto *OVE = dyn_cast<OpaqueValueExpr>(S))
2019           // Look past the OVE into the expression it binds.
2020           Visit(OVE->getSourceExpr());
2021         else
2022           Visit(S);
2023       }
2024     }
2025 
FoundDeclInUse()2026     bool FoundDeclInUse() { return FoundDecl; }
2027 
2028   };  // end class DeclMatcher
2029 
CheckForLoopConditionalStatement(Sema & S,Expr * Second,Expr * Third,Stmt * Body)2030   void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
2031                                         Expr *Third, Stmt *Body) {
2032     // Condition is empty
2033     if (!Second) return;
2034 
2035     if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
2036                           Second->getBeginLoc()))
2037       return;
2038 
2039     PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
2040     DeclSetVector Decls;
2041     SmallVector<SourceRange, 10> Ranges;
2042     DeclExtractor DE(S, Decls, Ranges);
2043     DE.Visit(Second);
2044 
2045     // Don't analyze complex conditionals.
2046     if (!DE.isSimple()) return;
2047 
2048     // No decls found.
2049     if (Decls.size() == 0) return;
2050 
2051     // Don't warn on volatile, static, or global variables.
2052     for (auto *VD : Decls)
2053       if (VD->getType().isVolatileQualified() || VD->hasGlobalStorage())
2054         return;
2055 
2056     if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
2057         DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
2058         DeclMatcher(S, Decls, Body).FoundDeclInUse())
2059       return;
2060 
2061     // Load decl names into diagnostic.
2062     if (Decls.size() > 4) {
2063       PDiag << 0;
2064     } else {
2065       PDiag << (unsigned)Decls.size();
2066       for (auto *VD : Decls)
2067         PDiag << VD->getDeclName();
2068     }
2069 
2070     for (auto Range : Ranges)
2071       PDiag << Range;
2072 
2073     S.Diag(Ranges.begin()->getBegin(), PDiag);
2074   }
2075 
2076   // If Statement is an incemement or decrement, return true and sets the
2077   // variables Increment and DRE.
ProcessIterationStmt(Sema & S,Stmt * Statement,bool & Increment,DeclRefExpr * & DRE)2078   bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
2079                             DeclRefExpr *&DRE) {
2080     if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement))
2081       if (!Cleanups->cleanupsHaveSideEffects())
2082         Statement = Cleanups->getSubExpr();
2083 
2084     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
2085       switch (UO->getOpcode()) {
2086         default: return false;
2087         case UO_PostInc:
2088         case UO_PreInc:
2089           Increment = true;
2090           break;
2091         case UO_PostDec:
2092         case UO_PreDec:
2093           Increment = false;
2094           break;
2095       }
2096       DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
2097       return DRE;
2098     }
2099 
2100     if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
2101       FunctionDecl *FD = Call->getDirectCallee();
2102       if (!FD || !FD->isOverloadedOperator()) return false;
2103       switch (FD->getOverloadedOperator()) {
2104         default: return false;
2105         case OO_PlusPlus:
2106           Increment = true;
2107           break;
2108         case OO_MinusMinus:
2109           Increment = false;
2110           break;
2111       }
2112       DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
2113       return DRE;
2114     }
2115 
2116     return false;
2117   }
2118 
2119   // A visitor to determine if a continue or break statement is a
2120   // subexpression.
2121   class BreakContinueFinder : public ConstEvaluatedExprVisitor<BreakContinueFinder> {
2122     SourceLocation BreakLoc;
2123     SourceLocation ContinueLoc;
2124     bool InSwitch = false;
2125 
2126   public:
BreakContinueFinder(Sema & S,const Stmt * Body)2127     BreakContinueFinder(Sema &S, const Stmt* Body) :
2128         Inherited(S.Context) {
2129       Visit(Body);
2130     }
2131 
2132     typedef ConstEvaluatedExprVisitor<BreakContinueFinder> Inherited;
2133 
VisitContinueStmt(const ContinueStmt * E)2134     void VisitContinueStmt(const ContinueStmt* E) {
2135       ContinueLoc = E->getContinueLoc();
2136     }
2137 
VisitBreakStmt(const BreakStmt * E)2138     void VisitBreakStmt(const BreakStmt* E) {
2139       if (!InSwitch)
2140         BreakLoc = E->getBreakLoc();
2141     }
2142 
VisitSwitchStmt(const SwitchStmt * S)2143     void VisitSwitchStmt(const SwitchStmt* S) {
2144       if (const Stmt *Init = S->getInit())
2145         Visit(Init);
2146       if (const Stmt *CondVar = S->getConditionVariableDeclStmt())
2147         Visit(CondVar);
2148       if (const Stmt *Cond = S->getCond())
2149         Visit(Cond);
2150 
2151       // Don't return break statements from the body of a switch.
2152       InSwitch = true;
2153       if (const Stmt *Body = S->getBody())
2154         Visit(Body);
2155       InSwitch = false;
2156     }
2157 
VisitForStmt(const ForStmt * S)2158     void VisitForStmt(const ForStmt *S) {
2159       // Only visit the init statement of a for loop; the body
2160       // has a different break/continue scope.
2161       if (const Stmt *Init = S->getInit())
2162         Visit(Init);
2163     }
2164 
VisitWhileStmt(const WhileStmt *)2165     void VisitWhileStmt(const WhileStmt *) {
2166       // Do nothing; the children of a while loop have a different
2167       // break/continue scope.
2168     }
2169 
VisitDoStmt(const DoStmt *)2170     void VisitDoStmt(const DoStmt *) {
2171       // Do nothing; the children of a while loop have a different
2172       // break/continue scope.
2173     }
2174 
VisitCXXForRangeStmt(const CXXForRangeStmt * S)2175     void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
2176       // Only visit the initialization of a for loop; the body
2177       // has a different break/continue scope.
2178       if (const Stmt *Init = S->getInit())
2179         Visit(Init);
2180       if (const Stmt *Range = S->getRangeStmt())
2181         Visit(Range);
2182       if (const Stmt *Begin = S->getBeginStmt())
2183         Visit(Begin);
2184       if (const Stmt *End = S->getEndStmt())
2185         Visit(End);
2186     }
2187 
VisitObjCForCollectionStmt(const ObjCForCollectionStmt * S)2188     void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
2189       // Only visit the initialization of a for loop; the body
2190       // has a different break/continue scope.
2191       if (const Stmt *Element = S->getElement())
2192         Visit(Element);
2193       if (const Stmt *Collection = S->getCollection())
2194         Visit(Collection);
2195     }
2196 
ContinueFound()2197     bool ContinueFound() { return ContinueLoc.isValid(); }
BreakFound()2198     bool BreakFound() { return BreakLoc.isValid(); }
GetContinueLoc()2199     SourceLocation GetContinueLoc() { return ContinueLoc; }
GetBreakLoc()2200     SourceLocation GetBreakLoc() { return BreakLoc; }
2201 
2202   };  // end class BreakContinueFinder
2203 
2204   // Emit a warning when a loop increment/decrement appears twice per loop
2205   // iteration.  The conditions which trigger this warning are:
2206   // 1) The last statement in the loop body and the third expression in the
2207   //    for loop are both increment or both decrement of the same variable
2208   // 2) No continue statements in the loop body.
CheckForRedundantIteration(Sema & S,Expr * Third,Stmt * Body)2209   void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
2210     // Return when there is nothing to check.
2211     if (!Body || !Third) return;
2212 
2213     // Get the last statement from the loop body.
2214     CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
2215     if (!CS || CS->body_empty()) return;
2216     Stmt *LastStmt = CS->body_back();
2217     if (!LastStmt) return;
2218 
2219     if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
2220                           Third->getBeginLoc()))
2221       return;
2222 
2223     bool LoopIncrement, LastIncrement;
2224     DeclRefExpr *LoopDRE, *LastDRE;
2225 
2226     if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
2227     if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
2228 
2229     // Check that the two statements are both increments or both decrements
2230     // on the same variable.
2231     if (LoopIncrement != LastIncrement ||
2232         LoopDRE->getDecl() != LastDRE->getDecl()) return;
2233 
2234     if (BreakContinueFinder(S, Body).ContinueFound()) return;
2235 
2236     S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
2237          << LastDRE->getDecl() << LastIncrement;
2238     S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
2239          << LoopIncrement;
2240   }
2241 
2242 } // end namespace
2243 
2244 
CheckBreakContinueBinding(Expr * E)2245 void Sema::CheckBreakContinueBinding(Expr *E) {
2246   if (!E || getLangOpts().CPlusPlus)
2247     return;
2248   BreakContinueFinder BCFinder(*this, E);
2249   Scope *BreakParent = CurScope->getBreakParent();
2250   if (BCFinder.BreakFound() && BreakParent) {
2251     if (BreakParent->getFlags() & Scope::SwitchScope) {
2252       Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
2253     } else {
2254       Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
2255           << "break";
2256     }
2257   } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
2258     Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
2259         << "continue";
2260   }
2261 }
2262 
ActOnForStmt(SourceLocation ForLoc,SourceLocation LParenLoc,Stmt * First,ConditionResult Second,FullExprArg third,SourceLocation RParenLoc,Stmt * Body)2263 StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
2264                               Stmt *First, ConditionResult Second,
2265                               FullExprArg third, SourceLocation RParenLoc,
2266                               Stmt *Body) {
2267   if (Second.isInvalid())
2268     return StmtError();
2269 
2270   if (!getLangOpts().CPlusPlus) {
2271     if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
2272       // C99 6.8.5p3: The declaration part of a 'for' statement shall only
2273       // declare identifiers for objects having storage class 'auto' or
2274       // 'register'.
2275       const Decl *NonVarSeen = nullptr;
2276       bool VarDeclSeen = false;
2277       for (auto *DI : DS->decls()) {
2278         if (VarDecl *VD = dyn_cast<VarDecl>(DI)) {
2279           VarDeclSeen = true;
2280           if (VD->isLocalVarDecl() && !VD->hasLocalStorage())
2281             Diag(DI->getLocation(),
2282                  getLangOpts().C23
2283                      ? diag::warn_c17_non_local_variable_decl_in_for
2284                      : diag::ext_c23_non_local_variable_decl_in_for);
2285         } else if (!NonVarSeen) {
2286           // Keep track of the first non-variable declaration we saw so that
2287           // we can diagnose if we don't see any variable declarations. This
2288           // covers a case like declaring a typedef, function, or structure
2289           // type rather than a variable.
2290           //
2291           // Note, _Static_assert is acceptable because it does not declare an
2292           // identifier at all, so "for object having" does not apply.
2293           if (!isa<StaticAssertDecl>(DI))
2294             NonVarSeen = DI;
2295         }
2296       }
2297       // Diagnose if we saw a non-variable declaration but no variable
2298       // declarations.
2299       if (NonVarSeen && !VarDeclSeen)
2300         Diag(NonVarSeen->getLocation(),
2301              getLangOpts().C23 ? diag::warn_c17_non_variable_decl_in_for
2302                                : diag::ext_c23_non_variable_decl_in_for);
2303     }
2304   }
2305 
2306   CheckBreakContinueBinding(Second.get().second);
2307   CheckBreakContinueBinding(third.get());
2308 
2309   if (!Second.get().first)
2310     CheckForLoopConditionalStatement(*this, Second.get().second, third.get(),
2311                                      Body);
2312   CheckForRedundantIteration(*this, third.get(), Body);
2313 
2314   if (Second.get().second &&
2315       !Diags.isIgnored(diag::warn_comma_operator,
2316                        Second.get().second->getExprLoc()))
2317     CommaVisitor(*this).Visit(Second.get().second);
2318 
2319   Expr *Third  = third.release().getAs<Expr>();
2320   if (isa<NullStmt>(Body))
2321     getCurCompoundScope().setHasEmptyLoopBodies();
2322 
2323   return new (Context)
2324       ForStmt(Context, First, Second.get().second, Second.get().first, Third,
2325               Body, ForLoc, LParenLoc, RParenLoc);
2326 }
2327 
ActOnForEachLValueExpr(Expr * E)2328 StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
2329   // Reduce placeholder expressions here.  Note that this rejects the
2330   // use of pseudo-object l-values in this position.
2331   ExprResult result = CheckPlaceholderExpr(E);
2332   if (result.isInvalid()) return StmtError();
2333   E = result.get();
2334 
2335   ExprResult FullExpr = ActOnFinishFullExpr(E, /*DiscardedValue*/ false);
2336   if (FullExpr.isInvalid())
2337     return StmtError();
2338   return StmtResult(static_cast<Stmt*>(FullExpr.get()));
2339 }
2340 
2341 /// Finish building a variable declaration for a for-range statement.
2342 /// \return true if an error occurs.
FinishForRangeVarDecl(Sema & SemaRef,VarDecl * Decl,Expr * Init,SourceLocation Loc,int DiagID)2343 static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
2344                                   SourceLocation Loc, int DiagID) {
2345   if (Decl->getType()->isUndeducedType()) {
2346     ExprResult Res = Init;
2347     if (!Res.isUsable()) {
2348       Decl->setInvalidDecl();
2349       return true;
2350     }
2351     Init = Res.get();
2352   }
2353 
2354   // Deduce the type for the iterator variable now rather than leaving it to
2355   // AddInitializerToDecl, so we can produce a more suitable diagnostic.
2356   QualType InitType;
2357   if (!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) {
2358     SemaRef.Diag(Loc, DiagID) << Init->getType();
2359   } else {
2360     TemplateDeductionInfo Info(Init->getExprLoc());
2361     TemplateDeductionResult Result = SemaRef.DeduceAutoType(
2362         Decl->getTypeSourceInfo()->getTypeLoc(), Init, InitType, Info);
2363     if (Result != TemplateDeductionResult::Success &&
2364         Result != TemplateDeductionResult::AlreadyDiagnosed)
2365       SemaRef.Diag(Loc, DiagID) << Init->getType();
2366   }
2367 
2368   if (InitType.isNull()) {
2369     Decl->setInvalidDecl();
2370     return true;
2371   }
2372   Decl->setType(InitType);
2373 
2374   // In ARC, infer lifetime.
2375   // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
2376   // we're doing the equivalent of fast iteration.
2377   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
2378       SemaRef.ObjC().inferObjCARCLifetime(Decl))
2379     Decl->setInvalidDecl();
2380 
2381   SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false);
2382   SemaRef.FinalizeDeclaration(Decl);
2383   SemaRef.CurContext->addHiddenDecl(Decl);
2384   return false;
2385 }
2386 
2387 namespace {
2388 // An enum to represent whether something is dealing with a call to begin()
2389 // or a call to end() in a range-based for loop.
2390 enum BeginEndFunction {
2391   BEF_begin,
2392   BEF_end
2393 };
2394 
2395 /// Produce a note indicating which begin/end function was implicitly called
2396 /// by a C++11 for-range statement. This is often not obvious from the code,
2397 /// nor from the diagnostics produced when analysing the implicit expressions
2398 /// required in a for-range statement.
NoteForRangeBeginEndFunction(Sema & SemaRef,Expr * E,BeginEndFunction BEF)2399 void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
2400                                   BeginEndFunction BEF) {
2401   CallExpr *CE = dyn_cast<CallExpr>(E);
2402   if (!CE)
2403     return;
2404   FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
2405   if (!D)
2406     return;
2407   SourceLocation Loc = D->getLocation();
2408 
2409   std::string Description;
2410   bool IsTemplate = false;
2411   if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
2412     Description = SemaRef.getTemplateArgumentBindingsText(
2413       FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
2414     IsTemplate = true;
2415   }
2416 
2417   SemaRef.Diag(Loc, diag::note_for_range_begin_end)
2418     << BEF << IsTemplate << Description << E->getType();
2419 }
2420 
2421 /// Build a variable declaration for a for-range statement.
BuildForRangeVarDecl(Sema & SemaRef,SourceLocation Loc,QualType Type,StringRef Name)2422 VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
2423                               QualType Type, StringRef Name) {
2424   DeclContext *DC = SemaRef.CurContext;
2425   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
2426   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
2427   VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
2428                                   TInfo, SC_None);
2429   Decl->setImplicit();
2430   Decl->setCXXForRangeImplicitVar(true);
2431   return Decl;
2432 }
2433 
2434 }
2435 
ObjCEnumerationCollection(Expr * Collection)2436 static bool ObjCEnumerationCollection(Expr *Collection) {
2437   return !Collection->isTypeDependent()
2438           && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
2439 }
2440 
ActOnCXXForRangeStmt(Scope * S,SourceLocation ForLoc,SourceLocation CoawaitLoc,Stmt * InitStmt,Stmt * First,SourceLocation ColonLoc,Expr * Range,SourceLocation RParenLoc,BuildForRangeKind Kind,ArrayRef<MaterializeTemporaryExpr * > LifetimeExtendTemps)2441 StmtResult Sema::ActOnCXXForRangeStmt(
2442     Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt,
2443     Stmt *First, SourceLocation ColonLoc, Expr *Range, SourceLocation RParenLoc,
2444     BuildForRangeKind Kind,
2445     ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps) {
2446   // FIXME: recover in order to allow the body to be parsed.
2447   if (!First)
2448     return StmtError();
2449 
2450   if (Range && ObjCEnumerationCollection(Range)) {
2451     // FIXME: Support init-statements in Objective-C++20 ranged for statement.
2452     if (InitStmt)
2453       return Diag(InitStmt->getBeginLoc(), diag::err_objc_for_range_init_stmt)
2454                  << InitStmt->getSourceRange();
2455     return ObjC().ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
2456   }
2457 
2458   DeclStmt *DS = dyn_cast<DeclStmt>(First);
2459   assert(DS && "first part of for range not a decl stmt");
2460 
2461   if (!DS->isSingleDecl()) {
2462     Diag(DS->getBeginLoc(), diag::err_type_defined_in_for_range);
2463     return StmtError();
2464   }
2465 
2466   // This function is responsible for attaching an initializer to LoopVar. We
2467   // must call ActOnInitializerError if we fail to do so.
2468   Decl *LoopVar = DS->getSingleDecl();
2469   if (LoopVar->isInvalidDecl() || !Range ||
2470       DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
2471     ActOnInitializerError(LoopVar);
2472     return StmtError();
2473   }
2474 
2475   // Build the coroutine state immediately and not later during template
2476   // instantiation
2477   if (!CoawaitLoc.isInvalid()) {
2478     if (!ActOnCoroutineBodyStart(S, CoawaitLoc, "co_await")) {
2479       ActOnInitializerError(LoopVar);
2480       return StmtError();
2481     }
2482   }
2483 
2484   // Build  auto && __range = range-init
2485   // Divide by 2, since the variables are in the inner scope (loop body).
2486   const auto DepthStr = std::to_string(S->getDepth() / 2);
2487   SourceLocation RangeLoc = Range->getBeginLoc();
2488   VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
2489                                            Context.getAutoRRefDeductType(),
2490                                            std::string("__range") + DepthStr);
2491   if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
2492                             diag::err_for_range_deduction_failure)) {
2493     ActOnInitializerError(LoopVar);
2494     return StmtError();
2495   }
2496 
2497   // Claim the type doesn't contain auto: we've already done the checking.
2498   DeclGroupPtrTy RangeGroup =
2499       BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1));
2500   StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
2501   if (RangeDecl.isInvalid()) {
2502     ActOnInitializerError(LoopVar);
2503     return StmtError();
2504   }
2505 
2506   StmtResult R = BuildCXXForRangeStmt(
2507       ForLoc, CoawaitLoc, InitStmt, ColonLoc, RangeDecl.get(),
2508       /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
2509       /*Cond=*/nullptr, /*Inc=*/nullptr, DS, RParenLoc, Kind,
2510       LifetimeExtendTemps);
2511   if (R.isInvalid()) {
2512     ActOnInitializerError(LoopVar);
2513     return StmtError();
2514   }
2515 
2516   return R;
2517 }
2518 
2519 /// Create the initialization, compare, and increment steps for
2520 /// the range-based for loop expression.
2521 /// This function does not handle array-based for loops,
2522 /// which are created in Sema::BuildCXXForRangeStmt.
2523 ///
2524 /// \returns a ForRangeStatus indicating success or what kind of error occurred.
2525 /// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2526 /// CandidateSet and BEF are set and some non-success value is returned on
2527 /// failure.
2528 static Sema::ForRangeStatus
BuildNonArrayForRange(Sema & SemaRef,Expr * BeginRange,Expr * EndRange,QualType RangeType,VarDecl * BeginVar,VarDecl * EndVar,SourceLocation ColonLoc,SourceLocation CoawaitLoc,OverloadCandidateSet * CandidateSet,ExprResult * BeginExpr,ExprResult * EndExpr,BeginEndFunction * BEF)2529 BuildNonArrayForRange(Sema &SemaRef, Expr *BeginRange, Expr *EndRange,
2530                       QualType RangeType, VarDecl *BeginVar, VarDecl *EndVar,
2531                       SourceLocation ColonLoc, SourceLocation CoawaitLoc,
2532                       OverloadCandidateSet *CandidateSet, ExprResult *BeginExpr,
2533                       ExprResult *EndExpr, BeginEndFunction *BEF) {
2534   DeclarationNameInfo BeginNameInfo(
2535       &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2536   DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2537                                   ColonLoc);
2538 
2539   LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2540                                  Sema::LookupMemberName);
2541   LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2542 
2543   auto BuildBegin = [&] {
2544     *BEF = BEF_begin;
2545     Sema::ForRangeStatus RangeStatus =
2546         SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
2547                                           BeginMemberLookup, CandidateSet,
2548                                           BeginRange, BeginExpr);
2549 
2550     if (RangeStatus != Sema::FRS_Success) {
2551       if (RangeStatus == Sema::FRS_DiagnosticIssued)
2552         SemaRef.Diag(BeginRange->getBeginLoc(), diag::note_in_for_range)
2553             << ColonLoc << BEF_begin << BeginRange->getType();
2554       return RangeStatus;
2555     }
2556     if (!CoawaitLoc.isInvalid()) {
2557       // FIXME: getCurScope() should not be used during template instantiation.
2558       // We should pick up the set of unqualified lookup results for operator
2559       // co_await during the initial parse.
2560       *BeginExpr = SemaRef.ActOnCoawaitExpr(SemaRef.getCurScope(), ColonLoc,
2561                                             BeginExpr->get());
2562       if (BeginExpr->isInvalid())
2563         return Sema::FRS_DiagnosticIssued;
2564     }
2565     if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2566                               diag::err_for_range_iter_deduction_failure)) {
2567       NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2568       return Sema::FRS_DiagnosticIssued;
2569     }
2570     return Sema::FRS_Success;
2571   };
2572 
2573   auto BuildEnd = [&] {
2574     *BEF = BEF_end;
2575     Sema::ForRangeStatus RangeStatus =
2576         SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
2577                                           EndMemberLookup, CandidateSet,
2578                                           EndRange, EndExpr);
2579     if (RangeStatus != Sema::FRS_Success) {
2580       if (RangeStatus == Sema::FRS_DiagnosticIssued)
2581         SemaRef.Diag(EndRange->getBeginLoc(), diag::note_in_for_range)
2582             << ColonLoc << BEF_end << EndRange->getType();
2583       return RangeStatus;
2584     }
2585     if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2586                               diag::err_for_range_iter_deduction_failure)) {
2587       NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2588       return Sema::FRS_DiagnosticIssued;
2589     }
2590     return Sema::FRS_Success;
2591   };
2592 
2593   if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2594     // - if _RangeT is a class type, the unqualified-ids begin and end are
2595     //   looked up in the scope of class _RangeT as if by class member access
2596     //   lookup (3.4.5), and if either (or both) finds at least one
2597     //   declaration, begin-expr and end-expr are __range.begin() and
2598     //   __range.end(), respectively;
2599     SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2600     if (BeginMemberLookup.isAmbiguous())
2601       return Sema::FRS_DiagnosticIssued;
2602 
2603     SemaRef.LookupQualifiedName(EndMemberLookup, D);
2604     if (EndMemberLookup.isAmbiguous())
2605       return Sema::FRS_DiagnosticIssued;
2606 
2607     if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2608       // Look up the non-member form of the member we didn't find, first.
2609       // This way we prefer a "no viable 'end'" diagnostic over a "i found
2610       // a 'begin' but ignored it because there was no member 'end'"
2611       // diagnostic.
2612       auto BuildNonmember = [&](
2613           BeginEndFunction BEFFound, LookupResult &Found,
2614           llvm::function_ref<Sema::ForRangeStatus()> BuildFound,
2615           llvm::function_ref<Sema::ForRangeStatus()> BuildNotFound) {
2616         LookupResult OldFound = std::move(Found);
2617         Found.clear();
2618 
2619         if (Sema::ForRangeStatus Result = BuildNotFound())
2620           return Result;
2621 
2622         switch (BuildFound()) {
2623         case Sema::FRS_Success:
2624           return Sema::FRS_Success;
2625 
2626         case Sema::FRS_NoViableFunction:
2627           CandidateSet->NoteCandidates(
2628               PartialDiagnosticAt(BeginRange->getBeginLoc(),
2629                                   SemaRef.PDiag(diag::err_for_range_invalid)
2630                                       << BeginRange->getType() << BEFFound),
2631               SemaRef, OCD_AllCandidates, BeginRange);
2632           [[fallthrough]];
2633 
2634         case Sema::FRS_DiagnosticIssued:
2635           for (NamedDecl *D : OldFound) {
2636             SemaRef.Diag(D->getLocation(),
2637                          diag::note_for_range_member_begin_end_ignored)
2638                 << BeginRange->getType() << BEFFound;
2639           }
2640           return Sema::FRS_DiagnosticIssued;
2641         }
2642         llvm_unreachable("unexpected ForRangeStatus");
2643       };
2644       if (BeginMemberLookup.empty())
2645         return BuildNonmember(BEF_end, EndMemberLookup, BuildEnd, BuildBegin);
2646       return BuildNonmember(BEF_begin, BeginMemberLookup, BuildBegin, BuildEnd);
2647     }
2648   } else {
2649     // - otherwise, begin-expr and end-expr are begin(__range) and
2650     //   end(__range), respectively, where begin and end are looked up with
2651     //   argument-dependent lookup (3.4.2). For the purposes of this name
2652     //   lookup, namespace std is an associated namespace.
2653   }
2654 
2655   if (Sema::ForRangeStatus Result = BuildBegin())
2656     return Result;
2657   return BuildEnd();
2658 }
2659 
2660 /// Speculatively attempt to dereference an invalid range expression.
2661 /// If the attempt fails, this function will return a valid, null StmtResult
2662 /// and emit no diagnostics.
RebuildForRangeWithDereference(Sema & SemaRef,Scope * S,SourceLocation ForLoc,SourceLocation CoawaitLoc,Stmt * InitStmt,Stmt * LoopVarDecl,SourceLocation ColonLoc,Expr * Range,SourceLocation RangeLoc,SourceLocation RParenLoc)2663 static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2664                                                  SourceLocation ForLoc,
2665                                                  SourceLocation CoawaitLoc,
2666                                                  Stmt *InitStmt,
2667                                                  Stmt *LoopVarDecl,
2668                                                  SourceLocation ColonLoc,
2669                                                  Expr *Range,
2670                                                  SourceLocation RangeLoc,
2671                                                  SourceLocation RParenLoc) {
2672   // Determine whether we can rebuild the for-range statement with a
2673   // dereferenced range expression.
2674   ExprResult AdjustedRange;
2675   {
2676     Sema::SFINAETrap Trap(SemaRef);
2677 
2678     AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2679     if (AdjustedRange.isInvalid())
2680       return StmtResult();
2681 
2682     StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
2683         S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
2684         AdjustedRange.get(), RParenLoc, Sema::BFRK_Check);
2685     if (SR.isInvalid())
2686       return StmtResult();
2687   }
2688 
2689   // The attempt to dereference worked well enough that it could produce a valid
2690   // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2691   // case there are any other (non-fatal) problems with it.
2692   SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2693     << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
2694   return SemaRef.ActOnCXXForRangeStmt(
2695       S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
2696       AdjustedRange.get(), RParenLoc, Sema::BFRK_Rebuild);
2697 }
2698 
BuildCXXForRangeStmt(SourceLocation ForLoc,SourceLocation CoawaitLoc,Stmt * InitStmt,SourceLocation ColonLoc,Stmt * RangeDecl,Stmt * Begin,Stmt * End,Expr * Cond,Expr * Inc,Stmt * LoopVarDecl,SourceLocation RParenLoc,BuildForRangeKind Kind,ArrayRef<MaterializeTemporaryExpr * > LifetimeExtendTemps)2699 StmtResult Sema::BuildCXXForRangeStmt(
2700     SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt,
2701     SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End,
2702     Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc,
2703     BuildForRangeKind Kind,
2704     ArrayRef<MaterializeTemporaryExpr *> LifetimeExtendTemps) {
2705   // FIXME: This should not be used during template instantiation. We should
2706   // pick up the set of unqualified lookup results for the != and + operators
2707   // in the initial parse.
2708   //
2709   // Testcase (accepts-invalid):
2710   //   template<typename T> void f() { for (auto x : T()) {} }
2711   //   namespace N { struct X { X begin(); X end(); int operator*(); }; }
2712   //   bool operator!=(N::X, N::X); void operator++(N::X);
2713   //   void g() { f<N::X>(); }
2714   Scope *S = getCurScope();
2715 
2716   DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2717   VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2718   QualType RangeVarType = RangeVar->getType();
2719 
2720   DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2721   VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2722 
2723   StmtResult BeginDeclStmt = Begin;
2724   StmtResult EndDeclStmt = End;
2725   ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2726 
2727   if (RangeVarType->isDependentType()) {
2728     // The range is implicitly used as a placeholder when it is dependent.
2729     RangeVar->markUsed(Context);
2730 
2731     // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2732     // them in properly when we instantiate the loop.
2733     if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2734       if (auto *DD = dyn_cast<DecompositionDecl>(LoopVar))
2735         for (auto *Binding : DD->bindings()) {
2736           if (!Binding->isParameterPack())
2737             Binding->setType(Context.DependentTy);
2738         }
2739       LoopVar->setType(SubstAutoTypeDependent(LoopVar->getType()));
2740     }
2741   } else if (!BeginDeclStmt.get()) {
2742     SourceLocation RangeLoc = RangeVar->getLocation();
2743 
2744     const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2745 
2746     ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2747                                                 VK_LValue, ColonLoc);
2748     if (BeginRangeRef.isInvalid())
2749       return StmtError();
2750 
2751     ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2752                                               VK_LValue, ColonLoc);
2753     if (EndRangeRef.isInvalid())
2754       return StmtError();
2755 
2756     QualType AutoType = Context.getAutoDeductType();
2757     Expr *Range = RangeVar->getInit();
2758     if (!Range)
2759       return StmtError();
2760     QualType RangeType = Range->getType();
2761 
2762     if (RequireCompleteType(RangeLoc, RangeType,
2763                             diag::err_for_range_incomplete_type))
2764       return StmtError();
2765 
2766     // P2718R0 - Lifetime extension in range-based for loops.
2767     if (getLangOpts().CPlusPlus23 && !LifetimeExtendTemps.empty()) {
2768       InitializedEntity Entity =
2769           InitializedEntity::InitializeVariable(RangeVar);
2770       for (auto *MTE : LifetimeExtendTemps)
2771         MTE->setExtendingDecl(RangeVar, Entity.allocateManglingNumber());
2772     }
2773 
2774     // Build auto __begin = begin-expr, __end = end-expr.
2775     // Divide by 2, since the variables are in the inner scope (loop body).
2776     const auto DepthStr = std::to_string(S->getDepth() / 2);
2777     VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2778                                              std::string("__begin") + DepthStr);
2779     VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2780                                            std::string("__end") + DepthStr);
2781 
2782     // Build begin-expr and end-expr and attach to __begin and __end variables.
2783     ExprResult BeginExpr, EndExpr;
2784     if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2785       // - if _RangeT is an array type, begin-expr and end-expr are __range and
2786       //   __range + __bound, respectively, where __bound is the array bound. If
2787       //   _RangeT is an array of unknown size or an array of incomplete type,
2788       //   the program is ill-formed;
2789 
2790       // begin-expr is __range.
2791       BeginExpr = BeginRangeRef;
2792       if (!CoawaitLoc.isInvalid()) {
2793         BeginExpr = ActOnCoawaitExpr(S, ColonLoc, BeginExpr.get());
2794         if (BeginExpr.isInvalid())
2795           return StmtError();
2796       }
2797       if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
2798                                 diag::err_for_range_iter_deduction_failure)) {
2799         NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2800         return StmtError();
2801       }
2802 
2803       // Find the array bound.
2804       ExprResult BoundExpr;
2805       if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
2806         BoundExpr = IntegerLiteral::Create(
2807             Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
2808       else if (const VariableArrayType *VAT =
2809                dyn_cast<VariableArrayType>(UnqAT)) {
2810         // For a variably modified type we can't just use the expression within
2811         // the array bounds, since we don't want that to be re-evaluated here.
2812         // Rather, we need to determine what it was when the array was first
2813         // created - so we resort to using sizeof(vla)/sizeof(element).
2814         // For e.g.
2815         //  void f(int b) {
2816         //    int vla[b];
2817         //    b = -1;   <-- This should not affect the num of iterations below
2818         //    for (int &c : vla) { .. }
2819         //  }
2820 
2821         // FIXME: This results in codegen generating IR that recalculates the
2822         // run-time number of elements (as opposed to just using the IR Value
2823         // that corresponds to the run-time value of each bound that was
2824         // generated when the array was created.) If this proves too embarrassing
2825         // even for unoptimized IR, consider passing a magic-value/cookie to
2826         // codegen that then knows to simply use that initial llvm::Value (that
2827         // corresponds to the bound at time of array creation) within
2828         // getelementptr.  But be prepared to pay the price of increasing a
2829         // customized form of coupling between the two components - which  could
2830         // be hard to maintain as the codebase evolves.
2831 
2832         ExprResult SizeOfVLAExprR = ActOnUnaryExprOrTypeTraitExpr(
2833             EndVar->getLocation(), UETT_SizeOf,
2834             /*IsType=*/true,
2835             CreateParsedType(VAT->desugar(), Context.getTrivialTypeSourceInfo(
2836                                                  VAT->desugar(), RangeLoc))
2837                 .getAsOpaquePtr(),
2838             EndVar->getSourceRange());
2839         if (SizeOfVLAExprR.isInvalid())
2840           return StmtError();
2841 
2842         ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr(
2843             EndVar->getLocation(), UETT_SizeOf,
2844             /*IsType=*/true,
2845             CreateParsedType(VAT->desugar(),
2846                              Context.getTrivialTypeSourceInfo(
2847                                  VAT->getElementType(), RangeLoc))
2848                 .getAsOpaquePtr(),
2849             EndVar->getSourceRange());
2850         if (SizeOfEachElementExprR.isInvalid())
2851           return StmtError();
2852 
2853         BoundExpr =
2854             ActOnBinOp(S, EndVar->getLocation(), tok::slash,
2855                        SizeOfVLAExprR.get(), SizeOfEachElementExprR.get());
2856         if (BoundExpr.isInvalid())
2857           return StmtError();
2858 
2859       } else {
2860         // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2861         // UnqAT is not incomplete and Range is not type-dependent.
2862         llvm_unreachable("Unexpected array type in for-range");
2863       }
2864 
2865       // end-expr is __range + __bound.
2866       EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
2867                            BoundExpr.get());
2868       if (EndExpr.isInvalid())
2869         return StmtError();
2870       if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2871                                 diag::err_for_range_iter_deduction_failure)) {
2872         NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2873         return StmtError();
2874       }
2875     } else {
2876       OverloadCandidateSet CandidateSet(RangeLoc,
2877                                         OverloadCandidateSet::CSK_Normal);
2878       BeginEndFunction BEFFailure;
2879       ForRangeStatus RangeStatus = BuildNonArrayForRange(
2880           *this, BeginRangeRef.get(), EndRangeRef.get(), RangeType, BeginVar,
2881           EndVar, ColonLoc, CoawaitLoc, &CandidateSet, &BeginExpr, &EndExpr,
2882           &BEFFailure);
2883 
2884       if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
2885           BEFFailure == BEF_begin) {
2886         // If the range is being built from an array parameter, emit a
2887         // a diagnostic that it is being treated as a pointer.
2888         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2889           if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2890             QualType ArrayTy = PVD->getOriginalType();
2891             QualType PointerTy = PVD->getType();
2892             if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2893               Diag(Range->getBeginLoc(), diag::err_range_on_array_parameter)
2894                   << RangeLoc << PVD << ArrayTy << PointerTy;
2895               Diag(PVD->getLocation(), diag::note_declared_at);
2896               return StmtError();
2897             }
2898           }
2899         }
2900 
2901         // If building the range failed, try dereferencing the range expression
2902         // unless a diagnostic was issued or the end function is problematic.
2903         StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2904                                                        CoawaitLoc, InitStmt,
2905                                                        LoopVarDecl, ColonLoc,
2906                                                        Range, RangeLoc,
2907                                                        RParenLoc);
2908         if (SR.isInvalid() || SR.isUsable())
2909           return SR;
2910       }
2911 
2912       // Otherwise, emit diagnostics if we haven't already.
2913       if (RangeStatus == FRS_NoViableFunction) {
2914         Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
2915         CandidateSet.NoteCandidates(
2916             PartialDiagnosticAt(Range->getBeginLoc(),
2917                                 PDiag(diag::err_for_range_invalid)
2918                                     << RangeLoc << Range->getType()
2919                                     << BEFFailure),
2920             *this, OCD_AllCandidates, Range);
2921       }
2922       // Return an error if no fix was discovered.
2923       if (RangeStatus != FRS_Success)
2924         return StmtError();
2925     }
2926 
2927     assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2928            "invalid range expression in for loop");
2929 
2930     // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
2931     // C++1z removes this restriction.
2932     QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2933     if (!Context.hasSameType(BeginType, EndType)) {
2934       Diag(RangeLoc, getLangOpts().CPlusPlus17
2935                          ? diag::warn_for_range_begin_end_types_differ
2936                          : diag::ext_for_range_begin_end_types_differ)
2937           << BeginType << EndType;
2938       NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2939       NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2940     }
2941 
2942     BeginDeclStmt =
2943         ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
2944     EndDeclStmt =
2945         ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
2946 
2947     const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2948     ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2949                                            VK_LValue, ColonLoc);
2950     if (BeginRef.isInvalid())
2951       return StmtError();
2952 
2953     ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2954                                          VK_LValue, ColonLoc);
2955     if (EndRef.isInvalid())
2956       return StmtError();
2957 
2958     // Build and check __begin != __end expression.
2959     NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2960                            BeginRef.get(), EndRef.get());
2961     if (!NotEqExpr.isInvalid())
2962       NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get());
2963     if (!NotEqExpr.isInvalid())
2964       NotEqExpr =
2965           ActOnFinishFullExpr(NotEqExpr.get(), /*DiscardedValue*/ false);
2966     if (NotEqExpr.isInvalid()) {
2967       Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2968         << RangeLoc << 0 << BeginRangeRef.get()->getType();
2969       NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2970       if (!Context.hasSameType(BeginType, EndType))
2971         NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2972       return StmtError();
2973     }
2974 
2975     // Build and check ++__begin expression.
2976     BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2977                                 VK_LValue, ColonLoc);
2978     if (BeginRef.isInvalid())
2979       return StmtError();
2980 
2981     IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2982     if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
2983       // FIXME: getCurScope() should not be used during template instantiation.
2984       // We should pick up the set of unqualified lookup results for operator
2985       // co_await during the initial parse.
2986       IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
2987     if (!IncrExpr.isInvalid())
2988       IncrExpr = ActOnFinishFullExpr(IncrExpr.get(), /*DiscardedValue*/ false);
2989     if (IncrExpr.isInvalid()) {
2990       Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2991         << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
2992       NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2993       return StmtError();
2994     }
2995 
2996     // Build and check *__begin  expression.
2997     BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2998                                 VK_LValue, ColonLoc);
2999     if (BeginRef.isInvalid())
3000       return StmtError();
3001 
3002     ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
3003     if (DerefExpr.isInvalid()) {
3004       Diag(RangeLoc, diag::note_for_range_invalid_iterator)
3005         << RangeLoc << 1 << BeginRangeRef.get()->getType();
3006       NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
3007       return StmtError();
3008     }
3009 
3010     // Attach  *__begin  as initializer for VD. Don't touch it if we're just
3011     // trying to determine whether this would be a valid range.
3012     if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
3013       AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false);
3014       if (LoopVar->isInvalidDecl() ||
3015           (LoopVar->getInit() && LoopVar->getInit()->containsErrors()))
3016         NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
3017     }
3018   }
3019 
3020   // Don't bother to actually allocate the result if we're just trying to
3021   // determine whether it would be valid.
3022   if (Kind == BFRK_Check)
3023     return StmtResult();
3024 
3025   // In OpenMP loop region loop control variable must be private. Perform
3026   // analysis of first part (if any).
3027   if (getLangOpts().OpenMP >= 50 && BeginDeclStmt.isUsable())
3028     OpenMP().ActOnOpenMPLoopInitialization(ForLoc, BeginDeclStmt.get());
3029 
3030   return new (Context) CXXForRangeStmt(
3031       InitStmt, RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
3032       cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
3033       IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
3034       ColonLoc, RParenLoc);
3035 }
3036 
3037 // Warn when the loop variable is a const reference that creates a copy.
3038 // Suggest using the non-reference type for copies.  If a copy can be prevented
3039 // suggest the const reference type that would do so.
3040 // For instance, given "for (const &Foo : Range)", suggest
3041 // "for (const Foo : Range)" to denote a copy is made for the loop.  If
3042 // possible, also suggest "for (const &Bar : Range)" if this type prevents
3043 // the copy altogether.
DiagnoseForRangeReferenceVariableCopies(Sema & SemaRef,const VarDecl * VD,QualType RangeInitType)3044 static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
3045                                                     const VarDecl *VD,
3046                                                     QualType RangeInitType) {
3047   const Expr *InitExpr = VD->getInit();
3048   if (!InitExpr)
3049     return;
3050 
3051   QualType VariableType = VD->getType();
3052 
3053   if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr))
3054     if (!Cleanups->cleanupsHaveSideEffects())
3055       InitExpr = Cleanups->getSubExpr();
3056 
3057   const MaterializeTemporaryExpr *MTE =
3058       dyn_cast<MaterializeTemporaryExpr>(InitExpr);
3059 
3060   // No copy made.
3061   if (!MTE)
3062     return;
3063 
3064   const Expr *E = MTE->getSubExpr()->IgnoreImpCasts();
3065 
3066   // Searching for either UnaryOperator for dereference of a pointer or
3067   // CXXOperatorCallExpr for handling iterators.
3068   while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
3069     if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
3070       E = CCE->getArg(0);
3071     } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
3072       const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
3073       E = ME->getBase();
3074     } else {
3075       const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
3076       E = MTE->getSubExpr();
3077     }
3078     E = E->IgnoreImpCasts();
3079   }
3080 
3081   QualType ReferenceReturnType;
3082   if (isa<UnaryOperator>(E)) {
3083     ReferenceReturnType = SemaRef.Context.getLValueReferenceType(E->getType());
3084   } else {
3085     const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
3086     const FunctionDecl *FD = Call->getDirectCallee();
3087     QualType ReturnType = FD->getReturnType();
3088     if (ReturnType->isReferenceType())
3089       ReferenceReturnType = ReturnType;
3090   }
3091 
3092   if (!ReferenceReturnType.isNull()) {
3093     // Loop variable creates a temporary.  Suggest either to go with
3094     // non-reference loop variable to indicate a copy is made, or
3095     // the correct type to bind a const reference.
3096     SemaRef.Diag(VD->getLocation(),
3097                  diag::warn_for_range_const_ref_binds_temp_built_from_ref)
3098         << VD << VariableType << ReferenceReturnType;
3099     QualType NonReferenceType = VariableType.getNonReferenceType();
3100     NonReferenceType.removeLocalConst();
3101     QualType NewReferenceType =
3102         SemaRef.Context.getLValueReferenceType(E->getType().withConst());
3103     SemaRef.Diag(VD->getBeginLoc(), diag::note_use_type_or_non_reference)
3104         << NonReferenceType << NewReferenceType << VD->getSourceRange()
3105         << FixItHint::CreateRemoval(VD->getTypeSpecEndLoc());
3106   } else if (!VariableType->isRValueReferenceType()) {
3107     // The range always returns a copy, so a temporary is always created.
3108     // Suggest removing the reference from the loop variable.
3109     // If the type is a rvalue reference do not warn since that changes the
3110     // semantic of the code.
3111     SemaRef.Diag(VD->getLocation(), diag::warn_for_range_ref_binds_ret_temp)
3112         << VD << RangeInitType;
3113     QualType NonReferenceType = VariableType.getNonReferenceType();
3114     NonReferenceType.removeLocalConst();
3115     SemaRef.Diag(VD->getBeginLoc(), diag::note_use_non_reference_type)
3116         << NonReferenceType << VD->getSourceRange()
3117         << FixItHint::CreateRemoval(VD->getTypeSpecEndLoc());
3118   }
3119 }
3120 
3121 /// Determines whether the @p VariableType's declaration is a record with the
3122 /// clang::trivial_abi attribute.
hasTrivialABIAttr(QualType VariableType)3123 static bool hasTrivialABIAttr(QualType VariableType) {
3124   if (CXXRecordDecl *RD = VariableType->getAsCXXRecordDecl())
3125     return RD->hasAttr<TrivialABIAttr>();
3126 
3127   return false;
3128 }
3129 
3130 // Warns when the loop variable can be changed to a reference type to
3131 // prevent a copy.  For instance, if given "for (const Foo x : Range)" suggest
3132 // "for (const Foo &x : Range)" if this form does not make a copy.
DiagnoseForRangeConstVariableCopies(Sema & SemaRef,const VarDecl * VD)3133 static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
3134                                                 const VarDecl *VD) {
3135   const Expr *InitExpr = VD->getInit();
3136   if (!InitExpr)
3137     return;
3138 
3139   QualType VariableType = VD->getType();
3140 
3141   if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
3142     if (!CE->getConstructor()->isCopyConstructor())
3143       return;
3144   } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
3145     if (CE->getCastKind() != CK_LValueToRValue)
3146       return;
3147   } else {
3148     return;
3149   }
3150 
3151   // Small trivially copyable types are cheap to copy. Do not emit the
3152   // diagnostic for these instances. 64 bytes is a common size of a cache line.
3153   // (The function `getTypeSize` returns the size in bits.)
3154   ASTContext &Ctx = SemaRef.Context;
3155   if (Ctx.getTypeSize(VariableType) <= 64 * 8 &&
3156       (VariableType.isTriviallyCopyConstructibleType(Ctx) ||
3157        hasTrivialABIAttr(VariableType)))
3158     return;
3159 
3160   // Suggest changing from a const variable to a const reference variable
3161   // if doing so will prevent a copy.
3162   SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
3163       << VD << VariableType;
3164   SemaRef.Diag(VD->getBeginLoc(), diag::note_use_reference_type)
3165       << SemaRef.Context.getLValueReferenceType(VariableType)
3166       << VD->getSourceRange()
3167       << FixItHint::CreateInsertion(VD->getLocation(), "&");
3168 }
3169 
3170 /// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
3171 /// 1) for (const foo &x : foos) where foos only returns a copy.  Suggest
3172 ///    using "const foo x" to show that a copy is made
3173 /// 2) for (const bar &x : foos) where bar is a temporary initialized by bar.
3174 ///    Suggest either "const bar x" to keep the copying or "const foo& x" to
3175 ///    prevent the copy.
3176 /// 3) for (const foo x : foos) where x is constructed from a reference foo.
3177 ///    Suggest "const foo &x" to prevent the copy.
DiagnoseForRangeVariableCopies(Sema & SemaRef,const CXXForRangeStmt * ForStmt)3178 static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
3179                                            const CXXForRangeStmt *ForStmt) {
3180   if (SemaRef.inTemplateInstantiation())
3181     return;
3182 
3183   SourceLocation Loc = ForStmt->getBeginLoc();
3184   if (SemaRef.Diags.isIgnored(
3185           diag::warn_for_range_const_ref_binds_temp_built_from_ref, Loc) &&
3186       SemaRef.Diags.isIgnored(diag::warn_for_range_ref_binds_ret_temp, Loc) &&
3187       SemaRef.Diags.isIgnored(diag::warn_for_range_copy, Loc)) {
3188     return;
3189   }
3190 
3191   const VarDecl *VD = ForStmt->getLoopVariable();
3192   if (!VD)
3193     return;
3194 
3195   QualType VariableType = VD->getType();
3196 
3197   if (VariableType->isIncompleteType())
3198     return;
3199 
3200   const Expr *InitExpr = VD->getInit();
3201   if (!InitExpr)
3202     return;
3203 
3204   if (InitExpr->getExprLoc().isMacroID())
3205     return;
3206 
3207   if (VariableType->isReferenceType()) {
3208     DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
3209                                             ForStmt->getRangeInit()->getType());
3210   } else if (VariableType.isConstQualified()) {
3211     DiagnoseForRangeConstVariableCopies(SemaRef, VD);
3212   }
3213 }
3214 
FinishCXXForRangeStmt(Stmt * S,Stmt * B)3215 StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
3216   if (!S || !B)
3217     return StmtError();
3218 
3219   if (isa<ObjCForCollectionStmt>(S))
3220     return ObjC().FinishObjCForCollectionStmt(S, B);
3221 
3222   CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
3223   ForStmt->setBody(B);
3224 
3225   DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
3226                         diag::warn_empty_range_based_for_body);
3227 
3228   DiagnoseForRangeVariableCopies(*this, ForStmt);
3229 
3230   return S;
3231 }
3232 
ActOnGotoStmt(SourceLocation GotoLoc,SourceLocation LabelLoc,LabelDecl * TheDecl)3233 StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
3234                                SourceLocation LabelLoc,
3235                                LabelDecl *TheDecl) {
3236   setFunctionHasBranchIntoScope();
3237 
3238   // If this goto is in a compute construct scope, we need to make sure we check
3239   // gotos in/out.
3240   if (getCurScope()->isInOpenACCComputeConstructScope())
3241     setFunctionHasBranchProtectedScope();
3242 
3243   TheDecl->markUsed(Context);
3244   return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
3245 }
3246 
3247 StmtResult
ActOnIndirectGotoStmt(SourceLocation GotoLoc,SourceLocation StarLoc,Expr * E)3248 Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
3249                             Expr *E) {
3250   // Convert operand to void*
3251   if (!E->isTypeDependent()) {
3252     QualType ETy = E->getType();
3253     QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
3254     ExprResult ExprRes = E;
3255     AssignConvertType ConvTy =
3256       CheckSingleAssignmentConstraints(DestTy, ExprRes);
3257     if (ExprRes.isInvalid())
3258       return StmtError();
3259     E = ExprRes.get();
3260     if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E,
3261                                  AssignmentAction::Passing))
3262       return StmtError();
3263   }
3264 
3265   ExprResult ExprRes = ActOnFinishFullExpr(E, /*DiscardedValue*/ false);
3266   if (ExprRes.isInvalid())
3267     return StmtError();
3268   E = ExprRes.get();
3269 
3270   setFunctionHasIndirectGoto();
3271 
3272   // If this goto is in a compute construct scope, we need to make sure we
3273   // check gotos in/out.
3274   if (getCurScope()->isInOpenACCComputeConstructScope())
3275     setFunctionHasBranchProtectedScope();
3276 
3277   return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
3278 }
3279 
CheckJumpOutOfSEHFinally(Sema & S,SourceLocation Loc,const Scope & DestScope)3280 static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
3281                                      const Scope &DestScope) {
3282   if (!S.CurrentSEHFinally.empty() &&
3283       DestScope.Contains(*S.CurrentSEHFinally.back())) {
3284     S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
3285   }
3286 }
3287 
3288 StmtResult
ActOnContinueStmt(SourceLocation ContinueLoc,Scope * CurScope)3289 Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
3290   Scope *S = CurScope->getContinueParent();
3291   if (!S) {
3292     // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
3293     return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
3294   }
3295   if (S->isConditionVarScope()) {
3296     // We cannot 'continue;' from within a statement expression in the
3297     // initializer of a condition variable because we would jump past the
3298     // initialization of that variable.
3299     return StmtError(Diag(ContinueLoc, diag::err_continue_from_cond_var_init));
3300   }
3301 
3302   // A 'continue' that would normally have execution continue on a block outside
3303   // of a compute construct counts as 'branching out of' the compute construct,
3304   // so diagnose here.
3305   if (S->isOpenACCComputeConstructScope())
3306     return StmtError(
3307         Diag(ContinueLoc, diag::err_acc_branch_in_out_compute_construct)
3308         << /*branch*/ 0 << /*out of */ 0);
3309 
3310   CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
3311 
3312   return new (Context) ContinueStmt(ContinueLoc);
3313 }
3314 
3315 StmtResult
ActOnBreakStmt(SourceLocation BreakLoc,Scope * CurScope)3316 Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
3317   Scope *S = CurScope->getBreakParent();
3318   if (!S) {
3319     // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
3320     return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
3321   }
3322   if (S->isOpenMPLoopScope())
3323     return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
3324                      << "break");
3325 
3326   // OpenACC doesn't allow 'break'ing from a compute construct, so diagnose if
3327   // we are trying to do so.  This can come in 2 flavors: 1-the break'able thing
3328   // (besides the compute construct) 'contains' the compute construct, at which
3329   // point the 'break' scope will be the compute construct.  Else it could be a
3330   // loop of some sort that has a direct parent of the compute construct.
3331   // However, a 'break' in a 'switch' marked as a compute construct doesn't
3332   // count as 'branch out of' the compute construct.
3333   if (S->isOpenACCComputeConstructScope() ||
3334       (S->isLoopScope() && S->getParent() &&
3335        S->getParent()->isOpenACCComputeConstructScope()))
3336     return StmtError(
3337         Diag(BreakLoc, diag::err_acc_branch_in_out_compute_construct)
3338         << /*branch*/ 0 << /*out of */ 0);
3339 
3340   CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
3341 
3342   return new (Context) BreakStmt(BreakLoc);
3343 }
3344 
getNamedReturnInfo(Expr * & E,SimplerImplicitMoveMode Mode)3345 Sema::NamedReturnInfo Sema::getNamedReturnInfo(Expr *&E,
3346                                                SimplerImplicitMoveMode Mode) {
3347   if (!E)
3348     return NamedReturnInfo();
3349   // - in a return statement in a function [where] ...
3350   // ... the expression is the name of a non-volatile automatic object ...
3351   const auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
3352   if (!DR || DR->refersToEnclosingVariableOrCapture())
3353     return NamedReturnInfo();
3354   const auto *VD = dyn_cast<VarDecl>(DR->getDecl());
3355   if (!VD)
3356     return NamedReturnInfo();
3357   if (VD->getInit() && VD->getInit()->containsErrors())
3358     return NamedReturnInfo();
3359   NamedReturnInfo Res = getNamedReturnInfo(VD);
3360   if (Res.Candidate && !E->isXValue() &&
3361       (Mode == SimplerImplicitMoveMode::ForceOn ||
3362        (Mode != SimplerImplicitMoveMode::ForceOff &&
3363         getLangOpts().CPlusPlus23))) {
3364     E = ImplicitCastExpr::Create(Context, VD->getType().getNonReferenceType(),
3365                                  CK_NoOp, E, nullptr, VK_XValue,
3366                                  FPOptionsOverride());
3367   }
3368   return Res;
3369 }
3370 
getNamedReturnInfo(const VarDecl * VD)3371 Sema::NamedReturnInfo Sema::getNamedReturnInfo(const VarDecl *VD) {
3372   NamedReturnInfo Info{VD, NamedReturnInfo::MoveEligibleAndCopyElidable};
3373 
3374   // C++20 [class.copy.elision]p3:
3375   // - in a return statement in a function with ...
3376   // (other than a function ... parameter)
3377   if (VD->getKind() == Decl::ParmVar)
3378     Info.S = NamedReturnInfo::MoveEligible;
3379   else if (VD->getKind() != Decl::Var)
3380     return NamedReturnInfo();
3381 
3382   // (other than ... a catch-clause parameter)
3383   if (VD->isExceptionVariable())
3384     Info.S = NamedReturnInfo::MoveEligible;
3385 
3386   // ...automatic...
3387   if (!VD->hasLocalStorage())
3388     return NamedReturnInfo();
3389 
3390   // We don't want to implicitly move out of a __block variable during a return
3391   // because we cannot assume the variable will no longer be used.
3392   if (VD->hasAttr<BlocksAttr>())
3393     return NamedReturnInfo();
3394 
3395   QualType VDType = VD->getType();
3396   if (VDType->isObjectType()) {
3397     // C++17 [class.copy.elision]p3:
3398     // ...non-volatile automatic object...
3399     if (VDType.isVolatileQualified())
3400       return NamedReturnInfo();
3401   } else if (VDType->isRValueReferenceType()) {
3402     // C++20 [class.copy.elision]p3:
3403     // ...either a non-volatile object or an rvalue reference to a non-volatile
3404     // object type...
3405     QualType VDReferencedType = VDType.getNonReferenceType();
3406     if (VDReferencedType.isVolatileQualified() ||
3407         !VDReferencedType->isObjectType())
3408       return NamedReturnInfo();
3409     Info.S = NamedReturnInfo::MoveEligible;
3410   } else {
3411     return NamedReturnInfo();
3412   }
3413 
3414   // Variables with higher required alignment than their type's ABI
3415   // alignment cannot use NRVO.
3416   if (!VD->hasDependentAlignment() && !VDType->isIncompleteType() &&
3417       Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VDType))
3418     Info.S = NamedReturnInfo::MoveEligible;
3419 
3420   return Info;
3421 }
3422 
getCopyElisionCandidate(NamedReturnInfo & Info,QualType ReturnType)3423 const VarDecl *Sema::getCopyElisionCandidate(NamedReturnInfo &Info,
3424                                              QualType ReturnType) {
3425   if (!Info.Candidate)
3426     return nullptr;
3427 
3428   auto invalidNRVO = [&] {
3429     Info = NamedReturnInfo();
3430     return nullptr;
3431   };
3432 
3433   // If we got a non-deduced auto ReturnType, we are in a dependent context and
3434   // there is no point in allowing copy elision since we won't have it deduced
3435   // by the point the VardDecl is instantiated, which is the last chance we have
3436   // of deciding if the candidate is really copy elidable.
3437   if ((ReturnType->getTypeClass() == Type::TypeClass::Auto &&
3438        ReturnType->isCanonicalUnqualified()) ||
3439       ReturnType->isSpecificBuiltinType(BuiltinType::Dependent))
3440     return invalidNRVO();
3441 
3442   if (!ReturnType->isDependentType()) {
3443     // - in a return statement in a function with ...
3444     // ... a class return type ...
3445     if (!ReturnType->isRecordType())
3446       return invalidNRVO();
3447 
3448     QualType VDType = Info.Candidate->getType();
3449     // ... the same cv-unqualified type as the function return type ...
3450     // When considering moving this expression out, allow dissimilar types.
3451     if (!VDType->isDependentType() &&
3452         !Context.hasSameUnqualifiedType(ReturnType, VDType))
3453       Info.S = NamedReturnInfo::MoveEligible;
3454   }
3455   return Info.isCopyElidable() ? Info.Candidate : nullptr;
3456 }
3457 
3458 /// Verify that the initialization sequence that was picked for the
3459 /// first overload resolution is permissible under C++98.
3460 ///
3461 /// Reject (possibly converting) constructors not taking an rvalue reference,
3462 /// or user conversion operators which are not ref-qualified.
3463 static bool
VerifyInitializationSequenceCXX98(const Sema & S,const InitializationSequence & Seq)3464 VerifyInitializationSequenceCXX98(const Sema &S,
3465                                   const InitializationSequence &Seq) {
3466   const auto *Step = llvm::find_if(Seq.steps(), [](const auto &Step) {
3467     return Step.Kind == InitializationSequence::SK_ConstructorInitialization ||
3468            Step.Kind == InitializationSequence::SK_UserConversion;
3469   });
3470   if (Step != Seq.step_end()) {
3471     const auto *FD = Step->Function.Function;
3472     if (isa<CXXConstructorDecl>(FD)
3473             ? !FD->getParamDecl(0)->getType()->isRValueReferenceType()
3474             : cast<CXXMethodDecl>(FD)->getRefQualifier() == RQ_None)
3475       return false;
3476   }
3477   return true;
3478 }
3479 
PerformMoveOrCopyInitialization(const InitializedEntity & Entity,const NamedReturnInfo & NRInfo,Expr * Value,bool SupressSimplerImplicitMoves)3480 ExprResult Sema::PerformMoveOrCopyInitialization(
3481     const InitializedEntity &Entity, const NamedReturnInfo &NRInfo, Expr *Value,
3482     bool SupressSimplerImplicitMoves) {
3483   if (getLangOpts().CPlusPlus &&
3484       (!getLangOpts().CPlusPlus23 || SupressSimplerImplicitMoves) &&
3485       NRInfo.isMoveEligible()) {
3486     ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(),
3487                               CK_NoOp, Value, VK_XValue, FPOptionsOverride());
3488     Expr *InitExpr = &AsRvalue;
3489     auto Kind = InitializationKind::CreateCopy(Value->getBeginLoc(),
3490                                                Value->getBeginLoc());
3491     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3492     auto Res = Seq.getFailedOverloadResult();
3493     if ((Res == OR_Success || Res == OR_Deleted) &&
3494         (getLangOpts().CPlusPlus11 ||
3495          VerifyInitializationSequenceCXX98(*this, Seq))) {
3496       // Promote "AsRvalue" to the heap, since we now need this
3497       // expression node to persist.
3498       Value =
3499           ImplicitCastExpr::Create(Context, Value->getType(), CK_NoOp, Value,
3500                                    nullptr, VK_XValue, FPOptionsOverride());
3501       // Complete type-checking the initialization of the return type
3502       // using the constructor we found.
3503       return Seq.Perform(*this, Entity, Kind, Value);
3504     }
3505   }
3506   // Either we didn't meet the criteria for treating an lvalue as an rvalue,
3507   // above, or overload resolution failed. Either way, we need to try
3508   // (again) now with the return value expression as written.
3509   return PerformCopyInitialization(Entity, SourceLocation(), Value);
3510 }
3511 
3512 /// Determine whether the declared return type of the specified function
3513 /// contains 'auto'.
hasDeducedReturnType(FunctionDecl * FD)3514 static bool hasDeducedReturnType(FunctionDecl *FD) {
3515   const FunctionProtoType *FPT =
3516       FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
3517   return FPT->getReturnType()->isUndeducedType();
3518 }
3519 
ActOnCapScopeReturnStmt(SourceLocation ReturnLoc,Expr * RetValExp,NamedReturnInfo & NRInfo,bool SupressSimplerImplicitMoves)3520 StmtResult Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc,
3521                                          Expr *RetValExp,
3522                                          NamedReturnInfo &NRInfo,
3523                                          bool SupressSimplerImplicitMoves) {
3524   // If this is the first return we've seen, infer the return type.
3525   // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
3526   CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
3527   QualType FnRetType = CurCap->ReturnType;
3528   LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
3529   if (CurLambda && CurLambda->CallOperator->getType().isNull())
3530     return StmtError();
3531   bool HasDeducedReturnType =
3532       CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
3533 
3534   if (ExprEvalContexts.back().isDiscardedStatementContext() &&
3535       (HasDeducedReturnType || CurCap->HasImplicitReturnType)) {
3536     if (RetValExp) {
3537       ExprResult ER =
3538           ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3539       if (ER.isInvalid())
3540         return StmtError();
3541       RetValExp = ER.get();
3542     }
3543     return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3544                               /* NRVOCandidate=*/nullptr);
3545   }
3546 
3547   if (HasDeducedReturnType) {
3548     FunctionDecl *FD = CurLambda->CallOperator;
3549     // If we've already decided this lambda is invalid, e.g. because
3550     // we saw a `return` whose expression had an error, don't keep
3551     // trying to deduce its return type.
3552     if (FD->isInvalidDecl())
3553       return StmtError();
3554     // In C++1y, the return type may involve 'auto'.
3555     // FIXME: Blocks might have a return type of 'auto' explicitly specified.
3556     if (CurCap->ReturnType.isNull())
3557       CurCap->ReturnType = FD->getReturnType();
3558 
3559     AutoType *AT = CurCap->ReturnType->getContainedAutoType();
3560     assert(AT && "lost auto type from lambda return type");
3561     if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3562       FD->setInvalidDecl();
3563       // FIXME: preserve the ill-formed return expression.
3564       return StmtError();
3565     }
3566     CurCap->ReturnType = FnRetType = FD->getReturnType();
3567   } else if (CurCap->HasImplicitReturnType) {
3568     // For blocks/lambdas with implicit return types, we check each return
3569     // statement individually, and deduce the common return type when the block
3570     // or lambda is completed.
3571     // FIXME: Fold this into the 'auto' codepath above.
3572     if (RetValExp && !isa<InitListExpr>(RetValExp)) {
3573       ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
3574       if (Result.isInvalid())
3575         return StmtError();
3576       RetValExp = Result.get();
3577 
3578       // DR1048: even prior to C++14, we should use the 'auto' deduction rules
3579       // when deducing a return type for a lambda-expression (or by extension
3580       // for a block). These rules differ from the stated C++11 rules only in
3581       // that they remove top-level cv-qualifiers.
3582       if (!CurContext->isDependentContext())
3583         FnRetType = RetValExp->getType().getUnqualifiedType();
3584       else
3585         FnRetType = CurCap->ReturnType = Context.DependentTy;
3586     } else {
3587       if (RetValExp) {
3588         // C++11 [expr.lambda.prim]p4 bans inferring the result from an
3589         // initializer list, because it is not an expression (even
3590         // though we represent it as one). We still deduce 'void'.
3591         Diag(ReturnLoc, diag::err_lambda_return_init_list)
3592           << RetValExp->getSourceRange();
3593       }
3594 
3595       FnRetType = Context.VoidTy;
3596     }
3597 
3598     // Although we'll properly infer the type of the block once it's completed,
3599     // make sure we provide a return type now for better error recovery.
3600     if (CurCap->ReturnType.isNull())
3601       CurCap->ReturnType = FnRetType;
3602   }
3603   const VarDecl *NRVOCandidate = getCopyElisionCandidate(NRInfo, FnRetType);
3604 
3605   if (auto *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
3606     if (CurBlock->FunctionType->castAs<FunctionType>()->getNoReturnAttr()) {
3607       Diag(ReturnLoc, diag::err_noreturn_has_return_expr)
3608           << diag::FalloffFunctionKind::Block;
3609       return StmtError();
3610     }
3611   } else if (auto *CurRegion = dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
3612     Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
3613     return StmtError();
3614   } else {
3615     assert(CurLambda && "unknown kind of captured scope");
3616     if (CurLambda->CallOperator->getType()
3617             ->castAs<FunctionType>()
3618             ->getNoReturnAttr()) {
3619       Diag(ReturnLoc, diag::err_noreturn_has_return_expr)
3620           << diag::FalloffFunctionKind::Lambda;
3621       return StmtError();
3622     }
3623   }
3624 
3625   // Otherwise, verify that this result type matches the previous one.  We are
3626   // pickier with blocks than for normal functions because we don't have GCC
3627   // compatibility to worry about here.
3628   if (FnRetType->isDependentType()) {
3629     // Delay processing for now.  TODO: there are lots of dependent
3630     // types we can conclusively prove aren't void.
3631   } else if (FnRetType->isVoidType()) {
3632     if (RetValExp && !isa<InitListExpr>(RetValExp) &&
3633         !(getLangOpts().CPlusPlus &&
3634           (RetValExp->isTypeDependent() ||
3635            RetValExp->getType()->isVoidType()))) {
3636       if (!getLangOpts().CPlusPlus &&
3637           RetValExp->getType()->isVoidType())
3638         Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
3639       else {
3640         Diag(ReturnLoc, diag::err_return_block_has_expr);
3641         RetValExp = nullptr;
3642       }
3643     }
3644   } else if (!RetValExp) {
3645     return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
3646   } else if (!RetValExp->isTypeDependent()) {
3647     // we have a non-void block with an expression, continue checking
3648 
3649     // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3650     // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3651     // function return.
3652 
3653     // In C++ the return statement is handled via a copy initialization.
3654     // the C version of which boils down to CheckSingleAssignmentConstraints.
3655     InitializedEntity Entity =
3656         InitializedEntity::InitializeResult(ReturnLoc, FnRetType);
3657     ExprResult Res = PerformMoveOrCopyInitialization(
3658         Entity, NRInfo, RetValExp, SupressSimplerImplicitMoves);
3659     if (Res.isInvalid()) {
3660       // FIXME: Cleanup temporaries here, anyway?
3661       return StmtError();
3662     }
3663     RetValExp = Res.get();
3664     CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
3665   }
3666 
3667   if (RetValExp) {
3668     ExprResult ER =
3669         ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3670     if (ER.isInvalid())
3671       return StmtError();
3672     RetValExp = ER.get();
3673   }
3674   auto *Result =
3675       ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
3676 
3677   // If we need to check for the named return value optimization,
3678   // or if we need to infer the return type,
3679   // save the return statement in our scope for later processing.
3680   if (CurCap->HasImplicitReturnType || NRVOCandidate)
3681     FunctionScopes.back()->Returns.push_back(Result);
3682 
3683   if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3684     FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3685 
3686   if (auto *CurBlock = dyn_cast<BlockScopeInfo>(CurCap);
3687       CurBlock && CurCap->HasImplicitReturnType && RetValExp &&
3688       RetValExp->containsErrors())
3689     CurBlock->TheDecl->setInvalidDecl();
3690 
3691   return Result;
3692 }
3693 
3694 namespace {
3695 /// Marks all typedefs in all local classes in a type referenced.
3696 ///
3697 /// In a function like
3698 /// auto f() {
3699 ///   struct S { typedef int a; };
3700 ///   return S();
3701 /// }
3702 ///
3703 /// the local type escapes and could be referenced in some TUs but not in
3704 /// others. Pretend that all local typedefs are always referenced, to not warn
3705 /// on this. This isn't necessary if f has internal linkage, or the typedef
3706 /// is private.
3707 class LocalTypedefNameReferencer : public DynamicRecursiveASTVisitor {
3708 public:
LocalTypedefNameReferencer(Sema & S)3709   LocalTypedefNameReferencer(Sema &S) : S(S) {}
3710   bool VisitRecordType(RecordType *RT) override;
3711 
3712 private:
3713   Sema &S;
3714 };
VisitRecordType(RecordType * RT)3715 bool LocalTypedefNameReferencer::VisitRecordType(RecordType *RT) {
3716   auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
3717   if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
3718       R->isDependentType())
3719     return true;
3720   for (auto *TmpD : R->decls())
3721     if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
3722       if (T->getAccess() != AS_private || R->hasFriends())
3723         S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
3724   return true;
3725 }
3726 }
3727 
getReturnTypeLoc(FunctionDecl * FD) const3728 TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
3729   return FD->getTypeSourceInfo()
3730       ->getTypeLoc()
3731       .getAsAdjusted<FunctionProtoTypeLoc>()
3732       .getReturnLoc();
3733 }
3734 
DeduceFunctionTypeFromReturnExpr(FunctionDecl * FD,SourceLocation ReturnLoc,Expr * RetExpr,const AutoType * AT)3735 bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
3736                                             SourceLocation ReturnLoc,
3737                                             Expr *RetExpr, const AutoType *AT) {
3738   // If this is the conversion function for a lambda, we choose to deduce its
3739   // type from the corresponding call operator, not from the synthesized return
3740   // statement within it. See Sema::DeduceReturnType.
3741   if (isLambdaConversionOperator(FD))
3742     return false;
3743 
3744   if (isa_and_nonnull<InitListExpr>(RetExpr)) {
3745     //  If the deduction is for a return statement and the initializer is
3746     //  a braced-init-list, the program is ill-formed.
3747     Diag(RetExpr->getExprLoc(),
3748          getCurLambda() ? diag::err_lambda_return_init_list
3749                         : diag::err_auto_fn_return_init_list)
3750         << RetExpr->getSourceRange();
3751     return true;
3752   }
3753 
3754   if (FD->isDependentContext()) {
3755     // C++1y [dcl.spec.auto]p12:
3756     //   Return type deduction [...] occurs when the definition is
3757     //   instantiated even if the function body contains a return
3758     //   statement with a non-type-dependent operand.
3759     assert(AT->isDeduced() && "should have deduced to dependent type");
3760     return false;
3761   }
3762 
3763   TypeLoc OrigResultType = getReturnTypeLoc(FD);
3764   //  In the case of a return with no operand, the initializer is considered
3765   //  to be void().
3766   CXXScalarValueInitExpr VoidVal(Context.VoidTy, nullptr, SourceLocation());
3767   if (!RetExpr) {
3768     // For a function with a deduced result type to return with omitted
3769     // expression, the result type as written must be 'auto' or
3770     // 'decltype(auto)', possibly cv-qualified or constrained, but not
3771     // ref-qualified.
3772     if (!OrigResultType.getType()->getAs<AutoType>()) {
3773       Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3774           << OrigResultType.getType();
3775       return true;
3776     }
3777     RetExpr = &VoidVal;
3778   }
3779 
3780   QualType Deduced = AT->getDeducedType();
3781   {
3782     //  Otherwise, [...] deduce a value for U using the rules of template
3783     //  argument deduction.
3784     auto RetExprLoc = RetExpr->getExprLoc();
3785     TemplateDeductionInfo Info(RetExprLoc);
3786     SourceLocation TemplateSpecLoc;
3787     if (RetExpr->getType() == Context.OverloadTy) {
3788       auto FindResult = OverloadExpr::find(RetExpr);
3789       if (FindResult.Expression)
3790         TemplateSpecLoc = FindResult.Expression->getNameLoc();
3791     }
3792     TemplateSpecCandidateSet FailedTSC(TemplateSpecLoc);
3793     TemplateDeductionResult Res = DeduceAutoType(
3794         OrigResultType, RetExpr, Deduced, Info, /*DependentDeduction=*/false,
3795         /*IgnoreConstraints=*/false, &FailedTSC);
3796     if (Res != TemplateDeductionResult::Success && FD->isInvalidDecl())
3797       return true;
3798     switch (Res) {
3799     case TemplateDeductionResult::Success:
3800       break;
3801     case TemplateDeductionResult::AlreadyDiagnosed:
3802       return true;
3803     case TemplateDeductionResult::Inconsistent: {
3804       //  If a function with a declared return type that contains a placeholder
3805       //  type has multiple return statements, the return type is deduced for
3806       //  each return statement. [...] if the type deduced is not the same in
3807       //  each deduction, the program is ill-formed.
3808       const LambdaScopeInfo *LambdaSI = getCurLambda();
3809       if (LambdaSI && LambdaSI->HasImplicitReturnType)
3810         Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
3811             << Info.SecondArg << Info.FirstArg << true /*IsLambda*/;
3812       else
3813         Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3814             << (AT->isDecltypeAuto() ? 1 : 0) << Info.SecondArg
3815             << Info.FirstArg;
3816       return true;
3817     }
3818     default:
3819       Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3820           << OrigResultType.getType() << RetExpr->getType();
3821       FailedTSC.NoteCandidates(*this, RetExprLoc);
3822       return true;
3823     }
3824   }
3825 
3826   // If a local type is part of the returned type, mark its fields as
3827   // referenced.
3828   LocalTypedefNameReferencer(*this).TraverseType(RetExpr->getType());
3829 
3830   // CUDA: Kernel function must have 'void' return type.
3831   if (getLangOpts().CUDA && FD->hasAttr<CUDAGlobalAttr>() &&
3832       !Deduced->isVoidType()) {
3833     Diag(FD->getLocation(), diag::err_kern_type_not_void_return)
3834         << FD->getType() << FD->getSourceRange();
3835     return true;
3836   }
3837 
3838   if (!FD->isInvalidDecl() && AT->getDeducedType() != Deduced)
3839     // Update all declarations of the function to have the deduced return type.
3840     Context.adjustDeducedFunctionResultType(FD, Deduced);
3841 
3842   return false;
3843 }
3844 
3845 StmtResult
ActOnReturnStmt(SourceLocation ReturnLoc,Expr * RetValExp,Scope * CurScope)3846 Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3847                       Scope *CurScope) {
3848   ExprResult RetVal = RetValExp;
3849   if (RetVal.isInvalid())
3850     return StmtError();
3851 
3852   if (getCurScope()->isInOpenACCComputeConstructScope())
3853     return StmtError(
3854         Diag(ReturnLoc, diag::err_acc_branch_in_out_compute_construct)
3855         << /*return*/ 1 << /*out of */ 0);
3856 
3857   // using plain return in a coroutine is not allowed.
3858   FunctionScopeInfo *FSI = getCurFunction();
3859   if (FSI->FirstReturnLoc.isInvalid() && FSI->isCoroutine()) {
3860     assert(FSI->FirstCoroutineStmtLoc.isValid() &&
3861            "first coroutine location not set");
3862     Diag(ReturnLoc, diag::err_return_in_coroutine);
3863     Diag(FSI->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
3864         << FSI->getFirstCoroutineStmtKeyword();
3865   }
3866 
3867   CheckInvalidBuiltinCountedByRef(RetVal.get(),
3868                                   BuiltinCountedByRefKind::ReturnArg);
3869 
3870   StmtResult R =
3871       BuildReturnStmt(ReturnLoc, RetVal.get(), /*AllowRecovery=*/true);
3872   if (R.isInvalid() || ExprEvalContexts.back().isDiscardedStatementContext())
3873     return R;
3874 
3875   VarDecl *VD =
3876       const_cast<VarDecl *>(cast<ReturnStmt>(R.get())->getNRVOCandidate());
3877 
3878   CurScope->updateNRVOCandidate(VD);
3879 
3880   CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3881 
3882   return R;
3883 }
3884 
CheckSimplerImplicitMovesMSVCWorkaround(const Sema & S,const Expr * E)3885 static bool CheckSimplerImplicitMovesMSVCWorkaround(const Sema &S,
3886                                                     const Expr *E) {
3887   if (!E || !S.getLangOpts().CPlusPlus23 || !S.getLangOpts().MSVCCompat)
3888     return false;
3889   const Decl *D = E->getReferencedDeclOfCallee();
3890   if (!D || !S.SourceMgr.isInSystemHeader(D->getLocation()))
3891     return false;
3892   for (const DeclContext *DC = D->getDeclContext(); DC; DC = DC->getParent()) {
3893     if (DC->isStdNamespace())
3894       return true;
3895   }
3896   return false;
3897 }
3898 
BuildReturnStmt(SourceLocation ReturnLoc,Expr * RetValExp,bool AllowRecovery)3899 StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3900                                  bool AllowRecovery) {
3901   // Check for unexpanded parameter packs.
3902   if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3903     return StmtError();
3904 
3905   // HACK: We suppress simpler implicit move here in msvc compatibility mode
3906   // just as a temporary work around, as the MSVC STL has issues with
3907   // this change.
3908   bool SupressSimplerImplicitMoves =
3909       CheckSimplerImplicitMovesMSVCWorkaround(*this, RetValExp);
3910   NamedReturnInfo NRInfo = getNamedReturnInfo(
3911       RetValExp, SupressSimplerImplicitMoves ? SimplerImplicitMoveMode::ForceOff
3912                                              : SimplerImplicitMoveMode::Normal);
3913 
3914   if (isa<CapturingScopeInfo>(getCurFunction()))
3915     return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp, NRInfo,
3916                                    SupressSimplerImplicitMoves);
3917 
3918   QualType FnRetType;
3919   QualType RelatedRetType;
3920   const AttrVec *Attrs = nullptr;
3921   bool isObjCMethod = false;
3922 
3923   if (const FunctionDecl *FD = getCurFunctionDecl()) {
3924     FnRetType = FD->getReturnType();
3925     if (FD->hasAttrs())
3926       Attrs = &FD->getAttrs();
3927     if (FD->isNoReturn() && !getCurFunction()->isCoroutine())
3928       Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr) << FD;
3929     if (FD->isMain() && RetValExp)
3930       if (isa<CXXBoolLiteralExpr>(RetValExp))
3931         Diag(ReturnLoc, diag::warn_main_returns_bool_literal)
3932             << RetValExp->getSourceRange();
3933     if (FD->hasAttr<CmseNSEntryAttr>() && RetValExp) {
3934       if (const auto *RT = dyn_cast<RecordType>(FnRetType.getCanonicalType())) {
3935         if (RT->getDecl()->isOrContainsUnion())
3936           Diag(RetValExp->getBeginLoc(), diag::warn_cmse_nonsecure_union) << 1;
3937       }
3938     }
3939   } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
3940     FnRetType = MD->getReturnType();
3941     isObjCMethod = true;
3942     if (MD->hasAttrs())
3943       Attrs = &MD->getAttrs();
3944     if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3945       // In the implementation of a method with a related return type, the
3946       // type used to type-check the validity of return statements within the
3947       // method body is a pointer to the type of the class being implemented.
3948       RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3949       RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
3950     }
3951   } else // If we don't have a function/method context, bail.
3952     return StmtError();
3953 
3954   if (RetValExp) {
3955     const auto *ATy = dyn_cast<ArrayType>(RetValExp->getType());
3956     if (ATy && ATy->getElementType().isWebAssemblyReferenceType()) {
3957       Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
3958       return StmtError();
3959     }
3960   }
3961 
3962   // C++1z: discarded return statements are not considered when deducing a
3963   // return type.
3964   if (ExprEvalContexts.back().isDiscardedStatementContext() &&
3965       FnRetType->getContainedAutoType()) {
3966     if (RetValExp) {
3967       ExprResult ER =
3968           ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
3969       if (ER.isInvalid())
3970         return StmtError();
3971       RetValExp = ER.get();
3972     }
3973     return ReturnStmt::Create(Context, ReturnLoc, RetValExp,
3974                               /* NRVOCandidate=*/nullptr);
3975   }
3976 
3977   // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3978   // deduction.
3979   if (getLangOpts().CPlusPlus14) {
3980     if (AutoType *AT = FnRetType->getContainedAutoType()) {
3981       FunctionDecl *FD = cast<FunctionDecl>(CurContext);
3982       // If we've already decided this function is invalid, e.g. because
3983       // we saw a `return` whose expression had an error, don't keep
3984       // trying to deduce its return type.
3985       // (Some return values may be needlessly wrapped in RecoveryExpr).
3986       if (FD->isInvalidDecl() ||
3987           DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3988         FD->setInvalidDecl();
3989         if (!AllowRecovery)
3990           return StmtError();
3991         // The deduction failure is diagnosed and marked, try to recover.
3992         if (RetValExp) {
3993           // Wrap return value with a recovery expression of the previous type.
3994           // If no deduction yet, use DependentTy.
3995           auto Recovery = CreateRecoveryExpr(
3996               RetValExp->getBeginLoc(), RetValExp->getEndLoc(), RetValExp,
3997               AT->isDeduced() ? FnRetType : QualType());
3998           if (Recovery.isInvalid())
3999             return StmtError();
4000           RetValExp = Recovery.get();
4001         } else {
4002           // Nothing to do: a ReturnStmt with no value is fine recovery.
4003         }
4004       } else {
4005         FnRetType = FD->getReturnType();
4006       }
4007     }
4008   }
4009   const VarDecl *NRVOCandidate = getCopyElisionCandidate(NRInfo, FnRetType);
4010 
4011   bool HasDependentReturnType = FnRetType->isDependentType();
4012 
4013   ReturnStmt *Result = nullptr;
4014   if (FnRetType->isVoidType()) {
4015     if (RetValExp) {
4016       if (auto *ILE = dyn_cast<InitListExpr>(RetValExp)) {
4017         // We simply never allow init lists as the return value of void
4018         // functions. This is compatible because this was never allowed before,
4019         // so there's no legacy code to deal with.
4020         NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
4021         int FunctionKind = 0;
4022         if (isa<ObjCMethodDecl>(CurDecl))
4023           FunctionKind = 1;
4024         else if (isa<CXXConstructorDecl>(CurDecl))
4025           FunctionKind = 2;
4026         else if (isa<CXXDestructorDecl>(CurDecl))
4027           FunctionKind = 3;
4028 
4029         Diag(ReturnLoc, diag::err_return_init_list)
4030             << CurDecl << FunctionKind << RetValExp->getSourceRange();
4031 
4032         // Preserve the initializers in the AST.
4033         RetValExp = AllowRecovery
4034                         ? CreateRecoveryExpr(ILE->getLBraceLoc(),
4035                                              ILE->getRBraceLoc(), ILE->inits())
4036                               .get()
4037                         : nullptr;
4038       } else if (!RetValExp->isTypeDependent()) {
4039         // C99 6.8.6.4p1 (ext_ since GCC warns)
4040         unsigned D = diag::ext_return_has_expr;
4041         if (RetValExp->getType()->isVoidType()) {
4042           NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
4043           if (isa<CXXConstructorDecl>(CurDecl) ||
4044               isa<CXXDestructorDecl>(CurDecl))
4045             D = diag::err_ctor_dtor_returns_void;
4046           else
4047             D = diag::ext_return_has_void_expr;
4048         }
4049         else {
4050           ExprResult Result = RetValExp;
4051           Result = IgnoredValueConversions(Result.get());
4052           if (Result.isInvalid())
4053             return StmtError();
4054           RetValExp = Result.get();
4055           RetValExp = ImpCastExprToType(RetValExp,
4056                                         Context.VoidTy, CK_ToVoid).get();
4057         }
4058         // return of void in constructor/destructor is illegal in C++.
4059         if (D == diag::err_ctor_dtor_returns_void) {
4060           NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
4061           Diag(ReturnLoc, D) << CurDecl << isa<CXXDestructorDecl>(CurDecl)
4062                              << RetValExp->getSourceRange();
4063         }
4064         // return (some void expression); is legal in C++ and C2y.
4065         else if (D != diag::ext_return_has_void_expr ||
4066                  (!getLangOpts().CPlusPlus && !getLangOpts().C2y)) {
4067           NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
4068 
4069           int FunctionKind = 0;
4070           if (isa<ObjCMethodDecl>(CurDecl))
4071             FunctionKind = 1;
4072           else if (isa<CXXConstructorDecl>(CurDecl))
4073             FunctionKind = 2;
4074           else if (isa<CXXDestructorDecl>(CurDecl))
4075             FunctionKind = 3;
4076 
4077           Diag(ReturnLoc, D)
4078               << CurDecl << FunctionKind << RetValExp->getSourceRange();
4079         }
4080       }
4081 
4082       if (RetValExp) {
4083         ExprResult ER =
4084             ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
4085         if (ER.isInvalid())
4086           return StmtError();
4087         RetValExp = ER.get();
4088       }
4089     }
4090 
4091     Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp,
4092                                 /* NRVOCandidate=*/nullptr);
4093   } else if (!RetValExp && !HasDependentReturnType) {
4094     FunctionDecl *FD = getCurFunctionDecl();
4095 
4096     if ((FD && FD->isInvalidDecl()) || FnRetType->containsErrors()) {
4097       // The intended return type might have been "void", so don't warn.
4098     } else if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
4099       // C++11 [stmt.return]p2
4100       Diag(ReturnLoc, diag::err_constexpr_return_missing_expr)
4101           << FD << FD->isConsteval();
4102       FD->setInvalidDecl();
4103     } else {
4104       // C99 6.8.6.4p1 (ext_ since GCC warns)
4105       // C90 6.6.6.4p4
4106       unsigned DiagID = getLangOpts().C99 ? diag::ext_return_missing_expr
4107                                           : diag::warn_return_missing_expr;
4108       // Note that at this point one of getCurFunctionDecl() or
4109       // getCurMethodDecl() must be non-null (see above).
4110       assert((getCurFunctionDecl() || getCurMethodDecl()) &&
4111              "Not in a FunctionDecl or ObjCMethodDecl?");
4112       bool IsMethod = FD == nullptr;
4113       const NamedDecl *ND =
4114           IsMethod ? cast<NamedDecl>(getCurMethodDecl()) : cast<NamedDecl>(FD);
4115       Diag(ReturnLoc, DiagID) << ND << IsMethod;
4116     }
4117 
4118     Result = ReturnStmt::Create(Context, ReturnLoc, /* RetExpr=*/nullptr,
4119                                 /* NRVOCandidate=*/nullptr);
4120   } else {
4121     assert(RetValExp || HasDependentReturnType);
4122     QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
4123 
4124     // C99 6.8.6.4p3(136): The return statement is not an assignment. The
4125     // overlap restriction of subclause 6.5.16.1 does not apply to the case of
4126     // function return.
4127 
4128     // In C++ the return statement is handled via a copy initialization,
4129     // the C version of which boils down to CheckSingleAssignmentConstraints.
4130     if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
4131       // we have a non-void function with an expression, continue checking
4132       InitializedEntity Entity =
4133           InitializedEntity::InitializeResult(ReturnLoc, RetType);
4134       ExprResult Res = PerformMoveOrCopyInitialization(
4135           Entity, NRInfo, RetValExp, SupressSimplerImplicitMoves);
4136       if (Res.isInvalid() && AllowRecovery)
4137         Res = CreateRecoveryExpr(RetValExp->getBeginLoc(),
4138                                  RetValExp->getEndLoc(), RetValExp, RetType);
4139       if (Res.isInvalid()) {
4140         // FIXME: Clean up temporaries here anyway?
4141         return StmtError();
4142       }
4143       RetValExp = Res.getAs<Expr>();
4144 
4145       // If we have a related result type, we need to implicitly
4146       // convert back to the formal result type.  We can't pretend to
4147       // initialize the result again --- we might end double-retaining
4148       // --- so instead we initialize a notional temporary.
4149       if (!RelatedRetType.isNull()) {
4150         Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
4151                                                             FnRetType);
4152         Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
4153         if (Res.isInvalid()) {
4154           // FIXME: Clean up temporaries here anyway?
4155           return StmtError();
4156         }
4157         RetValExp = Res.getAs<Expr>();
4158       }
4159 
4160       CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
4161                          getCurFunctionDecl());
4162     }
4163 
4164     if (RetValExp) {
4165       ExprResult ER =
4166           ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false);
4167       if (ER.isInvalid())
4168         return StmtError();
4169       RetValExp = ER.get();
4170     }
4171     Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate);
4172   }
4173 
4174   // If we need to check for the named return value optimization, save the
4175   // return statement in our scope for later processing.
4176   if (Result->getNRVOCandidate())
4177     FunctionScopes.back()->Returns.push_back(Result);
4178 
4179   if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
4180     FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
4181 
4182   return Result;
4183 }
4184 
4185 StmtResult
ActOnCXXCatchBlock(SourceLocation CatchLoc,Decl * ExDecl,Stmt * HandlerBlock)4186 Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
4187                          Stmt *HandlerBlock) {
4188   // There's nothing to test that ActOnExceptionDecl didn't already test.
4189   return new (Context)
4190       CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
4191 }
4192 
4193 namespace {
4194 class CatchHandlerType {
4195   QualType QT;
4196   LLVM_PREFERRED_TYPE(bool)
4197   unsigned IsPointer : 1;
4198 
4199   // This is a special constructor to be used only with DenseMapInfo's
4200   // getEmptyKey() and getTombstoneKey() functions.
4201   friend struct llvm::DenseMapInfo<CatchHandlerType>;
4202   enum Unique { ForDenseMap };
CatchHandlerType(QualType QT,Unique)4203   CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
4204 
4205 public:
4206   /// Used when creating a CatchHandlerType from a handler type; will determine
4207   /// whether the type is a pointer or reference and will strip off the top
4208   /// level pointer and cv-qualifiers.
CatchHandlerType(QualType Q)4209   CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
4210     if (QT->isPointerType())
4211       IsPointer = true;
4212 
4213     QT = QT.getUnqualifiedType();
4214     if (IsPointer || QT->isReferenceType())
4215       QT = QT->getPointeeType();
4216   }
4217 
4218   /// Used when creating a CatchHandlerType from a base class type; pretends the
4219   /// type passed in had the pointer qualifier, does not need to get an
4220   /// unqualified type.
CatchHandlerType(QualType QT,bool IsPointer)4221   CatchHandlerType(QualType QT, bool IsPointer)
4222       : QT(QT), IsPointer(IsPointer) {}
4223 
underlying() const4224   QualType underlying() const { return QT; }
isPointer() const4225   bool isPointer() const { return IsPointer; }
4226 
operator ==(const CatchHandlerType & LHS,const CatchHandlerType & RHS)4227   friend bool operator==(const CatchHandlerType &LHS,
4228                          const CatchHandlerType &RHS) {
4229     // If the pointer qualification does not match, we can return early.
4230     if (LHS.IsPointer != RHS.IsPointer)
4231       return false;
4232     // Otherwise, check the underlying type without cv-qualifiers.
4233     return LHS.QT == RHS.QT;
4234   }
4235 };
4236 } // namespace
4237 
4238 namespace llvm {
4239 template <> struct DenseMapInfo<CatchHandlerType> {
getEmptyKeyllvm::DenseMapInfo4240   static CatchHandlerType getEmptyKey() {
4241     return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
4242                        CatchHandlerType::ForDenseMap);
4243   }
4244 
getTombstoneKeyllvm::DenseMapInfo4245   static CatchHandlerType getTombstoneKey() {
4246     return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
4247                        CatchHandlerType::ForDenseMap);
4248   }
4249 
getHashValuellvm::DenseMapInfo4250   static unsigned getHashValue(const CatchHandlerType &Base) {
4251     return DenseMapInfo<QualType>::getHashValue(Base.underlying());
4252   }
4253 
isEqualllvm::DenseMapInfo4254   static bool isEqual(const CatchHandlerType &LHS,
4255                       const CatchHandlerType &RHS) {
4256     return LHS == RHS;
4257   }
4258 };
4259 }
4260 
4261 namespace {
4262 class CatchTypePublicBases {
4263   const llvm::DenseMap<QualType, CXXCatchStmt *> &TypesToCheck;
4264 
4265   CXXCatchStmt *FoundHandler;
4266   QualType FoundHandlerType;
4267   QualType TestAgainstType;
4268 
4269 public:
CatchTypePublicBases(const llvm::DenseMap<QualType,CXXCatchStmt * > & T,QualType QT)4270   CatchTypePublicBases(const llvm::DenseMap<QualType, CXXCatchStmt *> &T,
4271                        QualType QT)
4272       : TypesToCheck(T), FoundHandler(nullptr), TestAgainstType(QT) {}
4273 
getFoundHandler() const4274   CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
getFoundHandlerType() const4275   QualType getFoundHandlerType() const { return FoundHandlerType; }
4276 
operator ()(const CXXBaseSpecifier * S,CXXBasePath &)4277   bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
4278     if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
4279       QualType Check = S->getType().getCanonicalType();
4280       const auto &M = TypesToCheck;
4281       auto I = M.find(Check);
4282       if (I != M.end()) {
4283         // We're pretty sure we found what we need to find. However, we still
4284         // need to make sure that we properly compare for pointers and
4285         // references, to handle cases like:
4286         //
4287         // } catch (Base *b) {
4288         // } catch (Derived &d) {
4289         // }
4290         //
4291         // where there is a qualification mismatch that disqualifies this
4292         // handler as a potential problem.
4293         if (I->second->getCaughtType()->isPointerType() ==
4294                 TestAgainstType->isPointerType()) {
4295           FoundHandler = I->second;
4296           FoundHandlerType = Check;
4297           return true;
4298         }
4299       }
4300     }
4301     return false;
4302   }
4303 };
4304 }
4305 
ActOnCXXTryBlock(SourceLocation TryLoc,Stmt * TryBlock,ArrayRef<Stmt * > Handlers)4306 StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
4307                                   ArrayRef<Stmt *> Handlers) {
4308   const llvm::Triple &T = Context.getTargetInfo().getTriple();
4309   const bool IsOpenMPGPUTarget =
4310       getLangOpts().OpenMPIsTargetDevice && (T.isNVPTX() || T.isAMDGCN());
4311 
4312   DiagnoseExceptionUse(TryLoc, /* IsTry= */ true);
4313 
4314   // In OpenMP target regions, we assume that catch is never reached on GPU
4315   // targets.
4316   if (IsOpenMPGPUTarget)
4317     targetDiag(TryLoc, diag::warn_try_not_valid_on_target) << T.str();
4318 
4319   // Exceptions aren't allowed in CUDA device code.
4320   if (getLangOpts().CUDA)
4321     CUDA().DiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions)
4322         << "try" << CUDA().CurrentTarget();
4323 
4324   if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
4325     Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
4326 
4327   sema::FunctionScopeInfo *FSI = getCurFunction();
4328 
4329   // C++ try is incompatible with SEH __try.
4330   if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
4331     Diag(TryLoc, diag::err_mixing_cxx_try_seh_try) << 0;
4332     Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
4333   }
4334 
4335   const unsigned NumHandlers = Handlers.size();
4336   assert(!Handlers.empty() &&
4337          "The parser shouldn't call this if there are no handlers.");
4338 
4339   llvm::DenseMap<QualType, CXXCatchStmt *> HandledBaseTypes;
4340   llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
4341   for (unsigned i = 0; i < NumHandlers; ++i) {
4342     CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
4343 
4344     // Diagnose when the handler is a catch-all handler, but it isn't the last
4345     // handler for the try block. [except.handle]p5. Also, skip exception
4346     // declarations that are invalid, since we can't usefully report on them.
4347     if (!H->getExceptionDecl()) {
4348       if (i < NumHandlers - 1)
4349         return StmtError(Diag(H->getBeginLoc(), diag::err_early_catch_all));
4350       continue;
4351     } else if (H->getExceptionDecl()->isInvalidDecl())
4352       continue;
4353 
4354     // Walk the type hierarchy to diagnose when this type has already been
4355     // handled (duplication), or cannot be handled (derivation inversion). We
4356     // ignore top-level cv-qualifiers, per [except.handle]p3
4357     CatchHandlerType HandlerCHT = H->getCaughtType().getCanonicalType();
4358 
4359     // We can ignore whether the type is a reference or a pointer; we need the
4360     // underlying declaration type in order to get at the underlying record
4361     // decl, if there is one.
4362     QualType Underlying = HandlerCHT.underlying();
4363     if (auto *RD = Underlying->getAsCXXRecordDecl()) {
4364       if (!RD->hasDefinition())
4365         continue;
4366       // Check that none of the public, unambiguous base classes are in the
4367       // map ([except.handle]p1). Give the base classes the same pointer
4368       // qualification as the original type we are basing off of. This allows
4369       // comparison against the handler type using the same top-level pointer
4370       // as the original type.
4371       CXXBasePaths Paths;
4372       Paths.setOrigin(RD);
4373       CatchTypePublicBases CTPB(HandledBaseTypes,
4374                                 H->getCaughtType().getCanonicalType());
4375       if (RD->lookupInBases(CTPB, Paths)) {
4376         const CXXCatchStmt *Problem = CTPB.getFoundHandler();
4377         if (!Paths.isAmbiguous(
4378                 CanQualType::CreateUnsafe(CTPB.getFoundHandlerType()))) {
4379           Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
4380                diag::warn_exception_caught_by_earlier_handler)
4381               << H->getCaughtType();
4382           Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
4383                 diag::note_previous_exception_handler)
4384               << Problem->getCaughtType();
4385         }
4386       }
4387       // Strip the qualifiers here because we're going to be comparing this
4388       // type to the base type specifiers of a class, which are ignored in a
4389       // base specifier per [class.derived.general]p2.
4390       HandledBaseTypes[Underlying.getUnqualifiedType()] = H;
4391     }
4392 
4393     // Add the type the list of ones we have handled; diagnose if we've already
4394     // handled it.
4395     auto R = HandledTypes.insert(
4396         std::make_pair(H->getCaughtType().getCanonicalType(), H));
4397     if (!R.second) {
4398       const CXXCatchStmt *Problem = R.first->second;
4399       Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
4400            diag::warn_exception_caught_by_earlier_handler)
4401           << H->getCaughtType();
4402       Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
4403            diag::note_previous_exception_handler)
4404           << Problem->getCaughtType();
4405     }
4406   }
4407 
4408   FSI->setHasCXXTry(TryLoc);
4409 
4410   return CXXTryStmt::Create(Context, TryLoc, cast<CompoundStmt>(TryBlock),
4411                             Handlers);
4412 }
4413 
DiagnoseExceptionUse(SourceLocation Loc,bool IsTry)4414 void Sema::DiagnoseExceptionUse(SourceLocation Loc, bool IsTry) {
4415   const llvm::Triple &T = Context.getTargetInfo().getTriple();
4416   const bool IsOpenMPGPUTarget =
4417       getLangOpts().OpenMPIsTargetDevice && (T.isNVPTX() || T.isAMDGCN());
4418 
4419   // Don't report an error if 'try' is used in system headers or in an OpenMP
4420   // target region compiled for a GPU architecture.
4421   if (IsOpenMPGPUTarget || getLangOpts().CUDA)
4422     // Delay error emission for the OpenMP device code.
4423     return;
4424 
4425   if (!getLangOpts().CXXExceptions &&
4426       !getSourceManager().isInSystemHeader(Loc) &&
4427       !CurContext->isDependentContext())
4428     targetDiag(Loc, diag::err_exceptions_disabled) << (IsTry ? "try" : "throw");
4429 }
4430 
ActOnSEHTryBlock(bool IsCXXTry,SourceLocation TryLoc,Stmt * TryBlock,Stmt * Handler)4431 StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
4432                                   Stmt *TryBlock, Stmt *Handler) {
4433   assert(TryBlock && Handler);
4434 
4435   sema::FunctionScopeInfo *FSI = getCurFunction();
4436 
4437   // SEH __try is incompatible with C++ try. Borland appears to support this,
4438   // however.
4439   if (!getLangOpts().Borland) {
4440     if (FSI->FirstCXXOrObjCTryLoc.isValid()) {
4441       Diag(TryLoc, diag::err_mixing_cxx_try_seh_try) << FSI->FirstTryType;
4442       Diag(FSI->FirstCXXOrObjCTryLoc, diag::note_conflicting_try_here)
4443           << (FSI->FirstTryType == sema::FunctionScopeInfo::TryLocIsCXX
4444                   ? "'try'"
4445                   : "'@try'");
4446     }
4447   }
4448 
4449   FSI->setHasSEHTry(TryLoc);
4450 
4451   // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
4452   // track if they use SEH.
4453   DeclContext *DC = CurContext;
4454   while (DC && !DC->isFunctionOrMethod())
4455     DC = DC->getParent();
4456   FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
4457   if (FD)
4458     FD->setUsesSEHTry(true);
4459   else
4460     Diag(TryLoc, diag::err_seh_try_outside_functions);
4461 
4462   // Reject __try on unsupported targets.
4463   if (!Context.getTargetInfo().isSEHTrySupported())
4464     Diag(TryLoc, diag::err_seh_try_unsupported);
4465 
4466   return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
4467 }
4468 
ActOnSEHExceptBlock(SourceLocation Loc,Expr * FilterExpr,Stmt * Block)4469 StmtResult Sema::ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr,
4470                                      Stmt *Block) {
4471   assert(FilterExpr && Block);
4472   QualType FTy = FilterExpr->getType();
4473   if (!FTy->isIntegerType() && !FTy->isDependentType()) {
4474     return StmtError(
4475         Diag(FilterExpr->getExprLoc(), diag::err_filter_expression_integral)
4476         << FTy);
4477   }
4478   return SEHExceptStmt::Create(Context, Loc, FilterExpr, Block);
4479 }
4480 
ActOnStartSEHFinallyBlock()4481 void Sema::ActOnStartSEHFinallyBlock() {
4482   CurrentSEHFinally.push_back(CurScope);
4483 }
4484 
ActOnAbortSEHFinallyBlock()4485 void Sema::ActOnAbortSEHFinallyBlock() {
4486   CurrentSEHFinally.pop_back();
4487 }
4488 
ActOnFinishSEHFinallyBlock(SourceLocation Loc,Stmt * Block)4489 StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
4490   assert(Block);
4491   CurrentSEHFinally.pop_back();
4492   return SEHFinallyStmt::Create(Context, Loc, Block);
4493 }
4494 
4495 StmtResult
ActOnSEHLeaveStmt(SourceLocation Loc,Scope * CurScope)4496 Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
4497   Scope *SEHTryParent = CurScope;
4498   while (SEHTryParent && !SEHTryParent->isSEHTryScope())
4499     SEHTryParent = SEHTryParent->getParent();
4500   if (!SEHTryParent)
4501     return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
4502   CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
4503 
4504   return new (Context) SEHLeaveStmt(Loc);
4505 }
4506 
BuildMSDependentExistsStmt(SourceLocation KeywordLoc,bool IsIfExists,NestedNameSpecifierLoc QualifierLoc,DeclarationNameInfo NameInfo,Stmt * Nested)4507 StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
4508                                             bool IsIfExists,
4509                                             NestedNameSpecifierLoc QualifierLoc,
4510                                             DeclarationNameInfo NameInfo,
4511                                             Stmt *Nested)
4512 {
4513   return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
4514                                              QualifierLoc, NameInfo,
4515                                              cast<CompoundStmt>(Nested));
4516 }
4517 
4518 
ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,bool IsIfExists,CXXScopeSpec & SS,UnqualifiedId & Name,Stmt * Nested)4519 StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
4520                                             bool IsIfExists,
4521                                             CXXScopeSpec &SS,
4522                                             UnqualifiedId &Name,
4523                                             Stmt *Nested) {
4524   return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
4525                                     SS.getWithLocInContext(Context),
4526                                     GetNameFromUnqualifiedId(Name),
4527                                     Nested);
4528 }
4529 
4530 RecordDecl*
CreateCapturedStmtRecordDecl(CapturedDecl * & CD,SourceLocation Loc,unsigned NumParams)4531 Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
4532                                    unsigned NumParams) {
4533   DeclContext *DC = CurContext;
4534   while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
4535     DC = DC->getParent();
4536 
4537   RecordDecl *RD = nullptr;
4538   if (getLangOpts().CPlusPlus)
4539     RD = CXXRecordDecl::Create(Context, TagTypeKind::Struct, DC, Loc, Loc,
4540                                /*Id=*/nullptr);
4541   else
4542     RD = RecordDecl::Create(Context, TagTypeKind::Struct, DC, Loc, Loc,
4543                             /*Id=*/nullptr);
4544 
4545   RD->setCapturedRecord();
4546   DC->addDecl(RD);
4547   RD->setImplicit();
4548   RD->startDefinition();
4549 
4550   assert(NumParams > 0 && "CapturedStmt requires context parameter");
4551   CD = CapturedDecl::Create(Context, CurContext, NumParams);
4552   DC->addDecl(CD);
4553   return RD;
4554 }
4555 
4556 static bool
buildCapturedStmtCaptureList(Sema & S,CapturedRegionScopeInfo * RSI,SmallVectorImpl<CapturedStmt::Capture> & Captures,SmallVectorImpl<Expr * > & CaptureInits)4557 buildCapturedStmtCaptureList(Sema &S, CapturedRegionScopeInfo *RSI,
4558                              SmallVectorImpl<CapturedStmt::Capture> &Captures,
4559                              SmallVectorImpl<Expr *> &CaptureInits) {
4560   for (const sema::Capture &Cap : RSI->Captures) {
4561     if (Cap.isInvalid())
4562       continue;
4563 
4564     // Form the initializer for the capture.
4565     ExprResult Init = S.BuildCaptureInit(Cap, Cap.getLocation(),
4566                                          RSI->CapRegionKind == CR_OpenMP);
4567 
4568     // FIXME: Bail out now if the capture is not used and the initializer has
4569     // no side-effects.
4570 
4571     // Create a field for this capture.
4572     FieldDecl *Field = S.BuildCaptureField(RSI->TheRecordDecl, Cap);
4573 
4574     // Add the capture to our list of captures.
4575     if (Cap.isThisCapture()) {
4576       Captures.push_back(CapturedStmt::Capture(Cap.getLocation(),
4577                                                CapturedStmt::VCK_This));
4578     } else if (Cap.isVLATypeCapture()) {
4579       Captures.push_back(
4580           CapturedStmt::Capture(Cap.getLocation(), CapturedStmt::VCK_VLAType));
4581     } else {
4582       assert(Cap.isVariableCapture() && "unknown kind of capture");
4583 
4584       if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
4585         S.OpenMP().setOpenMPCaptureKind(Field, Cap.getVariable(),
4586                                         RSI->OpenMPLevel);
4587 
4588       Captures.push_back(CapturedStmt::Capture(
4589           Cap.getLocation(),
4590           Cap.isReferenceCapture() ? CapturedStmt::VCK_ByRef
4591                                    : CapturedStmt::VCK_ByCopy,
4592           cast<VarDecl>(Cap.getVariable())));
4593     }
4594     CaptureInits.push_back(Init.get());
4595   }
4596   return false;
4597 }
4598 
4599 static std::optional<int>
isOpenMPCapturedRegionInArmSMEFunction(Sema const & S,CapturedRegionKind Kind)4600 isOpenMPCapturedRegionInArmSMEFunction(Sema const &S, CapturedRegionKind Kind) {
4601   if (!S.getLangOpts().OpenMP || Kind != CR_OpenMP)
4602     return {};
4603   if (const FunctionDecl *FD = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
4604     if (IsArmStreamingFunction(FD, /*IncludeLocallyStreaming=*/true))
4605       return /* in streaming functions */ 0;
4606     if (hasArmZAState(FD))
4607       return /* in functions with ZA state */ 1;
4608     if (hasArmZT0State(FD))
4609       return /* in fuctions with ZT0 state */ 2;
4610   }
4611   return {};
4612 }
4613 
ActOnCapturedRegionStart(SourceLocation Loc,Scope * CurScope,CapturedRegionKind Kind,unsigned NumParams)4614 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4615                                     CapturedRegionKind Kind,
4616                                     unsigned NumParams) {
4617   if (auto ErrorIndex = isOpenMPCapturedRegionInArmSMEFunction(*this, Kind))
4618     Diag(Loc, diag::err_sme_openmp_captured_region) << *ErrorIndex;
4619 
4620   CapturedDecl *CD = nullptr;
4621   RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
4622 
4623   // Build the context parameter
4624   DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4625   IdentifierInfo *ParamName = &Context.Idents.get("__context");
4626   QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
4627   auto *Param =
4628       ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4629                                 ImplicitParamKind::CapturedContext);
4630   DC->addDecl(Param);
4631 
4632   CD->setContextParam(0, Param);
4633 
4634   // Enter the capturing scope for this captured region.
4635   PushCapturedRegionScope(CurScope, CD, RD, Kind);
4636 
4637   if (CurScope)
4638     PushDeclContext(CurScope, CD);
4639   else
4640     CurContext = CD;
4641 
4642   PushExpressionEvaluationContext(
4643       ExpressionEvaluationContext::PotentiallyEvaluated);
4644   ExprEvalContexts.back().InImmediateEscalatingFunctionContext = false;
4645 }
4646 
ActOnCapturedRegionStart(SourceLocation Loc,Scope * CurScope,CapturedRegionKind Kind,ArrayRef<CapturedParamNameType> Params,unsigned OpenMPCaptureLevel)4647 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4648                                     CapturedRegionKind Kind,
4649                                     ArrayRef<CapturedParamNameType> Params,
4650                                     unsigned OpenMPCaptureLevel) {
4651   if (auto ErrorIndex = isOpenMPCapturedRegionInArmSMEFunction(*this, Kind))
4652     Diag(Loc, diag::err_sme_openmp_captured_region) << *ErrorIndex;
4653 
4654   CapturedDecl *CD = nullptr;
4655   RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
4656 
4657   // Build the context parameter
4658   DeclContext *DC = CapturedDecl::castToDeclContext(CD);
4659   bool ContextIsFound = false;
4660   unsigned ParamNum = 0;
4661   for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
4662                                                  E = Params.end();
4663        I != E; ++I, ++ParamNum) {
4664     if (I->second.isNull()) {
4665       assert(!ContextIsFound &&
4666              "null type has been found already for '__context' parameter");
4667       IdentifierInfo *ParamName = &Context.Idents.get("__context");
4668       QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD))
4669                                .withConst()
4670                                .withRestrict();
4671       auto *Param =
4672           ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4673                                     ImplicitParamKind::CapturedContext);
4674       DC->addDecl(Param);
4675       CD->setContextParam(ParamNum, Param);
4676       ContextIsFound = true;
4677     } else {
4678       IdentifierInfo *ParamName = &Context.Idents.get(I->first);
4679       auto *Param =
4680           ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second,
4681                                     ImplicitParamKind::CapturedContext);
4682       DC->addDecl(Param);
4683       CD->setParam(ParamNum, Param);
4684     }
4685   }
4686   assert(ContextIsFound && "no null type for '__context' parameter");
4687   if (!ContextIsFound) {
4688     // Add __context implicitly if it is not specified.
4689     IdentifierInfo *ParamName = &Context.Idents.get("__context");
4690     QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
4691     auto *Param =
4692         ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType,
4693                                   ImplicitParamKind::CapturedContext);
4694     DC->addDecl(Param);
4695     CD->setContextParam(ParamNum, Param);
4696   }
4697   // Enter the capturing scope for this captured region.
4698   PushCapturedRegionScope(CurScope, CD, RD, Kind, OpenMPCaptureLevel);
4699 
4700   if (CurScope)
4701     PushDeclContext(CurScope, CD);
4702   else
4703     CurContext = CD;
4704 
4705   PushExpressionEvaluationContext(
4706       ExpressionEvaluationContext::PotentiallyEvaluated);
4707 }
4708 
ActOnCapturedRegionError()4709 void Sema::ActOnCapturedRegionError() {
4710   DiscardCleanupsInEvaluationContext();
4711   PopExpressionEvaluationContext();
4712   PopDeclContext();
4713   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo();
4714   CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(ScopeRAII.get());
4715 
4716   RecordDecl *Record = RSI->TheRecordDecl;
4717   Record->setInvalidDecl();
4718 
4719   SmallVector<Decl*, 4> Fields(Record->fields());
4720   ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
4721               SourceLocation(), SourceLocation(), ParsedAttributesView());
4722 }
4723 
ActOnCapturedRegionEnd(Stmt * S)4724 StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
4725   // Leave the captured scope before we start creating captures in the
4726   // enclosing scope.
4727   DiscardCleanupsInEvaluationContext();
4728   PopExpressionEvaluationContext();
4729   PopDeclContext();
4730   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo();
4731   CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(ScopeRAII.get());
4732 
4733   SmallVector<CapturedStmt::Capture, 4> Captures;
4734   SmallVector<Expr *, 4> CaptureInits;
4735   if (buildCapturedStmtCaptureList(*this, RSI, Captures, CaptureInits))
4736     return StmtError();
4737 
4738   CapturedDecl *CD = RSI->TheCapturedDecl;
4739   RecordDecl *RD = RSI->TheRecordDecl;
4740 
4741   CapturedStmt *Res = CapturedStmt::Create(
4742       getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind),
4743       Captures, CaptureInits, CD, RD);
4744 
4745   CD->setBody(Res->getCapturedStmt());
4746   RD->completeDefinition();
4747 
4748   return Res;
4749 }
4750