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