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