SemaStmt.cpp revision be3d0dbf2e8d2f93191ff4c023dd3bbf8f859d5a
1//===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements semantic analysis for statements.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Sema/SemaInternal.h"
15#include "clang/Sema/Scope.h"
16#include "clang/Sema/ScopeInfo.h"
17#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
19#include "clang/AST/ASTContext.h"
20#include "clang/AST/CharUnits.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/EvaluatedExprVisitor.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/ExprObjC.h"
25#include "clang/AST/StmtObjC.h"
26#include "clang/AST/StmtCXX.h"
27#include "clang/AST/TypeLoc.h"
28#include "clang/Lex/Preprocessor.h"
29#include "clang/Basic/TargetInfo.h"
30#include "llvm/ADT/ArrayRef.h"
31#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/SmallPtrSet.h"
33#include "llvm/ADT/SmallString.h"
34#include "llvm/ADT/SmallVector.h"
35#include "llvm/Support/TargetSelect.h"
36using namespace clang;
37using namespace sema;
38
39StmtResult Sema::ActOnExprStmt(FullExprArg expr) {
40  Expr *E = expr.get();
41  if (!E) // FIXME: FullExprArg has no error state?
42    return StmtError();
43
44  // C99 6.8.3p2: The expression in an expression statement is evaluated as a
45  // void expression for its side effects.  Conversion to void allows any
46  // operand, even incomplete types.
47
48  // Same thing in for stmt first clause (when expr) and third clause.
49  return Owned(static_cast<Stmt*>(E));
50}
51
52
53StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
54                               bool HasLeadingEmptyMacro) {
55  return Owned(new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro));
56}
57
58StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
59                               SourceLocation EndLoc) {
60  DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
61
62  // If we have an invalid decl, just return an error.
63  if (DG.isNull()) return StmtError();
64
65  return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
66}
67
68void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
69  DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
70
71  // If we have an invalid decl, just return.
72  if (DG.isNull() || !DG.isSingleDecl()) return;
73  VarDecl *var = cast<VarDecl>(DG.getSingleDecl());
74
75  // suppress any potential 'unused variable' warning.
76  var->setUsed();
77
78  // foreach variables are never actually initialized in the way that
79  // the parser came up with.
80  var->setInit(0);
81
82  // In ARC, we don't need to retain the iteration variable of a fast
83  // enumeration loop.  Rather than actually trying to catch that
84  // during declaration processing, we remove the consequences here.
85  if (getLangOpts().ObjCAutoRefCount) {
86    QualType type = var->getType();
87
88    // Only do this if we inferred the lifetime.  Inferred lifetime
89    // will show up as a local qualifier because explicit lifetime
90    // should have shown up as an AttributedType instead.
91    if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
92      // Add 'const' and mark the variable as pseudo-strong.
93      var->setType(type.withConst());
94      var->setARCPseudoStrong(true);
95    }
96  }
97}
98
99/// \brief Diagnose unused '==' and '!=' as likely typos for '=' or '|='.
100///
101/// Adding a cast to void (or other expression wrappers) will prevent the
102/// warning from firing.
103static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
104  SourceLocation Loc;
105  bool IsNotEqual, CanAssign;
106
107  if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
108    if (Op->getOpcode() != BO_EQ && Op->getOpcode() != BO_NE)
109      return false;
110
111    Loc = Op->getOperatorLoc();
112    IsNotEqual = Op->getOpcode() == BO_NE;
113    CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
114  } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
115    if (Op->getOperator() != OO_EqualEqual &&
116        Op->getOperator() != OO_ExclaimEqual)
117      return false;
118
119    Loc = Op->getOperatorLoc();
120    IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
121    CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
122  } else {
123    // Not a typo-prone comparison.
124    return false;
125  }
126
127  // Suppress warnings when the operator, suspicious as it may be, comes from
128  // a macro expansion.
129  if (Loc.isMacroID())
130    return false;
131
132  S.Diag(Loc, diag::warn_unused_comparison)
133    << (unsigned)IsNotEqual << E->getSourceRange();
134
135  // If the LHS is a plausible entity to assign to, provide a fixit hint to
136  // correct common typos.
137  if (CanAssign) {
138    if (IsNotEqual)
139      S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
140        << FixItHint::CreateReplacement(Loc, "|=");
141    else
142      S.Diag(Loc, diag::note_equality_comparison_to_assign)
143        << FixItHint::CreateReplacement(Loc, "=");
144  }
145
146  return true;
147}
148
149void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
150  if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
151    return DiagnoseUnusedExprResult(Label->getSubStmt());
152
153  const Expr *E = dyn_cast_or_null<Expr>(S);
154  if (!E)
155    return;
156
157  const Expr *WarnExpr;
158  SourceLocation Loc;
159  SourceRange R1, R2;
160  if (SourceMgr.isInSystemMacro(E->getExprLoc()) ||
161      !E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
162    return;
163
164  // Okay, we have an unused result.  Depending on what the base expression is,
165  // we might want to make a more specific diagnostic.  Check for one of these
166  // cases now.
167  unsigned DiagID = diag::warn_unused_expr;
168  if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
169    E = Temps->getSubExpr();
170  if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
171    E = TempExpr->getSubExpr();
172
173  if (DiagnoseUnusedComparison(*this, E))
174    return;
175
176  E = WarnExpr;
177  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
178    if (E->getType()->isVoidType())
179      return;
180
181    // If the callee has attribute pure, const, or warn_unused_result, warn with
182    // a more specific message to make it clear what is happening.
183    if (const Decl *FD = CE->getCalleeDecl()) {
184      if (FD->getAttr<WarnUnusedResultAttr>()) {
185        Diag(Loc, diag::warn_unused_result) << R1 << R2;
186        return;
187      }
188      if (FD->getAttr<PureAttr>()) {
189        Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
190        return;
191      }
192      if (FD->getAttr<ConstAttr>()) {
193        Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
194        return;
195      }
196    }
197  } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
198    if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
199      Diag(Loc, diag::err_arc_unused_init_message) << R1;
200      return;
201    }
202    const ObjCMethodDecl *MD = ME->getMethodDecl();
203    if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
204      Diag(Loc, diag::warn_unused_result) << R1 << R2;
205      return;
206    }
207  } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
208    const Expr *Source = POE->getSyntacticForm();
209    if (isa<ObjCSubscriptRefExpr>(Source))
210      DiagID = diag::warn_unused_container_subscript_expr;
211    else
212      DiagID = diag::warn_unused_property_expr;
213  } else if (const CXXFunctionalCastExpr *FC
214                                       = dyn_cast<CXXFunctionalCastExpr>(E)) {
215    if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
216        isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
217      return;
218  }
219  // Diagnose "(void*) blah" as a typo for "(void) blah".
220  else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
221    TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
222    QualType T = TI->getType();
223
224    // We really do want to use the non-canonical type here.
225    if (T == Context.VoidPtrTy) {
226      PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc());
227
228      Diag(Loc, diag::warn_unused_voidptr)
229        << FixItHint::CreateRemoval(TL.getStarLoc());
230      return;
231    }
232  }
233
234  if (E->isGLValue() && E->getType().isVolatileQualified()) {
235    Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
236    return;
237  }
238
239  DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
240}
241
242void Sema::ActOnStartOfCompoundStmt() {
243  PushCompoundScope();
244}
245
246void Sema::ActOnFinishOfCompoundStmt() {
247  PopCompoundScope();
248}
249
250sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
251  return getCurFunction()->CompoundScopes.back();
252}
253
254StmtResult
255Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
256                        MultiStmtArg elts, bool isStmtExpr) {
257  unsigned NumElts = elts.size();
258  Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
259  // If we're in C89 mode, check that we don't have any decls after stmts.  If
260  // so, emit an extension diagnostic.
261  if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
262    // Note that __extension__ can be around a decl.
263    unsigned i = 0;
264    // Skip over all declarations.
265    for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
266      /*empty*/;
267
268    // We found the end of the list or a statement.  Scan for another declstmt.
269    for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
270      /*empty*/;
271
272    if (i != NumElts) {
273      Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
274      Diag(D->getLocation(), diag::ext_mixed_decls_code);
275    }
276  }
277  // Warn about unused expressions in statements.
278  for (unsigned i = 0; i != NumElts; ++i) {
279    // Ignore statements that are last in a statement expression.
280    if (isStmtExpr && i == NumElts - 1)
281      continue;
282
283    DiagnoseUnusedExprResult(Elts[i]);
284  }
285
286  // Check for suspicious empty body (null statement) in `for' and `while'
287  // statements.  Don't do anything for template instantiations, this just adds
288  // noise.
289  if (NumElts != 0 && !CurrentInstantiationScope &&
290      getCurCompoundScope().HasEmptyLoopBodies) {
291    for (unsigned i = 0; i != NumElts - 1; ++i)
292      DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
293  }
294
295  return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
296}
297
298StmtResult
299Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
300                    SourceLocation DotDotDotLoc, Expr *RHSVal,
301                    SourceLocation ColonLoc) {
302  assert((LHSVal != 0) && "missing expression in case statement");
303
304  if (getCurFunction()->SwitchStack.empty()) {
305    Diag(CaseLoc, diag::err_case_not_in_switch);
306    return StmtError();
307  }
308
309  if (!getLangOpts().CPlusPlus0x) {
310    // C99 6.8.4.2p3: The expression shall be an integer constant.
311    // However, GCC allows any evaluatable integer expression.
312    if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
313      LHSVal = VerifyIntegerConstantExpression(LHSVal).take();
314      if (!LHSVal)
315        return StmtError();
316    }
317
318    // GCC extension: The expression shall be an integer constant.
319
320    if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
321      RHSVal = VerifyIntegerConstantExpression(RHSVal).take();
322      // Recover from an error by just forgetting about it.
323    }
324  }
325
326  CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
327                                        ColonLoc);
328  getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
329  return Owned(CS);
330}
331
332/// ActOnCaseStmtBody - This installs a statement as the body of a case.
333void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
334  DiagnoseUnusedExprResult(SubStmt);
335
336  CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
337  CS->setSubStmt(SubStmt);
338}
339
340StmtResult
341Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
342                       Stmt *SubStmt, Scope *CurScope) {
343  DiagnoseUnusedExprResult(SubStmt);
344
345  if (getCurFunction()->SwitchStack.empty()) {
346    Diag(DefaultLoc, diag::err_default_not_in_switch);
347    return Owned(SubStmt);
348  }
349
350  DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
351  getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
352  return Owned(DS);
353}
354
355StmtResult
356Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
357                     SourceLocation ColonLoc, Stmt *SubStmt) {
358  // If the label was multiply defined, reject it now.
359  if (TheDecl->getStmt()) {
360    Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
361    Diag(TheDecl->getLocation(), diag::note_previous_definition);
362    return Owned(SubStmt);
363  }
364
365  // Otherwise, things are good.  Fill in the declaration and return it.
366  LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
367  TheDecl->setStmt(LS);
368  if (!TheDecl->isGnuLocal())
369    TheDecl->setLocation(IdentLoc);
370  return Owned(LS);
371}
372
373StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
374                                     ArrayRef<const Attr*> Attrs,
375                                     Stmt *SubStmt) {
376  // Fill in the declaration and return it.
377  AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
378  return Owned(LS);
379}
380
381StmtResult
382Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
383                  Stmt *thenStmt, SourceLocation ElseLoc,
384                  Stmt *elseStmt) {
385  ExprResult CondResult(CondVal.release());
386
387  VarDecl *ConditionVar = 0;
388  if (CondVar) {
389    ConditionVar = cast<VarDecl>(CondVar);
390    CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
391    if (CondResult.isInvalid())
392      return StmtError();
393  }
394  Expr *ConditionExpr = CondResult.takeAs<Expr>();
395  if (!ConditionExpr)
396    return StmtError();
397
398  DiagnoseUnusedExprResult(thenStmt);
399
400  if (!elseStmt) {
401    DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
402                          diag::warn_empty_if_body);
403  }
404
405  DiagnoseUnusedExprResult(elseStmt);
406
407  return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
408                                    thenStmt, ElseLoc, elseStmt));
409}
410
411/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
412/// the specified width and sign.  If an overflow occurs, detect it and emit
413/// the specified diagnostic.
414void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
415                                              unsigned NewWidth, bool NewSign,
416                                              SourceLocation Loc,
417                                              unsigned DiagID) {
418  // Perform a conversion to the promoted condition type if needed.
419  if (NewWidth > Val.getBitWidth()) {
420    // If this is an extension, just do it.
421    Val = Val.extend(NewWidth);
422    Val.setIsSigned(NewSign);
423
424    // If the input was signed and negative and the output is
425    // unsigned, don't bother to warn: this is implementation-defined
426    // behavior.
427    // FIXME: Introduce a second, default-ignored warning for this case?
428  } else if (NewWidth < Val.getBitWidth()) {
429    // If this is a truncation, check for overflow.
430    llvm::APSInt ConvVal(Val);
431    ConvVal = ConvVal.trunc(NewWidth);
432    ConvVal.setIsSigned(NewSign);
433    ConvVal = ConvVal.extend(Val.getBitWidth());
434    ConvVal.setIsSigned(Val.isSigned());
435    if (ConvVal != Val)
436      Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
437
438    // Regardless of whether a diagnostic was emitted, really do the
439    // truncation.
440    Val = Val.trunc(NewWidth);
441    Val.setIsSigned(NewSign);
442  } else if (NewSign != Val.isSigned()) {
443    // Convert the sign to match the sign of the condition.  This can cause
444    // overflow as well: unsigned(INTMIN)
445    // We don't diagnose this overflow, because it is implementation-defined
446    // behavior.
447    // FIXME: Introduce a second, default-ignored warning for this case?
448    llvm::APSInt OldVal(Val);
449    Val.setIsSigned(NewSign);
450  }
451}
452
453namespace {
454  struct CaseCompareFunctor {
455    bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
456                    const llvm::APSInt &RHS) {
457      return LHS.first < RHS;
458    }
459    bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
460                    const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
461      return LHS.first < RHS.first;
462    }
463    bool operator()(const llvm::APSInt &LHS,
464                    const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
465      return LHS < RHS.first;
466    }
467  };
468}
469
470/// CmpCaseVals - Comparison predicate for sorting case values.
471///
472static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
473                        const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
474  if (lhs.first < rhs.first)
475    return true;
476
477  if (lhs.first == rhs.first &&
478      lhs.second->getCaseLoc().getRawEncoding()
479       < rhs.second->getCaseLoc().getRawEncoding())
480    return true;
481  return false;
482}
483
484/// CmpEnumVals - Comparison predicate for sorting enumeration values.
485///
486static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
487                        const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
488{
489  return lhs.first < rhs.first;
490}
491
492/// EqEnumVals - Comparison preficate for uniqing enumeration values.
493///
494static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
495                       const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
496{
497  return lhs.first == rhs.first;
498}
499
500/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
501/// potentially integral-promoted expression @p expr.
502static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
503  if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
504    expr = cleanups->getSubExpr();
505  while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
506    if (impcast->getCastKind() != CK_IntegralCast) break;
507    expr = impcast->getSubExpr();
508  }
509  return expr->getType();
510}
511
512StmtResult
513Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
514                             Decl *CondVar) {
515  ExprResult CondResult;
516
517  VarDecl *ConditionVar = 0;
518  if (CondVar) {
519    ConditionVar = cast<VarDecl>(CondVar);
520    CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
521    if (CondResult.isInvalid())
522      return StmtError();
523
524    Cond = CondResult.release();
525  }
526
527  if (!Cond)
528    return StmtError();
529
530  class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
531    Expr *Cond;
532
533  public:
534    SwitchConvertDiagnoser(Expr *Cond)
535      : ICEConvertDiagnoser(false, true), Cond(Cond) { }
536
537    virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
538                                             QualType T) {
539      return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
540    }
541
542    virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
543                                                 QualType T) {
544      return S.Diag(Loc, diag::err_switch_incomplete_class_type)
545               << T << Cond->getSourceRange();
546    }
547
548    virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
549                                                   QualType T,
550                                                   QualType ConvTy) {
551      return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
552    }
553
554    virtual DiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
555                                               QualType ConvTy) {
556      return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
557        << ConvTy->isEnumeralType() << ConvTy;
558    }
559
560    virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
561                                                QualType T) {
562      return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
563    }
564
565    virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
566                                            QualType ConvTy) {
567      return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
568      << ConvTy->isEnumeralType() << ConvTy;
569    }
570
571    virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
572                                                 QualType T,
573                                                 QualType ConvTy) {
574      return DiagnosticBuilder::getEmpty();
575    }
576  } SwitchDiagnoser(Cond);
577
578  CondResult
579    = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond, SwitchDiagnoser,
580                                         /*AllowScopedEnumerations*/ true);
581  if (CondResult.isInvalid()) return StmtError();
582  Cond = CondResult.take();
583
584  // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
585  CondResult = UsualUnaryConversions(Cond);
586  if (CondResult.isInvalid()) return StmtError();
587  Cond = CondResult.take();
588
589  if (!CondVar) {
590    CheckImplicitConversions(Cond, SwitchLoc);
591    CondResult = MaybeCreateExprWithCleanups(Cond);
592    if (CondResult.isInvalid())
593      return StmtError();
594    Cond = CondResult.take();
595  }
596
597  getCurFunction()->setHasBranchIntoScope();
598
599  SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
600  getCurFunction()->SwitchStack.push_back(SS);
601  return Owned(SS);
602}
603
604static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
605  if (Val.getBitWidth() < BitWidth)
606    Val = Val.extend(BitWidth);
607  else if (Val.getBitWidth() > BitWidth)
608    Val = Val.trunc(BitWidth);
609  Val.setIsSigned(IsSigned);
610}
611
612StmtResult
613Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
614                            Stmt *BodyStmt) {
615  SwitchStmt *SS = cast<SwitchStmt>(Switch);
616  assert(SS == getCurFunction()->SwitchStack.back() &&
617         "switch stack missing push/pop!");
618
619  SS->setBody(BodyStmt, SwitchLoc);
620  getCurFunction()->SwitchStack.pop_back();
621
622  Expr *CondExpr = SS->getCond();
623  if (!CondExpr) return StmtError();
624
625  QualType CondType = CondExpr->getType();
626
627  Expr *CondExprBeforePromotion = CondExpr;
628  QualType CondTypeBeforePromotion =
629      GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
630
631  // C++ 6.4.2.p2:
632  // Integral promotions are performed (on the switch condition).
633  //
634  // A case value unrepresentable by the original switch condition
635  // type (before the promotion) doesn't make sense, even when it can
636  // be represented by the promoted type.  Therefore we need to find
637  // the pre-promotion type of the switch condition.
638  if (!CondExpr->isTypeDependent()) {
639    // We have already converted the expression to an integral or enumeration
640    // type, when we started the switch statement. If we don't have an
641    // appropriate type now, just return an error.
642    if (!CondType->isIntegralOrEnumerationType())
643      return StmtError();
644
645    if (CondExpr->isKnownToHaveBooleanValue()) {
646      // switch(bool_expr) {...} is often a programmer error, e.g.
647      //   switch(n && mask) { ... }  // Doh - should be "n & mask".
648      // One can always use an if statement instead of switch(bool_expr).
649      Diag(SwitchLoc, diag::warn_bool_switch_condition)
650          << CondExpr->getSourceRange();
651    }
652  }
653
654  // Get the bitwidth of the switched-on value before promotions.  We must
655  // convert the integer case values to this width before comparison.
656  bool HasDependentValue
657    = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
658  unsigned CondWidth
659    = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
660  bool CondIsSigned
661    = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
662
663  // Accumulate all of the case values in a vector so that we can sort them
664  // and detect duplicates.  This vector contains the APInt for the case after
665  // it has been converted to the condition type.
666  typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
667  CaseValsTy CaseVals;
668
669  // Keep track of any GNU case ranges we see.  The APSInt is the low value.
670  typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
671  CaseRangesTy CaseRanges;
672
673  DefaultStmt *TheDefaultStmt = 0;
674
675  bool CaseListIsErroneous = false;
676
677  for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
678       SC = SC->getNextSwitchCase()) {
679
680    if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
681      if (TheDefaultStmt) {
682        Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
683        Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
684
685        // FIXME: Remove the default statement from the switch block so that
686        // we'll return a valid AST.  This requires recursing down the AST and
687        // finding it, not something we are set up to do right now.  For now,
688        // just lop the entire switch stmt out of the AST.
689        CaseListIsErroneous = true;
690      }
691      TheDefaultStmt = DS;
692
693    } else {
694      CaseStmt *CS = cast<CaseStmt>(SC);
695
696      Expr *Lo = CS->getLHS();
697
698      if (Lo->isTypeDependent() || Lo->isValueDependent()) {
699        HasDependentValue = true;
700        break;
701      }
702
703      llvm::APSInt LoVal;
704
705      if (getLangOpts().CPlusPlus0x) {
706        // C++11 [stmt.switch]p2: the constant-expression shall be a converted
707        // constant expression of the promoted type of the switch condition.
708        ExprResult ConvLo =
709          CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
710        if (ConvLo.isInvalid()) {
711          CaseListIsErroneous = true;
712          continue;
713        }
714        Lo = ConvLo.take();
715      } else {
716        // We already verified that the expression has a i-c-e value (C99
717        // 6.8.4.2p3) - get that value now.
718        LoVal = Lo->EvaluateKnownConstInt(Context);
719
720        // If the LHS is not the same type as the condition, insert an implicit
721        // cast.
722        Lo = DefaultLvalueConversion(Lo).take();
723        Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
724      }
725
726      // Convert the value to the same width/sign as the condition had prior to
727      // integral promotions.
728      //
729      // FIXME: This causes us to reject valid code:
730      //   switch ((char)c) { case 256: case 0: return 0; }
731      // Here we claim there is a duplicated condition value, but there is not.
732      ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
733                                         Lo->getLocStart(),
734                                         diag::warn_case_value_overflow);
735
736      CS->setLHS(Lo);
737
738      // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
739      if (CS->getRHS()) {
740        if (CS->getRHS()->isTypeDependent() ||
741            CS->getRHS()->isValueDependent()) {
742          HasDependentValue = true;
743          break;
744        }
745        CaseRanges.push_back(std::make_pair(LoVal, CS));
746      } else
747        CaseVals.push_back(std::make_pair(LoVal, CS));
748    }
749  }
750
751  if (!HasDependentValue) {
752    // If we don't have a default statement, check whether the
753    // condition is constant.
754    llvm::APSInt ConstantCondValue;
755    bool HasConstantCond = false;
756    if (!HasDependentValue && !TheDefaultStmt) {
757      HasConstantCond
758        = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context,
759                                                 Expr::SE_AllowSideEffects);
760      assert(!HasConstantCond ||
761             (ConstantCondValue.getBitWidth() == CondWidth &&
762              ConstantCondValue.isSigned() == CondIsSigned));
763    }
764    bool ShouldCheckConstantCond = HasConstantCond;
765
766    // Sort all the scalar case values so we can easily detect duplicates.
767    std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
768
769    if (!CaseVals.empty()) {
770      for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
771        if (ShouldCheckConstantCond &&
772            CaseVals[i].first == ConstantCondValue)
773          ShouldCheckConstantCond = false;
774
775        if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
776          // If we have a duplicate, report it.
777          // First, determine if either case value has a name
778          StringRef PrevString, CurrString;
779          Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
780          Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
781          if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
782            PrevString = DeclRef->getDecl()->getName();
783          }
784          if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
785            CurrString = DeclRef->getDecl()->getName();
786          }
787          llvm::SmallString<16> CaseValStr;
788          CaseVals[i-1].first.toString(CaseValStr);
789
790          if (PrevString == CurrString)
791            Diag(CaseVals[i].second->getLHS()->getLocStart(),
792                 diag::err_duplicate_case) <<
793                 (PrevString.empty() ? CaseValStr.str() : PrevString);
794          else
795            Diag(CaseVals[i].second->getLHS()->getLocStart(),
796                 diag::err_duplicate_case_differing_expr) <<
797                 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
798                 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
799                 CaseValStr;
800
801          Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
802               diag::note_duplicate_case_prev);
803          // FIXME: We really want to remove the bogus case stmt from the
804          // substmt, but we have no way to do this right now.
805          CaseListIsErroneous = true;
806        }
807      }
808    }
809
810    // Detect duplicate case ranges, which usually don't exist at all in
811    // the first place.
812    if (!CaseRanges.empty()) {
813      // Sort all the case ranges by their low value so we can easily detect
814      // overlaps between ranges.
815      std::stable_sort(CaseRanges.begin(), CaseRanges.end());
816
817      // Scan the ranges, computing the high values and removing empty ranges.
818      std::vector<llvm::APSInt> HiVals;
819      for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
820        llvm::APSInt &LoVal = CaseRanges[i].first;
821        CaseStmt *CR = CaseRanges[i].second;
822        Expr *Hi = CR->getRHS();
823        llvm::APSInt HiVal;
824
825        if (getLangOpts().CPlusPlus0x) {
826          // C++11 [stmt.switch]p2: the constant-expression shall be a converted
827          // constant expression of the promoted type of the switch condition.
828          ExprResult ConvHi =
829            CheckConvertedConstantExpression(Hi, CondType, HiVal,
830                                             CCEK_CaseValue);
831          if (ConvHi.isInvalid()) {
832            CaseListIsErroneous = true;
833            continue;
834          }
835          Hi = ConvHi.take();
836        } else {
837          HiVal = Hi->EvaluateKnownConstInt(Context);
838
839          // If the RHS is not the same type as the condition, insert an
840          // implicit cast.
841          Hi = DefaultLvalueConversion(Hi).take();
842          Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
843        }
844
845        // Convert the value to the same width/sign as the condition.
846        ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
847                                           Hi->getLocStart(),
848                                           diag::warn_case_value_overflow);
849
850        CR->setRHS(Hi);
851
852        // If the low value is bigger than the high value, the case is empty.
853        if (LoVal > HiVal) {
854          Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
855            << SourceRange(CR->getLHS()->getLocStart(),
856                           Hi->getLocEnd());
857          CaseRanges.erase(CaseRanges.begin()+i);
858          --i, --e;
859          continue;
860        }
861
862        if (ShouldCheckConstantCond &&
863            LoVal <= ConstantCondValue &&
864            ConstantCondValue <= HiVal)
865          ShouldCheckConstantCond = false;
866
867        HiVals.push_back(HiVal);
868      }
869
870      // Rescan the ranges, looking for overlap with singleton values and other
871      // ranges.  Since the range list is sorted, we only need to compare case
872      // ranges with their neighbors.
873      for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
874        llvm::APSInt &CRLo = CaseRanges[i].first;
875        llvm::APSInt &CRHi = HiVals[i];
876        CaseStmt *CR = CaseRanges[i].second;
877
878        // Check to see whether the case range overlaps with any
879        // singleton cases.
880        CaseStmt *OverlapStmt = 0;
881        llvm::APSInt OverlapVal(32);
882
883        // Find the smallest value >= the lower bound.  If I is in the
884        // case range, then we have overlap.
885        CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
886                                                  CaseVals.end(), CRLo,
887                                                  CaseCompareFunctor());
888        if (I != CaseVals.end() && I->first < CRHi) {
889          OverlapVal  = I->first;   // Found overlap with scalar.
890          OverlapStmt = I->second;
891        }
892
893        // Find the smallest value bigger than the upper bound.
894        I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
895        if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
896          OverlapVal  = (I-1)->first;      // Found overlap with scalar.
897          OverlapStmt = (I-1)->second;
898        }
899
900        // Check to see if this case stmt overlaps with the subsequent
901        // case range.
902        if (i && CRLo <= HiVals[i-1]) {
903          OverlapVal  = HiVals[i-1];       // Found overlap with range.
904          OverlapStmt = CaseRanges[i-1].second;
905        }
906
907        if (OverlapStmt) {
908          // If we have a duplicate, report it.
909          Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
910            << OverlapVal.toString(10);
911          Diag(OverlapStmt->getLHS()->getLocStart(),
912               diag::note_duplicate_case_prev);
913          // FIXME: We really want to remove the bogus case stmt from the
914          // substmt, but we have no way to do this right now.
915          CaseListIsErroneous = true;
916        }
917      }
918    }
919
920    // Complain if we have a constant condition and we didn't find a match.
921    if (!CaseListIsErroneous && ShouldCheckConstantCond) {
922      // TODO: it would be nice if we printed enums as enums, chars as
923      // chars, etc.
924      Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
925        << ConstantCondValue.toString(10)
926        << CondExpr->getSourceRange();
927    }
928
929    // Check to see if switch is over an Enum and handles all of its
930    // values.  We only issue a warning if there is not 'default:', but
931    // we still do the analysis to preserve this information in the AST
932    // (which can be used by flow-based analyes).
933    //
934    const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
935
936    // If switch has default case, then ignore it.
937    if (!CaseListIsErroneous  && !HasConstantCond && ET) {
938      const EnumDecl *ED = ET->getDecl();
939      typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
940        EnumValsTy;
941      EnumValsTy EnumVals;
942
943      // Gather all enum values, set their type and sort them,
944      // allowing easier comparison with CaseVals.
945      for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
946           EDI != ED->enumerator_end(); ++EDI) {
947        llvm::APSInt Val = EDI->getInitVal();
948        AdjustAPSInt(Val, CondWidth, CondIsSigned);
949        EnumVals.push_back(std::make_pair(Val, *EDI));
950      }
951      std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
952      EnumValsTy::iterator EIend =
953        std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
954
955      // See which case values aren't in enum.
956      EnumValsTy::const_iterator EI = EnumVals.begin();
957      for (CaseValsTy::const_iterator CI = CaseVals.begin();
958           CI != CaseVals.end(); CI++) {
959        while (EI != EIend && EI->first < CI->first)
960          EI++;
961        if (EI == EIend || EI->first > CI->first)
962          Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
963            << CondTypeBeforePromotion;
964      }
965      // See which of case ranges aren't in enum
966      EI = EnumVals.begin();
967      for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
968           RI != CaseRanges.end() && EI != EIend; RI++) {
969        while (EI != EIend && EI->first < RI->first)
970          EI++;
971
972        if (EI == EIend || EI->first != RI->first) {
973          Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
974            << CondTypeBeforePromotion;
975        }
976
977        llvm::APSInt Hi =
978          RI->second->getRHS()->EvaluateKnownConstInt(Context);
979        AdjustAPSInt(Hi, CondWidth, CondIsSigned);
980        while (EI != EIend && EI->first < Hi)
981          EI++;
982        if (EI == EIend || EI->first != Hi)
983          Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
984            << CondTypeBeforePromotion;
985      }
986
987      // Check which enum vals aren't in switch
988      CaseValsTy::const_iterator CI = CaseVals.begin();
989      CaseRangesTy::const_iterator RI = CaseRanges.begin();
990      bool hasCasesNotInSwitch = false;
991
992      SmallVector<DeclarationName,8> UnhandledNames;
993
994      for (EI = EnumVals.begin(); EI != EIend; EI++){
995        // Drop unneeded case values
996        llvm::APSInt CIVal;
997        while (CI != CaseVals.end() && CI->first < EI->first)
998          CI++;
999
1000        if (CI != CaseVals.end() && CI->first == EI->first)
1001          continue;
1002
1003        // Drop unneeded case ranges
1004        for (; RI != CaseRanges.end(); RI++) {
1005          llvm::APSInt Hi =
1006            RI->second->getRHS()->EvaluateKnownConstInt(Context);
1007          AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1008          if (EI->first <= Hi)
1009            break;
1010        }
1011
1012        if (RI == CaseRanges.end() || EI->first < RI->first) {
1013          hasCasesNotInSwitch = true;
1014          UnhandledNames.push_back(EI->second->getDeclName());
1015        }
1016      }
1017
1018      if (TheDefaultStmt && UnhandledNames.empty())
1019        Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
1020
1021      // Produce a nice diagnostic if multiple values aren't handled.
1022      switch (UnhandledNames.size()) {
1023      case 0: break;
1024      case 1:
1025        Diag(CondExpr->getExprLoc(), TheDefaultStmt
1026          ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
1027          << UnhandledNames[0];
1028        break;
1029      case 2:
1030        Diag(CondExpr->getExprLoc(), TheDefaultStmt
1031          ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
1032          << UnhandledNames[0] << UnhandledNames[1];
1033        break;
1034      case 3:
1035        Diag(CondExpr->getExprLoc(), TheDefaultStmt
1036          ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
1037          << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1038        break;
1039      default:
1040        Diag(CondExpr->getExprLoc(), TheDefaultStmt
1041          ? diag::warn_def_missing_cases : diag::warn_missing_cases)
1042          << (unsigned)UnhandledNames.size()
1043          << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1044        break;
1045      }
1046
1047      if (!hasCasesNotInSwitch)
1048        SS->setAllEnumCasesCovered();
1049    }
1050  }
1051
1052  DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1053                        diag::warn_empty_switch_body);
1054
1055  // FIXME: If the case list was broken is some way, we don't have a good system
1056  // to patch it up.  Instead, just return the whole substmt as broken.
1057  if (CaseListIsErroneous)
1058    return StmtError();
1059
1060  return Owned(SS);
1061}
1062
1063void
1064Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1065                             Expr *SrcExpr) {
1066  unsigned DIAG = diag::warn_not_in_enum_assignement;
1067  if (Diags.getDiagnosticLevel(DIAG, SrcExpr->getExprLoc())
1068      == DiagnosticsEngine::Ignored)
1069    return;
1070
1071  if (const EnumType *ET = DstType->getAs<EnumType>())
1072    if (!Context.hasSameType(SrcType, DstType) &&
1073        SrcType->isIntegerType()) {
1074      if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1075          SrcExpr->isIntegerConstantExpr(Context)) {
1076        // Get the bitwidth of the enum value before promotions.
1077        unsigned DstWith = Context.getIntWidth(DstType);
1078        bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1079
1080        llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1081        const EnumDecl *ED = ET->getDecl();
1082        typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
1083        EnumValsTy;
1084        EnumValsTy EnumVals;
1085
1086        // Gather all enum values, set their type and sort them,
1087        // allowing easier comparison with rhs constant.
1088        for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
1089             EDI != ED->enumerator_end(); ++EDI) {
1090          llvm::APSInt Val = EDI->getInitVal();
1091          AdjustAPSInt(Val, DstWith, DstIsSigned);
1092          EnumVals.push_back(std::make_pair(Val, *EDI));
1093        }
1094        if (EnumVals.empty())
1095          return;
1096        std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1097        EnumValsTy::iterator EIend =
1098        std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1099
1100        // See which case values aren't in enum.
1101        EnumValsTy::const_iterator EI = EnumVals.begin();
1102        while (EI != EIend && EI->first < RhsVal)
1103          EI++;
1104        if (EI == EIend || EI->first != RhsVal) {
1105          Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignement)
1106          << DstType;
1107        }
1108      }
1109    }
1110}
1111
1112StmtResult
1113Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
1114                     Decl *CondVar, Stmt *Body) {
1115  ExprResult CondResult(Cond.release());
1116
1117  VarDecl *ConditionVar = 0;
1118  if (CondVar) {
1119    ConditionVar = cast<VarDecl>(CondVar);
1120    CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
1121    if (CondResult.isInvalid())
1122      return StmtError();
1123  }
1124  Expr *ConditionExpr = CondResult.take();
1125  if (!ConditionExpr)
1126    return StmtError();
1127
1128  DiagnoseUnusedExprResult(Body);
1129
1130  if (isa<NullStmt>(Body))
1131    getCurCompoundScope().setHasEmptyLoopBodies();
1132
1133  return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
1134                                       Body, WhileLoc));
1135}
1136
1137StmtResult
1138Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
1139                  SourceLocation WhileLoc, SourceLocation CondLParen,
1140                  Expr *Cond, SourceLocation CondRParen) {
1141  assert(Cond && "ActOnDoStmt(): missing expression");
1142
1143  ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
1144  if (CondResult.isInvalid() || CondResult.isInvalid())
1145    return StmtError();
1146  Cond = CondResult.take();
1147
1148  CheckImplicitConversions(Cond, DoLoc);
1149  CondResult = MaybeCreateExprWithCleanups(Cond);
1150  if (CondResult.isInvalid())
1151    return StmtError();
1152  Cond = CondResult.take();
1153
1154  DiagnoseUnusedExprResult(Body);
1155
1156  return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
1157}
1158
1159namespace {
1160  // This visitor will traverse a conditional statement and store all
1161  // the evaluated decls into a vector.  Simple is set to true if none
1162  // of the excluded constructs are used.
1163  class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1164    llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1165    llvm::SmallVector<SourceRange, 10> &Ranges;
1166    bool Simple;
1167public:
1168  typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1169
1170  DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
1171                llvm::SmallVector<SourceRange, 10> &Ranges) :
1172      Inherited(S.Context),
1173      Decls(Decls),
1174      Ranges(Ranges),
1175      Simple(true) {}
1176
1177  bool isSimple() { return Simple; }
1178
1179  // Replaces the method in EvaluatedExprVisitor.
1180  void VisitMemberExpr(MemberExpr* E) {
1181    Simple = false;
1182  }
1183
1184  // Any Stmt not whitelisted will cause the condition to be marked complex.
1185  void VisitStmt(Stmt *S) {
1186    Simple = false;
1187  }
1188
1189  void VisitBinaryOperator(BinaryOperator *E) {
1190    Visit(E->getLHS());
1191    Visit(E->getRHS());
1192  }
1193
1194  void VisitCastExpr(CastExpr *E) {
1195    Visit(E->getSubExpr());
1196  }
1197
1198  void VisitUnaryOperator(UnaryOperator *E) {
1199    // Skip checking conditionals with derefernces.
1200    if (E->getOpcode() == UO_Deref)
1201      Simple = false;
1202    else
1203      Visit(E->getSubExpr());
1204  }
1205
1206  void VisitConditionalOperator(ConditionalOperator *E) {
1207    Visit(E->getCond());
1208    Visit(E->getTrueExpr());
1209    Visit(E->getFalseExpr());
1210  }
1211
1212  void VisitParenExpr(ParenExpr *E) {
1213    Visit(E->getSubExpr());
1214  }
1215
1216  void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1217    Visit(E->getOpaqueValue()->getSourceExpr());
1218    Visit(E->getFalseExpr());
1219  }
1220
1221  void VisitIntegerLiteral(IntegerLiteral *E) { }
1222  void VisitFloatingLiteral(FloatingLiteral *E) { }
1223  void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1224  void VisitCharacterLiteral(CharacterLiteral *E) { }
1225  void VisitGNUNullExpr(GNUNullExpr *E) { }
1226  void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1227
1228  void VisitDeclRefExpr(DeclRefExpr *E) {
1229    VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1230    if (!VD) return;
1231
1232    Ranges.push_back(E->getSourceRange());
1233
1234    Decls.insert(VD);
1235  }
1236
1237  }; // end class DeclExtractor
1238
1239  // DeclMatcher checks to see if the decls are used in a non-evauluated
1240  // context.
1241  class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1242    llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1243    bool FoundDecl;
1244
1245public:
1246  typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1247
1248  DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls, Stmt *Statement) :
1249      Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1250    if (!Statement) return;
1251
1252    Visit(Statement);
1253  }
1254
1255  void VisitReturnStmt(ReturnStmt *S) {
1256    FoundDecl = true;
1257  }
1258
1259  void VisitBreakStmt(BreakStmt *S) {
1260    FoundDecl = true;
1261  }
1262
1263  void VisitGotoStmt(GotoStmt *S) {
1264    FoundDecl = true;
1265  }
1266
1267  void VisitCastExpr(CastExpr *E) {
1268    if (E->getCastKind() == CK_LValueToRValue)
1269      CheckLValueToRValueCast(E->getSubExpr());
1270    else
1271      Visit(E->getSubExpr());
1272  }
1273
1274  void CheckLValueToRValueCast(Expr *E) {
1275    E = E->IgnoreParenImpCasts();
1276
1277    if (isa<DeclRefExpr>(E)) {
1278      return;
1279    }
1280
1281    if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1282      Visit(CO->getCond());
1283      CheckLValueToRValueCast(CO->getTrueExpr());
1284      CheckLValueToRValueCast(CO->getFalseExpr());
1285      return;
1286    }
1287
1288    if (BinaryConditionalOperator *BCO =
1289            dyn_cast<BinaryConditionalOperator>(E)) {
1290      CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1291      CheckLValueToRValueCast(BCO->getFalseExpr());
1292      return;
1293    }
1294
1295    Visit(E);
1296  }
1297
1298  void VisitDeclRefExpr(DeclRefExpr *E) {
1299    if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1300      if (Decls.count(VD))
1301        FoundDecl = true;
1302  }
1303
1304  bool FoundDeclInUse() { return FoundDecl; }
1305
1306  };  // end class DeclMatcher
1307
1308  void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1309                                        Expr *Third, Stmt *Body) {
1310    // Condition is empty
1311    if (!Second) return;
1312
1313    if (S.Diags.getDiagnosticLevel(diag::warn_variables_not_in_loop_body,
1314                                   Second->getLocStart())
1315        == DiagnosticsEngine::Ignored)
1316      return;
1317
1318    PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1319    llvm::SmallPtrSet<VarDecl*, 8> Decls;
1320    llvm::SmallVector<SourceRange, 10> Ranges;
1321    DeclExtractor DE(S, Decls, Ranges);
1322    DE.Visit(Second);
1323
1324    // Don't analyze complex conditionals.
1325    if (!DE.isSimple()) return;
1326
1327    // No decls found.
1328    if (Decls.size() == 0) return;
1329
1330    // Don't warn on volatile, static, or global variables.
1331    for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1332                                                  E = Decls.end();
1333         I != E; ++I)
1334      if ((*I)->getType().isVolatileQualified() ||
1335          (*I)->hasGlobalStorage()) return;
1336
1337    if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1338        DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1339        DeclMatcher(S, Decls, Body).FoundDeclInUse())
1340      return;
1341
1342    // Load decl names into diagnostic.
1343    if (Decls.size() > 4)
1344      PDiag << 0;
1345    else {
1346      PDiag << Decls.size();
1347      for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1348                                                    E = Decls.end();
1349           I != E; ++I)
1350        PDiag << (*I)->getDeclName();
1351    }
1352
1353    // Load SourceRanges into diagnostic if there is room.
1354    // Otherwise, load the SourceRange of the conditional expression.
1355    if (Ranges.size() <= PartialDiagnostic::MaxArguments)
1356      for (llvm::SmallVector<SourceRange, 10>::iterator I = Ranges.begin(),
1357                                                        E = Ranges.end();
1358           I != E; ++I)
1359        PDiag << *I;
1360    else
1361      PDiag << Second->getSourceRange();
1362
1363    S.Diag(Ranges.begin()->getBegin(), PDiag);
1364  }
1365
1366} // end namespace
1367
1368StmtResult
1369Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1370                   Stmt *First, FullExprArg second, Decl *secondVar,
1371                   FullExprArg third,
1372                   SourceLocation RParenLoc, Stmt *Body) {
1373  if (!getLangOpts().CPlusPlus) {
1374    if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
1375      // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1376      // declare identifiers for objects having storage class 'auto' or
1377      // 'register'.
1378      for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
1379           DI!=DE; ++DI) {
1380        VarDecl *VD = dyn_cast<VarDecl>(*DI);
1381        if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
1382          VD = 0;
1383        if (VD == 0)
1384          Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
1385        // FIXME: mark decl erroneous!
1386      }
1387    }
1388  }
1389
1390  CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
1391
1392  ExprResult SecondResult(second.release());
1393  VarDecl *ConditionVar = 0;
1394  if (secondVar) {
1395    ConditionVar = cast<VarDecl>(secondVar);
1396    SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
1397    if (SecondResult.isInvalid())
1398      return StmtError();
1399  }
1400
1401  Expr *Third  = third.release().takeAs<Expr>();
1402
1403  DiagnoseUnusedExprResult(First);
1404  DiagnoseUnusedExprResult(Third);
1405  DiagnoseUnusedExprResult(Body);
1406
1407  if (isa<NullStmt>(Body))
1408    getCurCompoundScope().setHasEmptyLoopBodies();
1409
1410  return Owned(new (Context) ForStmt(Context, First,
1411                                     SecondResult.take(), ConditionVar,
1412                                     Third, Body, ForLoc, LParenLoc,
1413                                     RParenLoc));
1414}
1415
1416/// In an Objective C collection iteration statement:
1417///   for (x in y)
1418/// x can be an arbitrary l-value expression.  Bind it up as a
1419/// full-expression.
1420StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
1421  // Reduce placeholder expressions here.  Note that this rejects the
1422  // use of pseudo-object l-values in this position.
1423  ExprResult result = CheckPlaceholderExpr(E);
1424  if (result.isInvalid()) return StmtError();
1425  E = result.take();
1426
1427  CheckImplicitConversions(E);
1428
1429  result = MaybeCreateExprWithCleanups(E);
1430  if (result.isInvalid()) return StmtError();
1431
1432  return Owned(static_cast<Stmt*>(result.take()));
1433}
1434
1435ExprResult
1436Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1437  if (!collection)
1438    return ExprError();
1439
1440  // Bail out early if we've got a type-dependent expression.
1441  if (collection->isTypeDependent()) return Owned(collection);
1442
1443  // Perform normal l-value conversion.
1444  ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1445  if (result.isInvalid())
1446    return ExprError();
1447  collection = result.take();
1448
1449  // The operand needs to have object-pointer type.
1450  // TODO: should we do a contextual conversion?
1451  const ObjCObjectPointerType *pointerType =
1452    collection->getType()->getAs<ObjCObjectPointerType>();
1453  if (!pointerType)
1454    return Diag(forLoc, diag::err_collection_expr_type)
1455             << collection->getType() << collection->getSourceRange();
1456
1457  // Check that the operand provides
1458  //   - countByEnumeratingWithState:objects:count:
1459  const ObjCObjectType *objectType = pointerType->getObjectType();
1460  ObjCInterfaceDecl *iface = objectType->getInterface();
1461
1462  // If we have a forward-declared type, we can't do this check.
1463  // Under ARC, it is an error not to have a forward-declared class.
1464  if (iface &&
1465      RequireCompleteType(forLoc, QualType(objectType, 0),
1466                          getLangOpts().ObjCAutoRefCount
1467                            ? diag::err_arc_collection_forward
1468                            : 0,
1469                          collection)) {
1470    // Otherwise, if we have any useful type information, check that
1471    // the type declares the appropriate method.
1472  } else if (iface || !objectType->qual_empty()) {
1473    IdentifierInfo *selectorIdents[] = {
1474      &Context.Idents.get("countByEnumeratingWithState"),
1475      &Context.Idents.get("objects"),
1476      &Context.Idents.get("count")
1477    };
1478    Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1479
1480    ObjCMethodDecl *method = 0;
1481
1482    // If there's an interface, look in both the public and private APIs.
1483    if (iface) {
1484      method = iface->lookupInstanceMethod(selector);
1485      if (!method) method = iface->lookupPrivateMethod(selector);
1486    }
1487
1488    // Also check protocol qualifiers.
1489    if (!method)
1490      method = LookupMethodInQualifiedType(selector, pointerType,
1491                                           /*instance*/ true);
1492
1493    // If we didn't find it anywhere, give up.
1494    if (!method) {
1495      Diag(forLoc, diag::warn_collection_expr_type)
1496        << collection->getType() << selector << collection->getSourceRange();
1497    }
1498
1499    // TODO: check for an incompatible signature?
1500  }
1501
1502  // Wrap up any cleanups in the expression.
1503  return Owned(MaybeCreateExprWithCleanups(collection));
1504}
1505
1506StmtResult
1507Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1508                                 SourceLocation LParenLoc,
1509                                 Stmt *First, Expr *collection,
1510                                 SourceLocation RParenLoc) {
1511
1512  ExprResult CollectionExprResult =
1513    CheckObjCForCollectionOperand(ForLoc, collection);
1514
1515  if (First) {
1516    QualType FirstType;
1517    if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
1518      if (!DS->isSingleDecl())
1519        return StmtError(Diag((*DS->decl_begin())->getLocation(),
1520                         diag::err_toomany_element_decls));
1521
1522      VarDecl *D = cast<VarDecl>(DS->getSingleDecl());
1523      FirstType = D->getType();
1524      // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1525      // declare identifiers for objects having storage class 'auto' or
1526      // 'register'.
1527      if (!D->hasLocalStorage())
1528        return StmtError(Diag(D->getLocation(),
1529                              diag::err_non_variable_decl_in_for));
1530    } else {
1531      Expr *FirstE = cast<Expr>(First);
1532      if (!FirstE->isTypeDependent() && !FirstE->isLValue())
1533        return StmtError(Diag(First->getLocStart(),
1534                   diag::err_selector_element_not_lvalue)
1535          << First->getSourceRange());
1536
1537      FirstType = static_cast<Expr*>(First)->getType();
1538    }
1539    if (!FirstType->isDependentType() &&
1540        !FirstType->isObjCObjectPointerType() &&
1541        !FirstType->isBlockPointerType())
1542        return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1543                           << FirstType << First->getSourceRange());
1544  }
1545
1546  if (CollectionExprResult.isInvalid())
1547    return StmtError();
1548
1549  return Owned(new (Context) ObjCForCollectionStmt(First,
1550                                                   CollectionExprResult.take(), 0,
1551                                                   ForLoc, RParenLoc));
1552}
1553
1554namespace {
1555
1556enum BeginEndFunction {
1557  BEF_begin,
1558  BEF_end
1559};
1560
1561/// Build a variable declaration for a for-range statement.
1562static VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1563                                     QualType Type, const char *Name) {
1564  DeclContext *DC = SemaRef.CurContext;
1565  IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1566  TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1567  VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1568                                  TInfo, SC_Auto, SC_None);
1569  Decl->setImplicit();
1570  return Decl;
1571}
1572
1573/// Finish building a variable declaration for a for-range statement.
1574/// \return true if an error occurs.
1575static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1576                                  SourceLocation Loc, int diag) {
1577  // Deduce the type for the iterator variable now rather than leaving it to
1578  // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1579  TypeSourceInfo *InitTSI = 0;
1580  if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
1581      SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI) ==
1582          Sema::DAR_Failed)
1583    SemaRef.Diag(Loc, diag) << Init->getType();
1584  if (!InitTSI) {
1585    Decl->setInvalidDecl();
1586    return true;
1587  }
1588  Decl->setTypeSourceInfo(InitTSI);
1589  Decl->setType(InitTSI->getType());
1590
1591  // In ARC, infer lifetime.
1592  // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1593  // we're doing the equivalent of fast iteration.
1594  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1595      SemaRef.inferObjCARCLifetime(Decl))
1596    Decl->setInvalidDecl();
1597
1598  SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1599                               /*TypeMayContainAuto=*/false);
1600  SemaRef.FinalizeDeclaration(Decl);
1601  SemaRef.CurContext->addHiddenDecl(Decl);
1602  return false;
1603}
1604
1605/// Produce a note indicating which begin/end function was implicitly called
1606/// by a C++0x for-range statement. This is often not obvious from the code,
1607/// nor from the diagnostics produced when analysing the implicit expressions
1608/// required in a for-range statement.
1609void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
1610                                  BeginEndFunction BEF) {
1611  CallExpr *CE = dyn_cast<CallExpr>(E);
1612  if (!CE)
1613    return;
1614  FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1615  if (!D)
1616    return;
1617  SourceLocation Loc = D->getLocation();
1618
1619  std::string Description;
1620  bool IsTemplate = false;
1621  if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1622    Description = SemaRef.getTemplateArgumentBindingsText(
1623      FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1624    IsTemplate = true;
1625  }
1626
1627  SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1628    << BEF << IsTemplate << Description << E->getType();
1629}
1630
1631/// Build a call to 'begin' or 'end' for a C++0x for-range statement. If the
1632/// given LookupResult is non-empty, it is assumed to describe a member which
1633/// will be invoked. Otherwise, the function will be found via argument
1634/// dependent lookup.
1635static ExprResult BuildForRangeBeginEndCall(Sema &SemaRef, Scope *S,
1636                                            SourceLocation Loc,
1637                                            VarDecl *Decl,
1638                                            BeginEndFunction BEF,
1639                                            const DeclarationNameInfo &NameInfo,
1640                                            LookupResult &MemberLookup,
1641                                            Expr *Range) {
1642  ExprResult CallExpr;
1643  if (!MemberLookup.empty()) {
1644    ExprResult MemberRef =
1645      SemaRef.BuildMemberReferenceExpr(Range, Range->getType(), Loc,
1646                                       /*IsPtr=*/false, CXXScopeSpec(),
1647                                       /*TemplateKWLoc=*/SourceLocation(),
1648                                       /*FirstQualifierInScope=*/0,
1649                                       MemberLookup,
1650                                       /*TemplateArgs=*/0);
1651    if (MemberRef.isInvalid())
1652      return ExprError();
1653    CallExpr = SemaRef.ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(),
1654                                     Loc, 0);
1655    if (CallExpr.isInvalid())
1656      return ExprError();
1657  } else {
1658    UnresolvedSet<0> FoundNames;
1659    // C++0x [stmt.ranged]p1: For the purposes of this name lookup, namespace
1660    // std is an associated namespace.
1661    UnresolvedLookupExpr *Fn =
1662      UnresolvedLookupExpr::Create(SemaRef.Context, /*NamingClass=*/0,
1663                                   NestedNameSpecifierLoc(), NameInfo,
1664                                   /*NeedsADL=*/true, /*Overloaded=*/false,
1665                                   FoundNames.begin(), FoundNames.end(),
1666                                   /*LookInStdNamespace=*/true);
1667    CallExpr = SemaRef.BuildOverloadedCallExpr(S, Fn, Fn, Loc, &Range, 1, Loc,
1668                                               0, /*AllowTypoCorrection=*/false);
1669    if (CallExpr.isInvalid()) {
1670      SemaRef.Diag(Range->getLocStart(), diag::note_for_range_type)
1671        << Range->getType();
1672      return ExprError();
1673    }
1674  }
1675  if (FinishForRangeVarDecl(SemaRef, Decl, CallExpr.get(), Loc,
1676                            diag::err_for_range_iter_deduction_failure)) {
1677    NoteForRangeBeginEndFunction(SemaRef, CallExpr.get(), BEF);
1678    return ExprError();
1679  }
1680  return CallExpr;
1681}
1682
1683}
1684
1685static bool ObjCEnumerationCollection(Expr *Collection) {
1686  return !Collection->isTypeDependent()
1687          && Collection->getType()->getAs<ObjCObjectPointerType>() != 0;
1688}
1689
1690/// ActOnCXXForRangeStmt - Check and build a C++0x for-range statement.
1691///
1692/// C++0x [stmt.ranged]:
1693///   A range-based for statement is equivalent to
1694///
1695///   {
1696///     auto && __range = range-init;
1697///     for ( auto __begin = begin-expr,
1698///           __end = end-expr;
1699///           __begin != __end;
1700///           ++__begin ) {
1701///       for-range-declaration = *__begin;
1702///       statement
1703///     }
1704///   }
1705///
1706/// The body of the loop is not available yet, since it cannot be analysed until
1707/// we have determined the type of the for-range-declaration.
1708StmtResult
1709Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1710                           Stmt *First, SourceLocation ColonLoc, Expr *Range,
1711                           SourceLocation RParenLoc) {
1712  if (!First || !Range)
1713    return StmtError();
1714
1715  if (ObjCEnumerationCollection(Range))
1716    return ActOnObjCForCollectionStmt(ForLoc, LParenLoc, First, Range,
1717                                      RParenLoc);
1718
1719  DeclStmt *DS = dyn_cast<DeclStmt>(First);
1720  assert(DS && "first part of for range not a decl stmt");
1721
1722  if (!DS->isSingleDecl()) {
1723    Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1724    return StmtError();
1725  }
1726  if (DS->getSingleDecl()->isInvalidDecl())
1727    return StmtError();
1728
1729  if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1730    return StmtError();
1731
1732  // Build  auto && __range = range-init
1733  SourceLocation RangeLoc = Range->getLocStart();
1734  VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1735                                           Context.getAutoRRefDeductType(),
1736                                           "__range");
1737  if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1738                            diag::err_for_range_deduction_failure))
1739    return StmtError();
1740
1741  // Claim the type doesn't contain auto: we've already done the checking.
1742  DeclGroupPtrTy RangeGroup =
1743    BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false);
1744  StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1745  if (RangeDecl.isInvalid())
1746    return StmtError();
1747
1748  return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1749                              /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
1750                              RParenLoc);
1751}
1752
1753/// BuildCXXForRangeStmt - Build or instantiate a C++0x for-range statement.
1754StmtResult
1755Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
1756                           Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
1757                           Expr *Inc, Stmt *LoopVarDecl,
1758                           SourceLocation RParenLoc) {
1759  Scope *S = getCurScope();
1760
1761  DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
1762  VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
1763  QualType RangeVarType = RangeVar->getType();
1764
1765  DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
1766  VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
1767
1768  StmtResult BeginEndDecl = BeginEnd;
1769  ExprResult NotEqExpr = Cond, IncrExpr = Inc;
1770
1771  if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) {
1772    SourceLocation RangeLoc = RangeVar->getLocation();
1773
1774    const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
1775
1776    ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1777                                                VK_LValue, ColonLoc);
1778    if (BeginRangeRef.isInvalid())
1779      return StmtError();
1780
1781    ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1782                                              VK_LValue, ColonLoc);
1783    if (EndRangeRef.isInvalid())
1784      return StmtError();
1785
1786    QualType AutoType = Context.getAutoDeductType();
1787    Expr *Range = RangeVar->getInit();
1788    if (!Range)
1789      return StmtError();
1790    QualType RangeType = Range->getType();
1791
1792    if (RequireCompleteType(RangeLoc, RangeType,
1793                            diag::err_for_range_incomplete_type))
1794      return StmtError();
1795
1796    // Build auto __begin = begin-expr, __end = end-expr.
1797    VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1798                                             "__begin");
1799    VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1800                                           "__end");
1801
1802    // Build begin-expr and end-expr and attach to __begin and __end variables.
1803    ExprResult BeginExpr, EndExpr;
1804    if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
1805      // - if _RangeT is an array type, begin-expr and end-expr are __range and
1806      //   __range + __bound, respectively, where __bound is the array bound. If
1807      //   _RangeT is an array of unknown size or an array of incomplete type,
1808      //   the program is ill-formed;
1809
1810      // begin-expr is __range.
1811      BeginExpr = BeginRangeRef;
1812      if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
1813                                diag::err_for_range_iter_deduction_failure)) {
1814        NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1815        return StmtError();
1816      }
1817
1818      // Find the array bound.
1819      ExprResult BoundExpr;
1820      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
1821        BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
1822                                                 Context.getPointerDiffType(),
1823                                                 RangeLoc));
1824      else if (const VariableArrayType *VAT =
1825               dyn_cast<VariableArrayType>(UnqAT))
1826        BoundExpr = VAT->getSizeExpr();
1827      else {
1828        // Can't be a DependentSizedArrayType or an IncompleteArrayType since
1829        // UnqAT is not incomplete and Range is not type-dependent.
1830        llvm_unreachable("Unexpected array type in for-range");
1831      }
1832
1833      // end-expr is __range + __bound.
1834      EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
1835                           BoundExpr.get());
1836      if (EndExpr.isInvalid())
1837        return StmtError();
1838      if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
1839                                diag::err_for_range_iter_deduction_failure)) {
1840        NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1841        return StmtError();
1842      }
1843    } else {
1844      DeclarationNameInfo BeginNameInfo(&PP.getIdentifierTable().get("begin"),
1845                                        ColonLoc);
1846      DeclarationNameInfo EndNameInfo(&PP.getIdentifierTable().get("end"),
1847                                      ColonLoc);
1848
1849      LookupResult BeginMemberLookup(*this, BeginNameInfo, LookupMemberName);
1850      LookupResult EndMemberLookup(*this, EndNameInfo, LookupMemberName);
1851
1852      if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1853        // - if _RangeT is a class type, the unqualified-ids begin and end are
1854        //   looked up in the scope of class _RangeT as if by class member access
1855        //   lookup (3.4.5), and if either (or both) finds at least one
1856        //   declaration, begin-expr and end-expr are __range.begin() and
1857        //   __range.end(), respectively;
1858        LookupQualifiedName(BeginMemberLookup, D);
1859        LookupQualifiedName(EndMemberLookup, D);
1860
1861        if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1862          Diag(ColonLoc, diag::err_for_range_member_begin_end_mismatch)
1863            << RangeType << BeginMemberLookup.empty();
1864          return StmtError();
1865        }
1866      } else {
1867        // - otherwise, begin-expr and end-expr are begin(__range) and
1868        //   end(__range), respectively, where begin and end are looked up with
1869        //   argument-dependent lookup (3.4.2). For the purposes of this name
1870        //   lookup, namespace std is an associated namespace.
1871      }
1872
1873      BeginExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, BeginVar,
1874                                            BEF_begin, BeginNameInfo,
1875                                            BeginMemberLookup,
1876                                            BeginRangeRef.get());
1877      if (BeginExpr.isInvalid())
1878        return StmtError();
1879
1880      EndExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, EndVar,
1881                                          BEF_end, EndNameInfo,
1882                                          EndMemberLookup, EndRangeRef.get());
1883      if (EndExpr.isInvalid())
1884        return StmtError();
1885    }
1886
1887    // C++0x [decl.spec.auto]p6: BeginType and EndType must be the same.
1888    QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
1889    if (!Context.hasSameType(BeginType, EndType)) {
1890      Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
1891        << BeginType << EndType;
1892      NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1893      NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1894    }
1895
1896    Decl *BeginEndDecls[] = { BeginVar, EndVar };
1897    // Claim the type doesn't contain auto: we've already done the checking.
1898    DeclGroupPtrTy BeginEndGroup =
1899      BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false);
1900    BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
1901
1902    const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
1903    ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1904                                           VK_LValue, ColonLoc);
1905    if (BeginRef.isInvalid())
1906      return StmtError();
1907
1908    ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
1909                                         VK_LValue, ColonLoc);
1910    if (EndRef.isInvalid())
1911      return StmtError();
1912
1913    // Build and check __begin != __end expression.
1914    NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
1915                           BeginRef.get(), EndRef.get());
1916    NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
1917    NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
1918    if (NotEqExpr.isInvalid()) {
1919      NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1920      if (!Context.hasSameType(BeginType, EndType))
1921        NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1922      return StmtError();
1923    }
1924
1925    // Build and check ++__begin expression.
1926    BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1927                                VK_LValue, ColonLoc);
1928    if (BeginRef.isInvalid())
1929      return StmtError();
1930
1931    IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
1932    IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
1933    if (IncrExpr.isInvalid()) {
1934      NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1935      return StmtError();
1936    }
1937
1938    // Build and check *__begin  expression.
1939    BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1940                                VK_LValue, ColonLoc);
1941    if (BeginRef.isInvalid())
1942      return StmtError();
1943
1944    ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
1945    if (DerefExpr.isInvalid()) {
1946      NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1947      return StmtError();
1948    }
1949
1950    // Attach  *__begin  as initializer for VD.
1951    if (!LoopVar->isInvalidDecl()) {
1952      AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
1953                           /*TypeMayContainAuto=*/true);
1954      if (LoopVar->isInvalidDecl())
1955        NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1956    }
1957  } else {
1958    // The range is implicitly used as a placeholder when it is dependent.
1959    RangeVar->setUsed();
1960  }
1961
1962  return Owned(new (Context) CXXForRangeStmt(RangeDS,
1963                                     cast_or_null<DeclStmt>(BeginEndDecl.get()),
1964                                             NotEqExpr.take(), IncrExpr.take(),
1965                                             LoopVarDS, /*Body=*/0, ForLoc,
1966                                             ColonLoc, RParenLoc));
1967}
1968
1969/// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
1970/// statement.
1971StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
1972  if (!S || !B)
1973    return StmtError();
1974  ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
1975
1976  ForStmt->setBody(B);
1977  return S;
1978}
1979
1980/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
1981/// This is a separate step from ActOnCXXForRangeStmt because analysis of the
1982/// body cannot be performed until after the type of the range variable is
1983/// determined.
1984StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
1985  if (!S || !B)
1986    return StmtError();
1987
1988  if (isa<ObjCForCollectionStmt>(S))
1989    return FinishObjCForCollectionStmt(S, B);
1990
1991  CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
1992  ForStmt->setBody(B);
1993
1994  DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
1995                        diag::warn_empty_range_based_for_body);
1996
1997  return S;
1998}
1999
2000StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2001                               SourceLocation LabelLoc,
2002                               LabelDecl *TheDecl) {
2003  getCurFunction()->setHasBranchIntoScope();
2004  TheDecl->setUsed();
2005  return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
2006}
2007
2008StmtResult
2009Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
2010                            Expr *E) {
2011  // Convert operand to void*
2012  if (!E->isTypeDependent()) {
2013    QualType ETy = E->getType();
2014    QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
2015    ExprResult ExprRes = Owned(E);
2016    AssignConvertType ConvTy =
2017      CheckSingleAssignmentConstraints(DestTy, ExprRes);
2018    if (ExprRes.isInvalid())
2019      return StmtError();
2020    E = ExprRes.take();
2021    if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
2022      return StmtError();
2023    E = MaybeCreateExprWithCleanups(E);
2024  }
2025
2026  getCurFunction()->setHasIndirectGoto();
2027
2028  return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
2029}
2030
2031StmtResult
2032Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
2033  Scope *S = CurScope->getContinueParent();
2034  if (!S) {
2035    // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
2036    return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
2037  }
2038
2039  return Owned(new (Context) ContinueStmt(ContinueLoc));
2040}
2041
2042StmtResult
2043Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
2044  Scope *S = CurScope->getBreakParent();
2045  if (!S) {
2046    // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
2047    return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
2048  }
2049
2050  return Owned(new (Context) BreakStmt(BreakLoc));
2051}
2052
2053/// \brief Determine whether the given expression is a candidate for
2054/// copy elision in either a return statement or a throw expression.
2055///
2056/// \param ReturnType If we're determining the copy elision candidate for
2057/// a return statement, this is the return type of the function. If we're
2058/// determining the copy elision candidate for a throw expression, this will
2059/// be a NULL type.
2060///
2061/// \param E The expression being returned from the function or block, or
2062/// being thrown.
2063///
2064/// \param AllowFunctionParameter Whether we allow function parameters to
2065/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2066/// we re-use this logic to determine whether we should try to move as part of
2067/// a return or throw (which does allow function parameters).
2068///
2069/// \returns The NRVO candidate variable, if the return statement may use the
2070/// NRVO, or NULL if there is no such candidate.
2071const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2072                                             Expr *E,
2073                                             bool AllowFunctionParameter) {
2074  QualType ExprType = E->getType();
2075  // - in a return statement in a function with ...
2076  // ... a class return type ...
2077  if (!ReturnType.isNull()) {
2078    if (!ReturnType->isRecordType())
2079      return 0;
2080    // ... the same cv-unqualified type as the function return type ...
2081    if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
2082      return 0;
2083  }
2084
2085  // ... the expression is the name of a non-volatile automatic object
2086  // (other than a function or catch-clause parameter)) ...
2087  const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
2088  if (!DR || DR->refersToEnclosingLocal())
2089    return 0;
2090  const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2091  if (!VD)
2092    return 0;
2093
2094  // ...object (other than a function or catch-clause parameter)...
2095  if (VD->getKind() != Decl::Var &&
2096      !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
2097    return 0;
2098  if (VD->isExceptionVariable()) return 0;
2099
2100  // ...automatic...
2101  if (!VD->hasLocalStorage()) return 0;
2102
2103  // ...non-volatile...
2104  if (VD->getType().isVolatileQualified()) return 0;
2105  if (VD->getType()->isReferenceType()) return 0;
2106
2107  // __block variables can't be allocated in a way that permits NRVO.
2108  if (VD->hasAttr<BlocksAttr>()) return 0;
2109
2110  // Variables with higher required alignment than their type's ABI
2111  // alignment cannot use NRVO.
2112  if (VD->hasAttr<AlignedAttr>() &&
2113      Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2114    return 0;
2115
2116  return VD;
2117}
2118
2119/// \brief Perform the initialization of a potentially-movable value, which
2120/// is the result of return value.
2121///
2122/// This routine implements C++0x [class.copy]p33, which attempts to treat
2123/// returned lvalues as rvalues in certain cases (to prefer move construction),
2124/// then falls back to treating them as lvalues if that failed.
2125ExprResult
2126Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2127                                      const VarDecl *NRVOCandidate,
2128                                      QualType ResultType,
2129                                      Expr *Value,
2130                                      bool AllowNRVO) {
2131  // C++0x [class.copy]p33:
2132  //   When the criteria for elision of a copy operation are met or would
2133  //   be met save for the fact that the source object is a function
2134  //   parameter, and the object to be copied is designated by an lvalue,
2135  //   overload resolution to select the constructor for the copy is first
2136  //   performed as if the object were designated by an rvalue.
2137  ExprResult Res = ExprError();
2138  if (AllowNRVO &&
2139      (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
2140    ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
2141                              Value->getType(), CK_NoOp, Value, VK_XValue);
2142
2143    Expr *InitExpr = &AsRvalue;
2144    InitializationKind Kind
2145      = InitializationKind::CreateCopy(Value->getLocStart(),
2146                                       Value->getLocStart());
2147    InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
2148
2149    //   [...] If overload resolution fails, or if the type of the first
2150    //   parameter of the selected constructor is not an rvalue reference
2151    //   to the object's type (possibly cv-qualified), overload resolution
2152    //   is performed again, considering the object as an lvalue.
2153    if (Seq) {
2154      for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2155           StepEnd = Seq.step_end();
2156           Step != StepEnd; ++Step) {
2157        if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
2158          continue;
2159
2160        CXXConstructorDecl *Constructor
2161        = cast<CXXConstructorDecl>(Step->Function.Function);
2162
2163        const RValueReferenceType *RRefType
2164          = Constructor->getParamDecl(0)->getType()
2165                                                 ->getAs<RValueReferenceType>();
2166
2167        // If we don't meet the criteria, break out now.
2168        if (!RRefType ||
2169            !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2170                            Context.getTypeDeclType(Constructor->getParent())))
2171          break;
2172
2173        // Promote "AsRvalue" to the heap, since we now need this
2174        // expression node to persist.
2175        Value = ImplicitCastExpr::Create(Context, Value->getType(),
2176                                         CK_NoOp, Value, 0, VK_XValue);
2177
2178        // Complete type-checking the initialization of the return type
2179        // using the constructor we found.
2180        Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
2181      }
2182    }
2183  }
2184
2185  // Either we didn't meet the criteria for treating an lvalue as an rvalue,
2186  // above, or overload resolution failed. Either way, we need to try
2187  // (again) now with the return value expression as written.
2188  if (Res.isInvalid())
2189    Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
2190
2191  return Res;
2192}
2193
2194/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2195/// for capturing scopes.
2196///
2197StmtResult
2198Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2199  // If this is the first return we've seen, infer the return type.
2200  // [expr.prim.lambda]p4 in C++11; block literals follow a superset of those
2201  // rules which allows multiple return statements.
2202  CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
2203  QualType FnRetType = CurCap->ReturnType;
2204
2205  // For blocks/lambdas with implicit return types, we check each return
2206  // statement individually, and deduce the common return type when the block
2207  // or lambda is completed.
2208  if (CurCap->HasImplicitReturnType) {
2209    if (RetValExp && !isa<InitListExpr>(RetValExp)) {
2210      ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2211      if (Result.isInvalid())
2212        return StmtError();
2213      RetValExp = Result.take();
2214
2215      if (!RetValExp->isTypeDependent())
2216        FnRetType = RetValExp->getType();
2217      else
2218        FnRetType = CurCap->ReturnType = Context.DependentTy;
2219    } else {
2220      if (RetValExp) {
2221        // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2222        // initializer list, because it is not an expression (even
2223        // though we represent it as one). We still deduce 'void'.
2224        Diag(ReturnLoc, diag::err_lambda_return_init_list)
2225          << RetValExp->getSourceRange();
2226      }
2227
2228      FnRetType = Context.VoidTy;
2229    }
2230
2231    // Although we'll properly infer the type of the block once it's completed,
2232    // make sure we provide a return type now for better error recovery.
2233    if (CurCap->ReturnType.isNull())
2234      CurCap->ReturnType = FnRetType;
2235  }
2236  assert(!FnRetType.isNull());
2237
2238  if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
2239    if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2240      Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2241      return StmtError();
2242    }
2243  } else {
2244    LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CurCap);
2245    if (LSI->CallOperator->getType()->getAs<FunctionType>()->getNoReturnAttr()){
2246      Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2247      return StmtError();
2248    }
2249  }
2250
2251  // Otherwise, verify that this result type matches the previous one.  We are
2252  // pickier with blocks than for normal functions because we don't have GCC
2253  // compatibility to worry about here.
2254  const VarDecl *NRVOCandidate = 0;
2255  if (FnRetType->isDependentType()) {
2256    // Delay processing for now.  TODO: there are lots of dependent
2257    // types we can conclusively prove aren't void.
2258  } else if (FnRetType->isVoidType()) {
2259    if (RetValExp && !isa<InitListExpr>(RetValExp) &&
2260        !(getLangOpts().CPlusPlus &&
2261          (RetValExp->isTypeDependent() ||
2262           RetValExp->getType()->isVoidType()))) {
2263      if (!getLangOpts().CPlusPlus &&
2264          RetValExp->getType()->isVoidType())
2265        Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
2266      else {
2267        Diag(ReturnLoc, diag::err_return_block_has_expr);
2268        RetValExp = 0;
2269      }
2270    }
2271  } else if (!RetValExp) {
2272    return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2273  } else if (!RetValExp->isTypeDependent()) {
2274    // we have a non-void block with an expression, continue checking
2275
2276    // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2277    // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2278    // function return.
2279
2280    // In C++ the return statement is handled via a copy initialization.
2281    // the C version of which boils down to CheckSingleAssignmentConstraints.
2282    NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2283    InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2284                                                                   FnRetType,
2285                                                          NRVOCandidate != 0);
2286    ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2287                                                     FnRetType, RetValExp);
2288    if (Res.isInvalid()) {
2289      // FIXME: Cleanup temporaries here, anyway?
2290      return StmtError();
2291    }
2292    RetValExp = Res.take();
2293    CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
2294  }
2295
2296  if (RetValExp) {
2297    CheckImplicitConversions(RetValExp, ReturnLoc);
2298    RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2299  }
2300  ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2301                                                NRVOCandidate);
2302
2303  // If we need to check for the named return value optimization,
2304  // or if we need to infer the return type,
2305  // save the return statement in our scope for later processing.
2306  if (CurCap->HasImplicitReturnType ||
2307      (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
2308       !CurContext->isDependentContext()))
2309    FunctionScopes.back()->Returns.push_back(Result);
2310
2311  return Owned(Result);
2312}
2313
2314StmtResult
2315Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2316  // Check for unexpanded parameter packs.
2317  if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2318    return StmtError();
2319
2320  if (isa<CapturingScopeInfo>(getCurFunction()))
2321    return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
2322
2323  QualType FnRetType;
2324  QualType RelatedRetType;
2325  if (const FunctionDecl *FD = getCurFunctionDecl()) {
2326    FnRetType = FD->getResultType();
2327    if (FD->hasAttr<NoReturnAttr>() ||
2328        FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
2329      Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
2330        << FD->getDeclName();
2331  } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2332    FnRetType = MD->getResultType();
2333    if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2334      // In the implementation of a method with a related return type, the
2335      // type used to type-check the validity of return statements within the
2336      // method body is a pointer to the type of the class being implemented.
2337      RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2338      RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
2339    }
2340  } else // If we don't have a function/method context, bail.
2341    return StmtError();
2342
2343  ReturnStmt *Result = 0;
2344  if (FnRetType->isVoidType()) {
2345    if (RetValExp) {
2346      if (isa<InitListExpr>(RetValExp)) {
2347        // We simply never allow init lists as the return value of void
2348        // functions. This is compatible because this was never allowed before,
2349        // so there's no legacy code to deal with.
2350        NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2351        int FunctionKind = 0;
2352        if (isa<ObjCMethodDecl>(CurDecl))
2353          FunctionKind = 1;
2354        else if (isa<CXXConstructorDecl>(CurDecl))
2355          FunctionKind = 2;
2356        else if (isa<CXXDestructorDecl>(CurDecl))
2357          FunctionKind = 3;
2358
2359        Diag(ReturnLoc, diag::err_return_init_list)
2360          << CurDecl->getDeclName() << FunctionKind
2361          << RetValExp->getSourceRange();
2362
2363        // Drop the expression.
2364        RetValExp = 0;
2365      } else if (!RetValExp->isTypeDependent()) {
2366        // C99 6.8.6.4p1 (ext_ since GCC warns)
2367        unsigned D = diag::ext_return_has_expr;
2368        if (RetValExp->getType()->isVoidType())
2369          D = diag::ext_return_has_void_expr;
2370        else {
2371          ExprResult Result = Owned(RetValExp);
2372          Result = IgnoredValueConversions(Result.take());
2373          if (Result.isInvalid())
2374            return StmtError();
2375          RetValExp = Result.take();
2376          RetValExp = ImpCastExprToType(RetValExp,
2377                                        Context.VoidTy, CK_ToVoid).take();
2378        }
2379
2380        // return (some void expression); is legal in C++.
2381        if (D != diag::ext_return_has_void_expr ||
2382            !getLangOpts().CPlusPlus) {
2383          NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2384
2385          int FunctionKind = 0;
2386          if (isa<ObjCMethodDecl>(CurDecl))
2387            FunctionKind = 1;
2388          else if (isa<CXXConstructorDecl>(CurDecl))
2389            FunctionKind = 2;
2390          else if (isa<CXXDestructorDecl>(CurDecl))
2391            FunctionKind = 3;
2392
2393          Diag(ReturnLoc, D)
2394            << CurDecl->getDeclName() << FunctionKind
2395            << RetValExp->getSourceRange();
2396        }
2397      }
2398
2399      if (RetValExp) {
2400        CheckImplicitConversions(RetValExp, ReturnLoc);
2401        RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2402      }
2403    }
2404
2405    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
2406  } else if (!RetValExp && !FnRetType->isDependentType()) {
2407    unsigned DiagID = diag::warn_return_missing_expr;  // C90 6.6.6.4p4
2408    // C99 6.8.6.4p1 (ext_ since GCC warns)
2409    if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
2410
2411    if (FunctionDecl *FD = getCurFunctionDecl())
2412      Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
2413    else
2414      Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
2415    Result = new (Context) ReturnStmt(ReturnLoc);
2416  } else {
2417    const VarDecl *NRVOCandidate = 0;
2418    if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
2419      // we have a non-void function with an expression, continue checking
2420
2421      if (!RelatedRetType.isNull()) {
2422        // If we have a related result type, perform an extra conversion here.
2423        // FIXME: The diagnostics here don't really describe what is happening.
2424        InitializedEntity Entity =
2425            InitializedEntity::InitializeTemporary(RelatedRetType);
2426
2427        ExprResult Res = PerformCopyInitialization(Entity, SourceLocation(),
2428                                                   RetValExp);
2429        if (Res.isInvalid()) {
2430          // FIXME: Cleanup temporaries here, anyway?
2431          return StmtError();
2432        }
2433        RetValExp = Res.takeAs<Expr>();
2434      }
2435
2436      // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2437      // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2438      // function return.
2439
2440      // In C++ the return statement is handled via a copy initialization,
2441      // the C version of which boils down to CheckSingleAssignmentConstraints.
2442      NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2443      InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2444                                                                     FnRetType,
2445                                                            NRVOCandidate != 0);
2446      ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2447                                                       FnRetType, RetValExp);
2448      if (Res.isInvalid()) {
2449        // FIXME: Cleanup temporaries here, anyway?
2450        return StmtError();
2451      }
2452
2453      RetValExp = Res.takeAs<Expr>();
2454      if (RetValExp)
2455        CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
2456    }
2457
2458    if (RetValExp) {
2459      CheckImplicitConversions(RetValExp, ReturnLoc);
2460      RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2461    }
2462    Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
2463  }
2464
2465  // If we need to check for the named return value optimization, save the
2466  // return statement in our scope for later processing.
2467  if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
2468      !CurContext->isDependentContext())
2469    FunctionScopes.back()->Returns.push_back(Result);
2470
2471  return Owned(Result);
2472}
2473
2474/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
2475/// ignore "noop" casts in places where an lvalue is required by an inline asm.
2476/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
2477/// provide a strong guidance to not use it.
2478///
2479/// This method checks to see if the argument is an acceptable l-value and
2480/// returns false if it is a case we can handle.
2481static bool CheckAsmLValue(const Expr *E, Sema &S) {
2482  // Type dependent expressions will be checked during instantiation.
2483  if (E->isTypeDependent())
2484    return false;
2485
2486  if (E->isLValue())
2487    return false;  // Cool, this is an lvalue.
2488
2489  // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
2490  // are supposed to allow.
2491  const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
2492  if (E != E2 && E2->isLValue()) {
2493    if (!S.getLangOpts().HeinousExtensions)
2494      S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
2495        << E->getSourceRange();
2496    else
2497      S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
2498        << E->getSourceRange();
2499    // Accept, even if we emitted an error diagnostic.
2500    return false;
2501  }
2502
2503  // None of the above, just randomly invalid non-lvalue.
2504  return true;
2505}
2506
2507/// isOperandMentioned - Return true if the specified operand # is mentioned
2508/// anywhere in the decomposed asm string.
2509static bool isOperandMentioned(unsigned OpNo,
2510                         ArrayRef<AsmStmt::AsmStringPiece> AsmStrPieces) {
2511  for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
2512    const AsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
2513    if (!Piece.isOperand()) continue;
2514
2515    // If this is a reference to the input and if the input was the smaller
2516    // one, then we have to reject this asm.
2517    if (Piece.getOperandNo() == OpNo)
2518      return true;
2519  }
2520  return false;
2521}
2522
2523StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, bool IsSimple,
2524                              bool IsVolatile, unsigned NumOutputs,
2525                              unsigned NumInputs, IdentifierInfo **Names,
2526                              MultiExprArg constraints, MultiExprArg exprs,
2527                              Expr *asmString, MultiExprArg clobbers,
2528                              SourceLocation RParenLoc, bool MSAsm) {
2529  unsigned NumClobbers = clobbers.size();
2530  StringLiteral **Constraints =
2531    reinterpret_cast<StringLiteral**>(constraints.get());
2532  Expr **Exprs = exprs.get();
2533  StringLiteral *AsmString = cast<StringLiteral>(asmString);
2534  StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
2535
2536  SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
2537
2538  // The parser verifies that there is a string literal here.
2539  if (!AsmString->isAscii())
2540    return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
2541      << AsmString->getSourceRange());
2542
2543  for (unsigned i = 0; i != NumOutputs; i++) {
2544    StringLiteral *Literal = Constraints[i];
2545    if (!Literal->isAscii())
2546      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2547        << Literal->getSourceRange());
2548
2549    StringRef OutputName;
2550    if (Names[i])
2551      OutputName = Names[i]->getName();
2552
2553    TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
2554    if (!Context.getTargetInfo().validateOutputConstraint(Info))
2555      return StmtError(Diag(Literal->getLocStart(),
2556                            diag::err_asm_invalid_output_constraint)
2557                       << Info.getConstraintStr());
2558
2559    // Check that the output exprs are valid lvalues.
2560    Expr *OutputExpr = Exprs[i];
2561    if (CheckAsmLValue(OutputExpr, *this)) {
2562      return StmtError(Diag(OutputExpr->getLocStart(),
2563                  diag::err_asm_invalid_lvalue_in_output)
2564        << OutputExpr->getSourceRange());
2565    }
2566
2567    OutputConstraintInfos.push_back(Info);
2568  }
2569
2570  SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
2571
2572  for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
2573    StringLiteral *Literal = Constraints[i];
2574    if (!Literal->isAscii())
2575      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2576        << Literal->getSourceRange());
2577
2578    StringRef InputName;
2579    if (Names[i])
2580      InputName = Names[i]->getName();
2581
2582    TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
2583    if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos.data(),
2584                                                NumOutputs, Info)) {
2585      return StmtError(Diag(Literal->getLocStart(),
2586                            diag::err_asm_invalid_input_constraint)
2587                       << Info.getConstraintStr());
2588    }
2589
2590    Expr *InputExpr = Exprs[i];
2591
2592    // Only allow void types for memory constraints.
2593    if (Info.allowsMemory() && !Info.allowsRegister()) {
2594      if (CheckAsmLValue(InputExpr, *this))
2595        return StmtError(Diag(InputExpr->getLocStart(),
2596                              diag::err_asm_invalid_lvalue_in_input)
2597                         << Info.getConstraintStr()
2598                         << InputExpr->getSourceRange());
2599    }
2600
2601    if (Info.allowsRegister()) {
2602      if (InputExpr->getType()->isVoidType()) {
2603        return StmtError(Diag(InputExpr->getLocStart(),
2604                              diag::err_asm_invalid_type_in_input)
2605          << InputExpr->getType() << Info.getConstraintStr()
2606          << InputExpr->getSourceRange());
2607      }
2608    }
2609
2610    ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
2611    if (Result.isInvalid())
2612      return StmtError();
2613
2614    Exprs[i] = Result.take();
2615    InputConstraintInfos.push_back(Info);
2616  }
2617
2618  // Check that the clobbers are valid.
2619  for (unsigned i = 0; i != NumClobbers; i++) {
2620    StringLiteral *Literal = Clobbers[i];
2621    if (!Literal->isAscii())
2622      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2623        << Literal->getSourceRange());
2624
2625    StringRef Clobber = Literal->getString();
2626
2627    if (!Context.getTargetInfo().isValidClobber(Clobber))
2628      return StmtError(Diag(Literal->getLocStart(),
2629                  diag::err_asm_unknown_register_name) << Clobber);
2630  }
2631
2632  AsmStmt *NS =
2633    new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm,
2634                          NumOutputs, NumInputs, Names, Constraints, Exprs,
2635                          AsmString, NumClobbers, Clobbers, RParenLoc);
2636  // Validate the asm string, ensuring it makes sense given the operands we
2637  // have.
2638  SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
2639  unsigned DiagOffs;
2640  if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
2641    Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
2642           << AsmString->getSourceRange();
2643    return StmtError();
2644  }
2645
2646  // Validate tied input operands for type mismatches.
2647  for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
2648    TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
2649
2650    // If this is a tied constraint, verify that the output and input have
2651    // either exactly the same type, or that they are int/ptr operands with the
2652    // same size (int/long, int*/long, are ok etc).
2653    if (!Info.hasTiedOperand()) continue;
2654
2655    unsigned TiedTo = Info.getTiedOperand();
2656    unsigned InputOpNo = i+NumOutputs;
2657    Expr *OutputExpr = Exprs[TiedTo];
2658    Expr *InputExpr = Exprs[InputOpNo];
2659
2660    if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
2661      continue;
2662
2663    QualType InTy = InputExpr->getType();
2664    QualType OutTy = OutputExpr->getType();
2665    if (Context.hasSameType(InTy, OutTy))
2666      continue;  // All types can be tied to themselves.
2667
2668    // Decide if the input and output are in the same domain (integer/ptr or
2669    // floating point.
2670    enum AsmDomain {
2671      AD_Int, AD_FP, AD_Other
2672    } InputDomain, OutputDomain;
2673
2674    if (InTy->isIntegerType() || InTy->isPointerType())
2675      InputDomain = AD_Int;
2676    else if (InTy->isRealFloatingType())
2677      InputDomain = AD_FP;
2678    else
2679      InputDomain = AD_Other;
2680
2681    if (OutTy->isIntegerType() || OutTy->isPointerType())
2682      OutputDomain = AD_Int;
2683    else if (OutTy->isRealFloatingType())
2684      OutputDomain = AD_FP;
2685    else
2686      OutputDomain = AD_Other;
2687
2688    // They are ok if they are the same size and in the same domain.  This
2689    // allows tying things like:
2690    //   void* to int*
2691    //   void* to int            if they are the same size.
2692    //   double to long double   if they are the same size.
2693    //
2694    uint64_t OutSize = Context.getTypeSize(OutTy);
2695    uint64_t InSize = Context.getTypeSize(InTy);
2696    if (OutSize == InSize && InputDomain == OutputDomain &&
2697        InputDomain != AD_Other)
2698      continue;
2699
2700    // If the smaller input/output operand is not mentioned in the asm string,
2701    // then we can promote the smaller one to a larger input and the asm string
2702    // won't notice.
2703    bool SmallerValueMentioned = false;
2704
2705    // If this is a reference to the input and if the input was the smaller
2706    // one, then we have to reject this asm.
2707    if (isOperandMentioned(InputOpNo, Pieces)) {
2708      // This is a use in the asm string of the smaller operand.  Since we
2709      // codegen this by promoting to a wider value, the asm will get printed
2710      // "wrong".
2711      SmallerValueMentioned |= InSize < OutSize;
2712    }
2713    if (isOperandMentioned(TiedTo, Pieces)) {
2714      // If this is a reference to the output, and if the output is the larger
2715      // value, then it's ok because we'll promote the input to the larger type.
2716      SmallerValueMentioned |= OutSize < InSize;
2717    }
2718
2719    // If the smaller value wasn't mentioned in the asm string, and if the
2720    // output was a register, just extend the shorter one to the size of the
2721    // larger one.
2722    if (!SmallerValueMentioned && InputDomain != AD_Other &&
2723        OutputConstraintInfos[TiedTo].allowsRegister())
2724      continue;
2725
2726    // Either both of the operands were mentioned or the smaller one was
2727    // mentioned.  One more special case that we'll allow: if the tied input is
2728    // integer, unmentioned, and is a constant, then we'll allow truncating it
2729    // down to the size of the destination.
2730    if (InputDomain == AD_Int && OutputDomain == AD_Int &&
2731        !isOperandMentioned(InputOpNo, Pieces) &&
2732        InputExpr->isEvaluatable(Context)) {
2733      CastKind castKind =
2734        (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
2735      InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).take();
2736      Exprs[InputOpNo] = InputExpr;
2737      NS->setInputExpr(i, InputExpr);
2738      continue;
2739    }
2740
2741    Diag(InputExpr->getLocStart(),
2742         diag::err_asm_tying_incompatible_types)
2743      << InTy << OutTy << OutputExpr->getSourceRange()
2744      << InputExpr->getSourceRange();
2745    return StmtError();
2746  }
2747
2748  return Owned(NS);
2749}
2750
2751// needSpaceAsmToken - This function handles whitespace around asm punctuation.
2752// Returns true if a space should be emitted.
2753static inline bool needSpaceAsmToken(Token currTok) {
2754  static Token prevTok;
2755
2756  // No need for space after prevToken.
2757  switch(prevTok.getKind()) {
2758  default:
2759    break;
2760  case tok::l_square:
2761  case tok::r_square:
2762  case tok::l_brace:
2763  case tok::r_brace:
2764  case tok::colon:
2765    prevTok = currTok;
2766    return false;
2767  }
2768
2769  // No need for a space before currToken.
2770  switch(currTok.getKind()) {
2771  default:
2772    break;
2773  case tok::l_square:
2774  case tok::r_square:
2775  case tok::l_brace:
2776  case tok::r_brace:
2777  case tok::comma:
2778  case tok::colon:
2779    prevTok = currTok;
2780    return false;
2781  }
2782  prevTok = currTok;
2783  return true;
2784}
2785
2786static std::string PatchMSAsmString(Sema &SemaRef, bool &IsSimple,
2787                                    SourceLocation AsmLoc,
2788                                    ArrayRef<Token> AsmToks,
2789                                    const TargetInfo &TI) {
2790  // Assume simple asm stmt until we parse a non-register identifer.
2791  IsSimple = true;
2792
2793  if (AsmToks.empty())
2794    return "";
2795
2796  std::string Res;
2797  IdentifierInfo *II = AsmToks[0].getIdentifierInfo();
2798  Res = II->getName().str();
2799
2800  // Check the operands.
2801  for (unsigned i = 1, e = AsmToks.size(); i != e; ++i) {
2802    if (needSpaceAsmToken(AsmToks[i]))
2803        Res += " ";
2804
2805    switch (AsmToks[i].getKind()) {
2806    default:
2807      //llvm_unreachable("Unknown token.");
2808      break;
2809    case tok::comma: Res += ","; break;
2810    case tok::colon: Res += ":"; break;
2811    case tok::l_square: Res += "["; break;
2812    case tok::r_square: Res += "]"; break;
2813    case tok::l_brace: Res += "{"; break;
2814    case tok::r_brace: Res += "}"; break;
2815    case tok::numeric_constant: {
2816      SmallString<32> TokenBuf;
2817      TokenBuf.resize(32);
2818      bool StringInvalid = false;
2819      const char *ThisTokBuf = &TokenBuf[0];
2820      unsigned ThisTokLen =
2821        Lexer::getSpelling(AsmToks[i], ThisTokBuf, SemaRef.getSourceManager(),
2822                           SemaRef.getLangOpts(), &StringInvalid);
2823      Res += StringRef(ThisTokBuf, ThisTokLen);
2824      break;
2825    }
2826    case tok::identifier: {
2827      II = AsmToks[i].getIdentifierInfo();
2828      StringRef Name = II->getName();
2829
2830      // Valid registers don't need modification.
2831      if (TI.isValidGCCRegisterName(Name)) {
2832        Res += Name;
2833        break;
2834      }
2835
2836      // TODO: Lookup the identifier.
2837      IsSimple = false;
2838    }
2839    } // AsmToks[i].getKind()
2840  }
2841  return Res;
2842}
2843
2844// Build the unmodified MSAsmString.
2845static std::string buildMSAsmString(Sema &SemaRef,
2846                                    ArrayRef<Token> AsmToks,
2847                                    ArrayRef<unsigned> LineEnds) {
2848  if (AsmToks.empty())
2849    return "";
2850
2851  SmallString<512> Asm;
2852  SmallString<512> TokenBuf;
2853  TokenBuf.resize(512);
2854  unsigned AsmLineNum = 0;
2855  for (unsigned i = 0, e = AsmToks.size(); i < e; ++i) {
2856    const char *ThisTokBuf = &TokenBuf[0];
2857    bool StringInvalid = false;
2858    unsigned ThisTokLen =
2859      Lexer::getSpelling(AsmToks[i], ThisTokBuf, SemaRef.getSourceManager(),
2860                         SemaRef.getLangOpts(), &StringInvalid);
2861    if (i && (!AsmLineNum || i != LineEnds[AsmLineNum-1]) &&
2862        needSpaceAsmToken(AsmToks[i]))
2863      Asm += ' ';
2864    Asm += StringRef(ThisTokBuf, ThisTokLen);
2865    if (i + 1 == LineEnds[AsmLineNum] && i + 1 != AsmToks.size()) {
2866      Asm += '\n';
2867      ++AsmLineNum;
2868    }
2869  }
2870  return Asm.c_str();
2871}
2872
2873StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc,
2874                                ArrayRef<Token> AsmToks,
2875                                ArrayRef<unsigned> LineEnds,
2876                                SourceLocation EndLoc) {
2877  // MS-style inline assembly is not fully supported, so emit a warning.
2878  Diag(AsmLoc, diag::warn_unsupported_msasm);
2879
2880  std::string AsmString = buildMSAsmString(*this, AsmToks, LineEnds);
2881
2882  bool IsSimple;
2883  // Rewrite operands to appease the AsmParser.
2884  std::string PatchedAsmString =
2885    PatchMSAsmString(*this, IsSimple, AsmLoc, AsmToks, Context.getTargetInfo());
2886
2887  // Silence compiler warnings.  Eventually, the PatchedAsmString will be
2888  // passed to the AsmParser.
2889  (void)PatchedAsmString;
2890
2891  // Initialize targets and assembly printers/parsers.
2892  llvm::InitializeAllTargetInfos();
2893  llvm::InitializeAllTargetMCs();
2894  llvm::InitializeAllAsmParsers();
2895
2896  MSAsmStmt *NS =
2897    new (Context) MSAsmStmt(Context, AsmLoc, IsSimple, /* IsVolatile */ true,
2898                            AsmToks, LineEnds, AsmString, EndLoc);
2899
2900  return Owned(NS);
2901}
2902
2903StmtResult
2904Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
2905                           SourceLocation RParen, Decl *Parm,
2906                           Stmt *Body) {
2907  VarDecl *Var = cast_or_null<VarDecl>(Parm);
2908  if (Var && Var->isInvalidDecl())
2909    return StmtError();
2910
2911  return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
2912}
2913
2914StmtResult
2915Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
2916  return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
2917}
2918
2919StmtResult
2920Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
2921                         MultiStmtArg CatchStmts, Stmt *Finally) {
2922  if (!getLangOpts().ObjCExceptions)
2923    Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
2924
2925  getCurFunction()->setHasBranchProtectedScope();
2926  unsigned NumCatchStmts = CatchStmts.size();
2927  return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
2928                                     CatchStmts.release(),
2929                                     NumCatchStmts,
2930                                     Finally));
2931}
2932
2933StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
2934  if (Throw) {
2935    ExprResult Result = DefaultLvalueConversion(Throw);
2936    if (Result.isInvalid())
2937      return StmtError();
2938
2939    Throw = MaybeCreateExprWithCleanups(Result.take());
2940    QualType ThrowType = Throw->getType();
2941    // Make sure the expression type is an ObjC pointer or "void *".
2942    if (!ThrowType->isDependentType() &&
2943        !ThrowType->isObjCObjectPointerType()) {
2944      const PointerType *PT = ThrowType->getAs<PointerType>();
2945      if (!PT || !PT->getPointeeType()->isVoidType())
2946        return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
2947                         << Throw->getType() << Throw->getSourceRange());
2948    }
2949  }
2950
2951  return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
2952}
2953
2954StmtResult
2955Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
2956                           Scope *CurScope) {
2957  if (!getLangOpts().ObjCExceptions)
2958    Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
2959
2960  if (!Throw) {
2961    // @throw without an expression designates a rethrow (which much occur
2962    // in the context of an @catch clause).
2963    Scope *AtCatchParent = CurScope;
2964    while (AtCatchParent && !AtCatchParent->isAtCatchScope())
2965      AtCatchParent = AtCatchParent->getParent();
2966    if (!AtCatchParent)
2967      return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
2968  }
2969  return BuildObjCAtThrowStmt(AtLoc, Throw);
2970}
2971
2972ExprResult
2973Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
2974  ExprResult result = DefaultLvalueConversion(operand);
2975  if (result.isInvalid())
2976    return ExprError();
2977  operand = result.take();
2978
2979  // Make sure the expression type is an ObjC pointer or "void *".
2980  QualType type = operand->getType();
2981  if (!type->isDependentType() &&
2982      !type->isObjCObjectPointerType()) {
2983    const PointerType *pointerType = type->getAs<PointerType>();
2984    if (!pointerType || !pointerType->getPointeeType()->isVoidType())
2985      return Diag(atLoc, diag::error_objc_synchronized_expects_object)
2986               << type << operand->getSourceRange();
2987  }
2988
2989  // The operand to @synchronized is a full-expression.
2990  return MaybeCreateExprWithCleanups(operand);
2991}
2992
2993StmtResult
2994Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
2995                                  Stmt *SyncBody) {
2996  // We can't jump into or indirect-jump out of a @synchronized block.
2997  getCurFunction()->setHasBranchProtectedScope();
2998  return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
2999}
3000
3001/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3002/// and creates a proper catch handler from them.
3003StmtResult
3004Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
3005                         Stmt *HandlerBlock) {
3006  // There's nothing to test that ActOnExceptionDecl didn't already test.
3007  return Owned(new (Context) CXXCatchStmt(CatchLoc,
3008                                          cast_or_null<VarDecl>(ExDecl),
3009                                          HandlerBlock));
3010}
3011
3012StmtResult
3013Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3014  getCurFunction()->setHasBranchProtectedScope();
3015  return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
3016}
3017
3018namespace {
3019
3020class TypeWithHandler {
3021  QualType t;
3022  CXXCatchStmt *stmt;
3023public:
3024  TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
3025  : t(type), stmt(statement) {}
3026
3027  // An arbitrary order is fine as long as it places identical
3028  // types next to each other.
3029  bool operator<(const TypeWithHandler &y) const {
3030    if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
3031      return true;
3032    if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
3033      return false;
3034    else
3035      return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
3036  }
3037
3038  bool operator==(const TypeWithHandler& other) const {
3039    return t == other.t;
3040  }
3041
3042  CXXCatchStmt *getCatchStmt() const { return stmt; }
3043  SourceLocation getTypeSpecStartLoc() const {
3044    return stmt->getExceptionDecl()->getTypeSpecStartLoc();
3045  }
3046};
3047
3048}
3049
3050/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3051/// handlers and creates a try statement from them.
3052StmtResult
3053Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3054                       MultiStmtArg RawHandlers) {
3055  // Don't report an error if 'try' is used in system headers.
3056  if (!getLangOpts().CXXExceptions &&
3057      !getSourceManager().isInSystemHeader(TryLoc))
3058      Diag(TryLoc, diag::err_exceptions_disabled) << "try";
3059
3060  unsigned NumHandlers = RawHandlers.size();
3061  assert(NumHandlers > 0 &&
3062         "The parser shouldn't call this if there are no handlers.");
3063  Stmt **Handlers = RawHandlers.get();
3064
3065  SmallVector<TypeWithHandler, 8> TypesWithHandlers;
3066
3067  for (unsigned i = 0; i < NumHandlers; ++i) {
3068    CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
3069    if (!Handler->getExceptionDecl()) {
3070      if (i < NumHandlers - 1)
3071        return StmtError(Diag(Handler->getLocStart(),
3072                              diag::err_early_catch_all));
3073
3074      continue;
3075    }
3076
3077    const QualType CaughtType = Handler->getCaughtType();
3078    const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
3079    TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
3080  }
3081
3082  // Detect handlers for the same type as an earlier one.
3083  if (NumHandlers > 1) {
3084    llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
3085
3086    TypeWithHandler prev = TypesWithHandlers[0];
3087    for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
3088      TypeWithHandler curr = TypesWithHandlers[i];
3089
3090      if (curr == prev) {
3091        Diag(curr.getTypeSpecStartLoc(),
3092             diag::warn_exception_caught_by_earlier_handler)
3093          << curr.getCatchStmt()->getCaughtType().getAsString();
3094        Diag(prev.getTypeSpecStartLoc(),
3095             diag::note_previous_exception_handler)
3096          << prev.getCatchStmt()->getCaughtType().getAsString();
3097      }
3098
3099      prev = curr;
3100    }
3101  }
3102
3103  getCurFunction()->setHasBranchProtectedScope();
3104
3105  // FIXME: We should detect handlers that cannot catch anything because an
3106  // earlier handler catches a superclass. Need to find a method that is not
3107  // quadratic for this.
3108  // Neither of these are explicitly forbidden, but every compiler detects them
3109  // and warns.
3110
3111  return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
3112                                  Handlers, NumHandlers));
3113}
3114
3115StmtResult
3116Sema::ActOnSEHTryBlock(bool IsCXXTry,
3117                       SourceLocation TryLoc,
3118                       Stmt *TryBlock,
3119                       Stmt *Handler) {
3120  assert(TryBlock && Handler);
3121
3122  getCurFunction()->setHasBranchProtectedScope();
3123
3124  return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
3125}
3126
3127StmtResult
3128Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3129                          Expr *FilterExpr,
3130                          Stmt *Block) {
3131  assert(FilterExpr && Block);
3132
3133  if(!FilterExpr->getType()->isIntegerType()) {
3134    return StmtError(Diag(FilterExpr->getExprLoc(),
3135                     diag::err_filter_expression_integral)
3136                     << FilterExpr->getType());
3137  }
3138
3139  return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
3140}
3141
3142StmtResult
3143Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
3144                           Stmt *Block) {
3145  assert(Block);
3146  return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
3147}
3148
3149StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3150                                            bool IsIfExists,
3151                                            NestedNameSpecifierLoc QualifierLoc,
3152                                            DeclarationNameInfo NameInfo,
3153                                            Stmt *Nested)
3154{
3155  return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
3156                                             QualifierLoc, NameInfo,
3157                                             cast<CompoundStmt>(Nested));
3158}
3159
3160
3161StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
3162                                            bool IsIfExists,
3163                                            CXXScopeSpec &SS,
3164                                            UnqualifiedId &Name,
3165                                            Stmt *Nested) {
3166  return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
3167                                    SS.getWithLocInContext(Context),
3168                                    GetNameFromUnqualifiedId(Name),
3169                                    Nested);
3170}
3171