SemaStmt.cpp revision 559fb554602bedb57dbbf3cc14ac8a38264b4547
1//===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements semantic analysis for statements.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Sema/SemaInternal.h"
15#include "clang/Sema/Scope.h"
16#include "clang/Sema/ScopeInfo.h"
17#include "clang/Sema/Initialization.h"
18#include "clang/AST/APValue.h"
19#include "clang/AST/ASTContext.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/ExprObjC.h"
23#include "clang/AST/StmtObjC.h"
24#include "clang/AST/StmtCXX.h"
25#include "clang/AST/TypeLoc.h"
26#include "clang/Lex/Preprocessor.h"
27#include "clang/Basic/TargetInfo.h"
28#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/SmallVector.h"
30using namespace clang;
31using namespace sema;
32
33StmtResult Sema::ActOnExprStmt(FullExprArg expr) {
34  Expr *E = expr.get();
35  assert(E && "ActOnExprStmt(): missing expression");
36  // C99 6.8.3p2: The expression in an expression statement is evaluated as a
37  // void expression for its side effects.  Conversion to void allows any
38  // operand, even incomplete types.
39
40  // Same thing in for stmt first clause (when expr) and third clause.
41  return Owned(static_cast<Stmt*>(E));
42}
43
44
45StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc) {
46  return Owned(new (Context) NullStmt(SemiLoc));
47}
48
49StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg,
50                                           SourceLocation StartLoc,
51                                           SourceLocation EndLoc) {
52  DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
53
54  // If we have an invalid decl, just return an error.
55  if (DG.isNull()) return StmtError();
56
57  return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
58}
59
60void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
61  DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
62
63  // If we have an invalid decl, just return.
64  if (DG.isNull() || !DG.isSingleDecl()) return;
65  // suppress any potential 'unused variable' warning.
66  DG.getSingleDecl()->setUsed();
67}
68
69void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
70  const Expr *E = dyn_cast_or_null<Expr>(S);
71  if (!E)
72    return;
73
74  SourceLocation Loc;
75  SourceRange R1, R2;
76  if (!E->isUnusedResultAWarning(Loc, R1, R2, Context))
77    return;
78
79  // Okay, we have an unused result.  Depending on what the base expression is,
80  // we might want to make a more specific diagnostic.  Check for one of these
81  // cases now.
82  unsigned DiagID = diag::warn_unused_expr;
83  E = E->IgnoreParens();
84  if (isa<ObjCImplicitSetterGetterRefExpr>(E))
85    DiagID = diag::warn_unused_property_expr;
86
87  if (const CXXExprWithTemporaries *Temps = dyn_cast<CXXExprWithTemporaries>(E))
88    E = Temps->getSubExpr();
89
90  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
91    if (E->getType()->isVoidType())
92      return;
93
94    // If the callee has attribute pure, const, or warn_unused_result, warn with
95    // a more specific message to make it clear what is happening.
96    if (const Decl *FD = CE->getCalleeDecl()) {
97      if (FD->getAttr<WarnUnusedResultAttr>()) {
98        Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result";
99        return;
100      }
101      if (FD->getAttr<PureAttr>()) {
102        Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
103        return;
104      }
105      if (FD->getAttr<ConstAttr>()) {
106        Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
107        return;
108      }
109    }
110  }
111  else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
112    const ObjCMethodDecl *MD = ME->getMethodDecl();
113    if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
114      Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result";
115      return;
116    }
117  } else if (const CXXFunctionalCastExpr *FC
118                                       = dyn_cast<CXXFunctionalCastExpr>(E)) {
119    if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
120        isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
121      return;
122  }
123  // Diagnose "(void*) blah" as a typo for "(void) blah".
124  else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
125    TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
126    QualType T = TI->getType();
127
128    // We really do want to use the non-canonical type here.
129    if (T == Context.VoidPtrTy) {
130      PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc());
131
132      Diag(Loc, diag::warn_unused_voidptr)
133        << FixItHint::CreateRemoval(TL.getStarLoc());
134      return;
135    }
136  }
137
138  DiagRuntimeBehavior(Loc, PDiag(DiagID) << R1 << R2);
139}
140
141StmtResult
142Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
143                        MultiStmtArg elts, bool isStmtExpr) {
144  unsigned NumElts = elts.size();
145  Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
146  // If we're in C89 mode, check that we don't have any decls after stmts.  If
147  // so, emit an extension diagnostic.
148  if (!getLangOptions().C99 && !getLangOptions().CPlusPlus) {
149    // Note that __extension__ can be around a decl.
150    unsigned i = 0;
151    // Skip over all declarations.
152    for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
153      /*empty*/;
154
155    // We found the end of the list or a statement.  Scan for another declstmt.
156    for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
157      /*empty*/;
158
159    if (i != NumElts) {
160      Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
161      Diag(D->getLocation(), diag::ext_mixed_decls_code);
162    }
163  }
164  // Warn about unused expressions in statements.
165  for (unsigned i = 0; i != NumElts; ++i) {
166    // Ignore statements that are last in a statement expression.
167    if (isStmtExpr && i == NumElts - 1)
168      continue;
169
170    DiagnoseUnusedExprResult(Elts[i]);
171  }
172
173  return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
174}
175
176StmtResult
177Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
178                    SourceLocation DotDotDotLoc, Expr *RHSVal,
179                    SourceLocation ColonLoc) {
180  assert((LHSVal != 0) && "missing expression in case statement");
181
182  // C99 6.8.4.2p3: The expression shall be an integer constant.
183  // However, GCC allows any evaluatable integer expression.
184  if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent() &&
185      VerifyIntegerConstantExpression(LHSVal))
186    return StmtError();
187
188  // GCC extension: The expression shall be an integer constant.
189
190  if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent() &&
191      VerifyIntegerConstantExpression(RHSVal)) {
192    RHSVal = 0;  // Recover by just forgetting about it.
193  }
194
195  if (getCurFunction()->SwitchStack.empty()) {
196    Diag(CaseLoc, diag::err_case_not_in_switch);
197    return StmtError();
198  }
199
200  CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
201                                        ColonLoc);
202  getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
203  return Owned(CS);
204}
205
206/// ActOnCaseStmtBody - This installs a statement as the body of a case.
207void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
208  CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
209  CS->setSubStmt(SubStmt);
210}
211
212StmtResult
213Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
214                       Stmt *SubStmt, Scope *CurScope) {
215  if (getCurFunction()->SwitchStack.empty()) {
216    Diag(DefaultLoc, diag::err_default_not_in_switch);
217    return Owned(SubStmt);
218  }
219
220  DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
221  getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
222  return Owned(DS);
223}
224
225StmtResult
226Sema::ActOnLabelStmt(SourceLocation IdentLoc, IdentifierInfo *II,
227                     SourceLocation ColonLoc, Stmt *SubStmt) {
228  // Look up the record for this label identifier.
229  LabelStmt *&LabelDecl = getCurFunction()->LabelMap[II];
230
231  // If not forward referenced or defined already, just create a new LabelStmt.
232  if (LabelDecl == 0)
233    return Owned(LabelDecl = new (Context) LabelStmt(IdentLoc, II, SubStmt));
234
235  assert(LabelDecl->getID() == II && "Label mismatch!");
236
237  // Otherwise, this label was either forward reference or multiply defined.  If
238  // multiply defined, reject it now.
239  if (LabelDecl->getSubStmt()) {
240    Diag(IdentLoc, diag::err_redefinition_of_label) << LabelDecl->getID();
241    Diag(LabelDecl->getIdentLoc(), diag::note_previous_definition);
242    return Owned(SubStmt);
243  }
244
245  // Otherwise, this label was forward declared, and we just found its real
246  // definition.  Fill in the forward definition and return it.
247  LabelDecl->setIdentLoc(IdentLoc);
248  LabelDecl->setSubStmt(SubStmt);
249  return Owned(LabelDecl);
250}
251
252StmtResult
253Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
254                  Stmt *thenStmt, SourceLocation ElseLoc,
255                  Stmt *elseStmt) {
256  ExprResult CondResult(CondVal.release());
257
258  VarDecl *ConditionVar = 0;
259  if (CondVar) {
260    ConditionVar = cast<VarDecl>(CondVar);
261    CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
262    if (CondResult.isInvalid())
263      return StmtError();
264  }
265  Expr *ConditionExpr = CondResult.takeAs<Expr>();
266  if (!ConditionExpr)
267    return StmtError();
268
269  DiagnoseUnusedExprResult(thenStmt);
270
271  // Warn if the if block has a null body without an else value.
272  // this helps prevent bugs due to typos, such as
273  // if (condition);
274  //   do_stuff();
275  if (!elseStmt) {
276    if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt))
277      Diag(stmt->getSemiLoc(), diag::warn_empty_if_body);
278  }
279
280  DiagnoseUnusedExprResult(elseStmt);
281
282  return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
283                                    thenStmt, ElseLoc, elseStmt));
284}
285
286/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
287/// the specified width and sign.  If an overflow occurs, detect it and emit
288/// the specified diagnostic.
289void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
290                                              unsigned NewWidth, bool NewSign,
291                                              SourceLocation Loc,
292                                              unsigned DiagID) {
293  // Perform a conversion to the promoted condition type if needed.
294  if (NewWidth > Val.getBitWidth()) {
295    // If this is an extension, just do it.
296    Val.extend(NewWidth);
297    Val.setIsSigned(NewSign);
298
299    // If the input was signed and negative and the output is
300    // unsigned, don't bother to warn: this is implementation-defined
301    // behavior.
302    // FIXME: Introduce a second, default-ignored warning for this case?
303  } else if (NewWidth < Val.getBitWidth()) {
304    // If this is a truncation, check for overflow.
305    llvm::APSInt ConvVal(Val);
306    ConvVal.trunc(NewWidth);
307    ConvVal.setIsSigned(NewSign);
308    ConvVal.extend(Val.getBitWidth());
309    ConvVal.setIsSigned(Val.isSigned());
310    if (ConvVal != Val)
311      Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
312
313    // Regardless of whether a diagnostic was emitted, really do the
314    // truncation.
315    Val.trunc(NewWidth);
316    Val.setIsSigned(NewSign);
317  } else if (NewSign != Val.isSigned()) {
318    // Convert the sign to match the sign of the condition.  This can cause
319    // overflow as well: unsigned(INTMIN)
320    // We don't diagnose this overflow, because it is implementation-defined
321    // behavior.
322    // FIXME: Introduce a second, default-ignored warning for this case?
323    llvm::APSInt OldVal(Val);
324    Val.setIsSigned(NewSign);
325  }
326}
327
328namespace {
329  struct CaseCompareFunctor {
330    bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
331                    const llvm::APSInt &RHS) {
332      return LHS.first < RHS;
333    }
334    bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
335                    const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
336      return LHS.first < RHS.first;
337    }
338    bool operator()(const llvm::APSInt &LHS,
339                    const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
340      return LHS < RHS.first;
341    }
342  };
343}
344
345/// CmpCaseVals - Comparison predicate for sorting case values.
346///
347static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
348                        const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
349  if (lhs.first < rhs.first)
350    return true;
351
352  if (lhs.first == rhs.first &&
353      lhs.second->getCaseLoc().getRawEncoding()
354       < rhs.second->getCaseLoc().getRawEncoding())
355    return true;
356  return false;
357}
358
359/// CmpEnumVals - Comparison predicate for sorting enumeration values.
360///
361static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
362                        const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
363{
364  return lhs.first < rhs.first;
365}
366
367/// EqEnumVals - Comparison preficate for uniqing enumeration values.
368///
369static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
370                       const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
371{
372  return lhs.first == rhs.first;
373}
374
375/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
376/// potentially integral-promoted expression @p expr.
377static QualType GetTypeBeforeIntegralPromotion(const Expr* expr) {
378  if (const CastExpr *ImplicitCast = dyn_cast<ImplicitCastExpr>(expr)) {
379    const Expr *ExprBeforePromotion = ImplicitCast->getSubExpr();
380    QualType TypeBeforePromotion = ExprBeforePromotion->getType();
381    if (TypeBeforePromotion->isIntegralOrEnumerationType()) {
382      return TypeBeforePromotion;
383    }
384  }
385  return expr->getType();
386}
387
388StmtResult
389Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
390                             Decl *CondVar) {
391  ExprResult CondResult;
392
393  VarDecl *ConditionVar = 0;
394  if (CondVar) {
395    ConditionVar = cast<VarDecl>(CondVar);
396    CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
397    if (CondResult.isInvalid())
398      return StmtError();
399
400    Cond = CondResult.release();
401  }
402
403  if (!Cond)
404    return StmtError();
405
406  CondResult
407    = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond,
408                          PDiag(diag::err_typecheck_statement_requires_integer),
409                                   PDiag(diag::err_switch_incomplete_class_type)
410                                     << Cond->getSourceRange(),
411                                   PDiag(diag::err_switch_explicit_conversion),
412                                         PDiag(diag::note_switch_conversion),
413                                   PDiag(diag::err_switch_multiple_conversions),
414                                         PDiag(diag::note_switch_conversion),
415                                         PDiag(0));
416  if (CondResult.isInvalid()) return StmtError();
417  Cond = CondResult.take();
418
419  if (!CondVar) {
420    CondResult = MaybeCreateCXXExprWithTemporaries(Cond);
421    if (CondResult.isInvalid())
422      return StmtError();
423    Cond = CondResult.take();
424  }
425
426  getCurFunction()->setHasBranchIntoScope();
427
428  SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
429  getCurFunction()->SwitchStack.push_back(SS);
430  return Owned(SS);
431}
432
433StmtResult
434Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
435                            Stmt *BodyStmt) {
436  SwitchStmt *SS = cast<SwitchStmt>(Switch);
437  assert(SS == getCurFunction()->SwitchStack.back() &&
438         "switch stack missing push/pop!");
439
440  SS->setBody(BodyStmt, SwitchLoc);
441  getCurFunction()->SwitchStack.pop_back();
442
443  if (SS->getCond() == 0)
444    return StmtError();
445
446  Expr *CondExpr = SS->getCond();
447  Expr *CondExprBeforePromotion = CondExpr;
448  QualType CondTypeBeforePromotion =
449      GetTypeBeforeIntegralPromotion(CondExpr);
450
451  // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
452  UsualUnaryConversions(CondExpr);
453  QualType CondType = CondExpr->getType();
454  SS->setCond(CondExpr);
455
456  // C++ 6.4.2.p2:
457  // Integral promotions are performed (on the switch condition).
458  //
459  // A case value unrepresentable by the original switch condition
460  // type (before the promotion) doesn't make sense, even when it can
461  // be represented by the promoted type.  Therefore we need to find
462  // the pre-promotion type of the switch condition.
463  if (!CondExpr->isTypeDependent()) {
464    // We have already converted the expression to an integral or enumeration
465    // type, when we started the switch statement. If we don't have an
466    // appropriate type now, just return an error.
467    if (!CondType->isIntegralOrEnumerationType())
468      return StmtError();
469
470    if (CondExpr->isKnownToHaveBooleanValue()) {
471      // switch(bool_expr) {...} is often a programmer error, e.g.
472      //   switch(n && mask) { ... }  // Doh - should be "n & mask".
473      // One can always use an if statement instead of switch(bool_expr).
474      Diag(SwitchLoc, diag::warn_bool_switch_condition)
475          << CondExpr->getSourceRange();
476    }
477  }
478
479  // Get the bitwidth of the switched-on value before promotions.  We must
480  // convert the integer case values to this width before comparison.
481  bool HasDependentValue
482    = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
483  unsigned CondWidth
484    = HasDependentValue? 0
485      : static_cast<unsigned>(Context.getTypeSize(CondTypeBeforePromotion));
486  bool CondIsSigned = CondTypeBeforePromotion->isSignedIntegerType();
487
488  // Accumulate all of the case values in a vector so that we can sort them
489  // and detect duplicates.  This vector contains the APInt for the case after
490  // it has been converted to the condition type.
491  typedef llvm::SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
492  CaseValsTy CaseVals;
493
494  // Keep track of any GNU case ranges we see.  The APSInt is the low value.
495  typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
496  CaseRangesTy CaseRanges;
497
498  DefaultStmt *TheDefaultStmt = 0;
499
500  bool CaseListIsErroneous = false;
501
502  for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
503       SC = SC->getNextSwitchCase()) {
504
505    if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
506      if (TheDefaultStmt) {
507        Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
508        Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
509
510        // FIXME: Remove the default statement from the switch block so that
511        // we'll return a valid AST.  This requires recursing down the AST and
512        // finding it, not something we are set up to do right now.  For now,
513        // just lop the entire switch stmt out of the AST.
514        CaseListIsErroneous = true;
515      }
516      TheDefaultStmt = DS;
517
518    } else {
519      CaseStmt *CS = cast<CaseStmt>(SC);
520
521      // We already verified that the expression has a i-c-e value (C99
522      // 6.8.4.2p3) - get that value now.
523      Expr *Lo = CS->getLHS();
524
525      if (Lo->isTypeDependent() || Lo->isValueDependent()) {
526        HasDependentValue = true;
527        break;
528      }
529
530      llvm::APSInt LoVal = Lo->EvaluateAsInt(Context);
531
532      // Convert the value to the same width/sign as the condition.
533      ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
534                                         CS->getLHS()->getLocStart(),
535                                         diag::warn_case_value_overflow);
536
537      // If the LHS is not the same type as the condition, insert an implicit
538      // cast.
539      ImpCastExprToType(Lo, CondType, CK_IntegralCast);
540      CS->setLHS(Lo);
541
542      // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
543      if (CS->getRHS()) {
544        if (CS->getRHS()->isTypeDependent() ||
545            CS->getRHS()->isValueDependent()) {
546          HasDependentValue = true;
547          break;
548        }
549        CaseRanges.push_back(std::make_pair(LoVal, CS));
550      } else
551        CaseVals.push_back(std::make_pair(LoVal, CS));
552    }
553  }
554
555  if (!HasDependentValue) {
556    // If we don't have a default statement, check whether the
557    // condition is constant.
558    llvm::APSInt ConstantCondValue;
559    bool HasConstantCond = false;
560    bool ShouldCheckConstantCond = false;
561    if (!HasDependentValue && !TheDefaultStmt) {
562      Expr::EvalResult Result;
563      HasConstantCond = CondExprBeforePromotion->Evaluate(Result, Context);
564      if (HasConstantCond) {
565        assert(Result.Val.isInt() && "switch condition evaluated to non-int");
566        ConstantCondValue = Result.Val.getInt();
567        ShouldCheckConstantCond = true;
568
569        assert(ConstantCondValue.getBitWidth() == CondWidth &&
570               ConstantCondValue.isSigned() == CondIsSigned);
571      }
572    }
573
574    // Sort all the scalar case values so we can easily detect duplicates.
575    std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
576
577    if (!CaseVals.empty()) {
578      for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
579        if (ShouldCheckConstantCond &&
580            CaseVals[i].first == ConstantCondValue)
581          ShouldCheckConstantCond = false;
582
583        if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
584          // If we have a duplicate, report it.
585          Diag(CaseVals[i].second->getLHS()->getLocStart(),
586               diag::err_duplicate_case) << CaseVals[i].first.toString(10);
587          Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
588               diag::note_duplicate_case_prev);
589          // FIXME: We really want to remove the bogus case stmt from the
590          // substmt, but we have no way to do this right now.
591          CaseListIsErroneous = true;
592        }
593      }
594    }
595
596    // Detect duplicate case ranges, which usually don't exist at all in
597    // the first place.
598    if (!CaseRanges.empty()) {
599      // Sort all the case ranges by their low value so we can easily detect
600      // overlaps between ranges.
601      std::stable_sort(CaseRanges.begin(), CaseRanges.end());
602
603      // Scan the ranges, computing the high values and removing empty ranges.
604      std::vector<llvm::APSInt> HiVals;
605      for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
606        llvm::APSInt &LoVal = CaseRanges[i].first;
607        CaseStmt *CR = CaseRanges[i].second;
608        Expr *Hi = CR->getRHS();
609        llvm::APSInt HiVal = Hi->EvaluateAsInt(Context);
610
611        // Convert the value to the same width/sign as the condition.
612        ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
613                                           CR->getRHS()->getLocStart(),
614                                           diag::warn_case_value_overflow);
615
616        // If the LHS is not the same type as the condition, insert an implicit
617        // cast.
618        ImpCastExprToType(Hi, CondType, CK_IntegralCast);
619        CR->setRHS(Hi);
620
621        // If the low value is bigger than the high value, the case is empty.
622        if (LoVal > HiVal) {
623          Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
624            << SourceRange(CR->getLHS()->getLocStart(),
625                           CR->getRHS()->getLocEnd());
626          CaseRanges.erase(CaseRanges.begin()+i);
627          --i, --e;
628          continue;
629        }
630
631        if (ShouldCheckConstantCond &&
632            LoVal <= ConstantCondValue &&
633            ConstantCondValue <= HiVal)
634          ShouldCheckConstantCond = false;
635
636        HiVals.push_back(HiVal);
637      }
638
639      // Rescan the ranges, looking for overlap with singleton values and other
640      // ranges.  Since the range list is sorted, we only need to compare case
641      // ranges with their neighbors.
642      for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
643        llvm::APSInt &CRLo = CaseRanges[i].first;
644        llvm::APSInt &CRHi = HiVals[i];
645        CaseStmt *CR = CaseRanges[i].second;
646
647        // Check to see whether the case range overlaps with any
648        // singleton cases.
649        CaseStmt *OverlapStmt = 0;
650        llvm::APSInt OverlapVal(32);
651
652        // Find the smallest value >= the lower bound.  If I is in the
653        // case range, then we have overlap.
654        CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
655                                                  CaseVals.end(), CRLo,
656                                                  CaseCompareFunctor());
657        if (I != CaseVals.end() && I->first < CRHi) {
658          OverlapVal  = I->first;   // Found overlap with scalar.
659          OverlapStmt = I->second;
660        }
661
662        // Find the smallest value bigger than the upper bound.
663        I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
664        if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
665          OverlapVal  = (I-1)->first;      // Found overlap with scalar.
666          OverlapStmt = (I-1)->second;
667        }
668
669        // Check to see if this case stmt overlaps with the subsequent
670        // case range.
671        if (i && CRLo <= HiVals[i-1]) {
672          OverlapVal  = HiVals[i-1];       // Found overlap with range.
673          OverlapStmt = CaseRanges[i-1].second;
674        }
675
676        if (OverlapStmt) {
677          // If we have a duplicate, report it.
678          Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
679            << OverlapVal.toString(10);
680          Diag(OverlapStmt->getLHS()->getLocStart(),
681               diag::note_duplicate_case_prev);
682          // FIXME: We really want to remove the bogus case stmt from the
683          // substmt, but we have no way to do this right now.
684          CaseListIsErroneous = true;
685        }
686      }
687    }
688
689    // Complain if we have a constant condition and we didn't find a match.
690    if (!CaseListIsErroneous && ShouldCheckConstantCond) {
691      // TODO: it would be nice if we printed enums as enums, chars as
692      // chars, etc.
693      Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
694        << ConstantCondValue.toString(10)
695        << CondExpr->getSourceRange();
696    }
697
698    // Check to see if switch is over an Enum and handles all of its
699    // values.  We only issue a warning if there is not 'default:', but
700    // we still do the analysis to preserve this information in the AST
701    // (which can be used by flow-based analyes).
702    //
703    const EnumType* ET = CondTypeBeforePromotion->getAs<EnumType>();
704
705    // If switch has default case, then ignore it.
706    if (!CaseListIsErroneous  && !HasConstantCond && ET) {
707      const EnumDecl *ED = ET->getDecl();
708      typedef llvm::SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
709      EnumValsTy EnumVals;
710
711      // Gather all enum values, set their type and sort them,
712      // allowing easier comparison with CaseVals.
713      for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
714             EDI != ED->enumerator_end(); EDI++) {
715        llvm::APSInt Val = (*EDI)->getInitVal();
716        if(Val.getBitWidth() < CondWidth)
717          Val.extend(CondWidth);
718        else if (Val.getBitWidth() > CondWidth)
719          Val.trunc(CondWidth);
720        Val.setIsSigned(CondIsSigned);
721        EnumVals.push_back(std::make_pair(Val, (*EDI)));
722      }
723      std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
724      EnumValsTy::iterator EIend =
725        std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
726
727      // See which case values aren't in enum.
728      // TODO: we might want to check whether case values are out of the
729      // enum even if we don't want to check whether all cases are handled.
730      if (!TheDefaultStmt) {
731	EnumValsTy::const_iterator EI = EnumVals.begin();
732	for (CaseValsTy::const_iterator CI = CaseVals.begin();
733             CI != CaseVals.end(); CI++) {
734	  while (EI != EIend && EI->first < CI->first)
735	    EI++;
736	  if (EI == EIend || EI->first > CI->first)
737            Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
738              << ED->getDeclName();
739	}
740	// See which of case ranges aren't in enum
741	EI = EnumVals.begin();
742	for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
743             RI != CaseRanges.end() && EI != EIend; RI++) {
744	  while (EI != EIend && EI->first < RI->first)
745	    EI++;
746
747	  if (EI == EIend || EI->first != RI->first) {
748	    Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
749	      << ED->getDeclName();
750	  }
751
752	  llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context);
753	  while (EI != EIend && EI->first < Hi)
754	    EI++;
755	  if (EI == EIend || EI->first != Hi)
756	    Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
757	      << ED->getDeclName();
758	}
759      }
760      // Check which enum vals aren't in switch
761      CaseValsTy::const_iterator CI = CaseVals.begin();
762      CaseRangesTy::const_iterator RI = CaseRanges.begin();
763      bool hasCasesNotInSwitch = false;
764
765      for (EnumValsTy::const_iterator EI = EnumVals.begin(); EI != EIend; EI++){
766        //Drop unneeded case values
767        llvm::APSInt CIVal;
768        while (CI != CaseVals.end() && CI->first < EI->first)
769          CI++;
770
771        if (CI != CaseVals.end() && CI->first == EI->first)
772          continue;
773
774        // Drop unneeded case ranges
775        for (; RI != CaseRanges.end(); RI++) {
776          llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context);
777          if (EI->first <= Hi)
778            break;
779        }
780
781        if (RI == CaseRanges.end() || EI->first < RI->first) {
782	  hasCasesNotInSwitch = true;
783	  if (!TheDefaultStmt)
784	    Diag(CondExpr->getExprLoc(), diag::warn_missing_cases)
785	      << EI->second->getDeclName();
786	}
787      }
788
789      if (!hasCasesNotInSwitch)
790	SS->setAllEnumCasesCovered();
791    }
792  }
793
794  // FIXME: If the case list was broken is some way, we don't have a good system
795  // to patch it up.  Instead, just return the whole substmt as broken.
796  if (CaseListIsErroneous)
797    return StmtError();
798
799  return Owned(SS);
800}
801
802StmtResult
803Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
804                     Decl *CondVar, Stmt *Body) {
805  ExprResult CondResult(Cond.release());
806
807  VarDecl *ConditionVar = 0;
808  if (CondVar) {
809    ConditionVar = cast<VarDecl>(CondVar);
810    CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
811    if (CondResult.isInvalid())
812      return StmtError();
813  }
814  Expr *ConditionExpr = CondResult.take();
815  if (!ConditionExpr)
816    return StmtError();
817
818  DiagnoseUnusedExprResult(Body);
819
820  return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
821                                       Body, WhileLoc));
822}
823
824StmtResult
825Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
826                  SourceLocation WhileLoc, SourceLocation CondLParen,
827                  Expr *Cond, SourceLocation CondRParen) {
828  assert(Cond && "ActOnDoStmt(): missing expression");
829
830  if (CheckBooleanCondition(Cond, DoLoc))
831    return StmtError();
832
833  ExprResult CondResult = MaybeCreateCXXExprWithTemporaries(Cond);
834  if (CondResult.isInvalid())
835    return StmtError();
836  Cond = CondResult.take();
837
838  DiagnoseUnusedExprResult(Body);
839
840  return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
841}
842
843StmtResult
844Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
845                   Stmt *First, FullExprArg second, Decl *secondVar,
846                   FullExprArg third,
847                   SourceLocation RParenLoc, Stmt *Body) {
848  if (!getLangOptions().CPlusPlus) {
849    if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
850      // C99 6.8.5p3: The declaration part of a 'for' statement shall only
851      // declare identifiers for objects having storage class 'auto' or
852      // 'register'.
853      for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
854           DI!=DE; ++DI) {
855        VarDecl *VD = dyn_cast<VarDecl>(*DI);
856        if (VD && VD->isBlockVarDecl() && !VD->hasLocalStorage())
857          VD = 0;
858        if (VD == 0)
859          Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
860        // FIXME: mark decl erroneous!
861      }
862    }
863  }
864
865  ExprResult SecondResult(second.release());
866  VarDecl *ConditionVar = 0;
867  if (secondVar) {
868    ConditionVar = cast<VarDecl>(secondVar);
869    SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
870    if (SecondResult.isInvalid())
871      return StmtError();
872  }
873
874  Expr *Third  = third.release().takeAs<Expr>();
875
876  DiagnoseUnusedExprResult(First);
877  DiagnoseUnusedExprResult(Third);
878  DiagnoseUnusedExprResult(Body);
879
880  return Owned(new (Context) ForStmt(Context, First,
881                                     SecondResult.take(), ConditionVar,
882                                     Third, Body, ForLoc, LParenLoc,
883                                     RParenLoc));
884}
885
886StmtResult
887Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
888                                 SourceLocation LParenLoc,
889                                 Stmt *First, Expr *Second,
890                                 SourceLocation RParenLoc, Stmt *Body) {
891  if (First) {
892    QualType FirstType;
893    if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
894      if (!DS->isSingleDecl())
895        return StmtError(Diag((*DS->decl_begin())->getLocation(),
896                         diag::err_toomany_element_decls));
897
898      Decl *D = DS->getSingleDecl();
899      FirstType = cast<ValueDecl>(D)->getType();
900      // C99 6.8.5p3: The declaration part of a 'for' statement shall only
901      // declare identifiers for objects having storage class 'auto' or
902      // 'register'.
903      VarDecl *VD = cast<VarDecl>(D);
904      if (VD->isBlockVarDecl() && !VD->hasLocalStorage())
905        return StmtError(Diag(VD->getLocation(),
906                              diag::err_non_variable_decl_in_for));
907    } else {
908      Expr *FirstE = cast<Expr>(First);
909      if (!FirstE->isTypeDependent() &&
910          FirstE->isLvalue(Context) != Expr::LV_Valid)
911        return StmtError(Diag(First->getLocStart(),
912                   diag::err_selector_element_not_lvalue)
913          << First->getSourceRange());
914
915      FirstType = static_cast<Expr*>(First)->getType();
916    }
917    if (!FirstType->isDependentType() &&
918        !FirstType->isObjCObjectPointerType() &&
919        !FirstType->isBlockPointerType())
920        Diag(ForLoc, diag::err_selector_element_type)
921          << FirstType << First->getSourceRange();
922  }
923  if (Second && !Second->isTypeDependent()) {
924    DefaultFunctionArrayLvalueConversion(Second);
925    QualType SecondType = Second->getType();
926    if (!SecondType->isObjCObjectPointerType())
927      Diag(ForLoc, diag::err_collection_expr_type)
928        << SecondType << Second->getSourceRange();
929    else if (const ObjCObjectPointerType *OPT =
930             SecondType->getAsObjCInterfacePointerType()) {
931      llvm::SmallVector<IdentifierInfo *, 4> KeyIdents;
932      IdentifierInfo* selIdent =
933        &Context.Idents.get("countByEnumeratingWithState");
934      KeyIdents.push_back(selIdent);
935      selIdent = &Context.Idents.get("objects");
936      KeyIdents.push_back(selIdent);
937      selIdent = &Context.Idents.get("count");
938      KeyIdents.push_back(selIdent);
939      Selector CSelector = Context.Selectors.getSelector(3, &KeyIdents[0]);
940      if (ObjCInterfaceDecl *IDecl = OPT->getInterfaceDecl()) {
941        if (!IDecl->isForwardDecl() &&
942            !IDecl->lookupInstanceMethod(CSelector)) {
943          // Must further look into private implementation methods.
944          if (!LookupPrivateInstanceMethod(CSelector, IDecl))
945            Diag(ForLoc, diag::warn_collection_expr_type)
946              << SecondType << CSelector << Second->getSourceRange();
947        }
948      }
949    }
950  }
951  return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body,
952                                                   ForLoc, RParenLoc));
953}
954
955StmtResult
956Sema::ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
957                    IdentifierInfo *LabelII) {
958  // Look up the record for this label identifier.
959  LabelStmt *&LabelDecl = getCurFunction()->LabelMap[LabelII];
960
961  getCurFunction()->setHasBranchIntoScope();
962
963  // If we haven't seen this label yet, create a forward reference.
964  if (LabelDecl == 0)
965    LabelDecl = new (Context) LabelStmt(LabelLoc, LabelII, 0);
966
967  return Owned(new (Context) GotoStmt(LabelDecl, GotoLoc, LabelLoc));
968}
969
970StmtResult
971Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
972                            Expr *E) {
973  // Convert operand to void*
974  if (!E->isTypeDependent()) {
975    QualType ETy = E->getType();
976    QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
977    AssignConvertType ConvTy =
978      CheckSingleAssignmentConstraints(DestTy, E);
979    if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
980      return StmtError();
981  }
982
983  getCurFunction()->setHasIndirectGoto();
984
985  return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
986}
987
988StmtResult
989Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
990  Scope *S = CurScope->getContinueParent();
991  if (!S) {
992    // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
993    return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
994  }
995
996  return Owned(new (Context) ContinueStmt(ContinueLoc));
997}
998
999StmtResult
1000Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
1001  Scope *S = CurScope->getBreakParent();
1002  if (!S) {
1003    // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
1004    return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
1005  }
1006
1007  return Owned(new (Context) BreakStmt(BreakLoc));
1008}
1009
1010/// \brief Determine whether a return statement is a candidate for the named
1011/// return value optimization (C++0x 12.8p34, bullet 1).
1012///
1013/// \param Ctx The context in which the return expression and type occur.
1014///
1015/// \param RetType The return type of the function or block.
1016///
1017/// \param RetExpr The expression being returned from the function or block.
1018///
1019/// \returns The NRVO candidate variable, if the return statement may use the
1020/// NRVO, or NULL if there is no such candidate.
1021static const VarDecl *getNRVOCandidate(ASTContext &Ctx, QualType RetType,
1022                                       Expr *RetExpr) {
1023  QualType ExprType = RetExpr->getType();
1024  // - in a return statement in a function with ...
1025  // ... a class return type ...
1026  if (!RetType->isRecordType())
1027    return 0;
1028  // ... the same cv-unqualified type as the function return type ...
1029  if (!Ctx.hasSameUnqualifiedType(RetType, ExprType))
1030    return 0;
1031  // ... the expression is the name of a non-volatile automatic object ...
1032  // We ignore parentheses here.
1033  // FIXME: Is this compliant? (Everyone else does it)
1034  const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetExpr->IgnoreParens());
1035  if (!DR)
1036    return 0;
1037  const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1038  if (!VD)
1039    return 0;
1040
1041  if (VD->getKind() == Decl::Var && VD->hasLocalStorage() &&
1042      !VD->getType()->isReferenceType() && !VD->hasAttr<BlocksAttr>() &&
1043      !VD->getType().isVolatileQualified())
1044    return VD;
1045
1046  return 0;
1047}
1048
1049/// ActOnBlockReturnStmt - Utility routine to figure out block's return type.
1050///
1051StmtResult
1052Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
1053  // If this is the first return we've seen in the block, infer the type of
1054  // the block from it.
1055  BlockScopeInfo *CurBlock = getCurBlock();
1056  if (CurBlock->ReturnType.isNull()) {
1057    if (RetValExp) {
1058      // Don't call UsualUnaryConversions(), since we don't want to do
1059      // integer promotions here.
1060      DefaultFunctionArrayLvalueConversion(RetValExp);
1061      CurBlock->ReturnType = RetValExp->getType();
1062      if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) {
1063        // We have to remove a 'const' added to copied-in variable which was
1064        // part of the implementation spec. and not the actual qualifier for
1065        // the variable.
1066        if (CDRE->isConstQualAdded())
1067           CurBlock->ReturnType.removeConst();
1068      }
1069    } else
1070      CurBlock->ReturnType = Context.VoidTy;
1071  }
1072  QualType FnRetType = CurBlock->ReturnType;
1073
1074  if (CurBlock->TheDecl->hasAttr<NoReturnAttr>()) {
1075    Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr)
1076      << getCurFunctionOrMethodDecl()->getDeclName();
1077    return StmtError();
1078  }
1079
1080  // Otherwise, verify that this result type matches the previous one.  We are
1081  // pickier with blocks than for normal functions because we don't have GCC
1082  // compatibility to worry about here.
1083  ReturnStmt *Result = 0;
1084  if (CurBlock->ReturnType->isVoidType()) {
1085    if (RetValExp) {
1086      Diag(ReturnLoc, diag::err_return_block_has_expr);
1087      RetValExp = 0;
1088    }
1089    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1090  } else if (!RetValExp) {
1091    return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
1092  } else {
1093    const VarDecl *NRVOCandidate = 0;
1094
1095    if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1096      // we have a non-void block with an expression, continue checking
1097
1098      // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1099      // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1100      // function return.
1101
1102      // In C++ the return statement is handled via a copy initialization.
1103      // the C version of which boils down to CheckSingleAssignmentConstraints.
1104      NRVOCandidate = getNRVOCandidate(Context, FnRetType, RetValExp);
1105      ExprResult Res = PerformCopyInitialization(
1106                               InitializedEntity::InitializeResult(ReturnLoc,
1107                                                                   FnRetType,
1108                                                            NRVOCandidate != 0),
1109                               SourceLocation(),
1110                               Owned(RetValExp));
1111      if (Res.isInvalid()) {
1112        // FIXME: Cleanup temporaries here, anyway?
1113        return StmtError();
1114      }
1115
1116      if (RetValExp)
1117        RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp);
1118
1119      RetValExp = Res.takeAs<Expr>();
1120      if (RetValExp)
1121        CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
1122    }
1123
1124    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
1125  }
1126
1127  // If we need to check for the named return value optimization, save the
1128  // return statement in our scope for later processing.
1129  if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
1130      !CurContext->isDependentContext())
1131    FunctionScopes.back()->Returns.push_back(Result);
1132
1133  return Owned(Result);
1134}
1135
1136StmtResult
1137Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
1138  if (getCurBlock())
1139    return ActOnBlockReturnStmt(ReturnLoc, RetValExp);
1140
1141  QualType FnRetType;
1142  if (const FunctionDecl *FD = getCurFunctionDecl()) {
1143    FnRetType = FD->getResultType();
1144    if (FD->hasAttr<NoReturnAttr>() ||
1145        FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
1146      Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
1147        << getCurFunctionOrMethodDecl()->getDeclName();
1148  } else if (ObjCMethodDecl *MD = getCurMethodDecl())
1149    FnRetType = MD->getResultType();
1150  else // If we don't have a function/method context, bail.
1151    return StmtError();
1152
1153  ReturnStmt *Result = 0;
1154  if (FnRetType->isVoidType()) {
1155    if (RetValExp && !RetValExp->isTypeDependent()) {
1156      // C99 6.8.6.4p1 (ext_ since GCC warns)
1157      unsigned D = diag::ext_return_has_expr;
1158      if (RetValExp->getType()->isVoidType())
1159        D = diag::ext_return_has_void_expr;
1160
1161      // return (some void expression); is legal in C++.
1162      if (D != diag::ext_return_has_void_expr ||
1163          !getLangOptions().CPlusPlus) {
1164        NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
1165        Diag(ReturnLoc, D)
1166          << CurDecl->getDeclName() << isa<ObjCMethodDecl>(CurDecl)
1167          << RetValExp->getSourceRange();
1168      }
1169
1170      RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp);
1171    }
1172
1173    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1174  } else if (!RetValExp && !FnRetType->isDependentType()) {
1175    unsigned DiagID = diag::warn_return_missing_expr;  // C90 6.6.6.4p4
1176    // C99 6.8.6.4p1 (ext_ since GCC warns)
1177    if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr;
1178
1179    if (FunctionDecl *FD = getCurFunctionDecl())
1180      Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
1181    else
1182      Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
1183    Result = new (Context) ReturnStmt(ReturnLoc);
1184  } else {
1185    const VarDecl *NRVOCandidate = 0;
1186    if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1187      // we have a non-void function with an expression, continue checking
1188
1189      // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1190      // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1191      // function return.
1192
1193      // In C++ the return statement is handled via a copy initialization.
1194      // the C version of which boils down to CheckSingleAssignmentConstraints.
1195      NRVOCandidate = getNRVOCandidate(Context, FnRetType, RetValExp);
1196      ExprResult Res = PerformCopyInitialization(
1197                               InitializedEntity::InitializeResult(ReturnLoc,
1198                                                                   FnRetType,
1199                                                            NRVOCandidate != 0),
1200                               SourceLocation(),
1201                               Owned(RetValExp));
1202      if (Res.isInvalid()) {
1203        // FIXME: Cleanup temporaries here, anyway?
1204        return StmtError();
1205      }
1206
1207      RetValExp = Res.takeAs<Expr>();
1208      if (RetValExp)
1209        CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
1210    }
1211
1212    if (RetValExp)
1213      RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp);
1214    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
1215  }
1216
1217  // If we need to check for the named return value optimization, save the
1218  // return statement in our scope for later processing.
1219  if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
1220      !CurContext->isDependentContext())
1221    FunctionScopes.back()->Returns.push_back(Result);
1222
1223  return Owned(Result);
1224}
1225
1226/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
1227/// ignore "noop" casts in places where an lvalue is required by an inline asm.
1228/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
1229/// provide a strong guidance to not use it.
1230///
1231/// This method checks to see if the argument is an acceptable l-value and
1232/// returns false if it is a case we can handle.
1233static bool CheckAsmLValue(const Expr *E, Sema &S) {
1234  // Type dependent expressions will be checked during instantiation.
1235  if (E->isTypeDependent())
1236    return false;
1237
1238  if (E->isLvalue(S.Context) == Expr::LV_Valid)
1239    return false;  // Cool, this is an lvalue.
1240
1241  // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
1242  // are supposed to allow.
1243  const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
1244  if (E != E2 && E2->isLvalue(S.Context) == Expr::LV_Valid) {
1245    if (!S.getLangOptions().HeinousExtensions)
1246      S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
1247        << E->getSourceRange();
1248    else
1249      S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
1250        << E->getSourceRange();
1251    // Accept, even if we emitted an error diagnostic.
1252    return false;
1253  }
1254
1255  // None of the above, just randomly invalid non-lvalue.
1256  return true;
1257}
1258
1259
1260StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc,
1261                                          bool IsSimple,
1262                                          bool IsVolatile,
1263                                          unsigned NumOutputs,
1264                                          unsigned NumInputs,
1265                                          IdentifierInfo **Names,
1266                                          MultiExprArg constraints,
1267                                          MultiExprArg exprs,
1268                                          Expr *asmString,
1269                                          MultiExprArg clobbers,
1270                                          SourceLocation RParenLoc,
1271                                          bool MSAsm) {
1272  unsigned NumClobbers = clobbers.size();
1273  StringLiteral **Constraints =
1274    reinterpret_cast<StringLiteral**>(constraints.get());
1275  Expr **Exprs = exprs.get();
1276  StringLiteral *AsmString = cast<StringLiteral>(asmString);
1277  StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
1278
1279  llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1280
1281  // The parser verifies that there is a string literal here.
1282  if (AsmString->isWide())
1283    return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
1284      << AsmString->getSourceRange());
1285
1286  for (unsigned i = 0; i != NumOutputs; i++) {
1287    StringLiteral *Literal = Constraints[i];
1288    if (Literal->isWide())
1289      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1290        << Literal->getSourceRange());
1291
1292    llvm::StringRef OutputName;
1293    if (Names[i])
1294      OutputName = Names[i]->getName();
1295
1296    TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
1297    if (!Context.Target.validateOutputConstraint(Info))
1298      return StmtError(Diag(Literal->getLocStart(),
1299                            diag::err_asm_invalid_output_constraint)
1300                       << Info.getConstraintStr());
1301
1302    // Check that the output exprs are valid lvalues.
1303    Expr *OutputExpr = Exprs[i];
1304    if (CheckAsmLValue(OutputExpr, *this)) {
1305      return StmtError(Diag(OutputExpr->getLocStart(),
1306                  diag::err_asm_invalid_lvalue_in_output)
1307        << OutputExpr->getSourceRange());
1308    }
1309
1310    OutputConstraintInfos.push_back(Info);
1311  }
1312
1313  llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1314
1315  for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
1316    StringLiteral *Literal = Constraints[i];
1317    if (Literal->isWide())
1318      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1319        << Literal->getSourceRange());
1320
1321    llvm::StringRef InputName;
1322    if (Names[i])
1323      InputName = Names[i]->getName();
1324
1325    TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
1326    if (!Context.Target.validateInputConstraint(OutputConstraintInfos.data(),
1327                                                NumOutputs, Info)) {
1328      return StmtError(Diag(Literal->getLocStart(),
1329                            diag::err_asm_invalid_input_constraint)
1330                       << Info.getConstraintStr());
1331    }
1332
1333    Expr *InputExpr = Exprs[i];
1334
1335    // Only allow void types for memory constraints.
1336    if (Info.allowsMemory() && !Info.allowsRegister()) {
1337      if (CheckAsmLValue(InputExpr, *this))
1338        return StmtError(Diag(InputExpr->getLocStart(),
1339                              diag::err_asm_invalid_lvalue_in_input)
1340                         << Info.getConstraintStr()
1341                         << InputExpr->getSourceRange());
1342    }
1343
1344    if (Info.allowsRegister()) {
1345      if (InputExpr->getType()->isVoidType()) {
1346        return StmtError(Diag(InputExpr->getLocStart(),
1347                              diag::err_asm_invalid_type_in_input)
1348          << InputExpr->getType() << Info.getConstraintStr()
1349          << InputExpr->getSourceRange());
1350      }
1351    }
1352
1353    DefaultFunctionArrayLvalueConversion(Exprs[i]);
1354
1355    InputConstraintInfos.push_back(Info);
1356  }
1357
1358  // Check that the clobbers are valid.
1359  for (unsigned i = 0; i != NumClobbers; i++) {
1360    StringLiteral *Literal = Clobbers[i];
1361    if (Literal->isWide())
1362      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1363        << Literal->getSourceRange());
1364
1365    llvm::StringRef Clobber = Literal->getString();
1366
1367    if (!Context.Target.isValidGCCRegisterName(Clobber))
1368      return StmtError(Diag(Literal->getLocStart(),
1369                  diag::err_asm_unknown_register_name) << Clobber);
1370  }
1371
1372  AsmStmt *NS =
1373    new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm,
1374                          NumOutputs, NumInputs, Names, Constraints, Exprs,
1375                          AsmString, NumClobbers, Clobbers, RParenLoc);
1376  // Validate the asm string, ensuring it makes sense given the operands we
1377  // have.
1378  llvm::SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
1379  unsigned DiagOffs;
1380  if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
1381    Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
1382           << AsmString->getSourceRange();
1383    return StmtError();
1384  }
1385
1386  // Validate tied input operands for type mismatches.
1387  for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
1388    TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1389
1390    // If this is a tied constraint, verify that the output and input have
1391    // either exactly the same type, or that they are int/ptr operands with the
1392    // same size (int/long, int*/long, are ok etc).
1393    if (!Info.hasTiedOperand()) continue;
1394
1395    unsigned TiedTo = Info.getTiedOperand();
1396    Expr *OutputExpr = Exprs[TiedTo];
1397    Expr *InputExpr = Exprs[i+NumOutputs];
1398    QualType InTy = InputExpr->getType();
1399    QualType OutTy = OutputExpr->getType();
1400    if (Context.hasSameType(InTy, OutTy))
1401      continue;  // All types can be tied to themselves.
1402
1403    // Decide if the input and output are in the same domain (integer/ptr or
1404    // floating point.
1405    enum AsmDomain {
1406      AD_Int, AD_FP, AD_Other
1407    } InputDomain, OutputDomain;
1408
1409    if (InTy->isIntegerType() || InTy->isPointerType())
1410      InputDomain = AD_Int;
1411    else if (InTy->isRealFloatingType())
1412      InputDomain = AD_FP;
1413    else
1414      InputDomain = AD_Other;
1415
1416    if (OutTy->isIntegerType() || OutTy->isPointerType())
1417      OutputDomain = AD_Int;
1418    else if (OutTy->isRealFloatingType())
1419      OutputDomain = AD_FP;
1420    else
1421      OutputDomain = AD_Other;
1422
1423    // They are ok if they are the same size and in the same domain.  This
1424    // allows tying things like:
1425    //   void* to int*
1426    //   void* to int            if they are the same size.
1427    //   double to long double   if they are the same size.
1428    //
1429    uint64_t OutSize = Context.getTypeSize(OutTy);
1430    uint64_t InSize = Context.getTypeSize(InTy);
1431    if (OutSize == InSize && InputDomain == OutputDomain &&
1432        InputDomain != AD_Other)
1433      continue;
1434
1435    // If the smaller input/output operand is not mentioned in the asm string,
1436    // then we can promote it and the asm string won't notice.  Check this
1437    // case now.
1438    bool SmallerValueMentioned = false;
1439    for (unsigned p = 0, e = Pieces.size(); p != e; ++p) {
1440      AsmStmt::AsmStringPiece &Piece = Pieces[p];
1441      if (!Piece.isOperand()) continue;
1442
1443      // If this is a reference to the input and if the input was the smaller
1444      // one, then we have to reject this asm.
1445      if (Piece.getOperandNo() == i+NumOutputs) {
1446        if (InSize < OutSize) {
1447          SmallerValueMentioned = true;
1448          break;
1449        }
1450      }
1451
1452      // If this is a reference to the input and if the input was the smaller
1453      // one, then we have to reject this asm.
1454      if (Piece.getOperandNo() == TiedTo) {
1455        if (InSize > OutSize) {
1456          SmallerValueMentioned = true;
1457          break;
1458        }
1459      }
1460    }
1461
1462    // If the smaller value wasn't mentioned in the asm string, and if the
1463    // output was a register, just extend the shorter one to the size of the
1464    // larger one.
1465    if (!SmallerValueMentioned && InputDomain != AD_Other &&
1466        OutputConstraintInfos[TiedTo].allowsRegister())
1467      continue;
1468
1469    Diag(InputExpr->getLocStart(),
1470         diag::err_asm_tying_incompatible_types)
1471      << InTy << OutTy << OutputExpr->getSourceRange()
1472      << InputExpr->getSourceRange();
1473    return StmtError();
1474  }
1475
1476  return Owned(NS);
1477}
1478
1479StmtResult
1480Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
1481                           SourceLocation RParen, Decl *Parm,
1482                           Stmt *Body) {
1483  VarDecl *Var = cast_or_null<VarDecl>(Parm);
1484  if (Var && Var->isInvalidDecl())
1485    return StmtError();
1486
1487  return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
1488}
1489
1490StmtResult
1491Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
1492  return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
1493}
1494
1495StmtResult
1496Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
1497                         MultiStmtArg CatchStmts, Stmt *Finally) {
1498  getCurFunction()->setHasBranchProtectedScope();
1499  unsigned NumCatchStmts = CatchStmts.size();
1500  return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
1501                                     CatchStmts.release(),
1502                                     NumCatchStmts,
1503                                     Finally));
1504}
1505
1506StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc,
1507                                                  Expr *Throw) {
1508  if (Throw) {
1509    QualType ThrowType = Throw->getType();
1510    // Make sure the expression type is an ObjC pointer or "void *".
1511    if (!ThrowType->isDependentType() &&
1512        !ThrowType->isObjCObjectPointerType()) {
1513      const PointerType *PT = ThrowType->getAs<PointerType>();
1514      if (!PT || !PT->getPointeeType()->isVoidType())
1515        return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
1516                         << Throw->getType() << Throw->getSourceRange());
1517    }
1518  }
1519
1520  return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
1521}
1522
1523StmtResult
1524Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
1525                           Scope *CurScope) {
1526  if (!Throw) {
1527    // @throw without an expression designates a rethrow (which much occur
1528    // in the context of an @catch clause).
1529    Scope *AtCatchParent = CurScope;
1530    while (AtCatchParent && !AtCatchParent->isAtCatchScope())
1531      AtCatchParent = AtCatchParent->getParent();
1532    if (!AtCatchParent)
1533      return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
1534  }
1535
1536  return BuildObjCAtThrowStmt(AtLoc, Throw);
1537}
1538
1539StmtResult
1540Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
1541                                  Stmt *SyncBody) {
1542  getCurFunction()->setHasBranchProtectedScope();
1543
1544  // Make sure the expression type is an ObjC pointer or "void *".
1545  if (!SyncExpr->getType()->isDependentType() &&
1546      !SyncExpr->getType()->isObjCObjectPointerType()) {
1547    const PointerType *PT = SyncExpr->getType()->getAs<PointerType>();
1548    if (!PT || !PT->getPointeeType()->isVoidType())
1549      return StmtError(Diag(AtLoc, diag::error_objc_synchronized_expects_object)
1550                       << SyncExpr->getType() << SyncExpr->getSourceRange());
1551  }
1552
1553  return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
1554}
1555
1556/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
1557/// and creates a proper catch handler from them.
1558StmtResult
1559Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
1560                         Stmt *HandlerBlock) {
1561  // There's nothing to test that ActOnExceptionDecl didn't already test.
1562  return Owned(new (Context) CXXCatchStmt(CatchLoc,
1563                                          cast_or_null<VarDecl>(ExDecl),
1564                                          HandlerBlock));
1565}
1566
1567namespace {
1568
1569class TypeWithHandler {
1570  QualType t;
1571  CXXCatchStmt *stmt;
1572public:
1573  TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
1574  : t(type), stmt(statement) {}
1575
1576  // An arbitrary order is fine as long as it places identical
1577  // types next to each other.
1578  bool operator<(const TypeWithHandler &y) const {
1579    if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
1580      return true;
1581    if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
1582      return false;
1583    else
1584      return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
1585  }
1586
1587  bool operator==(const TypeWithHandler& other) const {
1588    return t == other.t;
1589  }
1590
1591  CXXCatchStmt *getCatchStmt() const { return stmt; }
1592  SourceLocation getTypeSpecStartLoc() const {
1593    return stmt->getExceptionDecl()->getTypeSpecStartLoc();
1594  }
1595};
1596
1597}
1598
1599/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
1600/// handlers and creates a try statement from them.
1601StmtResult
1602Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
1603                       MultiStmtArg RawHandlers) {
1604  unsigned NumHandlers = RawHandlers.size();
1605  assert(NumHandlers > 0 &&
1606         "The parser shouldn't call this if there are no handlers.");
1607  Stmt **Handlers = RawHandlers.get();
1608
1609  llvm::SmallVector<TypeWithHandler, 8> TypesWithHandlers;
1610
1611  for (unsigned i = 0; i < NumHandlers; ++i) {
1612    CXXCatchStmt *Handler = llvm::cast<CXXCatchStmt>(Handlers[i]);
1613    if (!Handler->getExceptionDecl()) {
1614      if (i < NumHandlers - 1)
1615        return StmtError(Diag(Handler->getLocStart(),
1616                              diag::err_early_catch_all));
1617
1618      continue;
1619    }
1620
1621    const QualType CaughtType = Handler->getCaughtType();
1622    const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
1623    TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
1624  }
1625
1626  // Detect handlers for the same type as an earlier one.
1627  if (NumHandlers > 1) {
1628    llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
1629
1630    TypeWithHandler prev = TypesWithHandlers[0];
1631    for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
1632      TypeWithHandler curr = TypesWithHandlers[i];
1633
1634      if (curr == prev) {
1635        Diag(curr.getTypeSpecStartLoc(),
1636             diag::warn_exception_caught_by_earlier_handler)
1637          << curr.getCatchStmt()->getCaughtType().getAsString();
1638        Diag(prev.getTypeSpecStartLoc(),
1639             diag::note_previous_exception_handler)
1640          << prev.getCatchStmt()->getCaughtType().getAsString();
1641      }
1642
1643      prev = curr;
1644    }
1645  }
1646
1647  getCurFunction()->setHasBranchProtectedScope();
1648
1649  // FIXME: We should detect handlers that cannot catch anything because an
1650  // earlier handler catches a superclass. Need to find a method that is not
1651  // quadratic for this.
1652  // Neither of these are explicitly forbidden, but every compiler detects them
1653  // and warns.
1654
1655  return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
1656                                  Handlers, NumHandlers));
1657}
1658