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/CXXInheritance.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/AST/TypeOrdering.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Lex/Preprocessor.h"
30 #include "clang/Sema/Initialization.h"
31 #include "clang/Sema/Lookup.h"
32 #include "clang/Sema/Scope.h"
33 #include "clang/Sema/ScopeInfo.h"
34 #include "llvm/ADT/ArrayRef.h"
35 #include "llvm/ADT/DenseMap.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/SmallPtrSet.h"
38 #include "llvm/ADT/SmallString.h"
39 #include "llvm/ADT/SmallVector.h"
41 using namespace clang;
44 StmtResult Sema::ActOnExprStmt(ExprResult FE) {
48 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
49 /*DiscardedValue*/ true);
53 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
54 // void expression for its side effects. Conversion to void allows any
55 // operand, even incomplete types.
57 // Same thing in for stmt first clause (when expr) and third clause.
58 return StmtResult(FE.getAs<Stmt>());
62 StmtResult Sema::ActOnExprStmtError() {
63 DiscardCleanupsInEvaluationContext();
67 StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
68 bool HasLeadingEmptyMacro) {
69 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
72 StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
73 SourceLocation EndLoc) {
74 DeclGroupRef DG = dg.get();
76 // If we have an invalid decl, just return an error.
77 if (DG.isNull()) return StmtError();
79 return new (Context) DeclStmt(DG, StartLoc, EndLoc);
82 void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
83 DeclGroupRef DG = dg.get();
85 // If we don't have a declaration, or we have an invalid declaration,
87 if (DG.isNull() || !DG.isSingleDecl())
90 Decl *decl = DG.getSingleDecl();
91 if (!decl || decl->isInvalidDecl())
94 // Only variable declarations are permitted.
95 VarDecl *var = dyn_cast<VarDecl>(decl);
97 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
98 decl->setInvalidDecl();
102 // foreach variables are never actually initialized in the way that
103 // the parser came up with.
104 var->setInit(nullptr);
106 // In ARC, we don't need to retain the iteration variable of a fast
107 // enumeration loop. Rather than actually trying to catch that
108 // during declaration processing, we remove the consequences here.
109 if (getLangOpts().ObjCAutoRefCount) {
110 QualType type = var->getType();
112 // Only do this if we inferred the lifetime. Inferred lifetime
113 // will show up as a local qualifier because explicit lifetime
114 // should have shown up as an AttributedType instead.
115 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
116 // Add 'const' and mark the variable as pseudo-strong.
117 var->setType(type.withConst());
118 var->setARCPseudoStrong(true);
123 /// \brief Diagnose unused comparisons, both builtin and overloaded operators.
124 /// For '==' and '!=', suggest fixits for '=' or '|='.
126 /// Adding a cast to void (or other expression wrappers) will prevent the
127 /// warning from firing.
128 static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
130 bool IsNotEqual, CanAssign, IsRelational;
132 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
133 if (!Op->isComparisonOp())
136 IsRelational = Op->isRelationalOp();
137 Loc = Op->getOperatorLoc();
138 IsNotEqual = Op->getOpcode() == BO_NE;
139 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
140 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
141 switch (Op->getOperator()) {
145 case OO_ExclaimEqual:
146 IsRelational = false;
150 case OO_GreaterEqual:
156 Loc = Op->getOperatorLoc();
157 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
158 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
160 // Not a typo-prone comparison.
164 // Suppress warnings when the operator, suspicious as it may be, comes from
165 // a macro expansion.
166 if (S.SourceMgr.isMacroBodyExpansion(Loc))
169 S.Diag(Loc, diag::warn_unused_comparison)
170 << (unsigned)IsRelational << (unsigned)IsNotEqual << E->getSourceRange();
172 // If the LHS is a plausible entity to assign to, provide a fixit hint to
173 // correct common typos.
174 if (!IsRelational && CanAssign) {
176 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
177 << FixItHint::CreateReplacement(Loc, "|=");
179 S.Diag(Loc, diag::note_equality_comparison_to_assign)
180 << FixItHint::CreateReplacement(Loc, "=");
186 void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
187 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
188 return DiagnoseUnusedExprResult(Label->getSubStmt());
190 const Expr *E = dyn_cast_or_null<Expr>(S);
194 // If we are in an unevaluated expression context, then there can be no unused
195 // results because the results aren't expected to be used in the first place.
196 if (isUnevaluatedContext())
199 SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc();
200 // In most cases, we don't want to warn if the expression is written in a
201 // macro body, or if the macro comes from a system header. If the offending
202 // expression is a call to a function with the warn_unused_result attribute,
203 // we warn no matter the location. Because of the order in which the various
204 // checks need to happen, we factor out the macro-related test here.
205 bool ShouldSuppress =
206 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
207 SourceMgr.isInSystemMacro(ExprLoc);
209 const Expr *WarnExpr;
212 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
215 // If this is a GNU statement expression expanded from a macro, it is probably
216 // unused because it is a function-like macro that can be used as either an
217 // expression or statement. Don't warn, because it is almost certainly a
219 if (isa<StmtExpr>(E) && Loc.isMacroID())
222 // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers.
223 // That macro is frequently used to suppress "unused parameter" warnings,
224 // but its implementation makes clang's -Wunused-value fire. Prevent this.
225 if (isa<ParenExpr>(E->IgnoreImpCasts()) && Loc.isMacroID()) {
226 SourceLocation SpellLoc = Loc;
227 if (findMacroSpelling(SpellLoc, "UNREFERENCED_PARAMETER"))
231 // Okay, we have an unused result. Depending on what the base expression is,
232 // we might want to make a more specific diagnostic. Check for one of these
234 unsigned DiagID = diag::warn_unused_expr;
235 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
236 E = Temps->getSubExpr();
237 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
238 E = TempExpr->getSubExpr();
240 if (DiagnoseUnusedComparison(*this, E))
244 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
245 if (E->getType()->isVoidType())
248 // If the callee has attribute pure, const, or warn_unused_result, warn with
249 // a more specific message to make it clear what is happening. If the call
250 // is written in a macro body, only warn if it has the warn_unused_result
252 if (const Decl *FD = CE->getCalleeDecl()) {
253 if (const Attr *A = isa<FunctionDecl>(FD)
254 ? cast<FunctionDecl>(FD)->getUnusedResultAttr()
255 : FD->getAttr<WarnUnusedResultAttr>()) {
256 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
261 if (FD->hasAttr<PureAttr>()) {
262 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
265 if (FD->hasAttr<ConstAttr>()) {
266 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
270 } else if (ShouldSuppress)
273 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
274 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
275 Diag(Loc, diag::err_arc_unused_init_message) << R1;
278 const ObjCMethodDecl *MD = ME->getMethodDecl();
280 if (const auto *A = MD->getAttr<WarnUnusedResultAttr>()) {
281 Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
285 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
286 const Expr *Source = POE->getSyntacticForm();
287 if (isa<ObjCSubscriptRefExpr>(Source))
288 DiagID = diag::warn_unused_container_subscript_expr;
290 DiagID = diag::warn_unused_property_expr;
291 } else if (const CXXFunctionalCastExpr *FC
292 = dyn_cast<CXXFunctionalCastExpr>(E)) {
293 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
294 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
297 // Diagnose "(void*) blah" as a typo for "(void) blah".
298 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
299 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
300 QualType T = TI->getType();
302 // We really do want to use the non-canonical type here.
303 if (T == Context.VoidPtrTy) {
304 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
306 Diag(Loc, diag::warn_unused_voidptr)
307 << FixItHint::CreateRemoval(TL.getStarLoc());
312 if (E->isGLValue() && E->getType().isVolatileQualified()) {
313 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
317 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
320 void Sema::ActOnStartOfCompoundStmt() {
324 void Sema::ActOnFinishOfCompoundStmt() {
328 sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
329 return getCurFunction()->CompoundScopes.back();
332 StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
333 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
334 const unsigned NumElts = Elts.size();
336 // If we're in C89 mode, check that we don't have any decls after stmts. If
337 // so, emit an extension diagnostic.
338 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
339 // Note that __extension__ can be around a decl.
341 // Skip over all declarations.
342 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
345 // We found the end of the list or a statement. Scan for another declstmt.
346 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
350 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
351 Diag(D->getLocation(), diag::ext_mixed_decls_code);
354 // Warn about unused expressions in statements.
355 for (unsigned i = 0; i != NumElts; ++i) {
356 // Ignore statements that are last in a statement expression.
357 if (isStmtExpr && i == NumElts - 1)
360 DiagnoseUnusedExprResult(Elts[i]);
363 // Check for suspicious empty body (null statement) in `for' and `while'
364 // statements. Don't do anything for template instantiations, this just adds
366 if (NumElts != 0 && !CurrentInstantiationScope &&
367 getCurCompoundScope().HasEmptyLoopBodies) {
368 for (unsigned i = 0; i != NumElts - 1; ++i)
369 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
372 return new (Context) CompoundStmt(Context, Elts, L, R);
376 Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
377 SourceLocation DotDotDotLoc, Expr *RHSVal,
378 SourceLocation ColonLoc) {
379 assert(LHSVal && "missing expression in case statement");
381 if (getCurFunction()->SwitchStack.empty()) {
382 Diag(CaseLoc, diag::err_case_not_in_switch);
387 CorrectDelayedTyposInExpr(LHSVal, [this](class Expr *E) {
388 if (!getLangOpts().CPlusPlus11)
389 return VerifyIntegerConstantExpression(E);
391 getCurFunction()->SwitchStack.back()->getCond()) {
392 QualType CondType = CondExpr->getType();
393 llvm::APSInt TempVal;
394 return CheckConvertedConstantExpression(E, CondType, TempVal,
403 if (!getLangOpts().CPlusPlus11) {
404 // C99 6.8.4.2p3: The expression shall be an integer constant.
405 // However, GCC allows any evaluatable integer expression.
406 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
407 LHSVal = VerifyIntegerConstantExpression(LHSVal).get();
412 // GCC extension: The expression shall be an integer constant.
414 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
415 RHSVal = VerifyIntegerConstantExpression(RHSVal).get();
416 // Recover from an error by just forgetting about it.
420 LHS = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
421 getLangOpts().CPlusPlus11);
425 auto RHS = RHSVal ? ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
426 getLangOpts().CPlusPlus11)
431 CaseStmt *CS = new (Context)
432 CaseStmt(LHS.get(), RHS.get(), CaseLoc, DotDotDotLoc, ColonLoc);
433 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
437 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
438 void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
439 DiagnoseUnusedExprResult(SubStmt);
441 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
442 CS->setSubStmt(SubStmt);
446 Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
447 Stmt *SubStmt, Scope *CurScope) {
448 DiagnoseUnusedExprResult(SubStmt);
450 if (getCurFunction()->SwitchStack.empty()) {
451 Diag(DefaultLoc, diag::err_default_not_in_switch);
455 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
456 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
461 Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
462 SourceLocation ColonLoc, Stmt *SubStmt) {
463 // If the label was multiply defined, reject it now.
464 if (TheDecl->getStmt()) {
465 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
466 Diag(TheDecl->getLocation(), diag::note_previous_definition);
470 // Otherwise, things are good. Fill in the declaration and return it.
471 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
472 TheDecl->setStmt(LS);
473 if (!TheDecl->isGnuLocal()) {
474 TheDecl->setLocStart(IdentLoc);
475 if (!TheDecl->isMSAsmLabel()) {
476 // Don't update the location of MS ASM labels. These will result in
477 // a diagnostic, and changing the location here will mess that up.
478 TheDecl->setLocation(IdentLoc);
484 StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
485 ArrayRef<const Attr*> Attrs,
487 // Fill in the declaration and return it.
488 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
493 class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> {
494 typedef EvaluatedExprVisitor<CommaVisitor> Inherited;
497 CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
498 void VisitBinaryOperator(BinaryOperator *E) {
499 if (E->getOpcode() == BO_Comma)
500 SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc());
501 EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E);
507 Sema::ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt,
508 ConditionResult Cond,
509 Stmt *thenStmt, SourceLocation ElseLoc,
511 if (Cond.isInvalid())
512 Cond = ConditionResult(
514 MakeFullExpr(new (Context) OpaqueValueExpr(SourceLocation(),
515 Context.BoolTy, VK_RValue),
519 Expr *CondExpr = Cond.get().second;
520 if (!Diags.isIgnored(diag::warn_comma_operator,
521 CondExpr->getExprLoc()))
522 CommaVisitor(*this).Visit(CondExpr);
525 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), thenStmt,
526 diag::warn_empty_if_body);
528 return BuildIfStmt(IfLoc, IsConstexpr, InitStmt, Cond, thenStmt, ElseLoc,
532 StmtResult Sema::BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr,
533 Stmt *InitStmt, ConditionResult Cond,
534 Stmt *thenStmt, SourceLocation ElseLoc,
536 if (Cond.isInvalid())
539 if (IsConstexpr || isa<ObjCAvailabilityCheckExpr>(Cond.get().second))
540 getCurFunction()->setHasBranchProtectedScope();
542 DiagnoseUnusedExprResult(thenStmt);
543 DiagnoseUnusedExprResult(elseStmt);
546 IfStmt(Context, IfLoc, IsConstexpr, InitStmt, Cond.get().first,
547 Cond.get().second, thenStmt, ElseLoc, elseStmt);
551 struct CaseCompareFunctor {
552 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
553 const llvm::APSInt &RHS) {
554 return LHS.first < RHS;
556 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
557 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
558 return LHS.first < RHS.first;
560 bool operator()(const llvm::APSInt &LHS,
561 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
562 return LHS < RHS.first;
567 /// CmpCaseVals - Comparison predicate for sorting case values.
569 static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
570 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
571 if (lhs.first < rhs.first)
574 if (lhs.first == rhs.first &&
575 lhs.second->getCaseLoc().getRawEncoding()
576 < rhs.second->getCaseLoc().getRawEncoding())
581 /// CmpEnumVals - Comparison predicate for sorting enumeration values.
583 static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
584 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
586 return lhs.first < rhs.first;
589 /// EqEnumVals - Comparison preficate for uniqing enumeration values.
591 static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
592 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
594 return lhs.first == rhs.first;
597 /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
598 /// potentially integral-promoted expression @p expr.
599 static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
600 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
601 expr = cleanups->getSubExpr();
602 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
603 if (impcast->getCastKind() != CK_IntegralCast) break;
604 expr = impcast->getSubExpr();
606 return expr->getType();
609 ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) {
610 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
614 SwitchConvertDiagnoser(Expr *Cond)
615 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
618 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
619 QualType T) override {
620 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
623 SemaDiagnosticBuilder diagnoseIncomplete(
624 Sema &S, SourceLocation Loc, QualType T) override {
625 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
626 << T << Cond->getSourceRange();
629 SemaDiagnosticBuilder diagnoseExplicitConv(
630 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
631 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
634 SemaDiagnosticBuilder noteExplicitConv(
635 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
636 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
637 << ConvTy->isEnumeralType() << ConvTy;
640 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
641 QualType T) override {
642 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
645 SemaDiagnosticBuilder noteAmbiguous(
646 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
647 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
648 << ConvTy->isEnumeralType() << ConvTy;
651 SemaDiagnosticBuilder diagnoseConversion(
652 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
653 llvm_unreachable("conversion functions are permitted");
655 } SwitchDiagnoser(Cond);
657 ExprResult CondResult =
658 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
659 if (CondResult.isInvalid())
662 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
663 return UsualUnaryConversions(CondResult.get());
666 StmtResult Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
667 Stmt *InitStmt, ConditionResult Cond) {
668 if (Cond.isInvalid())
671 getCurFunction()->setHasBranchIntoScope();
673 SwitchStmt *SS = new (Context)
674 SwitchStmt(Context, InitStmt, Cond.get().first, Cond.get().second);
675 getCurFunction()->SwitchStack.push_back(SS);
679 static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
680 Val = Val.extOrTrunc(BitWidth);
681 Val.setIsSigned(IsSigned);
684 /// Check the specified case value is in range for the given unpromoted switch
686 static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
687 unsigned UnpromotedWidth, bool UnpromotedSign) {
688 // If the case value was signed and negative and the switch expression is
689 // unsigned, don't bother to warn: this is implementation-defined behavior.
690 // FIXME: Introduce a second, default-ignored warning for this case?
691 if (UnpromotedWidth < Val.getBitWidth()) {
692 llvm::APSInt ConvVal(Val);
693 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
694 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
695 // FIXME: Use different diagnostics for overflow in conversion to promoted
696 // type versus "switch expression cannot have this value". Use proper
697 // IntRange checking rather than just looking at the unpromoted type here.
699 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
700 << ConvVal.toString(10);
704 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
706 /// Returns true if we should emit a diagnostic about this case expression not
707 /// being a part of the enum used in the switch controlling expression.
708 static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S,
710 const Expr *CaseExpr,
711 EnumValsTy::iterator &EI,
712 EnumValsTy::iterator &EIEnd,
713 const llvm::APSInt &Val) {
714 if (const DeclRefExpr *DRE =
715 dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) {
716 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
717 QualType VarType = VD->getType();
718 QualType EnumType = S.Context.getTypeDeclType(ED);
719 if (VD->hasGlobalStorage() && VarType.isConstQualified() &&
720 S.Context.hasSameUnqualifiedType(EnumType, VarType))
725 if (ED->hasAttr<FlagEnumAttr>()) {
726 return !S.IsValueInFlagEnum(ED, Val, false);
728 while (EI != EIEnd && EI->first < Val)
731 if (EI != EIEnd && EI->first == Val)
739 Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
741 SwitchStmt *SS = cast<SwitchStmt>(Switch);
742 assert(SS == getCurFunction()->SwitchStack.back() &&
743 "switch stack missing push/pop!");
745 getCurFunction()->SwitchStack.pop_back();
747 if (!BodyStmt) return StmtError();
748 SS->setBody(BodyStmt, SwitchLoc);
750 Expr *CondExpr = SS->getCond();
751 if (!CondExpr) return StmtError();
753 QualType CondType = CondExpr->getType();
755 Expr *CondExprBeforePromotion = CondExpr;
756 QualType CondTypeBeforePromotion =
757 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
760 // Integral promotions are performed (on the switch condition).
762 // A case value unrepresentable by the original switch condition
763 // type (before the promotion) doesn't make sense, even when it can
764 // be represented by the promoted type. Therefore we need to find
765 // the pre-promotion type of the switch condition.
766 if (!CondExpr->isTypeDependent()) {
767 // We have already converted the expression to an integral or enumeration
768 // type, when we started the switch statement. If we don't have an
769 // appropriate type now, just return an error.
770 if (!CondType->isIntegralOrEnumerationType())
773 if (CondExpr->isKnownToHaveBooleanValue()) {
774 // switch(bool_expr) {...} is often a programmer error, e.g.
775 // switch(n && mask) { ... } // Doh - should be "n & mask".
776 // One can always use an if statement instead of switch(bool_expr).
777 Diag(SwitchLoc, diag::warn_bool_switch_condition)
778 << CondExpr->getSourceRange();
782 // Get the bitwidth of the switched-on value after promotions. We must
783 // convert the integer case values to this width before comparison.
784 bool HasDependentValue
785 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
786 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
787 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
789 // Get the width and signedness that the condition might actually have, for
791 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
793 unsigned CondWidthBeforePromotion
794 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
795 bool CondIsSignedBeforePromotion
796 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
798 // Accumulate all of the case values in a vector so that we can sort them
799 // and detect duplicates. This vector contains the APInt for the case after
800 // it has been converted to the condition type.
801 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
804 // Keep track of any GNU case ranges we see. The APSInt is the low value.
805 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
806 CaseRangesTy CaseRanges;
808 DefaultStmt *TheDefaultStmt = nullptr;
810 bool CaseListIsErroneous = false;
812 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
813 SC = SC->getNextSwitchCase()) {
815 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
816 if (TheDefaultStmt) {
817 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
818 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
820 // FIXME: Remove the default statement from the switch block so that
821 // we'll return a valid AST. This requires recursing down the AST and
822 // finding it, not something we are set up to do right now. For now,
823 // just lop the entire switch stmt out of the AST.
824 CaseListIsErroneous = true;
829 CaseStmt *CS = cast<CaseStmt>(SC);
831 Expr *Lo = CS->getLHS();
833 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
834 HasDependentValue = true;
840 if (getLangOpts().CPlusPlus11) {
841 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
842 // constant expression of the promoted type of the switch condition.
844 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
845 if (ConvLo.isInvalid()) {
846 CaseListIsErroneous = true;
851 // We already verified that the expression has a i-c-e value (C99
852 // 6.8.4.2p3) - get that value now.
853 LoVal = Lo->EvaluateKnownConstInt(Context);
855 // If the LHS is not the same type as the condition, insert an implicit
857 Lo = DefaultLvalueConversion(Lo).get();
858 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).get();
861 // Check the unconverted value is within the range of possible values of
862 // the switch expression.
863 checkCaseValue(*this, Lo->getLocStart(), LoVal,
864 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
866 // Convert the value to the same width/sign as the condition.
867 AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
871 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
873 if (CS->getRHS()->isTypeDependent() ||
874 CS->getRHS()->isValueDependent()) {
875 HasDependentValue = true;
878 CaseRanges.push_back(std::make_pair(LoVal, CS));
880 CaseVals.push_back(std::make_pair(LoVal, CS));
884 if (!HasDependentValue) {
885 // If we don't have a default statement, check whether the
886 // condition is constant.
887 llvm::APSInt ConstantCondValue;
888 bool HasConstantCond = false;
889 if (!HasDependentValue && !TheDefaultStmt) {
890 HasConstantCond = CondExpr->EvaluateAsInt(ConstantCondValue, Context,
891 Expr::SE_AllowSideEffects);
892 assert(!HasConstantCond ||
893 (ConstantCondValue.getBitWidth() == CondWidth &&
894 ConstantCondValue.isSigned() == CondIsSigned));
896 bool ShouldCheckConstantCond = HasConstantCond;
898 // Sort all the scalar case values so we can easily detect duplicates.
899 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
901 if (!CaseVals.empty()) {
902 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
903 if (ShouldCheckConstantCond &&
904 CaseVals[i].first == ConstantCondValue)
905 ShouldCheckConstantCond = false;
907 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
908 // If we have a duplicate, report it.
909 // First, determine if either case value has a name
910 StringRef PrevString, CurrString;
911 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
912 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
913 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
914 PrevString = DeclRef->getDecl()->getName();
916 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
917 CurrString = DeclRef->getDecl()->getName();
919 SmallString<16> CaseValStr;
920 CaseVals[i-1].first.toString(CaseValStr);
922 if (PrevString == CurrString)
923 Diag(CaseVals[i].second->getLHS()->getLocStart(),
924 diag::err_duplicate_case) <<
925 (PrevString.empty() ? StringRef(CaseValStr) : PrevString);
927 Diag(CaseVals[i].second->getLHS()->getLocStart(),
928 diag::err_duplicate_case_differing_expr) <<
929 (PrevString.empty() ? StringRef(CaseValStr) : PrevString) <<
930 (CurrString.empty() ? StringRef(CaseValStr) : CurrString) <<
933 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
934 diag::note_duplicate_case_prev);
935 // FIXME: We really want to remove the bogus case stmt from the
936 // substmt, but we have no way to do this right now.
937 CaseListIsErroneous = true;
942 // Detect duplicate case ranges, which usually don't exist at all in
944 if (!CaseRanges.empty()) {
945 // Sort all the case ranges by their low value so we can easily detect
946 // overlaps between ranges.
947 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
949 // Scan the ranges, computing the high values and removing empty ranges.
950 std::vector<llvm::APSInt> HiVals;
951 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
952 llvm::APSInt &LoVal = CaseRanges[i].first;
953 CaseStmt *CR = CaseRanges[i].second;
954 Expr *Hi = CR->getRHS();
957 if (getLangOpts().CPlusPlus11) {
958 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
959 // constant expression of the promoted type of the switch condition.
961 CheckConvertedConstantExpression(Hi, CondType, HiVal,
963 if (ConvHi.isInvalid()) {
964 CaseListIsErroneous = true;
969 HiVal = Hi->EvaluateKnownConstInt(Context);
971 // If the RHS is not the same type as the condition, insert an
973 Hi = DefaultLvalueConversion(Hi).get();
974 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).get();
977 // Check the unconverted value is within the range of possible values of
978 // the switch expression.
979 checkCaseValue(*this, Hi->getLocStart(), HiVal,
980 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
982 // Convert the value to the same width/sign as the condition.
983 AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
987 // If the low value is bigger than the high value, the case is empty.
989 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
990 << SourceRange(CR->getLHS()->getLocStart(),
992 CaseRanges.erase(CaseRanges.begin()+i);
998 if (ShouldCheckConstantCond &&
999 LoVal <= ConstantCondValue &&
1000 ConstantCondValue <= HiVal)
1001 ShouldCheckConstantCond = false;
1003 HiVals.push_back(HiVal);
1006 // Rescan the ranges, looking for overlap with singleton values and other
1007 // ranges. Since the range list is sorted, we only need to compare case
1008 // ranges with their neighbors.
1009 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1010 llvm::APSInt &CRLo = CaseRanges[i].first;
1011 llvm::APSInt &CRHi = HiVals[i];
1012 CaseStmt *CR = CaseRanges[i].second;
1014 // Check to see whether the case range overlaps with any
1016 CaseStmt *OverlapStmt = nullptr;
1017 llvm::APSInt OverlapVal(32);
1019 // Find the smallest value >= the lower bound. If I is in the
1020 // case range, then we have overlap.
1021 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
1022 CaseVals.end(), CRLo,
1023 CaseCompareFunctor());
1024 if (I != CaseVals.end() && I->first < CRHi) {
1025 OverlapVal = I->first; // Found overlap with scalar.
1026 OverlapStmt = I->second;
1029 // Find the smallest value bigger than the upper bound.
1030 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1031 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1032 OverlapVal = (I-1)->first; // Found overlap with scalar.
1033 OverlapStmt = (I-1)->second;
1036 // Check to see if this case stmt overlaps with the subsequent
1038 if (i && CRLo <= HiVals[i-1]) {
1039 OverlapVal = HiVals[i-1]; // Found overlap with range.
1040 OverlapStmt = CaseRanges[i-1].second;
1044 // If we have a duplicate, report it.
1045 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
1046 << OverlapVal.toString(10);
1047 Diag(OverlapStmt->getLHS()->getLocStart(),
1048 diag::note_duplicate_case_prev);
1049 // FIXME: We really want to remove the bogus case stmt from the
1050 // substmt, but we have no way to do this right now.
1051 CaseListIsErroneous = true;
1056 // Complain if we have a constant condition and we didn't find a match.
1057 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
1058 // TODO: it would be nice if we printed enums as enums, chars as
1060 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1061 << ConstantCondValue.toString(10)
1062 << CondExpr->getSourceRange();
1065 // Check to see if switch is over an Enum and handles all of its
1066 // values. We only issue a warning if there is not 'default:', but
1067 // we still do the analysis to preserve this information in the AST
1068 // (which can be used by flow-based analyes).
1070 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
1072 // If switch has default case, then ignore it.
1073 if (!CaseListIsErroneous && !HasConstantCond && ET &&
1074 ET->getDecl()->isCompleteDefinition()) {
1075 const EnumDecl *ED = ET->getDecl();
1076 EnumValsTy EnumVals;
1078 // Gather all enum values, set their type and sort them,
1079 // allowing easier comparison with CaseVals.
1080 for (auto *EDI : ED->enumerators()) {
1081 llvm::APSInt Val = EDI->getInitVal();
1082 AdjustAPSInt(Val, CondWidth, CondIsSigned);
1083 EnumVals.push_back(std::make_pair(Val, EDI));
1085 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1086 auto EI = EnumVals.begin(), EIEnd =
1087 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1089 // See which case values aren't in enum.
1090 for (CaseValsTy::const_iterator CI = CaseVals.begin();
1091 CI != CaseVals.end(); CI++) {
1092 Expr *CaseExpr = CI->second->getLHS();
1093 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1095 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1096 << CondTypeBeforePromotion;
1099 // See which of case ranges aren't in enum
1100 EI = EnumVals.begin();
1101 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1102 RI != CaseRanges.end(); RI++) {
1103 Expr *CaseExpr = RI->second->getLHS();
1104 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1106 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1107 << CondTypeBeforePromotion;
1110 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1111 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1113 CaseExpr = RI->second->getRHS();
1114 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd,
1116 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1117 << CondTypeBeforePromotion;
1120 // Check which enum vals aren't in switch
1121 auto CI = CaseVals.begin();
1122 auto RI = CaseRanges.begin();
1123 bool hasCasesNotInSwitch = false;
1125 SmallVector<DeclarationName,8> UnhandledNames;
1127 for (EI = EnumVals.begin(); EI != EIEnd; EI++){
1128 // Drop unneeded case values
1129 while (CI != CaseVals.end() && CI->first < EI->first)
1132 if (CI != CaseVals.end() && CI->first == EI->first)
1135 // Drop unneeded case ranges
1136 for (; RI != CaseRanges.end(); RI++) {
1138 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1139 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1140 if (EI->first <= Hi)
1144 if (RI == CaseRanges.end() || EI->first < RI->first) {
1145 hasCasesNotInSwitch = true;
1146 UnhandledNames.push_back(EI->second->getDeclName());
1150 if (TheDefaultStmt && UnhandledNames.empty())
1151 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
1153 // Produce a nice diagnostic if multiple values aren't handled.
1154 if (!UnhandledNames.empty()) {
1155 DiagnosticBuilder DB = Diag(CondExpr->getExprLoc(),
1156 TheDefaultStmt ? diag::warn_def_missing_case
1157 : diag::warn_missing_case)
1158 << (int)UnhandledNames.size();
1160 for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3);
1162 DB << UnhandledNames[I];
1165 if (!hasCasesNotInSwitch)
1166 SS->setAllEnumCasesCovered();
1171 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1172 diag::warn_empty_switch_body);
1174 // FIXME: If the case list was broken is some way, we don't have a good system
1175 // to patch it up. Instead, just return the whole substmt as broken.
1176 if (CaseListIsErroneous)
1183 Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1185 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
1188 if (const EnumType *ET = DstType->getAs<EnumType>())
1189 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
1190 SrcType->isIntegerType()) {
1191 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1192 SrcExpr->isIntegerConstantExpr(Context)) {
1193 // Get the bitwidth of the enum value before promotions.
1194 unsigned DstWidth = Context.getIntWidth(DstType);
1195 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1197 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1198 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
1199 const EnumDecl *ED = ET->getDecl();
1201 if (ED->hasAttr<FlagEnumAttr>()) {
1202 if (!IsValueInFlagEnum(ED, RhsVal, true))
1203 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1204 << DstType.getUnqualifiedType();
1206 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1208 EnumValsTy EnumVals;
1210 // Gather all enum values, set their type and sort them,
1211 // allowing easier comparison with rhs constant.
1212 for (auto *EDI : ED->enumerators()) {
1213 llvm::APSInt Val = EDI->getInitVal();
1214 AdjustAPSInt(Val, DstWidth, DstIsSigned);
1215 EnumVals.push_back(std::make_pair(Val, EDI));
1217 if (EnumVals.empty())
1219 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1220 EnumValsTy::iterator EIend =
1221 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1223 // See which values aren't in the enum.
1224 EnumValsTy::const_iterator EI = EnumVals.begin();
1225 while (EI != EIend && EI->first < RhsVal)
1227 if (EI == EIend || EI->first != RhsVal) {
1228 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1229 << DstType.getUnqualifiedType();
1236 StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond,
1238 if (Cond.isInvalid())
1241 auto CondVal = Cond.get();
1242 CheckBreakContinueBinding(CondVal.second);
1244 if (CondVal.second &&
1245 !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc()))
1246 CommaVisitor(*this).Visit(CondVal.second);
1248 DiagnoseUnusedExprResult(Body);
1250 if (isa<NullStmt>(Body))
1251 getCurCompoundScope().setHasEmptyLoopBodies();
1253 return new (Context)
1254 WhileStmt(Context, CondVal.first, CondVal.second, Body, WhileLoc);
1258 Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
1259 SourceLocation WhileLoc, SourceLocation CondLParen,
1260 Expr *Cond, SourceLocation CondRParen) {
1261 assert(Cond && "ActOnDoStmt(): missing expression");
1263 CheckBreakContinueBinding(Cond);
1264 ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond);
1265 if (CondResult.isInvalid())
1267 Cond = CondResult.get();
1269 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
1270 if (CondResult.isInvalid())
1272 Cond = CondResult.get();
1274 DiagnoseUnusedExprResult(Body);
1276 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
1280 // This visitor will traverse a conditional statement and store all
1281 // the evaluated decls into a vector. Simple is set to true if none
1282 // of the excluded constructs are used.
1283 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1284 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
1285 SmallVectorImpl<SourceRange> &Ranges;
1288 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1290 DeclExtractor(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
1291 SmallVectorImpl<SourceRange> &Ranges) :
1292 Inherited(S.Context),
1297 bool isSimple() { return Simple; }
1299 // Replaces the method in EvaluatedExprVisitor.
1300 void VisitMemberExpr(MemberExpr* E) {
1304 // Any Stmt not whitelisted will cause the condition to be marked complex.
1305 void VisitStmt(Stmt *S) {
1309 void VisitBinaryOperator(BinaryOperator *E) {
1314 void VisitCastExpr(CastExpr *E) {
1315 Visit(E->getSubExpr());
1318 void VisitUnaryOperator(UnaryOperator *E) {
1319 // Skip checking conditionals with derefernces.
1320 if (E->getOpcode() == UO_Deref)
1323 Visit(E->getSubExpr());
1326 void VisitConditionalOperator(ConditionalOperator *E) {
1327 Visit(E->getCond());
1328 Visit(E->getTrueExpr());
1329 Visit(E->getFalseExpr());
1332 void VisitParenExpr(ParenExpr *E) {
1333 Visit(E->getSubExpr());
1336 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1337 Visit(E->getOpaqueValue()->getSourceExpr());
1338 Visit(E->getFalseExpr());
1341 void VisitIntegerLiteral(IntegerLiteral *E) { }
1342 void VisitFloatingLiteral(FloatingLiteral *E) { }
1343 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1344 void VisitCharacterLiteral(CharacterLiteral *E) { }
1345 void VisitGNUNullExpr(GNUNullExpr *E) { }
1346 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1348 void VisitDeclRefExpr(DeclRefExpr *E) {
1349 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1352 Ranges.push_back(E->getSourceRange());
1357 }; // end class DeclExtractor
1359 // DeclMatcher checks to see if the decls are used in a non-evaluated
1361 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1362 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
1366 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1368 DeclMatcher(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
1370 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1371 if (!Statement) return;
1376 void VisitReturnStmt(ReturnStmt *S) {
1380 void VisitBreakStmt(BreakStmt *S) {
1384 void VisitGotoStmt(GotoStmt *S) {
1388 void VisitCastExpr(CastExpr *E) {
1389 if (E->getCastKind() == CK_LValueToRValue)
1390 CheckLValueToRValueCast(E->getSubExpr());
1392 Visit(E->getSubExpr());
1395 void CheckLValueToRValueCast(Expr *E) {
1396 E = E->IgnoreParenImpCasts();
1398 if (isa<DeclRefExpr>(E)) {
1402 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1403 Visit(CO->getCond());
1404 CheckLValueToRValueCast(CO->getTrueExpr());
1405 CheckLValueToRValueCast(CO->getFalseExpr());
1409 if (BinaryConditionalOperator *BCO =
1410 dyn_cast<BinaryConditionalOperator>(E)) {
1411 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1412 CheckLValueToRValueCast(BCO->getFalseExpr());
1419 void VisitDeclRefExpr(DeclRefExpr *E) {
1420 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1421 if (Decls.count(VD))
1425 void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
1426 // Only need to visit the semantics for POE.
1427 // SyntaticForm doesn't really use the Decal.
1428 for (auto *S : POE->semantics()) {
1429 if (auto *OVE = dyn_cast<OpaqueValueExpr>(S))
1430 // Look past the OVE into the expression it binds.
1431 Visit(OVE->getSourceExpr());
1437 bool FoundDeclInUse() { return FoundDecl; }
1439 }; // end class DeclMatcher
1441 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1442 Expr *Third, Stmt *Body) {
1443 // Condition is empty
1444 if (!Second) return;
1446 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1447 Second->getLocStart()))
1450 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1451 llvm::SmallPtrSet<VarDecl*, 8> Decls;
1452 SmallVector<SourceRange, 10> Ranges;
1453 DeclExtractor DE(S, Decls, Ranges);
1456 // Don't analyze complex conditionals.
1457 if (!DE.isSimple()) return;
1460 if (Decls.size() == 0) return;
1462 // Don't warn on volatile, static, or global variables.
1463 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1466 if ((*I)->getType().isVolatileQualified() ||
1467 (*I)->hasGlobalStorage()) return;
1469 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1470 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1471 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1474 // Load decl names into diagnostic.
1475 if (Decls.size() > 4)
1478 PDiag << Decls.size();
1479 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1482 PDiag << (*I)->getDeclName();
1485 // Load SourceRanges into diagnostic if there is room.
1486 // Otherwise, load the SourceRange of the conditional expression.
1487 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
1488 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
1493 PDiag << Second->getSourceRange();
1495 S.Diag(Ranges.begin()->getBegin(), PDiag);
1498 // If Statement is an incemement or decrement, return true and sets the
1499 // variables Increment and DRE.
1500 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1501 DeclRefExpr *&DRE) {
1502 if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement))
1503 if (!Cleanups->cleanupsHaveSideEffects())
1504 Statement = Cleanups->getSubExpr();
1506 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1507 switch (UO->getOpcode()) {
1508 default: return false;
1518 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1522 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1523 FunctionDecl *FD = Call->getDirectCallee();
1524 if (!FD || !FD->isOverloadedOperator()) return false;
1525 switch (FD->getOverloadedOperator()) {
1526 default: return false;
1534 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1541 // A visitor to determine if a continue or break statement is a
1543 class BreakContinueFinder : public EvaluatedExprVisitor<BreakContinueFinder> {
1544 SourceLocation BreakLoc;
1545 SourceLocation ContinueLoc;
1547 BreakContinueFinder(Sema &S, Stmt* Body) :
1548 Inherited(S.Context) {
1552 typedef EvaluatedExprVisitor<BreakContinueFinder> Inherited;
1554 void VisitContinueStmt(ContinueStmt* E) {
1555 ContinueLoc = E->getContinueLoc();
1558 void VisitBreakStmt(BreakStmt* E) {
1559 BreakLoc = E->getBreakLoc();
1562 bool ContinueFound() { return ContinueLoc.isValid(); }
1563 bool BreakFound() { return BreakLoc.isValid(); }
1564 SourceLocation GetContinueLoc() { return ContinueLoc; }
1565 SourceLocation GetBreakLoc() { return BreakLoc; }
1567 }; // end class BreakContinueFinder
1569 // Emit a warning when a loop increment/decrement appears twice per loop
1570 // iteration. The conditions which trigger this warning are:
1571 // 1) The last statement in the loop body and the third expression in the
1572 // for loop are both increment or both decrement of the same variable
1573 // 2) No continue statements in the loop body.
1574 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1575 // Return when there is nothing to check.
1576 if (!Body || !Third) return;
1578 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1579 Third->getLocStart()))
1582 // Get the last statement from the loop body.
1583 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1584 if (!CS || CS->body_empty()) return;
1585 Stmt *LastStmt = CS->body_back();
1586 if (!LastStmt) return;
1588 bool LoopIncrement, LastIncrement;
1589 DeclRefExpr *LoopDRE, *LastDRE;
1591 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1592 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1594 // Check that the two statements are both increments or both decrements
1595 // on the same variable.
1596 if (LoopIncrement != LastIncrement ||
1597 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1599 if (BreakContinueFinder(S, Body).ContinueFound()) return;
1601 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1602 << LastDRE->getDecl() << LastIncrement;
1603 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1610 void Sema::CheckBreakContinueBinding(Expr *E) {
1611 if (!E || getLangOpts().CPlusPlus)
1613 BreakContinueFinder BCFinder(*this, E);
1614 Scope *BreakParent = CurScope->getBreakParent();
1615 if (BCFinder.BreakFound() && BreakParent) {
1616 if (BreakParent->getFlags() & Scope::SwitchScope) {
1617 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1619 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1622 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1623 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1628 StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1629 Stmt *First, ConditionResult Second,
1630 FullExprArg third, SourceLocation RParenLoc,
1632 if (Second.isInvalid())
1635 if (!getLangOpts().CPlusPlus) {
1636 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
1637 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1638 // declare identifiers for objects having storage class 'auto' or
1640 for (auto *DI : DS->decls()) {
1641 VarDecl *VD = dyn_cast<VarDecl>(DI);
1642 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
1645 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1646 DI->setInvalidDecl();
1652 CheckBreakContinueBinding(Second.get().second);
1653 CheckBreakContinueBinding(third.get());
1655 if (!Second.get().first)
1656 CheckForLoopConditionalStatement(*this, Second.get().second, third.get(),
1658 CheckForRedundantIteration(*this, third.get(), Body);
1660 if (Second.get().second &&
1661 !Diags.isIgnored(diag::warn_comma_operator,
1662 Second.get().second->getExprLoc()))
1663 CommaVisitor(*this).Visit(Second.get().second);
1665 Expr *Third = third.release().getAs<Expr>();
1667 DiagnoseUnusedExprResult(First);
1668 DiagnoseUnusedExprResult(Third);
1669 DiagnoseUnusedExprResult(Body);
1671 if (isa<NullStmt>(Body))
1672 getCurCompoundScope().setHasEmptyLoopBodies();
1674 return new (Context)
1675 ForStmt(Context, First, Second.get().second, Second.get().first, Third,
1676 Body, ForLoc, LParenLoc, RParenLoc);
1679 /// In an Objective C collection iteration statement:
1681 /// x can be an arbitrary l-value expression. Bind it up as a
1682 /// full-expression.
1683 StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
1684 // Reduce placeholder expressions here. Note that this rejects the
1685 // use of pseudo-object l-values in this position.
1686 ExprResult result = CheckPlaceholderExpr(E);
1687 if (result.isInvalid()) return StmtError();
1690 ExprResult FullExpr = ActOnFinishFullExpr(E);
1691 if (FullExpr.isInvalid())
1693 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
1697 Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1701 ExprResult result = CorrectDelayedTyposInExpr(collection);
1702 if (!result.isUsable())
1704 collection = result.get();
1706 // Bail out early if we've got a type-dependent expression.
1707 if (collection->isTypeDependent()) return collection;
1709 // Perform normal l-value conversion.
1710 result = DefaultFunctionArrayLvalueConversion(collection);
1711 if (result.isInvalid())
1713 collection = result.get();
1715 // The operand needs to have object-pointer type.
1716 // TODO: should we do a contextual conversion?
1717 const ObjCObjectPointerType *pointerType =
1718 collection->getType()->getAs<ObjCObjectPointerType>();
1720 return Diag(forLoc, diag::err_collection_expr_type)
1721 << collection->getType() << collection->getSourceRange();
1723 // Check that the operand provides
1724 // - countByEnumeratingWithState:objects:count:
1725 const ObjCObjectType *objectType = pointerType->getObjectType();
1726 ObjCInterfaceDecl *iface = objectType->getInterface();
1728 // If we have a forward-declared type, we can't do this check.
1729 // Under ARC, it is an error not to have a forward-declared class.
1731 (getLangOpts().ObjCAutoRefCount
1732 ? RequireCompleteType(forLoc, QualType(objectType, 0),
1733 diag::err_arc_collection_forward, collection)
1734 : !isCompleteType(forLoc, QualType(objectType, 0)))) {
1735 // Otherwise, if we have any useful type information, check that
1736 // the type declares the appropriate method.
1737 } else if (iface || !objectType->qual_empty()) {
1738 IdentifierInfo *selectorIdents[] = {
1739 &Context.Idents.get("countByEnumeratingWithState"),
1740 &Context.Idents.get("objects"),
1741 &Context.Idents.get("count")
1743 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1745 ObjCMethodDecl *method = nullptr;
1747 // If there's an interface, look in both the public and private APIs.
1749 method = iface->lookupInstanceMethod(selector);
1750 if (!method) method = iface->lookupPrivateMethod(selector);
1753 // Also check protocol qualifiers.
1755 method = LookupMethodInQualifiedType(selector, pointerType,
1758 // If we didn't find it anywhere, give up.
1760 Diag(forLoc, diag::warn_collection_expr_type)
1761 << collection->getType() << selector << collection->getSourceRange();
1764 // TODO: check for an incompatible signature?
1767 // Wrap up any cleanups in the expression.
1772 Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1773 Stmt *First, Expr *collection,
1774 SourceLocation RParenLoc) {
1776 ExprResult CollectionExprResult =
1777 CheckObjCForCollectionOperand(ForLoc, collection);
1781 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
1782 if (!DS->isSingleDecl())
1783 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1784 diag::err_toomany_element_decls));
1786 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1787 if (!D || D->isInvalidDecl())
1790 FirstType = D->getType();
1791 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1792 // declare identifiers for objects having storage class 'auto' or
1794 if (!D->hasLocalStorage())
1795 return StmtError(Diag(D->getLocation(),
1796 diag::err_non_local_variable_decl_in_for));
1798 // If the type contained 'auto', deduce the 'auto' to 'id'.
1799 if (FirstType->getContainedAutoType()) {
1800 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1802 Expr *DeducedInit = &OpaqueId;
1803 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1805 DiagnoseAutoDeductionFailure(D, DeducedInit);
1806 if (FirstType.isNull()) {
1807 D->setInvalidDecl();
1811 D->setType(FirstType);
1813 if (ActiveTemplateInstantiations.empty()) {
1814 SourceLocation Loc =
1815 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
1816 Diag(Loc, diag::warn_auto_var_is_id)
1817 << D->getDeclName();
1822 Expr *FirstE = cast<Expr>(First);
1823 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
1824 return StmtError(Diag(First->getLocStart(),
1825 diag::err_selector_element_not_lvalue)
1826 << First->getSourceRange());
1828 FirstType = static_cast<Expr*>(First)->getType();
1829 if (FirstType.isConstQualified())
1830 Diag(ForLoc, diag::err_selector_element_const_type)
1831 << FirstType << First->getSourceRange();
1833 if (!FirstType->isDependentType() &&
1834 !FirstType->isObjCObjectPointerType() &&
1835 !FirstType->isBlockPointerType())
1836 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1837 << FirstType << First->getSourceRange());
1840 if (CollectionExprResult.isInvalid())
1843 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
1844 if (CollectionExprResult.isInvalid())
1847 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1848 nullptr, ForLoc, RParenLoc);
1851 /// Finish building a variable declaration for a for-range statement.
1852 /// \return true if an error occurs.
1853 static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1854 SourceLocation Loc, int DiagID) {
1855 if (Decl->getType()->isUndeducedType()) {
1856 ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init);
1857 if (!Res.isUsable()) {
1858 Decl->setInvalidDecl();
1864 // Deduce the type for the iterator variable now rather than leaving it to
1865 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1867 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
1868 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
1870 SemaRef.Diag(Loc, DiagID) << Init->getType();
1871 if (InitType.isNull()) {
1872 Decl->setInvalidDecl();
1875 Decl->setType(InitType);
1877 // In ARC, infer lifetime.
1878 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1879 // we're doing the equivalent of fast iteration.
1880 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1881 SemaRef.inferObjCARCLifetime(Decl))
1882 Decl->setInvalidDecl();
1884 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false);
1885 SemaRef.FinalizeDeclaration(Decl);
1886 SemaRef.CurContext->addHiddenDecl(Decl);
1891 // An enum to represent whether something is dealing with a call to begin()
1892 // or a call to end() in a range-based for loop.
1893 enum BeginEndFunction {
1898 /// Produce a note indicating which begin/end function was implicitly called
1899 /// by a C++11 for-range statement. This is often not obvious from the code,
1900 /// nor from the diagnostics produced when analysing the implicit expressions
1901 /// required in a for-range statement.
1902 void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
1903 BeginEndFunction BEF) {
1904 CallExpr *CE = dyn_cast<CallExpr>(E);
1907 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1910 SourceLocation Loc = D->getLocation();
1912 std::string Description;
1913 bool IsTemplate = false;
1914 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1915 Description = SemaRef.getTemplateArgumentBindingsText(
1916 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1920 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1921 << BEF << IsTemplate << Description << E->getType();
1924 /// Build a variable declaration for a for-range statement.
1925 VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1926 QualType Type, const char *Name) {
1927 DeclContext *DC = SemaRef.CurContext;
1928 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1929 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1930 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1932 Decl->setImplicit();
1938 static bool ObjCEnumerationCollection(Expr *Collection) {
1939 return !Collection->isTypeDependent()
1940 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
1943 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
1945 /// C++11 [stmt.ranged]:
1946 /// A range-based for statement is equivalent to
1949 /// auto && __range = range-init;
1950 /// for ( auto __begin = begin-expr,
1951 /// __end = end-expr;
1952 /// __begin != __end;
1954 /// for-range-declaration = *__begin;
1959 /// The body of the loop is not available yet, since it cannot be analysed until
1960 /// we have determined the type of the for-range-declaration.
1961 StmtResult Sema::ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
1962 SourceLocation CoawaitLoc, Stmt *First,
1963 SourceLocation ColonLoc, Expr *Range,
1964 SourceLocation RParenLoc,
1965 BuildForRangeKind Kind) {
1969 if (Range && ObjCEnumerationCollection(Range))
1970 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
1972 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1973 assert(DS && "first part of for range not a decl stmt");
1975 if (!DS->isSingleDecl()) {
1976 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1980 Decl *LoopVar = DS->getSingleDecl();
1981 if (LoopVar->isInvalidDecl() || !Range ||
1982 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
1983 LoopVar->setInvalidDecl();
1987 // Coroutines: 'for co_await' implicitly co_awaits its range.
1988 if (CoawaitLoc.isValid()) {
1989 ExprResult Coawait = ActOnCoawaitExpr(S, CoawaitLoc, Range);
1990 if (Coawait.isInvalid()) return StmtError();
1991 Range = Coawait.get();
1994 // Build auto && __range = range-init
1995 SourceLocation RangeLoc = Range->getLocStart();
1996 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1997 Context.getAutoRRefDeductType(),
1999 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
2000 diag::err_for_range_deduction_failure)) {
2001 LoopVar->setInvalidDecl();
2005 // Claim the type doesn't contain auto: we've already done the checking.
2006 DeclGroupPtrTy RangeGroup =
2007 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1));
2008 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
2009 if (RangeDecl.isInvalid()) {
2010 LoopVar->setInvalidDecl();
2014 return BuildCXXForRangeStmt(ForLoc, CoawaitLoc, ColonLoc, RangeDecl.get(),
2015 /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr,
2016 /*Cond=*/nullptr, /*Inc=*/nullptr,
2017 DS, RParenLoc, Kind);
2020 /// \brief Create the initialization, compare, and increment steps for
2021 /// the range-based for loop expression.
2022 /// This function does not handle array-based for loops,
2023 /// which are created in Sema::BuildCXXForRangeStmt.
2025 /// \returns a ForRangeStatus indicating success or what kind of error occurred.
2026 /// BeginExpr and EndExpr are set and FRS_Success is returned on success;
2027 /// CandidateSet and BEF are set and some non-success value is returned on
2029 static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef,
2030 Expr *BeginRange, Expr *EndRange,
2034 SourceLocation ColonLoc,
2035 OverloadCandidateSet *CandidateSet,
2036 ExprResult *BeginExpr,
2037 ExprResult *EndExpr,
2038 BeginEndFunction *BEF) {
2039 DeclarationNameInfo BeginNameInfo(
2040 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
2041 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2044 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2045 Sema::LookupMemberName);
2046 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2048 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2049 // - if _RangeT is a class type, the unqualified-ids begin and end are
2050 // looked up in the scope of class _RangeT as if by class member access
2051 // lookup (3.4.5), and if either (or both) finds at least one
2052 // declaration, begin-expr and end-expr are __range.begin() and
2053 // __range.end(), respectively;
2054 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2055 SemaRef.LookupQualifiedName(EndMemberLookup, D);
2057 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2058 SourceLocation RangeLoc = BeginVar->getLocation();
2059 *BEF = BeginMemberLookup.empty() ? BEF_end : BEF_begin;
2061 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
2062 << RangeLoc << BeginRange->getType() << *BEF;
2063 return Sema::FRS_DiagnosticIssued;
2066 // - otherwise, begin-expr and end-expr are begin(__range) and
2067 // end(__range), respectively, where begin and end are looked up with
2068 // argument-dependent lookup (3.4.2). For the purposes of this name
2069 // lookup, namespace std is an associated namespace.
2074 Sema::ForRangeStatus RangeStatus =
2075 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo,
2076 BeginMemberLookup, CandidateSet,
2077 BeginRange, BeginExpr);
2079 if (RangeStatus != Sema::FRS_Success) {
2080 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2081 SemaRef.Diag(BeginRange->getLocStart(), diag::note_in_for_range)
2082 << ColonLoc << BEF_begin << BeginRange->getType();
2085 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2086 diag::err_for_range_iter_deduction_failure)) {
2087 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2088 return Sema::FRS_DiagnosticIssued;
2093 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo,
2094 EndMemberLookup, CandidateSet,
2096 if (RangeStatus != Sema::FRS_Success) {
2097 if (RangeStatus == Sema::FRS_DiagnosticIssued)
2098 SemaRef.Diag(EndRange->getLocStart(), diag::note_in_for_range)
2099 << ColonLoc << BEF_end << EndRange->getType();
2102 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2103 diag::err_for_range_iter_deduction_failure)) {
2104 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2105 return Sema::FRS_DiagnosticIssued;
2107 return Sema::FRS_Success;
2110 /// Speculatively attempt to dereference an invalid range expression.
2111 /// If the attempt fails, this function will return a valid, null StmtResult
2112 /// and emit no diagnostics.
2113 static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2114 SourceLocation ForLoc,
2115 SourceLocation CoawaitLoc,
2117 SourceLocation ColonLoc,
2119 SourceLocation RangeLoc,
2120 SourceLocation RParenLoc) {
2121 // Determine whether we can rebuild the for-range statement with a
2122 // dereferenced range expression.
2123 ExprResult AdjustedRange;
2125 Sema::SFINAETrap Trap(SemaRef);
2127 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2128 if (AdjustedRange.isInvalid())
2129 return StmtResult();
2131 StmtResult SR = SemaRef.ActOnCXXForRangeStmt(
2132 S, ForLoc, CoawaitLoc, LoopVarDecl, ColonLoc, AdjustedRange.get(),
2133 RParenLoc, Sema::BFRK_Check);
2135 return StmtResult();
2138 // The attempt to dereference worked well enough that it could produce a valid
2139 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2140 // case there are any other (non-fatal) problems with it.
2141 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2142 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
2143 return SemaRef.ActOnCXXForRangeStmt(S, ForLoc, CoawaitLoc, LoopVarDecl,
2144 ColonLoc, AdjustedRange.get(), RParenLoc,
2145 Sema::BFRK_Rebuild);
2149 /// RAII object to automatically invalidate a declaration if an error occurs.
2150 struct InvalidateOnErrorScope {
2151 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2152 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2153 ~InvalidateOnErrorScope() {
2154 if (Enabled && Trap.hasErrorOccurred())
2155 D->setInvalidDecl();
2158 DiagnosticErrorTrap Trap;
2164 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
2166 Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc,
2167 SourceLocation ColonLoc, Stmt *RangeDecl,
2168 Stmt *Begin, Stmt *End, Expr *Cond,
2169 Expr *Inc, Stmt *LoopVarDecl,
2170 SourceLocation RParenLoc, BuildForRangeKind Kind) {
2171 // FIXME: This should not be used during template instantiation. We should
2172 // pick up the set of unqualified lookup results for the != and + operators
2173 // in the initial parse.
2175 // Testcase (accepts-invalid):
2176 // template<typename T> void f() { for (auto x : T()) {} }
2177 // namespace N { struct X { X begin(); X end(); int operator*(); }; }
2178 // bool operator!=(N::X, N::X); void operator++(N::X);
2179 // void g() { f<N::X>(); }
2180 Scope *S = getCurScope();
2182 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2183 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2184 QualType RangeVarType = RangeVar->getType();
2186 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2187 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2189 // If we hit any errors, mark the loop variable as invalid if its type
2191 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2192 LoopVar->getType()->isUndeducedType());
2194 StmtResult BeginDeclStmt = Begin;
2195 StmtResult EndDeclStmt = End;
2196 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2198 if (RangeVarType->isDependentType()) {
2199 // The range is implicitly used as a placeholder when it is dependent.
2200 RangeVar->markUsed(Context);
2202 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2203 // them in properly when we instantiate the loop.
2204 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
2205 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
2206 } else if (!BeginDeclStmt.get()) {
2207 SourceLocation RangeLoc = RangeVar->getLocation();
2209 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2211 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2212 VK_LValue, ColonLoc);
2213 if (BeginRangeRef.isInvalid())
2216 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2217 VK_LValue, ColonLoc);
2218 if (EndRangeRef.isInvalid())
2221 QualType AutoType = Context.getAutoDeductType();
2222 Expr *Range = RangeVar->getInit();
2225 QualType RangeType = Range->getType();
2227 if (RequireCompleteType(RangeLoc, RangeType,
2228 diag::err_for_range_incomplete_type))
2231 // Build auto __begin = begin-expr, __end = end-expr.
2232 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2234 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2237 // Build begin-expr and end-expr and attach to __begin and __end variables.
2238 ExprResult BeginExpr, EndExpr;
2239 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2240 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2241 // __range + __bound, respectively, where __bound is the array bound. If
2242 // _RangeT is an array of unknown size or an array of incomplete type,
2243 // the program is ill-formed;
2245 // begin-expr is __range.
2246 BeginExpr = BeginRangeRef;
2247 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
2248 diag::err_for_range_iter_deduction_failure)) {
2249 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2253 // Find the array bound.
2254 ExprResult BoundExpr;
2255 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
2256 BoundExpr = IntegerLiteral::Create(
2257 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
2258 else if (const VariableArrayType *VAT =
2259 dyn_cast<VariableArrayType>(UnqAT))
2260 BoundExpr = VAT->getSizeExpr();
2262 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2263 // UnqAT is not incomplete and Range is not type-dependent.
2264 llvm_unreachable("Unexpected array type in for-range");
2267 // end-expr is __range + __bound.
2268 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
2270 if (EndExpr.isInvalid())
2272 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2273 diag::err_for_range_iter_deduction_failure)) {
2274 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2278 OverloadCandidateSet CandidateSet(RangeLoc,
2279 OverloadCandidateSet::CSK_Normal);
2280 BeginEndFunction BEFFailure;
2281 ForRangeStatus RangeStatus =
2282 BuildNonArrayForRange(*this, BeginRangeRef.get(),
2283 EndRangeRef.get(), RangeType,
2284 BeginVar, EndVar, ColonLoc, &CandidateSet,
2285 &BeginExpr, &EndExpr, &BEFFailure);
2287 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
2288 BEFFailure == BEF_begin) {
2289 // If the range is being built from an array parameter, emit a
2290 // a diagnostic that it is being treated as a pointer.
2291 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2292 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2293 QualType ArrayTy = PVD->getOriginalType();
2294 QualType PointerTy = PVD->getType();
2295 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2296 Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
2297 << RangeLoc << PVD << ArrayTy << PointerTy;
2298 Diag(PVD->getLocation(), diag::note_declared_at);
2304 // If building the range failed, try dereferencing the range expression
2305 // unless a diagnostic was issued or the end function is problematic.
2306 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2308 LoopVarDecl, ColonLoc,
2311 if (SR.isInvalid() || SR.isUsable())
2315 // Otherwise, emit diagnostics if we haven't already.
2316 if (RangeStatus == FRS_NoViableFunction) {
2317 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
2318 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2319 << RangeLoc << Range->getType() << BEFFailure;
2320 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
2322 // Return an error if no fix was discovered.
2323 if (RangeStatus != FRS_Success)
2327 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2328 "invalid range expression in for loop");
2330 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
2331 // C++1z removes this restriction.
2332 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2333 if (!Context.hasSameType(BeginType, EndType)) {
2334 Diag(RangeLoc, getLangOpts().CPlusPlus1z
2335 ? diag::warn_for_range_begin_end_types_differ
2336 : diag::ext_for_range_begin_end_types_differ)
2337 << BeginType << EndType;
2338 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2339 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2343 ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
2345 ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
2347 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2348 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2349 VK_LValue, ColonLoc);
2350 if (BeginRef.isInvalid())
2353 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2354 VK_LValue, ColonLoc);
2355 if (EndRef.isInvalid())
2358 // Build and check __begin != __end expression.
2359 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2360 BeginRef.get(), EndRef.get());
2361 if (!NotEqExpr.isInvalid())
2362 NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get());
2363 if (!NotEqExpr.isInvalid())
2364 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2365 if (NotEqExpr.isInvalid()) {
2366 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2367 << RangeLoc << 0 << BeginRangeRef.get()->getType();
2368 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2369 if (!Context.hasSameType(BeginType, EndType))
2370 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2374 // Build and check ++__begin expression.
2375 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2376 VK_LValue, ColonLoc);
2377 if (BeginRef.isInvalid())
2380 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2381 if (!IncrExpr.isInvalid() && CoawaitLoc.isValid())
2382 IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
2383 if (!IncrExpr.isInvalid())
2384 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2385 if (IncrExpr.isInvalid()) {
2386 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2387 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
2388 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2392 // Build and check *__begin expression.
2393 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2394 VK_LValue, ColonLoc);
2395 if (BeginRef.isInvalid())
2398 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2399 if (DerefExpr.isInvalid()) {
2400 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2401 << RangeLoc << 1 << BeginRangeRef.get()->getType();
2402 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2406 // Attach *__begin as initializer for VD. Don't touch it if we're just
2407 // trying to determine whether this would be a valid range.
2408 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2409 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false);
2410 if (LoopVar->isInvalidDecl())
2411 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2415 // Don't bother to actually allocate the result if we're just trying to
2416 // determine whether it would be valid.
2417 if (Kind == BFRK_Check)
2418 return StmtResult();
2420 return new (Context) CXXForRangeStmt(
2421 RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()),
2422 cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(),
2423 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc,
2424 ColonLoc, RParenLoc);
2427 /// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
2429 StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2432 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
2434 ForStmt->setBody(B);
2438 // Warn when the loop variable is a const reference that creates a copy.
2439 // Suggest using the non-reference type for copies. If a copy can be prevented
2440 // suggest the const reference type that would do so.
2441 // For instance, given "for (const &Foo : Range)", suggest
2442 // "for (const Foo : Range)" to denote a copy is made for the loop. If
2443 // possible, also suggest "for (const &Bar : Range)" if this type prevents
2444 // the copy altogether.
2445 static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef,
2447 QualType RangeInitType) {
2448 const Expr *InitExpr = VD->getInit();
2452 QualType VariableType = VD->getType();
2454 if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr))
2455 if (!Cleanups->cleanupsHaveSideEffects())
2456 InitExpr = Cleanups->getSubExpr();
2458 const MaterializeTemporaryExpr *MTE =
2459 dyn_cast<MaterializeTemporaryExpr>(InitExpr);
2465 const Expr *E = MTE->GetTemporaryExpr()->IgnoreImpCasts();
2467 // Searching for either UnaryOperator for dereference of a pointer or
2468 // CXXOperatorCallExpr for handling iterators.
2469 while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
2470 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) {
2472 } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) {
2473 const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
2476 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
2477 E = MTE->GetTemporaryExpr();
2479 E = E->IgnoreImpCasts();
2482 bool ReturnsReference = false;
2483 if (isa<UnaryOperator>(E)) {
2484 ReturnsReference = true;
2486 const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E);
2487 const FunctionDecl *FD = Call->getDirectCallee();
2488 QualType ReturnType = FD->getReturnType();
2489 ReturnsReference = ReturnType->isReferenceType();
2492 if (ReturnsReference) {
2493 // Loop variable creates a temporary. Suggest either to go with
2494 // non-reference loop variable to indiciate a copy is made, or
2495 // the correct time to bind a const reference.
2496 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_const_reference_copy)
2497 << VD << VariableType << E->getType();
2498 QualType NonReferenceType = VariableType.getNonReferenceType();
2499 NonReferenceType.removeLocalConst();
2500 QualType NewReferenceType =
2501 SemaRef.Context.getLValueReferenceType(E->getType().withConst());
2502 SemaRef.Diag(VD->getLocStart(), diag::note_use_type_or_non_reference)
2503 << NonReferenceType << NewReferenceType << VD->getSourceRange();
2505 // The range always returns a copy, so a temporary is always created.
2506 // Suggest removing the reference from the loop variable.
2507 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_variable_always_copy)
2508 << VD << RangeInitType;
2509 QualType NonReferenceType = VariableType.getNonReferenceType();
2510 NonReferenceType.removeLocalConst();
2511 SemaRef.Diag(VD->getLocStart(), diag::note_use_non_reference_type)
2512 << NonReferenceType << VD->getSourceRange();
2516 // Warns when the loop variable can be changed to a reference type to
2517 // prevent a copy. For instance, if given "for (const Foo x : Range)" suggest
2518 // "for (const Foo &x : Range)" if this form does not make a copy.
2519 static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef,
2520 const VarDecl *VD) {
2521 const Expr *InitExpr = VD->getInit();
2525 QualType VariableType = VD->getType();
2527 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
2528 if (!CE->getConstructor()->isCopyConstructor())
2530 } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
2531 if (CE->getCastKind() != CK_LValueToRValue)
2537 // TODO: Determine a maximum size that a POD type can be before a diagnostic
2538 // should be emitted. Also, only ignore POD types with trivial copy
2540 if (VariableType.isPODType(SemaRef.Context))
2543 // Suggest changing from a const variable to a const reference variable
2544 // if doing so will prevent a copy.
2545 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy)
2546 << VD << VariableType << InitExpr->getType();
2547 SemaRef.Diag(VD->getLocStart(), diag::note_use_reference_type)
2548 << SemaRef.Context.getLValueReferenceType(VariableType)
2549 << VD->getSourceRange();
2552 /// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them.
2553 /// 1) for (const foo &x : foos) where foos only returns a copy. Suggest
2554 /// using "const foo x" to show that a copy is made
2555 /// 2) for (const bar &x : foos) where bar is a temporary intialized by bar.
2556 /// Suggest either "const bar x" to keep the copying or "const foo& x" to
2557 /// prevent the copy.
2558 /// 3) for (const foo x : foos) where x is constructed from a reference foo.
2559 /// Suggest "const foo &x" to prevent the copy.
2560 static void DiagnoseForRangeVariableCopies(Sema &SemaRef,
2561 const CXXForRangeStmt *ForStmt) {
2562 if (SemaRef.Diags.isIgnored(diag::warn_for_range_const_reference_copy,
2563 ForStmt->getLocStart()) &&
2564 SemaRef.Diags.isIgnored(diag::warn_for_range_variable_always_copy,
2565 ForStmt->getLocStart()) &&
2566 SemaRef.Diags.isIgnored(diag::warn_for_range_copy,
2567 ForStmt->getLocStart())) {
2571 const VarDecl *VD = ForStmt->getLoopVariable();
2575 QualType VariableType = VD->getType();
2577 if (VariableType->isIncompleteType())
2580 const Expr *InitExpr = VD->getInit();
2584 if (VariableType->isReferenceType()) {
2585 DiagnoseForRangeReferenceVariableCopies(SemaRef, VD,
2586 ForStmt->getRangeInit()->getType());
2587 } else if (VariableType.isConstQualified()) {
2588 DiagnoseForRangeConstVariableCopies(SemaRef, VD);
2592 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2593 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2594 /// body cannot be performed until after the type of the range variable is
2596 StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2600 if (isa<ObjCForCollectionStmt>(S))
2601 return FinishObjCForCollectionStmt(S, B);
2603 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2604 ForStmt->setBody(B);
2606 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2607 diag::warn_empty_range_based_for_body);
2609 DiagnoseForRangeVariableCopies(*this, ForStmt);
2614 StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2615 SourceLocation LabelLoc,
2616 LabelDecl *TheDecl) {
2617 getCurFunction()->setHasBranchIntoScope();
2618 TheDecl->markUsed(Context);
2619 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
2623 Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
2625 // Convert operand to void*
2626 if (!E->isTypeDependent()) {
2627 QualType ETy = E->getType();
2628 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
2629 ExprResult ExprRes = E;
2630 AssignConvertType ConvTy =
2631 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2632 if (ExprRes.isInvalid())
2635 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
2639 ExprResult ExprRes = ActOnFinishFullExpr(E);
2640 if (ExprRes.isInvalid())
2644 getCurFunction()->setHasIndirectGoto();
2646 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
2649 static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc,
2650 const Scope &DestScope) {
2651 if (!S.CurrentSEHFinally.empty() &&
2652 DestScope.Contains(*S.CurrentSEHFinally.back())) {
2653 S.Diag(Loc, diag::warn_jump_out_of_seh_finally);
2658 Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
2659 Scope *S = CurScope->getContinueParent();
2661 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
2662 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
2664 CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S);
2666 return new (Context) ContinueStmt(ContinueLoc);
2670 Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
2671 Scope *S = CurScope->getBreakParent();
2673 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
2674 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
2676 if (S->isOpenMPLoopScope())
2677 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2679 CheckJumpOutOfSEHFinally(*this, BreakLoc, *S);
2681 return new (Context) BreakStmt(BreakLoc);
2684 /// \brief Determine whether the given expression is a candidate for
2685 /// copy elision in either a return statement or a throw expression.
2687 /// \param ReturnType If we're determining the copy elision candidate for
2688 /// a return statement, this is the return type of the function. If we're
2689 /// determining the copy elision candidate for a throw expression, this will
2692 /// \param E The expression being returned from the function or block, or
2695 /// \param AllowParamOrMoveConstructible Whether we allow function parameters or
2696 /// id-expressions that could be moved out of the function to be considered NRVO
2697 /// candidates. C++ prohibits these for NRVO itself, but we re-use this logic to
2698 /// determine whether we should try to move as part of a return or throw (which
2699 /// does allow function parameters).
2701 /// \returns The NRVO candidate variable, if the return statement may use the
2702 /// NRVO, or NULL if there is no such candidate.
2703 VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, Expr *E,
2704 bool AllowParamOrMoveConstructible) {
2705 if (!getLangOpts().CPlusPlus)
2708 // - in a return statement in a function [where] ...
2709 // ... the expression is the name of a non-volatile automatic object ...
2710 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
2711 if (!DR || DR->refersToEnclosingVariableOrCapture())
2713 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2717 if (isCopyElisionCandidate(ReturnType, VD, AllowParamOrMoveConstructible))
2722 bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
2723 bool AllowParamOrMoveConstructible) {
2724 QualType VDType = VD->getType();
2725 // - in a return statement in a function with ...
2726 // ... a class return type ...
2727 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
2728 if (!ReturnType->isRecordType())
2730 // ... the same cv-unqualified type as the function return type ...
2731 // When considering moving this expression out, allow dissimilar types.
2732 if (!AllowParamOrMoveConstructible && !VDType->isDependentType() &&
2733 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2737 // ...object (other than a function or catch-clause parameter)...
2738 if (VD->getKind() != Decl::Var &&
2739 !(AllowParamOrMoveConstructible && VD->getKind() == Decl::ParmVar))
2741 if (VD->isExceptionVariable()) return false;
2744 if (!VD->hasLocalStorage()) return false;
2746 // Return false if VD is a __block variable. We don't want to implicitly move
2747 // out of a __block variable during a return because we cannot assume the
2748 // variable will no longer be used.
2749 if (VD->hasAttr<BlocksAttr>()) return false;
2751 if (AllowParamOrMoveConstructible)
2754 // ...non-volatile...
2755 if (VD->getType().isVolatileQualified()) return false;
2757 // Variables with higher required alignment than their type's ABI
2758 // alignment cannot use NRVO.
2759 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
2760 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2766 /// \brief Perform the initialization of a potentially-movable value, which
2767 /// is the result of return value.
2769 /// This routine implements C++14 [class.copy]p32, which attempts to treat
2770 /// returned lvalues as rvalues in certain cases (to prefer move construction),
2771 /// then falls back to treating them as lvalues if that failed.
2773 Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2774 const VarDecl *NRVOCandidate,
2775 QualType ResultType,
2778 // C++14 [class.copy]p32:
2779 // When the criteria for elision of a copy/move operation are met, but not for
2780 // an exception-declaration, and the object to be copied is designated by an
2781 // lvalue, or when the expression in a return statement is a (possibly
2782 // parenthesized) id-expression that names an object with automatic storage
2783 // duration declared in the body or parameter-declaration-clause of the
2784 // innermost enclosing function or lambda-expression, overload resolution to
2785 // select the constructor for the copy is first performed as if the object
2786 // were designated by an rvalue.
2787 ExprResult Res = ExprError();
2789 if (AllowNRVO && !NRVOCandidate)
2790 NRVOCandidate = getCopyElisionCandidate(ResultType, Value, true);
2792 if (AllowNRVO && NRVOCandidate) {
2793 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(),
2794 CK_NoOp, Value, VK_XValue);
2796 Expr *InitExpr = &AsRvalue;
2798 InitializationKind Kind = InitializationKind::CreateCopy(
2799 Value->getLocStart(), Value->getLocStart());
2801 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2803 for (const InitializationSequence::Step &Step : Seq.steps()) {
2805 InitializationSequence::SK_ConstructorInitialization ||
2806 (Step.Kind == InitializationSequence::SK_UserConversion &&
2807 isa<CXXConstructorDecl>(Step.Function.Function))))
2810 CXXConstructorDecl *Constructor =
2811 cast<CXXConstructorDecl>(Step.Function.Function);
2813 const RValueReferenceType *RRefType
2814 = Constructor->getParamDecl(0)->getType()
2815 ->getAs<RValueReferenceType>();
2817 // [...] If the first overload resolution fails or was not performed, or
2818 // if the type of the first parameter of the selected constructor is not
2819 // an rvalue reference to the object’s type (possibly cv-qualified),
2820 // overload resolution is performed again, considering the object as an
2823 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2824 NRVOCandidate->getType()))
2827 // Promote "AsRvalue" to the heap, since we now need this
2828 // expression node to persist.
2829 Value = ImplicitCastExpr::Create(Context, Value->getType(), CK_NoOp,
2830 Value, nullptr, VK_XValue);
2832 // Complete type-checking the initialization of the return type
2833 // using the constructor we found.
2834 Res = Seq.Perform(*this, Entity, Kind, Value);
2839 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
2840 // above, or overload resolution failed. Either way, we need to try
2841 // (again) now with the return value expression as written.
2842 if (Res.isInvalid())
2843 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
2848 /// \brief Determine whether the declared return type of the specified function
2849 /// contains 'auto'.
2850 static bool hasDeducedReturnType(FunctionDecl *FD) {
2851 const FunctionProtoType *FPT =
2852 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
2853 return FPT->getReturnType()->isUndeducedType();
2856 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2857 /// for capturing scopes.
2860 Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2861 // If this is the first return we've seen, infer the return type.
2862 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
2863 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
2864 QualType FnRetType = CurCap->ReturnType;
2865 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
2866 bool HasDeducedReturnType =
2867 CurLambda && hasDeducedReturnType(CurLambda->CallOperator);
2869 if (ExprEvalContexts.back().Context == DiscardedStatement &&
2870 (HasDeducedReturnType || CurCap->HasImplicitReturnType)) {
2872 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2875 RetValExp = ER.get();
2877 return new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
2880 if (HasDeducedReturnType) {
2881 // In C++1y, the return type may involve 'auto'.
2882 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
2883 FunctionDecl *FD = CurLambda->CallOperator;
2884 if (CurCap->ReturnType.isNull())
2885 CurCap->ReturnType = FD->getReturnType();
2887 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
2888 assert(AT && "lost auto type from lambda return type");
2889 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2890 FD->setInvalidDecl();
2893 CurCap->ReturnType = FnRetType = FD->getReturnType();
2894 } else if (CurCap->HasImplicitReturnType) {
2895 // For blocks/lambdas with implicit return types, we check each return
2896 // statement individually, and deduce the common return type when the block
2897 // or lambda is completed.
2898 // FIXME: Fold this into the 'auto' codepath above.
2899 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
2900 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2901 if (Result.isInvalid())
2903 RetValExp = Result.get();
2905 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
2906 // when deducing a return type for a lambda-expression (or by extension
2907 // for a block). These rules differ from the stated C++11 rules only in
2908 // that they remove top-level cv-qualifiers.
2909 if (!CurContext->isDependentContext())
2910 FnRetType = RetValExp->getType().getUnqualifiedType();
2912 FnRetType = CurCap->ReturnType = Context.DependentTy;
2915 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2916 // initializer list, because it is not an expression (even
2917 // though we represent it as one). We still deduce 'void'.
2918 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2919 << RetValExp->getSourceRange();
2922 FnRetType = Context.VoidTy;
2925 // Although we'll properly infer the type of the block once it's completed,
2926 // make sure we provide a return type now for better error recovery.
2927 if (CurCap->ReturnType.isNull())
2928 CurCap->ReturnType = FnRetType;
2930 assert(!FnRetType.isNull());
2932 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
2933 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2934 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2937 } else if (CapturedRegionScopeInfo *CurRegion =
2938 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
2939 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
2942 assert(CurLambda && "unknown kind of captured scope");
2943 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
2944 ->getNoReturnAttr()) {
2945 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2950 // Otherwise, verify that this result type matches the previous one. We are
2951 // pickier with blocks than for normal functions because we don't have GCC
2952 // compatibility to worry about here.
2953 const VarDecl *NRVOCandidate = nullptr;
2954 if (FnRetType->isDependentType()) {
2955 // Delay processing for now. TODO: there are lots of dependent
2956 // types we can conclusively prove aren't void.
2957 } else if (FnRetType->isVoidType()) {
2958 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
2959 !(getLangOpts().CPlusPlus &&
2960 (RetValExp->isTypeDependent() ||
2961 RetValExp->getType()->isVoidType()))) {
2962 if (!getLangOpts().CPlusPlus &&
2963 RetValExp->getType()->isVoidType())
2964 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
2966 Diag(ReturnLoc, diag::err_return_block_has_expr);
2967 RetValExp = nullptr;
2970 } else if (!RetValExp) {
2971 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2972 } else if (!RetValExp->isTypeDependent()) {
2973 // we have a non-void block with an expression, continue checking
2975 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2976 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2979 // In C++ the return statement is handled via a copy initialization.
2980 // the C version of which boils down to CheckSingleAssignmentConstraints.
2981 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2982 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2984 NRVOCandidate != nullptr);
2985 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2986 FnRetType, RetValExp);
2987 if (Res.isInvalid()) {
2988 // FIXME: Cleanup temporaries here, anyway?
2991 RetValExp = Res.get();
2992 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
2994 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2998 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3001 RetValExp = ER.get();
3003 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
3006 // If we need to check for the named return value optimization,
3007 // or if we need to infer the return type,
3008 // save the return statement in our scope for later processing.
3009 if (CurCap->HasImplicitReturnType || NRVOCandidate)
3010 FunctionScopes.back()->Returns.push_back(Result);
3012 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3013 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3019 /// \brief Marks all typedefs in all local classes in a type referenced.
3021 /// In a function like
3023 /// struct S { typedef int a; };
3027 /// the local type escapes and could be referenced in some TUs but not in
3028 /// others. Pretend that all local typedefs are always referenced, to not warn
3029 /// on this. This isn't necessary if f has internal linkage, or the typedef
3031 class LocalTypedefNameReferencer
3032 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
3034 LocalTypedefNameReferencer(Sema &S) : S(S) {}
3035 bool VisitRecordType(const RecordType *RT);
3039 bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
3040 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
3041 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
3042 R->isDependentType())
3044 for (auto *TmpD : R->decls())
3045 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
3046 if (T->getAccess() != AS_private || R->hasFriends())
3047 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
3052 TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
3053 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
3054 while (auto ATL = TL.getAs<AttributedTypeLoc>())
3055 TL = ATL.getModifiedLoc().IgnoreParens();
3056 return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc();
3059 /// Deduce the return type for a function from a returned expression, per
3060 /// C++1y [dcl.spec.auto]p6.
3061 bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
3062 SourceLocation ReturnLoc,
3065 TypeLoc OrigResultType = getReturnTypeLoc(FD);
3068 if (RetExpr && isa<InitListExpr>(RetExpr)) {
3069 // If the deduction is for a return statement and the initializer is
3070 // a braced-init-list, the program is ill-formed.
3071 Diag(RetExpr->getExprLoc(),
3072 getCurLambda() ? diag::err_lambda_return_init_list
3073 : diag::err_auto_fn_return_init_list)
3074 << RetExpr->getSourceRange();
3078 if (FD->isDependentContext()) {
3079 // C++1y [dcl.spec.auto]p12:
3080 // Return type deduction [...] occurs when the definition is
3081 // instantiated even if the function body contains a return
3082 // statement with a non-type-dependent operand.
3083 assert(AT->isDeduced() && "should have deduced to dependent type");
3088 // Otherwise, [...] deduce a value for U using the rules of template
3089 // argument deduction.
3090 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
3092 if (DAR == DAR_Failed && !FD->isInvalidDecl())
3093 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
3094 << OrigResultType.getType() << RetExpr->getType();
3096 if (DAR != DAR_Succeeded)
3099 // If a local type is part of the returned type, mark its fields as
3101 LocalTypedefNameReferencer Referencer(*this);
3102 Referencer.TraverseType(RetExpr->getType());
3104 // In the case of a return with no operand, the initializer is considered
3107 // Deduction here can only succeed if the return type is exactly 'cv auto'
3108 // or 'decltype(auto)', so just check for that case directly.
3109 if (!OrigResultType.getType()->getAs<AutoType>()) {
3110 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3111 << OrigResultType.getType();
3114 // We always deduce U = void in this case.
3115 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
3116 if (Deduced.isNull())
3120 // If a function with a declared return type that contains a placeholder type
3121 // has multiple return statements, the return type is deduced for each return
3122 // statement. [...] if the type deduced is not the same in each deduction,
3123 // the program is ill-formed.
3124 QualType DeducedT = AT->getDeducedType();
3125 if (!DeducedT.isNull() && !FD->isInvalidDecl()) {
3126 AutoType *NewAT = Deduced->getContainedAutoType();
3127 // It is possible that NewAT->getDeducedType() is null. When that happens,
3128 // we should not crash, instead we ignore this deduction.
3129 if (NewAT->getDeducedType().isNull())
3132 CanQualType OldDeducedType = Context.getCanonicalFunctionResultType(
3134 CanQualType NewDeducedType = Context.getCanonicalFunctionResultType(
3135 NewAT->getDeducedType());
3136 if (!FD->isDependentContext() && OldDeducedType != NewDeducedType) {
3137 const LambdaScopeInfo *LambdaSI = getCurLambda();
3138 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
3139 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
3140 << NewAT->getDeducedType() << DeducedT
3141 << true /*IsLambda*/;
3143 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3144 << (AT->isDecltypeAuto() ? 1 : 0)
3145 << NewAT->getDeducedType() << DeducedT;
3149 } else if (!FD->isInvalidDecl()) {
3150 // Update all declarations of the function to have the deduced return type.
3151 Context.adjustDeducedFunctionResultType(FD, Deduced);
3158 Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
3160 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
3161 if (R.isInvalid() || ExprEvalContexts.back().Context == DiscardedStatement)
3165 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
3166 CurScope->addNRVOCandidate(VD);
3168 CurScope->setNoNRVO();
3171 CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent());
3176 StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
3177 // Check for unexpanded parameter packs.
3178 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3181 if (isa<CapturingScopeInfo>(getCurFunction()))
3182 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
3185 QualType RelatedRetType;
3186 const AttrVec *Attrs = nullptr;
3187 bool isObjCMethod = false;
3189 if (const FunctionDecl *FD = getCurFunctionDecl()) {
3190 FnRetType = FD->getReturnType();
3192 Attrs = &FD->getAttrs();
3193 if (FD->isNoReturn())
3194 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
3195 << FD->getDeclName();
3196 if (FD->isMain() && RetValExp)
3197 if (isa<CXXBoolLiteralExpr>(RetValExp))
3198 Diag(ReturnLoc, diag::warn_main_returns_bool_literal)
3199 << RetValExp->getSourceRange();
3200 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
3201 FnRetType = MD->getReturnType();
3202 isObjCMethod = true;
3204 Attrs = &MD->getAttrs();
3205 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3206 // In the implementation of a method with a related return type, the
3207 // type used to type-check the validity of return statements within the
3208 // method body is a pointer to the type of the class being implemented.
3209 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
3210 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
3212 } else // If we don't have a function/method context, bail.
3215 // C++1z: discarded return statements are not considered when deducing a
3217 if (ExprEvalContexts.back().Context == DiscardedStatement &&
3218 FnRetType->getContainedAutoType()) {
3220 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3223 RetValExp = ER.get();
3225 return new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
3228 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
3230 if (getLangOpts().CPlusPlus14) {
3231 if (AutoType *AT = FnRetType->getContainedAutoType()) {
3232 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
3233 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3234 FD->setInvalidDecl();
3237 FnRetType = FD->getReturnType();
3242 bool HasDependentReturnType = FnRetType->isDependentType();
3244 ReturnStmt *Result = nullptr;
3245 if (FnRetType->isVoidType()) {
3247 if (isa<InitListExpr>(RetValExp)) {
3248 // We simply never allow init lists as the return value of void
3249 // functions. This is compatible because this was never allowed before,
3250 // so there's no legacy code to deal with.
3251 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3252 int FunctionKind = 0;
3253 if (isa<ObjCMethodDecl>(CurDecl))
3255 else if (isa<CXXConstructorDecl>(CurDecl))
3257 else if (isa<CXXDestructorDecl>(CurDecl))
3260 Diag(ReturnLoc, diag::err_return_init_list)
3261 << CurDecl->getDeclName() << FunctionKind
3262 << RetValExp->getSourceRange();
3264 // Drop the expression.
3265 RetValExp = nullptr;
3266 } else if (!RetValExp->isTypeDependent()) {
3267 // C99 6.8.6.4p1 (ext_ since GCC warns)
3268 unsigned D = diag::ext_return_has_expr;
3269 if (RetValExp->getType()->isVoidType()) {
3270 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3271 if (isa<CXXConstructorDecl>(CurDecl) ||
3272 isa<CXXDestructorDecl>(CurDecl))
3273 D = diag::err_ctor_dtor_returns_void;
3275 D = diag::ext_return_has_void_expr;
3278 ExprResult Result = RetValExp;
3279 Result = IgnoredValueConversions(Result.get());
3280 if (Result.isInvalid())
3282 RetValExp = Result.get();
3283 RetValExp = ImpCastExprToType(RetValExp,
3284 Context.VoidTy, CK_ToVoid).get();
3286 // return of void in constructor/destructor is illegal in C++.
3287 if (D == diag::err_ctor_dtor_returns_void) {
3288 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3290 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3291 << RetValExp->getSourceRange();
3293 // return (some void expression); is legal in C++.
3294 else if (D != diag::ext_return_has_void_expr ||
3295 !getLangOpts().CPlusPlus) {
3296 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3298 int FunctionKind = 0;
3299 if (isa<ObjCMethodDecl>(CurDecl))
3301 else if (isa<CXXConstructorDecl>(CurDecl))
3303 else if (isa<CXXDestructorDecl>(CurDecl))
3307 << CurDecl->getDeclName() << FunctionKind
3308 << RetValExp->getSourceRange();
3313 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3316 RetValExp = ER.get();
3320 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
3321 } else if (!RetValExp && !HasDependentReturnType) {
3322 FunctionDecl *FD = getCurFunctionDecl();
3325 if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3326 // C++11 [stmt.return]p2
3327 DiagID = diag::err_constexpr_return_missing_expr;
3328 FD->setInvalidDecl();
3329 } else if (getLangOpts().C99) {
3330 // C99 6.8.6.4p1 (ext_ since GCC warns)
3331 DiagID = diag::ext_return_missing_expr;
3334 DiagID = diag::warn_return_missing_expr;
3338 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
3340 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
3342 Result = new (Context) ReturnStmt(ReturnLoc);
3344 assert(RetValExp || HasDependentReturnType);
3345 const VarDecl *NRVOCandidate = nullptr;
3347 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3349 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3350 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3353 // In C++ the return statement is handled via a copy initialization,
3354 // the C version of which boils down to CheckSingleAssignmentConstraints.
3356 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
3357 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
3358 // we have a non-void function with an expression, continue checking
3359 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
3361 NRVOCandidate != nullptr);
3362 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
3363 RetType, RetValExp);
3364 if (Res.isInvalid()) {
3365 // FIXME: Clean up temporaries here anyway?
3368 RetValExp = Res.getAs<Expr>();
3370 // If we have a related result type, we need to implicitly
3371 // convert back to the formal result type. We can't pretend to
3372 // initialize the result again --- we might end double-retaining
3373 // --- so instead we initialize a notional temporary.
3374 if (!RelatedRetType.isNull()) {
3375 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3377 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3378 if (Res.isInvalid()) {
3379 // FIXME: Clean up temporaries here anyway?
3382 RetValExp = Res.getAs<Expr>();
3385 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3386 getCurFunctionDecl());
3390 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3393 RetValExp = ER.get();
3395 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
3398 // If we need to check for the named return value optimization, save the
3399 // return statement in our scope for later processing.
3400 if (Result->getNRVOCandidate())
3401 FunctionScopes.back()->Returns.push_back(Result);
3403 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3404 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3410 Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
3411 SourceLocation RParen, Decl *Parm,
3413 VarDecl *Var = cast_or_null<VarDecl>(Parm);
3414 if (Var && Var->isInvalidDecl())
3417 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
3421 Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
3422 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
3426 Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3427 MultiStmtArg CatchStmts, Stmt *Finally) {
3428 if (!getLangOpts().ObjCExceptions)
3429 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3431 getCurFunction()->setHasBranchProtectedScope();
3432 unsigned NumCatchStmts = CatchStmts.size();
3433 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3434 NumCatchStmts, Finally);
3437 StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
3439 ExprResult Result = DefaultLvalueConversion(Throw);
3440 if (Result.isInvalid())
3443 Result = ActOnFinishFullExpr(Result.get());
3444 if (Result.isInvalid())
3446 Throw = Result.get();
3448 QualType ThrowType = Throw->getType();
3449 // Make sure the expression type is an ObjC pointer or "void *".
3450 if (!ThrowType->isDependentType() &&
3451 !ThrowType->isObjCObjectPointerType()) {
3452 const PointerType *PT = ThrowType->getAs<PointerType>();
3453 if (!PT || !PT->getPointeeType()->isVoidType())
3454 return StmtError(Diag(AtLoc, diag::err_objc_throw_expects_object)
3455 << Throw->getType() << Throw->getSourceRange());
3459 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
3463 Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3465 if (!getLangOpts().ObjCExceptions)
3466 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3469 // @throw without an expression designates a rethrow (which must occur
3470 // in the context of an @catch clause).
3471 Scope *AtCatchParent = CurScope;
3472 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3473 AtCatchParent = AtCatchParent->getParent();
3475 return StmtError(Diag(AtLoc, diag::err_rethrow_used_outside_catch));
3477 return BuildObjCAtThrowStmt(AtLoc, Throw);
3481 Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3482 ExprResult result = DefaultLvalueConversion(operand);
3483 if (result.isInvalid())
3485 operand = result.get();
3487 // Make sure the expression type is an ObjC pointer or "void *".
3488 QualType type = operand->getType();
3489 if (!type->isDependentType() &&
3490 !type->isObjCObjectPointerType()) {
3491 const PointerType *pointerType = type->getAs<PointerType>();
3492 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3493 if (getLangOpts().CPlusPlus) {
3494 if (RequireCompleteType(atLoc, type,
3495 diag::err_incomplete_receiver_type))
3496 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
3497 << type << operand->getSourceRange();
3499 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
3500 if (result.isInvalid())
3502 if (!result.isUsable())
3503 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
3504 << type << operand->getSourceRange();
3506 operand = result.get();
3508 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
3509 << type << operand->getSourceRange();
3514 // The operand to @synchronized is a full-expression.
3515 return ActOnFinishFullExpr(operand);
3519 Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3521 // We can't jump into or indirect-jump out of a @synchronized block.
3522 getCurFunction()->setHasBranchProtectedScope();
3523 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
3526 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3527 /// and creates a proper catch handler from them.
3529 Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
3530 Stmt *HandlerBlock) {
3531 // There's nothing to test that ActOnExceptionDecl didn't already test.
3532 return new (Context)
3533 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
3537 Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3538 getCurFunction()->setHasBranchProtectedScope();
3539 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
3543 class CatchHandlerType {
3545 unsigned IsPointer : 1;
3547 // This is a special constructor to be used only with DenseMapInfo's
3548 // getEmptyKey() and getTombstoneKey() functions.
3549 friend struct llvm::DenseMapInfo<CatchHandlerType>;
3550 enum Unique { ForDenseMap };
3551 CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {}
3554 /// Used when creating a CatchHandlerType from a handler type; will determine
3555 /// whether the type is a pointer or reference and will strip off the top
3556 /// level pointer and cv-qualifiers.
3557 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) {
3558 if (QT->isPointerType())
3561 if (IsPointer || QT->isReferenceType())
3562 QT = QT->getPointeeType();
3563 QT = QT.getUnqualifiedType();
3566 /// Used when creating a CatchHandlerType from a base class type; pretends the
3567 /// type passed in had the pointer qualifier, does not need to get an
3568 /// unqualified type.
3569 CatchHandlerType(QualType QT, bool IsPointer)
3570 : QT(QT), IsPointer(IsPointer) {}
3572 QualType underlying() const { return QT; }
3573 bool isPointer() const { return IsPointer; }
3575 friend bool operator==(const CatchHandlerType &LHS,
3576 const CatchHandlerType &RHS) {
3577 // If the pointer qualification does not match, we can return early.
3578 if (LHS.IsPointer != RHS.IsPointer)
3580 // Otherwise, check the underlying type without cv-qualifiers.
3581 return LHS.QT == RHS.QT;
3587 template <> struct DenseMapInfo<CatchHandlerType> {
3588 static CatchHandlerType getEmptyKey() {
3589 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
3590 CatchHandlerType::ForDenseMap);
3593 static CatchHandlerType getTombstoneKey() {
3594 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
3595 CatchHandlerType::ForDenseMap);
3598 static unsigned getHashValue(const CatchHandlerType &Base) {
3599 return DenseMapInfo<QualType>::getHashValue(Base.underlying());
3602 static bool isEqual(const CatchHandlerType &LHS,
3603 const CatchHandlerType &RHS) {
3610 class CatchTypePublicBases {
3612 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
3613 const bool CheckAgainstPointer;
3615 CXXCatchStmt *FoundHandler;
3616 CanQualType FoundHandlerType;
3619 CatchTypePublicBases(
3621 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T, bool C)
3622 : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(C),
3623 FoundHandler(nullptr) {}
3625 CXXCatchStmt *getFoundHandler() const { return FoundHandler; }
3626 CanQualType getFoundHandlerType() const { return FoundHandlerType; }
3628 bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) {
3629 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) {
3630 CatchHandlerType Check(S->getType(), CheckAgainstPointer);
3631 const auto &M = TypesToCheck;
3632 auto I = M.find(Check);
3634 FoundHandler = I->second;
3635 FoundHandlerType = Ctx.getCanonicalType(S->getType());
3644 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3645 /// handlers and creates a try statement from them.
3646 StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3647 ArrayRef<Stmt *> Handlers) {
3648 // Don't report an error if 'try' is used in system headers.
3649 if (!getLangOpts().CXXExceptions &&
3650 !getSourceManager().isInSystemHeader(TryLoc))
3651 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
3653 // Exceptions aren't allowed in CUDA device code.
3654 if (getLangOpts().CUDA)
3655 CUDADiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions)
3656 << "try" << CurrentCUDATarget();
3658 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
3659 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
3661 sema::FunctionScopeInfo *FSI = getCurFunction();
3663 // C++ try is incompatible with SEH __try.
3664 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) {
3665 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
3666 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'";
3669 const unsigned NumHandlers = Handlers.size();
3670 assert(!Handlers.empty() &&
3671 "The parser shouldn't call this if there are no handlers.");
3673 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
3674 for (unsigned i = 0; i < NumHandlers; ++i) {
3675 CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]);
3677 // Diagnose when the handler is a catch-all handler, but it isn't the last
3678 // handler for the try block. [except.handle]p5. Also, skip exception
3679 // declarations that are invalid, since we can't usefully report on them.
3680 if (!H->getExceptionDecl()) {
3681 if (i < NumHandlers - 1)
3682 return StmtError(Diag(H->getLocStart(), diag::err_early_catch_all));
3684 } else if (H->getExceptionDecl()->isInvalidDecl())
3687 // Walk the type hierarchy to diagnose when this type has already been
3688 // handled (duplication), or cannot be handled (derivation inversion). We
3689 // ignore top-level cv-qualifiers, per [except.handle]p3
3690 CatchHandlerType HandlerCHT =
3691 (QualType)Context.getCanonicalType(H->getCaughtType());
3693 // We can ignore whether the type is a reference or a pointer; we need the
3694 // underlying declaration type in order to get at the underlying record
3695 // decl, if there is one.
3696 QualType Underlying = HandlerCHT.underlying();
3697 if (auto *RD = Underlying->getAsCXXRecordDecl()) {
3698 if (!RD->hasDefinition())
3700 // Check that none of the public, unambiguous base classes are in the
3701 // map ([except.handle]p1). Give the base classes the same pointer
3702 // qualification as the original type we are basing off of. This allows
3703 // comparison against the handler type using the same top-level pointer
3704 // as the original type.
3706 Paths.setOrigin(RD);
3707 CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
3708 if (RD->lookupInBases(CTPB, Paths)) {
3709 const CXXCatchStmt *Problem = CTPB.getFoundHandler();
3710 if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
3711 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3712 diag::warn_exception_caught_by_earlier_handler)
3713 << H->getCaughtType();
3714 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3715 diag::note_previous_exception_handler)
3716 << Problem->getCaughtType();
3721 // Add the type the list of ones we have handled; diagnose if we've already
3723 auto R = HandledTypes.insert(std::make_pair(H->getCaughtType(), H));
3725 const CXXCatchStmt *Problem = R.first->second;
3726 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(),
3727 diag::warn_exception_caught_by_earlier_handler)
3728 << H->getCaughtType();
3729 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(),
3730 diag::note_previous_exception_handler)
3731 << Problem->getCaughtType();
3735 FSI->setHasCXXTry(TryLoc);
3737 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
3740 StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc,
3741 Stmt *TryBlock, Stmt *Handler) {
3742 assert(TryBlock && Handler);
3744 sema::FunctionScopeInfo *FSI = getCurFunction();
3746 // SEH __try is incompatible with C++ try. Borland appears to support this,
3748 if (!getLangOpts().Borland) {
3749 if (FSI->FirstCXXTryLoc.isValid()) {
3750 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try);
3751 Diag(FSI->FirstCXXTryLoc, diag::note_conflicting_try_here) << "'try'";
3755 FSI->setHasSEHTry(TryLoc);
3757 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't
3758 // track if they use SEH.
3759 DeclContext *DC = CurContext;
3760 while (DC && !DC->isFunctionOrMethod())
3761 DC = DC->getParent();
3762 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC);
3764 FD->setUsesSEHTry(true);
3766 Diag(TryLoc, diag::err_seh_try_outside_functions);
3768 // Reject __try on unsupported targets.
3769 if (!Context.getTargetInfo().isSEHTrySupported())
3770 Diag(TryLoc, diag::err_seh_try_unsupported);
3772 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler);
3776 Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3779 assert(FilterExpr && Block);
3781 if(!FilterExpr->getType()->isIntegerType()) {
3782 return StmtError(Diag(FilterExpr->getExprLoc(),
3783 diag::err_filter_expression_integral)
3784 << FilterExpr->getType());
3787 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
3790 void Sema::ActOnStartSEHFinallyBlock() {
3791 CurrentSEHFinally.push_back(CurScope);
3794 void Sema::ActOnAbortSEHFinallyBlock() {
3795 CurrentSEHFinally.pop_back();
3798 StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) {
3800 CurrentSEHFinally.pop_back();
3801 return SEHFinallyStmt::Create(Context, Loc, Block);
3805 Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
3806 Scope *SEHTryParent = CurScope;
3807 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
3808 SEHTryParent = SEHTryParent->getParent();
3810 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
3811 CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent);
3813 return new (Context) SEHLeaveStmt(Loc);
3816 StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3818 NestedNameSpecifierLoc QualifierLoc,
3819 DeclarationNameInfo NameInfo,
3822 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
3823 QualifierLoc, NameInfo,
3824 cast<CompoundStmt>(Nested));
3828 StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
3831 UnqualifiedId &Name,
3833 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
3834 SS.getWithLocInContext(Context),
3835 GetNameFromUnqualifiedId(Name),
3840 Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
3841 unsigned NumParams) {
3842 DeclContext *DC = CurContext;
3843 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
3844 DC = DC->getParent();
3846 RecordDecl *RD = nullptr;
3847 if (getLangOpts().CPlusPlus)
3848 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
3851 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
3853 RD->setCapturedRecord();
3856 RD->startDefinition();
3858 assert(NumParams > 0 && "CapturedStmt requires context parameter");
3859 CD = CapturedDecl::Create(Context, CurContext, NumParams);
3864 static void buildCapturedStmtCaptureList(
3865 SmallVectorImpl<CapturedStmt::Capture> &Captures,
3866 SmallVectorImpl<Expr *> &CaptureInits,
3867 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
3869 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
3870 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
3872 if (Cap->isThisCapture()) {
3873 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3874 CapturedStmt::VCK_This));
3875 CaptureInits.push_back(Cap->getInitExpr());
3877 } else if (Cap->isVLATypeCapture()) {
3879 CapturedStmt::Capture(Cap->getLocation(), CapturedStmt::VCK_VLAType));
3880 CaptureInits.push_back(nullptr);
3884 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3885 Cap->isReferenceCapture()
3886 ? CapturedStmt::VCK_ByRef
3887 : CapturedStmt::VCK_ByCopy,
3888 Cap->getVariable()));
3889 CaptureInits.push_back(Cap->getInitExpr());
3893 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3894 CapturedRegionKind Kind,
3895 unsigned NumParams) {
3896 CapturedDecl *CD = nullptr;
3897 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
3899 // Build the context parameter
3900 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3901 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3902 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3903 ImplicitParamDecl *Param
3904 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3907 CD->setContextParam(0, Param);
3909 // Enter the capturing scope for this captured region.
3910 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3913 PushDeclContext(CurScope, CD);
3917 PushExpressionEvaluationContext(PotentiallyEvaluated);
3920 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3921 CapturedRegionKind Kind,
3922 ArrayRef<CapturedParamNameType> Params) {
3923 CapturedDecl *CD = nullptr;
3924 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
3926 // Build the context parameter
3927 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3928 bool ContextIsFound = false;
3929 unsigned ParamNum = 0;
3930 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
3932 I != E; ++I, ++ParamNum) {
3933 if (I->second.isNull()) {
3934 assert(!ContextIsFound &&
3935 "null type has been found already for '__context' parameter");
3936 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3937 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3938 ImplicitParamDecl *Param
3939 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3941 CD->setContextParam(ParamNum, Param);
3942 ContextIsFound = true;
3944 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
3945 ImplicitParamDecl *Param
3946 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second);
3948 CD->setParam(ParamNum, Param);
3951 assert(ContextIsFound && "no null type for '__context' parameter");
3952 if (!ContextIsFound) {
3953 // Add __context implicitly if it is not specified.
3954 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3955 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3956 ImplicitParamDecl *Param =
3957 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3959 CD->setContextParam(ParamNum, Param);
3961 // Enter the capturing scope for this captured region.
3962 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3965 PushDeclContext(CurScope, CD);
3969 PushExpressionEvaluationContext(PotentiallyEvaluated);
3972 void Sema::ActOnCapturedRegionError() {
3973 DiscardCleanupsInEvaluationContext();
3974 PopExpressionEvaluationContext();
3976 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3977 RecordDecl *Record = RSI->TheRecordDecl;
3978 Record->setInvalidDecl();
3980 SmallVector<Decl*, 4> Fields(Record->fields());
3981 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
3982 SourceLocation(), SourceLocation(), /*AttributeList=*/nullptr);
3985 PopFunctionScopeInfo();
3988 StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
3989 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3991 SmallVector<CapturedStmt::Capture, 4> Captures;
3992 SmallVector<Expr *, 4> CaptureInits;
3993 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
3995 CapturedDecl *CD = RSI->TheCapturedDecl;
3996 RecordDecl *RD = RSI->TheRecordDecl;
3998 CapturedStmt *Res = CapturedStmt::Create(
3999 getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind),
4000 Captures, CaptureInits, CD, RD);
4002 CD->setBody(Res->getCapturedStmt());
4003 RD->completeDefinition();
4005 DiscardCleanupsInEvaluationContext();
4006 PopExpressionEvaluationContext();
4009 PopFunctionScopeInfo();