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