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