SemaStmt.cpp revision 5140b9832b2a844ecea92c250bbe95f50d190baa
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 "Sema.h"
15#include "clang/AST/APValue.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ASTContext.h"
20#include "clang/Basic/TargetInfo.h"
21using namespace clang;
22
23Sema::OwningStmtResult Sema::ActOnExprStmt(ExprArg expr) {
24  Expr *E = static_cast<Expr*>(expr.release());
25  assert(E && "ActOnExprStmt(): missing expression");
26
27  // C99 6.8.3p2: The expression in an expression statement is evaluated as a
28  // void expression for its side effects.  Conversion to void allows any
29  // operand, even incomplete types.
30
31  // Same thing in for stmt first clause (when expr) and third clause.
32  return Owned(static_cast<Stmt*>(E));
33}
34
35
36Sema::OwningStmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc) {
37  return Owned(new (Context) NullStmt(SemiLoc));
38}
39
40Sema::OwningStmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg,
41                                           SourceLocation StartLoc,
42                                           SourceLocation EndLoc) {
43  DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
44
45  // If we have an invalid decl, just return an error.
46  if (DG.isNull()) return StmtError();
47
48  return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
49}
50
51Action::OwningStmtResult
52Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
53                        MultiStmtArg elts, bool isStmtExpr) {
54  unsigned NumElts = elts.size();
55  Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
56  // If we're in C89 mode, check that we don't have any decls after stmts.  If
57  // so, emit an extension diagnostic.
58  if (!getLangOptions().C99 && !getLangOptions().CPlusPlus) {
59    // Note that __extension__ can be around a decl.
60    unsigned i = 0;
61    // Skip over all declarations.
62    for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
63      /*empty*/;
64
65    // We found the end of the list or a statement.  Scan for another declstmt.
66    for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
67      /*empty*/;
68
69    if (i != NumElts) {
70      Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
71      Diag(D->getLocation(), diag::ext_mixed_decls_code);
72    }
73  }
74  // Warn about unused expressions in statements.
75  for (unsigned i = 0; i != NumElts; ++i) {
76    Expr *E = dyn_cast<Expr>(Elts[i]);
77    if (!E) continue;
78
79    // Warn about expressions with unused results if they are non-void and if
80    // this not the last stmt in a stmt expr.
81    if (E->getType()->isVoidType() || (isStmtExpr && i == NumElts-1))
82      continue;
83
84    SourceLocation Loc;
85    SourceRange R1, R2;
86    if (!E->isUnusedResultAWarning(Loc, R1, R2))
87      continue;
88
89    Diag(Loc, diag::warn_unused_expr) << R1 << R2;
90  }
91
92  return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
93}
94
95Action::OwningStmtResult
96Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprArg lhsval,
97                    SourceLocation DotDotDotLoc, ExprArg rhsval,
98                    SourceLocation ColonLoc) {
99  assert((lhsval.get() != 0) && "missing expression in case statement");
100
101  // C99 6.8.4.2p3: The expression shall be an integer constant.
102  // However, GCC allows any evaluatable integer expression.
103  Expr *LHSVal = static_cast<Expr*>(lhsval.get());
104  if (VerifyIntegerConstantExpression(LHSVal))
105    return StmtError();
106
107  // GCC extension: The expression shall be an integer constant.
108
109  Expr *RHSVal = static_cast<Expr*>(rhsval.get());
110  if (RHSVal && VerifyIntegerConstantExpression(RHSVal)) {
111    RHSVal = 0;  // Recover by just forgetting about it.
112    rhsval = 0;
113  }
114
115  if (SwitchStack.empty()) {
116    Diag(CaseLoc, diag::err_case_not_in_switch);
117    return StmtError();
118  }
119
120  // Only now release the smart pointers.
121  lhsval.release();
122  rhsval.release();
123  CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc);
124  SwitchStack.back()->addSwitchCase(CS);
125  return Owned(CS);
126}
127
128/// ActOnCaseStmtBody - This installs a statement as the body of a case.
129void Sema::ActOnCaseStmtBody(StmtTy *caseStmt, StmtArg subStmt) {
130  CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
131  Stmt *SubStmt = static_cast<Stmt*>(subStmt.release());
132  CS->setSubStmt(SubStmt);
133}
134
135Action::OwningStmtResult
136Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
137                       StmtArg subStmt, Scope *CurScope) {
138  Stmt *SubStmt = static_cast<Stmt*>(subStmt.release());
139
140  if (SwitchStack.empty()) {
141    Diag(DefaultLoc, diag::err_default_not_in_switch);
142    return Owned(SubStmt);
143  }
144
145  DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, SubStmt);
146  SwitchStack.back()->addSwitchCase(DS);
147  return Owned(DS);
148}
149
150Action::OwningStmtResult
151Sema::ActOnLabelStmt(SourceLocation IdentLoc, IdentifierInfo *II,
152                     SourceLocation ColonLoc, StmtArg subStmt) {
153  Stmt *SubStmt = static_cast<Stmt*>(subStmt.release());
154  // Look up the record for this label identifier.
155  LabelStmt *&LabelDecl = CurBlock ? CurBlock->LabelMap[II] : LabelMap[II];
156
157  // If not forward referenced or defined already, just create a new LabelStmt.
158  if (LabelDecl == 0)
159    return Owned(LabelDecl = new (Context) LabelStmt(IdentLoc, II, SubStmt));
160
161  assert(LabelDecl->getID() == II && "Label mismatch!");
162
163  // Otherwise, this label was either forward reference or multiply defined.  If
164  // multiply defined, reject it now.
165  if (LabelDecl->getSubStmt()) {
166    Diag(IdentLoc, diag::err_redefinition_of_label) << LabelDecl->getID();
167    Diag(LabelDecl->getIdentLoc(), diag::note_previous_definition);
168    return Owned(SubStmt);
169  }
170
171  // Otherwise, this label was forward declared, and we just found its real
172  // definition.  Fill in the forward definition and return it.
173  LabelDecl->setIdentLoc(IdentLoc);
174  LabelDecl->setSubStmt(SubStmt);
175  return Owned(LabelDecl);
176}
177
178Action::OwningStmtResult
179Sema::ActOnIfStmt(SourceLocation IfLoc, ExprArg CondVal,
180                  StmtArg ThenVal, SourceLocation ElseLoc,
181                  StmtArg ElseVal) {
182  Expr *condExpr = (Expr *)CondVal.release();
183
184  assert(condExpr && "ActOnIfStmt(): missing expression");
185
186  DefaultFunctionArrayConversion(condExpr);
187  // Take ownership again until we're past the error checking.
188  CondVal = condExpr;
189  QualType condType = condExpr->getType();
190
191  if (getLangOptions().CPlusPlus) {
192    if (CheckCXXBooleanCondition(condExpr)) // C++ 6.4p4
193      return StmtError();
194  } else if (!condType->isScalarType()) // C99 6.8.4.1p1
195    return StmtError(Diag(IfLoc, diag::err_typecheck_statement_requires_scalar)
196      << condType << condExpr->getSourceRange());
197
198  Stmt *thenStmt = (Stmt *)ThenVal.release();
199
200  // Warn if the if block has a null body without an else value.
201  // this helps prevent bugs due to typos, such as
202  // if (condition);
203  //   do_stuff();
204  if (!ElseVal.get()) {
205    if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt))
206      Diag(stmt->getSemiLoc(), diag::warn_empty_if_body);
207  }
208
209  CondVal.release();
210  return Owned(new (Context) IfStmt(IfLoc, condExpr, thenStmt,
211                                    (Stmt*)ElseVal.release()));
212}
213
214Action::OwningStmtResult
215Sema::ActOnStartOfSwitchStmt(ExprArg cond) {
216  Expr *Cond = static_cast<Expr*>(cond.release());
217
218  if (getLangOptions().CPlusPlus) {
219    // C++ 6.4.2.p2:
220    // The condition shall be of integral type, enumeration type, or of a class
221    // type for which a single conversion function to integral or enumeration
222    // type exists (12.3). If the condition is of class type, the condition is
223    // converted by calling that conversion function, and the result of the
224    // conversion is used in place of the original condition for the remainder
225    // of this section. Integral promotions are performed.
226
227    QualType Ty = Cond->getType();
228
229    // FIXME: Handle class types.
230
231    // If the type is wrong a diagnostic will be emitted later at
232    // ActOnFinishSwitchStmt.
233    if (Ty->isIntegralType() || Ty->isEnumeralType()) {
234      // Integral promotions are performed.
235      // FIXME: Integral promotions for C++ are not complete.
236      UsualUnaryConversions(Cond);
237    }
238  } else {
239    // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
240    UsualUnaryConversions(Cond);
241  }
242
243  SwitchStmt *SS = new (Context) SwitchStmt(Cond);
244  SwitchStack.push_back(SS);
245  return Owned(SS);
246}
247
248/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
249/// the specified width and sign.  If an overflow occurs, detect it and emit
250/// the specified diagnostic.
251void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
252                                              unsigned NewWidth, bool NewSign,
253                                              SourceLocation Loc,
254                                              unsigned DiagID) {
255  // Perform a conversion to the promoted condition type if needed.
256  if (NewWidth > Val.getBitWidth()) {
257    // If this is an extension, just do it.
258    llvm::APSInt OldVal(Val);
259    Val.extend(NewWidth);
260
261    // If the input was signed and negative and the output is unsigned,
262    // warn.
263    if (!NewSign && OldVal.isSigned() && OldVal.isNegative())
264      Diag(Loc, DiagID) << OldVal.toString(10) << Val.toString(10);
265
266    Val.setIsSigned(NewSign);
267  } else if (NewWidth < Val.getBitWidth()) {
268    // If this is a truncation, check for overflow.
269    llvm::APSInt ConvVal(Val);
270    ConvVal.trunc(NewWidth);
271    ConvVal.setIsSigned(NewSign);
272    ConvVal.extend(Val.getBitWidth());
273    ConvVal.setIsSigned(Val.isSigned());
274    if (ConvVal != Val)
275      Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
276
277    // Regardless of whether a diagnostic was emitted, really do the
278    // truncation.
279    Val.trunc(NewWidth);
280    Val.setIsSigned(NewSign);
281  } else if (NewSign != Val.isSigned()) {
282    // Convert the sign to match the sign of the condition.  This can cause
283    // overflow as well: unsigned(INTMIN)
284    llvm::APSInt OldVal(Val);
285    Val.setIsSigned(NewSign);
286
287    if (Val.isNegative())  // Sign bit changes meaning.
288      Diag(Loc, DiagID) << OldVal.toString(10) << Val.toString(10);
289  }
290}
291
292namespace {
293  struct CaseCompareFunctor {
294    bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
295                    const llvm::APSInt &RHS) {
296      return LHS.first < RHS;
297    }
298    bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
299                    const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
300      return LHS.first < RHS.first;
301    }
302    bool operator()(const llvm::APSInt &LHS,
303                    const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
304      return LHS < RHS.first;
305    }
306  };
307}
308
309/// CmpCaseVals - Comparison predicate for sorting case values.
310///
311static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
312                        const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
313  if (lhs.first < rhs.first)
314    return true;
315
316  if (lhs.first == rhs.first &&
317      lhs.second->getCaseLoc().getRawEncoding()
318       < rhs.second->getCaseLoc().getRawEncoding())
319    return true;
320  return false;
321}
322
323Action::OwningStmtResult
324Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, StmtArg Switch,
325                            StmtArg Body) {
326  Stmt *BodyStmt = (Stmt*)Body.release();
327
328  SwitchStmt *SS = SwitchStack.back();
329  assert(SS == (SwitchStmt*)Switch.get() && "switch stack missing push/pop!");
330
331  SS->setBody(BodyStmt, SwitchLoc);
332  SwitchStack.pop_back();
333
334  Expr *CondExpr = SS->getCond();
335  QualType CondType = CondExpr->getType();
336
337  if (!CondType->isIntegerType()) { // C99 6.8.4.2p1
338    Diag(SwitchLoc, diag::err_typecheck_statement_requires_integer)
339      << CondType << CondExpr->getSourceRange();
340    return StmtError();
341  }
342
343  // Get the bitwidth of the switched-on value before promotions.  We must
344  // convert the integer case values to this width before comparison.
345  unsigned CondWidth = static_cast<unsigned>(Context.getTypeSize(CondType));
346  bool CondIsSigned = CondType->isSignedIntegerType();
347
348  // Accumulate all of the case values in a vector so that we can sort them
349  // and detect duplicates.  This vector contains the APInt for the case after
350  // it has been converted to the condition type.
351  typedef llvm::SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
352  CaseValsTy CaseVals;
353
354  // Keep track of any GNU case ranges we see.  The APSInt is the low value.
355  std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRanges;
356
357  DefaultStmt *TheDefaultStmt = 0;
358
359  bool CaseListIsErroneous = false;
360
361  for (SwitchCase *SC = SS->getSwitchCaseList(); SC;
362       SC = SC->getNextSwitchCase()) {
363
364    if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
365      if (TheDefaultStmt) {
366        Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
367        Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
368
369        // FIXME: Remove the default statement from the switch block so that
370        // we'll return a valid AST.  This requires recursing down the
371        // AST and finding it, not something we are set up to do right now.  For
372        // now, just lop the entire switch stmt out of the AST.
373        CaseListIsErroneous = true;
374      }
375      TheDefaultStmt = DS;
376
377    } else {
378      CaseStmt *CS = cast<CaseStmt>(SC);
379
380      // We already verified that the expression has a i-c-e value (C99
381      // 6.8.4.2p3) - get that value now.
382      Expr *Lo = CS->getLHS();
383      llvm::APSInt LoVal = Lo->EvaluateAsInt(Context);
384
385      // Convert the value to the same width/sign as the condition.
386      ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
387                                         CS->getLHS()->getLocStart(),
388                                         diag::warn_case_value_overflow);
389
390      // If the LHS is not the same type as the condition, insert an implicit
391      // cast.
392      ImpCastExprToType(Lo, CondType);
393      CS->setLHS(Lo);
394
395      // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
396      if (CS->getRHS())
397        CaseRanges.push_back(std::make_pair(LoVal, CS));
398      else
399        CaseVals.push_back(std::make_pair(LoVal, CS));
400    }
401  }
402
403  // Sort all the scalar case values so we can easily detect duplicates.
404  std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
405
406  if (!CaseVals.empty()) {
407    for (unsigned i = 0, e = CaseVals.size()-1; i != e; ++i) {
408      if (CaseVals[i].first == CaseVals[i+1].first) {
409        // If we have a duplicate, report it.
410        Diag(CaseVals[i+1].second->getLHS()->getLocStart(),
411             diag::err_duplicate_case) << CaseVals[i].first.toString(10);
412        Diag(CaseVals[i].second->getLHS()->getLocStart(),
413             diag::note_duplicate_case_prev);
414        // FIXME: We really want to remove the bogus case stmt from the substmt,
415        // but we have no way to do this right now.
416        CaseListIsErroneous = true;
417      }
418    }
419  }
420
421  // Detect duplicate case ranges, which usually don't exist at all in the first
422  // place.
423  if (!CaseRanges.empty()) {
424    // Sort all the case ranges by their low value so we can easily detect
425    // overlaps between ranges.
426    std::stable_sort(CaseRanges.begin(), CaseRanges.end());
427
428    // Scan the ranges, computing the high values and removing empty ranges.
429    std::vector<llvm::APSInt> HiVals;
430    for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
431      CaseStmt *CR = CaseRanges[i].second;
432      Expr *Hi = CR->getRHS();
433      llvm::APSInt HiVal = Hi->EvaluateAsInt(Context);
434
435      // Convert the value to the same width/sign as the condition.
436      ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
437                                         CR->getRHS()->getLocStart(),
438                                         diag::warn_case_value_overflow);
439
440      // If the LHS is not the same type as the condition, insert an implicit
441      // cast.
442      ImpCastExprToType(Hi, CondType);
443      CR->setRHS(Hi);
444
445      // If the low value is bigger than the high value, the case is empty.
446      if (CaseRanges[i].first > HiVal) {
447        Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
448          << SourceRange(CR->getLHS()->getLocStart(),
449                         CR->getRHS()->getLocEnd());
450        CaseRanges.erase(CaseRanges.begin()+i);
451        --i, --e;
452        continue;
453      }
454      HiVals.push_back(HiVal);
455    }
456
457    // Rescan the ranges, looking for overlap with singleton values and other
458    // ranges.  Since the range list is sorted, we only need to compare case
459    // ranges with their neighbors.
460    for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
461      llvm::APSInt &CRLo = CaseRanges[i].first;
462      llvm::APSInt &CRHi = HiVals[i];
463      CaseStmt *CR = CaseRanges[i].second;
464
465      // Check to see whether the case range overlaps with any singleton cases.
466      CaseStmt *OverlapStmt = 0;
467      llvm::APSInt OverlapVal(32);
468
469      // Find the smallest value >= the lower bound.  If I is in the case range,
470      // then we have overlap.
471      CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
472                                                CaseVals.end(), CRLo,
473                                                CaseCompareFunctor());
474      if (I != CaseVals.end() && I->first < CRHi) {
475        OverlapVal  = I->first;   // Found overlap with scalar.
476        OverlapStmt = I->second;
477      }
478
479      // Find the smallest value bigger than the upper bound.
480      I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
481      if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
482        OverlapVal  = (I-1)->first;      // Found overlap with scalar.
483        OverlapStmt = (I-1)->second;
484      }
485
486      // Check to see if this case stmt overlaps with the subsequent case range.
487      if (i && CRLo <= HiVals[i-1]) {
488        OverlapVal  = HiVals[i-1];       // Found overlap with range.
489        OverlapStmt = CaseRanges[i-1].second;
490      }
491
492      if (OverlapStmt) {
493        // If we have a duplicate, report it.
494        Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
495          << OverlapVal.toString(10);
496        Diag(OverlapStmt->getLHS()->getLocStart(),
497             diag::note_duplicate_case_prev);
498        // FIXME: We really want to remove the bogus case stmt from the substmt,
499        // but we have no way to do this right now.
500        CaseListIsErroneous = true;
501      }
502    }
503  }
504
505  // FIXME: If the case list was broken is some way, we don't have a good system
506  // to patch it up.  Instead, just return the whole substmt as broken.
507  if (CaseListIsErroneous)
508    return StmtError();
509
510  Switch.release();
511  return Owned(SS);
512}
513
514Action::OwningStmtResult
515Sema::ActOnWhileStmt(SourceLocation WhileLoc, ExprArg Cond, StmtArg Body) {
516  Expr *condExpr = (Expr *)Cond.release();
517  assert(condExpr && "ActOnWhileStmt(): missing expression");
518
519  DefaultFunctionArrayConversion(condExpr);
520  Cond = condExpr;
521  QualType condType = condExpr->getType();
522
523  if (getLangOptions().CPlusPlus) {
524    if (CheckCXXBooleanCondition(condExpr)) // C++ 6.4p4
525      return StmtError();
526  } else if (!condType->isScalarType()) // C99 6.8.5p2
527    return StmtError(Diag(WhileLoc,
528      diag::err_typecheck_statement_requires_scalar)
529      << condType << condExpr->getSourceRange());
530
531  Cond.release();
532  return Owned(new (Context) WhileStmt(condExpr, (Stmt*)Body.release(),
533                                       WhileLoc));
534}
535
536Action::OwningStmtResult
537Sema::ActOnDoStmt(SourceLocation DoLoc, StmtArg Body,
538                  SourceLocation WhileLoc, ExprArg Cond) {
539  Expr *condExpr = (Expr *)Cond.release();
540  assert(condExpr && "ActOnDoStmt(): missing expression");
541
542  DefaultFunctionArrayConversion(condExpr);
543  Cond = condExpr;
544  QualType condType = condExpr->getType();
545
546  if (getLangOptions().CPlusPlus) {
547    if (CheckCXXBooleanCondition(condExpr)) // C++ 6.4p4
548      return StmtError();
549  } else if (!condType->isScalarType()) // C99 6.8.5p2
550    return StmtError(Diag(DoLoc, diag::err_typecheck_statement_requires_scalar)
551      << condType << condExpr->getSourceRange());
552
553  Cond.release();
554  return Owned(new (Context) DoStmt((Stmt*)Body.release(), condExpr, DoLoc));
555}
556
557Action::OwningStmtResult
558Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
559                   StmtArg first, ExprArg second, ExprArg third,
560                   SourceLocation RParenLoc, StmtArg body) {
561  Stmt *First  = static_cast<Stmt*>(first.get());
562  Expr *Second = static_cast<Expr*>(second.get());
563  Expr *Third  = static_cast<Expr*>(third.get());
564  Stmt *Body  = static_cast<Stmt*>(body.get());
565
566  if (!getLangOptions().CPlusPlus) {
567    if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
568      // C99 6.8.5p3: The declaration part of a 'for' statement shall only
569      // declare identifiers for objects having storage class 'auto' or
570      // 'register'.
571      for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
572           DI!=DE; ++DI) {
573        VarDecl *VD = dyn_cast<VarDecl>(*DI);
574        if (VD && VD->isBlockVarDecl() && !VD->hasLocalStorage())
575          VD = 0;
576        if (VD == 0)
577          Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
578        // FIXME: mark decl erroneous!
579      }
580    }
581  }
582  if (Second) {
583    DefaultFunctionArrayConversion(Second);
584    QualType SecondType = Second->getType();
585
586    if (getLangOptions().CPlusPlus) {
587      if (CheckCXXBooleanCondition(Second)) // C++ 6.4p4
588        return StmtError();
589    } else if (!SecondType->isScalarType()) // C99 6.8.5p2
590      return StmtError(Diag(ForLoc,
591                            diag::err_typecheck_statement_requires_scalar)
592        << SecondType << Second->getSourceRange());
593  }
594  first.release();
595  second.release();
596  third.release();
597  body.release();
598  return Owned(new (Context) ForStmt(First, Second, Third, Body, ForLoc));
599}
600
601Action::OwningStmtResult
602Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
603                                 SourceLocation LParenLoc,
604                                 StmtArg first, ExprArg second,
605                                 SourceLocation RParenLoc, StmtArg body) {
606  Stmt *First  = static_cast<Stmt*>(first.get());
607  Expr *Second = static_cast<Expr*>(second.get());
608  Stmt *Body  = static_cast<Stmt*>(body.get());
609  if (First) {
610    QualType FirstType;
611    if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
612      if (!DS->isSingleDecl())
613        return StmtError(Diag((*DS->decl_begin())->getLocation(),
614                         diag::err_toomany_element_decls));
615
616      Decl *D = DS->getSingleDecl();
617      FirstType = cast<ValueDecl>(D)->getType();
618      // C99 6.8.5p3: The declaration part of a 'for' statement shall only
619      // declare identifiers for objects having storage class 'auto' or
620      // 'register'.
621      VarDecl *VD = cast<VarDecl>(D);
622      if (VD->isBlockVarDecl() && !VD->hasLocalStorage())
623        return StmtError(Diag(VD->getLocation(),
624                              diag::err_non_variable_decl_in_for));
625    } else {
626      if (cast<Expr>(First)->isLvalue(Context) != Expr::LV_Valid)
627        return StmtError(Diag(First->getLocStart(),
628                   diag::err_selector_element_not_lvalue)
629          << First->getSourceRange());
630
631      FirstType = static_cast<Expr*>(First)->getType();
632    }
633    if (!Context.isObjCObjectPointerType(FirstType))
634        Diag(ForLoc, diag::err_selector_element_type)
635          << FirstType << First->getSourceRange();
636  }
637  if (Second) {
638    DefaultFunctionArrayConversion(Second);
639    QualType SecondType = Second->getType();
640    if (!Context.isObjCObjectPointerType(SecondType))
641      Diag(ForLoc, diag::err_collection_expr_type)
642        << SecondType << Second->getSourceRange();
643  }
644  first.release();
645  second.release();
646  body.release();
647  return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body,
648                                                   ForLoc, RParenLoc));
649}
650
651Action::OwningStmtResult
652Sema::ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
653                    IdentifierInfo *LabelII) {
654  // If we are in a block, reject all gotos for now.
655  if (CurBlock)
656    return StmtError(Diag(GotoLoc, diag::err_goto_in_block));
657
658  // Look up the record for this label identifier.
659  LabelStmt *&LabelDecl = CurBlock ? CurBlock->LabelMap[LabelII] :
660                                     LabelMap[LabelII];
661
662  // If we haven't seen this label yet, create a forward reference.
663  if (LabelDecl == 0)
664    LabelDecl = new (Context) LabelStmt(LabelLoc, LabelII, 0);
665
666  return Owned(new (Context) GotoStmt(LabelDecl, GotoLoc, LabelLoc));
667}
668
669Action::OwningStmtResult
670Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc,SourceLocation StarLoc,
671                            ExprArg DestExp) {
672  // Convert operand to void*
673  Expr* E = DestExp.takeAs<Expr>();
674  QualType ETy = E->getType();
675  AssignConvertType ConvTy =
676        CheckSingleAssignmentConstraints(Context.VoidPtrTy, E);
677  if (DiagnoseAssignmentResult(ConvTy, StarLoc, Context.VoidPtrTy, ETy,
678                               E, "passing"))
679    return StmtError();
680  return Owned(new (Context) IndirectGotoStmt(E));
681}
682
683Action::OwningStmtResult
684Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
685  Scope *S = CurScope->getContinueParent();
686  if (!S) {
687    // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
688    return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
689  }
690
691  return Owned(new (Context) ContinueStmt(ContinueLoc));
692}
693
694Action::OwningStmtResult
695Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
696  Scope *S = CurScope->getBreakParent();
697  if (!S) {
698    // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
699    return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
700  }
701
702  return Owned(new (Context) BreakStmt(BreakLoc));
703}
704
705/// ActOnBlockReturnStmt - Utility routine to figure out block's return type.
706///
707Action::OwningStmtResult
708Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
709
710  // If this is the first return we've seen in the block, infer the type of
711  // the block from it.
712  if (CurBlock->ReturnType == 0) {
713    if (RetValExp) {
714      // Don't call UsualUnaryConversions(), since we don't want to do
715      // integer promotions here.
716      DefaultFunctionArrayConversion(RetValExp);
717      CurBlock->ReturnType = RetValExp->getType().getTypePtr();
718    } else
719      CurBlock->ReturnType = Context.VoidTy.getTypePtr();
720  }
721  QualType FnRetType = QualType(CurBlock->ReturnType, 0);
722
723  // Otherwise, verify that this result type matches the previous one.  We are
724  // pickier with blocks than for normal functions because we don't have GCC
725  // compatibility to worry about here.
726  if (CurBlock->ReturnType->isVoidType()) {
727    if (RetValExp) {
728      Diag(ReturnLoc, diag::err_return_block_has_expr);
729      RetValExp->Destroy(Context);
730      RetValExp = 0;
731    }
732    return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
733  }
734
735  if (!RetValExp)
736    return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
737
738  if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
739    // we have a non-void block with an expression, continue checking
740    QualType RetValType = RetValExp->getType();
741
742    // C99 6.8.6.4p3(136): The return statement is not an assignment. The
743    // overlap restriction of subclause 6.5.16.1 does not apply to the case of
744    // function return.
745
746    // In C++ the return statement is handled via a copy initialization.
747    // the C version of which boils down to CheckSingleAssignmentConstraints.
748    // FIXME: Leaks RetValExp.
749    if (PerformCopyInitialization(RetValExp, FnRetType, "returning"))
750      return StmtError();
751
752    if (RetValExp) CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
753  }
754
755  return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
756}
757
758/// IsReturnCopyElidable - Whether returning @p RetExpr from a function that
759/// returns a @p RetType fulfills the criteria for copy elision (C++0x 12.8p15).
760static bool IsReturnCopyElidable(ASTContext &Ctx, QualType RetType,
761                                 Expr *RetExpr) {
762  QualType ExprType = RetExpr->getType();
763  // - in a return statement in a function with ...
764  // ... a class return type ...
765  if (!RetType->isRecordType())
766    return false;
767  // ... the same cv-unqualified type as the function return type ...
768  if (Ctx.getCanonicalType(RetType).getUnqualifiedType() !=
769      Ctx.getCanonicalType(ExprType).getUnqualifiedType())
770    return false;
771  // ... the expression is the name of a non-volatile automatic object ...
772  // We ignore parentheses here.
773  // FIXME: Is this compliant?
774  const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetExpr->IgnoreParens());
775  if (!DR)
776    return false;
777  const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
778  if (!VD)
779    return false;
780  return VD->hasLocalStorage() && !VD->getType()->isReferenceType()
781    && !VD->getType().isVolatileQualified();
782}
783
784Action::OwningStmtResult
785Sema::ActOnReturnStmt(SourceLocation ReturnLoc, ExprArg rex) {
786  Expr *RetValExp = static_cast<Expr *>(rex.release());
787  if (CurBlock)
788    return ActOnBlockReturnStmt(ReturnLoc, RetValExp);
789
790  QualType FnRetType;
791  if (FunctionDecl *FD = getCurFunctionDecl())
792    FnRetType = FD->getResultType();
793  else if (ObjCMethodDecl *MD = getCurMethodDecl())
794    FnRetType = MD->getResultType();
795  else // If we don't have a function/method context, bail.
796    return StmtError();
797
798  if (FnRetType->isVoidType()) {
799    if (RetValExp) {// C99 6.8.6.4p1 (ext_ since GCC warns)
800      unsigned D = diag::ext_return_has_expr;
801      if (RetValExp->getType()->isVoidType())
802        D = diag::ext_return_has_void_expr;
803
804      // return (some void expression); is legal in C++.
805      if (D != diag::ext_return_has_void_expr ||
806          !getLangOptions().CPlusPlus) {
807        NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
808        Diag(ReturnLoc, D)
809          << CurDecl->getDeclName() << isa<ObjCMethodDecl>(CurDecl)
810          << RetValExp->getSourceRange();
811      }
812    }
813    return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
814  }
815
816  if (!RetValExp) {
817    unsigned DiagID = diag::warn_return_missing_expr;  // C90 6.6.6.4p4
818    // C99 6.8.6.4p1 (ext_ since GCC warns)
819    if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr;
820
821    if (FunctionDecl *FD = getCurFunctionDecl())
822      Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
823    else
824      Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
825    return Owned(new (Context) ReturnStmt(ReturnLoc, (Expr*)0));
826  }
827
828  if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
829    // we have a non-void function with an expression, continue checking
830
831    // C99 6.8.6.4p3(136): The return statement is not an assignment. The
832    // overlap restriction of subclause 6.5.16.1 does not apply to the case of
833    // function return.
834
835    // C++0x 12.8p15: When certain criteria are met, an implementation is
836    //   allowed to omit the copy construction of a class object, [...]
837    //   - in a return statement in a function with a class return type, when
838    //     the expression is the name of a non-volatile automatic object with
839    //     the same cv-unqualified type as the function return type, the copy
840    //     operation can be omitted [...]
841    // C++0x 12.8p16: When the criteria for elision of a copy operation are met
842    //   and the object to be copied is designated by an lvalue, overload
843    //   resolution to select the constructor for the copy is first performed
844    //   as if the object were designated by an rvalue.
845    // Note that we only compute Elidable if we're in C++0x, since we don't
846    // care otherwise.
847    bool Elidable = getLangOptions().CPlusPlus0x ?
848                      IsReturnCopyElidable(Context, FnRetType, RetValExp) :
849                      false;
850
851    // In C++ the return statement is handled via a copy initialization.
852    // the C version of which boils down to CheckSingleAssignmentConstraints.
853    // FIXME: Leaks RetValExp on error.
854    if (PerformCopyInitialization(RetValExp, FnRetType, "returning", Elidable))
855      return StmtError();
856
857    if (RetValExp) CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
858  }
859
860  return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
861}
862
863/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
864/// ignore "noop" casts in places where an lvalue is required by an inline asm.
865/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
866/// provide a strong guidance to not use it.
867///
868/// This method checks to see if the argument is an acceptable l-value and
869/// returns false if it is a case we can handle.
870static bool CheckAsmLValue(const Expr *E, Sema &S) {
871  if (E->isLvalue(S.Context) == Expr::LV_Valid)
872    return false;  // Cool, this is an lvalue.
873
874  // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
875  // are supposed to allow.
876  const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
877  if (E != E2 && E2->isLvalue(S.Context) == Expr::LV_Valid) {
878    if (!S.getLangOptions().HeinousExtensions)
879      S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
880        << E->getSourceRange();
881    else
882      S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
883        << E->getSourceRange();
884    // Accept, even if we emitted an error diagnostic.
885    return false;
886  }
887
888  // None of the above, just randomly invalid non-lvalue.
889  return true;
890}
891
892
893Sema::OwningStmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc,
894                                          bool IsSimple,
895                                          bool IsVolatile,
896                                          unsigned NumOutputs,
897                                          unsigned NumInputs,
898                                          std::string *Names,
899                                          MultiExprArg constraints,
900                                          MultiExprArg exprs,
901                                          ExprArg asmString,
902                                          MultiExprArg clobbers,
903                                          SourceLocation RParenLoc) {
904  unsigned NumClobbers = clobbers.size();
905  StringLiteral **Constraints =
906    reinterpret_cast<StringLiteral**>(constraints.get());
907  Expr **Exprs = reinterpret_cast<Expr **>(exprs.get());
908  StringLiteral *AsmString = cast<StringLiteral>((Expr *)asmString.get());
909  StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
910
911  llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
912
913  // The parser verifies that there is a string literal here.
914  if (AsmString->isWide())
915    return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
916      << AsmString->getSourceRange());
917
918
919  for (unsigned i = 0; i != NumOutputs; i++) {
920    StringLiteral *Literal = Constraints[i];
921    if (Literal->isWide())
922      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
923        << Literal->getSourceRange());
924
925    std::string OutputConstraint(Literal->getStrData(),
926                                 Literal->getByteLength());
927
928    TargetInfo::ConstraintInfo info;
929    if (!Context.Target.validateOutputConstraint(OutputConstraint.c_str(),info))
930      return StmtError(Diag(Literal->getLocStart(),
931                  diag::err_asm_invalid_output_constraint) << OutputConstraint);
932
933    // Check that the output exprs are valid lvalues.
934    ParenExpr *OutputExpr = cast<ParenExpr>(Exprs[i]);
935    if (CheckAsmLValue(OutputExpr, *this)) {
936      return StmtError(Diag(OutputExpr->getSubExpr()->getLocStart(),
937                  diag::err_asm_invalid_lvalue_in_output)
938        << OutputExpr->getSubExpr()->getSourceRange());
939    }
940
941    OutputConstraintInfos.push_back(info);
942  }
943
944  for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
945    StringLiteral *Literal = Constraints[i];
946    if (Literal->isWide())
947      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
948        << Literal->getSourceRange());
949
950    std::string InputConstraint(Literal->getStrData(),
951                                Literal->getByteLength());
952
953    TargetInfo::ConstraintInfo info;
954    if (!Context.Target.validateInputConstraint(InputConstraint.c_str(),
955                                                &Names[0],
956                                                &Names[0] + NumOutputs,
957                                                &OutputConstraintInfos[0],
958                                                info)) {
959      return StmtError(Diag(Literal->getLocStart(),
960                  diag::err_asm_invalid_input_constraint) << InputConstraint);
961    }
962
963    ParenExpr *InputExpr = cast<ParenExpr>(Exprs[i]);
964
965    // Only allow void types for memory constraints.
966    if ((info & TargetInfo::CI_AllowsMemory)
967        && !(info & TargetInfo::CI_AllowsRegister)) {
968      if (CheckAsmLValue(InputExpr, *this))
969        return StmtError(Diag(InputExpr->getSubExpr()->getLocStart(),
970                              diag::err_asm_invalid_lvalue_in_input)
971          << InputConstraint << InputExpr->getSubExpr()->getSourceRange());
972    }
973
974    if (info & TargetInfo::CI_AllowsRegister) {
975      if (InputExpr->getType()->isVoidType()) {
976        return StmtError(Diag(InputExpr->getSubExpr()->getLocStart(),
977                              diag::err_asm_invalid_type_in_input)
978          << InputExpr->getType() << InputConstraint
979          << InputExpr->getSubExpr()->getSourceRange());
980      }
981    }
982
983    DefaultFunctionArrayConversion(Exprs[i]);
984  }
985
986  // Check that the clobbers are valid.
987  for (unsigned i = 0; i != NumClobbers; i++) {
988    StringLiteral *Literal = Clobbers[i];
989    if (Literal->isWide())
990      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
991        << Literal->getSourceRange());
992
993    llvm::SmallString<16> Clobber(Literal->getStrData(),
994                                  Literal->getStrData() +
995                                  Literal->getByteLength());
996
997    if (!Context.Target.isValidGCCRegisterName(Clobber.c_str()))
998      return StmtError(Diag(Literal->getLocStart(),
999                  diag::err_asm_unknown_register_name) << Clobber.c_str());
1000  }
1001
1002  constraints.release();
1003  exprs.release();
1004  asmString.release();
1005  clobbers.release();
1006  AsmStmt *NS =
1007    new (Context) AsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs, NumInputs,
1008                          Names, Constraints, Exprs, AsmString, NumClobbers,
1009                          Clobbers, RParenLoc);
1010  // Validate the asm string, ensuring it makes sense given the operands we
1011  // have.
1012  llvm::SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
1013  unsigned DiagOffs;
1014  if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
1015    Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
1016           << AsmString->getSourceRange();
1017    DeleteStmt(NS);
1018    return StmtError();
1019  }
1020
1021
1022  return Owned(NS);
1023}
1024
1025Action::OwningStmtResult
1026Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
1027                           SourceLocation RParen, DeclPtrTy Parm,
1028                           StmtArg Body, StmtArg catchList) {
1029  Stmt *CatchList = static_cast<Stmt*>(catchList.release());
1030  ParmVarDecl *PVD = cast_or_null<ParmVarDecl>(Parm.getAs<Decl>());
1031
1032  // PVD == 0 implies @catch(...).
1033  if (PVD) {
1034    if (!Context.isObjCObjectPointerType(PVD->getType()))
1035      return StmtError(Diag(PVD->getLocation(),
1036                       diag::err_catch_param_not_objc_type));
1037    if (PVD->getType()->isObjCQualifiedIdType())
1038      return StmtError(Diag(PVD->getLocation(),
1039                       diag::err_illegal_qualifiers_on_catch_parm));
1040  }
1041
1042  ObjCAtCatchStmt *CS = new (Context) ObjCAtCatchStmt(AtLoc, RParen,
1043    PVD, static_cast<Stmt*>(Body.release()), CatchList);
1044  return Owned(CatchList ? CatchList : CS);
1045}
1046
1047Action::OwningStmtResult
1048Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, StmtArg Body) {
1049  return Owned(new (Context) ObjCAtFinallyStmt(AtLoc,
1050                                           static_cast<Stmt*>(Body.release())));
1051}
1052
1053Action::OwningStmtResult
1054Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc,
1055                         StmtArg Try, StmtArg Catch, StmtArg Finally) {
1056  return Owned(new (Context) ObjCAtTryStmt(AtLoc,
1057                                        static_cast<Stmt*>(Try.release()),
1058                                        static_cast<Stmt*>(Catch.release()),
1059                                        static_cast<Stmt*>(Finally.release())));
1060}
1061
1062Action::OwningStmtResult
1063Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, ExprArg expr,Scope *CurScope) {
1064  Expr *ThrowExpr = static_cast<Expr*>(expr.release());
1065  if (!ThrowExpr) {
1066    // @throw without an expression designates a rethrow (which much occur
1067    // in the context of an @catch clause).
1068    Scope *AtCatchParent = CurScope;
1069    while (AtCatchParent && !AtCatchParent->isAtCatchScope())
1070      AtCatchParent = AtCatchParent->getParent();
1071    if (!AtCatchParent)
1072      return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
1073  } else {
1074    QualType ThrowType = ThrowExpr->getType();
1075    // Make sure the expression type is an ObjC pointer or "void *".
1076    if (!Context.isObjCObjectPointerType(ThrowType)) {
1077      const PointerType *PT = ThrowType->getAsPointerType();
1078      if (!PT || !PT->getPointeeType()->isVoidType())
1079        return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
1080                        << ThrowExpr->getType() << ThrowExpr->getSourceRange());
1081    }
1082  }
1083  return Owned(new (Context) ObjCAtThrowStmt(AtLoc, ThrowExpr));
1084}
1085
1086Action::OwningStmtResult
1087Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, ExprArg SynchExpr,
1088                                  StmtArg SynchBody) {
1089  return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc,
1090                     static_cast<Stmt*>(SynchExpr.release()),
1091                     static_cast<Stmt*>(SynchBody.release())));
1092}
1093
1094/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
1095/// and creates a proper catch handler from them.
1096Action::OwningStmtResult
1097Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, DeclPtrTy ExDecl,
1098                         StmtArg HandlerBlock) {
1099  // There's nothing to test that ActOnExceptionDecl didn't already test.
1100  return Owned(new (Context) CXXCatchStmt(CatchLoc,
1101                                  cast_or_null<VarDecl>(ExDecl.getAs<Decl>()),
1102                                  static_cast<Stmt*>(HandlerBlock.release())));
1103}
1104
1105/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
1106/// handlers and creates a try statement from them.
1107Action::OwningStmtResult
1108Sema::ActOnCXXTryBlock(SourceLocation TryLoc, StmtArg TryBlock,
1109                       MultiStmtArg RawHandlers) {
1110  unsigned NumHandlers = RawHandlers.size();
1111  assert(NumHandlers > 0 &&
1112         "The parser shouldn't call this if there are no handlers.");
1113  Stmt **Handlers = reinterpret_cast<Stmt**>(RawHandlers.get());
1114
1115  for(unsigned i = 0; i < NumHandlers - 1; ++i) {
1116    CXXCatchStmt *Handler = llvm::cast<CXXCatchStmt>(Handlers[i]);
1117    if (!Handler->getExceptionDecl())
1118      return StmtError(Diag(Handler->getLocStart(), diag::err_early_catch_all));
1119  }
1120  // FIXME: We should detect handlers for the same type as an earlier one.
1121  // This one is rather easy.
1122  // FIXME: We should detect handlers that cannot catch anything because an
1123  // earlier handler catches a superclass. Need to find a method that is not
1124  // quadratic for this.
1125  // Neither of these are explicitly forbidden, but every compiler detects them
1126  // and warns.
1127
1128  RawHandlers.release();
1129  return Owned(new (Context) CXXTryStmt(TryLoc,
1130                                        static_cast<Stmt*>(TryBlock.release()),
1131                                        Handlers, NumHandlers));
1132}
1133