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