SemaStmt.cpp revision 2d88708cbe4e4ec5e04e4acb6bd7f5be68557379
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 don't need to do this if there's a default
700    // statement or if we have a constant condition.
701    //
702    // TODO: we might want to check whether case values are out of the
703    // enum even if we don't want to check whether all cases are handled.
704    const EnumType* ET = CondTypeBeforePromotion->getAs<EnumType>();
705    // If switch has default case, then ignore it.
706    if (!CaseListIsErroneous && !TheDefaultStmt && !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      // See which case values aren't in enum
727      EnumValsTy::const_iterator EI = EnumVals.begin();
728      for (CaseValsTy::const_iterator CI = CaseVals.begin();
729             CI != CaseVals.end(); CI++) {
730        while (EI != EIend && EI->first < CI->first)
731          EI++;
732        if (EI == EIend || EI->first > CI->first)
733            Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
734              << ED->getDeclName();
735      }
736      // See which of case ranges aren't in enum
737      EI = EnumVals.begin();
738      for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
739             RI != CaseRanges.end() && EI != EIend; RI++) {
740        while (EI != EIend && EI->first < RI->first)
741          EI++;
742
743        if (EI == EIend || EI->first != RI->first) {
744          Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
745            << ED->getDeclName();
746        }
747
748        llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context);
749        while (EI != EIend && EI->first < Hi)
750          EI++;
751        if (EI == EIend || EI->first != Hi)
752          Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
753            << ED->getDeclName();
754      }
755      //Check which enum vals aren't in switch
756      CaseValsTy::const_iterator CI = CaseVals.begin();
757      CaseRangesTy::const_iterator RI = CaseRanges.begin();
758      EI = EnumVals.begin();
759      for (; EI != EIend; EI++) {
760        //Drop unneeded case values
761        llvm::APSInt CIVal;
762        while (CI != CaseVals.end() && CI->first < EI->first)
763          CI++;
764
765        if (CI != CaseVals.end() && CI->first == EI->first)
766          continue;
767
768        //Drop unneeded case ranges
769        for (; RI != CaseRanges.end(); RI++) {
770          llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context);
771          if (EI->first <= Hi)
772            break;
773        }
774
775        if (RI == CaseRanges.end() || EI->first < RI->first)
776          Diag(CondExpr->getExprLoc(), diag::warn_missing_cases)
777            << EI->second->getDeclName();
778      }
779    }
780  }
781
782  // FIXME: If the case list was broken is some way, we don't have a good system
783  // to patch it up.  Instead, just return the whole substmt as broken.
784  if (CaseListIsErroneous)
785    return StmtError();
786
787  return Owned(SS);
788}
789
790StmtResult
791Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
792                     Decl *CondVar, Stmt *Body) {
793  ExprResult CondResult(Cond.release());
794
795  VarDecl *ConditionVar = 0;
796  if (CondVar) {
797    ConditionVar = cast<VarDecl>(CondVar);
798    CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
799    if (CondResult.isInvalid())
800      return StmtError();
801  }
802  Expr *ConditionExpr = CondResult.take();
803  if (!ConditionExpr)
804    return StmtError();
805
806  DiagnoseUnusedExprResult(Body);
807
808  return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
809                                       Body, WhileLoc));
810}
811
812StmtResult
813Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
814                  SourceLocation WhileLoc, SourceLocation CondLParen,
815                  Expr *Cond, SourceLocation CondRParen) {
816  assert(Cond && "ActOnDoStmt(): missing expression");
817
818  if (CheckBooleanCondition(Cond, DoLoc))
819    return StmtError();
820
821  ExprResult CondResult = MaybeCreateCXXExprWithTemporaries(Cond);
822  if (CondResult.isInvalid())
823    return StmtError();
824  Cond = CondResult.take();
825
826  DiagnoseUnusedExprResult(Body);
827
828  return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
829}
830
831StmtResult
832Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
833                   Stmt *First, FullExprArg second, Decl *secondVar,
834                   FullExprArg third,
835                   SourceLocation RParenLoc, Stmt *Body) {
836  if (!getLangOptions().CPlusPlus) {
837    if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
838      // C99 6.8.5p3: The declaration part of a 'for' statement shall only
839      // declare identifiers for objects having storage class 'auto' or
840      // 'register'.
841      for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
842           DI!=DE; ++DI) {
843        VarDecl *VD = dyn_cast<VarDecl>(*DI);
844        if (VD && VD->isBlockVarDecl() && !VD->hasLocalStorage())
845          VD = 0;
846        if (VD == 0)
847          Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
848        // FIXME: mark decl erroneous!
849      }
850    }
851  }
852
853  ExprResult SecondResult(second.release());
854  VarDecl *ConditionVar = 0;
855  if (secondVar) {
856    ConditionVar = cast<VarDecl>(secondVar);
857    SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
858    if (SecondResult.isInvalid())
859      return StmtError();
860  }
861
862  Expr *Third  = third.release().takeAs<Expr>();
863
864  DiagnoseUnusedExprResult(First);
865  DiagnoseUnusedExprResult(Third);
866  DiagnoseUnusedExprResult(Body);
867
868  return Owned(new (Context) ForStmt(Context, First,
869                                     SecondResult.take(), ConditionVar,
870                                     Third, Body, ForLoc, LParenLoc,
871                                     RParenLoc));
872}
873
874StmtResult
875Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
876                                 SourceLocation LParenLoc,
877                                 Stmt *First, Expr *Second,
878                                 SourceLocation RParenLoc, Stmt *Body) {
879  if (First) {
880    QualType FirstType;
881    if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
882      if (!DS->isSingleDecl())
883        return StmtError(Diag((*DS->decl_begin())->getLocation(),
884                         diag::err_toomany_element_decls));
885
886      Decl *D = DS->getSingleDecl();
887      FirstType = cast<ValueDecl>(D)->getType();
888      // C99 6.8.5p3: The declaration part of a 'for' statement shall only
889      // declare identifiers for objects having storage class 'auto' or
890      // 'register'.
891      VarDecl *VD = cast<VarDecl>(D);
892      if (VD->isBlockVarDecl() && !VD->hasLocalStorage())
893        return StmtError(Diag(VD->getLocation(),
894                              diag::err_non_variable_decl_in_for));
895    } else {
896      Expr *FirstE = cast<Expr>(First);
897      if (!FirstE->isTypeDependent() &&
898          FirstE->isLvalue(Context) != Expr::LV_Valid)
899        return StmtError(Diag(First->getLocStart(),
900                   diag::err_selector_element_not_lvalue)
901          << First->getSourceRange());
902
903      FirstType = static_cast<Expr*>(First)->getType();
904    }
905    if (!FirstType->isDependentType() &&
906        !FirstType->isObjCObjectPointerType() &&
907        !FirstType->isBlockPointerType())
908        Diag(ForLoc, diag::err_selector_element_type)
909          << FirstType << First->getSourceRange();
910  }
911  if (Second && !Second->isTypeDependent()) {
912    DefaultFunctionArrayLvalueConversion(Second);
913    QualType SecondType = Second->getType();
914    if (!SecondType->isObjCObjectPointerType())
915      Diag(ForLoc, diag::err_collection_expr_type)
916        << SecondType << Second->getSourceRange();
917    else if (const ObjCObjectPointerType *OPT =
918             SecondType->getAsObjCInterfacePointerType()) {
919      llvm::SmallVector<IdentifierInfo *, 4> KeyIdents;
920      IdentifierInfo* selIdent =
921        &Context.Idents.get("countByEnumeratingWithState");
922      KeyIdents.push_back(selIdent);
923      selIdent = &Context.Idents.get("objects");
924      KeyIdents.push_back(selIdent);
925      selIdent = &Context.Idents.get("count");
926      KeyIdents.push_back(selIdent);
927      Selector CSelector = Context.Selectors.getSelector(3, &KeyIdents[0]);
928      if (ObjCInterfaceDecl *IDecl = OPT->getInterfaceDecl()) {
929        if (!IDecl->isForwardDecl() &&
930            !IDecl->lookupInstanceMethod(CSelector)) {
931          // Must further look into private implementation methods.
932          if (!LookupPrivateInstanceMethod(CSelector, IDecl))
933            Diag(ForLoc, diag::warn_collection_expr_type)
934              << SecondType << CSelector << Second->getSourceRange();
935        }
936      }
937    }
938  }
939  return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body,
940                                                   ForLoc, RParenLoc));
941}
942
943StmtResult
944Sema::ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
945                    IdentifierInfo *LabelII) {
946  // Look up the record for this label identifier.
947  LabelStmt *&LabelDecl = getCurFunction()->LabelMap[LabelII];
948
949  getCurFunction()->setHasBranchIntoScope();
950
951  // If we haven't seen this label yet, create a forward reference.
952  if (LabelDecl == 0)
953    LabelDecl = new (Context) LabelStmt(LabelLoc, LabelII, 0);
954
955  return Owned(new (Context) GotoStmt(LabelDecl, GotoLoc, LabelLoc));
956}
957
958StmtResult
959Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
960                            Expr *E) {
961  // Convert operand to void*
962  if (!E->isTypeDependent()) {
963    QualType ETy = E->getType();
964    QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
965    AssignConvertType ConvTy =
966      CheckSingleAssignmentConstraints(DestTy, E);
967    if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
968      return StmtError();
969  }
970
971  getCurFunction()->setHasIndirectGoto();
972
973  return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
974}
975
976StmtResult
977Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
978  Scope *S = CurScope->getContinueParent();
979  if (!S) {
980    // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
981    return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
982  }
983
984  return Owned(new (Context) ContinueStmt(ContinueLoc));
985}
986
987StmtResult
988Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
989  Scope *S = CurScope->getBreakParent();
990  if (!S) {
991    // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
992    return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
993  }
994
995  return Owned(new (Context) BreakStmt(BreakLoc));
996}
997
998/// \brief Determine whether a return statement is a candidate for the named
999/// return value optimization (C++0x 12.8p34, bullet 1).
1000///
1001/// \param Ctx The context in which the return expression and type occur.
1002///
1003/// \param RetType The return type of the function or block.
1004///
1005/// \param RetExpr The expression being returned from the function or block.
1006///
1007/// \returns The NRVO candidate variable, if the return statement may use the
1008/// NRVO, or NULL if there is no such candidate.
1009static const VarDecl *getNRVOCandidate(ASTContext &Ctx, QualType RetType,
1010                                       Expr *RetExpr) {
1011  QualType ExprType = RetExpr->getType();
1012  // - in a return statement in a function with ...
1013  // ... a class return type ...
1014  if (!RetType->isRecordType())
1015    return 0;
1016  // ... the same cv-unqualified type as the function return type ...
1017  if (!Ctx.hasSameUnqualifiedType(RetType, ExprType))
1018    return 0;
1019  // ... the expression is the name of a non-volatile automatic object ...
1020  // We ignore parentheses here.
1021  // FIXME: Is this compliant? (Everyone else does it)
1022  const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetExpr->IgnoreParens());
1023  if (!DR)
1024    return 0;
1025  const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1026  if (!VD)
1027    return 0;
1028
1029  if (VD->getKind() == Decl::Var && VD->hasLocalStorage() &&
1030      !VD->getType()->isReferenceType() && !VD->hasAttr<BlocksAttr>() &&
1031      !VD->getType().isVolatileQualified())
1032    return VD;
1033
1034  return 0;
1035}
1036
1037/// ActOnBlockReturnStmt - Utility routine to figure out block's return type.
1038///
1039StmtResult
1040Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
1041  // If this is the first return we've seen in the block, infer the type of
1042  // the block from it.
1043  BlockScopeInfo *CurBlock = getCurBlock();
1044  if (CurBlock->ReturnType.isNull()) {
1045    if (RetValExp) {
1046      // Don't call UsualUnaryConversions(), since we don't want to do
1047      // integer promotions here.
1048      DefaultFunctionArrayLvalueConversion(RetValExp);
1049      CurBlock->ReturnType = RetValExp->getType();
1050      if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) {
1051        // We have to remove a 'const' added to copied-in variable which was
1052        // part of the implementation spec. and not the actual qualifier for
1053        // the variable.
1054        if (CDRE->isConstQualAdded())
1055           CurBlock->ReturnType.removeConst();
1056      }
1057    } else
1058      CurBlock->ReturnType = Context.VoidTy;
1059  }
1060  QualType FnRetType = CurBlock->ReturnType;
1061
1062  if (CurBlock->TheDecl->hasAttr<NoReturnAttr>()) {
1063    Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr)
1064      << getCurFunctionOrMethodDecl()->getDeclName();
1065    return StmtError();
1066  }
1067
1068  // Otherwise, verify that this result type matches the previous one.  We are
1069  // pickier with blocks than for normal functions because we don't have GCC
1070  // compatibility to worry about here.
1071  ReturnStmt *Result = 0;
1072  if (CurBlock->ReturnType->isVoidType()) {
1073    if (RetValExp) {
1074      Diag(ReturnLoc, diag::err_return_block_has_expr);
1075      RetValExp = 0;
1076    }
1077    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1078  } else if (!RetValExp) {
1079    return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
1080  } else {
1081    const VarDecl *NRVOCandidate = 0;
1082
1083    if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1084      // we have a non-void block with an expression, continue checking
1085
1086      // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1087      // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1088      // function return.
1089
1090      // In C++ the return statement is handled via a copy initialization.
1091      // the C version of which boils down to CheckSingleAssignmentConstraints.
1092      NRVOCandidate = getNRVOCandidate(Context, FnRetType, RetValExp);
1093      ExprResult Res = PerformCopyInitialization(
1094                               InitializedEntity::InitializeResult(ReturnLoc,
1095                                                                   FnRetType,
1096                                                            NRVOCandidate != 0),
1097                               SourceLocation(),
1098                               Owned(RetValExp));
1099      if (Res.isInvalid()) {
1100        // FIXME: Cleanup temporaries here, anyway?
1101        return StmtError();
1102      }
1103
1104      if (RetValExp)
1105        RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp);
1106
1107      RetValExp = Res.takeAs<Expr>();
1108      if (RetValExp)
1109        CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
1110    }
1111
1112    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
1113  }
1114
1115  // If we need to check for the named return value optimization, save the
1116  // return statement in our scope for later processing.
1117  if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
1118      !CurContext->isDependentContext())
1119    FunctionScopes.back()->Returns.push_back(Result);
1120
1121  return Owned(Result);
1122}
1123
1124StmtResult
1125Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
1126  if (getCurBlock())
1127    return ActOnBlockReturnStmt(ReturnLoc, RetValExp);
1128
1129  QualType FnRetType;
1130  if (const FunctionDecl *FD = getCurFunctionDecl()) {
1131    FnRetType = FD->getResultType();
1132    if (FD->hasAttr<NoReturnAttr>() ||
1133        FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
1134      Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
1135        << getCurFunctionOrMethodDecl()->getDeclName();
1136  } else if (ObjCMethodDecl *MD = getCurMethodDecl())
1137    FnRetType = MD->getResultType();
1138  else // If we don't have a function/method context, bail.
1139    return StmtError();
1140
1141  ReturnStmt *Result = 0;
1142  if (FnRetType->isVoidType()) {
1143    if (RetValExp && !RetValExp->isTypeDependent()) {
1144      // C99 6.8.6.4p1 (ext_ since GCC warns)
1145      unsigned D = diag::ext_return_has_expr;
1146      if (RetValExp->getType()->isVoidType())
1147        D = diag::ext_return_has_void_expr;
1148
1149      // return (some void expression); is legal in C++.
1150      if (D != diag::ext_return_has_void_expr ||
1151          !getLangOptions().CPlusPlus) {
1152        NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
1153        Diag(ReturnLoc, D)
1154          << CurDecl->getDeclName() << isa<ObjCMethodDecl>(CurDecl)
1155          << RetValExp->getSourceRange();
1156      }
1157
1158      RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp);
1159    }
1160
1161    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1162  } else if (!RetValExp && !FnRetType->isDependentType()) {
1163    unsigned DiagID = diag::warn_return_missing_expr;  // C90 6.6.6.4p4
1164    // C99 6.8.6.4p1 (ext_ since GCC warns)
1165    if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr;
1166
1167    if (FunctionDecl *FD = getCurFunctionDecl())
1168      Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
1169    else
1170      Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
1171    Result = new (Context) ReturnStmt(ReturnLoc);
1172  } else {
1173    const VarDecl *NRVOCandidate = 0;
1174    if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1175      // we have a non-void function with an expression, continue checking
1176
1177      // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1178      // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1179      // function return.
1180
1181      // In C++ the return statement is handled via a copy initialization.
1182      // the C version of which boils down to CheckSingleAssignmentConstraints.
1183      NRVOCandidate = getNRVOCandidate(Context, FnRetType, RetValExp);
1184      ExprResult Res = PerformCopyInitialization(
1185                               InitializedEntity::InitializeResult(ReturnLoc,
1186                                                                   FnRetType,
1187                                                            NRVOCandidate != 0),
1188                               SourceLocation(),
1189                               Owned(RetValExp));
1190      if (Res.isInvalid()) {
1191        // FIXME: Cleanup temporaries here, anyway?
1192        return StmtError();
1193      }
1194
1195      RetValExp = Res.takeAs<Expr>();
1196      if (RetValExp)
1197        CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
1198    }
1199
1200    if (RetValExp)
1201      RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp);
1202    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
1203  }
1204
1205  // If we need to check for the named return value optimization, save the
1206  // return statement in our scope for later processing.
1207  if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
1208      !CurContext->isDependentContext())
1209    FunctionScopes.back()->Returns.push_back(Result);
1210
1211  return Owned(Result);
1212}
1213
1214/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
1215/// ignore "noop" casts in places where an lvalue is required by an inline asm.
1216/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
1217/// provide a strong guidance to not use it.
1218///
1219/// This method checks to see if the argument is an acceptable l-value and
1220/// returns false if it is a case we can handle.
1221static bool CheckAsmLValue(const Expr *E, Sema &S) {
1222  // Type dependent expressions will be checked during instantiation.
1223  if (E->isTypeDependent())
1224    return false;
1225
1226  if (E->isLvalue(S.Context) == Expr::LV_Valid)
1227    return false;  // Cool, this is an lvalue.
1228
1229  // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
1230  // are supposed to allow.
1231  const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
1232  if (E != E2 && E2->isLvalue(S.Context) == Expr::LV_Valid) {
1233    if (!S.getLangOptions().HeinousExtensions)
1234      S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
1235        << E->getSourceRange();
1236    else
1237      S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
1238        << E->getSourceRange();
1239    // Accept, even if we emitted an error diagnostic.
1240    return false;
1241  }
1242
1243  // None of the above, just randomly invalid non-lvalue.
1244  return true;
1245}
1246
1247
1248StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc,
1249                                          bool IsSimple,
1250                                          bool IsVolatile,
1251                                          unsigned NumOutputs,
1252                                          unsigned NumInputs,
1253                                          IdentifierInfo **Names,
1254                                          MultiExprArg constraints,
1255                                          MultiExprArg exprs,
1256                                          Expr *asmString,
1257                                          MultiExprArg clobbers,
1258                                          SourceLocation RParenLoc,
1259                                          bool MSAsm) {
1260  unsigned NumClobbers = clobbers.size();
1261  StringLiteral **Constraints =
1262    reinterpret_cast<StringLiteral**>(constraints.get());
1263  Expr **Exprs = exprs.get();
1264  StringLiteral *AsmString = cast<StringLiteral>(asmString);
1265  StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
1266
1267  llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1268
1269  // The parser verifies that there is a string literal here.
1270  if (AsmString->isWide())
1271    return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
1272      << AsmString->getSourceRange());
1273
1274  for (unsigned i = 0; i != NumOutputs; i++) {
1275    StringLiteral *Literal = Constraints[i];
1276    if (Literal->isWide())
1277      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1278        << Literal->getSourceRange());
1279
1280    llvm::StringRef OutputName;
1281    if (Names[i])
1282      OutputName = Names[i]->getName();
1283
1284    TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
1285    if (!Context.Target.validateOutputConstraint(Info))
1286      return StmtError(Diag(Literal->getLocStart(),
1287                            diag::err_asm_invalid_output_constraint)
1288                       << Info.getConstraintStr());
1289
1290    // Check that the output exprs are valid lvalues.
1291    Expr *OutputExpr = Exprs[i];
1292    if (CheckAsmLValue(OutputExpr, *this)) {
1293      return StmtError(Diag(OutputExpr->getLocStart(),
1294                  diag::err_asm_invalid_lvalue_in_output)
1295        << OutputExpr->getSourceRange());
1296    }
1297
1298    OutputConstraintInfos.push_back(Info);
1299  }
1300
1301  llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1302
1303  for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
1304    StringLiteral *Literal = Constraints[i];
1305    if (Literal->isWide())
1306      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1307        << Literal->getSourceRange());
1308
1309    llvm::StringRef InputName;
1310    if (Names[i])
1311      InputName = Names[i]->getName();
1312
1313    TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
1314    if (!Context.Target.validateInputConstraint(OutputConstraintInfos.data(),
1315                                                NumOutputs, Info)) {
1316      return StmtError(Diag(Literal->getLocStart(),
1317                            diag::err_asm_invalid_input_constraint)
1318                       << Info.getConstraintStr());
1319    }
1320
1321    Expr *InputExpr = Exprs[i];
1322
1323    // Only allow void types for memory constraints.
1324    if (Info.allowsMemory() && !Info.allowsRegister()) {
1325      if (CheckAsmLValue(InputExpr, *this))
1326        return StmtError(Diag(InputExpr->getLocStart(),
1327                              diag::err_asm_invalid_lvalue_in_input)
1328                         << Info.getConstraintStr()
1329                         << InputExpr->getSourceRange());
1330    }
1331
1332    if (Info.allowsRegister()) {
1333      if (InputExpr->getType()->isVoidType()) {
1334        return StmtError(Diag(InputExpr->getLocStart(),
1335                              diag::err_asm_invalid_type_in_input)
1336          << InputExpr->getType() << Info.getConstraintStr()
1337          << InputExpr->getSourceRange());
1338      }
1339    }
1340
1341    DefaultFunctionArrayLvalueConversion(Exprs[i]);
1342
1343    InputConstraintInfos.push_back(Info);
1344  }
1345
1346  // Check that the clobbers are valid.
1347  for (unsigned i = 0; i != NumClobbers; i++) {
1348    StringLiteral *Literal = Clobbers[i];
1349    if (Literal->isWide())
1350      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1351        << Literal->getSourceRange());
1352
1353    llvm::StringRef Clobber = Literal->getString();
1354
1355    if (!Context.Target.isValidGCCRegisterName(Clobber))
1356      return StmtError(Diag(Literal->getLocStart(),
1357                  diag::err_asm_unknown_register_name) << Clobber);
1358  }
1359
1360  AsmStmt *NS =
1361    new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm,
1362                          NumOutputs, NumInputs, Names, Constraints, Exprs,
1363                          AsmString, NumClobbers, Clobbers, RParenLoc);
1364  // Validate the asm string, ensuring it makes sense given the operands we
1365  // have.
1366  llvm::SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
1367  unsigned DiagOffs;
1368  if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
1369    Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
1370           << AsmString->getSourceRange();
1371    DeleteStmt(NS);
1372    return StmtError();
1373  }
1374
1375  // Validate tied input operands for type mismatches.
1376  for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
1377    TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1378
1379    // If this is a tied constraint, verify that the output and input have
1380    // either exactly the same type, or that they are int/ptr operands with the
1381    // same size (int/long, int*/long, are ok etc).
1382    if (!Info.hasTiedOperand()) continue;
1383
1384    unsigned TiedTo = Info.getTiedOperand();
1385    Expr *OutputExpr = Exprs[TiedTo];
1386    Expr *InputExpr = Exprs[i+NumOutputs];
1387    QualType InTy = InputExpr->getType();
1388    QualType OutTy = OutputExpr->getType();
1389    if (Context.hasSameType(InTy, OutTy))
1390      continue;  // All types can be tied to themselves.
1391
1392    // Decide if the input and output are in the same domain (integer/ptr or
1393    // floating point.
1394    enum AsmDomain {
1395      AD_Int, AD_FP, AD_Other
1396    } InputDomain, OutputDomain;
1397
1398    if (InTy->isIntegerType() || InTy->isPointerType())
1399      InputDomain = AD_Int;
1400    else if (InTy->isRealFloatingType())
1401      InputDomain = AD_FP;
1402    else
1403      InputDomain = AD_Other;
1404
1405    if (OutTy->isIntegerType() || OutTy->isPointerType())
1406      OutputDomain = AD_Int;
1407    else if (OutTy->isRealFloatingType())
1408      OutputDomain = AD_FP;
1409    else
1410      OutputDomain = AD_Other;
1411
1412    // They are ok if they are the same size and in the same domain.  This
1413    // allows tying things like:
1414    //   void* to int*
1415    //   void* to int            if they are the same size.
1416    //   double to long double   if they are the same size.
1417    //
1418    uint64_t OutSize = Context.getTypeSize(OutTy);
1419    uint64_t InSize = Context.getTypeSize(InTy);
1420    if (OutSize == InSize && InputDomain == OutputDomain &&
1421        InputDomain != AD_Other)
1422      continue;
1423
1424    // If the smaller input/output operand is not mentioned in the asm string,
1425    // then we can promote it and the asm string won't notice.  Check this
1426    // case now.
1427    bool SmallerValueMentioned = false;
1428    for (unsigned p = 0, e = Pieces.size(); p != e; ++p) {
1429      AsmStmt::AsmStringPiece &Piece = Pieces[p];
1430      if (!Piece.isOperand()) continue;
1431
1432      // If this is a reference to the input and if the input was the smaller
1433      // one, then we have to reject this asm.
1434      if (Piece.getOperandNo() == i+NumOutputs) {
1435        if (InSize < OutSize) {
1436          SmallerValueMentioned = true;
1437          break;
1438        }
1439      }
1440
1441      // If this is a reference to the input and if the input was the smaller
1442      // one, then we have to reject this asm.
1443      if (Piece.getOperandNo() == TiedTo) {
1444        if (InSize > OutSize) {
1445          SmallerValueMentioned = true;
1446          break;
1447        }
1448      }
1449    }
1450
1451    // If the smaller value wasn't mentioned in the asm string, and if the
1452    // output was a register, just extend the shorter one to the size of the
1453    // larger one.
1454    if (!SmallerValueMentioned && InputDomain != AD_Other &&
1455        OutputConstraintInfos[TiedTo].allowsRegister())
1456      continue;
1457
1458    Diag(InputExpr->getLocStart(),
1459         diag::err_asm_tying_incompatible_types)
1460      << InTy << OutTy << OutputExpr->getSourceRange()
1461      << InputExpr->getSourceRange();
1462    DeleteStmt(NS);
1463    return StmtError();
1464  }
1465
1466  return Owned(NS);
1467}
1468
1469StmtResult
1470Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
1471                           SourceLocation RParen, Decl *Parm,
1472                           Stmt *Body) {
1473  VarDecl *Var = cast_or_null<VarDecl>(Parm);
1474  if (Var && Var->isInvalidDecl())
1475    return StmtError();
1476
1477  return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
1478}
1479
1480StmtResult
1481Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
1482  return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
1483}
1484
1485StmtResult
1486Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
1487                         MultiStmtArg CatchStmts, Stmt *Finally) {
1488  getCurFunction()->setHasBranchProtectedScope();
1489  unsigned NumCatchStmts = CatchStmts.size();
1490  return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
1491                                     CatchStmts.release(),
1492                                     NumCatchStmts,
1493                                     Finally));
1494}
1495
1496StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc,
1497                                                  Expr *Throw) {
1498  if (Throw) {
1499    QualType ThrowType = Throw->getType();
1500    // Make sure the expression type is an ObjC pointer or "void *".
1501    if (!ThrowType->isDependentType() &&
1502        !ThrowType->isObjCObjectPointerType()) {
1503      const PointerType *PT = ThrowType->getAs<PointerType>();
1504      if (!PT || !PT->getPointeeType()->isVoidType())
1505        return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
1506                         << Throw->getType() << Throw->getSourceRange());
1507    }
1508  }
1509
1510  return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
1511}
1512
1513StmtResult
1514Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
1515                           Scope *CurScope) {
1516  if (!Throw) {
1517    // @throw without an expression designates a rethrow (which much occur
1518    // in the context of an @catch clause).
1519    Scope *AtCatchParent = CurScope;
1520    while (AtCatchParent && !AtCatchParent->isAtCatchScope())
1521      AtCatchParent = AtCatchParent->getParent();
1522    if (!AtCatchParent)
1523      return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
1524  }
1525
1526  return BuildObjCAtThrowStmt(AtLoc, Throw);
1527}
1528
1529StmtResult
1530Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
1531                                  Stmt *SyncBody) {
1532  getCurFunction()->setHasBranchProtectedScope();
1533
1534  // Make sure the expression type is an ObjC pointer or "void *".
1535  if (!SyncExpr->getType()->isDependentType() &&
1536      !SyncExpr->getType()->isObjCObjectPointerType()) {
1537    const PointerType *PT = SyncExpr->getType()->getAs<PointerType>();
1538    if (!PT || !PT->getPointeeType()->isVoidType())
1539      return StmtError(Diag(AtLoc, diag::error_objc_synchronized_expects_object)
1540                       << SyncExpr->getType() << SyncExpr->getSourceRange());
1541  }
1542
1543  return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
1544}
1545
1546/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
1547/// and creates a proper catch handler from them.
1548StmtResult
1549Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
1550                         Stmt *HandlerBlock) {
1551  // There's nothing to test that ActOnExceptionDecl didn't already test.
1552  return Owned(new (Context) CXXCatchStmt(CatchLoc,
1553                                          cast_or_null<VarDecl>(ExDecl),
1554                                          HandlerBlock));
1555}
1556
1557namespace {
1558
1559class TypeWithHandler {
1560  QualType t;
1561  CXXCatchStmt *stmt;
1562public:
1563  TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
1564  : t(type), stmt(statement) {}
1565
1566  // An arbitrary order is fine as long as it places identical
1567  // types next to each other.
1568  bool operator<(const TypeWithHandler &y) const {
1569    if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
1570      return true;
1571    if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
1572      return false;
1573    else
1574      return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
1575  }
1576
1577  bool operator==(const TypeWithHandler& other) const {
1578    return t == other.t;
1579  }
1580
1581  QualType getQualType() const { return t; }
1582  CXXCatchStmt *getCatchStmt() const { return stmt; }
1583  SourceLocation getTypeSpecStartLoc() const {
1584    return stmt->getExceptionDecl()->getTypeSpecStartLoc();
1585  }
1586};
1587
1588}
1589
1590/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
1591/// handlers and creates a try statement from them.
1592StmtResult
1593Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
1594                       MultiStmtArg RawHandlers) {
1595  unsigned NumHandlers = RawHandlers.size();
1596  assert(NumHandlers > 0 &&
1597         "The parser shouldn't call this if there are no handlers.");
1598  Stmt **Handlers = RawHandlers.get();
1599
1600  llvm::SmallVector<TypeWithHandler, 8> TypesWithHandlers;
1601
1602  for (unsigned i = 0; i < NumHandlers; ++i) {
1603    CXXCatchStmt *Handler = llvm::cast<CXXCatchStmt>(Handlers[i]);
1604    if (!Handler->getExceptionDecl()) {
1605      if (i < NumHandlers - 1)
1606        return StmtError(Diag(Handler->getLocStart(),
1607                              diag::err_early_catch_all));
1608
1609      continue;
1610    }
1611
1612    const QualType CaughtType = Handler->getCaughtType();
1613    const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
1614    TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
1615  }
1616
1617  // Detect handlers for the same type as an earlier one.
1618  if (NumHandlers > 1) {
1619    llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
1620
1621    TypeWithHandler prev = TypesWithHandlers[0];
1622    for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
1623      TypeWithHandler curr = TypesWithHandlers[i];
1624
1625      if (curr == prev) {
1626        Diag(curr.getTypeSpecStartLoc(),
1627             diag::warn_exception_caught_by_earlier_handler)
1628          << curr.getCatchStmt()->getCaughtType().getAsString();
1629        Diag(prev.getTypeSpecStartLoc(),
1630             diag::note_previous_exception_handler)
1631          << prev.getCatchStmt()->getCaughtType().getAsString();
1632      }
1633
1634      prev = curr;
1635    }
1636  }
1637
1638  getCurFunction()->setHasBranchProtectedScope();
1639
1640  // FIXME: We should detect handlers that cannot catch anything because an
1641  // earlier handler catches a superclass. Need to find a method that is not
1642  // quadratic for this.
1643  // Neither of these are explicitly forbidden, but every compiler detects them
1644  // and warns.
1645
1646  return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
1647                                  Handlers, NumHandlers));
1648}
1649