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