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