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