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