1 //===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for statements.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTDiagnostic.h"
17 #include "clang/AST/CharUnits.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/EvaluatedExprVisitor.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/StmtCXX.h"
23 #include "clang/AST/StmtObjC.h"
24 #include "clang/AST/TypeLoc.h"
25 #include "clang/Lex/Preprocessor.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/Scope.h"
29 #include "clang/Sema/ScopeInfo.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;
38 StmtResult Sema::ActOnExprStmt(ExprResult FE) {
42 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
43 /*DiscardedValue*/ true);
47 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
48 // void expression for its side effects. Conversion to void allows any
49 // operand, even incomplete types.
51 // Same thing in for stmt first clause (when expr) and third clause.
52 return Owned(static_cast<Stmt*>(FE.take()));
56 StmtResult Sema::ActOnExprStmtError() {
57 DiscardCleanupsInEvaluationContext();
61 StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
62 bool HasLeadingEmptyMacro) {
63 return Owned(new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro));
66 StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
67 SourceLocation EndLoc) {
68 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
70 // If we have an invalid decl, just return an error.
71 if (DG.isNull()) return StmtError();
73 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
76 void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
77 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
79 // If we don't have a declaration, or we have an invalid declaration,
81 if (DG.isNull() || !DG.isSingleDecl())
84 Decl *decl = DG.getSingleDecl();
85 if (!decl || decl->isInvalidDecl())
88 // Only variable declarations are permitted.
89 VarDecl *var = dyn_cast<VarDecl>(decl);
91 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
92 decl->setInvalidDecl();
96 // suppress any potential 'unused variable' warning.
99 // foreach variables are never actually initialized in the way that
100 // the parser came up with.
103 // In ARC, we don't need to retain the iteration variable of a fast
104 // enumeration loop. Rather than actually trying to catch that
105 // during declaration processing, we remove the consequences here.
106 if (getLangOpts().ObjCAutoRefCount) {
107 QualType type = var->getType();
109 // Only do this if we inferred the lifetime. Inferred lifetime
110 // will show up as a local qualifier because explicit lifetime
111 // should have shown up as an AttributedType instead.
112 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
113 // Add 'const' and mark the variable as pseudo-strong.
114 var->setType(type.withConst());
115 var->setARCPseudoStrong(true);
120 /// \brief Diagnose unused '==' and '!=' as likely typos for '=' or '|='.
122 /// Adding a cast to void (or other expression wrappers) will prevent the
123 /// warning from firing.
124 static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
126 bool IsNotEqual, CanAssign;
128 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
129 if (Op->getOpcode() != BO_EQ && Op->getOpcode() != BO_NE)
132 Loc = Op->getOperatorLoc();
133 IsNotEqual = Op->getOpcode() == BO_NE;
134 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
135 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
136 if (Op->getOperator() != OO_EqualEqual &&
137 Op->getOperator() != OO_ExclaimEqual)
140 Loc = Op->getOperatorLoc();
141 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
142 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
144 // Not a typo-prone comparison.
148 // Suppress warnings when the operator, suspicious as it may be, comes from
149 // a macro expansion.
150 if (S.SourceMgr.isMacroBodyExpansion(Loc))
153 S.Diag(Loc, diag::warn_unused_comparison)
154 << (unsigned)IsNotEqual << E->getSourceRange();
156 // If the LHS is a plausible entity to assign to, provide a fixit hint to
157 // correct common typos.
160 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
161 << FixItHint::CreateReplacement(Loc, "|=");
163 S.Diag(Loc, diag::note_equality_comparison_to_assign)
164 << FixItHint::CreateReplacement(Loc, "=");
170 void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
171 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
172 return DiagnoseUnusedExprResult(Label->getSubStmt());
174 const Expr *E = dyn_cast_or_null<Expr>(S);
177 SourceLocation ExprLoc = E->IgnoreParens()->getExprLoc();
178 // In most cases, we don't want to warn if the expression is written in a
179 // macro body, or if the macro comes from a system header. If the offending
180 // expression is a call to a function with the warn_unused_result attribute,
181 // we warn no matter the location. Because of the order in which the various
182 // checks need to happen, we factor out the macro-related test here.
183 bool ShouldSuppress =
184 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
185 SourceMgr.isInSystemMacro(ExprLoc);
187 const Expr *WarnExpr;
190 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
193 // If this is a GNU statement expression expanded from a macro, it is probably
194 // unused because it is a function-like macro that can be used as either an
195 // expression or statement. Don't warn, because it is almost certainly a
197 if (isa<StmtExpr>(E) && Loc.isMacroID())
200 // Okay, we have an unused result. Depending on what the base expression is,
201 // we might want to make a more specific diagnostic. Check for one of these
203 unsigned DiagID = diag::warn_unused_expr;
204 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
205 E = Temps->getSubExpr();
206 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
207 E = TempExpr->getSubExpr();
209 if (DiagnoseUnusedComparison(*this, E))
213 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
214 if (E->getType()->isVoidType())
217 // If the callee has attribute pure, const, or warn_unused_result, warn with
218 // a more specific message to make it clear what is happening. If the call
219 // is written in a macro body, only warn if it has the warn_unused_result
221 if (const Decl *FD = CE->getCalleeDecl()) {
222 if (FD->getAttr<WarnUnusedResultAttr>()) {
223 Diag(Loc, diag::warn_unused_result) << R1 << R2;
228 if (FD->getAttr<PureAttr>()) {
229 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
232 if (FD->getAttr<ConstAttr>()) {
233 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
237 } else if (ShouldSuppress)
240 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
241 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
242 Diag(Loc, diag::err_arc_unused_init_message) << R1;
245 const ObjCMethodDecl *MD = ME->getMethodDecl();
246 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
247 Diag(Loc, diag::warn_unused_result) << R1 << R2;
250 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
251 const Expr *Source = POE->getSyntacticForm();
252 if (isa<ObjCSubscriptRefExpr>(Source))
253 DiagID = diag::warn_unused_container_subscript_expr;
255 DiagID = diag::warn_unused_property_expr;
256 } else if (const CXXFunctionalCastExpr *FC
257 = dyn_cast<CXXFunctionalCastExpr>(E)) {
258 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
259 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
262 // Diagnose "(void*) blah" as a typo for "(void) blah".
263 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
264 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
265 QualType T = TI->getType();
267 // We really do want to use the non-canonical type here.
268 if (T == Context.VoidPtrTy) {
269 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
271 Diag(Loc, diag::warn_unused_voidptr)
272 << FixItHint::CreateRemoval(TL.getStarLoc());
277 if (E->isGLValue() && E->getType().isVolatileQualified()) {
278 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
282 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
285 void Sema::ActOnStartOfCompoundStmt() {
289 void Sema::ActOnFinishOfCompoundStmt() {
293 sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
294 return getCurFunction()->CompoundScopes.back();
298 Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
299 MultiStmtArg elts, bool isStmtExpr) {
300 unsigned NumElts = elts.size();
301 Stmt **Elts = elts.data();
302 // If we're in C89 mode, check that we don't have any decls after stmts. If
303 // so, emit an extension diagnostic.
304 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
305 // Note that __extension__ can be around a decl.
307 // Skip over all declarations.
308 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
311 // We found the end of the list or a statement. Scan for another declstmt.
312 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
316 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
317 Diag(D->getLocation(), diag::ext_mixed_decls_code);
320 // Warn about unused expressions in statements.
321 for (unsigned i = 0; i != NumElts; ++i) {
322 // Ignore statements that are last in a statement expression.
323 if (isStmtExpr && i == NumElts - 1)
326 DiagnoseUnusedExprResult(Elts[i]);
329 // Check for suspicious empty body (null statement) in `for' and `while'
330 // statements. Don't do anything for template instantiations, this just adds
332 if (NumElts != 0 && !CurrentInstantiationScope &&
333 getCurCompoundScope().HasEmptyLoopBodies) {
334 for (unsigned i = 0; i != NumElts - 1; ++i)
335 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
338 return Owned(new (Context) CompoundStmt(Context,
339 llvm::makeArrayRef(Elts, NumElts),
344 Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
345 SourceLocation DotDotDotLoc, Expr *RHSVal,
346 SourceLocation ColonLoc) {
347 assert((LHSVal != 0) && "missing expression in case statement");
349 if (getCurFunction()->SwitchStack.empty()) {
350 Diag(CaseLoc, diag::err_case_not_in_switch);
354 if (!getLangOpts().CPlusPlus11) {
355 // C99 6.8.4.2p3: The expression shall be an integer constant.
356 // However, GCC allows any evaluatable integer expression.
357 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
358 LHSVal = VerifyIntegerConstantExpression(LHSVal).take();
363 // GCC extension: The expression shall be an integer constant.
365 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
366 RHSVal = VerifyIntegerConstantExpression(RHSVal).take();
367 // Recover from an error by just forgetting about it.
371 LHSVal = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
372 getLangOpts().CPlusPlus11).take();
374 RHSVal = ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
375 getLangOpts().CPlusPlus11).take();
377 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
379 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
383 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
384 void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
385 DiagnoseUnusedExprResult(SubStmt);
387 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
388 CS->setSubStmt(SubStmt);
392 Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
393 Stmt *SubStmt, Scope *CurScope) {
394 DiagnoseUnusedExprResult(SubStmt);
396 if (getCurFunction()->SwitchStack.empty()) {
397 Diag(DefaultLoc, diag::err_default_not_in_switch);
398 return Owned(SubStmt);
401 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
402 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
407 Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
408 SourceLocation ColonLoc, Stmt *SubStmt) {
409 // If the label was multiply defined, reject it now.
410 if (TheDecl->getStmt()) {
411 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
412 Diag(TheDecl->getLocation(), diag::note_previous_definition);
413 return Owned(SubStmt);
416 // Otherwise, things are good. Fill in the declaration and return it.
417 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
418 TheDecl->setStmt(LS);
419 if (!TheDecl->isGnuLocal()) {
420 TheDecl->setLocStart(IdentLoc);
421 TheDecl->setLocation(IdentLoc);
426 StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
427 ArrayRef<const Attr*> Attrs,
429 // Fill in the declaration and return it.
430 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
435 Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
436 Stmt *thenStmt, SourceLocation ElseLoc,
438 // If the condition was invalid, discard the if statement. We could recover
439 // better by replacing it with a valid expr, but don't do that yet.
440 if (!CondVal.get() && !CondVar) {
441 getCurFunction()->setHasDroppedStmt();
445 ExprResult CondResult(CondVal.release());
447 VarDecl *ConditionVar = 0;
449 ConditionVar = cast<VarDecl>(CondVar);
450 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
451 if (CondResult.isInvalid())
454 Expr *ConditionExpr = CondResult.takeAs<Expr>();
458 DiagnoseUnusedExprResult(thenStmt);
461 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
462 diag::warn_empty_if_body);
465 DiagnoseUnusedExprResult(elseStmt);
467 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
468 thenStmt, ElseLoc, elseStmt));
471 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
472 /// the specified width and sign. If an overflow occurs, detect it and emit
473 /// the specified diagnostic.
474 void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
475 unsigned NewWidth, bool NewSign,
478 // Perform a conversion to the promoted condition type if needed.
479 if (NewWidth > Val.getBitWidth()) {
480 // If this is an extension, just do it.
481 Val = Val.extend(NewWidth);
482 Val.setIsSigned(NewSign);
484 // If the input was signed and negative and the output is
485 // unsigned, don't bother to warn: this is implementation-defined
487 // FIXME: Introduce a second, default-ignored warning for this case?
488 } else if (NewWidth < Val.getBitWidth()) {
489 // If this is a truncation, check for overflow.
490 llvm::APSInt ConvVal(Val);
491 ConvVal = ConvVal.trunc(NewWidth);
492 ConvVal.setIsSigned(NewSign);
493 ConvVal = ConvVal.extend(Val.getBitWidth());
494 ConvVal.setIsSigned(Val.isSigned());
496 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
498 // Regardless of whether a diagnostic was emitted, really do the
500 Val = Val.trunc(NewWidth);
501 Val.setIsSigned(NewSign);
502 } else if (NewSign != Val.isSigned()) {
503 // Convert the sign to match the sign of the condition. This can cause
504 // overflow as well: unsigned(INTMIN)
505 // We don't diagnose this overflow, because it is implementation-defined
507 // FIXME: Introduce a second, default-ignored warning for this case?
508 llvm::APSInt OldVal(Val);
509 Val.setIsSigned(NewSign);
514 struct CaseCompareFunctor {
515 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
516 const llvm::APSInt &RHS) {
517 return LHS.first < RHS;
519 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
520 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
521 return LHS.first < RHS.first;
523 bool operator()(const llvm::APSInt &LHS,
524 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
525 return LHS < RHS.first;
530 /// CmpCaseVals - Comparison predicate for sorting case values.
532 static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
533 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
534 if (lhs.first < rhs.first)
537 if (lhs.first == rhs.first &&
538 lhs.second->getCaseLoc().getRawEncoding()
539 < rhs.second->getCaseLoc().getRawEncoding())
544 /// CmpEnumVals - Comparison predicate for sorting enumeration values.
546 static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
547 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
549 return lhs.first < rhs.first;
552 /// EqEnumVals - Comparison preficate for uniqing enumeration values.
554 static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
555 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
557 return lhs.first == rhs.first;
560 /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
561 /// potentially integral-promoted expression @p expr.
562 static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
563 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
564 expr = cleanups->getSubExpr();
565 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
566 if (impcast->getCastKind() != CK_IntegralCast) break;
567 expr = impcast->getSubExpr();
569 return expr->getType();
573 Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
575 ExprResult CondResult;
577 VarDecl *ConditionVar = 0;
579 ConditionVar = cast<VarDecl>(CondVar);
580 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
581 if (CondResult.isInvalid())
584 Cond = CondResult.release();
590 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
594 SwitchConvertDiagnoser(Expr *Cond)
595 : ICEConvertDiagnoser(false, true), Cond(Cond) { }
597 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
599 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
602 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
604 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
605 << T << Cond->getSourceRange();
608 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
611 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
614 virtual DiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
616 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
617 << ConvTy->isEnumeralType() << ConvTy;
620 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
622 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
625 virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
627 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
628 << ConvTy->isEnumeralType() << ConvTy;
631 virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
634 return DiagnosticBuilder::getEmpty();
636 } SwitchDiagnoser(Cond);
639 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond, SwitchDiagnoser,
640 /*AllowScopedEnumerations*/ true);
641 if (CondResult.isInvalid()) return StmtError();
642 Cond = CondResult.take();
644 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
645 CondResult = UsualUnaryConversions(Cond);
646 if (CondResult.isInvalid()) return StmtError();
647 Cond = CondResult.take();
650 CondResult = ActOnFinishFullExpr(Cond, SwitchLoc);
651 if (CondResult.isInvalid())
653 Cond = CondResult.take();
656 getCurFunction()->setHasBranchIntoScope();
658 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
659 getCurFunction()->SwitchStack.push_back(SS);
663 static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
664 if (Val.getBitWidth() < BitWidth)
665 Val = Val.extend(BitWidth);
666 else if (Val.getBitWidth() > BitWidth)
667 Val = Val.trunc(BitWidth);
668 Val.setIsSigned(IsSigned);
672 Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
674 SwitchStmt *SS = cast<SwitchStmt>(Switch);
675 assert(SS == getCurFunction()->SwitchStack.back() &&
676 "switch stack missing push/pop!");
678 SS->setBody(BodyStmt, SwitchLoc);
679 getCurFunction()->SwitchStack.pop_back();
681 Expr *CondExpr = SS->getCond();
682 if (!CondExpr) return StmtError();
684 QualType CondType = CondExpr->getType();
686 Expr *CondExprBeforePromotion = CondExpr;
687 QualType CondTypeBeforePromotion =
688 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
691 // Integral promotions are performed (on the switch condition).
693 // A case value unrepresentable by the original switch condition
694 // type (before the promotion) doesn't make sense, even when it can
695 // be represented by the promoted type. Therefore we need to find
696 // the pre-promotion type of the switch condition.
697 if (!CondExpr->isTypeDependent()) {
698 // We have already converted the expression to an integral or enumeration
699 // type, when we started the switch statement. If we don't have an
700 // appropriate type now, just return an error.
701 if (!CondType->isIntegralOrEnumerationType())
704 if (CondExpr->isKnownToHaveBooleanValue()) {
705 // switch(bool_expr) {...} is often a programmer error, e.g.
706 // switch(n && mask) { ... } // Doh - should be "n & mask".
707 // One can always use an if statement instead of switch(bool_expr).
708 Diag(SwitchLoc, diag::warn_bool_switch_condition)
709 << CondExpr->getSourceRange();
713 // Get the bitwidth of the switched-on value before promotions. We must
714 // convert the integer case values to this width before comparison.
715 bool HasDependentValue
716 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
718 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
720 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
722 // Accumulate all of the case values in a vector so that we can sort them
723 // and detect duplicates. This vector contains the APInt for the case after
724 // it has been converted to the condition type.
725 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
728 // Keep track of any GNU case ranges we see. The APSInt is the low value.
729 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
730 CaseRangesTy CaseRanges;
732 DefaultStmt *TheDefaultStmt = 0;
734 bool CaseListIsErroneous = false;
736 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
737 SC = SC->getNextSwitchCase()) {
739 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
740 if (TheDefaultStmt) {
741 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
742 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
744 // FIXME: Remove the default statement from the switch block so that
745 // we'll return a valid AST. This requires recursing down the AST and
746 // finding it, not something we are set up to do right now. For now,
747 // just lop the entire switch stmt out of the AST.
748 CaseListIsErroneous = true;
753 CaseStmt *CS = cast<CaseStmt>(SC);
755 Expr *Lo = CS->getLHS();
757 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
758 HasDependentValue = true;
764 if (getLangOpts().CPlusPlus11) {
765 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
766 // constant expression of the promoted type of the switch condition.
768 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
769 if (ConvLo.isInvalid()) {
770 CaseListIsErroneous = true;
775 // We already verified that the expression has a i-c-e value (C99
776 // 6.8.4.2p3) - get that value now.
777 LoVal = Lo->EvaluateKnownConstInt(Context);
779 // If the LHS is not the same type as the condition, insert an implicit
781 Lo = DefaultLvalueConversion(Lo).take();
782 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
785 // Convert the value to the same width/sign as the condition had prior to
786 // integral promotions.
788 // FIXME: This causes us to reject valid code:
789 // switch ((char)c) { case 256: case 0: return 0; }
790 // Here we claim there is a duplicated condition value, but there is not.
791 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
793 diag::warn_case_value_overflow);
797 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
799 if (CS->getRHS()->isTypeDependent() ||
800 CS->getRHS()->isValueDependent()) {
801 HasDependentValue = true;
804 CaseRanges.push_back(std::make_pair(LoVal, CS));
806 CaseVals.push_back(std::make_pair(LoVal, CS));
810 if (!HasDependentValue) {
811 // If we don't have a default statement, check whether the
812 // condition is constant.
813 llvm::APSInt ConstantCondValue;
814 bool HasConstantCond = false;
815 if (!HasDependentValue && !TheDefaultStmt) {
817 = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context,
818 Expr::SE_AllowSideEffects);
819 assert(!HasConstantCond ||
820 (ConstantCondValue.getBitWidth() == CondWidth &&
821 ConstantCondValue.isSigned() == CondIsSigned));
823 bool ShouldCheckConstantCond = HasConstantCond;
825 // Sort all the scalar case values so we can easily detect duplicates.
826 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
828 if (!CaseVals.empty()) {
829 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
830 if (ShouldCheckConstantCond &&
831 CaseVals[i].first == ConstantCondValue)
832 ShouldCheckConstantCond = false;
834 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
835 // If we have a duplicate, report it.
836 // First, determine if either case value has a name
837 StringRef PrevString, CurrString;
838 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
839 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
840 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
841 PrevString = DeclRef->getDecl()->getName();
843 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
844 CurrString = DeclRef->getDecl()->getName();
846 SmallString<16> CaseValStr;
847 CaseVals[i-1].first.toString(CaseValStr);
849 if (PrevString == CurrString)
850 Diag(CaseVals[i].second->getLHS()->getLocStart(),
851 diag::err_duplicate_case) <<
852 (PrevString.empty() ? CaseValStr.str() : PrevString);
854 Diag(CaseVals[i].second->getLHS()->getLocStart(),
855 diag::err_duplicate_case_differing_expr) <<
856 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
857 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
860 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
861 diag::note_duplicate_case_prev);
862 // FIXME: We really want to remove the bogus case stmt from the
863 // substmt, but we have no way to do this right now.
864 CaseListIsErroneous = true;
869 // Detect duplicate case ranges, which usually don't exist at all in
871 if (!CaseRanges.empty()) {
872 // Sort all the case ranges by their low value so we can easily detect
873 // overlaps between ranges.
874 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
876 // Scan the ranges, computing the high values and removing empty ranges.
877 std::vector<llvm::APSInt> HiVals;
878 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
879 llvm::APSInt &LoVal = CaseRanges[i].first;
880 CaseStmt *CR = CaseRanges[i].second;
881 Expr *Hi = CR->getRHS();
884 if (getLangOpts().CPlusPlus11) {
885 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
886 // constant expression of the promoted type of the switch condition.
888 CheckConvertedConstantExpression(Hi, CondType, HiVal,
890 if (ConvHi.isInvalid()) {
891 CaseListIsErroneous = true;
896 HiVal = Hi->EvaluateKnownConstInt(Context);
898 // If the RHS is not the same type as the condition, insert an
900 Hi = DefaultLvalueConversion(Hi).take();
901 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
904 // Convert the value to the same width/sign as the condition.
905 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
907 diag::warn_case_value_overflow);
911 // If the low value is bigger than the high value, the case is empty.
913 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
914 << SourceRange(CR->getLHS()->getLocStart(),
916 CaseRanges.erase(CaseRanges.begin()+i);
921 if (ShouldCheckConstantCond &&
922 LoVal <= ConstantCondValue &&
923 ConstantCondValue <= HiVal)
924 ShouldCheckConstantCond = false;
926 HiVals.push_back(HiVal);
929 // Rescan the ranges, looking for overlap with singleton values and other
930 // ranges. Since the range list is sorted, we only need to compare case
931 // ranges with their neighbors.
932 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
933 llvm::APSInt &CRLo = CaseRanges[i].first;
934 llvm::APSInt &CRHi = HiVals[i];
935 CaseStmt *CR = CaseRanges[i].second;
937 // Check to see whether the case range overlaps with any
939 CaseStmt *OverlapStmt = 0;
940 llvm::APSInt OverlapVal(32);
942 // Find the smallest value >= the lower bound. If I is in the
943 // case range, then we have overlap.
944 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
945 CaseVals.end(), CRLo,
946 CaseCompareFunctor());
947 if (I != CaseVals.end() && I->first < CRHi) {
948 OverlapVal = I->first; // Found overlap with scalar.
949 OverlapStmt = I->second;
952 // Find the smallest value bigger than the upper bound.
953 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
954 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
955 OverlapVal = (I-1)->first; // Found overlap with scalar.
956 OverlapStmt = (I-1)->second;
959 // Check to see if this case stmt overlaps with the subsequent
961 if (i && CRLo <= HiVals[i-1]) {
962 OverlapVal = HiVals[i-1]; // Found overlap with range.
963 OverlapStmt = CaseRanges[i-1].second;
967 // If we have a duplicate, report it.
968 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
969 << OverlapVal.toString(10);
970 Diag(OverlapStmt->getLHS()->getLocStart(),
971 diag::note_duplicate_case_prev);
972 // FIXME: We really want to remove the bogus case stmt from the
973 // substmt, but we have no way to do this right now.
974 CaseListIsErroneous = true;
979 // Complain if we have a constant condition and we didn't find a match.
980 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
981 // TODO: it would be nice if we printed enums as enums, chars as
983 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
984 << ConstantCondValue.toString(10)
985 << CondExpr->getSourceRange();
988 // Check to see if switch is over an Enum and handles all of its
989 // values. We only issue a warning if there is not 'default:', but
990 // we still do the analysis to preserve this information in the AST
991 // (which can be used by flow-based analyes).
993 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
995 // If switch has default case, then ignore it.
996 if (!CaseListIsErroneous && !HasConstantCond && ET) {
997 const EnumDecl *ED = ET->getDecl();
998 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
1000 EnumValsTy EnumVals;
1002 // Gather all enum values, set their type and sort them,
1003 // allowing easier comparison with CaseVals.
1004 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
1005 EDI != ED->enumerator_end(); ++EDI) {
1006 llvm::APSInt Val = EDI->getInitVal();
1007 AdjustAPSInt(Val, CondWidth, CondIsSigned);
1008 EnumVals.push_back(std::make_pair(Val, *EDI));
1010 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1011 EnumValsTy::iterator EIend =
1012 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1014 // See which case values aren't in enum.
1015 EnumValsTy::const_iterator EI = EnumVals.begin();
1016 for (CaseValsTy::const_iterator CI = CaseVals.begin();
1017 CI != CaseVals.end(); CI++) {
1018 while (EI != EIend && EI->first < CI->first)
1020 if (EI == EIend || EI->first > CI->first)
1021 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
1022 << CondTypeBeforePromotion;
1024 // See which of case ranges aren't in enum
1025 EI = EnumVals.begin();
1026 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1027 RI != CaseRanges.end() && EI != EIend; RI++) {
1028 while (EI != EIend && EI->first < RI->first)
1031 if (EI == EIend || EI->first != RI->first) {
1032 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
1033 << CondTypeBeforePromotion;
1037 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1038 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1039 while (EI != EIend && EI->first < Hi)
1041 if (EI == EIend || EI->first != Hi)
1042 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
1043 << CondTypeBeforePromotion;
1046 // Check which enum vals aren't in switch
1047 CaseValsTy::const_iterator CI = CaseVals.begin();
1048 CaseRangesTy::const_iterator RI = CaseRanges.begin();
1049 bool hasCasesNotInSwitch = false;
1051 SmallVector<DeclarationName,8> UnhandledNames;
1053 for (EI = EnumVals.begin(); EI != EIend; EI++){
1054 // Drop unneeded case values
1056 while (CI != CaseVals.end() && CI->first < EI->first)
1059 if (CI != CaseVals.end() && CI->first == EI->first)
1062 // Drop unneeded case ranges
1063 for (; RI != CaseRanges.end(); RI++) {
1065 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1066 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1067 if (EI->first <= Hi)
1071 if (RI == CaseRanges.end() || EI->first < RI->first) {
1072 hasCasesNotInSwitch = true;
1073 UnhandledNames.push_back(EI->second->getDeclName());
1077 if (TheDefaultStmt && UnhandledNames.empty())
1078 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
1080 // Produce a nice diagnostic if multiple values aren't handled.
1081 switch (UnhandledNames.size()) {
1084 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1085 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
1086 << UnhandledNames[0];
1089 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1090 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
1091 << UnhandledNames[0] << UnhandledNames[1];
1094 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1095 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
1096 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1099 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1100 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
1101 << (unsigned)UnhandledNames.size()
1102 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1106 if (!hasCasesNotInSwitch)
1107 SS->setAllEnumCasesCovered();
1111 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1112 diag::warn_empty_switch_body);
1114 // FIXME: If the case list was broken is some way, we don't have a good system
1115 // to patch it up. Instead, just return the whole substmt as broken.
1116 if (CaseListIsErroneous)
1123 Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1125 unsigned DIAG = diag::warn_not_in_enum_assignement;
1126 if (Diags.getDiagnosticLevel(DIAG, SrcExpr->getExprLoc())
1127 == DiagnosticsEngine::Ignored)
1130 if (const EnumType *ET = DstType->getAs<EnumType>())
1131 if (!Context.hasSameType(SrcType, DstType) &&
1132 SrcType->isIntegerType()) {
1133 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1134 SrcExpr->isIntegerConstantExpr(Context)) {
1135 // Get the bitwidth of the enum value before promotions.
1136 unsigned DstWith = Context.getIntWidth(DstType);
1137 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1139 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1140 const EnumDecl *ED = ET->getDecl();
1141 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
1143 EnumValsTy EnumVals;
1145 // Gather all enum values, set their type and sort them,
1146 // allowing easier comparison with rhs constant.
1147 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
1148 EDI != ED->enumerator_end(); ++EDI) {
1149 llvm::APSInt Val = EDI->getInitVal();
1150 AdjustAPSInt(Val, DstWith, DstIsSigned);
1151 EnumVals.push_back(std::make_pair(Val, *EDI));
1153 if (EnumVals.empty())
1155 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1156 EnumValsTy::iterator EIend =
1157 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1159 // See which case values aren't in enum.
1160 EnumValsTy::const_iterator EI = EnumVals.begin();
1161 while (EI != EIend && EI->first < RhsVal)
1163 if (EI == EIend || EI->first != RhsVal) {
1164 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignement)
1172 Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
1173 Decl *CondVar, Stmt *Body) {
1174 ExprResult CondResult(Cond.release());
1176 VarDecl *ConditionVar = 0;
1178 ConditionVar = cast<VarDecl>(CondVar);
1179 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
1180 if (CondResult.isInvalid())
1183 Expr *ConditionExpr = CondResult.take();
1187 DiagnoseUnusedExprResult(Body);
1189 if (isa<NullStmt>(Body))
1190 getCurCompoundScope().setHasEmptyLoopBodies();
1192 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
1197 Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
1198 SourceLocation WhileLoc, SourceLocation CondLParen,
1199 Expr *Cond, SourceLocation CondRParen) {
1200 assert(Cond && "ActOnDoStmt(): missing expression");
1202 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
1203 if (CondResult.isInvalid())
1205 Cond = CondResult.take();
1207 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
1208 if (CondResult.isInvalid())
1210 Cond = CondResult.take();
1212 DiagnoseUnusedExprResult(Body);
1214 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
1218 // This visitor will traverse a conditional statement and store all
1219 // the evaluated decls into a vector. Simple is set to true if none
1220 // of the excluded constructs are used.
1221 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1222 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1223 SmallVector<SourceRange, 10> &Ranges;
1226 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1228 DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
1229 SmallVector<SourceRange, 10> &Ranges) :
1230 Inherited(S.Context),
1235 bool isSimple() { return Simple; }
1237 // Replaces the method in EvaluatedExprVisitor.
1238 void VisitMemberExpr(MemberExpr* E) {
1242 // Any Stmt not whitelisted will cause the condition to be marked complex.
1243 void VisitStmt(Stmt *S) {
1247 void VisitBinaryOperator(BinaryOperator *E) {
1252 void VisitCastExpr(CastExpr *E) {
1253 Visit(E->getSubExpr());
1256 void VisitUnaryOperator(UnaryOperator *E) {
1257 // Skip checking conditionals with derefernces.
1258 if (E->getOpcode() == UO_Deref)
1261 Visit(E->getSubExpr());
1264 void VisitConditionalOperator(ConditionalOperator *E) {
1265 Visit(E->getCond());
1266 Visit(E->getTrueExpr());
1267 Visit(E->getFalseExpr());
1270 void VisitParenExpr(ParenExpr *E) {
1271 Visit(E->getSubExpr());
1274 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1275 Visit(E->getOpaqueValue()->getSourceExpr());
1276 Visit(E->getFalseExpr());
1279 void VisitIntegerLiteral(IntegerLiteral *E) { }
1280 void VisitFloatingLiteral(FloatingLiteral *E) { }
1281 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1282 void VisitCharacterLiteral(CharacterLiteral *E) { }
1283 void VisitGNUNullExpr(GNUNullExpr *E) { }
1284 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1286 void VisitDeclRefExpr(DeclRefExpr *E) {
1287 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1290 Ranges.push_back(E->getSourceRange());
1295 }; // end class DeclExtractor
1297 // DeclMatcher checks to see if the decls are used in a non-evauluated
1299 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1300 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1304 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1306 DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls, Stmt *Statement) :
1307 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1308 if (!Statement) return;
1313 void VisitReturnStmt(ReturnStmt *S) {
1317 void VisitBreakStmt(BreakStmt *S) {
1321 void VisitGotoStmt(GotoStmt *S) {
1325 void VisitCastExpr(CastExpr *E) {
1326 if (E->getCastKind() == CK_LValueToRValue)
1327 CheckLValueToRValueCast(E->getSubExpr());
1329 Visit(E->getSubExpr());
1332 void CheckLValueToRValueCast(Expr *E) {
1333 E = E->IgnoreParenImpCasts();
1335 if (isa<DeclRefExpr>(E)) {
1339 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1340 Visit(CO->getCond());
1341 CheckLValueToRValueCast(CO->getTrueExpr());
1342 CheckLValueToRValueCast(CO->getFalseExpr());
1346 if (BinaryConditionalOperator *BCO =
1347 dyn_cast<BinaryConditionalOperator>(E)) {
1348 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1349 CheckLValueToRValueCast(BCO->getFalseExpr());
1356 void VisitDeclRefExpr(DeclRefExpr *E) {
1357 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1358 if (Decls.count(VD))
1362 bool FoundDeclInUse() { return FoundDecl; }
1364 }; // end class DeclMatcher
1366 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1367 Expr *Third, Stmt *Body) {
1368 // Condition is empty
1369 if (!Second) return;
1371 if (S.Diags.getDiagnosticLevel(diag::warn_variables_not_in_loop_body,
1372 Second->getLocStart())
1373 == DiagnosticsEngine::Ignored)
1376 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1377 llvm::SmallPtrSet<VarDecl*, 8> Decls;
1378 SmallVector<SourceRange, 10> Ranges;
1379 DeclExtractor DE(S, Decls, Ranges);
1382 // Don't analyze complex conditionals.
1383 if (!DE.isSimple()) return;
1386 if (Decls.size() == 0) return;
1388 // Don't warn on volatile, static, or global variables.
1389 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1392 if ((*I)->getType().isVolatileQualified() ||
1393 (*I)->hasGlobalStorage()) return;
1395 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1396 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1397 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1400 // Load decl names into diagnostic.
1401 if (Decls.size() > 4)
1404 PDiag << Decls.size();
1405 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1408 PDiag << (*I)->getDeclName();
1411 // Load SourceRanges into diagnostic if there is room.
1412 // Otherwise, load the SourceRange of the conditional expression.
1413 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
1414 for (SmallVector<SourceRange, 10>::iterator I = Ranges.begin(),
1419 PDiag << Second->getSourceRange();
1421 S.Diag(Ranges.begin()->getBegin(), PDiag);
1427 Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1428 Stmt *First, FullExprArg second, Decl *secondVar,
1430 SourceLocation RParenLoc, Stmt *Body) {
1431 if (!getLangOpts().CPlusPlus) {
1432 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
1433 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1434 // declare identifiers for objects having storage class 'auto' or
1436 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
1438 VarDecl *VD = dyn_cast<VarDecl>(*DI);
1439 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
1442 Diag((*DI)->getLocation(), diag::err_non_local_variable_decl_in_for);
1443 (*DI)->setInvalidDecl();
1449 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
1451 ExprResult SecondResult(second.release());
1452 VarDecl *ConditionVar = 0;
1454 ConditionVar = cast<VarDecl>(secondVar);
1455 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
1456 if (SecondResult.isInvalid())
1460 Expr *Third = third.release().takeAs<Expr>();
1462 DiagnoseUnusedExprResult(First);
1463 DiagnoseUnusedExprResult(Third);
1464 DiagnoseUnusedExprResult(Body);
1466 if (isa<NullStmt>(Body))
1467 getCurCompoundScope().setHasEmptyLoopBodies();
1469 return Owned(new (Context) ForStmt(Context, First,
1470 SecondResult.take(), ConditionVar,
1471 Third, Body, ForLoc, LParenLoc,
1475 /// In an Objective C collection iteration statement:
1477 /// x can be an arbitrary l-value expression. Bind it up as a
1478 /// full-expression.
1479 StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
1480 // Reduce placeholder expressions here. Note that this rejects the
1481 // use of pseudo-object l-values in this position.
1482 ExprResult result = CheckPlaceholderExpr(E);
1483 if (result.isInvalid()) return StmtError();
1486 ExprResult FullExpr = ActOnFinishFullExpr(E);
1487 if (FullExpr.isInvalid())
1489 return StmtResult(static_cast<Stmt*>(FullExpr.take()));
1493 Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1497 // Bail out early if we've got a type-dependent expression.
1498 if (collection->isTypeDependent()) return Owned(collection);
1500 // Perform normal l-value conversion.
1501 ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1502 if (result.isInvalid())
1504 collection = result.take();
1506 // The operand needs to have object-pointer type.
1507 // TODO: should we do a contextual conversion?
1508 const ObjCObjectPointerType *pointerType =
1509 collection->getType()->getAs<ObjCObjectPointerType>();
1511 return Diag(forLoc, diag::err_collection_expr_type)
1512 << collection->getType() << collection->getSourceRange();
1514 // Check that the operand provides
1515 // - countByEnumeratingWithState:objects:count:
1516 const ObjCObjectType *objectType = pointerType->getObjectType();
1517 ObjCInterfaceDecl *iface = objectType->getInterface();
1519 // If we have a forward-declared type, we can't do this check.
1520 // Under ARC, it is an error not to have a forward-declared class.
1522 RequireCompleteType(forLoc, QualType(objectType, 0),
1523 getLangOpts().ObjCAutoRefCount
1524 ? diag::err_arc_collection_forward
1527 // Otherwise, if we have any useful type information, check that
1528 // the type declares the appropriate method.
1529 } else if (iface || !objectType->qual_empty()) {
1530 IdentifierInfo *selectorIdents[] = {
1531 &Context.Idents.get("countByEnumeratingWithState"),
1532 &Context.Idents.get("objects"),
1533 &Context.Idents.get("count")
1535 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1537 ObjCMethodDecl *method = 0;
1539 // If there's an interface, look in both the public and private APIs.
1541 method = iface->lookupInstanceMethod(selector);
1542 if (!method) method = iface->lookupPrivateMethod(selector);
1545 // Also check protocol qualifiers.
1547 method = LookupMethodInQualifiedType(selector, pointerType,
1550 // If we didn't find it anywhere, give up.
1552 Diag(forLoc, diag::warn_collection_expr_type)
1553 << collection->getType() << selector << collection->getSourceRange();
1556 // TODO: check for an incompatible signature?
1559 // Wrap up any cleanups in the expression.
1560 return Owned(collection);
1564 Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1565 Stmt *First, Expr *collection,
1566 SourceLocation RParenLoc) {
1568 ExprResult CollectionExprResult =
1569 CheckObjCForCollectionOperand(ForLoc, collection);
1573 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
1574 if (!DS->isSingleDecl())
1575 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1576 diag::err_toomany_element_decls));
1578 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1579 if (!D || D->isInvalidDecl())
1582 FirstType = D->getType();
1583 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1584 // declare identifiers for objects having storage class 'auto' or
1586 if (!D->hasLocalStorage())
1587 return StmtError(Diag(D->getLocation(),
1588 diag::err_non_local_variable_decl_in_for));
1590 // If the type contained 'auto', deduce the 'auto' to 'id'.
1591 if (FirstType->getContainedAutoType()) {
1592 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1594 Expr *DeducedInit = &OpaqueId;
1595 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1597 DiagnoseAutoDeductionFailure(D, DeducedInit);
1598 if (FirstType.isNull()) {
1599 D->setInvalidDecl();
1603 D->setType(FirstType);
1605 if (ActiveTemplateInstantiations.empty()) {
1606 SourceLocation Loc =
1607 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
1608 Diag(Loc, diag::warn_auto_var_is_id)
1609 << D->getDeclName();
1614 Expr *FirstE = cast<Expr>(First);
1615 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
1616 return StmtError(Diag(First->getLocStart(),
1617 diag::err_selector_element_not_lvalue)
1618 << First->getSourceRange());
1620 FirstType = static_cast<Expr*>(First)->getType();
1622 if (!FirstType->isDependentType() &&
1623 !FirstType->isObjCObjectPointerType() &&
1624 !FirstType->isBlockPointerType())
1625 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1626 << FirstType << First->getSourceRange());
1629 if (CollectionExprResult.isInvalid())
1632 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.take());
1633 if (CollectionExprResult.isInvalid())
1636 return Owned(new (Context) ObjCForCollectionStmt(First,
1637 CollectionExprResult.take(), 0,
1638 ForLoc, RParenLoc));
1641 /// Finish building a variable declaration for a for-range statement.
1642 /// \return true if an error occurs.
1643 static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1644 SourceLocation Loc, int DiagID) {
1645 // Deduce the type for the iterator variable now rather than leaving it to
1646 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1648 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
1649 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
1651 SemaRef.Diag(Loc, DiagID) << Init->getType();
1652 if (InitType.isNull()) {
1653 Decl->setInvalidDecl();
1656 Decl->setType(InitType);
1658 // In ARC, infer lifetime.
1659 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1660 // we're doing the equivalent of fast iteration.
1661 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1662 SemaRef.inferObjCARCLifetime(Decl))
1663 Decl->setInvalidDecl();
1665 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1666 /*TypeMayContainAuto=*/false);
1667 SemaRef.FinalizeDeclaration(Decl);
1668 SemaRef.CurContext->addHiddenDecl(Decl);
1674 /// Produce a note indicating which begin/end function was implicitly called
1675 /// by a C++11 for-range statement. This is often not obvious from the code,
1676 /// nor from the diagnostics produced when analysing the implicit expressions
1677 /// required in a for-range statement.
1678 void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
1679 Sema::BeginEndFunction BEF) {
1680 CallExpr *CE = dyn_cast<CallExpr>(E);
1683 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1686 SourceLocation Loc = D->getLocation();
1688 std::string Description;
1689 bool IsTemplate = false;
1690 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1691 Description = SemaRef.getTemplateArgumentBindingsText(
1692 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1696 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1697 << BEF << IsTemplate << Description << E->getType();
1700 /// Build a variable declaration for a for-range statement.
1701 VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1702 QualType Type, const char *Name) {
1703 DeclContext *DC = SemaRef.CurContext;
1704 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1705 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1706 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1708 Decl->setImplicit();
1714 static bool ObjCEnumerationCollection(Expr *Collection) {
1715 return !Collection->isTypeDependent()
1716 && Collection->getType()->getAs<ObjCObjectPointerType>() != 0;
1719 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
1721 /// C++11 [stmt.ranged]:
1722 /// A range-based for statement is equivalent to
1725 /// auto && __range = range-init;
1726 /// for ( auto __begin = begin-expr,
1727 /// __end = end-expr;
1728 /// __begin != __end;
1730 /// for-range-declaration = *__begin;
1735 /// The body of the loop is not available yet, since it cannot be analysed until
1736 /// we have determined the type of the for-range-declaration.
1738 Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
1739 Stmt *First, SourceLocation ColonLoc, Expr *Range,
1740 SourceLocation RParenLoc, BuildForRangeKind Kind) {
1741 if (!First || !Range)
1744 if (ObjCEnumerationCollection(Range))
1745 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
1747 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1748 assert(DS && "first part of for range not a decl stmt");
1750 if (!DS->isSingleDecl()) {
1751 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1754 if (DS->getSingleDecl()->isInvalidDecl())
1757 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1760 // Build auto && __range = range-init
1761 SourceLocation RangeLoc = Range->getLocStart();
1762 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1763 Context.getAutoRRefDeductType(),
1765 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1766 diag::err_for_range_deduction_failure))
1769 // Claim the type doesn't contain auto: we've already done the checking.
1770 DeclGroupPtrTy RangeGroup =
1771 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false);
1772 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1773 if (RangeDecl.isInvalid())
1776 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1777 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
1781 /// \brief Create the initialization, compare, and increment steps for
1782 /// the range-based for loop expression.
1783 /// This function does not handle array-based for loops,
1784 /// which are created in Sema::BuildCXXForRangeStmt.
1786 /// \returns a ForRangeStatus indicating success or what kind of error occurred.
1787 /// BeginExpr and EndExpr are set and FRS_Success is returned on success;
1788 /// CandidateSet and BEF are set and some non-success value is returned on
1790 static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
1791 Expr *BeginRange, Expr *EndRange,
1795 SourceLocation ColonLoc,
1796 OverloadCandidateSet *CandidateSet,
1797 ExprResult *BeginExpr,
1798 ExprResult *EndExpr,
1799 Sema::BeginEndFunction *BEF) {
1800 DeclarationNameInfo BeginNameInfo(
1801 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
1802 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
1805 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
1806 Sema::LookupMemberName);
1807 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
1809 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1810 // - if _RangeT is a class type, the unqualified-ids begin and end are
1811 // looked up in the scope of class _RangeT as if by class member access
1812 // lookup (3.4.5), and if either (or both) finds at least one
1813 // declaration, begin-expr and end-expr are __range.begin() and
1814 // __range.end(), respectively;
1815 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
1816 SemaRef.LookupQualifiedName(EndMemberLookup, D);
1818 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1819 SourceLocation RangeLoc = BeginVar->getLocation();
1820 *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
1822 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
1823 << RangeLoc << BeginRange->getType() << *BEF;
1824 return Sema::FRS_DiagnosticIssued;
1827 // - otherwise, begin-expr and end-expr are begin(__range) and
1828 // end(__range), respectively, where begin and end are looked up with
1829 // argument-dependent lookup (3.4.2). For the purposes of this name
1830 // lookup, namespace std is an associated namespace.
1834 *BEF = Sema::BEF_begin;
1835 Sema::ForRangeStatus RangeStatus =
1836 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
1837 Sema::BEF_begin, BeginNameInfo,
1838 BeginMemberLookup, CandidateSet,
1839 BeginRange, BeginExpr);
1841 if (RangeStatus != Sema::FRS_Success)
1843 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
1844 diag::err_for_range_iter_deduction_failure)) {
1845 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
1846 return Sema::FRS_DiagnosticIssued;
1849 *BEF = Sema::BEF_end;
1851 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
1852 Sema::BEF_end, EndNameInfo,
1853 EndMemberLookup, CandidateSet,
1855 if (RangeStatus != Sema::FRS_Success)
1857 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
1858 diag::err_for_range_iter_deduction_failure)) {
1859 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
1860 return Sema::FRS_DiagnosticIssued;
1862 return Sema::FRS_Success;
1865 /// Speculatively attempt to dereference an invalid range expression.
1866 /// If the attempt fails, this function will return a valid, null StmtResult
1867 /// and emit no diagnostics.
1868 static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
1869 SourceLocation ForLoc,
1871 SourceLocation ColonLoc,
1873 SourceLocation RangeLoc,
1874 SourceLocation RParenLoc) {
1875 // Determine whether we can rebuild the for-range statement with a
1876 // dereferenced range expression.
1877 ExprResult AdjustedRange;
1879 Sema::SFINAETrap Trap(SemaRef);
1881 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
1882 if (AdjustedRange.isInvalid())
1883 return StmtResult();
1886 SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
1887 AdjustedRange.get(), RParenLoc,
1890 return StmtResult();
1893 // The attempt to dereference worked well enough that it could produce a valid
1894 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
1895 // case there are any other (non-fatal) problems with it.
1896 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
1897 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
1898 return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
1899 AdjustedRange.get(), RParenLoc,
1900 Sema::BFRK_Rebuild);
1903 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
1905 Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
1906 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
1907 Expr *Inc, Stmt *LoopVarDecl,
1908 SourceLocation RParenLoc, BuildForRangeKind Kind) {
1909 Scope *S = getCurScope();
1911 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
1912 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
1913 QualType RangeVarType = RangeVar->getType();
1915 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
1916 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
1918 StmtResult BeginEndDecl = BeginEnd;
1919 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
1921 if (RangeVarType->isDependentType()) {
1922 // The range is implicitly used as a placeholder when it is dependent.
1923 RangeVar->setUsed();
1925 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
1926 // them in properly when we instantiate the loop.
1927 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
1928 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
1929 } else if (!BeginEndDecl.get()) {
1930 SourceLocation RangeLoc = RangeVar->getLocation();
1932 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
1934 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1935 VK_LValue, ColonLoc);
1936 if (BeginRangeRef.isInvalid())
1939 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1940 VK_LValue, ColonLoc);
1941 if (EndRangeRef.isInvalid())
1944 QualType AutoType = Context.getAutoDeductType();
1945 Expr *Range = RangeVar->getInit();
1948 QualType RangeType = Range->getType();
1950 if (RequireCompleteType(RangeLoc, RangeType,
1951 diag::err_for_range_incomplete_type))
1954 // Build auto __begin = begin-expr, __end = end-expr.
1955 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1957 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1960 // Build begin-expr and end-expr and attach to __begin and __end variables.
1961 ExprResult BeginExpr, EndExpr;
1962 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
1963 // - if _RangeT is an array type, begin-expr and end-expr are __range and
1964 // __range + __bound, respectively, where __bound is the array bound. If
1965 // _RangeT is an array of unknown size or an array of incomplete type,
1966 // the program is ill-formed;
1968 // begin-expr is __range.
1969 BeginExpr = BeginRangeRef;
1970 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
1971 diag::err_for_range_iter_deduction_failure)) {
1972 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1976 // Find the array bound.
1977 ExprResult BoundExpr;
1978 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
1979 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
1980 Context.getPointerDiffType(),
1982 else if (const VariableArrayType *VAT =
1983 dyn_cast<VariableArrayType>(UnqAT))
1984 // FIXME: Need to build an OpaqueValueExpr for this rather than
1986 BoundExpr = VAT->getSizeExpr();
1988 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
1989 // UnqAT is not incomplete and Range is not type-dependent.
1990 llvm_unreachable("Unexpected array type in for-range");
1993 // end-expr is __range + __bound.
1994 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
1996 if (EndExpr.isInvalid())
1998 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
1999 diag::err_for_range_iter_deduction_failure)) {
2000 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2004 OverloadCandidateSet CandidateSet(RangeLoc);
2005 Sema::BeginEndFunction BEFFailure;
2006 ForRangeStatus RangeStatus =
2007 BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
2008 EndRangeRef.get(), RangeType,
2009 BeginVar, EndVar, ColonLoc, &CandidateSet,
2010 &BeginExpr, &EndExpr, &BEFFailure);
2012 // If building the range failed, try dereferencing the range expression
2013 // unless a diagnostic was issued or the end function is problematic.
2014 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
2015 BEFFailure == BEF_begin) {
2016 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2017 LoopVarDecl, ColonLoc,
2020 if (SR.isInvalid() || SR.isUsable())
2024 // Otherwise, emit diagnostics if we haven't already.
2025 if (RangeStatus == FRS_NoViableFunction) {
2026 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
2027 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2028 << RangeLoc << Range->getType() << BEFFailure;
2029 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
2031 // Return an error if no fix was discovered.
2032 if (RangeStatus != FRS_Success)
2036 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2037 "invalid range expression in for loop");
2039 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
2040 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2041 if (!Context.hasSameType(BeginType, EndType)) {
2042 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
2043 << BeginType << EndType;
2044 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2045 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2048 Decl *BeginEndDecls[] = { BeginVar, EndVar };
2049 // Claim the type doesn't contain auto: we've already done the checking.
2050 DeclGroupPtrTy BeginEndGroup =
2051 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false);
2052 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
2054 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2055 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2056 VK_LValue, ColonLoc);
2057 if (BeginRef.isInvalid())
2060 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2061 VK_LValue, ColonLoc);
2062 if (EndRef.isInvalid())
2065 // Build and check __begin != __end expression.
2066 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2067 BeginRef.get(), EndRef.get());
2068 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
2069 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2070 if (NotEqExpr.isInvalid()) {
2071 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2072 << RangeLoc << 0 << BeginRangeRef.get()->getType();
2073 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2074 if (!Context.hasSameType(BeginType, EndType))
2075 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2079 // Build and check ++__begin expression.
2080 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2081 VK_LValue, ColonLoc);
2082 if (BeginRef.isInvalid())
2085 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2086 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2087 if (IncrExpr.isInvalid()) {
2088 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2089 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
2090 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2094 // Build and check *__begin expression.
2095 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2096 VK_LValue, ColonLoc);
2097 if (BeginRef.isInvalid())
2100 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2101 if (DerefExpr.isInvalid()) {
2102 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2103 << RangeLoc << 1 << BeginRangeRef.get()->getType();
2104 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2108 // Attach *__begin as initializer for VD. Don't touch it if we're just
2109 // trying to determine whether this would be a valid range.
2110 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2111 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2112 /*TypeMayContainAuto=*/true);
2113 if (LoopVar->isInvalidDecl())
2114 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2118 // Don't bother to actually allocate the result if we're just trying to
2119 // determine whether it would be valid.
2120 if (Kind == BFRK_Check)
2121 return StmtResult();
2123 return Owned(new (Context) CXXForRangeStmt(RangeDS,
2124 cast_or_null<DeclStmt>(BeginEndDecl.get()),
2125 NotEqExpr.take(), IncrExpr.take(),
2126 LoopVarDS, /*Body=*/0, ForLoc,
2127 ColonLoc, RParenLoc));
2130 /// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
2132 StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2135 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
2137 ForStmt->setBody(B);
2141 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2142 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2143 /// body cannot be performed until after the type of the range variable is
2145 StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2149 if (isa<ObjCForCollectionStmt>(S))
2150 return FinishObjCForCollectionStmt(S, B);
2152 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2153 ForStmt->setBody(B);
2155 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2156 diag::warn_empty_range_based_for_body);
2161 StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2162 SourceLocation LabelLoc,
2163 LabelDecl *TheDecl) {
2164 getCurFunction()->setHasBranchIntoScope();
2166 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
2170 Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
2172 // Convert operand to void*
2173 if (!E->isTypeDependent()) {
2174 QualType ETy = E->getType();
2175 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
2176 ExprResult ExprRes = Owned(E);
2177 AssignConvertType ConvTy =
2178 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2179 if (ExprRes.isInvalid())
2182 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
2186 ExprResult ExprRes = ActOnFinishFullExpr(E);
2187 if (ExprRes.isInvalid())
2191 getCurFunction()->setHasIndirectGoto();
2193 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
2197 Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
2198 Scope *S = CurScope->getContinueParent();
2200 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
2201 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
2204 return Owned(new (Context) ContinueStmt(ContinueLoc));
2208 Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
2209 Scope *S = CurScope->getBreakParent();
2211 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
2212 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
2215 return Owned(new (Context) BreakStmt(BreakLoc));
2218 /// \brief Determine whether the given expression is a candidate for
2219 /// copy elision in either a return statement or a throw expression.
2221 /// \param ReturnType If we're determining the copy elision candidate for
2222 /// a return statement, this is the return type of the function. If we're
2223 /// determining the copy elision candidate for a throw expression, this will
2226 /// \param E The expression being returned from the function or block, or
2229 /// \param AllowFunctionParameter Whether we allow function parameters to
2230 /// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2231 /// we re-use this logic to determine whether we should try to move as part of
2232 /// a return or throw (which does allow function parameters).
2234 /// \returns The NRVO candidate variable, if the return statement may use the
2235 /// NRVO, or NULL if there is no such candidate.
2236 const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2238 bool AllowFunctionParameter) {
2239 QualType ExprType = E->getType();
2240 // - in a return statement in a function with ...
2241 // ... a class return type ...
2242 if (!ReturnType.isNull()) {
2243 if (!ReturnType->isRecordType())
2245 // ... the same cv-unqualified type as the function return type ...
2246 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
2250 // ... the expression is the name of a non-volatile automatic object
2251 // (other than a function or catch-clause parameter)) ...
2252 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
2253 if (!DR || DR->refersToEnclosingLocal())
2255 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2259 // ...object (other than a function or catch-clause parameter)...
2260 if (VD->getKind() != Decl::Var &&
2261 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
2263 if (VD->isExceptionVariable()) return 0;
2266 if (!VD->hasLocalStorage()) return 0;
2268 // ...non-volatile...
2269 if (VD->getType().isVolatileQualified()) return 0;
2270 if (VD->getType()->isReferenceType()) return 0;
2272 // __block variables can't be allocated in a way that permits NRVO.
2273 if (VD->hasAttr<BlocksAttr>()) return 0;
2275 // Variables with higher required alignment than their type's ABI
2276 // alignment cannot use NRVO.
2277 if (VD->hasAttr<AlignedAttr>() &&
2278 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2284 /// \brief Perform the initialization of a potentially-movable value, which
2285 /// is the result of return value.
2287 /// This routine implements C++0x [class.copy]p33, which attempts to treat
2288 /// returned lvalues as rvalues in certain cases (to prefer move construction),
2289 /// then falls back to treating them as lvalues if that failed.
2291 Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2292 const VarDecl *NRVOCandidate,
2293 QualType ResultType,
2296 // C++0x [class.copy]p33:
2297 // When the criteria for elision of a copy operation are met or would
2298 // be met save for the fact that the source object is a function
2299 // parameter, and the object to be copied is designated by an lvalue,
2300 // overload resolution to select the constructor for the copy is first
2301 // performed as if the object were designated by an rvalue.
2302 ExprResult Res = ExprError();
2304 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
2305 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
2306 Value->getType(), CK_NoOp, Value, VK_XValue);
2308 Expr *InitExpr = &AsRvalue;
2309 InitializationKind Kind
2310 = InitializationKind::CreateCopy(Value->getLocStart(),
2311 Value->getLocStart());
2312 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2314 // [...] If overload resolution fails, or if the type of the first
2315 // parameter of the selected constructor is not an rvalue reference
2316 // to the object's type (possibly cv-qualified), overload resolution
2317 // is performed again, considering the object as an lvalue.
2319 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2320 StepEnd = Seq.step_end();
2321 Step != StepEnd; ++Step) {
2322 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
2325 CXXConstructorDecl *Constructor
2326 = cast<CXXConstructorDecl>(Step->Function.Function);
2328 const RValueReferenceType *RRefType
2329 = Constructor->getParamDecl(0)->getType()
2330 ->getAs<RValueReferenceType>();
2332 // If we don't meet the criteria, break out now.
2334 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2335 Context.getTypeDeclType(Constructor->getParent())))
2338 // Promote "AsRvalue" to the heap, since we now need this
2339 // expression node to persist.
2340 Value = ImplicitCastExpr::Create(Context, Value->getType(),
2341 CK_NoOp, Value, 0, VK_XValue);
2343 // Complete type-checking the initialization of the return type
2344 // using the constructor we found.
2345 Res = Seq.Perform(*this, Entity, Kind, Value);
2350 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
2351 // above, or overload resolution failed. Either way, we need to try
2352 // (again) now with the return value expression as written.
2353 if (Res.isInvalid())
2354 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
2359 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2360 /// for capturing scopes.
2363 Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2364 // If this is the first return we've seen, infer the return type.
2365 // [expr.prim.lambda]p4 in C++11; block literals follow a superset of those
2366 // rules which allows multiple return statements.
2367 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
2368 QualType FnRetType = CurCap->ReturnType;
2370 // For blocks/lambdas with implicit return types, we check each return
2371 // statement individually, and deduce the common return type when the block
2372 // or lambda is completed.
2373 if (CurCap->HasImplicitReturnType) {
2374 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
2375 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2376 if (Result.isInvalid())
2378 RetValExp = Result.take();
2380 if (!RetValExp->isTypeDependent())
2381 FnRetType = RetValExp->getType();
2383 FnRetType = CurCap->ReturnType = Context.DependentTy;
2386 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2387 // initializer list, because it is not an expression (even
2388 // though we represent it as one). We still deduce 'void'.
2389 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2390 << RetValExp->getSourceRange();
2393 FnRetType = Context.VoidTy;
2396 // Although we'll properly infer the type of the block once it's completed,
2397 // make sure we provide a return type now for better error recovery.
2398 if (CurCap->ReturnType.isNull())
2399 CurCap->ReturnType = FnRetType;
2401 assert(!FnRetType.isNull());
2403 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
2404 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2405 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2408 } else if (CapturedRegionScopeInfo *CurRegion =
2409 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
2410 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
2413 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CurCap);
2414 if (LSI->CallOperator->getType()->getAs<FunctionType>()->getNoReturnAttr()){
2415 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2420 // Otherwise, verify that this result type matches the previous one. We are
2421 // pickier with blocks than for normal functions because we don't have GCC
2422 // compatibility to worry about here.
2423 const VarDecl *NRVOCandidate = 0;
2424 if (FnRetType->isDependentType()) {
2425 // Delay processing for now. TODO: there are lots of dependent
2426 // types we can conclusively prove aren't void.
2427 } else if (FnRetType->isVoidType()) {
2428 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
2429 !(getLangOpts().CPlusPlus &&
2430 (RetValExp->isTypeDependent() ||
2431 RetValExp->getType()->isVoidType()))) {
2432 if (!getLangOpts().CPlusPlus &&
2433 RetValExp->getType()->isVoidType())
2434 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
2436 Diag(ReturnLoc, diag::err_return_block_has_expr);
2440 } else if (!RetValExp) {
2441 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2442 } else if (!RetValExp->isTypeDependent()) {
2443 // we have a non-void block with an expression, continue checking
2445 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2446 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2449 // In C++ the return statement is handled via a copy initialization.
2450 // the C version of which boils down to CheckSingleAssignmentConstraints.
2451 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2452 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2454 NRVOCandidate != 0);
2455 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2456 FnRetType, RetValExp);
2457 if (Res.isInvalid()) {
2458 // FIXME: Cleanup temporaries here, anyway?
2461 RetValExp = Res.take();
2462 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
2466 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2469 RetValExp = ER.take();
2471 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2474 // If we need to check for the named return value optimization,
2475 // or if we need to infer the return type,
2476 // save the return statement in our scope for later processing.
2477 if (CurCap->HasImplicitReturnType ||
2478 (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
2479 !CurContext->isDependentContext()))
2480 FunctionScopes.back()->Returns.push_back(Result);
2482 return Owned(Result);
2485 /// Deduce the return type for a function from a returned expression, per
2486 /// C++1y [dcl.spec.auto]p6.
2487 bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
2488 SourceLocation ReturnLoc,
2491 TypeLoc OrigResultType = FD->getTypeSourceInfo()->getTypeLoc().
2492 IgnoreParens().castAs<FunctionProtoTypeLoc>().getResultLoc();
2496 // If the deduction is for a return statement and the initializer is
2497 // a braced-init-list, the program is ill-formed.
2498 if (isa<InitListExpr>(RetExpr)) {
2499 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_return_init_list);
2503 // Otherwise, [...] deduce a value for U using the rules of template
2504 // argument deduction.
2505 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
2507 if (DAR == DAR_Failed && !FD->isInvalidDecl())
2508 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
2509 << OrigResultType.getType() << RetExpr->getType();
2511 if (DAR != DAR_Succeeded)
2514 // In the case of a return with no operand, the initializer is considered
2517 // Deduction here can only succeed if the return type is exactly 'cv auto'
2518 // or 'decltype(auto)', so just check for that case directly.
2519 if (!OrigResultType.getType()->getAs<AutoType>()) {
2520 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
2521 << OrigResultType.getType();
2524 // We always deduce U = void in this case.
2525 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
2526 if (Deduced.isNull())
2530 // If a function with a declared return type that contains a placeholder type
2531 // has multiple return statements, the return type is deduced for each return
2532 // statement. [...] if the type deduced is not the same in each deduction,
2533 // the program is ill-formed.
2534 if (AT->isDeduced() && !FD->isInvalidDecl()) {
2535 AutoType *NewAT = Deduced->getContainedAutoType();
2536 if (!Context.hasSameType(AT->getDeducedType(), NewAT->getDeducedType())) {
2537 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
2538 << (AT->isDecltypeAuto() ? 1 : 0)
2539 << NewAT->getDeducedType() << AT->getDeducedType();
2542 } else if (!FD->isInvalidDecl()) {
2543 // Update all declarations of the function to have the deduced return type.
2544 Context.adjustDeducedFunctionResultType(FD, Deduced);
2551 Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2552 // Check for unexpanded parameter packs.
2553 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2556 // FIXME: Unify this and C++1y auto function handling. In particular, we
2557 // should allow 'return { 1, 2, 3 };' in a lambda to deduce
2558 // 'std::initializer_list<int>'.
2559 if (isa<CapturingScopeInfo>(getCurFunction()))
2560 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
2563 QualType RelatedRetType;
2564 if (const FunctionDecl *FD = getCurFunctionDecl()) {
2565 FnRetType = FD->getResultType();
2566 if (FD->isNoReturn())
2567 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
2568 << FD->getDeclName();
2569 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2570 FnRetType = MD->getResultType();
2571 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2572 // In the implementation of a method with a related return type, the
2573 // type used to type-check the validity of return statements within the
2574 // method body is a pointer to the type of the class being implemented.
2575 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2576 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
2578 } else // If we don't have a function/method context, bail.
2581 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
2583 bool HasDependentReturnType = FnRetType->isDependentType();
2584 if (getLangOpts().CPlusPlus1y) {
2585 if (AutoType *AT = FnRetType->getContainedAutoType()) {
2586 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
2587 if (CurContext->isDependentContext())
2588 HasDependentReturnType = true;
2589 else if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2590 FD->setInvalidDecl();
2593 FnRetType = FD->getResultType();
2598 ReturnStmt *Result = 0;
2599 if (FnRetType->isVoidType()) {
2601 if (isa<InitListExpr>(RetValExp)) {
2602 // We simply never allow init lists as the return value of void
2603 // functions. This is compatible because this was never allowed before,
2604 // so there's no legacy code to deal with.
2605 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2606 int FunctionKind = 0;
2607 if (isa<ObjCMethodDecl>(CurDecl))
2609 else if (isa<CXXConstructorDecl>(CurDecl))
2611 else if (isa<CXXDestructorDecl>(CurDecl))
2614 Diag(ReturnLoc, diag::err_return_init_list)
2615 << CurDecl->getDeclName() << FunctionKind
2616 << RetValExp->getSourceRange();
2618 // Drop the expression.
2620 } else if (!RetValExp->isTypeDependent()) {
2621 // C99 6.8.6.4p1 (ext_ since GCC warns)
2622 unsigned D = diag::ext_return_has_expr;
2623 if (RetValExp->getType()->isVoidType())
2624 D = diag::ext_return_has_void_expr;
2626 ExprResult Result = Owned(RetValExp);
2627 Result = IgnoredValueConversions(Result.take());
2628 if (Result.isInvalid())
2630 RetValExp = Result.take();
2631 RetValExp = ImpCastExprToType(RetValExp,
2632 Context.VoidTy, CK_ToVoid).take();
2635 // return (some void expression); is legal in C++.
2636 if (D != diag::ext_return_has_void_expr ||
2637 !getLangOpts().CPlusPlus) {
2638 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2640 int FunctionKind = 0;
2641 if (isa<ObjCMethodDecl>(CurDecl))
2643 else if (isa<CXXConstructorDecl>(CurDecl))
2645 else if (isa<CXXDestructorDecl>(CurDecl))
2649 << CurDecl->getDeclName() << FunctionKind
2650 << RetValExp->getSourceRange();
2655 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2658 RetValExp = ER.take();
2662 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
2663 } else if (!RetValExp && !HasDependentReturnType) {
2664 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
2665 // C99 6.8.6.4p1 (ext_ since GCC warns)
2666 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
2668 if (FunctionDecl *FD = getCurFunctionDecl())
2669 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
2671 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
2672 Result = new (Context) ReturnStmt(ReturnLoc);
2674 assert(RetValExp || HasDependentReturnType);
2675 const VarDecl *NRVOCandidate = 0;
2676 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
2677 // we have a non-void function with an expression, continue checking
2679 QualType RetType = (RelatedRetType.isNull() ? FnRetType : RelatedRetType);
2681 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2682 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2685 // In C++ the return statement is handled via a copy initialization,
2686 // the C version of which boils down to CheckSingleAssignmentConstraints.
2687 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2688 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2690 NRVOCandidate != 0);
2691 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2692 RetType, RetValExp);
2693 if (Res.isInvalid()) {
2694 // FIXME: Clean up temporaries here anyway?
2697 RetValExp = Res.takeAs<Expr>();
2699 // If we have a related result type, we need to implicitly
2700 // convert back to the formal result type. We can't pretend to
2701 // initialize the result again --- we might end double-retaining
2702 // --- so instead we initialize a notional temporary; this can
2703 // lead to less-than-great diagnostics, but this stage is much
2704 // less likely to fail than the previous stage.
2705 if (!RelatedRetType.isNull()) {
2706 Entity = InitializedEntity::InitializeTemporary(FnRetType);
2707 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
2708 if (Res.isInvalid()) {
2709 // FIXME: Clean up temporaries here anyway?
2712 RetValExp = Res.takeAs<Expr>();
2715 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
2719 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2722 RetValExp = ER.take();
2724 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
2727 // If we need to check for the named return value optimization, save the
2728 // return statement in our scope for later processing.
2729 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
2730 !CurContext->isDependentContext())
2731 FunctionScopes.back()->Returns.push_back(Result);
2733 return Owned(Result);
2737 Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
2738 SourceLocation RParen, Decl *Parm,
2740 VarDecl *Var = cast_or_null<VarDecl>(Parm);
2741 if (Var && Var->isInvalidDecl())
2744 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
2748 Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
2749 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
2753 Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
2754 MultiStmtArg CatchStmts, Stmt *Finally) {
2755 if (!getLangOpts().ObjCExceptions)
2756 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
2758 getCurFunction()->setHasBranchProtectedScope();
2759 unsigned NumCatchStmts = CatchStmts.size();
2760 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
2766 StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
2768 ExprResult Result = DefaultLvalueConversion(Throw);
2769 if (Result.isInvalid())
2772 Result = ActOnFinishFullExpr(Result.take());
2773 if (Result.isInvalid())
2775 Throw = Result.take();
2777 QualType ThrowType = Throw->getType();
2778 // Make sure the expression type is an ObjC pointer or "void *".
2779 if (!ThrowType->isDependentType() &&
2780 !ThrowType->isObjCObjectPointerType()) {
2781 const PointerType *PT = ThrowType->getAs<PointerType>();
2782 if (!PT || !PT->getPointeeType()->isVoidType())
2783 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
2784 << Throw->getType() << Throw->getSourceRange());
2788 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
2792 Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
2794 if (!getLangOpts().ObjCExceptions)
2795 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
2798 // @throw without an expression designates a rethrow (which much occur
2799 // in the context of an @catch clause).
2800 Scope *AtCatchParent = CurScope;
2801 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
2802 AtCatchParent = AtCatchParent->getParent();
2804 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
2806 return BuildObjCAtThrowStmt(AtLoc, Throw);
2810 Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
2811 ExprResult result = DefaultLvalueConversion(operand);
2812 if (result.isInvalid())
2814 operand = result.take();
2816 // Make sure the expression type is an ObjC pointer or "void *".
2817 QualType type = operand->getType();
2818 if (!type->isDependentType() &&
2819 !type->isObjCObjectPointerType()) {
2820 const PointerType *pointerType = type->getAs<PointerType>();
2821 if (!pointerType || !pointerType->getPointeeType()->isVoidType())
2822 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
2823 << type << operand->getSourceRange();
2826 // The operand to @synchronized is a full-expression.
2827 return ActOnFinishFullExpr(operand);
2831 Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
2833 // We can't jump into or indirect-jump out of a @synchronized block.
2834 getCurFunction()->setHasBranchProtectedScope();
2835 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
2838 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
2839 /// and creates a proper catch handler from them.
2841 Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
2842 Stmt *HandlerBlock) {
2843 // There's nothing to test that ActOnExceptionDecl didn't already test.
2844 return Owned(new (Context) CXXCatchStmt(CatchLoc,
2845 cast_or_null<VarDecl>(ExDecl),
2850 Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
2851 getCurFunction()->setHasBranchProtectedScope();
2852 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
2857 class TypeWithHandler {
2861 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
2862 : t(type), stmt(statement) {}
2864 // An arbitrary order is fine as long as it places identical
2865 // types next to each other.
2866 bool operator<(const TypeWithHandler &y) const {
2867 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
2869 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
2872 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
2875 bool operator==(const TypeWithHandler& other) const {
2876 return t == other.t;
2879 CXXCatchStmt *getCatchStmt() const { return stmt; }
2880 SourceLocation getTypeSpecStartLoc() const {
2881 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
2887 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
2888 /// handlers and creates a try statement from them.
2890 Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
2891 MultiStmtArg RawHandlers) {
2892 // Don't report an error if 'try' is used in system headers.
2893 if (!getLangOpts().CXXExceptions &&
2894 !getSourceManager().isInSystemHeader(TryLoc))
2895 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
2897 unsigned NumHandlers = RawHandlers.size();
2898 assert(NumHandlers > 0 &&
2899 "The parser shouldn't call this if there are no handlers.");
2900 Stmt **Handlers = RawHandlers.data();
2902 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
2904 for (unsigned i = 0; i < NumHandlers; ++i) {
2905 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
2906 if (!Handler->getExceptionDecl()) {
2907 if (i < NumHandlers - 1)
2908 return StmtError(Diag(Handler->getLocStart(),
2909 diag::err_early_catch_all));
2914 const QualType CaughtType = Handler->getCaughtType();
2915 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
2916 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
2919 // Detect handlers for the same type as an earlier one.
2920 if (NumHandlers > 1) {
2921 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
2923 TypeWithHandler prev = TypesWithHandlers[0];
2924 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
2925 TypeWithHandler curr = TypesWithHandlers[i];
2928 Diag(curr.getTypeSpecStartLoc(),
2929 diag::warn_exception_caught_by_earlier_handler)
2930 << curr.getCatchStmt()->getCaughtType().getAsString();
2931 Diag(prev.getTypeSpecStartLoc(),
2932 diag::note_previous_exception_handler)
2933 << prev.getCatchStmt()->getCaughtType().getAsString();
2940 getCurFunction()->setHasBranchProtectedScope();
2942 // FIXME: We should detect handlers that cannot catch anything because an
2943 // earlier handler catches a superclass. Need to find a method that is not
2944 // quadratic for this.
2945 // Neither of these are explicitly forbidden, but every compiler detects them
2948 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
2949 llvm::makeArrayRef(Handlers, NumHandlers)));
2953 Sema::ActOnSEHTryBlock(bool IsCXXTry,
2954 SourceLocation TryLoc,
2957 assert(TryBlock && Handler);
2959 getCurFunction()->setHasBranchProtectedScope();
2961 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
2965 Sema::ActOnSEHExceptBlock(SourceLocation Loc,
2968 assert(FilterExpr && Block);
2970 if(!FilterExpr->getType()->isIntegerType()) {
2971 return StmtError(Diag(FilterExpr->getExprLoc(),
2972 diag::err_filter_expression_integral)
2973 << FilterExpr->getType());
2976 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
2980 Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
2983 return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
2986 StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2988 NestedNameSpecifierLoc QualifierLoc,
2989 DeclarationNameInfo NameInfo,
2992 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
2993 QualifierLoc, NameInfo,
2994 cast<CompoundStmt>(Nested));
2998 StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
3001 UnqualifiedId &Name,
3003 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
3004 SS.getWithLocInContext(Context),
3005 GetNameFromUnqualifiedId(Name),
3010 Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
3011 unsigned NumParams) {
3012 DeclContext *DC = CurContext;
3013 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
3014 DC = DC->getParent();
3017 if (getLangOpts().CPlusPlus)
3018 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/0);
3020 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/0);
3024 RD->startDefinition();
3026 CD = CapturedDecl::Create(Context, CurContext, NumParams);
3029 // Build the context parameter
3030 assert(NumParams > 0 && "CapturedStmt requires context parameter");
3031 DC = CapturedDecl::castToDeclContext(CD);
3032 IdentifierInfo *VarName = &Context.Idents.get("__context");
3033 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3034 ImplicitParamDecl *Param
3035 = ImplicitParamDecl::Create(Context, DC, Loc, VarName, ParamType);
3038 CD->setContextParam(Param);
3043 static void buildCapturedStmtCaptureList(
3044 SmallVectorImpl<CapturedStmt::Capture> &Captures,
3045 SmallVectorImpl<Expr *> &CaptureInits,
3046 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
3048 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
3049 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
3051 if (Cap->isThisCapture()) {
3052 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3053 CapturedStmt::VCK_This));
3054 CaptureInits.push_back(Cap->getCopyExpr());
3058 assert(Cap->isReferenceCapture() &&
3059 "non-reference capture not yet implemented");
3061 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3062 CapturedStmt::VCK_ByRef,
3063 Cap->getVariable()));
3064 CaptureInits.push_back(Cap->getCopyExpr());
3068 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3069 CapturedRegionKind Kind,
3070 unsigned NumParams) {
3071 CapturedDecl *CD = 0;
3072 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
3074 // Enter the capturing scope for this captured region.
3075 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3078 PushDeclContext(CurScope, CD);
3082 PushExpressionEvaluationContext(PotentiallyEvaluated);
3085 void Sema::ActOnCapturedRegionError() {
3086 DiscardCleanupsInEvaluationContext();
3087 PopExpressionEvaluationContext();
3089 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3090 RecordDecl *Record = RSI->TheRecordDecl;
3091 Record->setInvalidDecl();
3093 SmallVector<Decl*, 4> Fields;
3094 for (RecordDecl::field_iterator I = Record->field_begin(),
3095 E = Record->field_end(); I != E; ++I)
3096 Fields.push_back(*I);
3097 ActOnFields(/*Scope=*/0, Record->getLocation(), Record, Fields,
3098 SourceLocation(), SourceLocation(), /*AttributeList=*/0);
3101 PopFunctionScopeInfo();
3104 StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
3105 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3107 SmallVector<CapturedStmt::Capture, 4> Captures;
3108 SmallVector<Expr *, 4> CaptureInits;
3109 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
3111 CapturedDecl *CD = RSI->TheCapturedDecl;
3112 RecordDecl *RD = RSI->TheRecordDecl;
3114 CapturedStmt *Res = CapturedStmt::Create(getASTContext(), S,
3115 RSI->CapRegionKind, Captures,
3116 CaptureInits, CD, RD);
3118 CD->setBody(Res->getCapturedStmt());
3119 RD->completeDefinition();
3121 DiscardCleanupsInEvaluationContext();
3122 PopExpressionEvaluationContext();
3125 PopFunctionScopeInfo();