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