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