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