SemaStmt.cpp revision 64789f8496d9bd3ff5ba3686feca0de1a25d5a32
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/ASTContext.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/Expr.h"
18#include "clang/AST/Stmt.h"
19#include "clang/Parse/Scope.h"
20#include "clang/Basic/TargetInfo.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Basic/LangOptions.h"
23#include "llvm/ADT/SmallString.h"
24using namespace clang;
25
26Sema::StmtResult Sema::ActOnExprStmt(ExprTy *expr) {
27  Expr *E = static_cast<Expr*>(expr);
28  assert(E && "ActOnExprStmt(): missing expression");
29
30  // C99 6.8.3p2: The expression in an expression statement is evaluated as a
31  // void expression for its side effects.  Conversion to void allows any
32  // operand, even incomplete types.
33
34  // Same thing in for stmt first clause (when expr) and third clause.
35  return E;
36}
37
38
39Sema::StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc) {
40  return new NullStmt(SemiLoc);
41}
42
43Sema::StmtResult Sema::ActOnDeclStmt(DeclTy *decl, SourceLocation StartLoc,
44                                     SourceLocation EndLoc) {
45  if (decl == 0)
46    return true;
47
48  ScopedDecl *SD = cast<ScopedDecl>(static_cast<Decl *>(decl));
49  return new DeclStmt(SD, StartLoc, EndLoc);
50}
51
52Action::StmtResult
53Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
54                        StmtTy **elts, unsigned NumElts, bool isStmtExpr) {
55  Stmt **Elts = reinterpret_cast<Stmt**>(elts);
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      ScopedDecl *D = cast<DeclStmt>(Elts[i])->getDecl();
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.
80    if (E->hasLocalSideEffect() || E->getType()->isVoidType())
81      continue;
82
83    // The last expr in a stmt expr really is used.
84    if (isStmtExpr && i == NumElts-1)
85      continue;
86
87    /// DiagnoseDeadExpr - This expression is side-effect free and evaluated in
88    /// a context where the result is unused.  Emit a diagnostic to warn about
89    /// this.
90    if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
91      Diag(BO->getOperatorLoc(), diag::warn_unused_expr,
92           BO->getLHS()->getSourceRange(), BO->getRHS()->getSourceRange());
93    else if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
94      Diag(UO->getOperatorLoc(), diag::warn_unused_expr,
95           UO->getSubExpr()->getSourceRange());
96    else
97      Diag(E->getExprLoc(), diag::warn_unused_expr, E->getSourceRange());
98  }
99
100  return new CompoundStmt(Elts, NumElts, L, R);
101}
102
103Action::StmtResult
104Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprTy *lhsval,
105                    SourceLocation DotDotDotLoc, ExprTy *rhsval,
106                    SourceLocation ColonLoc, StmtTy *subStmt) {
107  Stmt *SubStmt = static_cast<Stmt*>(subStmt);
108  Expr *LHSVal = ((Expr *)lhsval), *RHSVal = ((Expr *)rhsval);
109  assert((LHSVal != 0) && "missing expression in case statement");
110
111  SourceLocation ExpLoc;
112  // C99 6.8.4.2p3: The expression shall be an integer constant.
113  if (!LHSVal->isIntegerConstantExpr(Context, &ExpLoc)) {
114    Diag(ExpLoc, diag::err_case_label_not_integer_constant_expr,
115         LHSVal->getSourceRange());
116    return SubStmt;
117  }
118
119  // GCC extension: The expression shall be an integer constant.
120  if (RHSVal && !RHSVal->isIntegerConstantExpr(Context, &ExpLoc)) {
121    Diag(ExpLoc, diag::err_case_label_not_integer_constant_expr,
122         RHSVal->getSourceRange());
123    RHSVal = 0;  // Recover by just forgetting about it.
124  }
125
126  if (SwitchStack.empty()) {
127    Diag(CaseLoc, diag::err_case_not_in_switch);
128    return SubStmt;
129  }
130
131  CaseStmt *CS = new CaseStmt(LHSVal, RHSVal, SubStmt, CaseLoc);
132  SwitchStack.back()->addSwitchCase(CS);
133  return CS;
134}
135
136Action::StmtResult
137Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
138                       StmtTy *subStmt, Scope *CurScope) {
139  Stmt *SubStmt = static_cast<Stmt*>(subStmt);
140
141  if (SwitchStack.empty()) {
142    Diag(DefaultLoc, diag::err_default_not_in_switch);
143    return SubStmt;
144  }
145
146  DefaultStmt *DS = new DefaultStmt(DefaultLoc, SubStmt);
147  SwitchStack.back()->addSwitchCase(DS);
148
149  return DS;
150}
151
152Action::StmtResult
153Sema::ActOnLabelStmt(SourceLocation IdentLoc, IdentifierInfo *II,
154                     SourceLocation ColonLoc, StmtTy *subStmt) {
155  Stmt *SubStmt = static_cast<Stmt*>(subStmt);
156  // Look up the record for this label identifier.
157  LabelStmt *&LabelDecl = LabelMap[II];
158
159  // If not forward referenced or defined already, just create a new LabelStmt.
160  if (LabelDecl == 0)
161    return LabelDecl = new LabelStmt(IdentLoc, II, SubStmt);
162
163  assert(LabelDecl->getID() == II && "Label mismatch!");
164
165  // Otherwise, this label was either forward reference or multiply defined.  If
166  // multiply defined, reject it now.
167  if (LabelDecl->getSubStmt()) {
168    Diag(IdentLoc, diag::err_redefinition_of_label, LabelDecl->getName());
169    Diag(LabelDecl->getIdentLoc(), diag::err_previous_definition);
170    return SubStmt;
171  }
172
173  // Otherwise, this label was forward declared, and we just found its real
174  // definition.  Fill in the forward definition and return it.
175  LabelDecl->setIdentLoc(IdentLoc);
176  LabelDecl->setSubStmt(SubStmt);
177  return LabelDecl;
178}
179
180Action::StmtResult
181Sema::ActOnIfStmt(SourceLocation IfLoc, ExprTy *CondVal,
182                  StmtTy *ThenVal, SourceLocation ElseLoc,
183                  StmtTy *ElseVal) {
184  Expr *condExpr = (Expr *)CondVal;
185  Stmt *thenStmt = (Stmt *)ThenVal;
186
187  assert(condExpr && "ActOnIfStmt(): missing expression");
188
189  DefaultFunctionArrayConversion(condExpr);
190  QualType condType = condExpr->getType();
191
192  if (!condType->isScalarType()) // C99 6.8.4.1p1
193    return Diag(IfLoc, diag::err_typecheck_statement_requires_scalar,
194             condType.getAsString(), condExpr->getSourceRange());
195
196  // Warn if the if block has a null body without an else value.
197  // this helps prevent bugs due to typos, such as
198  // if (condition);
199  //   do_stuff();
200  if (!ElseVal) {
201    if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt))
202      Diag(stmt->getSemiLoc(), diag::warn_empty_if_body);
203  }
204
205  return new IfStmt(IfLoc, condExpr, thenStmt, (Stmt*)ElseVal);
206}
207
208Action::StmtResult
209Sema::ActOnStartOfSwitchStmt(ExprTy *cond) {
210  Expr *Cond = static_cast<Expr*>(cond);
211
212  // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
213  UsualUnaryConversions(Cond);
214
215  SwitchStmt *SS = new SwitchStmt(Cond);
216  SwitchStack.push_back(SS);
217  return SS;
218}
219
220/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
221/// the specified width and sign.  If an overflow occurs, detect it and emit
222/// the specified diagnostic.
223void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
224                                              unsigned NewWidth, bool NewSign,
225                                              SourceLocation Loc,
226                                              unsigned DiagID) {
227  // Perform a conversion to the promoted condition type if needed.
228  if (NewWidth > Val.getBitWidth()) {
229    // If this is an extension, just do it.
230    llvm::APSInt OldVal(Val);
231    Val.extend(NewWidth);
232
233    // If the input was signed and negative and the output is unsigned,
234    // warn.
235    if (!NewSign && OldVal.isSigned() && OldVal.isNegative())
236      Diag(Loc, DiagID, OldVal.toString(), Val.toString());
237
238    Val.setIsSigned(NewSign);
239  } else if (NewWidth < Val.getBitWidth()) {
240    // If this is a truncation, check for overflow.
241    llvm::APSInt ConvVal(Val);
242    ConvVal.trunc(NewWidth);
243    ConvVal.setIsSigned(NewSign);
244    ConvVal.extend(Val.getBitWidth());
245    ConvVal.setIsSigned(Val.isSigned());
246    if (ConvVal != Val)
247      Diag(Loc, DiagID, Val.toString(), ConvVal.toString());
248
249    // Regardless of whether a diagnostic was emitted, really do the
250    // truncation.
251    Val.trunc(NewWidth);
252    Val.setIsSigned(NewSign);
253  } else if (NewSign != Val.isSigned()) {
254    // Convert the sign to match the sign of the condition.  This can cause
255    // overflow as well: unsigned(INTMIN)
256    llvm::APSInt OldVal(Val);
257    Val.setIsSigned(NewSign);
258
259    if (Val.isNegative())  // Sign bit changes meaning.
260      Diag(Loc, DiagID, OldVal.toString(), Val.toString());
261  }
262}
263
264namespace {
265  struct CaseCompareFunctor {
266    bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
267                    const llvm::APSInt &RHS) {
268      return LHS.first < RHS;
269    }
270    bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
271                    const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
272      return LHS.first < RHS.first;
273    }
274    bool operator()(const llvm::APSInt &LHS,
275                    const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
276      return LHS < RHS.first;
277    }
278  };
279}
280
281/// CmpCaseVals - Comparison predicate for sorting case values.
282///
283static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
284                        const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
285  if (lhs.first < rhs.first)
286    return true;
287
288  if (lhs.first == rhs.first &&
289      lhs.second->getCaseLoc().getRawEncoding()
290       < rhs.second->getCaseLoc().getRawEncoding())
291    return true;
292  return false;
293}
294
295Action::StmtResult
296Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, StmtTy *Switch,
297                            ExprTy *Body) {
298  Stmt *BodyStmt = (Stmt*)Body;
299
300  SwitchStmt *SS = SwitchStack.back();
301  assert(SS == (SwitchStmt*)Switch && "switch stack missing push/pop!");
302
303  SS->setBody(BodyStmt, SwitchLoc);
304  SwitchStack.pop_back();
305
306  Expr *CondExpr = SS->getCond();
307  QualType CondType = CondExpr->getType();
308
309  if (!CondType->isIntegerType()) { // C99 6.8.4.2p1
310    Diag(SwitchLoc, diag::err_typecheck_statement_requires_integer,
311         CondType.getAsString(), CondExpr->getSourceRange());
312    return true;
313  }
314
315  // Get the bitwidth of the switched-on value before promotions.  We must
316  // convert the integer case values to this width before comparison.
317  unsigned CondWidth = static_cast<unsigned>(Context.getTypeSize(CondType));
318  bool CondIsSigned = CondType->isSignedIntegerType();
319
320  // Accumulate all of the case values in a vector so that we can sort them
321  // and detect duplicates.  This vector contains the APInt for the case after
322  // it has been converted to the condition type.
323  typedef llvm::SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
324  CaseValsTy CaseVals;
325
326  // Keep track of any GNU case ranges we see.  The APSInt is the low value.
327  std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRanges;
328
329  DefaultStmt *TheDefaultStmt = 0;
330
331  bool CaseListIsErroneous = false;
332
333  for (SwitchCase *SC = SS->getSwitchCaseList(); SC;
334       SC = SC->getNextSwitchCase()) {
335
336    if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
337      if (TheDefaultStmt) {
338        Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
339        Diag(TheDefaultStmt->getDefaultLoc(), diag::err_first_label);
340
341        // FIXME: Remove the default statement from the switch block so that
342        // we'll return a valid AST.  This requires recursing down the
343        // AST and finding it, not something we are set up to do right now.  For
344        // now, just lop the entire switch stmt out of the AST.
345        CaseListIsErroneous = true;
346      }
347      TheDefaultStmt = DS;
348
349    } else {
350      CaseStmt *CS = cast<CaseStmt>(SC);
351
352      // We already verified that the expression has a i-c-e value (C99
353      // 6.8.4.2p3) - get that value now.
354      llvm::APSInt LoVal(32);
355      Expr *Lo = CS->getLHS();
356      Lo->isIntegerConstantExpr(LoVal, Context);
357
358      // Convert the value to the same width/sign as the condition.
359      ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
360                                         CS->getLHS()->getLocStart(),
361                                         diag::warn_case_value_overflow);
362
363      // If the LHS is not the same type as the condition, insert an implicit
364      // cast.
365      ImpCastExprToType(Lo, CondType);
366      CS->setLHS(Lo);
367
368      // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
369      if (CS->getRHS())
370        CaseRanges.push_back(std::make_pair(LoVal, CS));
371      else
372        CaseVals.push_back(std::make_pair(LoVal, CS));
373    }
374  }
375
376  // Sort all the scalar case values so we can easily detect duplicates.
377  std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
378
379  if (!CaseVals.empty()) {
380    for (unsigned i = 0, e = CaseVals.size()-1; i != e; ++i) {
381      if (CaseVals[i].first == CaseVals[i+1].first) {
382        // If we have a duplicate, report it.
383        Diag(CaseVals[i+1].second->getLHS()->getLocStart(),
384             diag::err_duplicate_case, CaseVals[i].first.toString());
385        Diag(CaseVals[i].second->getLHS()->getLocStart(),
386             diag::err_duplicate_case_prev);
387        // FIXME: We really want to remove the bogus case stmt from the substmt,
388        // but we have no way to do this right now.
389        CaseListIsErroneous = true;
390      }
391    }
392  }
393
394  // Detect duplicate case ranges, which usually don't exist at all in the first
395  // place.
396  if (!CaseRanges.empty()) {
397    // Sort all the case ranges by their low value so we can easily detect
398    // overlaps between ranges.
399    std::stable_sort(CaseRanges.begin(), CaseRanges.end());
400
401    // Scan the ranges, computing the high values and removing empty ranges.
402    std::vector<llvm::APSInt> HiVals;
403    for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
404      CaseStmt *CR = CaseRanges[i].second;
405      llvm::APSInt HiVal(32);
406      Expr *Hi = CR->getRHS();
407      Hi->isIntegerConstantExpr(HiVal, Context);
408
409      // Convert the value to the same width/sign as the condition.
410      ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
411                                         CR->getRHS()->getLocStart(),
412                                         diag::warn_case_value_overflow);
413
414      // If the LHS is not the same type as the condition, insert an implicit
415      // cast.
416      ImpCastExprToType(Hi, CondType);
417      CR->setRHS(Hi);
418
419      // If the low value is bigger than the high value, the case is empty.
420      if (CaseRanges[i].first > HiVal) {
421        Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range,
422             SourceRange(CR->getLHS()->getLocStart(),
423                         CR->getRHS()->getLocEnd()));
424        CaseRanges.erase(CaseRanges.begin()+i);
425        --i, --e;
426        continue;
427      }
428      HiVals.push_back(HiVal);
429    }
430
431    // Rescan the ranges, looking for overlap with singleton values and other
432    // ranges.  Since the range list is sorted, we only need to compare case
433    // ranges with their neighbors.
434    for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
435      llvm::APSInt &CRLo = CaseRanges[i].first;
436      llvm::APSInt &CRHi = HiVals[i];
437      CaseStmt *CR = CaseRanges[i].second;
438
439      // Check to see whether the case range overlaps with any singleton cases.
440      CaseStmt *OverlapStmt = 0;
441      llvm::APSInt OverlapVal(32);
442
443      // Find the smallest value >= the lower bound.  If I is in the case range,
444      // then we have overlap.
445      CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
446                                                CaseVals.end(), CRLo,
447                                                CaseCompareFunctor());
448      if (I != CaseVals.end() && I->first < CRHi) {
449        OverlapVal  = I->first;   // Found overlap with scalar.
450        OverlapStmt = I->second;
451      }
452
453      // Find the smallest value bigger than the upper bound.
454      I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
455      if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
456        OverlapVal  = (I-1)->first;      // Found overlap with scalar.
457        OverlapStmt = (I-1)->second;
458      }
459
460      // Check to see if this case stmt overlaps with the subsequent case range.
461      if (i && CRLo <= HiVals[i-1]) {
462        OverlapVal  = HiVals[i-1];       // Found overlap with range.
463        OverlapStmt = CaseRanges[i-1].second;
464      }
465
466      if (OverlapStmt) {
467        // If we have a duplicate, report it.
468        Diag(CR->getLHS()->getLocStart(),
469             diag::err_duplicate_case, OverlapVal.toString());
470        Diag(OverlapStmt->getLHS()->getLocStart(),
471             diag::err_duplicate_case_prev);
472        // FIXME: We really want to remove the bogus case stmt from the substmt,
473        // but we have no way to do this right now.
474        CaseListIsErroneous = true;
475      }
476    }
477  }
478
479  // FIXME: If the case list was broken is some way, we don't have a good system
480  // to patch it up.  Instead, just return the whole substmt as broken.
481  if (CaseListIsErroneous)
482    return true;
483
484  return SS;
485}
486
487Action::StmtResult
488Sema::ActOnWhileStmt(SourceLocation WhileLoc, ExprTy *Cond, StmtTy *Body) {
489  Expr *condExpr = (Expr *)Cond;
490  assert(condExpr && "ActOnWhileStmt(): missing expression");
491
492  DefaultFunctionArrayConversion(condExpr);
493  QualType condType = condExpr->getType();
494
495  if (!condType->isScalarType()) // C99 6.8.5p2
496    return Diag(WhileLoc, diag::err_typecheck_statement_requires_scalar,
497             condType.getAsString(), condExpr->getSourceRange());
498
499  return new WhileStmt(condExpr, (Stmt*)Body, WhileLoc);
500}
501
502Action::StmtResult
503Sema::ActOnDoStmt(SourceLocation DoLoc, StmtTy *Body,
504                  SourceLocation WhileLoc, ExprTy *Cond) {
505  Expr *condExpr = (Expr *)Cond;
506  assert(condExpr && "ActOnDoStmt(): missing expression");
507
508  DefaultFunctionArrayConversion(condExpr);
509  QualType condType = condExpr->getType();
510
511  if (!condType->isScalarType()) // C99 6.8.5p2
512    return Diag(DoLoc, diag::err_typecheck_statement_requires_scalar,
513             condType.getAsString(), condExpr->getSourceRange());
514
515  return new DoStmt((Stmt*)Body, condExpr, DoLoc);
516}
517
518Action::StmtResult
519Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
520                   StmtTy *first, ExprTy *second, ExprTy *third,
521                   SourceLocation RParenLoc, StmtTy *body) {
522  Stmt *First  = static_cast<Stmt*>(first);
523  Expr *Second = static_cast<Expr*>(second);
524  Expr *Third  = static_cast<Expr*>(third);
525  Stmt *Body  = static_cast<Stmt*>(body);
526
527  if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
528    // C99 6.8.5p3: The declaration part of a 'for' statement shall only declare
529    // identifiers for objects having storage class 'auto' or 'register'.
530    for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
531         DI!=DE; ++DI) {
532      VarDecl *VD = dyn_cast<VarDecl>(*DI);
533      if (VD && VD->isBlockVarDecl() && !VD->hasLocalStorage())
534        VD = 0;
535      if (VD == 0)
536        Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
537      // FIXME: mark decl erroneous!
538    }
539  }
540  if (Second) {
541    DefaultFunctionArrayConversion(Second);
542    QualType SecondType = Second->getType();
543
544    if (!SecondType->isScalarType()) // C99 6.8.5p2
545      return Diag(ForLoc, diag::err_typecheck_statement_requires_scalar,
546                  SecondType.getAsString(), Second->getSourceRange());
547  }
548  return new ForStmt(First, Second, Third, Body, ForLoc);
549}
550
551Action::StmtResult
552Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
553                                 SourceLocation LParenLoc,
554                                 StmtTy *first, ExprTy *second,
555                                 SourceLocation RParenLoc, StmtTy *body) {
556  Stmt *First  = static_cast<Stmt*>(first);
557  Expr *Second = static_cast<Expr*>(second);
558  Stmt *Body  = static_cast<Stmt*>(body);
559  if (First) {
560    QualType FirstType;
561    if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
562      FirstType = cast<ValueDecl>(DS->getDecl())->getType();
563      // C99 6.8.5p3: The declaration part of a 'for' statement shall only declare
564      // identifiers for objects having storage class 'auto' or 'register'.
565      ScopedDecl *D = DS->getDecl();
566      VarDecl *VD = cast<VarDecl>(D);
567      if (VD->isBlockVarDecl() && !VD->hasLocalStorage())
568        return Diag(VD->getLocation(), diag::err_non_variable_decl_in_for);
569      if (D->getNextDeclarator())
570        return Diag(D->getLocation(), diag::err_toomany_element_decls);
571    } else
572      FirstType = static_cast<Expr*>(first)->getType();
573    if (!Context.isObjCObjectPointerType(FirstType))
574        Diag(ForLoc, diag::err_selector_element_type,
575             FirstType.getAsString(), First->getSourceRange());
576  }
577  if (Second) {
578    DefaultFunctionArrayConversion(Second);
579    QualType SecondType = Second->getType();
580    if (!Context.isObjCObjectPointerType(SecondType))
581      Diag(ForLoc, diag::err_collection_expr_type,
582           SecondType.getAsString(), Second->getSourceRange());
583  }
584  return new ObjCForCollectionStmt(First, Second, Body, ForLoc, RParenLoc);
585}
586
587Action::StmtResult
588Sema::ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
589                    IdentifierInfo *LabelII) {
590  // Look up the record for this label identifier.
591  LabelStmt *&LabelDecl = LabelMap[LabelII];
592
593  // If we haven't seen this label yet, create a forward reference.
594  if (LabelDecl == 0)
595    LabelDecl = new LabelStmt(LabelLoc, LabelII, 0);
596
597  return new GotoStmt(LabelDecl, GotoLoc, LabelLoc);
598}
599
600Action::StmtResult
601Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc,SourceLocation StarLoc,
602                            ExprTy *DestExp) {
603  // FIXME: Verify that the operand is convertible to void*.
604
605  return new IndirectGotoStmt((Expr*)DestExp);
606}
607
608Action::StmtResult
609Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
610  Scope *S = CurScope->getContinueParent();
611  if (!S) {
612    // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
613    Diag(ContinueLoc, diag::err_continue_not_in_loop);
614    return true;
615  }
616
617  return new ContinueStmt(ContinueLoc);
618}
619
620Action::StmtResult
621Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
622  Scope *S = CurScope->getBreakParent();
623  if (!S) {
624    // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
625    Diag(BreakLoc, diag::err_break_not_in_loop_or_switch);
626    return true;
627  }
628
629  return new BreakStmt(BreakLoc);
630}
631
632
633Action::StmtResult
634Sema::ActOnReturnStmt(SourceLocation ReturnLoc, ExprTy *rex) {
635  Expr *RetValExp = static_cast<Expr *>(rex);
636  QualType FnRetType =
637        getCurFunctionDecl() ? getCurFunctionDecl()->getResultType() :
638                               getCurMethodDecl()->getResultType();
639
640  if (FnRetType->isVoidType()) {
641    if (RetValExp) // C99 6.8.6.4p1 (ext_ since GCC warns)
642      Diag(ReturnLoc, diag::ext_return_has_expr,
643           ( getCurFunctionDecl() ?
644                getCurFunctionDecl()->getIdentifier()->getName() :
645                getCurMethodDecl()->getSelector().getName()       ),
646           RetValExp->getSourceRange());
647    return new ReturnStmt(ReturnLoc, RetValExp);
648  } else {
649    if (!RetValExp) {
650      const char *funcName =
651                getCurFunctionDecl() ?
652                   getCurFunctionDecl()->getIdentifier()->getName() :
653                   getCurMethodDecl()->getSelector().getName().c_str();
654      if (getLangOptions().C99)  // C99 6.8.6.4p1 (ext_ since GCC warns)
655        Diag(ReturnLoc, diag::ext_return_missing_expr, funcName);
656      else  // C90 6.6.6.4p4
657        Diag(ReturnLoc, diag::warn_return_missing_expr, funcName);
658      return new ReturnStmt(ReturnLoc, (Expr*)0);
659    }
660  }
661  // we have a non-void function with an expression, continue checking
662  QualType RetValType = RetValExp->getType();
663
664  // C99 6.8.6.4p3(136): The return statement is not an assignment. The
665  // overlap restriction of subclause 6.5.16.1 does not apply to the case of
666  // function return.
667  AssignConvertType ConvTy = CheckSingleAssignmentConstraints(FnRetType,
668                                                              RetValExp);
669  if (DiagnoseAssignmentResult(ConvTy, ReturnLoc, FnRetType,
670                               RetValType, RetValExp, "returning"))
671    return true;
672
673  if (RetValExp) CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
674
675  return new ReturnStmt(ReturnLoc, (Expr*)RetValExp);
676}
677
678Sema::StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc,
679                                    bool IsSimple,
680                                    bool IsVolatile,
681                                    unsigned NumOutputs,
682                                    unsigned NumInputs,
683                                    std::string *Names,
684                                    ExprTy **Constraints,
685                                    ExprTy **Exprs,
686                                    ExprTy *asmString,
687                                    unsigned NumClobbers,
688                                    ExprTy **Clobbers,
689                                    SourceLocation RParenLoc) {
690  // The parser verifies that there is a string literal here.
691  StringLiteral *AsmString = cast<StringLiteral>((Expr *)asmString);
692  if (AsmString->isWide())
693    // FIXME: We currently leak memory here.
694    return Diag(AsmString->getLocStart(), diag::err_asm_wide_character,
695                AsmString->getSourceRange());
696
697
698  for (unsigned i = 0; i < NumOutputs; i++) {
699    StringLiteral *Literal = cast<StringLiteral>((Expr *)Constraints[i]);
700    if (Literal->isWide())
701      // FIXME: We currently leak memory here.
702      return Diag(Literal->getLocStart(), diag::err_asm_wide_character,
703                  Literal->getSourceRange());
704
705    std::string OutputConstraint(Literal->getStrData(),
706                                 Literal->getByteLength());
707
708    TargetInfo::ConstraintInfo info;
709    if (!Context.Target.validateOutputConstraint(OutputConstraint.c_str(),info))
710      // FIXME: We currently leak memory here.
711      return Diag(Literal->getLocStart(),
712                  diag::err_invalid_output_constraint_in_asm);
713
714    // Check that the output exprs are valid lvalues.
715    Expr *OutputExpr = (Expr *)Exprs[i];
716    Expr::isLvalueResult Result = OutputExpr->isLvalue(Context);
717    if (Result != Expr::LV_Valid) {
718      ParenExpr *PE = cast<ParenExpr>(OutputExpr);
719
720      // FIXME: We currently leak memory here.
721      return Diag(PE->getSubExpr()->getLocStart(),
722                  diag::err_invalid_lvalue_in_asm_output,
723                  PE->getSubExpr()->getSourceRange());
724    }
725  }
726
727  for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
728    StringLiteral *Literal = cast<StringLiteral>((Expr *)Constraints[i]);
729    if (Literal->isWide())
730      // FIXME: We currently leak memory here.
731      return Diag(Literal->getLocStart(), diag::err_asm_wide_character,
732                  Literal->getSourceRange());
733
734    std::string InputConstraint(Literal->getStrData(),
735                                Literal->getByteLength());
736
737    TargetInfo::ConstraintInfo info;
738    if (!Context.Target.validateInputConstraint(InputConstraint.c_str(),
739                                                NumOutputs,
740                                                info)) {
741      // FIXME: We currently leak memory here.
742      return Diag(Literal->getLocStart(),
743                  diag::err_invalid_input_constraint_in_asm);
744    }
745
746    // Check that the input exprs aren't of type void.
747    Expr *InputExpr = (Expr *)Exprs[i];
748    if (InputExpr->getType()->isVoidType()) {
749      ParenExpr *PE = cast<ParenExpr>(InputExpr);
750
751      // FIXME: We currently leak memory here.
752      return Diag(PE->getSubExpr()->getLocStart(),
753                  diag::err_invalid_type_in_asm_input,
754                  PE->getType().getAsString(),
755                  PE->getSubExpr()->getSourceRange());
756    }
757  }
758
759  // Check that the clobbers are valid.
760  for (unsigned i = 0; i < NumClobbers; i++) {
761    StringLiteral *Literal = cast<StringLiteral>((Expr *)Clobbers[i]);
762    if (Literal->isWide())
763      // FIXME: We currently leak memory here.
764      return Diag(Literal->getLocStart(), diag::err_asm_wide_character,
765                  Literal->getSourceRange());
766
767    llvm::SmallString<16> Clobber(Literal->getStrData(),
768                                  Literal->getStrData() +
769                                  Literal->getByteLength());
770
771    if (!Context.Target.isValidGCCRegisterName(Clobber.c_str()))
772      // FIXME: We currently leak memory here.
773      return Diag(Literal->getLocStart(),
774                  diag::err_unknown_register_name_in_asm, Clobber.c_str());
775  }
776
777  return new AsmStmt(AsmLoc,
778                     IsSimple,
779                     IsVolatile,
780                     NumOutputs,
781                     NumInputs,
782                     Names,
783                     reinterpret_cast<StringLiteral**>(Constraints),
784                     reinterpret_cast<Expr**>(Exprs),
785                     AsmString, NumClobbers,
786                     reinterpret_cast<StringLiteral**>(Clobbers),
787                     RParenLoc);
788}
789
790Action::StmtResult
791Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
792                           SourceLocation RParen, StmtTy *Parm,
793                           StmtTy *Body, StmtTy *CatchList) {
794  ObjCAtCatchStmt *CS = new ObjCAtCatchStmt(AtLoc, RParen,
795    static_cast<Stmt*>(Parm), static_cast<Stmt*>(Body),
796    static_cast<Stmt*>(CatchList));
797  return CatchList ? CatchList : CS;
798}
799
800Action::StmtResult
801Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, StmtTy *Body) {
802  ObjCAtFinallyStmt *FS = new ObjCAtFinallyStmt(AtLoc,
803                                                static_cast<Stmt*>(Body));
804  return FS;
805}
806
807Action::StmtResult
808Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc,
809                         StmtTy *Try, StmtTy *Catch, StmtTy *Finally) {
810  ObjCAtTryStmt *TS = new ObjCAtTryStmt(AtLoc, static_cast<Stmt*>(Try),
811                                        static_cast<Stmt*>(Catch),
812                                        static_cast<Stmt*>(Finally));
813  return TS;
814}
815
816Action::StmtResult
817Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, StmtTy *Throw) {
818  ObjCAtThrowStmt *TS = new ObjCAtThrowStmt(AtLoc, static_cast<Stmt*>(Throw));
819  return TS;
820}
821
822Action::StmtResult
823Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, ExprTy *SynchExpr,
824                                  StmtTy *SynchBody) {
825  ObjCAtSynchronizedStmt *SS = new ObjCAtSynchronizedStmt(AtLoc,
826    static_cast<Stmt*>(SynchExpr), static_cast<Stmt*>(SynchBody));
827  return SS;
828}
829