SemaStmt.cpp revision 5cee1195584fa8672253139c86e922daeda69b9e
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/Sema/Lookup.h"
19#include "clang/AST/APValue.h"
20#include "clang/AST/ASTContext.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/ExprObjC.h"
24#include "clang/AST/StmtObjC.h"
25#include "clang/AST/StmtCXX.h"
26#include "clang/AST/TypeLoc.h"
27#include "clang/Lex/Preprocessor.h"
28#include "clang/Basic/TargetInfo.h"
29#include "llvm/ADT/ArrayRef.h"
30#include "llvm/ADT/STLExtras.h"
31#include "llvm/ADT/SmallVector.h"
32using namespace clang;
33using namespace sema;
34
35StmtResult Sema::ActOnExprStmt(FullExprArg expr) {
36  Expr *E = expr.get();
37  if (!E) // FIXME: FullExprArg has no error state?
38    return StmtError();
39
40  // C99 6.8.3p2: The expression in an expression statement is evaluated as a
41  // void expression for its side effects.  Conversion to void allows any
42  // operand, even incomplete types.
43
44  // Same thing in for stmt first clause (when expr) and third clause.
45  return Owned(static_cast<Stmt*>(E));
46}
47
48
49StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
50                               SourceLocation LeadingEmptyMacroLoc) {
51  return Owned(new (Context) NullStmt(SemiLoc, LeadingEmptyMacroLoc));
52}
53
54StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
55                               SourceLocation EndLoc) {
56  DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
57
58  // If we have an invalid decl, just return an error.
59  if (DG.isNull()) return StmtError();
60
61  return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
62}
63
64void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
65  DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
66
67  // If we have an invalid decl, just return.
68  if (DG.isNull() || !DG.isSingleDecl()) return;
69  VarDecl *var = cast<VarDecl>(DG.getSingleDecl());
70
71  // suppress any potential 'unused variable' warning.
72  var->setUsed();
73
74  // foreach variables are never actually initialized in the way that
75  // the parser came up with.
76  var->setInit(0);
77
78  // In ARC, we don't need to retain the iteration variable of a fast
79  // enumeration loop.  Rather than actually trying to catch that
80  // during declaration processing, we remove the consequences here.
81  if (getLangOptions().ObjCAutoRefCount) {
82    QualType type = var->getType();
83
84    // Only do this if we inferred the lifetime.  Inferred lifetime
85    // will show up as a local qualifier because explicit lifetime
86    // should have shown up as an AttributedType instead.
87    if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
88      // Add 'const' and mark the variable as pseudo-strong.
89      var->setType(type.withConst());
90      var->setARCPseudoStrong(true);
91    }
92  }
93}
94
95void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
96  if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
97    return DiagnoseUnusedExprResult(Label->getSubStmt());
98
99  const Expr *E = dyn_cast_or_null<Expr>(S);
100  if (!E)
101    return;
102
103  SourceLocation Loc;
104  SourceRange R1, R2;
105  if (!E->isUnusedResultAWarning(Loc, R1, R2, Context))
106    return;
107
108  // Okay, we have an unused result.  Depending on what the base expression is,
109  // we might want to make a more specific diagnostic.  Check for one of these
110  // cases now.
111  unsigned DiagID = diag::warn_unused_expr;
112  if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
113    E = Temps->getSubExpr();
114  if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
115    E = TempExpr->getSubExpr();
116
117  E = E->IgnoreParenImpCasts();
118  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
119    if (E->getType()->isVoidType())
120      return;
121
122    // If the callee has attribute pure, const, or warn_unused_result, warn with
123    // a more specific message to make it clear what is happening.
124    if (const Decl *FD = CE->getCalleeDecl()) {
125      if (FD->getAttr<WarnUnusedResultAttr>()) {
126        Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result";
127        return;
128      }
129      if (FD->getAttr<PureAttr>()) {
130        Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
131        return;
132      }
133      if (FD->getAttr<ConstAttr>()) {
134        Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
135        return;
136      }
137    }
138  } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
139    if (getLangOptions().ObjCAutoRefCount && ME->isDelegateInitCall()) {
140      Diag(Loc, diag::err_arc_unused_init_message) << R1;
141      return;
142    }
143    const ObjCMethodDecl *MD = ME->getMethodDecl();
144    if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
145      Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result";
146      return;
147    }
148  } else if (isa<ObjCPropertyRefExpr>(E)) {
149    DiagID = diag::warn_unused_property_expr;
150  } else if (const CXXFunctionalCastExpr *FC
151                                       = dyn_cast<CXXFunctionalCastExpr>(E)) {
152    if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
153        isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
154      return;
155  }
156  // Diagnose "(void*) blah" as a typo for "(void) blah".
157  else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
158    TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
159    QualType T = TI->getType();
160
161    // We really do want to use the non-canonical type here.
162    if (T == Context.VoidPtrTy) {
163      PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc());
164
165      Diag(Loc, diag::warn_unused_voidptr)
166        << FixItHint::CreateRemoval(TL.getStarLoc());
167      return;
168    }
169  }
170
171  DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
172}
173
174StmtResult
175Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
176                        MultiStmtArg elts, bool isStmtExpr) {
177  unsigned NumElts = elts.size();
178  Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
179  // If we're in C89 mode, check that we don't have any decls after stmts.  If
180  // so, emit an extension diagnostic.
181  if (!getLangOptions().C99 && !getLangOptions().CPlusPlus) {
182    // Note that __extension__ can be around a decl.
183    unsigned i = 0;
184    // Skip over all declarations.
185    for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
186      /*empty*/;
187
188    // We found the end of the list or a statement.  Scan for another declstmt.
189    for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
190      /*empty*/;
191
192    if (i != NumElts) {
193      Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
194      Diag(D->getLocation(), diag::ext_mixed_decls_code);
195    }
196  }
197  // Warn about unused expressions in statements.
198  for (unsigned i = 0; i != NumElts; ++i) {
199    // Ignore statements that are last in a statement expression.
200    if (isStmtExpr && i == NumElts - 1)
201      continue;
202
203    DiagnoseUnusedExprResult(Elts[i]);
204  }
205
206  return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
207}
208
209StmtResult
210Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
211                    SourceLocation DotDotDotLoc, Expr *RHSVal,
212                    SourceLocation ColonLoc) {
213  assert((LHSVal != 0) && "missing expression in case statement");
214
215  // C99 6.8.4.2p3: The expression shall be an integer constant.
216  // However, GCC allows any evaluatable integer expression.
217  if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent() &&
218      VerifyIntegerConstantExpression(LHSVal))
219    return StmtError();
220
221  // GCC extension: The expression shall be an integer constant.
222
223  if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent() &&
224      VerifyIntegerConstantExpression(RHSVal)) {
225    RHSVal = 0;  // Recover by just forgetting about it.
226  }
227
228  if (getCurFunction()->SwitchStack.empty()) {
229    Diag(CaseLoc, diag::err_case_not_in_switch);
230    return StmtError();
231  }
232
233  CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
234                                        ColonLoc);
235  getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
236  return Owned(CS);
237}
238
239/// ActOnCaseStmtBody - This installs a statement as the body of a case.
240void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
241  CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
242  CS->setSubStmt(SubStmt);
243}
244
245StmtResult
246Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
247                       Stmt *SubStmt, Scope *CurScope) {
248  if (getCurFunction()->SwitchStack.empty()) {
249    Diag(DefaultLoc, diag::err_default_not_in_switch);
250    return Owned(SubStmt);
251  }
252
253  DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
254  getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
255  return Owned(DS);
256}
257
258StmtResult
259Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
260                     SourceLocation ColonLoc, Stmt *SubStmt) {
261
262  // If the label was multiply defined, reject it now.
263  if (TheDecl->getStmt()) {
264    Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
265    Diag(TheDecl->getLocation(), diag::note_previous_definition);
266    return Owned(SubStmt);
267  }
268
269  // Otherwise, things are good.  Fill in the declaration and return it.
270  LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
271  TheDecl->setStmt(LS);
272  if (!TheDecl->isGnuLocal())
273    TheDecl->setLocation(IdentLoc);
274  return Owned(LS);
275}
276
277StmtResult
278Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
279                  Stmt *thenStmt, SourceLocation ElseLoc,
280                  Stmt *elseStmt) {
281  ExprResult CondResult(CondVal.release());
282
283  VarDecl *ConditionVar = 0;
284  if (CondVar) {
285    ConditionVar = cast<VarDecl>(CondVar);
286    CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
287    if (CondResult.isInvalid())
288      return StmtError();
289  }
290  Expr *ConditionExpr = CondResult.takeAs<Expr>();
291  if (!ConditionExpr)
292    return StmtError();
293
294  DiagnoseUnusedExprResult(thenStmt);
295
296  // Warn if the if block has a null body without an else value.
297  // this helps prevent bugs due to typos, such as
298  // if (condition);
299  //   do_stuff();
300  //
301  if (!elseStmt) {
302    if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt))
303      // But do not warn if the body is a macro that expands to nothing, e.g:
304      //
305      // #define CALL(x)
306      // if (condition)
307      //   CALL(0);
308      //
309      if (!stmt->hasLeadingEmptyMacro())
310        Diag(stmt->getSemiLoc(), diag::warn_empty_if_body);
311  }
312
313  DiagnoseUnusedExprResult(elseStmt);
314
315  return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
316                                    thenStmt, ElseLoc, elseStmt));
317}
318
319/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
320/// the specified width and sign.  If an overflow occurs, detect it and emit
321/// the specified diagnostic.
322void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
323                                              unsigned NewWidth, bool NewSign,
324                                              SourceLocation Loc,
325                                              unsigned DiagID) {
326  // Perform a conversion to the promoted condition type if needed.
327  if (NewWidth > Val.getBitWidth()) {
328    // If this is an extension, just do it.
329    Val = Val.extend(NewWidth);
330    Val.setIsSigned(NewSign);
331
332    // If the input was signed and negative and the output is
333    // unsigned, don't bother to warn: this is implementation-defined
334    // behavior.
335    // FIXME: Introduce a second, default-ignored warning for this case?
336  } else if (NewWidth < Val.getBitWidth()) {
337    // If this is a truncation, check for overflow.
338    llvm::APSInt ConvVal(Val);
339    ConvVal = ConvVal.trunc(NewWidth);
340    ConvVal.setIsSigned(NewSign);
341    ConvVal = ConvVal.extend(Val.getBitWidth());
342    ConvVal.setIsSigned(Val.isSigned());
343    if (ConvVal != Val)
344      Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
345
346    // Regardless of whether a diagnostic was emitted, really do the
347    // truncation.
348    Val = Val.trunc(NewWidth);
349    Val.setIsSigned(NewSign);
350  } else if (NewSign != Val.isSigned()) {
351    // Convert the sign to match the sign of the condition.  This can cause
352    // overflow as well: unsigned(INTMIN)
353    // We don't diagnose this overflow, because it is implementation-defined
354    // behavior.
355    // FIXME: Introduce a second, default-ignored warning for this case?
356    llvm::APSInt OldVal(Val);
357    Val.setIsSigned(NewSign);
358  }
359}
360
361namespace {
362  struct CaseCompareFunctor {
363    bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
364                    const llvm::APSInt &RHS) {
365      return LHS.first < RHS;
366    }
367    bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
368                    const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
369      return LHS.first < RHS.first;
370    }
371    bool operator()(const llvm::APSInt &LHS,
372                    const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
373      return LHS < RHS.first;
374    }
375  };
376}
377
378/// CmpCaseVals - Comparison predicate for sorting case values.
379///
380static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
381                        const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
382  if (lhs.first < rhs.first)
383    return true;
384
385  if (lhs.first == rhs.first &&
386      lhs.second->getCaseLoc().getRawEncoding()
387       < rhs.second->getCaseLoc().getRawEncoding())
388    return true;
389  return false;
390}
391
392/// CmpEnumVals - Comparison predicate for sorting enumeration values.
393///
394static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
395                        const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
396{
397  return lhs.first < rhs.first;
398}
399
400/// EqEnumVals - Comparison preficate for uniqing enumeration values.
401///
402static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
403                       const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
404{
405  return lhs.first == rhs.first;
406}
407
408/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
409/// potentially integral-promoted expression @p expr.
410static QualType GetTypeBeforeIntegralPromotion(const Expr* expr) {
411  if (const CastExpr *ImplicitCast = dyn_cast<ImplicitCastExpr>(expr)) {
412    const Expr *ExprBeforePromotion = ImplicitCast->getSubExpr();
413    QualType TypeBeforePromotion = ExprBeforePromotion->getType();
414    if (TypeBeforePromotion->isIntegralOrEnumerationType()) {
415      return TypeBeforePromotion;
416    }
417  }
418  return expr->getType();
419}
420
421StmtResult
422Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
423                             Decl *CondVar) {
424  ExprResult CondResult;
425
426  VarDecl *ConditionVar = 0;
427  if (CondVar) {
428    ConditionVar = cast<VarDecl>(CondVar);
429    CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
430    if (CondResult.isInvalid())
431      return StmtError();
432
433    Cond = CondResult.release();
434  }
435
436  if (!Cond)
437    return StmtError();
438
439  CondResult
440    = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond,
441                          PDiag(diag::err_typecheck_statement_requires_integer),
442                                   PDiag(diag::err_switch_incomplete_class_type)
443                                     << Cond->getSourceRange(),
444                                   PDiag(diag::err_switch_explicit_conversion),
445                                         PDiag(diag::note_switch_conversion),
446                                   PDiag(diag::err_switch_multiple_conversions),
447                                         PDiag(diag::note_switch_conversion),
448                                         PDiag(0));
449  if (CondResult.isInvalid()) return StmtError();
450  Cond = CondResult.take();
451
452  if (!CondVar) {
453    CheckImplicitConversions(Cond, SwitchLoc);
454    CondResult = MaybeCreateExprWithCleanups(Cond);
455    if (CondResult.isInvalid())
456      return StmtError();
457    Cond = CondResult.take();
458  }
459
460  getCurFunction()->setHasBranchIntoScope();
461
462  SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
463  getCurFunction()->SwitchStack.push_back(SS);
464  return Owned(SS);
465}
466
467static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
468  if (Val.getBitWidth() < BitWidth)
469    Val = Val.extend(BitWidth);
470  else if (Val.getBitWidth() > BitWidth)
471    Val = Val.trunc(BitWidth);
472  Val.setIsSigned(IsSigned);
473}
474
475StmtResult
476Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
477                            Stmt *BodyStmt) {
478  SwitchStmt *SS = cast<SwitchStmt>(Switch);
479  assert(SS == getCurFunction()->SwitchStack.back() &&
480         "switch stack missing push/pop!");
481
482  SS->setBody(BodyStmt, SwitchLoc);
483  getCurFunction()->SwitchStack.pop_back();
484
485  if (SS->getCond() == 0)
486    return StmtError();
487
488  Expr *CondExpr = SS->getCond();
489  Expr *CondExprBeforePromotion = CondExpr;
490  QualType CondTypeBeforePromotion =
491      GetTypeBeforeIntegralPromotion(CondExpr);
492
493  // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
494  ExprResult CondResult = UsualUnaryConversions(CondExpr);
495  if (CondResult.isInvalid())
496    return StmtError();
497  CondExpr = CondResult.take();
498  QualType CondType = CondExpr->getType();
499  SS->setCond(CondExpr);
500
501  // C++ 6.4.2.p2:
502  // Integral promotions are performed (on the switch condition).
503  //
504  // A case value unrepresentable by the original switch condition
505  // type (before the promotion) doesn't make sense, even when it can
506  // be represented by the promoted type.  Therefore we need to find
507  // the pre-promotion type of the switch condition.
508  if (!CondExpr->isTypeDependent()) {
509    // We have already converted the expression to an integral or enumeration
510    // type, when we started the switch statement. If we don't have an
511    // appropriate type now, just return an error.
512    if (!CondType->isIntegralOrEnumerationType())
513      return StmtError();
514
515    if (CondExpr->isKnownToHaveBooleanValue()) {
516      // switch(bool_expr) {...} is often a programmer error, e.g.
517      //   switch(n && mask) { ... }  // Doh - should be "n & mask".
518      // One can always use an if statement instead of switch(bool_expr).
519      Diag(SwitchLoc, diag::warn_bool_switch_condition)
520          << CondExpr->getSourceRange();
521    }
522  }
523
524  // Get the bitwidth of the switched-on value before promotions.  We must
525  // convert the integer case values to this width before comparison.
526  bool HasDependentValue
527    = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
528  unsigned CondWidth
529    = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
530  bool CondIsSigned
531    = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
532
533  // Accumulate all of the case values in a vector so that we can sort them
534  // and detect duplicates.  This vector contains the APInt for the case after
535  // it has been converted to the condition type.
536  typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
537  CaseValsTy CaseVals;
538
539  // Keep track of any GNU case ranges we see.  The APSInt is the low value.
540  typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
541  CaseRangesTy CaseRanges;
542
543  DefaultStmt *TheDefaultStmt = 0;
544
545  bool CaseListIsErroneous = false;
546
547  for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
548       SC = SC->getNextSwitchCase()) {
549
550    if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
551      if (TheDefaultStmt) {
552        Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
553        Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
554
555        // FIXME: Remove the default statement from the switch block so that
556        // we'll return a valid AST.  This requires recursing down the AST and
557        // finding it, not something we are set up to do right now.  For now,
558        // just lop the entire switch stmt out of the AST.
559        CaseListIsErroneous = true;
560      }
561      TheDefaultStmt = DS;
562
563    } else {
564      CaseStmt *CS = cast<CaseStmt>(SC);
565
566      // We already verified that the expression has a i-c-e value (C99
567      // 6.8.4.2p3) - get that value now.
568      Expr *Lo = CS->getLHS();
569
570      if (Lo->isTypeDependent() || Lo->isValueDependent()) {
571        HasDependentValue = true;
572        break;
573      }
574
575      llvm::APSInt LoVal = Lo->EvaluateAsInt(Context);
576
577      // Convert the value to the same width/sign as the condition.
578      ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
579                                         Lo->getLocStart(),
580                                         diag::warn_case_value_overflow);
581
582      // If the LHS is not the same type as the condition, insert an implicit
583      // cast.
584      Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
585      CS->setLHS(Lo);
586
587      // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
588      if (CS->getRHS()) {
589        if (CS->getRHS()->isTypeDependent() ||
590            CS->getRHS()->isValueDependent()) {
591          HasDependentValue = true;
592          break;
593        }
594        CaseRanges.push_back(std::make_pair(LoVal, CS));
595      } else
596        CaseVals.push_back(std::make_pair(LoVal, CS));
597    }
598  }
599
600  if (!HasDependentValue) {
601    // If we don't have a default statement, check whether the
602    // condition is constant.
603    llvm::APSInt ConstantCondValue;
604    bool HasConstantCond = false;
605    bool ShouldCheckConstantCond = false;
606    if (!HasDependentValue && !TheDefaultStmt) {
607      Expr::EvalResult Result;
608      HasConstantCond = CondExprBeforePromotion->Evaluate(Result, Context);
609      if (HasConstantCond) {
610        assert(Result.Val.isInt() && "switch condition evaluated to non-int");
611        ConstantCondValue = Result.Val.getInt();
612        ShouldCheckConstantCond = true;
613
614        assert(ConstantCondValue.getBitWidth() == CondWidth &&
615               ConstantCondValue.isSigned() == CondIsSigned);
616      }
617    }
618
619    // Sort all the scalar case values so we can easily detect duplicates.
620    std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
621
622    if (!CaseVals.empty()) {
623      for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
624        if (ShouldCheckConstantCond &&
625            CaseVals[i].first == ConstantCondValue)
626          ShouldCheckConstantCond = false;
627
628        if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
629          // If we have a duplicate, report it.
630          Diag(CaseVals[i].second->getLHS()->getLocStart(),
631               diag::err_duplicate_case) << CaseVals[i].first.toString(10);
632          Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
633               diag::note_duplicate_case_prev);
634          // FIXME: We really want to remove the bogus case stmt from the
635          // substmt, but we have no way to do this right now.
636          CaseListIsErroneous = true;
637        }
638      }
639    }
640
641    // Detect duplicate case ranges, which usually don't exist at all in
642    // the first place.
643    if (!CaseRanges.empty()) {
644      // Sort all the case ranges by their low value so we can easily detect
645      // overlaps between ranges.
646      std::stable_sort(CaseRanges.begin(), CaseRanges.end());
647
648      // Scan the ranges, computing the high values and removing empty ranges.
649      std::vector<llvm::APSInt> HiVals;
650      for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
651        llvm::APSInt &LoVal = CaseRanges[i].first;
652        CaseStmt *CR = CaseRanges[i].second;
653        Expr *Hi = CR->getRHS();
654        llvm::APSInt HiVal = Hi->EvaluateAsInt(Context);
655
656        // Convert the value to the same width/sign as the condition.
657        ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
658                                           Hi->getLocStart(),
659                                           diag::warn_case_value_overflow);
660
661        // If the LHS is not the same type as the condition, insert an implicit
662        // cast.
663        Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
664        CR->setRHS(Hi);
665
666        // If the low value is bigger than the high value, the case is empty.
667        if (LoVal > HiVal) {
668          Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
669            << SourceRange(CR->getLHS()->getLocStart(),
670                           Hi->getLocEnd());
671          CaseRanges.erase(CaseRanges.begin()+i);
672          --i, --e;
673          continue;
674        }
675
676        if (ShouldCheckConstantCond &&
677            LoVal <= ConstantCondValue &&
678            ConstantCondValue <= HiVal)
679          ShouldCheckConstantCond = false;
680
681        HiVals.push_back(HiVal);
682      }
683
684      // Rescan the ranges, looking for overlap with singleton values and other
685      // ranges.  Since the range list is sorted, we only need to compare case
686      // ranges with their neighbors.
687      for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
688        llvm::APSInt &CRLo = CaseRanges[i].first;
689        llvm::APSInt &CRHi = HiVals[i];
690        CaseStmt *CR = CaseRanges[i].second;
691
692        // Check to see whether the case range overlaps with any
693        // singleton cases.
694        CaseStmt *OverlapStmt = 0;
695        llvm::APSInt OverlapVal(32);
696
697        // Find the smallest value >= the lower bound.  If I is in the
698        // case range, then we have overlap.
699        CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
700                                                  CaseVals.end(), CRLo,
701                                                  CaseCompareFunctor());
702        if (I != CaseVals.end() && I->first < CRHi) {
703          OverlapVal  = I->first;   // Found overlap with scalar.
704          OverlapStmt = I->second;
705        }
706
707        // Find the smallest value bigger than the upper bound.
708        I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
709        if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
710          OverlapVal  = (I-1)->first;      // Found overlap with scalar.
711          OverlapStmt = (I-1)->second;
712        }
713
714        // Check to see if this case stmt overlaps with the subsequent
715        // case range.
716        if (i && CRLo <= HiVals[i-1]) {
717          OverlapVal  = HiVals[i-1];       // Found overlap with range.
718          OverlapStmt = CaseRanges[i-1].second;
719        }
720
721        if (OverlapStmt) {
722          // If we have a duplicate, report it.
723          Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
724            << OverlapVal.toString(10);
725          Diag(OverlapStmt->getLHS()->getLocStart(),
726               diag::note_duplicate_case_prev);
727          // FIXME: We really want to remove the bogus case stmt from the
728          // substmt, but we have no way to do this right now.
729          CaseListIsErroneous = true;
730        }
731      }
732    }
733
734    // Complain if we have a constant condition and we didn't find a match.
735    if (!CaseListIsErroneous && ShouldCheckConstantCond) {
736      // TODO: it would be nice if we printed enums as enums, chars as
737      // chars, etc.
738      Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
739        << ConstantCondValue.toString(10)
740        << CondExpr->getSourceRange();
741    }
742
743    // Check to see if switch is over an Enum and handles all of its
744    // values.  We only issue a warning if there is not 'default:', but
745    // we still do the analysis to preserve this information in the AST
746    // (which can be used by flow-based analyes).
747    //
748    const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
749
750    // If switch has default case, then ignore it.
751    if (!CaseListIsErroneous  && !HasConstantCond && ET) {
752      const EnumDecl *ED = ET->getDecl();
753      typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
754        EnumValsTy;
755      EnumValsTy EnumVals;
756
757      // Gather all enum values, set their type and sort them,
758      // allowing easier comparison with CaseVals.
759      for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
760           EDI != ED->enumerator_end(); ++EDI) {
761        llvm::APSInt Val = EDI->getInitVal();
762        AdjustAPSInt(Val, CondWidth, CondIsSigned);
763        EnumVals.push_back(std::make_pair(Val, *EDI));
764      }
765      std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
766      EnumValsTy::iterator EIend =
767        std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
768
769      // See which case values aren't in enum.
770      // TODO: we might want to check whether case values are out of the
771      // enum even if we don't want to check whether all cases are handled.
772      if (!TheDefaultStmt) {
773        EnumValsTy::const_iterator EI = EnumVals.begin();
774        for (CaseValsTy::const_iterator CI = CaseVals.begin();
775             CI != CaseVals.end(); CI++) {
776          while (EI != EIend && EI->first < CI->first)
777            EI++;
778          if (EI == EIend || EI->first > CI->first)
779            Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
780              << ED->getDeclName();
781        }
782        // See which of case ranges aren't in enum
783        EI = EnumVals.begin();
784        for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
785             RI != CaseRanges.end() && EI != EIend; RI++) {
786          while (EI != EIend && EI->first < RI->first)
787            EI++;
788
789          if (EI == EIend || EI->first != RI->first) {
790            Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
791              << ED->getDeclName();
792          }
793
794          llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context);
795          AdjustAPSInt(Hi, CondWidth, CondIsSigned);
796          while (EI != EIend && EI->first < Hi)
797            EI++;
798          if (EI == EIend || EI->first != Hi)
799            Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
800              << ED->getDeclName();
801        }
802      }
803
804      // Check which enum vals aren't in switch
805      CaseValsTy::const_iterator CI = CaseVals.begin();
806      CaseRangesTy::const_iterator RI = CaseRanges.begin();
807      bool hasCasesNotInSwitch = false;
808
809      SmallVector<DeclarationName,8> UnhandledNames;
810
811      for (EnumValsTy::const_iterator EI = EnumVals.begin(); EI != EIend; EI++){
812        // Drop unneeded case values
813        llvm::APSInt CIVal;
814        while (CI != CaseVals.end() && CI->first < EI->first)
815          CI++;
816
817        if (CI != CaseVals.end() && CI->first == EI->first)
818          continue;
819
820        // Drop unneeded case ranges
821        for (; RI != CaseRanges.end(); RI++) {
822          llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context);
823          AdjustAPSInt(Hi, CondWidth, CondIsSigned);
824          if (EI->first <= Hi)
825            break;
826        }
827
828        if (RI == CaseRanges.end() || EI->first < RI->first) {
829          hasCasesNotInSwitch = true;
830          if (!TheDefaultStmt)
831            UnhandledNames.push_back(EI->second->getDeclName());
832        }
833      }
834
835      // Produce a nice diagnostic if multiple values aren't handled.
836      switch (UnhandledNames.size()) {
837      case 0: break;
838      case 1:
839        Diag(CondExpr->getExprLoc(), diag::warn_missing_case1)
840          << UnhandledNames[0];
841        break;
842      case 2:
843        Diag(CondExpr->getExprLoc(), diag::warn_missing_case2)
844          << UnhandledNames[0] << UnhandledNames[1];
845        break;
846      case 3:
847        Diag(CondExpr->getExprLoc(), diag::warn_missing_case3)
848          << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
849        break;
850      default:
851        Diag(CondExpr->getExprLoc(), diag::warn_missing_cases)
852          << (unsigned)UnhandledNames.size()
853          << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
854        break;
855      }
856
857      if (!hasCasesNotInSwitch)
858        SS->setAllEnumCasesCovered();
859    }
860  }
861
862  // FIXME: If the case list was broken is some way, we don't have a good system
863  // to patch it up.  Instead, just return the whole substmt as broken.
864  if (CaseListIsErroneous)
865    return StmtError();
866
867  return Owned(SS);
868}
869
870StmtResult
871Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
872                     Decl *CondVar, Stmt *Body) {
873  ExprResult CondResult(Cond.release());
874
875  VarDecl *ConditionVar = 0;
876  if (CondVar) {
877    ConditionVar = cast<VarDecl>(CondVar);
878    CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
879    if (CondResult.isInvalid())
880      return StmtError();
881  }
882  Expr *ConditionExpr = CondResult.take();
883  if (!ConditionExpr)
884    return StmtError();
885
886  DiagnoseUnusedExprResult(Body);
887
888  return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
889                                       Body, WhileLoc));
890}
891
892StmtResult
893Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
894                  SourceLocation WhileLoc, SourceLocation CondLParen,
895                  Expr *Cond, SourceLocation CondRParen) {
896  assert(Cond && "ActOnDoStmt(): missing expression");
897
898  ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
899  if (CondResult.isInvalid() || CondResult.isInvalid())
900    return StmtError();
901  Cond = CondResult.take();
902
903  CheckImplicitConversions(Cond, DoLoc);
904  CondResult = MaybeCreateExprWithCleanups(Cond);
905  if (CondResult.isInvalid())
906    return StmtError();
907  Cond = CondResult.take();
908
909  DiagnoseUnusedExprResult(Body);
910
911  return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
912}
913
914StmtResult
915Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
916                   Stmt *First, FullExprArg second, Decl *secondVar,
917                   FullExprArg third,
918                   SourceLocation RParenLoc, Stmt *Body) {
919  if (!getLangOptions().CPlusPlus) {
920    if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
921      // C99 6.8.5p3: The declaration part of a 'for' statement shall only
922      // declare identifiers for objects having storage class 'auto' or
923      // 'register'.
924      for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
925           DI!=DE; ++DI) {
926        VarDecl *VD = dyn_cast<VarDecl>(*DI);
927        if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
928          VD = 0;
929        if (VD == 0)
930          Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
931        // FIXME: mark decl erroneous!
932      }
933    }
934  }
935
936  ExprResult SecondResult(second.release());
937  VarDecl *ConditionVar = 0;
938  if (secondVar) {
939    ConditionVar = cast<VarDecl>(secondVar);
940    SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
941    if (SecondResult.isInvalid())
942      return StmtError();
943  }
944
945  Expr *Third  = third.release().takeAs<Expr>();
946
947  DiagnoseUnusedExprResult(First);
948  DiagnoseUnusedExprResult(Third);
949  DiagnoseUnusedExprResult(Body);
950
951  return Owned(new (Context) ForStmt(Context, First,
952                                     SecondResult.take(), ConditionVar,
953                                     Third, Body, ForLoc, LParenLoc,
954                                     RParenLoc));
955}
956
957/// In an Objective C collection iteration statement:
958///   for (x in y)
959/// x can be an arbitrary l-value expression.  Bind it up as a
960/// full-expression.
961StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
962  CheckImplicitConversions(E);
963  ExprResult Result = MaybeCreateExprWithCleanups(E);
964  if (Result.isInvalid()) return StmtError();
965  return Owned(static_cast<Stmt*>(Result.get()));
966}
967
968ExprResult
969Sema::ActOnObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
970  assert(collection);
971
972  // Bail out early if we've got a type-dependent expression.
973  if (collection->isTypeDependent()) return Owned(collection);
974
975  // Perform normal l-value conversion.
976  ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
977  if (result.isInvalid())
978    return ExprError();
979  collection = result.take();
980
981  // The operand needs to have object-pointer type.
982  // TODO: should we do a contextual conversion?
983  const ObjCObjectPointerType *pointerType =
984    collection->getType()->getAs<ObjCObjectPointerType>();
985  if (!pointerType)
986    return Diag(forLoc, diag::err_collection_expr_type)
987             << collection->getType() << collection->getSourceRange();
988
989  // Check that the operand provides
990  //   - countByEnumeratingWithState:objects:count:
991  const ObjCObjectType *objectType = pointerType->getObjectType();
992  ObjCInterfaceDecl *iface = objectType->getInterface();
993
994  // If we have a forward-declared type, we can't do this check.
995  if (iface && iface->isForwardDecl()) {
996    // This is ill-formed under ARC.
997    if (getLangOptions().ObjCAutoRefCount) {
998      Diag(forLoc, diag::err_arc_collection_forward)
999        << pointerType->getPointeeType() << collection->getSourceRange();
1000    }
1001
1002    // Otherwise, if we have any useful type information, check that
1003    // the type declares the appropriate method.
1004  } else if (iface || !objectType->qual_empty()) {
1005    IdentifierInfo *selectorIdents[] = {
1006      &Context.Idents.get("countByEnumeratingWithState"),
1007      &Context.Idents.get("objects"),
1008      &Context.Idents.get("count")
1009    };
1010    Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1011
1012    ObjCMethodDecl *method = 0;
1013
1014    // If there's an interface, look in both the public and private APIs.
1015    if (iface) {
1016      method = iface->lookupInstanceMethod(selector);
1017      if (!method) method = LookupPrivateInstanceMethod(selector, iface);
1018    }
1019
1020    // Also check protocol qualifiers.
1021    if (!method)
1022      method = LookupMethodInQualifiedType(selector, pointerType,
1023                                           /*instance*/ true);
1024
1025    // If we didn't find it anywhere, give up.
1026    if (!method) {
1027      Diag(forLoc, diag::warn_collection_expr_type)
1028        << collection->getType() << selector << collection->getSourceRange();
1029    }
1030
1031    // TODO: check for an incompatible signature?
1032  }
1033
1034  // Wrap up any cleanups in the expression.
1035  return Owned(MaybeCreateExprWithCleanups(collection));
1036}
1037
1038StmtResult
1039Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1040                                 SourceLocation LParenLoc,
1041                                 Stmt *First, Expr *Second,
1042                                 SourceLocation RParenLoc, Stmt *Body) {
1043  if (First) {
1044    QualType FirstType;
1045    if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
1046      if (!DS->isSingleDecl())
1047        return StmtError(Diag((*DS->decl_begin())->getLocation(),
1048                         diag::err_toomany_element_decls));
1049
1050      VarDecl *D = cast<VarDecl>(DS->getSingleDecl());
1051      FirstType = D->getType();
1052      // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1053      // declare identifiers for objects having storage class 'auto' or
1054      // 'register'.
1055      if (!D->hasLocalStorage())
1056        return StmtError(Diag(D->getLocation(),
1057                              diag::err_non_variable_decl_in_for));
1058    } else {
1059      Expr *FirstE = cast<Expr>(First);
1060      if (!FirstE->isTypeDependent() && !FirstE->isLValue())
1061        return StmtError(Diag(First->getLocStart(),
1062                   diag::err_selector_element_not_lvalue)
1063          << First->getSourceRange());
1064
1065      FirstType = static_cast<Expr*>(First)->getType();
1066    }
1067    if (!FirstType->isDependentType() &&
1068        !FirstType->isObjCObjectPointerType() &&
1069        !FirstType->isBlockPointerType())
1070        Diag(ForLoc, diag::err_selector_element_type)
1071          << FirstType << First->getSourceRange();
1072  }
1073
1074  return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body,
1075                                                   ForLoc, RParenLoc));
1076}
1077
1078namespace {
1079
1080enum BeginEndFunction {
1081  BEF_begin,
1082  BEF_end
1083};
1084
1085/// Build a variable declaration for a for-range statement.
1086static VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1087                                     QualType Type, const char *Name) {
1088  DeclContext *DC = SemaRef.CurContext;
1089  IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1090  TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1091  VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1092                                  TInfo, SC_Auto, SC_None);
1093  Decl->setImplicit();
1094  return Decl;
1095}
1096
1097/// Finish building a variable declaration for a for-range statement.
1098/// \return true if an error occurs.
1099static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1100                                  SourceLocation Loc, int diag) {
1101  // Deduce the type for the iterator variable now rather than leaving it to
1102  // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1103  TypeSourceInfo *InitTSI = 0;
1104  if (Init->getType()->isVoidType() ||
1105      !SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI))
1106    SemaRef.Diag(Loc, diag) << Init->getType();
1107  if (!InitTSI) {
1108    Decl->setInvalidDecl();
1109    return true;
1110  }
1111  Decl->setTypeSourceInfo(InitTSI);
1112  Decl->setType(InitTSI->getType());
1113
1114  // In ARC, infer lifetime.
1115  // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1116  // we're doing the equivalent of fast iteration.
1117  if (SemaRef.getLangOptions().ObjCAutoRefCount &&
1118      SemaRef.inferObjCARCLifetime(Decl))
1119    Decl->setInvalidDecl();
1120
1121  SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1122                               /*TypeMayContainAuto=*/false);
1123  SemaRef.FinalizeDeclaration(Decl);
1124  SemaRef.CurContext->addHiddenDecl(Decl);
1125  return false;
1126}
1127
1128/// Produce a note indicating which begin/end function was implicitly called
1129/// by a C++0x for-range statement. This is often not obvious from the code,
1130/// nor from the diagnostics produced when analysing the implicit expressions
1131/// required in a for-range statement.
1132void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
1133                                  BeginEndFunction BEF) {
1134  CallExpr *CE = dyn_cast<CallExpr>(E);
1135  if (!CE)
1136    return;
1137  FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1138  if (!D)
1139    return;
1140  SourceLocation Loc = D->getLocation();
1141
1142  std::string Description;
1143  bool IsTemplate = false;
1144  if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1145    Description = SemaRef.getTemplateArgumentBindingsText(
1146      FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1147    IsTemplate = true;
1148  }
1149
1150  SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1151    << BEF << IsTemplate << Description << E->getType();
1152}
1153
1154/// Build a call to 'begin' or 'end' for a C++0x for-range statement. If the
1155/// given LookupResult is non-empty, it is assumed to describe a member which
1156/// will be invoked. Otherwise, the function will be found via argument
1157/// dependent lookup.
1158static ExprResult BuildForRangeBeginEndCall(Sema &SemaRef, Scope *S,
1159                                            SourceLocation Loc,
1160                                            VarDecl *Decl,
1161                                            BeginEndFunction BEF,
1162                                            const DeclarationNameInfo &NameInfo,
1163                                            LookupResult &MemberLookup,
1164                                            Expr *Range) {
1165  ExprResult CallExpr;
1166  if (!MemberLookup.empty()) {
1167    ExprResult MemberRef =
1168      SemaRef.BuildMemberReferenceExpr(Range, Range->getType(), Loc,
1169                                       /*IsPtr=*/false, CXXScopeSpec(),
1170                                       /*Qualifier=*/0, MemberLookup,
1171                                       /*TemplateArgs=*/0);
1172    if (MemberRef.isInvalid())
1173      return ExprError();
1174    CallExpr = SemaRef.ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(),
1175                                     Loc, 0);
1176    if (CallExpr.isInvalid())
1177      return ExprError();
1178  } else {
1179    UnresolvedSet<0> FoundNames;
1180    // C++0x [stmt.ranged]p1: For the purposes of this name lookup, namespace
1181    // std is an associated namespace.
1182    UnresolvedLookupExpr *Fn =
1183      UnresolvedLookupExpr::Create(SemaRef.Context, /*NamingClass=*/0,
1184                                   NestedNameSpecifierLoc(), NameInfo,
1185                                   /*NeedsADL=*/true, /*Overloaded=*/false,
1186                                   FoundNames.begin(), FoundNames.end(),
1187                                   /*LookInStdNamespace=*/true);
1188    CallExpr = SemaRef.BuildOverloadedCallExpr(S, Fn, Fn, Loc, &Range, 1, Loc,
1189                                               0);
1190    if (CallExpr.isInvalid()) {
1191      SemaRef.Diag(Range->getLocStart(), diag::note_for_range_type)
1192        << Range->getType();
1193      return ExprError();
1194    }
1195  }
1196  if (FinishForRangeVarDecl(SemaRef, Decl, CallExpr.get(), Loc,
1197                            diag::err_for_range_iter_deduction_failure)) {
1198    NoteForRangeBeginEndFunction(SemaRef, CallExpr.get(), BEF);
1199    return ExprError();
1200  }
1201  return CallExpr;
1202}
1203
1204}
1205
1206/// ActOnCXXForRangeStmt - Check and build a C++0x for-range statement.
1207///
1208/// C++0x [stmt.ranged]:
1209///   A range-based for statement is equivalent to
1210///
1211///   {
1212///     auto && __range = range-init;
1213///     for ( auto __begin = begin-expr,
1214///           __end = end-expr;
1215///           __begin != __end;
1216///           ++__begin ) {
1217///       for-range-declaration = *__begin;
1218///       statement
1219///     }
1220///   }
1221///
1222/// The body of the loop is not available yet, since it cannot be analysed until
1223/// we have determined the type of the for-range-declaration.
1224StmtResult
1225Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1226                           Stmt *First, SourceLocation ColonLoc, Expr *Range,
1227                           SourceLocation RParenLoc) {
1228  if (!First || !Range)
1229    return StmtError();
1230
1231  DeclStmt *DS = dyn_cast<DeclStmt>(First);
1232  assert(DS && "first part of for range not a decl stmt");
1233
1234  if (!DS->isSingleDecl()) {
1235    Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1236    return StmtError();
1237  }
1238  if (DS->getSingleDecl()->isInvalidDecl())
1239    return StmtError();
1240
1241  if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1242    return StmtError();
1243
1244  // Build  auto && __range = range-init
1245  SourceLocation RangeLoc = Range->getLocStart();
1246  VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1247                                           Context.getAutoRRefDeductType(),
1248                                           "__range");
1249  if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1250                            diag::err_for_range_deduction_failure))
1251    return StmtError();
1252
1253  // Claim the type doesn't contain auto: we've already done the checking.
1254  DeclGroupPtrTy RangeGroup =
1255    BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false);
1256  StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1257  if (RangeDecl.isInvalid())
1258    return StmtError();
1259
1260  return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1261                              /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
1262                              RParenLoc);
1263}
1264
1265/// BuildCXXForRangeStmt - Build or instantiate a C++0x for-range statement.
1266StmtResult
1267Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
1268                           Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
1269                           Expr *Inc, Stmt *LoopVarDecl,
1270                           SourceLocation RParenLoc) {
1271  Scope *S = getCurScope();
1272
1273  DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
1274  VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
1275  QualType RangeVarType = RangeVar->getType();
1276
1277  DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
1278  VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
1279
1280  StmtResult BeginEndDecl = BeginEnd;
1281  ExprResult NotEqExpr = Cond, IncrExpr = Inc;
1282
1283  if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) {
1284    SourceLocation RangeLoc = RangeVar->getLocation();
1285
1286    ExprResult RangeRef = BuildDeclRefExpr(RangeVar,
1287                                           RangeVarType.getNonReferenceType(),
1288                                           VK_LValue, ColonLoc);
1289    if (RangeRef.isInvalid())
1290      return StmtError();
1291
1292    QualType AutoType = Context.getAutoDeductType();
1293    Expr *Range = RangeVar->getInit();
1294    if (!Range)
1295      return StmtError();
1296    QualType RangeType = Range->getType();
1297
1298    if (RequireCompleteType(RangeLoc, RangeType,
1299                            PDiag(diag::err_for_range_incomplete_type)))
1300      return StmtError();
1301
1302    // Build auto __begin = begin-expr, __end = end-expr.
1303    VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1304                                             "__begin");
1305    VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1306                                           "__end");
1307
1308    // Build begin-expr and end-expr and attach to __begin and __end variables.
1309    ExprResult BeginExpr, EndExpr;
1310    if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
1311      // - if _RangeT is an array type, begin-expr and end-expr are __range and
1312      //   __range + __bound, respectively, where __bound is the array bound. If
1313      //   _RangeT is an array of unknown size or an array of incomplete type,
1314      //   the program is ill-formed;
1315
1316      // begin-expr is __range.
1317      BeginExpr = RangeRef;
1318      if (FinishForRangeVarDecl(*this, BeginVar, RangeRef.get(), ColonLoc,
1319                                diag::err_for_range_iter_deduction_failure)) {
1320        NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1321        return StmtError();
1322      }
1323
1324      // Find the array bound.
1325      ExprResult BoundExpr;
1326      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
1327        BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
1328                                                 Context.getPointerDiffType(),
1329                                                 RangeLoc));
1330      else if (const VariableArrayType *VAT =
1331               dyn_cast<VariableArrayType>(UnqAT))
1332        BoundExpr = VAT->getSizeExpr();
1333      else {
1334        // Can't be a DependentSizedArrayType or an IncompleteArrayType since
1335        // UnqAT is not incomplete and Range is not type-dependent.
1336        assert(0 && "Unexpected array type in for-range");
1337        return StmtError();
1338      }
1339
1340      // end-expr is __range + __bound.
1341      EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, RangeRef.get(),
1342                           BoundExpr.get());
1343      if (EndExpr.isInvalid())
1344        return StmtError();
1345      if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
1346                                diag::err_for_range_iter_deduction_failure)) {
1347        NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1348        return StmtError();
1349      }
1350    } else {
1351      DeclarationNameInfo BeginNameInfo(&PP.getIdentifierTable().get("begin"),
1352                                        ColonLoc);
1353      DeclarationNameInfo EndNameInfo(&PP.getIdentifierTable().get("end"),
1354                                      ColonLoc);
1355
1356      LookupResult BeginMemberLookup(*this, BeginNameInfo, LookupMemberName);
1357      LookupResult EndMemberLookup(*this, EndNameInfo, LookupMemberName);
1358
1359      if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1360        // - if _RangeT is a class type, the unqualified-ids begin and end are
1361        //   looked up in the scope of class _RangeT as if by class member access
1362        //   lookup (3.4.5), and if either (or both) finds at least one
1363        //   declaration, begin-expr and end-expr are __range.begin() and
1364        //   __range.end(), respectively;
1365        LookupQualifiedName(BeginMemberLookup, D);
1366        LookupQualifiedName(EndMemberLookup, D);
1367
1368        if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1369          Diag(ColonLoc, diag::err_for_range_member_begin_end_mismatch)
1370            << RangeType << BeginMemberLookup.empty();
1371          return StmtError();
1372        }
1373      } else {
1374        // - otherwise, begin-expr and end-expr are begin(__range) and
1375        //   end(__range), respectively, where begin and end are looked up with
1376        //   argument-dependent lookup (3.4.2). For the purposes of this name
1377        //   lookup, namespace std is an associated namespace.
1378      }
1379
1380      BeginExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, BeginVar,
1381                                            BEF_begin, BeginNameInfo,
1382                                            BeginMemberLookup, RangeRef.get());
1383      if (BeginExpr.isInvalid())
1384        return StmtError();
1385
1386      EndExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, EndVar,
1387                                          BEF_end, EndNameInfo,
1388                                          EndMemberLookup, RangeRef.get());
1389      if (EndExpr.isInvalid())
1390        return StmtError();
1391    }
1392
1393    // C++0x [decl.spec.auto]p6: BeginType and EndType must be the same.
1394    QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
1395    if (!Context.hasSameType(BeginType, EndType)) {
1396      Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
1397        << BeginType << EndType;
1398      NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1399      NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1400    }
1401
1402    Decl *BeginEndDecls[] = { BeginVar, EndVar };
1403    // Claim the type doesn't contain auto: we've already done the checking.
1404    DeclGroupPtrTy BeginEndGroup =
1405      BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false);
1406    BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
1407
1408    ExprResult BeginRef = BuildDeclRefExpr(BeginVar,
1409                                           BeginType.getNonReferenceType(),
1410                                           VK_LValue, ColonLoc);
1411    ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
1412                                         VK_LValue, ColonLoc);
1413
1414    // Build and check __begin != __end expression.
1415    NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
1416                           BeginRef.get(), EndRef.get());
1417    NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
1418    NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
1419    if (NotEqExpr.isInvalid()) {
1420      NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1421      if (!Context.hasSameType(BeginType, EndType))
1422        NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1423      return StmtError();
1424    }
1425
1426    // Build and check ++__begin expression.
1427    IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
1428    IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
1429    if (IncrExpr.isInvalid()) {
1430      NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1431      return StmtError();
1432    }
1433
1434    // Build and check *__begin  expression.
1435    ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
1436    if (DerefExpr.isInvalid()) {
1437      NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1438      return StmtError();
1439    }
1440
1441    // Attach  *__begin  as initializer for VD.
1442    if (!LoopVar->isInvalidDecl()) {
1443      AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
1444                           /*TypeMayContainAuto=*/true);
1445      if (LoopVar->isInvalidDecl())
1446        NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1447    }
1448  } else {
1449    // The range is implicitly used as a placeholder when it is dependent.
1450    RangeVar->setUsed();
1451  }
1452
1453  return Owned(new (Context) CXXForRangeStmt(RangeDS,
1454                                     cast_or_null<DeclStmt>(BeginEndDecl.get()),
1455                                             NotEqExpr.take(), IncrExpr.take(),
1456                                             LoopVarDS, /*Body=*/0, ForLoc,
1457                                             ColonLoc, RParenLoc));
1458}
1459
1460/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
1461/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
1462/// body cannot be performed until after the type of the range variable is
1463/// determined.
1464StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
1465  if (!S || !B)
1466    return StmtError();
1467
1468  cast<CXXForRangeStmt>(S)->setBody(B);
1469  return S;
1470}
1471
1472StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
1473                               SourceLocation LabelLoc,
1474                               LabelDecl *TheDecl) {
1475  getCurFunction()->setHasBranchIntoScope();
1476  TheDecl->setUsed();
1477  return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
1478}
1479
1480StmtResult
1481Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
1482                            Expr *E) {
1483  // Convert operand to void*
1484  if (!E->isTypeDependent()) {
1485    QualType ETy = E->getType();
1486    QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
1487    ExprResult ExprRes = Owned(E);
1488    AssignConvertType ConvTy =
1489      CheckSingleAssignmentConstraints(DestTy, ExprRes);
1490    if (ExprRes.isInvalid())
1491      return StmtError();
1492    E = ExprRes.take();
1493    if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
1494      return StmtError();
1495  }
1496
1497  getCurFunction()->setHasIndirectGoto();
1498
1499  return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
1500}
1501
1502StmtResult
1503Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
1504  Scope *S = CurScope->getContinueParent();
1505  if (!S) {
1506    // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
1507    return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
1508  }
1509
1510  return Owned(new (Context) ContinueStmt(ContinueLoc));
1511}
1512
1513StmtResult
1514Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
1515  Scope *S = CurScope->getBreakParent();
1516  if (!S) {
1517    // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
1518    return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
1519  }
1520
1521  return Owned(new (Context) BreakStmt(BreakLoc));
1522}
1523
1524/// \brief Determine whether the given expression is a candidate for
1525/// copy elision in either a return statement or a throw expression.
1526///
1527/// \param ReturnType If we're determining the copy elision candidate for
1528/// a return statement, this is the return type of the function. If we're
1529/// determining the copy elision candidate for a throw expression, this will
1530/// be a NULL type.
1531///
1532/// \param E The expression being returned from the function or block, or
1533/// being thrown.
1534///
1535/// \param AllowFunctionParameter Whether we allow function parameters to
1536/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
1537/// we re-use this logic to determine whether we should try to move as part of
1538/// a return or throw (which does allow function parameters).
1539///
1540/// \returns The NRVO candidate variable, if the return statement may use the
1541/// NRVO, or NULL if there is no such candidate.
1542const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
1543                                             Expr *E,
1544                                             bool AllowFunctionParameter) {
1545  QualType ExprType = E->getType();
1546  // - in a return statement in a function with ...
1547  // ... a class return type ...
1548  if (!ReturnType.isNull()) {
1549    if (!ReturnType->isRecordType())
1550      return 0;
1551    // ... the same cv-unqualified type as the function return type ...
1552    if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
1553      return 0;
1554  }
1555
1556  // ... the expression is the name of a non-volatile automatic object
1557  // (other than a function or catch-clause parameter)) ...
1558  const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
1559  if (!DR)
1560    return 0;
1561  const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1562  if (!VD)
1563    return 0;
1564
1565  if (VD->hasLocalStorage() && !VD->isExceptionVariable() &&
1566      !VD->getType()->isReferenceType() && !VD->hasAttr<BlocksAttr>() &&
1567      !VD->getType().isVolatileQualified() &&
1568      ((VD->getKind() == Decl::Var) ||
1569       (AllowFunctionParameter && VD->getKind() == Decl::ParmVar)))
1570    return VD;
1571
1572  return 0;
1573}
1574
1575/// \brief Perform the initialization of a potentially-movable value, which
1576/// is the result of return value.
1577///
1578/// This routine implements C++0x [class.copy]p33, which attempts to treat
1579/// returned lvalues as rvalues in certain cases (to prefer move construction),
1580/// then falls back to treating them as lvalues if that failed.
1581ExprResult
1582Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
1583                                      const VarDecl *NRVOCandidate,
1584                                      QualType ResultType,
1585                                      Expr *Value,
1586                                      bool AllowNRVO) {
1587  // C++0x [class.copy]p33:
1588  //   When the criteria for elision of a copy operation are met or would
1589  //   be met save for the fact that the source object is a function
1590  //   parameter, and the object to be copied is designated by an lvalue,
1591  //   overload resolution to select the constructor for the copy is first
1592  //   performed as if the object were designated by an rvalue.
1593  ExprResult Res = ExprError();
1594  if (AllowNRVO &&
1595      (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
1596    ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
1597                              Value->getType(), CK_LValueToRValue,
1598                              Value, VK_XValue);
1599
1600    Expr *InitExpr = &AsRvalue;
1601    InitializationKind Kind
1602      = InitializationKind::CreateCopy(Value->getLocStart(),
1603                                       Value->getLocStart());
1604    InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
1605
1606    //   [...] If overload resolution fails, or if the type of the first
1607    //   parameter of the selected constructor is not an rvalue reference
1608    //   to the object's type (possibly cv-qualified), overload resolution
1609    //   is performed again, considering the object as an lvalue.
1610    if (Seq) {
1611      for (InitializationSequence::step_iterator Step = Seq.step_begin(),
1612           StepEnd = Seq.step_end();
1613           Step != StepEnd; ++Step) {
1614        if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
1615          continue;
1616
1617        CXXConstructorDecl *Constructor
1618        = cast<CXXConstructorDecl>(Step->Function.Function);
1619
1620        const RValueReferenceType *RRefType
1621          = Constructor->getParamDecl(0)->getType()
1622                                                 ->getAs<RValueReferenceType>();
1623
1624        // If we don't meet the criteria, break out now.
1625        if (!RRefType ||
1626            !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
1627                            Context.getTypeDeclType(Constructor->getParent())))
1628          break;
1629
1630        // Promote "AsRvalue" to the heap, since we now need this
1631        // expression node to persist.
1632        Value = ImplicitCastExpr::Create(Context, Value->getType(),
1633                                         CK_LValueToRValue, Value, 0,
1634                                         VK_XValue);
1635
1636        // Complete type-checking the initialization of the return type
1637        // using the constructor we found.
1638        Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
1639      }
1640    }
1641  }
1642
1643  // Either we didn't meet the criteria for treating an lvalue as an rvalue,
1644  // above, or overload resolution failed. Either way, we need to try
1645  // (again) now with the return value expression as written.
1646  if (Res.isInvalid())
1647    Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
1648
1649  return Res;
1650}
1651
1652/// ActOnBlockReturnStmt - Utility routine to figure out block's return type.
1653///
1654StmtResult
1655Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
1656  // If this is the first return we've seen in the block, infer the type of
1657  // the block from it.
1658  BlockScopeInfo *CurBlock = getCurBlock();
1659  if (CurBlock->ReturnType.isNull()) {
1660    if (RetValExp) {
1661      // Don't call UsualUnaryConversions(), since we don't want to do
1662      // integer promotions here.
1663      ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
1664      if (Result.isInvalid())
1665        return StmtError();
1666      RetValExp = Result.take();
1667
1668      if (!RetValExp->isTypeDependent()) {
1669        CurBlock->ReturnType = RetValExp->getType();
1670        if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) {
1671          // We have to remove a 'const' added to copied-in variable which was
1672          // part of the implementation spec. and not the actual qualifier for
1673          // the variable.
1674          if (CDRE->isConstQualAdded())
1675            CurBlock->ReturnType.removeLocalConst(); // FIXME: local???
1676        }
1677      } else
1678        CurBlock->ReturnType = Context.DependentTy;
1679    } else
1680      CurBlock->ReturnType = Context.VoidTy;
1681  }
1682  QualType FnRetType = CurBlock->ReturnType;
1683
1684  if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
1685    Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr)
1686      << getCurFunctionOrMethodDecl()->getDeclName();
1687    return StmtError();
1688  }
1689
1690  // Otherwise, verify that this result type matches the previous one.  We are
1691  // pickier with blocks than for normal functions because we don't have GCC
1692  // compatibility to worry about here.
1693  ReturnStmt *Result = 0;
1694  if (CurBlock->ReturnType->isVoidType()) {
1695    if (RetValExp && !RetValExp->isTypeDependent() &&
1696        (!getLangOptions().CPlusPlus || !RetValExp->getType()->isVoidType())) {
1697      Diag(ReturnLoc, diag::err_return_block_has_expr);
1698      RetValExp = 0;
1699    }
1700    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1701  } else if (!RetValExp) {
1702    if (!CurBlock->ReturnType->isDependentType())
1703      return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
1704
1705    Result = new (Context) ReturnStmt(ReturnLoc, 0, 0);
1706  } else {
1707    const VarDecl *NRVOCandidate = 0;
1708
1709    if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1710      // we have a non-void block with an expression, continue checking
1711
1712      // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1713      // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1714      // function return.
1715
1716      // In C++ the return statement is handled via a copy initialization.
1717      // the C version of which boils down to CheckSingleAssignmentConstraints.
1718      NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
1719      InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
1720                                                                     FnRetType,
1721                                                           NRVOCandidate != 0);
1722      ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
1723                                                       FnRetType, RetValExp);
1724      if (Res.isInvalid()) {
1725        // FIXME: Cleanup temporaries here, anyway?
1726        return StmtError();
1727      }
1728
1729      if (RetValExp) {
1730        CheckImplicitConversions(RetValExp, ReturnLoc);
1731        RetValExp = MaybeCreateExprWithCleanups(RetValExp);
1732      }
1733
1734      RetValExp = Res.takeAs<Expr>();
1735      if (RetValExp)
1736        CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
1737    }
1738
1739    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
1740  }
1741
1742  // If we need to check for the named return value optimization, save the
1743  // return statement in our scope for later processing.
1744  if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
1745      !CurContext->isDependentContext())
1746    FunctionScopes.back()->Returns.push_back(Result);
1747
1748  return Owned(Result);
1749}
1750
1751StmtResult
1752Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
1753  // Check for unexpanded parameter packs.
1754  if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
1755    return StmtError();
1756
1757  if (getCurBlock())
1758    return ActOnBlockReturnStmt(ReturnLoc, RetValExp);
1759
1760  QualType FnRetType;
1761  QualType DeclaredRetType;
1762  if (const FunctionDecl *FD = getCurFunctionDecl()) {
1763    FnRetType = FD->getResultType();
1764    DeclaredRetType = FnRetType;
1765    if (FD->hasAttr<NoReturnAttr>() ||
1766        FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
1767      Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
1768        << getCurFunctionOrMethodDecl()->getDeclName();
1769  } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
1770    DeclaredRetType = MD->getResultType();
1771    if (MD->hasRelatedResultType() && MD->getClassInterface()) {
1772      // In the implementation of a method with a related return type, the
1773      // type used to type-check the validity of return statements within the
1774      // method body is a pointer to the type of the class being implemented.
1775      FnRetType = Context.getObjCInterfaceType(MD->getClassInterface());
1776      FnRetType = Context.getObjCObjectPointerType(FnRetType);
1777    } else {
1778      FnRetType = DeclaredRetType;
1779    }
1780  } else // If we don't have a function/method context, bail.
1781    return StmtError();
1782
1783  ReturnStmt *Result = 0;
1784  if (FnRetType->isVoidType()) {
1785    if (RetValExp) {
1786      if (!RetValExp->isTypeDependent()) {
1787        // C99 6.8.6.4p1 (ext_ since GCC warns)
1788        unsigned D = diag::ext_return_has_expr;
1789        if (RetValExp->getType()->isVoidType())
1790          D = diag::ext_return_has_void_expr;
1791        else {
1792          ExprResult Result = Owned(RetValExp);
1793          Result = IgnoredValueConversions(Result.take());
1794          if (Result.isInvalid())
1795            return StmtError();
1796          RetValExp = Result.take();
1797          RetValExp = ImpCastExprToType(RetValExp,
1798                                        Context.VoidTy, CK_ToVoid).take();
1799        }
1800
1801        // return (some void expression); is legal in C++.
1802        if (D != diag::ext_return_has_void_expr ||
1803            !getLangOptions().CPlusPlus) {
1804          NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
1805
1806          int FunctionKind = 0;
1807          if (isa<ObjCMethodDecl>(CurDecl))
1808            FunctionKind = 1;
1809          else if (isa<CXXConstructorDecl>(CurDecl))
1810            FunctionKind = 2;
1811          else if (isa<CXXDestructorDecl>(CurDecl))
1812            FunctionKind = 3;
1813
1814          Diag(ReturnLoc, D)
1815            << CurDecl->getDeclName() << FunctionKind
1816            << RetValExp->getSourceRange();
1817        }
1818      }
1819
1820      CheckImplicitConversions(RetValExp, ReturnLoc);
1821      RetValExp = MaybeCreateExprWithCleanups(RetValExp);
1822    }
1823
1824    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1825  } else if (!RetValExp && !FnRetType->isDependentType()) {
1826    unsigned DiagID = diag::warn_return_missing_expr;  // C90 6.6.6.4p4
1827    // C99 6.8.6.4p1 (ext_ since GCC warns)
1828    if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr;
1829
1830    if (FunctionDecl *FD = getCurFunctionDecl())
1831      Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
1832    else
1833      Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
1834    Result = new (Context) ReturnStmt(ReturnLoc);
1835  } else {
1836    const VarDecl *NRVOCandidate = 0;
1837    if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1838      // we have a non-void function with an expression, continue checking
1839
1840      // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1841      // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1842      // function return.
1843
1844      // In C++ the return statement is handled via a copy initialization,
1845      // the C version of which boils down to CheckSingleAssignmentConstraints.
1846      NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
1847      InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
1848                                                                     FnRetType,
1849                                                            NRVOCandidate != 0);
1850      ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
1851                                                       FnRetType, RetValExp);
1852      if (Res.isInvalid()) {
1853        // FIXME: Cleanup temporaries here, anyway?
1854        return StmtError();
1855      }
1856
1857      RetValExp = Res.takeAs<Expr>();
1858      if (RetValExp)
1859        CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
1860    }
1861
1862    if (RetValExp) {
1863      // If we type-checked an Objective-C method's return type based
1864      // on a related return type, we may need to adjust the return
1865      // type again. Do so now.
1866      if (DeclaredRetType != FnRetType) {
1867        ExprResult result = PerformImplicitConversion(RetValExp,
1868                                                      DeclaredRetType,
1869                                                      AA_Returning);
1870        if (result.isInvalid()) return StmtError();
1871        RetValExp = result.take();
1872      }
1873
1874      CheckImplicitConversions(RetValExp, ReturnLoc);
1875      RetValExp = MaybeCreateExprWithCleanups(RetValExp);
1876    }
1877    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
1878  }
1879
1880  // If we need to check for the named return value optimization, save the
1881  // return statement in our scope for later processing.
1882  if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
1883      !CurContext->isDependentContext())
1884    FunctionScopes.back()->Returns.push_back(Result);
1885
1886  return Owned(Result);
1887}
1888
1889/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
1890/// ignore "noop" casts in places where an lvalue is required by an inline asm.
1891/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
1892/// provide a strong guidance to not use it.
1893///
1894/// This method checks to see if the argument is an acceptable l-value and
1895/// returns false if it is a case we can handle.
1896static bool CheckAsmLValue(const Expr *E, Sema &S) {
1897  // Type dependent expressions will be checked during instantiation.
1898  if (E->isTypeDependent())
1899    return false;
1900
1901  if (E->isLValue())
1902    return false;  // Cool, this is an lvalue.
1903
1904  // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
1905  // are supposed to allow.
1906  const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
1907  if (E != E2 && E2->isLValue()) {
1908    if (!S.getLangOptions().HeinousExtensions)
1909      S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
1910        << E->getSourceRange();
1911    else
1912      S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
1913        << E->getSourceRange();
1914    // Accept, even if we emitted an error diagnostic.
1915    return false;
1916  }
1917
1918  // None of the above, just randomly invalid non-lvalue.
1919  return true;
1920}
1921
1922/// isOperandMentioned - Return true if the specified operand # is mentioned
1923/// anywhere in the decomposed asm string.
1924static bool isOperandMentioned(unsigned OpNo,
1925                         ArrayRef<AsmStmt::AsmStringPiece> AsmStrPieces) {
1926  for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
1927    const AsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
1928    if (!Piece.isOperand()) continue;
1929
1930    // If this is a reference to the input and if the input was the smaller
1931    // one, then we have to reject this asm.
1932    if (Piece.getOperandNo() == OpNo)
1933      return true;
1934  }
1935
1936  return false;
1937}
1938
1939StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1940                              bool IsVolatile, unsigned NumOutputs,
1941                              unsigned NumInputs, IdentifierInfo **Names,
1942                              MultiExprArg constraints, MultiExprArg exprs,
1943                              Expr *asmString, MultiExprArg clobbers,
1944                              SourceLocation RParenLoc, bool MSAsm) {
1945  unsigned NumClobbers = clobbers.size();
1946  StringLiteral **Constraints =
1947    reinterpret_cast<StringLiteral**>(constraints.get());
1948  Expr **Exprs = exprs.get();
1949  StringLiteral *AsmString = cast<StringLiteral>(asmString);
1950  StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
1951
1952  SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1953
1954  // The parser verifies that there is a string literal here.
1955  if (!AsmString->isAscii())
1956    return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
1957      << AsmString->getSourceRange());
1958
1959  for (unsigned i = 0; i != NumOutputs; i++) {
1960    StringLiteral *Literal = Constraints[i];
1961    if (!Literal->isAscii())
1962      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1963        << Literal->getSourceRange());
1964
1965    StringRef OutputName;
1966    if (Names[i])
1967      OutputName = Names[i]->getName();
1968
1969    TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
1970    if (!Context.Target.validateOutputConstraint(Info))
1971      return StmtError(Diag(Literal->getLocStart(),
1972                            diag::err_asm_invalid_output_constraint)
1973                       << Info.getConstraintStr());
1974
1975    // Check that the output exprs are valid lvalues.
1976    Expr *OutputExpr = Exprs[i];
1977    if (CheckAsmLValue(OutputExpr, *this)) {
1978      return StmtError(Diag(OutputExpr->getLocStart(),
1979                  diag::err_asm_invalid_lvalue_in_output)
1980        << OutputExpr->getSourceRange());
1981    }
1982
1983    OutputConstraintInfos.push_back(Info);
1984  }
1985
1986  SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1987
1988  for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
1989    StringLiteral *Literal = Constraints[i];
1990    if (!Literal->isAscii())
1991      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1992        << Literal->getSourceRange());
1993
1994    StringRef InputName;
1995    if (Names[i])
1996      InputName = Names[i]->getName();
1997
1998    TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
1999    if (!Context.Target.validateInputConstraint(OutputConstraintInfos.data(),
2000                                                NumOutputs, Info)) {
2001      return StmtError(Diag(Literal->getLocStart(),
2002                            diag::err_asm_invalid_input_constraint)
2003                       << Info.getConstraintStr());
2004    }
2005
2006    Expr *InputExpr = Exprs[i];
2007
2008    // Only allow void types for memory constraints.
2009    if (Info.allowsMemory() && !Info.allowsRegister()) {
2010      if (CheckAsmLValue(InputExpr, *this))
2011        return StmtError(Diag(InputExpr->getLocStart(),
2012                              diag::err_asm_invalid_lvalue_in_input)
2013                         << Info.getConstraintStr()
2014                         << InputExpr->getSourceRange());
2015    }
2016
2017    if (Info.allowsRegister()) {
2018      if (InputExpr->getType()->isVoidType()) {
2019        return StmtError(Diag(InputExpr->getLocStart(),
2020                              diag::err_asm_invalid_type_in_input)
2021          << InputExpr->getType() << Info.getConstraintStr()
2022          << InputExpr->getSourceRange());
2023      }
2024    }
2025
2026    ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
2027    if (Result.isInvalid())
2028      return StmtError();
2029
2030    Exprs[i] = Result.take();
2031    InputConstraintInfos.push_back(Info);
2032  }
2033
2034  // Check that the clobbers are valid.
2035  for (unsigned i = 0; i != NumClobbers; i++) {
2036    StringLiteral *Literal = Clobbers[i];
2037    if (!Literal->isAscii())
2038      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2039        << Literal->getSourceRange());
2040
2041    StringRef Clobber = Literal->getString();
2042
2043    if (!Context.Target.isValidClobber(Clobber))
2044      return StmtError(Diag(Literal->getLocStart(),
2045                  diag::err_asm_unknown_register_name) << Clobber);
2046  }
2047
2048  AsmStmt *NS =
2049    new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm,
2050                          NumOutputs, NumInputs, Names, Constraints, Exprs,
2051                          AsmString, NumClobbers, Clobbers, RParenLoc);
2052  // Validate the asm string, ensuring it makes sense given the operands we
2053  // have.
2054  SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
2055  unsigned DiagOffs;
2056  if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
2057    Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
2058           << AsmString->getSourceRange();
2059    return StmtError();
2060  }
2061
2062  // Validate tied input operands for type mismatches.
2063  for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
2064    TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
2065
2066    // If this is a tied constraint, verify that the output and input have
2067    // either exactly the same type, or that they are int/ptr operands with the
2068    // same size (int/long, int*/long, are ok etc).
2069    if (!Info.hasTiedOperand()) continue;
2070
2071    unsigned TiedTo = Info.getTiedOperand();
2072    unsigned InputOpNo = i+NumOutputs;
2073    Expr *OutputExpr = Exprs[TiedTo];
2074    Expr *InputExpr = Exprs[InputOpNo];
2075    QualType InTy = InputExpr->getType();
2076    QualType OutTy = OutputExpr->getType();
2077    if (Context.hasSameType(InTy, OutTy))
2078      continue;  // All types can be tied to themselves.
2079
2080    // Decide if the input and output are in the same domain (integer/ptr or
2081    // floating point.
2082    enum AsmDomain {
2083      AD_Int, AD_FP, AD_Other
2084    } InputDomain, OutputDomain;
2085
2086    if (InTy->isIntegerType() || InTy->isPointerType())
2087      InputDomain = AD_Int;
2088    else if (InTy->isRealFloatingType())
2089      InputDomain = AD_FP;
2090    else
2091      InputDomain = AD_Other;
2092
2093    if (OutTy->isIntegerType() || OutTy->isPointerType())
2094      OutputDomain = AD_Int;
2095    else if (OutTy->isRealFloatingType())
2096      OutputDomain = AD_FP;
2097    else
2098      OutputDomain = AD_Other;
2099
2100    // They are ok if they are the same size and in the same domain.  This
2101    // allows tying things like:
2102    //   void* to int*
2103    //   void* to int            if they are the same size.
2104    //   double to long double   if they are the same size.
2105    //
2106    uint64_t OutSize = Context.getTypeSize(OutTy);
2107    uint64_t InSize = Context.getTypeSize(InTy);
2108    if (OutSize == InSize && InputDomain == OutputDomain &&
2109        InputDomain != AD_Other)
2110      continue;
2111
2112    // If the smaller input/output operand is not mentioned in the asm string,
2113    // then we can promote the smaller one to a larger input and the asm string
2114    // won't notice.
2115    bool SmallerValueMentioned = false;
2116
2117    // If this is a reference to the input and if the input was the smaller
2118    // one, then we have to reject this asm.
2119    if (isOperandMentioned(InputOpNo, Pieces)) {
2120      // This is a use in the asm string of the smaller operand.  Since we
2121      // codegen this by promoting to a wider value, the asm will get printed
2122      // "wrong".
2123      SmallerValueMentioned |= InSize < OutSize;
2124    }
2125    if (isOperandMentioned(TiedTo, Pieces)) {
2126      // If this is a reference to the output, and if the output is the larger
2127      // value, then it's ok because we'll promote the input to the larger type.
2128      SmallerValueMentioned |= OutSize < InSize;
2129    }
2130
2131    // If the smaller value wasn't mentioned in the asm string, and if the
2132    // output was a register, just extend the shorter one to the size of the
2133    // larger one.
2134    if (!SmallerValueMentioned && InputDomain != AD_Other &&
2135        OutputConstraintInfos[TiedTo].allowsRegister())
2136      continue;
2137
2138    // Either both of the operands were mentioned or the smaller one was
2139    // mentioned.  One more special case that we'll allow: if the tied input is
2140    // integer, unmentioned, and is a constant, then we'll allow truncating it
2141    // down to the size of the destination.
2142    if (InputDomain == AD_Int && OutputDomain == AD_Int &&
2143        !isOperandMentioned(InputOpNo, Pieces) &&
2144        InputExpr->isEvaluatable(Context)) {
2145      CastKind castKind =
2146        (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
2147      InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).take();
2148      Exprs[InputOpNo] = InputExpr;
2149      NS->setInputExpr(i, InputExpr);
2150      continue;
2151    }
2152
2153    Diag(InputExpr->getLocStart(),
2154         diag::err_asm_tying_incompatible_types)
2155      << InTy << OutTy << OutputExpr->getSourceRange()
2156      << InputExpr->getSourceRange();
2157    return StmtError();
2158  }
2159
2160  return Owned(NS);
2161}
2162
2163StmtResult
2164Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
2165                           SourceLocation RParen, Decl *Parm,
2166                           Stmt *Body) {
2167  VarDecl *Var = cast_or_null<VarDecl>(Parm);
2168  if (Var && Var->isInvalidDecl())
2169    return StmtError();
2170
2171  return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
2172}
2173
2174StmtResult
2175Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
2176  return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
2177}
2178
2179StmtResult
2180Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
2181                         MultiStmtArg CatchStmts, Stmt *Finally) {
2182  if (!getLangOptions().ObjCExceptions)
2183    Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
2184
2185  getCurFunction()->setHasBranchProtectedScope();
2186  unsigned NumCatchStmts = CatchStmts.size();
2187  return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
2188                                     CatchStmts.release(),
2189                                     NumCatchStmts,
2190                                     Finally));
2191}
2192
2193StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc,
2194                                                  Expr *Throw) {
2195  if (Throw) {
2196    Throw = MaybeCreateExprWithCleanups(Throw);
2197    ExprResult Result = DefaultLvalueConversion(Throw);
2198    if (Result.isInvalid())
2199      return StmtError();
2200
2201    Throw = Result.take();
2202    QualType ThrowType = Throw->getType();
2203    // Make sure the expression type is an ObjC pointer or "void *".
2204    if (!ThrowType->isDependentType() &&
2205        !ThrowType->isObjCObjectPointerType()) {
2206      const PointerType *PT = ThrowType->getAs<PointerType>();
2207      if (!PT || !PT->getPointeeType()->isVoidType())
2208        return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
2209                         << Throw->getType() << Throw->getSourceRange());
2210    }
2211  }
2212
2213  return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
2214}
2215
2216StmtResult
2217Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
2218                           Scope *CurScope) {
2219  if (!getLangOptions().ObjCExceptions)
2220    Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
2221
2222  if (!Throw) {
2223    // @throw without an expression designates a rethrow (which much occur
2224    // in the context of an @catch clause).
2225    Scope *AtCatchParent = CurScope;
2226    while (AtCatchParent && !AtCatchParent->isAtCatchScope())
2227      AtCatchParent = AtCatchParent->getParent();
2228    if (!AtCatchParent)
2229      return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
2230  }
2231
2232  return BuildObjCAtThrowStmt(AtLoc, Throw);
2233}
2234
2235StmtResult
2236Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
2237                                  Stmt *SyncBody) {
2238  getCurFunction()->setHasBranchProtectedScope();
2239
2240  ExprResult Result = DefaultLvalueConversion(SyncExpr);
2241  if (Result.isInvalid())
2242    return StmtError();
2243
2244  SyncExpr = Result.take();
2245  // Make sure the expression type is an ObjC pointer or "void *".
2246  if (!SyncExpr->getType()->isDependentType() &&
2247      !SyncExpr->getType()->isObjCObjectPointerType()) {
2248    const PointerType *PT = SyncExpr->getType()->getAs<PointerType>();
2249    if (!PT || !PT->getPointeeType()->isVoidType())
2250      return StmtError(Diag(AtLoc, diag::error_objc_synchronized_expects_object)
2251                       << SyncExpr->getType() << SyncExpr->getSourceRange());
2252  }
2253
2254  return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
2255}
2256
2257/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
2258/// and creates a proper catch handler from them.
2259StmtResult
2260Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
2261                         Stmt *HandlerBlock) {
2262  // There's nothing to test that ActOnExceptionDecl didn't already test.
2263  return Owned(new (Context) CXXCatchStmt(CatchLoc,
2264                                          cast_or_null<VarDecl>(ExDecl),
2265                                          HandlerBlock));
2266}
2267
2268StmtResult
2269Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
2270  getCurFunction()->setHasBranchProtectedScope();
2271  return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
2272}
2273
2274namespace {
2275
2276class TypeWithHandler {
2277  QualType t;
2278  CXXCatchStmt *stmt;
2279public:
2280  TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
2281  : t(type), stmt(statement) {}
2282
2283  // An arbitrary order is fine as long as it places identical
2284  // types next to each other.
2285  bool operator<(const TypeWithHandler &y) const {
2286    if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
2287      return true;
2288    if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
2289      return false;
2290    else
2291      return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
2292  }
2293
2294  bool operator==(const TypeWithHandler& other) const {
2295    return t == other.t;
2296  }
2297
2298  CXXCatchStmt *getCatchStmt() const { return stmt; }
2299  SourceLocation getTypeSpecStartLoc() const {
2300    return stmt->getExceptionDecl()->getTypeSpecStartLoc();
2301  }
2302};
2303
2304}
2305
2306/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
2307/// handlers and creates a try statement from them.
2308StmtResult
2309Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
2310                       MultiStmtArg RawHandlers) {
2311  // Don't report an error if 'try' is used in system headers.
2312  if (!getLangOptions().CXXExceptions &&
2313      !getSourceManager().isInSystemHeader(TryLoc))
2314      Diag(TryLoc, diag::err_exceptions_disabled) << "try";
2315
2316  unsigned NumHandlers = RawHandlers.size();
2317  assert(NumHandlers > 0 &&
2318         "The parser shouldn't call this if there are no handlers.");
2319  Stmt **Handlers = RawHandlers.get();
2320
2321  SmallVector<TypeWithHandler, 8> TypesWithHandlers;
2322
2323  for (unsigned i = 0; i < NumHandlers; ++i) {
2324    CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
2325    if (!Handler->getExceptionDecl()) {
2326      if (i < NumHandlers - 1)
2327        return StmtError(Diag(Handler->getLocStart(),
2328                              diag::err_early_catch_all));
2329
2330      continue;
2331    }
2332
2333    const QualType CaughtType = Handler->getCaughtType();
2334    const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
2335    TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
2336  }
2337
2338  // Detect handlers for the same type as an earlier one.
2339  if (NumHandlers > 1) {
2340    llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
2341
2342    TypeWithHandler prev = TypesWithHandlers[0];
2343    for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
2344      TypeWithHandler curr = TypesWithHandlers[i];
2345
2346      if (curr == prev) {
2347        Diag(curr.getTypeSpecStartLoc(),
2348             diag::warn_exception_caught_by_earlier_handler)
2349          << curr.getCatchStmt()->getCaughtType().getAsString();
2350        Diag(prev.getTypeSpecStartLoc(),
2351             diag::note_previous_exception_handler)
2352          << prev.getCatchStmt()->getCaughtType().getAsString();
2353      }
2354
2355      prev = curr;
2356    }
2357  }
2358
2359  getCurFunction()->setHasBranchProtectedScope();
2360
2361  // FIXME: We should detect handlers that cannot catch anything because an
2362  // earlier handler catches a superclass. Need to find a method that is not
2363  // quadratic for this.
2364  // Neither of these are explicitly forbidden, but every compiler detects them
2365  // and warns.
2366
2367  return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
2368                                  Handlers, NumHandlers));
2369}
2370
2371StmtResult
2372Sema::ActOnSEHTryBlock(bool IsCXXTry,
2373                       SourceLocation TryLoc,
2374                       Stmt *TryBlock,
2375                       Stmt *Handler) {
2376  assert(TryBlock && Handler);
2377
2378  getCurFunction()->setHasBranchProtectedScope();
2379
2380  return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
2381}
2382
2383StmtResult
2384Sema::ActOnSEHExceptBlock(SourceLocation Loc,
2385                          Expr *FilterExpr,
2386                          Stmt *Block) {
2387  assert(FilterExpr && Block);
2388
2389  if(!FilterExpr->getType()->isIntegerType()) {
2390    return StmtError(Diag(FilterExpr->getExprLoc(),
2391                     diag::err_filter_expression_integral)
2392                     << FilterExpr->getType());
2393  }
2394
2395  return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
2396}
2397
2398StmtResult
2399Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
2400                           Stmt *Block) {
2401  assert(Block);
2402  return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
2403}
2404