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