SemaStmt.cpp revision d86c477fb5d3fc34864afecbbb5443da9355e8fb
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/// \brief Determine whether a return statement is a candidate for the named
1062/// return value optimization (C++0x 12.8p34, bullet 1).
1063///
1064/// \param Ctx The context in which the return expression and type occur.
1065///
1066/// \param RetType The return type of the function or block.
1067///
1068/// \param RetExpr The expression being returned from the function or block.
1069///
1070/// \returns The NRVO candidate variable, if the return statement may use the
1071/// NRVO, or NULL if there is no such candidate.
1072static const VarDecl *getNRVOCandidate(ASTContext &Ctx, QualType RetType,
1073                                       Expr *RetExpr) {
1074  QualType ExprType = RetExpr->getType();
1075  // - in a return statement in a function with ...
1076  // ... a class return type ...
1077  if (!RetType->isRecordType())
1078    return 0;
1079  // ... the same cv-unqualified type as the function return type ...
1080  if (!Ctx.hasSameUnqualifiedType(RetType, ExprType))
1081    return 0;
1082  // ... the expression is the name of a non-volatile automatic object ...
1083  // We ignore parentheses here.
1084  // FIXME: Is this compliant? (Everyone else does it)
1085  const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetExpr->IgnoreParens());
1086  if (!DR)
1087    return 0;
1088  const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1089  if (!VD)
1090    return 0;
1091
1092  if (VD->getKind() == Decl::Var && VD->hasLocalStorage() &&
1093      !VD->getType()->isReferenceType() && !VD->hasAttr<BlocksAttr>() &&
1094      !VD->getType().isVolatileQualified())
1095    return VD;
1096
1097  return 0;
1098}
1099
1100/// ActOnBlockReturnStmt - Utility routine to figure out block's return type.
1101///
1102Action::OwningStmtResult
1103Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
1104  // If this is the first return we've seen in the block, infer the type of
1105  // the block from it.
1106  BlockScopeInfo *CurBlock = getCurBlock();
1107  if (CurBlock->ReturnType.isNull()) {
1108    if (RetValExp) {
1109      // Don't call UsualUnaryConversions(), since we don't want to do
1110      // integer promotions here.
1111      DefaultFunctionArrayLvalueConversion(RetValExp);
1112      CurBlock->ReturnType = RetValExp->getType();
1113      if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) {
1114        // We have to remove a 'const' added to copied-in variable which was
1115        // part of the implementation spec. and not the actual qualifier for
1116        // the variable.
1117        if (CDRE->isConstQualAdded())
1118           CurBlock->ReturnType.removeConst();
1119      }
1120    } else
1121      CurBlock->ReturnType = Context.VoidTy;
1122  }
1123  QualType FnRetType = CurBlock->ReturnType;
1124
1125  if (CurBlock->TheDecl->hasAttr<NoReturnAttr>()) {
1126    Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr)
1127      << getCurFunctionOrMethodDecl()->getDeclName();
1128    return StmtError();
1129  }
1130
1131  // Otherwise, verify that this result type matches the previous one.  We are
1132  // pickier with blocks than for normal functions because we don't have GCC
1133  // compatibility to worry about here.
1134  ReturnStmt *Result = 0;
1135  if (CurBlock->ReturnType->isVoidType()) {
1136    if (RetValExp) {
1137      Diag(ReturnLoc, diag::err_return_block_has_expr);
1138      RetValExp->Destroy(Context);
1139      RetValExp = 0;
1140    }
1141    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1142  } else if (!RetValExp) {
1143    return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
1144  } else {
1145    const VarDecl *NRVOCandidate = 0;
1146
1147    if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1148      // we have a non-void block with an expression, continue checking
1149
1150      // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1151      // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1152      // function return.
1153
1154      // In C++ the return statement is handled via a copy initialization.
1155      // the C version of which boils down to CheckSingleAssignmentConstraints.
1156      NRVOCandidate = getNRVOCandidate(Context, FnRetType, RetValExp);
1157      OwningExprResult Res = PerformCopyInitialization(
1158                               InitializedEntity::InitializeResult(ReturnLoc,
1159                                                                   FnRetType,
1160                                                            NRVOCandidate != 0),
1161                               SourceLocation(),
1162                               Owned(RetValExp));
1163      if (Res.isInvalid()) {
1164        // FIXME: Cleanup temporaries here, anyway?
1165        return StmtError();
1166      }
1167
1168      if (RetValExp)
1169        RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp);
1170
1171      RetValExp = Res.takeAs<Expr>();
1172      if (RetValExp)
1173        CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
1174    }
1175
1176    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
1177  }
1178
1179  // If we need to check for the named return value optimization, save the
1180  // return statement in our scope for later processing.
1181  if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
1182      !CurContext->isDependentContext())
1183    FunctionScopes.back()->Returns.push_back(Result);
1184
1185  return Owned(Result);
1186}
1187
1188Action::OwningStmtResult
1189Sema::ActOnReturnStmt(SourceLocation ReturnLoc, ExprArg rex) {
1190  Expr *RetValExp = rex.takeAs<Expr>();
1191  if (getCurBlock())
1192    return ActOnBlockReturnStmt(ReturnLoc, RetValExp);
1193
1194  QualType FnRetType;
1195  if (const FunctionDecl *FD = getCurFunctionDecl()) {
1196    FnRetType = FD->getResultType();
1197    if (FD->hasAttr<NoReturnAttr>() ||
1198        FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
1199      Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
1200        << getCurFunctionOrMethodDecl()->getDeclName();
1201  } else if (ObjCMethodDecl *MD = getCurMethodDecl())
1202    FnRetType = MD->getResultType();
1203  else // If we don't have a function/method context, bail.
1204    return StmtError();
1205
1206  ReturnStmt *Result = 0;
1207  if (FnRetType->isVoidType()) {
1208    if (RetValExp && !RetValExp->isTypeDependent()) {
1209      // C99 6.8.6.4p1 (ext_ since GCC warns)
1210      unsigned D = diag::ext_return_has_expr;
1211      if (RetValExp->getType()->isVoidType())
1212        D = diag::ext_return_has_void_expr;
1213
1214      // return (some void expression); is legal in C++.
1215      if (D != diag::ext_return_has_void_expr ||
1216          !getLangOptions().CPlusPlus) {
1217        NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
1218        Diag(ReturnLoc, D)
1219          << CurDecl->getDeclName() << isa<ObjCMethodDecl>(CurDecl)
1220          << RetValExp->getSourceRange();
1221      }
1222
1223      RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp);
1224    }
1225
1226    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1227  } else if (!RetValExp && !FnRetType->isDependentType()) {
1228    unsigned DiagID = diag::warn_return_missing_expr;  // C90 6.6.6.4p4
1229    // C99 6.8.6.4p1 (ext_ since GCC warns)
1230    if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr;
1231
1232    if (FunctionDecl *FD = getCurFunctionDecl())
1233      Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
1234    else
1235      Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
1236    Result = new (Context) ReturnStmt(ReturnLoc);
1237  } else {
1238    const VarDecl *NRVOCandidate = 0;
1239    if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1240      // we have a non-void function with an expression, continue checking
1241
1242      // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1243      // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1244      // function return.
1245
1246      // In C++ the return statement is handled via a copy initialization.
1247      // the C version of which boils down to CheckSingleAssignmentConstraints.
1248      NRVOCandidate = getNRVOCandidate(Context, FnRetType, RetValExp);
1249      OwningExprResult Res = PerformCopyInitialization(
1250                               InitializedEntity::InitializeResult(ReturnLoc,
1251                                                                   FnRetType,
1252                                                            NRVOCandidate != 0),
1253                               SourceLocation(),
1254                               Owned(RetValExp));
1255      if (Res.isInvalid()) {
1256        // FIXME: Cleanup temporaries here, anyway?
1257        return StmtError();
1258      }
1259
1260      RetValExp = Res.takeAs<Expr>();
1261      if (RetValExp)
1262        CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
1263    }
1264
1265    if (RetValExp)
1266      RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp);
1267    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
1268  }
1269
1270  // If we need to check for the named return value optimization, save the
1271  // return statement in our scope for later processing.
1272  if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
1273      !CurContext->isDependentContext())
1274    FunctionScopes.back()->Returns.push_back(Result);
1275
1276  return Owned(Result);
1277}
1278
1279/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
1280/// ignore "noop" casts in places where an lvalue is required by an inline asm.
1281/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
1282/// provide a strong guidance to not use it.
1283///
1284/// This method checks to see if the argument is an acceptable l-value and
1285/// returns false if it is a case we can handle.
1286static bool CheckAsmLValue(const Expr *E, Sema &S) {
1287  // Type dependent expressions will be checked during instantiation.
1288  if (E->isTypeDependent())
1289    return false;
1290
1291  if (E->isLvalue(S.Context) == Expr::LV_Valid)
1292    return false;  // Cool, this is an lvalue.
1293
1294  // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
1295  // are supposed to allow.
1296  const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
1297  if (E != E2 && E2->isLvalue(S.Context) == Expr::LV_Valid) {
1298    if (!S.getLangOptions().HeinousExtensions)
1299      S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
1300        << E->getSourceRange();
1301    else
1302      S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
1303        << E->getSourceRange();
1304    // Accept, even if we emitted an error diagnostic.
1305    return false;
1306  }
1307
1308  // None of the above, just randomly invalid non-lvalue.
1309  return true;
1310}
1311
1312
1313Sema::OwningStmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc,
1314                                          bool IsSimple,
1315                                          bool IsVolatile,
1316                                          unsigned NumOutputs,
1317                                          unsigned NumInputs,
1318                                          IdentifierInfo **Names,
1319                                          MultiExprArg constraints,
1320                                          MultiExprArg exprs,
1321                                          ExprArg asmString,
1322                                          MultiExprArg clobbers,
1323                                          SourceLocation RParenLoc,
1324                                          bool MSAsm) {
1325  unsigned NumClobbers = clobbers.size();
1326  StringLiteral **Constraints =
1327    reinterpret_cast<StringLiteral**>(constraints.get());
1328  Expr **Exprs = reinterpret_cast<Expr **>(exprs.get());
1329  StringLiteral *AsmString = cast<StringLiteral>((Expr *)asmString.get());
1330  StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
1331
1332  llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1333
1334  // The parser verifies that there is a string literal here.
1335  if (AsmString->isWide())
1336    return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
1337      << AsmString->getSourceRange());
1338
1339  for (unsigned i = 0; i != NumOutputs; i++) {
1340    StringLiteral *Literal = Constraints[i];
1341    if (Literal->isWide())
1342      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1343        << Literal->getSourceRange());
1344
1345    llvm::StringRef OutputName;
1346    if (Names[i])
1347      OutputName = Names[i]->getName();
1348
1349    TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
1350    if (!Context.Target.validateOutputConstraint(Info))
1351      return StmtError(Diag(Literal->getLocStart(),
1352                            diag::err_asm_invalid_output_constraint)
1353                       << Info.getConstraintStr());
1354
1355    // Check that the output exprs are valid lvalues.
1356    Expr *OutputExpr = Exprs[i];
1357    if (CheckAsmLValue(OutputExpr, *this)) {
1358      return StmtError(Diag(OutputExpr->getLocStart(),
1359                  diag::err_asm_invalid_lvalue_in_output)
1360        << OutputExpr->getSourceRange());
1361    }
1362
1363    OutputConstraintInfos.push_back(Info);
1364  }
1365
1366  llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1367
1368  for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
1369    StringLiteral *Literal = Constraints[i];
1370    if (Literal->isWide())
1371      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1372        << Literal->getSourceRange());
1373
1374    llvm::StringRef InputName;
1375    if (Names[i])
1376      InputName = Names[i]->getName();
1377
1378    TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
1379    if (!Context.Target.validateInputConstraint(OutputConstraintInfos.data(),
1380                                                NumOutputs, Info)) {
1381      return StmtError(Diag(Literal->getLocStart(),
1382                            diag::err_asm_invalid_input_constraint)
1383                       << Info.getConstraintStr());
1384    }
1385
1386    Expr *InputExpr = Exprs[i];
1387
1388    // Only allow void types for memory constraints.
1389    if (Info.allowsMemory() && !Info.allowsRegister()) {
1390      if (CheckAsmLValue(InputExpr, *this))
1391        return StmtError(Diag(InputExpr->getLocStart(),
1392                              diag::err_asm_invalid_lvalue_in_input)
1393                         << Info.getConstraintStr()
1394                         << InputExpr->getSourceRange());
1395    }
1396
1397    if (Info.allowsRegister()) {
1398      if (InputExpr->getType()->isVoidType()) {
1399        return StmtError(Diag(InputExpr->getLocStart(),
1400                              diag::err_asm_invalid_type_in_input)
1401          << InputExpr->getType() << Info.getConstraintStr()
1402          << InputExpr->getSourceRange());
1403      }
1404    }
1405
1406    DefaultFunctionArrayLvalueConversion(Exprs[i]);
1407
1408    InputConstraintInfos.push_back(Info);
1409  }
1410
1411  // Check that the clobbers are valid.
1412  for (unsigned i = 0; i != NumClobbers; i++) {
1413    StringLiteral *Literal = Clobbers[i];
1414    if (Literal->isWide())
1415      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1416        << Literal->getSourceRange());
1417
1418    llvm::StringRef Clobber = Literal->getString();
1419
1420    if (!Context.Target.isValidGCCRegisterName(Clobber))
1421      return StmtError(Diag(Literal->getLocStart(),
1422                  diag::err_asm_unknown_register_name) << Clobber);
1423  }
1424
1425  constraints.release();
1426  exprs.release();
1427  asmString.release();
1428  clobbers.release();
1429  AsmStmt *NS =
1430    new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm,
1431                          NumOutputs, NumInputs, Names, Constraints, Exprs,
1432                          AsmString, NumClobbers, Clobbers, RParenLoc);
1433  // Validate the asm string, ensuring it makes sense given the operands we
1434  // have.
1435  llvm::SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
1436  unsigned DiagOffs;
1437  if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
1438    Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
1439           << AsmString->getSourceRange();
1440    DeleteStmt(NS);
1441    return StmtError();
1442  }
1443
1444  // Validate tied input operands for type mismatches.
1445  for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
1446    TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1447
1448    // If this is a tied constraint, verify that the output and input have
1449    // either exactly the same type, or that they are int/ptr operands with the
1450    // same size (int/long, int*/long, are ok etc).
1451    if (!Info.hasTiedOperand()) continue;
1452
1453    unsigned TiedTo = Info.getTiedOperand();
1454    Expr *OutputExpr = Exprs[TiedTo];
1455    Expr *InputExpr = Exprs[i+NumOutputs];
1456    QualType InTy = InputExpr->getType();
1457    QualType OutTy = OutputExpr->getType();
1458    if (Context.hasSameType(InTy, OutTy))
1459      continue;  // All types can be tied to themselves.
1460
1461    // Decide if the input and output are in the same domain (integer/ptr or
1462    // floating point.
1463    enum AsmDomain {
1464      AD_Int, AD_FP, AD_Other
1465    } InputDomain, OutputDomain;
1466
1467    if (InTy->isIntegerType() || InTy->isPointerType())
1468      InputDomain = AD_Int;
1469    else if (InTy->isFloatingType())
1470      InputDomain = AD_FP;
1471    else
1472      InputDomain = AD_Other;
1473
1474    if (OutTy->isIntegerType() || OutTy->isPointerType())
1475      OutputDomain = AD_Int;
1476    else if (OutTy->isFloatingType())
1477      OutputDomain = AD_FP;
1478    else
1479      OutputDomain = AD_Other;
1480
1481    // They are ok if they are the same size and in the same domain.  This
1482    // allows tying things like:
1483    //   void* to int*
1484    //   void* to int            if they are the same size.
1485    //   double to long double   if they are the same size.
1486    //
1487    uint64_t OutSize = Context.getTypeSize(OutTy);
1488    uint64_t InSize = Context.getTypeSize(InTy);
1489    if (OutSize == InSize && InputDomain == OutputDomain &&
1490        InputDomain != AD_Other)
1491      continue;
1492
1493    // If the smaller input/output operand is not mentioned in the asm string,
1494    // then we can promote it and the asm string won't notice.  Check this
1495    // case now.
1496    bool SmallerValueMentioned = false;
1497    for (unsigned p = 0, e = Pieces.size(); p != e; ++p) {
1498      AsmStmt::AsmStringPiece &Piece = Pieces[p];
1499      if (!Piece.isOperand()) continue;
1500
1501      // If this is a reference to the input and if the input was the smaller
1502      // one, then we have to reject this asm.
1503      if (Piece.getOperandNo() == i+NumOutputs) {
1504        if (InSize < OutSize) {
1505          SmallerValueMentioned = true;
1506          break;
1507        }
1508      }
1509
1510      // If this is a reference to the input and if the input was the smaller
1511      // one, then we have to reject this asm.
1512      if (Piece.getOperandNo() == TiedTo) {
1513        if (InSize > OutSize) {
1514          SmallerValueMentioned = true;
1515          break;
1516        }
1517      }
1518    }
1519
1520    // If the smaller value wasn't mentioned in the asm string, and if the
1521    // output was a register, just extend the shorter one to the size of the
1522    // larger one.
1523    if (!SmallerValueMentioned && InputDomain != AD_Other &&
1524        OutputConstraintInfos[TiedTo].allowsRegister())
1525      continue;
1526
1527    Diag(InputExpr->getLocStart(),
1528         diag::err_asm_tying_incompatible_types)
1529      << InTy << OutTy << OutputExpr->getSourceRange()
1530      << InputExpr->getSourceRange();
1531    DeleteStmt(NS);
1532    return StmtError();
1533  }
1534
1535  return Owned(NS);
1536}
1537
1538Action::OwningStmtResult
1539Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
1540                           SourceLocation RParen, DeclPtrTy Parm,
1541                           StmtArg Body) {
1542  VarDecl *Var = cast_or_null<VarDecl>(Parm.getAs<Decl>());
1543  if (Var && Var->isInvalidDecl())
1544    return StmtError();
1545
1546  return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var,
1547                                             Body.takeAs<Stmt>()));
1548}
1549
1550Action::OwningStmtResult
1551Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, StmtArg Body) {
1552  return Owned(new (Context) ObjCAtFinallyStmt(AtLoc,
1553                                           static_cast<Stmt*>(Body.release())));
1554}
1555
1556Action::OwningStmtResult
1557Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, StmtArg Try,
1558                         MultiStmtArg CatchStmts, StmtArg Finally) {
1559  FunctionNeedsScopeChecking() = true;
1560  unsigned NumCatchStmts = CatchStmts.size();
1561  return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try.takeAs<Stmt>(),
1562                                     (Stmt **)CatchStmts.release(),
1563                                     NumCatchStmts,
1564                                     Finally.takeAs<Stmt>()));
1565}
1566
1567Sema::OwningStmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc,
1568                                                  ExprArg ThrowE) {
1569  Expr *Throw = static_cast<Expr *>(ThrowE.get());
1570  if (Throw) {
1571    QualType ThrowType = Throw->getType();
1572    // Make sure the expression type is an ObjC pointer or "void *".
1573    if (!ThrowType->isDependentType() &&
1574        !ThrowType->isObjCObjectPointerType()) {
1575      const PointerType *PT = ThrowType->getAs<PointerType>();
1576      if (!PT || !PT->getPointeeType()->isVoidType())
1577        return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
1578                         << Throw->getType() << Throw->getSourceRange());
1579    }
1580  }
1581
1582  return Owned(new (Context) ObjCAtThrowStmt(AtLoc, ThrowE.takeAs<Expr>()));
1583}
1584
1585Action::OwningStmtResult
1586Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, ExprArg Throw,
1587                           Scope *CurScope) {
1588  if (!Throw.get()) {
1589    // @throw without an expression designates a rethrow (which much occur
1590    // in the context of an @catch clause).
1591    Scope *AtCatchParent = CurScope;
1592    while (AtCatchParent && !AtCatchParent->isAtCatchScope())
1593      AtCatchParent = AtCatchParent->getParent();
1594    if (!AtCatchParent)
1595      return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
1596  }
1597
1598  return BuildObjCAtThrowStmt(AtLoc, move(Throw));
1599}
1600
1601Action::OwningStmtResult
1602Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, ExprArg SynchExpr,
1603                                  StmtArg SynchBody) {
1604  FunctionNeedsScopeChecking() = true;
1605
1606  // Make sure the expression type is an ObjC pointer or "void *".
1607  Expr *SyncExpr = static_cast<Expr*>(SynchExpr.get());
1608  if (!SyncExpr->getType()->isDependentType() &&
1609      !SyncExpr->getType()->isObjCObjectPointerType()) {
1610    const PointerType *PT = SyncExpr->getType()->getAs<PointerType>();
1611    if (!PT || !PT->getPointeeType()->isVoidType())
1612      return StmtError(Diag(AtLoc, diag::error_objc_synchronized_expects_object)
1613                       << SyncExpr->getType() << SyncExpr->getSourceRange());
1614  }
1615
1616  return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc,
1617                                                    SynchExpr.takeAs<Stmt>(),
1618                                                    SynchBody.takeAs<Stmt>()));
1619}
1620
1621/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
1622/// and creates a proper catch handler from them.
1623Action::OwningStmtResult
1624Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, DeclPtrTy ExDecl,
1625                         StmtArg HandlerBlock) {
1626  // There's nothing to test that ActOnExceptionDecl didn't already test.
1627  return Owned(new (Context) CXXCatchStmt(CatchLoc,
1628                                  cast_or_null<VarDecl>(ExDecl.getAs<Decl>()),
1629                                          HandlerBlock.takeAs<Stmt>()));
1630}
1631
1632class TypeWithHandler {
1633  QualType t;
1634  CXXCatchStmt *stmt;
1635public:
1636  TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
1637  : t(type), stmt(statement) {}
1638
1639  // An arbitrary order is fine as long as it places identical
1640  // types next to each other.
1641  bool operator<(const TypeWithHandler &y) const {
1642    if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
1643      return true;
1644    if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
1645      return false;
1646    else
1647      return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
1648  }
1649
1650  bool operator==(const TypeWithHandler& other) const {
1651    return t == other.t;
1652  }
1653
1654  QualType getQualType() const { return t; }
1655  CXXCatchStmt *getCatchStmt() const { return stmt; }
1656  SourceLocation getTypeSpecStartLoc() const {
1657    return stmt->getExceptionDecl()->getTypeSpecStartLoc();
1658  }
1659};
1660
1661/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
1662/// handlers and creates a try statement from them.
1663Action::OwningStmtResult
1664Sema::ActOnCXXTryBlock(SourceLocation TryLoc, StmtArg TryBlock,
1665                       MultiStmtArg RawHandlers) {
1666  unsigned NumHandlers = RawHandlers.size();
1667  assert(NumHandlers > 0 &&
1668         "The parser shouldn't call this if there are no handlers.");
1669  Stmt **Handlers = reinterpret_cast<Stmt**>(RawHandlers.get());
1670
1671  llvm::SmallVector<TypeWithHandler, 8> TypesWithHandlers;
1672
1673  for (unsigned i = 0; i < NumHandlers; ++i) {
1674    CXXCatchStmt *Handler = llvm::cast<CXXCatchStmt>(Handlers[i]);
1675    if (!Handler->getExceptionDecl()) {
1676      if (i < NumHandlers - 1)
1677        return StmtError(Diag(Handler->getLocStart(),
1678                              diag::err_early_catch_all));
1679
1680      continue;
1681    }
1682
1683    const QualType CaughtType = Handler->getCaughtType();
1684    const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
1685    TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
1686  }
1687
1688  // Detect handlers for the same type as an earlier one.
1689  if (NumHandlers > 1) {
1690    llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
1691
1692    TypeWithHandler prev = TypesWithHandlers[0];
1693    for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
1694      TypeWithHandler curr = TypesWithHandlers[i];
1695
1696      if (curr == prev) {
1697        Diag(curr.getTypeSpecStartLoc(),
1698             diag::warn_exception_caught_by_earlier_handler)
1699          << curr.getCatchStmt()->getCaughtType().getAsString();
1700        Diag(prev.getTypeSpecStartLoc(),
1701             diag::note_previous_exception_handler)
1702          << prev.getCatchStmt()->getCaughtType().getAsString();
1703      }
1704
1705      prev = curr;
1706    }
1707  }
1708
1709  // FIXME: We should detect handlers that cannot catch anything because an
1710  // earlier handler catches a superclass. Need to find a method that is not
1711  // quadratic for this.
1712  // Neither of these are explicitly forbidden, but every compiler detects them
1713  // and warns.
1714
1715  FunctionNeedsScopeChecking() = true;
1716  RawHandlers.release();
1717  return Owned(CXXTryStmt::Create(Context, TryLoc,
1718                                  static_cast<Stmt*>(TryBlock.release()),
1719                                  Handlers, NumHandlers));
1720}
1721