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