1 //===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for statements.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTDiagnostic.h"
17 #include "clang/AST/CharUnits.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/EvaluatedExprVisitor.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/RecursiveASTVisitor.h"
23 #include "clang/AST/StmtCXX.h"
24 #include "clang/AST/StmtObjC.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/Lex/Preprocessor.h"
27 #include "clang/Sema/Initialization.h"
28 #include "clang/Sema/Lookup.h"
29 #include "clang/Sema/Scope.h"
30 #include "clang/Sema/ScopeInfo.h"
31 #include "llvm/ADT/ArrayRef.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallString.h"
35 #include "llvm/ADT/SmallVector.h"
36 using namespace clang;
39 StmtResult Sema::ActOnExprStmt(ExprResult FE) {
43 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
44 /*DiscardedValue*/ true);
48 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
49 // void expression for its side effects. Conversion to void allows any
50 // operand, even incomplete types.
52 // Same thing in for stmt first clause (when expr) and third clause.
53 return StmtResult(FE.getAs<Stmt>());
57 StmtResult Sema::ActOnExprStmtError() {
58 DiscardCleanupsInEvaluationContext();
62 StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
63 bool HasLeadingEmptyMacro) {
64 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
67 StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
68 SourceLocation EndLoc) {
69 DeclGroupRef DG = dg.get();
71 // If we have an invalid decl, just return an error.
72 if (DG.isNull()) return StmtError();
74 return new (Context) DeclStmt(DG, StartLoc, EndLoc);
77 void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
78 DeclGroupRef DG = dg.get();
80 // If we don't have a declaration, or we have an invalid declaration,
82 if (DG.isNull() || !DG.isSingleDecl())
85 Decl *decl = DG.getSingleDecl();
86 if (!decl || decl->isInvalidDecl())
89 // Only variable declarations are permitted.
90 VarDecl *var = dyn_cast<VarDecl>(decl);
92 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
93 decl->setInvalidDecl();
97 // foreach variables are never actually initialized in the way that
98 // the parser came up with.
99 var->setInit(nullptr);
101 // In ARC, we don't need to retain the iteration variable of a fast
102 // enumeration loop. Rather than actually trying to catch that
103 // during declaration processing, we remove the consequences here.
104 if (getLangOpts().ObjCAutoRefCount) {
105 QualType type = var->getType();
107 // Only do this if we inferred the lifetime. Inferred lifetime
108 // will show up as a local qualifier because explicit lifetime
109 // should have shown up as an AttributedType instead.
110 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
111 // Add 'const' and mark the variable as pseudo-strong.
112 var->setType(type.withConst());
113 var->setARCPseudoStrong(true);
118 /// \brief Diagnose unused comparisons, both builtin and overloaded operators.
119 /// For '==' and '!=', suggest fixits for '=' or '|='.
121 /// Adding a cast to void (or other expression wrappers) will prevent the
122 /// warning from firing.
123 static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
125 bool IsNotEqual, CanAssign, IsRelational;
127 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
128 if (!Op->isComparisonOp())
131 IsRelational = Op->isRelationalOp();
132 Loc = Op->getOperatorLoc();
133 IsNotEqual = Op->getOpcode() == BO_NE;
134 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
135 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
136 switch (Op->getOperator()) {
140 case OO_ExclaimEqual:
141 IsRelational = false;
145 case OO_GreaterEqual:
151 Loc = Op->getOperatorLoc();
152 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
153 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
155 // Not a typo-prone comparison.
159 // Suppress warnings when the operator, suspicious as it may be, comes from
160 // a macro expansion.
161 if (S.SourceMgr.isMacroBodyExpansion(Loc))
164 S.Diag(Loc, diag::warn_unused_comparison)
165 << (unsigned)IsRelational << (unsigned)IsNotEqual << E->getSourceRange();
167 // If the LHS is a plausible entity to assign to, provide a fixit hint to
168 // correct common typos.
169 if (!IsRelational && CanAssign) {
171 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
172 << FixItHint::CreateReplacement(Loc, "|=");
174 S.Diag(Loc, diag::note_equality_comparison_to_assign)
175 << FixItHint::CreateReplacement(Loc, "=");
181 void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
182 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
183 return DiagnoseUnusedExprResult(Label->getSubStmt());
185 const Expr *E = dyn_cast_or_null<Expr>(S);
189 // If we are in an unevaluated expression context, then there can be no unused
190 // results because the results aren't expected to be used in the first place.
191 if (isUnevaluatedContext())
194 SourceLocation ExprLoc = E->IgnoreParens()->getExprLoc();
195 // In most cases, we don't want to warn if the expression is written in a
196 // macro body, or if the macro comes from a system header. If the offending
197 // expression is a call to a function with the warn_unused_result attribute,
198 // we warn no matter the location. Because of the order in which the various
199 // checks need to happen, we factor out the macro-related test here.
200 bool ShouldSuppress =
201 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
202 SourceMgr.isInSystemMacro(ExprLoc);
204 const Expr *WarnExpr;
207 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
210 // If this is a GNU statement expression expanded from a macro, it is probably
211 // unused because it is a function-like macro that can be used as either an
212 // expression or statement. Don't warn, because it is almost certainly a
214 if (isa<StmtExpr>(E) && Loc.isMacroID())
217 // Okay, we have an unused result. Depending on what the base expression is,
218 // we might want to make a more specific diagnostic. Check for one of these
220 unsigned DiagID = diag::warn_unused_expr;
221 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
222 E = Temps->getSubExpr();
223 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
224 E = TempExpr->getSubExpr();
226 if (DiagnoseUnusedComparison(*this, E))
230 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
231 if (E->getType()->isVoidType())
234 // If the callee has attribute pure, const, or warn_unused_result, warn with
235 // a more specific message to make it clear what is happening. If the call
236 // is written in a macro body, only warn if it has the warn_unused_result
238 if (const Decl *FD = CE->getCalleeDecl()) {
239 if (FD->hasAttr<WarnUnusedResultAttr>()) {
240 Diag(Loc, diag::warn_unused_result) << R1 << R2;
245 if (FD->hasAttr<PureAttr>()) {
246 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
249 if (FD->hasAttr<ConstAttr>()) {
250 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
254 } else if (ShouldSuppress)
257 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
258 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
259 Diag(Loc, diag::err_arc_unused_init_message) << R1;
262 const ObjCMethodDecl *MD = ME->getMethodDecl();
264 if (MD->hasAttr<WarnUnusedResultAttr>()) {
265 Diag(Loc, diag::warn_unused_result) << R1 << R2;
268 if (MD->isPropertyAccessor()) {
269 Diag(Loc, diag::warn_unused_property_expr);
273 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
274 const Expr *Source = POE->getSyntacticForm();
275 if (isa<ObjCSubscriptRefExpr>(Source))
276 DiagID = diag::warn_unused_container_subscript_expr;
278 DiagID = diag::warn_unused_property_expr;
279 } else if (const CXXFunctionalCastExpr *FC
280 = dyn_cast<CXXFunctionalCastExpr>(E)) {
281 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
282 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
285 // Diagnose "(void*) blah" as a typo for "(void) blah".
286 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
287 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
288 QualType T = TI->getType();
290 // We really do want to use the non-canonical type here.
291 if (T == Context.VoidPtrTy) {
292 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
294 Diag(Loc, diag::warn_unused_voidptr)
295 << FixItHint::CreateRemoval(TL.getStarLoc());
300 if (E->isGLValue() && E->getType().isVolatileQualified()) {
301 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
305 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
308 void Sema::ActOnStartOfCompoundStmt() {
312 void Sema::ActOnFinishOfCompoundStmt() {
316 sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
317 return getCurFunction()->CompoundScopes.back();
320 StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
321 ArrayRef<Stmt *> Elts, bool isStmtExpr) {
322 const unsigned NumElts = Elts.size();
324 // If we're in C89 mode, check that we don't have any decls after stmts. If
325 // so, emit an extension diagnostic.
326 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
327 // Note that __extension__ can be around a decl.
329 // Skip over all declarations.
330 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
333 // We found the end of the list or a statement. Scan for another declstmt.
334 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
338 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
339 Diag(D->getLocation(), diag::ext_mixed_decls_code);
342 // Warn about unused expressions in statements.
343 for (unsigned i = 0; i != NumElts; ++i) {
344 // Ignore statements that are last in a statement expression.
345 if (isStmtExpr && i == NumElts - 1)
348 DiagnoseUnusedExprResult(Elts[i]);
351 // Check for suspicious empty body (null statement) in `for' and `while'
352 // statements. Don't do anything for template instantiations, this just adds
354 if (NumElts != 0 && !CurrentInstantiationScope &&
355 getCurCompoundScope().HasEmptyLoopBodies) {
356 for (unsigned i = 0; i != NumElts - 1; ++i)
357 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
360 return new (Context) CompoundStmt(Context, Elts, L, R);
364 Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
365 SourceLocation DotDotDotLoc, Expr *RHSVal,
366 SourceLocation ColonLoc) {
367 assert(LHSVal && "missing expression in case statement");
369 if (getCurFunction()->SwitchStack.empty()) {
370 Diag(CaseLoc, diag::err_case_not_in_switch);
375 CorrectDelayedTyposInExpr(LHSVal, [this](class Expr *E) {
376 if (!getLangOpts().CPlusPlus11)
377 return VerifyIntegerConstantExpression(E);
379 getCurFunction()->SwitchStack.back()->getCond()) {
380 QualType CondType = CondExpr->getType();
381 llvm::APSInt TempVal;
382 return CheckConvertedConstantExpression(E, CondType, TempVal,
391 if (!getLangOpts().CPlusPlus11) {
392 // C99 6.8.4.2p3: The expression shall be an integer constant.
393 // However, GCC allows any evaluatable integer expression.
394 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
395 LHSVal = VerifyIntegerConstantExpression(LHSVal).get();
400 // GCC extension: The expression shall be an integer constant.
402 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
403 RHSVal = VerifyIntegerConstantExpression(RHSVal).get();
404 // Recover from an error by just forgetting about it.
408 LHS = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
409 getLangOpts().CPlusPlus11);
413 auto RHS = RHSVal ? ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
414 getLangOpts().CPlusPlus11)
419 CaseStmt *CS = new (Context)
420 CaseStmt(LHS.get(), RHS.get(), CaseLoc, DotDotDotLoc, ColonLoc);
421 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
425 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
426 void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
427 DiagnoseUnusedExprResult(SubStmt);
429 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
430 CS->setSubStmt(SubStmt);
434 Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
435 Stmt *SubStmt, Scope *CurScope) {
436 DiagnoseUnusedExprResult(SubStmt);
438 if (getCurFunction()->SwitchStack.empty()) {
439 Diag(DefaultLoc, diag::err_default_not_in_switch);
443 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
444 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
449 Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
450 SourceLocation ColonLoc, Stmt *SubStmt) {
451 // If the label was multiply defined, reject it now.
452 if (TheDecl->getStmt()) {
453 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
454 Diag(TheDecl->getLocation(), diag::note_previous_definition);
458 // Otherwise, things are good. Fill in the declaration and return it.
459 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
460 TheDecl->setStmt(LS);
461 if (!TheDecl->isGnuLocal()) {
462 TheDecl->setLocStart(IdentLoc);
463 if (!TheDecl->isMSAsmLabel()) {
464 // Don't update the location of MS ASM labels. These will result in
465 // a diagnostic, and changing the location here will mess that up.
466 TheDecl->setLocation(IdentLoc);
472 StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
473 ArrayRef<const Attr*> Attrs,
475 // Fill in the declaration and return it.
476 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
481 Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
482 Stmt *thenStmt, SourceLocation ElseLoc,
484 // If the condition was invalid, discard the if statement. We could recover
485 // better by replacing it with a valid expr, but don't do that yet.
486 if (!CondVal.get() && !CondVar) {
487 getCurFunction()->setHasDroppedStmt();
491 ExprResult CondResult(CondVal.release());
493 VarDecl *ConditionVar = nullptr;
495 ConditionVar = cast<VarDecl>(CondVar);
496 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
497 if (CondResult.isInvalid())
500 Expr *ConditionExpr = CondResult.getAs<Expr>();
504 DiagnoseUnusedExprResult(thenStmt);
507 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
508 diag::warn_empty_if_body);
511 DiagnoseUnusedExprResult(elseStmt);
513 return new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
514 thenStmt, ElseLoc, elseStmt);
518 struct CaseCompareFunctor {
519 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
520 const llvm::APSInt &RHS) {
521 return LHS.first < RHS;
523 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
524 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
525 return LHS.first < RHS.first;
527 bool operator()(const llvm::APSInt &LHS,
528 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
529 return LHS < RHS.first;
534 /// CmpCaseVals - Comparison predicate for sorting case values.
536 static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
537 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
538 if (lhs.first < rhs.first)
541 if (lhs.first == rhs.first &&
542 lhs.second->getCaseLoc().getRawEncoding()
543 < rhs.second->getCaseLoc().getRawEncoding())
548 /// CmpEnumVals - Comparison predicate for sorting enumeration values.
550 static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
551 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
553 return lhs.first < rhs.first;
556 /// EqEnumVals - Comparison preficate for uniqing enumeration values.
558 static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
559 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
561 return lhs.first == rhs.first;
564 /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
565 /// potentially integral-promoted expression @p expr.
566 static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
567 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
568 expr = cleanups->getSubExpr();
569 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
570 if (impcast->getCastKind() != CK_IntegralCast) break;
571 expr = impcast->getSubExpr();
573 return expr->getType();
577 Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
579 ExprResult CondResult;
581 VarDecl *ConditionVar = nullptr;
583 ConditionVar = cast<VarDecl>(CondVar);
584 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
585 if (CondResult.isInvalid())
588 Cond = CondResult.get();
594 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
598 SwitchConvertDiagnoser(Expr *Cond)
599 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
602 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
603 QualType T) override {
604 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
607 SemaDiagnosticBuilder diagnoseIncomplete(
608 Sema &S, SourceLocation Loc, QualType T) override {
609 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
610 << T << Cond->getSourceRange();
613 SemaDiagnosticBuilder diagnoseExplicitConv(
614 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
615 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
618 SemaDiagnosticBuilder noteExplicitConv(
619 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
620 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
621 << ConvTy->isEnumeralType() << ConvTy;
624 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
625 QualType T) override {
626 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
629 SemaDiagnosticBuilder noteAmbiguous(
630 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
631 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
632 << ConvTy->isEnumeralType() << ConvTy;
635 SemaDiagnosticBuilder diagnoseConversion(
636 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
637 llvm_unreachable("conversion functions are permitted");
639 } SwitchDiagnoser(Cond);
642 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
643 if (CondResult.isInvalid()) return StmtError();
644 Cond = CondResult.get();
646 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
647 CondResult = UsualUnaryConversions(Cond);
648 if (CondResult.isInvalid()) return StmtError();
649 Cond = CondResult.get();
652 CondResult = ActOnFinishFullExpr(Cond, SwitchLoc);
653 if (CondResult.isInvalid())
655 Cond = CondResult.get();
658 getCurFunction()->setHasBranchIntoScope();
660 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
661 getCurFunction()->SwitchStack.push_back(SS);
665 static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
666 Val = Val.extOrTrunc(BitWidth);
667 Val.setIsSigned(IsSigned);
670 /// Check the specified case value is in range for the given unpromoted switch
672 static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val,
673 unsigned UnpromotedWidth, bool UnpromotedSign) {
674 // If the case value was signed and negative and the switch expression is
675 // unsigned, don't bother to warn: this is implementation-defined behavior.
676 // FIXME: Introduce a second, default-ignored warning for this case?
677 if (UnpromotedWidth < Val.getBitWidth()) {
678 llvm::APSInt ConvVal(Val);
679 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
680 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
681 // FIXME: Use different diagnostics for overflow in conversion to promoted
682 // type versus "switch expression cannot have this value". Use proper
683 // IntRange checking rather than just looking at the unpromoted type here.
685 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10)
686 << ConvVal.toString(10);
690 /// Returns true if we should emit a diagnostic about this case expression not
691 /// being a part of the enum used in the switch controlling expression.
692 static bool ShouldDiagnoseSwitchCaseNotInEnum(const ASTContext &Ctx,
694 const Expr *CaseExpr) {
695 // Don't warn if the 'case' expression refers to a static const variable of
697 CaseExpr = CaseExpr->IgnoreParenImpCasts();
698 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseExpr)) {
699 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
700 if (!VD->hasGlobalStorage())
702 QualType VarType = VD->getType();
703 if (!VarType.isConstQualified())
705 QualType EnumType = Ctx.getTypeDeclType(ED);
706 if (Ctx.hasSameUnqualifiedType(EnumType, VarType))
714 Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
716 SwitchStmt *SS = cast<SwitchStmt>(Switch);
717 assert(SS == getCurFunction()->SwitchStack.back() &&
718 "switch stack missing push/pop!");
720 getCurFunction()->SwitchStack.pop_back();
722 if (!BodyStmt) return StmtError();
723 SS->setBody(BodyStmt, SwitchLoc);
725 Expr *CondExpr = SS->getCond();
726 if (!CondExpr) return StmtError();
728 QualType CondType = CondExpr->getType();
730 Expr *CondExprBeforePromotion = CondExpr;
731 QualType CondTypeBeforePromotion =
732 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
735 // Integral promotions are performed (on the switch condition).
737 // A case value unrepresentable by the original switch condition
738 // type (before the promotion) doesn't make sense, even when it can
739 // be represented by the promoted type. Therefore we need to find
740 // the pre-promotion type of the switch condition.
741 if (!CondExpr->isTypeDependent()) {
742 // We have already converted the expression to an integral or enumeration
743 // type, when we started the switch statement. If we don't have an
744 // appropriate type now, just return an error.
745 if (!CondType->isIntegralOrEnumerationType())
748 if (CondExpr->isKnownToHaveBooleanValue()) {
749 // switch(bool_expr) {...} is often a programmer error, e.g.
750 // switch(n && mask) { ... } // Doh - should be "n & mask".
751 // One can always use an if statement instead of switch(bool_expr).
752 Diag(SwitchLoc, diag::warn_bool_switch_condition)
753 << CondExpr->getSourceRange();
757 // Get the bitwidth of the switched-on value after promotions. We must
758 // convert the integer case values to this width before comparison.
759 bool HasDependentValue
760 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
761 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType);
762 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType();
764 // Get the width and signedness that the condition might actually have, for
766 // FIXME: Grab an IntRange for the condition rather than using the unpromoted
768 unsigned CondWidthBeforePromotion
769 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
770 bool CondIsSignedBeforePromotion
771 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
773 // Accumulate all of the case values in a vector so that we can sort them
774 // and detect duplicates. This vector contains the APInt for the case after
775 // it has been converted to the condition type.
776 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
779 // Keep track of any GNU case ranges we see. The APSInt is the low value.
780 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
781 CaseRangesTy CaseRanges;
783 DefaultStmt *TheDefaultStmt = nullptr;
785 bool CaseListIsErroneous = false;
787 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
788 SC = SC->getNextSwitchCase()) {
790 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
791 if (TheDefaultStmt) {
792 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
793 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
795 // FIXME: Remove the default statement from the switch block so that
796 // we'll return a valid AST. This requires recursing down the AST and
797 // finding it, not something we are set up to do right now. For now,
798 // just lop the entire switch stmt out of the AST.
799 CaseListIsErroneous = true;
804 CaseStmt *CS = cast<CaseStmt>(SC);
806 Expr *Lo = CS->getLHS();
808 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
809 HasDependentValue = true;
815 if (getLangOpts().CPlusPlus11) {
816 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
817 // constant expression of the promoted type of the switch condition.
819 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
820 if (ConvLo.isInvalid()) {
821 CaseListIsErroneous = true;
826 // We already verified that the expression has a i-c-e value (C99
827 // 6.8.4.2p3) - get that value now.
828 LoVal = Lo->EvaluateKnownConstInt(Context);
830 // If the LHS is not the same type as the condition, insert an implicit
832 Lo = DefaultLvalueConversion(Lo).get();
833 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).get();
836 // Check the unconverted value is within the range of possible values of
837 // the switch expression.
838 checkCaseValue(*this, Lo->getLocStart(), LoVal,
839 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
841 // Convert the value to the same width/sign as the condition.
842 AdjustAPSInt(LoVal, CondWidth, CondIsSigned);
846 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
848 if (CS->getRHS()->isTypeDependent() ||
849 CS->getRHS()->isValueDependent()) {
850 HasDependentValue = true;
853 CaseRanges.push_back(std::make_pair(LoVal, CS));
855 CaseVals.push_back(std::make_pair(LoVal, CS));
859 if (!HasDependentValue) {
860 // If we don't have a default statement, check whether the
861 // condition is constant.
862 llvm::APSInt ConstantCondValue;
863 bool HasConstantCond = false;
864 if (!HasDependentValue && !TheDefaultStmt) {
865 HasConstantCond = CondExpr->EvaluateAsInt(ConstantCondValue, Context,
866 Expr::SE_AllowSideEffects);
867 assert(!HasConstantCond ||
868 (ConstantCondValue.getBitWidth() == CondWidth &&
869 ConstantCondValue.isSigned() == CondIsSigned));
871 bool ShouldCheckConstantCond = HasConstantCond;
873 // Sort all the scalar case values so we can easily detect duplicates.
874 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
876 if (!CaseVals.empty()) {
877 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
878 if (ShouldCheckConstantCond &&
879 CaseVals[i].first == ConstantCondValue)
880 ShouldCheckConstantCond = false;
882 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
883 // If we have a duplicate, report it.
884 // First, determine if either case value has a name
885 StringRef PrevString, CurrString;
886 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
887 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
888 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
889 PrevString = DeclRef->getDecl()->getName();
891 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
892 CurrString = DeclRef->getDecl()->getName();
894 SmallString<16> CaseValStr;
895 CaseVals[i-1].first.toString(CaseValStr);
897 if (PrevString == CurrString)
898 Diag(CaseVals[i].second->getLHS()->getLocStart(),
899 diag::err_duplicate_case) <<
900 (PrevString.empty() ? CaseValStr.str() : PrevString);
902 Diag(CaseVals[i].second->getLHS()->getLocStart(),
903 diag::err_duplicate_case_differing_expr) <<
904 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
905 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
908 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
909 diag::note_duplicate_case_prev);
910 // FIXME: We really want to remove the bogus case stmt from the
911 // substmt, but we have no way to do this right now.
912 CaseListIsErroneous = true;
917 // Detect duplicate case ranges, which usually don't exist at all in
919 if (!CaseRanges.empty()) {
920 // Sort all the case ranges by their low value so we can easily detect
921 // overlaps between ranges.
922 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
924 // Scan the ranges, computing the high values and removing empty ranges.
925 std::vector<llvm::APSInt> HiVals;
926 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
927 llvm::APSInt &LoVal = CaseRanges[i].first;
928 CaseStmt *CR = CaseRanges[i].second;
929 Expr *Hi = CR->getRHS();
932 if (getLangOpts().CPlusPlus11) {
933 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
934 // constant expression of the promoted type of the switch condition.
936 CheckConvertedConstantExpression(Hi, CondType, HiVal,
938 if (ConvHi.isInvalid()) {
939 CaseListIsErroneous = true;
944 HiVal = Hi->EvaluateKnownConstInt(Context);
946 // If the RHS is not the same type as the condition, insert an
948 Hi = DefaultLvalueConversion(Hi).get();
949 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).get();
952 // Check the unconverted value is within the range of possible values of
953 // the switch expression.
954 checkCaseValue(*this, Hi->getLocStart(), HiVal,
955 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
957 // Convert the value to the same width/sign as the condition.
958 AdjustAPSInt(HiVal, CondWidth, CondIsSigned);
962 // If the low value is bigger than the high value, the case is empty.
964 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
965 << SourceRange(CR->getLHS()->getLocStart(),
967 CaseRanges.erase(CaseRanges.begin()+i);
972 if (ShouldCheckConstantCond &&
973 LoVal <= ConstantCondValue &&
974 ConstantCondValue <= HiVal)
975 ShouldCheckConstantCond = false;
977 HiVals.push_back(HiVal);
980 // Rescan the ranges, looking for overlap with singleton values and other
981 // ranges. Since the range list is sorted, we only need to compare case
982 // ranges with their neighbors.
983 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
984 llvm::APSInt &CRLo = CaseRanges[i].first;
985 llvm::APSInt &CRHi = HiVals[i];
986 CaseStmt *CR = CaseRanges[i].second;
988 // Check to see whether the case range overlaps with any
990 CaseStmt *OverlapStmt = nullptr;
991 llvm::APSInt OverlapVal(32);
993 // Find the smallest value >= the lower bound. If I is in the
994 // case range, then we have overlap.
995 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
996 CaseVals.end(), CRLo,
997 CaseCompareFunctor());
998 if (I != CaseVals.end() && I->first < CRHi) {
999 OverlapVal = I->first; // Found overlap with scalar.
1000 OverlapStmt = I->second;
1003 // Find the smallest value bigger than the upper bound.
1004 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1005 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1006 OverlapVal = (I-1)->first; // Found overlap with scalar.
1007 OverlapStmt = (I-1)->second;
1010 // Check to see if this case stmt overlaps with the subsequent
1012 if (i && CRLo <= HiVals[i-1]) {
1013 OverlapVal = HiVals[i-1]; // Found overlap with range.
1014 OverlapStmt = CaseRanges[i-1].second;
1018 // If we have a duplicate, report it.
1019 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
1020 << OverlapVal.toString(10);
1021 Diag(OverlapStmt->getLHS()->getLocStart(),
1022 diag::note_duplicate_case_prev);
1023 // FIXME: We really want to remove the bogus case stmt from the
1024 // substmt, but we have no way to do this right now.
1025 CaseListIsErroneous = true;
1030 // Complain if we have a constant condition and we didn't find a match.
1031 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
1032 // TODO: it would be nice if we printed enums as enums, chars as
1034 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1035 << ConstantCondValue.toString(10)
1036 << CondExpr->getSourceRange();
1039 // Check to see if switch is over an Enum and handles all of its
1040 // values. We only issue a warning if there is not 'default:', but
1041 // we still do the analysis to preserve this information in the AST
1042 // (which can be used by flow-based analyes).
1044 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
1046 // If switch has default case, then ignore it.
1047 if (!CaseListIsErroneous && !HasConstantCond && ET) {
1048 const EnumDecl *ED = ET->getDecl();
1049 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
1051 EnumValsTy EnumVals;
1053 // Gather all enum values, set their type and sort them,
1054 // allowing easier comparison with CaseVals.
1055 for (auto *EDI : ED->enumerators()) {
1056 llvm::APSInt Val = EDI->getInitVal();
1057 AdjustAPSInt(Val, CondWidth, CondIsSigned);
1058 EnumVals.push_back(std::make_pair(Val, EDI));
1060 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1061 EnumValsTy::iterator EIend =
1062 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1064 // See which case values aren't in enum.
1065 EnumValsTy::const_iterator EI = EnumVals.begin();
1066 for (CaseValsTy::const_iterator CI = CaseVals.begin();
1067 CI != CaseVals.end(); CI++) {
1068 while (EI != EIend && EI->first < CI->first)
1070 if (EI == EIend || EI->first > CI->first) {
1071 Expr *CaseExpr = CI->second->getLHS();
1072 if (ShouldDiagnoseSwitchCaseNotInEnum(Context, ED, CaseExpr))
1073 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1074 << CondTypeBeforePromotion;
1077 // See which of case ranges aren't in enum
1078 EI = EnumVals.begin();
1079 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1080 RI != CaseRanges.end() && EI != EIend; RI++) {
1081 while (EI != EIend && EI->first < RI->first)
1084 if (EI == EIend || EI->first != RI->first) {
1085 Expr *CaseExpr = RI->second->getLHS();
1086 if (ShouldDiagnoseSwitchCaseNotInEnum(Context, ED, CaseExpr))
1087 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1088 << CondTypeBeforePromotion;
1092 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1093 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1094 while (EI != EIend && EI->first < Hi)
1096 if (EI == EIend || EI->first != Hi) {
1097 Expr *CaseExpr = RI->second->getRHS();
1098 if (ShouldDiagnoseSwitchCaseNotInEnum(Context, ED, CaseExpr))
1099 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1100 << CondTypeBeforePromotion;
1104 // Check which enum vals aren't in switch
1105 CaseValsTy::const_iterator CI = CaseVals.begin();
1106 CaseRangesTy::const_iterator RI = CaseRanges.begin();
1107 bool hasCasesNotInSwitch = false;
1109 SmallVector<DeclarationName,8> UnhandledNames;
1111 for (EI = EnumVals.begin(); EI != EIend; EI++){
1112 // Drop unneeded case values
1113 while (CI != CaseVals.end() && CI->first < EI->first)
1116 if (CI != CaseVals.end() && CI->first == EI->first)
1119 // Drop unneeded case ranges
1120 for (; RI != CaseRanges.end(); RI++) {
1122 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1123 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1124 if (EI->first <= Hi)
1128 if (RI == CaseRanges.end() || EI->first < RI->first) {
1129 hasCasesNotInSwitch = true;
1130 UnhandledNames.push_back(EI->second->getDeclName());
1134 if (TheDefaultStmt && UnhandledNames.empty())
1135 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
1137 // Produce a nice diagnostic if multiple values aren't handled.
1138 switch (UnhandledNames.size()) {
1141 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1142 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
1143 << UnhandledNames[0];
1146 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1147 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
1148 << UnhandledNames[0] << UnhandledNames[1];
1151 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1152 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
1153 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1156 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1157 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
1158 << (unsigned)UnhandledNames.size()
1159 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1163 if (!hasCasesNotInSwitch)
1164 SS->setAllEnumCasesCovered();
1169 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1170 diag::warn_empty_switch_body);
1172 // FIXME: If the case list was broken is some way, we don't have a good system
1173 // to patch it up. Instead, just return the whole substmt as broken.
1174 if (CaseListIsErroneous)
1181 Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1183 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
1186 if (const EnumType *ET = DstType->getAs<EnumType>())
1187 if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
1188 SrcType->isIntegerType()) {
1189 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1190 SrcExpr->isIntegerConstantExpr(Context)) {
1191 // Get the bitwidth of the enum value before promotions.
1192 unsigned DstWidth = Context.getIntWidth(DstType);
1193 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1195 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1196 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
1197 const EnumDecl *ED = ET->getDecl();
1198 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1200 EnumValsTy EnumVals;
1202 // Gather all enum values, set their type and sort them,
1203 // allowing easier comparison with rhs constant.
1204 for (auto *EDI : ED->enumerators()) {
1205 llvm::APSInt Val = EDI->getInitVal();
1206 AdjustAPSInt(Val, DstWidth, DstIsSigned);
1207 EnumVals.push_back(std::make_pair(Val, EDI));
1209 if (EnumVals.empty())
1211 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1212 EnumValsTy::iterator EIend =
1213 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1215 // See which values aren't in the enum.
1216 EnumValsTy::const_iterator EI = EnumVals.begin();
1217 while (EI != EIend && EI->first < RhsVal)
1219 if (EI == EIend || EI->first != RhsVal) {
1220 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1221 << DstType.getUnqualifiedType();
1228 Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
1229 Decl *CondVar, Stmt *Body) {
1230 ExprResult CondResult(Cond.release());
1232 VarDecl *ConditionVar = nullptr;
1234 ConditionVar = cast<VarDecl>(CondVar);
1235 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
1236 if (CondResult.isInvalid())
1239 Expr *ConditionExpr = CondResult.get();
1242 CheckBreakContinueBinding(ConditionExpr);
1244 DiagnoseUnusedExprResult(Body);
1246 if (isa<NullStmt>(Body))
1247 getCurCompoundScope().setHasEmptyLoopBodies();
1249 return new (Context)
1250 WhileStmt(Context, ConditionVar, ConditionExpr, Body, WhileLoc);
1254 Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
1255 SourceLocation WhileLoc, SourceLocation CondLParen,
1256 Expr *Cond, SourceLocation CondRParen) {
1257 assert(Cond && "ActOnDoStmt(): missing expression");
1259 CheckBreakContinueBinding(Cond);
1260 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
1261 if (CondResult.isInvalid())
1263 Cond = CondResult.get();
1265 CondResult = ActOnFinishFullExpr(Cond, DoLoc);
1266 if (CondResult.isInvalid())
1268 Cond = CondResult.get();
1270 DiagnoseUnusedExprResult(Body);
1272 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
1276 // This visitor will traverse a conditional statement and store all
1277 // the evaluated decls into a vector. Simple is set to true if none
1278 // of the excluded constructs are used.
1279 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1280 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
1281 SmallVectorImpl<SourceRange> &Ranges;
1284 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1286 DeclExtractor(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
1287 SmallVectorImpl<SourceRange> &Ranges) :
1288 Inherited(S.Context),
1293 bool isSimple() { return Simple; }
1295 // Replaces the method in EvaluatedExprVisitor.
1296 void VisitMemberExpr(MemberExpr* E) {
1300 // Any Stmt not whitelisted will cause the condition to be marked complex.
1301 void VisitStmt(Stmt *S) {
1305 void VisitBinaryOperator(BinaryOperator *E) {
1310 void VisitCastExpr(CastExpr *E) {
1311 Visit(E->getSubExpr());
1314 void VisitUnaryOperator(UnaryOperator *E) {
1315 // Skip checking conditionals with derefernces.
1316 if (E->getOpcode() == UO_Deref)
1319 Visit(E->getSubExpr());
1322 void VisitConditionalOperator(ConditionalOperator *E) {
1323 Visit(E->getCond());
1324 Visit(E->getTrueExpr());
1325 Visit(E->getFalseExpr());
1328 void VisitParenExpr(ParenExpr *E) {
1329 Visit(E->getSubExpr());
1332 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1333 Visit(E->getOpaqueValue()->getSourceExpr());
1334 Visit(E->getFalseExpr());
1337 void VisitIntegerLiteral(IntegerLiteral *E) { }
1338 void VisitFloatingLiteral(FloatingLiteral *E) { }
1339 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1340 void VisitCharacterLiteral(CharacterLiteral *E) { }
1341 void VisitGNUNullExpr(GNUNullExpr *E) { }
1342 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1344 void VisitDeclRefExpr(DeclRefExpr *E) {
1345 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1348 Ranges.push_back(E->getSourceRange());
1353 }; // end class DeclExtractor
1355 // DeclMatcher checks to see if the decls are used in a non-evauluated
1357 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1358 llvm::SmallPtrSetImpl<VarDecl*> &Decls;
1362 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1364 DeclMatcher(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls,
1366 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1367 if (!Statement) return;
1372 void VisitReturnStmt(ReturnStmt *S) {
1376 void VisitBreakStmt(BreakStmt *S) {
1380 void VisitGotoStmt(GotoStmt *S) {
1384 void VisitCastExpr(CastExpr *E) {
1385 if (E->getCastKind() == CK_LValueToRValue)
1386 CheckLValueToRValueCast(E->getSubExpr());
1388 Visit(E->getSubExpr());
1391 void CheckLValueToRValueCast(Expr *E) {
1392 E = E->IgnoreParenImpCasts();
1394 if (isa<DeclRefExpr>(E)) {
1398 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1399 Visit(CO->getCond());
1400 CheckLValueToRValueCast(CO->getTrueExpr());
1401 CheckLValueToRValueCast(CO->getFalseExpr());
1405 if (BinaryConditionalOperator *BCO =
1406 dyn_cast<BinaryConditionalOperator>(E)) {
1407 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1408 CheckLValueToRValueCast(BCO->getFalseExpr());
1415 void VisitDeclRefExpr(DeclRefExpr *E) {
1416 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1417 if (Decls.count(VD))
1421 bool FoundDeclInUse() { return FoundDecl; }
1423 }; // end class DeclMatcher
1425 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1426 Expr *Third, Stmt *Body) {
1427 // Condition is empty
1428 if (!Second) return;
1430 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1431 Second->getLocStart()))
1434 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1435 llvm::SmallPtrSet<VarDecl*, 8> Decls;
1436 SmallVector<SourceRange, 10> Ranges;
1437 DeclExtractor DE(S, Decls, Ranges);
1440 // Don't analyze complex conditionals.
1441 if (!DE.isSimple()) return;
1444 if (Decls.size() == 0) return;
1446 // Don't warn on volatile, static, or global variables.
1447 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1450 if ((*I)->getType().isVolatileQualified() ||
1451 (*I)->hasGlobalStorage()) return;
1453 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1454 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1455 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1458 // Load decl names into diagnostic.
1459 if (Decls.size() > 4)
1462 PDiag << Decls.size();
1463 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(),
1466 PDiag << (*I)->getDeclName();
1469 // Load SourceRanges into diagnostic if there is room.
1470 // Otherwise, load the SourceRange of the conditional expression.
1471 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
1472 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
1477 PDiag << Second->getSourceRange();
1479 S.Diag(Ranges.begin()->getBegin(), PDiag);
1482 // If Statement is an incemement or decrement, return true and sets the
1483 // variables Increment and DRE.
1484 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1485 DeclRefExpr *&DRE) {
1486 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1487 switch (UO->getOpcode()) {
1488 default: return false;
1498 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1502 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1503 FunctionDecl *FD = Call->getDirectCallee();
1504 if (!FD || !FD->isOverloadedOperator()) return false;
1505 switch (FD->getOverloadedOperator()) {
1506 default: return false;
1514 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1521 // A visitor to determine if a continue or break statement is a
1523 class BreakContinueFinder : public EvaluatedExprVisitor<BreakContinueFinder> {
1524 SourceLocation BreakLoc;
1525 SourceLocation ContinueLoc;
1527 BreakContinueFinder(Sema &S, Stmt* Body) :
1528 Inherited(S.Context) {
1532 typedef EvaluatedExprVisitor<BreakContinueFinder> Inherited;
1534 void VisitContinueStmt(ContinueStmt* E) {
1535 ContinueLoc = E->getContinueLoc();
1538 void VisitBreakStmt(BreakStmt* E) {
1539 BreakLoc = E->getBreakLoc();
1542 bool ContinueFound() { return ContinueLoc.isValid(); }
1543 bool BreakFound() { return BreakLoc.isValid(); }
1544 SourceLocation GetContinueLoc() { return ContinueLoc; }
1545 SourceLocation GetBreakLoc() { return BreakLoc; }
1547 }; // end class BreakContinueFinder
1549 // Emit a warning when a loop increment/decrement appears twice per loop
1550 // iteration. The conditions which trigger this warning are:
1551 // 1) The last statement in the loop body and the third expression in the
1552 // for loop are both increment or both decrement of the same variable
1553 // 2) No continue statements in the loop body.
1554 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1555 // Return when there is nothing to check.
1556 if (!Body || !Third) return;
1558 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1559 Third->getLocStart()))
1562 // Get the last statement from the loop body.
1563 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1564 if (!CS || CS->body_empty()) return;
1565 Stmt *LastStmt = CS->body_back();
1566 if (!LastStmt) return;
1568 bool LoopIncrement, LastIncrement;
1569 DeclRefExpr *LoopDRE, *LastDRE;
1571 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1572 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1574 // Check that the two statements are both increments or both decrements
1575 // on the same variable.
1576 if (LoopIncrement != LastIncrement ||
1577 LoopDRE->getDecl() != LastDRE->getDecl()) return;
1579 if (BreakContinueFinder(S, Body).ContinueFound()) return;
1581 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1582 << LastDRE->getDecl() << LastIncrement;
1583 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1590 void Sema::CheckBreakContinueBinding(Expr *E) {
1591 if (!E || getLangOpts().CPlusPlus)
1593 BreakContinueFinder BCFinder(*this, E);
1594 Scope *BreakParent = CurScope->getBreakParent();
1595 if (BCFinder.BreakFound() && BreakParent) {
1596 if (BreakParent->getFlags() & Scope::SwitchScope) {
1597 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1599 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1602 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1603 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1609 Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1610 Stmt *First, FullExprArg second, Decl *secondVar,
1612 SourceLocation RParenLoc, Stmt *Body) {
1613 if (!getLangOpts().CPlusPlus) {
1614 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
1615 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1616 // declare identifiers for objects having storage class 'auto' or
1618 for (auto *DI : DS->decls()) {
1619 VarDecl *VD = dyn_cast<VarDecl>(DI);
1620 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
1623 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1624 DI->setInvalidDecl();
1630 CheckBreakContinueBinding(second.get());
1631 CheckBreakContinueBinding(third.get());
1633 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
1634 CheckForRedundantIteration(*this, third.get(), Body);
1636 ExprResult SecondResult(second.release());
1637 VarDecl *ConditionVar = nullptr;
1639 ConditionVar = cast<VarDecl>(secondVar);
1640 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
1641 if (SecondResult.isInvalid())
1645 Expr *Third = third.release().getAs<Expr>();
1647 DiagnoseUnusedExprResult(First);
1648 DiagnoseUnusedExprResult(Third);
1649 DiagnoseUnusedExprResult(Body);
1651 if (isa<NullStmt>(Body))
1652 getCurCompoundScope().setHasEmptyLoopBodies();
1654 return new (Context) ForStmt(Context, First, SecondResult.get(), ConditionVar,
1655 Third, Body, ForLoc, LParenLoc, RParenLoc);
1658 /// In an Objective C collection iteration statement:
1660 /// x can be an arbitrary l-value expression. Bind it up as a
1661 /// full-expression.
1662 StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
1663 // Reduce placeholder expressions here. Note that this rejects the
1664 // use of pseudo-object l-values in this position.
1665 ExprResult result = CheckPlaceholderExpr(E);
1666 if (result.isInvalid()) return StmtError();
1669 ExprResult FullExpr = ActOnFinishFullExpr(E);
1670 if (FullExpr.isInvalid())
1672 return StmtResult(static_cast<Stmt*>(FullExpr.get()));
1676 Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1680 ExprResult result = CorrectDelayedTyposInExpr(collection);
1681 if (!result.isUsable())
1683 collection = result.get();
1685 // Bail out early if we've got a type-dependent expression.
1686 if (collection->isTypeDependent()) return collection;
1688 // Perform normal l-value conversion.
1689 result = DefaultFunctionArrayLvalueConversion(collection);
1690 if (result.isInvalid())
1692 collection = result.get();
1694 // The operand needs to have object-pointer type.
1695 // TODO: should we do a contextual conversion?
1696 const ObjCObjectPointerType *pointerType =
1697 collection->getType()->getAs<ObjCObjectPointerType>();
1699 return Diag(forLoc, diag::err_collection_expr_type)
1700 << collection->getType() << collection->getSourceRange();
1702 // Check that the operand provides
1703 // - countByEnumeratingWithState:objects:count:
1704 const ObjCObjectType *objectType = pointerType->getObjectType();
1705 ObjCInterfaceDecl *iface = objectType->getInterface();
1707 // If we have a forward-declared type, we can't do this check.
1708 // Under ARC, it is an error not to have a forward-declared class.
1710 RequireCompleteType(forLoc, QualType(objectType, 0),
1711 getLangOpts().ObjCAutoRefCount
1712 ? diag::err_arc_collection_forward
1715 // Otherwise, if we have any useful type information, check that
1716 // the type declares the appropriate method.
1717 } else if (iface || !objectType->qual_empty()) {
1718 IdentifierInfo *selectorIdents[] = {
1719 &Context.Idents.get("countByEnumeratingWithState"),
1720 &Context.Idents.get("objects"),
1721 &Context.Idents.get("count")
1723 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1725 ObjCMethodDecl *method = nullptr;
1727 // If there's an interface, look in both the public and private APIs.
1729 method = iface->lookupInstanceMethod(selector);
1730 if (!method) method = iface->lookupPrivateMethod(selector);
1733 // Also check protocol qualifiers.
1735 method = LookupMethodInQualifiedType(selector, pointerType,
1738 // If we didn't find it anywhere, give up.
1740 Diag(forLoc, diag::warn_collection_expr_type)
1741 << collection->getType() << selector << collection->getSourceRange();
1744 // TODO: check for an incompatible signature?
1747 // Wrap up any cleanups in the expression.
1752 Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1753 Stmt *First, Expr *collection,
1754 SourceLocation RParenLoc) {
1756 ExprResult CollectionExprResult =
1757 CheckObjCForCollectionOperand(ForLoc, collection);
1761 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
1762 if (!DS->isSingleDecl())
1763 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1764 diag::err_toomany_element_decls));
1766 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1767 if (!D || D->isInvalidDecl())
1770 FirstType = D->getType();
1771 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1772 // declare identifiers for objects having storage class 'auto' or
1774 if (!D->hasLocalStorage())
1775 return StmtError(Diag(D->getLocation(),
1776 diag::err_non_local_variable_decl_in_for));
1778 // If the type contained 'auto', deduce the 'auto' to 'id'.
1779 if (FirstType->getContainedAutoType()) {
1780 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1782 Expr *DeducedInit = &OpaqueId;
1783 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1785 DiagnoseAutoDeductionFailure(D, DeducedInit);
1786 if (FirstType.isNull()) {
1787 D->setInvalidDecl();
1791 D->setType(FirstType);
1793 if (ActiveTemplateInstantiations.empty()) {
1794 SourceLocation Loc =
1795 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
1796 Diag(Loc, diag::warn_auto_var_is_id)
1797 << D->getDeclName();
1802 Expr *FirstE = cast<Expr>(First);
1803 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
1804 return StmtError(Diag(First->getLocStart(),
1805 diag::err_selector_element_not_lvalue)
1806 << First->getSourceRange());
1808 FirstType = static_cast<Expr*>(First)->getType();
1809 if (FirstType.isConstQualified())
1810 Diag(ForLoc, diag::err_selector_element_const_type)
1811 << FirstType << First->getSourceRange();
1813 if (!FirstType->isDependentType() &&
1814 !FirstType->isObjCObjectPointerType() &&
1815 !FirstType->isBlockPointerType())
1816 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1817 << FirstType << First->getSourceRange());
1820 if (CollectionExprResult.isInvalid())
1823 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
1824 if (CollectionExprResult.isInvalid())
1827 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1828 nullptr, ForLoc, RParenLoc);
1831 /// Finish building a variable declaration for a for-range statement.
1832 /// \return true if an error occurs.
1833 static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1834 SourceLocation Loc, int DiagID) {
1835 // Deduce the type for the iterator variable now rather than leaving it to
1836 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1838 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
1839 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
1841 SemaRef.Diag(Loc, DiagID) << Init->getType();
1842 if (InitType.isNull()) {
1843 Decl->setInvalidDecl();
1846 Decl->setType(InitType);
1848 // In ARC, infer lifetime.
1849 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1850 // we're doing the equivalent of fast iteration.
1851 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1852 SemaRef.inferObjCARCLifetime(Decl))
1853 Decl->setInvalidDecl();
1855 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1856 /*TypeMayContainAuto=*/false);
1857 SemaRef.FinalizeDeclaration(Decl);
1858 SemaRef.CurContext->addHiddenDecl(Decl);
1864 /// Produce a note indicating which begin/end function was implicitly called
1865 /// by a C++11 for-range statement. This is often not obvious from the code,
1866 /// nor from the diagnostics produced when analysing the implicit expressions
1867 /// required in a for-range statement.
1868 void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
1869 Sema::BeginEndFunction BEF) {
1870 CallExpr *CE = dyn_cast<CallExpr>(E);
1873 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1876 SourceLocation Loc = D->getLocation();
1878 std::string Description;
1879 bool IsTemplate = false;
1880 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1881 Description = SemaRef.getTemplateArgumentBindingsText(
1882 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1886 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1887 << BEF << IsTemplate << Description << E->getType();
1890 /// Build a variable declaration for a for-range statement.
1891 VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1892 QualType Type, const char *Name) {
1893 DeclContext *DC = SemaRef.CurContext;
1894 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1895 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1896 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1898 Decl->setImplicit();
1904 static bool ObjCEnumerationCollection(Expr *Collection) {
1905 return !Collection->isTypeDependent()
1906 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
1909 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
1911 /// C++11 [stmt.ranged]:
1912 /// A range-based for statement is equivalent to
1915 /// auto && __range = range-init;
1916 /// for ( auto __begin = begin-expr,
1917 /// __end = end-expr;
1918 /// __begin != __end;
1920 /// for-range-declaration = *__begin;
1925 /// The body of the loop is not available yet, since it cannot be analysed until
1926 /// we have determined the type of the for-range-declaration.
1928 Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
1929 Stmt *First, SourceLocation ColonLoc, Expr *Range,
1930 SourceLocation RParenLoc, BuildForRangeKind Kind) {
1934 if (Range && ObjCEnumerationCollection(Range))
1935 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
1937 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1938 assert(DS && "first part of for range not a decl stmt");
1940 if (!DS->isSingleDecl()) {
1941 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1945 Decl *LoopVar = DS->getSingleDecl();
1946 if (LoopVar->isInvalidDecl() || !Range ||
1947 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
1948 LoopVar->setInvalidDecl();
1952 // Build auto && __range = range-init
1953 SourceLocation RangeLoc = Range->getLocStart();
1954 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1955 Context.getAutoRRefDeductType(),
1957 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1958 diag::err_for_range_deduction_failure)) {
1959 LoopVar->setInvalidDecl();
1963 // Claim the type doesn't contain auto: we've already done the checking.
1964 DeclGroupPtrTy RangeGroup =
1965 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1),
1966 /*TypeMayContainAuto=*/ false);
1967 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1968 if (RangeDecl.isInvalid()) {
1969 LoopVar->setInvalidDecl();
1973 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1974 /*BeginEndDecl=*/nullptr, /*Cond=*/nullptr,
1975 /*Inc=*/nullptr, DS, RParenLoc, Kind);
1978 /// \brief Create the initialization, compare, and increment steps for
1979 /// the range-based for loop expression.
1980 /// This function does not handle array-based for loops,
1981 /// which are created in Sema::BuildCXXForRangeStmt.
1983 /// \returns a ForRangeStatus indicating success or what kind of error occurred.
1984 /// BeginExpr and EndExpr are set and FRS_Success is returned on success;
1985 /// CandidateSet and BEF are set and some non-success value is returned on
1987 static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
1988 Expr *BeginRange, Expr *EndRange,
1992 SourceLocation ColonLoc,
1993 OverloadCandidateSet *CandidateSet,
1994 ExprResult *BeginExpr,
1995 ExprResult *EndExpr,
1996 Sema::BeginEndFunction *BEF) {
1997 DeclarationNameInfo BeginNameInfo(
1998 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
1999 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
2002 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
2003 Sema::LookupMemberName);
2004 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
2006 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
2007 // - if _RangeT is a class type, the unqualified-ids begin and end are
2008 // looked up in the scope of class _RangeT as if by class member access
2009 // lookup (3.4.5), and if either (or both) finds at least one
2010 // declaration, begin-expr and end-expr are __range.begin() and
2011 // __range.end(), respectively;
2012 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
2013 SemaRef.LookupQualifiedName(EndMemberLookup, D);
2015 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
2016 SourceLocation RangeLoc = BeginVar->getLocation();
2017 *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
2019 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
2020 << RangeLoc << BeginRange->getType() << *BEF;
2021 return Sema::FRS_DiagnosticIssued;
2024 // - otherwise, begin-expr and end-expr are begin(__range) and
2025 // end(__range), respectively, where begin and end are looked up with
2026 // argument-dependent lookup (3.4.2). For the purposes of this name
2027 // lookup, namespace std is an associated namespace.
2031 *BEF = Sema::BEF_begin;
2032 Sema::ForRangeStatus RangeStatus =
2033 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
2034 Sema::BEF_begin, BeginNameInfo,
2035 BeginMemberLookup, CandidateSet,
2036 BeginRange, BeginExpr);
2038 if (RangeStatus != Sema::FRS_Success)
2040 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2041 diag::err_for_range_iter_deduction_failure)) {
2042 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2043 return Sema::FRS_DiagnosticIssued;
2046 *BEF = Sema::BEF_end;
2048 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
2049 Sema::BEF_end, EndNameInfo,
2050 EndMemberLookup, CandidateSet,
2052 if (RangeStatus != Sema::FRS_Success)
2054 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2055 diag::err_for_range_iter_deduction_failure)) {
2056 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2057 return Sema::FRS_DiagnosticIssued;
2059 return Sema::FRS_Success;
2062 /// Speculatively attempt to dereference an invalid range expression.
2063 /// If the attempt fails, this function will return a valid, null StmtResult
2064 /// and emit no diagnostics.
2065 static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2066 SourceLocation ForLoc,
2068 SourceLocation ColonLoc,
2070 SourceLocation RangeLoc,
2071 SourceLocation RParenLoc) {
2072 // Determine whether we can rebuild the for-range statement with a
2073 // dereferenced range expression.
2074 ExprResult AdjustedRange;
2076 Sema::SFINAETrap Trap(SemaRef);
2078 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2079 if (AdjustedRange.isInvalid())
2080 return StmtResult();
2083 SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
2084 AdjustedRange.get(), RParenLoc,
2087 return StmtResult();
2090 // The attempt to dereference worked well enough that it could produce a valid
2091 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2092 // case there are any other (non-fatal) problems with it.
2093 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2094 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
2095 return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
2096 AdjustedRange.get(), RParenLoc,
2097 Sema::BFRK_Rebuild);
2101 /// RAII object to automatically invalidate a declaration if an error occurs.
2102 struct InvalidateOnErrorScope {
2103 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2104 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
2105 ~InvalidateOnErrorScope() {
2106 if (Enabled && Trap.hasErrorOccurred())
2107 D->setInvalidDecl();
2110 DiagnosticErrorTrap Trap;
2116 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
2118 Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
2119 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
2120 Expr *Inc, Stmt *LoopVarDecl,
2121 SourceLocation RParenLoc, BuildForRangeKind Kind) {
2122 Scope *S = getCurScope();
2124 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2125 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2126 QualType RangeVarType = RangeVar->getType();
2128 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2129 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2131 // If we hit any errors, mark the loop variable as invalid if its type
2133 InvalidateOnErrorScope Invalidate(*this, LoopVar,
2134 LoopVar->getType()->isUndeducedType());
2136 StmtResult BeginEndDecl = BeginEnd;
2137 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2139 if (RangeVarType->isDependentType()) {
2140 // The range is implicitly used as a placeholder when it is dependent.
2141 RangeVar->markUsed(Context);
2143 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2144 // them in properly when we instantiate the loop.
2145 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
2146 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
2147 } else if (!BeginEndDecl.get()) {
2148 SourceLocation RangeLoc = RangeVar->getLocation();
2150 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2152 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2153 VK_LValue, ColonLoc);
2154 if (BeginRangeRef.isInvalid())
2157 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2158 VK_LValue, ColonLoc);
2159 if (EndRangeRef.isInvalid())
2162 QualType AutoType = Context.getAutoDeductType();
2163 Expr *Range = RangeVar->getInit();
2166 QualType RangeType = Range->getType();
2168 if (RequireCompleteType(RangeLoc, RangeType,
2169 diag::err_for_range_incomplete_type))
2172 // Build auto __begin = begin-expr, __end = end-expr.
2173 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2175 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2178 // Build begin-expr and end-expr and attach to __begin and __end variables.
2179 ExprResult BeginExpr, EndExpr;
2180 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2181 // - if _RangeT is an array type, begin-expr and end-expr are __range and
2182 // __range + __bound, respectively, where __bound is the array bound. If
2183 // _RangeT is an array of unknown size or an array of incomplete type,
2184 // the program is ill-formed;
2186 // begin-expr is __range.
2187 BeginExpr = BeginRangeRef;
2188 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
2189 diag::err_for_range_iter_deduction_failure)) {
2190 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2194 // Find the array bound.
2195 ExprResult BoundExpr;
2196 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
2197 BoundExpr = IntegerLiteral::Create(
2198 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
2199 else if (const VariableArrayType *VAT =
2200 dyn_cast<VariableArrayType>(UnqAT))
2201 BoundExpr = VAT->getSizeExpr();
2203 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2204 // UnqAT is not incomplete and Range is not type-dependent.
2205 llvm_unreachable("Unexpected array type in for-range");
2208 // end-expr is __range + __bound.
2209 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
2211 if (EndExpr.isInvalid())
2213 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2214 diag::err_for_range_iter_deduction_failure)) {
2215 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2219 OverloadCandidateSet CandidateSet(RangeLoc,
2220 OverloadCandidateSet::CSK_Normal);
2221 Sema::BeginEndFunction BEFFailure;
2222 ForRangeStatus RangeStatus =
2223 BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
2224 EndRangeRef.get(), RangeType,
2225 BeginVar, EndVar, ColonLoc, &CandidateSet,
2226 &BeginExpr, &EndExpr, &BEFFailure);
2228 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
2229 BEFFailure == BEF_begin) {
2230 // If the range is being built from an array parameter, emit a
2231 // a diagnostic that it is being treated as a pointer.
2232 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2233 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2234 QualType ArrayTy = PVD->getOriginalType();
2235 QualType PointerTy = PVD->getType();
2236 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2237 Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
2238 << RangeLoc << PVD << ArrayTy << PointerTy;
2239 Diag(PVD->getLocation(), diag::note_declared_at);
2245 // If building the range failed, try dereferencing the range expression
2246 // unless a diagnostic was issued or the end function is problematic.
2247 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2248 LoopVarDecl, ColonLoc,
2251 if (SR.isInvalid() || SR.isUsable())
2255 // Otherwise, emit diagnostics if we haven't already.
2256 if (RangeStatus == FRS_NoViableFunction) {
2257 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
2258 Diag(Range->getLocStart(), diag::err_for_range_invalid)
2259 << RangeLoc << Range->getType() << BEFFailure;
2260 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
2262 // Return an error if no fix was discovered.
2263 if (RangeStatus != FRS_Success)
2267 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2268 "invalid range expression in for loop");
2270 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
2271 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2272 if (!Context.hasSameType(BeginType, EndType)) {
2273 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
2274 << BeginType << EndType;
2275 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2276 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2279 Decl *BeginEndDecls[] = { BeginVar, EndVar };
2280 // Claim the type doesn't contain auto: we've already done the checking.
2281 DeclGroupPtrTy BeginEndGroup =
2282 BuildDeclaratorGroup(MutableArrayRef<Decl *>(BeginEndDecls, 2),
2283 /*TypeMayContainAuto=*/ false);
2284 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
2286 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2287 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2288 VK_LValue, ColonLoc);
2289 if (BeginRef.isInvalid())
2292 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2293 VK_LValue, ColonLoc);
2294 if (EndRef.isInvalid())
2297 // Build and check __begin != __end expression.
2298 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2299 BeginRef.get(), EndRef.get());
2300 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
2301 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2302 if (NotEqExpr.isInvalid()) {
2303 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2304 << RangeLoc << 0 << BeginRangeRef.get()->getType();
2305 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2306 if (!Context.hasSameType(BeginType, EndType))
2307 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2311 // Build and check ++__begin expression.
2312 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2313 VK_LValue, ColonLoc);
2314 if (BeginRef.isInvalid())
2317 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2318 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2319 if (IncrExpr.isInvalid()) {
2320 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2321 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
2322 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2326 // Build and check *__begin expression.
2327 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2328 VK_LValue, ColonLoc);
2329 if (BeginRef.isInvalid())
2332 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2333 if (DerefExpr.isInvalid()) {
2334 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2335 << RangeLoc << 1 << BeginRangeRef.get()->getType();
2336 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2340 // Attach *__begin as initializer for VD. Don't touch it if we're just
2341 // trying to determine whether this would be a valid range.
2342 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2343 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2344 /*TypeMayContainAuto=*/true);
2345 if (LoopVar->isInvalidDecl())
2346 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2350 // Don't bother to actually allocate the result if we're just trying to
2351 // determine whether it would be valid.
2352 if (Kind == BFRK_Check)
2353 return StmtResult();
2355 return new (Context) CXXForRangeStmt(
2356 RangeDS, cast_or_null<DeclStmt>(BeginEndDecl.get()), NotEqExpr.get(),
2357 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, ColonLoc, RParenLoc);
2360 /// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
2362 StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2365 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
2367 ForStmt->setBody(B);
2371 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2372 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2373 /// body cannot be performed until after the type of the range variable is
2375 StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2379 if (isa<ObjCForCollectionStmt>(S))
2380 return FinishObjCForCollectionStmt(S, B);
2382 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2383 ForStmt->setBody(B);
2385 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2386 diag::warn_empty_range_based_for_body);
2391 StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2392 SourceLocation LabelLoc,
2393 LabelDecl *TheDecl) {
2394 getCurFunction()->setHasBranchIntoScope();
2395 TheDecl->markUsed(Context);
2396 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
2400 Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
2402 // Convert operand to void*
2403 if (!E->isTypeDependent()) {
2404 QualType ETy = E->getType();
2405 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
2406 ExprResult ExprRes = E;
2407 AssignConvertType ConvTy =
2408 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2409 if (ExprRes.isInvalid())
2412 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
2416 ExprResult ExprRes = ActOnFinishFullExpr(E);
2417 if (ExprRes.isInvalid())
2421 getCurFunction()->setHasIndirectGoto();
2423 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
2427 Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
2428 Scope *S = CurScope->getContinueParent();
2430 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
2431 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
2434 return new (Context) ContinueStmt(ContinueLoc);
2438 Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
2439 Scope *S = CurScope->getBreakParent();
2441 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
2442 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
2444 if (S->isOpenMPLoopScope())
2445 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2448 return new (Context) BreakStmt(BreakLoc);
2451 /// \brief Determine whether the given expression is a candidate for
2452 /// copy elision in either a return statement or a throw expression.
2454 /// \param ReturnType If we're determining the copy elision candidate for
2455 /// a return statement, this is the return type of the function. If we're
2456 /// determining the copy elision candidate for a throw expression, this will
2459 /// \param E The expression being returned from the function or block, or
2462 /// \param AllowFunctionParameter Whether we allow function parameters to
2463 /// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2464 /// we re-use this logic to determine whether we should try to move as part of
2465 /// a return or throw (which does allow function parameters).
2467 /// \returns The NRVO candidate variable, if the return statement may use the
2468 /// NRVO, or NULL if there is no such candidate.
2469 VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2471 bool AllowFunctionParameter) {
2472 if (!getLangOpts().CPlusPlus)
2475 // - in a return statement in a function [where] ...
2476 // ... the expression is the name of a non-volatile automatic object ...
2477 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
2478 if (!DR || DR->refersToEnclosingVariableOrCapture())
2480 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2484 if (isCopyElisionCandidate(ReturnType, VD, AllowFunctionParameter))
2489 bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
2490 bool AllowFunctionParameter) {
2491 QualType VDType = VD->getType();
2492 // - in a return statement in a function with ...
2493 // ... a class return type ...
2494 if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
2495 if (!ReturnType->isRecordType())
2497 // ... the same cv-unqualified type as the function return type ...
2498 if (!VDType->isDependentType() &&
2499 !Context.hasSameUnqualifiedType(ReturnType, VDType))
2503 // ...object (other than a function or catch-clause parameter)...
2504 if (VD->getKind() != Decl::Var &&
2505 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
2507 if (VD->isExceptionVariable()) return false;
2510 if (!VD->hasLocalStorage()) return false;
2512 // ...non-volatile...
2513 if (VD->getType().isVolatileQualified()) return false;
2515 // __block variables can't be allocated in a way that permits NRVO.
2516 if (VD->hasAttr<BlocksAttr>()) return false;
2518 // Variables with higher required alignment than their type's ABI
2519 // alignment cannot use NRVO.
2520 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
2521 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2527 /// \brief Perform the initialization of a potentially-movable value, which
2528 /// is the result of return value.
2530 /// This routine implements C++0x [class.copy]p33, which attempts to treat
2531 /// returned lvalues as rvalues in certain cases (to prefer move construction),
2532 /// then falls back to treating them as lvalues if that failed.
2534 Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2535 const VarDecl *NRVOCandidate,
2536 QualType ResultType,
2539 // C++0x [class.copy]p33:
2540 // When the criteria for elision of a copy operation are met or would
2541 // be met save for the fact that the source object is a function
2542 // parameter, and the object to be copied is designated by an lvalue,
2543 // overload resolution to select the constructor for the copy is first
2544 // performed as if the object were designated by an rvalue.
2545 ExprResult Res = ExprError();
2547 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
2548 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
2549 Value->getType(), CK_NoOp, Value, VK_XValue);
2551 Expr *InitExpr = &AsRvalue;
2552 InitializationKind Kind
2553 = InitializationKind::CreateCopy(Value->getLocStart(),
2554 Value->getLocStart());
2555 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2557 // [...] If overload resolution fails, or if the type of the first
2558 // parameter of the selected constructor is not an rvalue reference
2559 // to the object's type (possibly cv-qualified), overload resolution
2560 // is performed again, considering the object as an lvalue.
2562 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2563 StepEnd = Seq.step_end();
2564 Step != StepEnd; ++Step) {
2565 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
2568 CXXConstructorDecl *Constructor
2569 = cast<CXXConstructorDecl>(Step->Function.Function);
2571 const RValueReferenceType *RRefType
2572 = Constructor->getParamDecl(0)->getType()
2573 ->getAs<RValueReferenceType>();
2575 // If we don't meet the criteria, break out now.
2577 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2578 Context.getTypeDeclType(Constructor->getParent())))
2581 // Promote "AsRvalue" to the heap, since we now need this
2582 // expression node to persist.
2583 Value = ImplicitCastExpr::Create(Context, Value->getType(),
2584 CK_NoOp, Value, nullptr, VK_XValue);
2586 // Complete type-checking the initialization of the return type
2587 // using the constructor we found.
2588 Res = Seq.Perform(*this, Entity, Kind, Value);
2593 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
2594 // above, or overload resolution failed. Either way, we need to try
2595 // (again) now with the return value expression as written.
2596 if (Res.isInvalid())
2597 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
2602 /// \brief Determine whether the declared return type of the specified function
2603 /// contains 'auto'.
2604 static bool hasDeducedReturnType(FunctionDecl *FD) {
2605 const FunctionProtoType *FPT =
2606 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
2607 return FPT->getReturnType()->isUndeducedType();
2610 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2611 /// for capturing scopes.
2614 Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2615 // If this is the first return we've seen, infer the return type.
2616 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
2617 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
2618 QualType FnRetType = CurCap->ReturnType;
2619 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
2621 if (CurLambda && hasDeducedReturnType(CurLambda->CallOperator)) {
2622 // In C++1y, the return type may involve 'auto'.
2623 // FIXME: Blocks might have a return type of 'auto' explicitly specified.
2624 FunctionDecl *FD = CurLambda->CallOperator;
2625 if (CurCap->ReturnType.isNull())
2626 CurCap->ReturnType = FD->getReturnType();
2628 AutoType *AT = CurCap->ReturnType->getContainedAutoType();
2629 assert(AT && "lost auto type from lambda return type");
2630 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2631 FD->setInvalidDecl();
2634 CurCap->ReturnType = FnRetType = FD->getReturnType();
2635 } else if (CurCap->HasImplicitReturnType) {
2636 // For blocks/lambdas with implicit return types, we check each return
2637 // statement individually, and deduce the common return type when the block
2638 // or lambda is completed.
2639 // FIXME: Fold this into the 'auto' codepath above.
2640 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
2641 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2642 if (Result.isInvalid())
2644 RetValExp = Result.get();
2646 // DR1048: even prior to C++14, we should use the 'auto' deduction rules
2647 // when deducing a return type for a lambda-expression (or by extension
2648 // for a block). These rules differ from the stated C++11 rules only in
2649 // that they remove top-level cv-qualifiers.
2650 if (!CurContext->isDependentContext())
2651 FnRetType = RetValExp->getType().getUnqualifiedType();
2653 FnRetType = CurCap->ReturnType = Context.DependentTy;
2656 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2657 // initializer list, because it is not an expression (even
2658 // though we represent it as one). We still deduce 'void'.
2659 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2660 << RetValExp->getSourceRange();
2663 FnRetType = Context.VoidTy;
2666 // Although we'll properly infer the type of the block once it's completed,
2667 // make sure we provide a return type now for better error recovery.
2668 if (CurCap->ReturnType.isNull())
2669 CurCap->ReturnType = FnRetType;
2671 assert(!FnRetType.isNull());
2673 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
2674 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2675 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2678 } else if (CapturedRegionScopeInfo *CurRegion =
2679 dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
2680 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
2683 assert(CurLambda && "unknown kind of captured scope");
2684 if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
2685 ->getNoReturnAttr()) {
2686 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2691 // Otherwise, verify that this result type matches the previous one. We are
2692 // pickier with blocks than for normal functions because we don't have GCC
2693 // compatibility to worry about here.
2694 const VarDecl *NRVOCandidate = nullptr;
2695 if (FnRetType->isDependentType()) {
2696 // Delay processing for now. TODO: there are lots of dependent
2697 // types we can conclusively prove aren't void.
2698 } else if (FnRetType->isVoidType()) {
2699 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
2700 !(getLangOpts().CPlusPlus &&
2701 (RetValExp->isTypeDependent() ||
2702 RetValExp->getType()->isVoidType()))) {
2703 if (!getLangOpts().CPlusPlus &&
2704 RetValExp->getType()->isVoidType())
2705 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
2707 Diag(ReturnLoc, diag::err_return_block_has_expr);
2708 RetValExp = nullptr;
2711 } else if (!RetValExp) {
2712 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2713 } else if (!RetValExp->isTypeDependent()) {
2714 // we have a non-void block with an expression, continue checking
2716 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2717 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2720 // In C++ the return statement is handled via a copy initialization.
2721 // the C version of which boils down to CheckSingleAssignmentConstraints.
2722 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2723 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2725 NRVOCandidate != nullptr);
2726 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2727 FnRetType, RetValExp);
2728 if (Res.isInvalid()) {
2729 // FIXME: Cleanup temporaries here, anyway?
2732 RetValExp = Res.get();
2733 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
2735 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2739 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2742 RetValExp = ER.get();
2744 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2747 // If we need to check for the named return value optimization,
2748 // or if we need to infer the return type,
2749 // save the return statement in our scope for later processing.
2750 if (CurCap->HasImplicitReturnType || NRVOCandidate)
2751 FunctionScopes.back()->Returns.push_back(Result);
2757 /// \brief Marks all typedefs in all local classes in a type referenced.
2759 /// In a function like
2761 /// struct S { typedef int a; };
2765 /// the local type escapes and could be referenced in some TUs but not in
2766 /// others. Pretend that all local typedefs are always referenced, to not warn
2767 /// on this. This isn't necessary if f has internal linkage, or the typedef
2769 class LocalTypedefNameReferencer
2770 : public RecursiveASTVisitor<LocalTypedefNameReferencer> {
2772 LocalTypedefNameReferencer(Sema &S) : S(S) {}
2773 bool VisitRecordType(const RecordType *RT);
2777 bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) {
2778 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl());
2779 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
2780 R->isDependentType())
2782 for (auto *TmpD : R->decls())
2783 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD))
2784 if (T->getAccess() != AS_private || R->hasFriends())
2785 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false);
2790 TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const {
2791 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens();
2792 while (auto ATL = TL.getAs<AttributedTypeLoc>())
2793 TL = ATL.getModifiedLoc().IgnoreParens();
2794 return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc();
2797 /// Deduce the return type for a function from a returned expression, per
2798 /// C++1y [dcl.spec.auto]p6.
2799 bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
2800 SourceLocation ReturnLoc,
2803 TypeLoc OrigResultType = getReturnTypeLoc(FD);
2806 if (RetExpr && isa<InitListExpr>(RetExpr)) {
2807 // If the deduction is for a return statement and the initializer is
2808 // a braced-init-list, the program is ill-formed.
2809 Diag(RetExpr->getExprLoc(),
2810 getCurLambda() ? diag::err_lambda_return_init_list
2811 : diag::err_auto_fn_return_init_list)
2812 << RetExpr->getSourceRange();
2816 if (FD->isDependentContext()) {
2817 // C++1y [dcl.spec.auto]p12:
2818 // Return type deduction [...] occurs when the definition is
2819 // instantiated even if the function body contains a return
2820 // statement with a non-type-dependent operand.
2821 assert(AT->isDeduced() && "should have deduced to dependent type");
2823 } else if (RetExpr) {
2824 // If the deduction is for a return statement and the initializer is
2825 // a braced-init-list, the program is ill-formed.
2826 if (isa<InitListExpr>(RetExpr)) {
2827 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_return_init_list);
2831 // Otherwise, [...] deduce a value for U using the rules of template
2832 // argument deduction.
2833 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
2835 if (DAR == DAR_Failed && !FD->isInvalidDecl())
2836 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
2837 << OrigResultType.getType() << RetExpr->getType();
2839 if (DAR != DAR_Succeeded)
2842 // If a local type is part of the returned type, mark its fields as
2844 LocalTypedefNameReferencer Referencer(*this);
2845 Referencer.TraverseType(RetExpr->getType());
2847 // In the case of a return with no operand, the initializer is considered
2850 // Deduction here can only succeed if the return type is exactly 'cv auto'
2851 // or 'decltype(auto)', so just check for that case directly.
2852 if (!OrigResultType.getType()->getAs<AutoType>()) {
2853 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
2854 << OrigResultType.getType();
2857 // We always deduce U = void in this case.
2858 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
2859 if (Deduced.isNull())
2863 // If a function with a declared return type that contains a placeholder type
2864 // has multiple return statements, the return type is deduced for each return
2865 // statement. [...] if the type deduced is not the same in each deduction,
2866 // the program is ill-formed.
2867 if (AT->isDeduced() && !FD->isInvalidDecl()) {
2868 AutoType *NewAT = Deduced->getContainedAutoType();
2869 if (!FD->isDependentContext() &&
2870 !Context.hasSameType(AT->getDeducedType(), NewAT->getDeducedType())) {
2871 const LambdaScopeInfo *LambdaSI = getCurLambda();
2872 if (LambdaSI && LambdaSI->HasImplicitReturnType) {
2873 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
2874 << NewAT->getDeducedType() << AT->getDeducedType()
2875 << true /*IsLambda*/;
2877 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
2878 << (AT->isDecltypeAuto() ? 1 : 0)
2879 << NewAT->getDeducedType() << AT->getDeducedType();
2883 } else if (!FD->isInvalidDecl()) {
2884 // Update all declarations of the function to have the deduced return type.
2885 Context.adjustDeducedFunctionResultType(FD, Deduced);
2892 Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
2894 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
2895 if (R.isInvalid()) {
2900 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
2901 CurScope->addNRVOCandidate(VD);
2903 CurScope->setNoNRVO();
2909 StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2910 // Check for unexpanded parameter packs.
2911 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2914 if (isa<CapturingScopeInfo>(getCurFunction()))
2915 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
2918 QualType RelatedRetType;
2919 const AttrVec *Attrs = nullptr;
2920 bool isObjCMethod = false;
2922 if (const FunctionDecl *FD = getCurFunctionDecl()) {
2923 FnRetType = FD->getReturnType();
2925 Attrs = &FD->getAttrs();
2926 if (FD->isNoReturn())
2927 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
2928 << FD->getDeclName();
2929 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2930 FnRetType = MD->getReturnType();
2931 isObjCMethod = true;
2933 Attrs = &MD->getAttrs();
2934 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2935 // In the implementation of a method with a related return type, the
2936 // type used to type-check the validity of return statements within the
2937 // method body is a pointer to the type of the class being implemented.
2938 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2939 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
2941 } else // If we don't have a function/method context, bail.
2944 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
2946 if (getLangOpts().CPlusPlus14) {
2947 if (AutoType *AT = FnRetType->getContainedAutoType()) {
2948 FunctionDecl *FD = cast<FunctionDecl>(CurContext);
2949 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2950 FD->setInvalidDecl();
2953 FnRetType = FD->getReturnType();
2958 bool HasDependentReturnType = FnRetType->isDependentType();
2960 ReturnStmt *Result = nullptr;
2961 if (FnRetType->isVoidType()) {
2963 if (isa<InitListExpr>(RetValExp)) {
2964 // We simply never allow init lists as the return value of void
2965 // functions. This is compatible because this was never allowed before,
2966 // so there's no legacy code to deal with.
2967 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2968 int FunctionKind = 0;
2969 if (isa<ObjCMethodDecl>(CurDecl))
2971 else if (isa<CXXConstructorDecl>(CurDecl))
2973 else if (isa<CXXDestructorDecl>(CurDecl))
2976 Diag(ReturnLoc, diag::err_return_init_list)
2977 << CurDecl->getDeclName() << FunctionKind
2978 << RetValExp->getSourceRange();
2980 // Drop the expression.
2981 RetValExp = nullptr;
2982 } else if (!RetValExp->isTypeDependent()) {
2983 // C99 6.8.6.4p1 (ext_ since GCC warns)
2984 unsigned D = diag::ext_return_has_expr;
2985 if (RetValExp->getType()->isVoidType()) {
2986 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2987 if (isa<CXXConstructorDecl>(CurDecl) ||
2988 isa<CXXDestructorDecl>(CurDecl))
2989 D = diag::err_ctor_dtor_returns_void;
2991 D = diag::ext_return_has_void_expr;
2994 ExprResult Result = RetValExp;
2995 Result = IgnoredValueConversions(Result.get());
2996 if (Result.isInvalid())
2998 RetValExp = Result.get();
2999 RetValExp = ImpCastExprToType(RetValExp,
3000 Context.VoidTy, CK_ToVoid).get();
3002 // return of void in constructor/destructor is illegal in C++.
3003 if (D == diag::err_ctor_dtor_returns_void) {
3004 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3006 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
3007 << RetValExp->getSourceRange();
3009 // return (some void expression); is legal in C++.
3010 else if (D != diag::ext_return_has_void_expr ||
3011 !getLangOpts().CPlusPlus) {
3012 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
3014 int FunctionKind = 0;
3015 if (isa<ObjCMethodDecl>(CurDecl))
3017 else if (isa<CXXConstructorDecl>(CurDecl))
3019 else if (isa<CXXDestructorDecl>(CurDecl))
3023 << CurDecl->getDeclName() << FunctionKind
3024 << RetValExp->getSourceRange();
3029 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3032 RetValExp = ER.get();
3036 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
3037 } else if (!RetValExp && !HasDependentReturnType) {
3038 FunctionDecl *FD = getCurFunctionDecl();
3041 if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) {
3042 // C++11 [stmt.return]p2
3043 DiagID = diag::err_constexpr_return_missing_expr;
3044 FD->setInvalidDecl();
3045 } else if (getLangOpts().C99) {
3046 // C99 6.8.6.4p1 (ext_ since GCC warns)
3047 DiagID = diag::ext_return_missing_expr;
3050 DiagID = diag::warn_return_missing_expr;
3054 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
3056 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
3058 Result = new (Context) ReturnStmt(ReturnLoc);
3060 assert(RetValExp || HasDependentReturnType);
3061 const VarDecl *NRVOCandidate = nullptr;
3063 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
3065 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
3066 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
3069 // In C++ the return statement is handled via a copy initialization,
3070 // the C version of which boils down to CheckSingleAssignmentConstraints.
3072 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
3073 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
3074 // we have a non-void function with an expression, continue checking
3075 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
3077 NRVOCandidate != nullptr);
3078 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
3079 RetType, RetValExp);
3080 if (Res.isInvalid()) {
3081 // FIXME: Clean up temporaries here anyway?
3084 RetValExp = Res.getAs<Expr>();
3086 // If we have a related result type, we need to implicitly
3087 // convert back to the formal result type. We can't pretend to
3088 // initialize the result again --- we might end double-retaining
3089 // --- so instead we initialize a notional temporary.
3090 if (!RelatedRetType.isNull()) {
3091 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3093 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3094 if (Res.isInvalid()) {
3095 // FIXME: Clean up temporaries here anyway?
3098 RetValExp = Res.getAs<Expr>();
3101 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3102 getCurFunctionDecl());
3106 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3109 RetValExp = ER.get();
3111 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
3114 // If we need to check for the named return value optimization, save the
3115 // return statement in our scope for later processing.
3116 if (Result->getNRVOCandidate())
3117 FunctionScopes.back()->Returns.push_back(Result);
3123 Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
3124 SourceLocation RParen, Decl *Parm,
3126 VarDecl *Var = cast_or_null<VarDecl>(Parm);
3127 if (Var && Var->isInvalidDecl())
3130 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
3134 Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
3135 return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
3139 Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3140 MultiStmtArg CatchStmts, Stmt *Finally) {
3141 if (!getLangOpts().ObjCExceptions)
3142 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3144 getCurFunction()->setHasBranchProtectedScope();
3145 unsigned NumCatchStmts = CatchStmts.size();
3146 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3147 NumCatchStmts, Finally);
3150 StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
3152 ExprResult Result = DefaultLvalueConversion(Throw);
3153 if (Result.isInvalid())
3156 Result = ActOnFinishFullExpr(Result.get());
3157 if (Result.isInvalid())
3159 Throw = Result.get();
3161 QualType ThrowType = Throw->getType();
3162 // Make sure the expression type is an ObjC pointer or "void *".
3163 if (!ThrowType->isDependentType() &&
3164 !ThrowType->isObjCObjectPointerType()) {
3165 const PointerType *PT = ThrowType->getAs<PointerType>();
3166 if (!PT || !PT->getPointeeType()->isVoidType())
3167 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
3168 << Throw->getType() << Throw->getSourceRange());
3172 return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
3176 Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3178 if (!getLangOpts().ObjCExceptions)
3179 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3182 // @throw without an expression designates a rethrow (which much occur
3183 // in the context of an @catch clause).
3184 Scope *AtCatchParent = CurScope;
3185 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3186 AtCatchParent = AtCatchParent->getParent();
3188 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
3190 return BuildObjCAtThrowStmt(AtLoc, Throw);
3194 Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3195 ExprResult result = DefaultLvalueConversion(operand);
3196 if (result.isInvalid())
3198 operand = result.get();
3200 // Make sure the expression type is an ObjC pointer or "void *".
3201 QualType type = operand->getType();
3202 if (!type->isDependentType() &&
3203 !type->isObjCObjectPointerType()) {
3204 const PointerType *pointerType = type->getAs<PointerType>();
3205 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) {
3206 if (getLangOpts().CPlusPlus) {
3207 if (RequireCompleteType(atLoc, type,
3208 diag::err_incomplete_receiver_type))
3209 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3210 << type << operand->getSourceRange();
3212 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
3213 if (!result.isUsable())
3214 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3215 << type << operand->getSourceRange();
3217 operand = result.get();
3219 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3220 << type << operand->getSourceRange();
3225 // The operand to @synchronized is a full-expression.
3226 return ActOnFinishFullExpr(operand);
3230 Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3232 // We can't jump into or indirect-jump out of a @synchronized block.
3233 getCurFunction()->setHasBranchProtectedScope();
3234 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
3237 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3238 /// and creates a proper catch handler from them.
3240 Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
3241 Stmt *HandlerBlock) {
3242 // There's nothing to test that ActOnExceptionDecl didn't already test.
3243 return new (Context)
3244 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
3248 Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3249 getCurFunction()->setHasBranchProtectedScope();
3250 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
3255 class TypeWithHandler {
3259 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
3260 : t(type), stmt(statement) {}
3262 // An arbitrary order is fine as long as it places identical
3263 // types next to each other.
3264 bool operator<(const TypeWithHandler &y) const {
3265 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
3267 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
3270 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
3273 bool operator==(const TypeWithHandler& other) const {
3274 return t == other.t;
3277 CXXCatchStmt *getCatchStmt() const { return stmt; }
3278 SourceLocation getTypeSpecStartLoc() const {
3279 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
3285 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3286 /// handlers and creates a try statement from them.
3287 StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3288 ArrayRef<Stmt *> Handlers) {
3289 // Don't report an error if 'try' is used in system headers.
3290 if (!getLangOpts().CXXExceptions &&
3291 !getSourceManager().isInSystemHeader(TryLoc))
3292 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
3294 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
3295 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
3297 const unsigned NumHandlers = Handlers.size();
3298 assert(NumHandlers > 0 &&
3299 "The parser shouldn't call this if there are no handlers.");
3301 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
3303 for (unsigned i = 0; i < NumHandlers; ++i) {
3304 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
3305 if (!Handler->getExceptionDecl()) {
3306 if (i < NumHandlers - 1)
3307 return StmtError(Diag(Handler->getLocStart(),
3308 diag::err_early_catch_all));
3313 const QualType CaughtType = Handler->getCaughtType();
3314 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
3315 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
3318 // Detect handlers for the same type as an earlier one.
3319 if (NumHandlers > 1) {
3320 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
3322 TypeWithHandler prev = TypesWithHandlers[0];
3323 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
3324 TypeWithHandler curr = TypesWithHandlers[i];
3327 Diag(curr.getTypeSpecStartLoc(),
3328 diag::warn_exception_caught_by_earlier_handler)
3329 << curr.getCatchStmt()->getCaughtType().getAsString();
3330 Diag(prev.getTypeSpecStartLoc(),
3331 diag::note_previous_exception_handler)
3332 << prev.getCatchStmt()->getCaughtType().getAsString();
3339 getCurFunction()->setHasBranchProtectedScope();
3341 // FIXME: We should detect handlers that cannot catch anything because an
3342 // earlier handler catches a superclass. Need to find a method that is not
3343 // quadratic for this.
3344 // Neither of these are explicitly forbidden, but every compiler detects them
3347 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
3351 Sema::ActOnSEHTryBlock(bool IsCXXTry,
3352 SourceLocation TryLoc,
3355 assert(TryBlock && Handler);
3357 getCurFunction()->setHasBranchProtectedScope();
3359 return SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler);
3363 Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3366 assert(FilterExpr && Block);
3368 if(!FilterExpr->getType()->isIntegerType()) {
3369 return StmtError(Diag(FilterExpr->getExprLoc(),
3370 diag::err_filter_expression_integral)
3371 << FilterExpr->getType());
3374 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
3378 Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
3381 return SEHFinallyStmt::Create(Context,Loc,Block);
3385 Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
3386 Scope *SEHTryParent = CurScope;
3387 while (SEHTryParent && !SEHTryParent->isSEHTryScope())
3388 SEHTryParent = SEHTryParent->getParent();
3390 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
3392 return new (Context) SEHLeaveStmt(Loc);
3395 StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3397 NestedNameSpecifierLoc QualifierLoc,
3398 DeclarationNameInfo NameInfo,
3401 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
3402 QualifierLoc, NameInfo,
3403 cast<CompoundStmt>(Nested));
3407 StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
3410 UnqualifiedId &Name,
3412 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
3413 SS.getWithLocInContext(Context),
3414 GetNameFromUnqualifiedId(Name),
3419 Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
3420 unsigned NumParams) {
3421 DeclContext *DC = CurContext;
3422 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
3423 DC = DC->getParent();
3425 RecordDecl *RD = nullptr;
3426 if (getLangOpts().CPlusPlus)
3427 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
3430 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
3432 RD->setCapturedRecord();
3435 RD->startDefinition();
3437 assert(NumParams > 0 && "CapturedStmt requires context parameter");
3438 CD = CapturedDecl::Create(Context, CurContext, NumParams);
3443 static void buildCapturedStmtCaptureList(
3444 SmallVectorImpl<CapturedStmt::Capture> &Captures,
3445 SmallVectorImpl<Expr *> &CaptureInits,
3446 ArrayRef<CapturingScopeInfo::Capture> Candidates) {
3448 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
3449 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
3451 if (Cap->isThisCapture()) {
3452 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3453 CapturedStmt::VCK_This));
3454 CaptureInits.push_back(Cap->getInitExpr());
3456 } else if (Cap->isVLATypeCapture()) {
3458 CapturedStmt::Capture(Cap->getLocation(), CapturedStmt::VCK_VLAType));
3459 CaptureInits.push_back(nullptr);
3463 assert(Cap->isReferenceCapture() &&
3464 "non-reference capture not yet implemented");
3466 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3467 CapturedStmt::VCK_ByRef,
3468 Cap->getVariable()));
3469 CaptureInits.push_back(Cap->getInitExpr());
3473 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3474 CapturedRegionKind Kind,
3475 unsigned NumParams) {
3476 CapturedDecl *CD = nullptr;
3477 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
3479 // Build the context parameter
3480 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3481 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3482 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3483 ImplicitParamDecl *Param
3484 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3487 CD->setContextParam(0, Param);
3489 // Enter the capturing scope for this captured region.
3490 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3493 PushDeclContext(CurScope, CD);
3497 PushExpressionEvaluationContext(PotentiallyEvaluated);
3500 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3501 CapturedRegionKind Kind,
3502 ArrayRef<CapturedParamNameType> Params) {
3503 CapturedDecl *CD = nullptr;
3504 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
3506 // Build the context parameter
3507 DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3508 bool ContextIsFound = false;
3509 unsigned ParamNum = 0;
3510 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
3512 I != E; ++I, ++ParamNum) {
3513 if (I->second.isNull()) {
3514 assert(!ContextIsFound &&
3515 "null type has been found already for '__context' parameter");
3516 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3517 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3518 ImplicitParamDecl *Param
3519 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3521 CD->setContextParam(ParamNum, Param);
3522 ContextIsFound = true;
3524 IdentifierInfo *ParamName = &Context.Idents.get(I->first);
3525 ImplicitParamDecl *Param
3526 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second);
3528 CD->setParam(ParamNum, Param);
3531 assert(ContextIsFound && "no null type for '__context' parameter");
3532 if (!ContextIsFound) {
3533 // Add __context implicitly if it is not specified.
3534 IdentifierInfo *ParamName = &Context.Idents.get("__context");
3535 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3536 ImplicitParamDecl *Param =
3537 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3539 CD->setContextParam(ParamNum, Param);
3541 // Enter the capturing scope for this captured region.
3542 PushCapturedRegionScope(CurScope, CD, RD, Kind);
3545 PushDeclContext(CurScope, CD);
3549 PushExpressionEvaluationContext(PotentiallyEvaluated);
3552 void Sema::ActOnCapturedRegionError() {
3553 DiscardCleanupsInEvaluationContext();
3554 PopExpressionEvaluationContext();
3556 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3557 RecordDecl *Record = RSI->TheRecordDecl;
3558 Record->setInvalidDecl();
3560 SmallVector<Decl*, 4> Fields(Record->fields());
3561 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
3562 SourceLocation(), SourceLocation(), /*AttributeList=*/nullptr);
3565 PopFunctionScopeInfo();
3568 StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
3569 CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3571 SmallVector<CapturedStmt::Capture, 4> Captures;
3572 SmallVector<Expr *, 4> CaptureInits;
3573 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
3575 CapturedDecl *CD = RSI->TheCapturedDecl;
3576 RecordDecl *RD = RSI->TheRecordDecl;
3578 CapturedStmt *Res = CapturedStmt::Create(getASTContext(), S,
3579 RSI->CapRegionKind, Captures,
3580 CaptureInits, CD, RD);
3582 CD->setBody(Res->getCapturedStmt());
3583 RD->completeDefinition();
3585 DiscardCleanupsInEvaluationContext();
3586 PopExpressionEvaluationContext();
3589 PopFunctionScopeInfo();