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