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