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