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