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