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