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