diff --git a/clang-tools-extra/test/clang-tidy/checkers/bugprone/unchecked-optional-access.cpp b/clang-tools-extra/test/clang-tidy/checkers/bugprone/unchecked-optional-access.cpp index 3167b85f0e024..084ec84d02937 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/bugprone/unchecked-optional-access.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone/unchecked-optional-access.cpp @@ -141,6 +141,39 @@ void nullable_value_after_swap(BloombergLP::bdlb::NullableValue &opt1, Bloo } } +void assertion_handler_imp() __attribute__((analyzer_noreturn)); + +void assertion_handler(); + +void assertion_handler() { + do { + assertion_handler_imp(); + } while(0); +} + +void function_calling_analyzer_noreturn(const bsl::optional& opt) +{ + if (!opt) { + assertion_handler(); // This will be deduced to have an implicit `analyzer_noreturn` attribute. + } + + *opt; // no-warning: The previous condition guards this dereference. +} + +// Should be considered as 'noreturn' by CFG +void halt() { + for(;;) {} +} + +void function_calling_no_return_from_cfg(const bsl::optional& opt) +{ + if (!opt) { + halt(); + } + + *opt; // no-warning: The previous condition guards this dereference. +} + template void function_template_without_user(const absl::optional &opt) { opt.value(); // no-warning diff --git a/clang/include/clang/AST/Decl.h b/clang/include/clang/AST/Decl.h index 3d7969cca83fd..62d8dad48768b 100644 --- a/clang/include/clang/AST/Decl.h +++ b/clang/include/clang/AST/Decl.h @@ -2648,6 +2648,14 @@ class FunctionDecl : public DeclaratorDecl, /// an attribute on its declaration or its type. bool isNoReturn() const; + /// Determines whether this function is known to never return for CFG + /// analysis. Checks for noreturn attributes on the function declaration + /// or its type, including 'analyzer_noreturn' attribute. + /// + /// Returns 'std::nullopt' if function declaration has no '*noreturn' + /// attributes + std::optional getAnalyzerNoReturn() const; + /// True if the function was a definition but its body was skipped. bool hasSkippedBody() const { return FunctionDeclBits.HasSkippedBody; } void setHasSkippedBody(bool Skipped = true) { diff --git a/clang/include/clang/Basic/Attr.td b/clang/include/clang/Basic/Attr.td index 224cb6a32af28..671f9ef6ef159 100644 --- a/clang/include/clang/Basic/Attr.td +++ b/clang/include/clang/Basic/Attr.td @@ -974,7 +974,8 @@ def AnalyzerNoReturn : InheritableAttr { // vendor namespace, or should it use a vendor namespace specific to the // analyzer? let Spellings = [GNU<"analyzer_noreturn">]; - // TODO: Add subject list. + let Args = [DefaultBoolArgument<"Value", /*default=*/1, /*fake=*/0>]; + let Subjects = SubjectList<[Function]>; let Documentation = [Undocumented]; } diff --git a/clang/lib/AST/Decl.cpp b/clang/lib/AST/Decl.cpp index bd1b5950d30a6..8bdfd4cf92fd5 100644 --- a/clang/lib/AST/Decl.cpp +++ b/clang/lib/AST/Decl.cpp @@ -3596,6 +3596,16 @@ bool FunctionDecl::isNoReturn() const { return false; } +std::optional FunctionDecl::getAnalyzerNoReturn() const { + if (isNoReturn()) + return true; + + if (auto *Attr = getAttr()) + return Attr->getValue(); + + return std::nullopt; +} + bool FunctionDecl::isMemberLikeConstrainedFriend() const { // C++20 [temp.friend]p9: // A non-template friend declaration with a requires-clause [or] diff --git a/clang/lib/Analysis/CFG.cpp b/clang/lib/Analysis/CFG.cpp index d960d5130332b..c220a3fd9702d 100644 --- a/clang/lib/Analysis/CFG.cpp +++ b/clang/lib/Analysis/CFG.cpp @@ -2833,8 +2833,8 @@ CFGBlock *CFGBuilder::VisitCallExpr(CallExpr *C, AddStmtChoice asc) { if (!FD->isVariadic()) findConstructionContextsForArguments(C); - if (FD->isNoReturn() || C->isBuiltinAssumeFalse(*Context)) - NoReturn = true; + NoReturn |= FD->getAnalyzerNoReturn().value_or(false) || C->isBuiltinAssumeFalse(*Context); + if (FD->hasAttr()) AddEHEdge = false; if (isBuiltinAssumeWithSideEffects(FD->getASTContext(), C) || @@ -6288,6 +6288,12 @@ void CFGBlock::printTerminatorJson(raw_ostream &Out, const LangOptions &LO, // There may be many more reasons why a sink would appear during analysis // (eg. checkers may generate sinks arbitrarily), but here we only consider // sinks that would be obvious by looking at the CFG. +// +// This function also performs inter-procedural analysis by recursively +// examining called functions to detect forwarding chains to noreturn +// functions. When a function is determined to never return through this +// analysis, it's automatically marked with analyzer_noreturn attribute +// for caching and future reference. static bool isImmediateSinkBlock(const CFGBlock *Blk) { if (Blk->hasNoReturnElement()) return true; @@ -6298,10 +6304,60 @@ static bool isImmediateSinkBlock(const CFGBlock *Blk) { // at least for now, but once we have better support for exceptions, // we'd need to carefully handle the case when the throw is being // immediately caught. - if (llvm::any_of(*Blk, [](const CFGElement &Elm) { + if (llvm::any_of(*Blk, [](const CFGElement &Elm) -> bool { + if (std::optional StmtElm = Elm.getAs()) + return isa(StmtElm->getStmt()); + return false; + })) + return true; + + auto HasNoReturnCall = [&](const CallExpr *CE) { + if (!CE) + return false; + + auto *FD = CE->getDirectCallee(); + + if (!FD) + return false; + + auto *CanCD = FD->getCanonicalDecl(); + auto *DefFD = CanCD->getDefinition(); + auto NoRetAttrOpt = CanCD->getAnalyzerNoReturn(); + auto NoReturn = false; + + if (!NoRetAttrOpt && DefFD && DefFD->getBody()) { + // HACK: we are gonna cache analysis result as implicit + // `analyzer_noreturn` attribute + auto *MutCD = const_cast(CanCD); + + // Mark function as `analyzer_noreturn(false)` to: + // * prevent infinite recursion in noreturn analysis + // * indicate that we've already analyzed(-ing) this function + // * serve as a safe default assumption (function may return) + MutCD->addAttr(AnalyzerNoReturnAttr::CreateImplicit( + CanCD->getASTContext(), false, CanCD->getLocation())); + + auto CalleeCFG = + CFG::buildCFG(DefFD, DefFD->getBody(), &DefFD->getASTContext(), {}); + + NoReturn = CalleeCFG && CalleeCFG->getEntry().isInevitablySinking(); + + // Override to `analyzer_noreturn(true)` + if (NoReturn) { + MutCD->dropAttr(); + MutCD->addAttr(AnalyzerNoReturnAttr::CreateImplicit( + CanCD->getASTContext(), NoReturn, CanCD->getLocation())); + } + + } else if (NoRetAttrOpt) + NoReturn = *NoRetAttrOpt; + + return NoReturn; + }; + + if (llvm::any_of(*Blk, [&](const CFGElement &Elm) { if (std::optional StmtElm = Elm.getAs()) - if (isa(StmtElm->getStmt())) - return true; + return HasNoReturnCall(dyn_cast(StmtElm->getStmt())); return false; })) return true; diff --git a/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp b/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp index 1113bbe7f4d9c..c799ca98e4a0d 100644 --- a/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp +++ b/clang/lib/Analysis/FlowSensitive/TypeErasedDataflowAnalysis.cpp @@ -283,7 +283,7 @@ computeBlockInputState(const CFGBlock &Block, AnalysisContext &AC) { JoinedStateBuilder Builder(AC, JoinBehavior); for (const CFGBlock *Pred : Preds) { // Skip if the `Block` is unreachable or control flow cannot get past it. - if (!Pred || Pred->hasNoReturnElement()) + if (!Pred || Pred->isInevitablySinking()) continue; // Skip if `Pred` was not evaluated yet. This could happen if `Pred` has a @@ -562,7 +562,7 @@ runTypeErasedDataflowAnalysis( BlockStates[Block->getBlockID()] = std::move(NewBlockState); // Do not add unreachable successor blocks to `Worklist`. - if (Block->hasNoReturnElement()) + if (Block->isInevitablySinking()) continue; Worklist.enqueueSuccessors(Block); diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp index 5f481ed1f7139..7d3b2d5d286c1 100644 --- a/clang/lib/Sema/SemaDeclAttr.cpp +++ b/clang/lib/Sema/SemaDeclAttr.cpp @@ -2060,7 +2060,23 @@ static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) { } } - D->addAttr(::new (S.Context) AnalyzerNoReturnAttr(S.Context, AL)); + bool Value = true; + + if (AL.getNumArgs() > 0) { + auto *E = AL.getArgAsExpr(0); + + if (S.CheckBooleanCondition(AL.getLoc(), E, true).isInvalid()) + return; + + if (!E->EvaluateAsBooleanCondition(Value, S.Context, true)) { + S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) + << AL << 1 << AANT_ArgumentIntOrBool << E->getSourceRange(); + + return; + } + } + + D->addAttr(::new (S.Context) AnalyzerNoReturnAttr(S.Context, AL, Value)); } // PS3 PPU-specific. diff --git a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp index 214aaee9f97f6..d1916673debb7 100644 --- a/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp +++ b/clang/unittests/Analysis/FlowSensitive/TransferTest.cpp @@ -5940,8 +5940,18 @@ TEST(TransferTest, ForStmtBranchExtendsFlowCondition) { TEST(TransferTest, ForStmtBranchWithoutConditionDoesNotExtendFlowCondition) { std::string Code = R"( void target(bool Foo) { - for (;;) { + unsigned i = 0; + + for (;;++i) { (void)0; + + // preventing CFG from considering this function + // as 'noreturn' + if (i == ~0) + break; + else + i = 0; + // [[loop_body]] } } @@ -5950,16 +5960,16 @@ TEST(TransferTest, ForStmtBranchWithoutConditionDoesNotExtendFlowCondition) { Code, [](const llvm::StringMap> &Results, ASTContext &ASTCtx) { - ASSERT_THAT(Results.keys(), UnorderedElementsAre("loop_body")); const Environment &LoopBodyEnv = getEnvironmentAtAnnotation(Results, "loop_body"); const ValueDecl *FooDecl = findValueDecl(ASTCtx, "Foo"); ASSERT_THAT(FooDecl, NotNull()); - auto &LoopBodyFooVal= getFormula(*FooDecl, LoopBodyEnv); + auto &LoopBodyFooVal = getFormula(*FooDecl, LoopBodyEnv); EXPECT_FALSE(LoopBodyEnv.proves(LoopBodyFooVal)); }); +}); } TEST(TransferTest, ContextSensitiveOptionDisabled) { diff --git a/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp b/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp index 9fb7bebdbe41e..0f51e7a64c9b0 100644 --- a/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp +++ b/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp @@ -49,6 +49,7 @@ using namespace ast_matchers; using llvm::IsStringMapEntry; using ::testing::DescribeMatcher; using ::testing::IsEmpty; +using ::testing::Not; using ::testing::NotNull; using ::testing::Test; using ::testing::UnorderedElementsAre; @@ -407,6 +408,7 @@ TEST_F(DiscardExprStateTest, CallWithParenExprTreatedCorrectly) { EXPECT_NE(CallExpectState.Env.getValue(FnToPtrDecay), nullptr); } + struct NonConvergingLattice { int State; @@ -441,7 +443,15 @@ class NonConvergingAnalysis TEST_F(DataflowAnalysisTest, NonConvergingAnalysis) { std::string Code = R"( void target() { - while(true) {} + unsigned i =0; + for(;;++i) { + // preventing CFG from considering this function + // as 'noreturn' + if (i == ~0) + break; + else + i = 0; + } } )"; auto Res = runAnalysis( @@ -693,6 +703,153 @@ TEST_F(NoreturnDestructorTest, ConditionalOperatorNestedBranchReturns) { // FIXME: Called functions at point `p` should contain only "foo". } +class AnalyzerNoreturnTest : public Test { +protected: + template + void runDataflow(llvm::StringRef Code, Matcher Expectations) { + tooling::FileContentMappings FilesContents; + FilesContents.push_back( + std::make_pair("noreturn_test_defs.h", R"( + void assertionHandler() __attribute__((analyzer_noreturn)); + + void assertionTrampoline() { + assertionHandler(); + } + + void trap() {} + )")); + FilesContents.push_back(std::make_pair( + "noreturn_test_defs_canonical.h", R"( + extern void assertionHandler(); + + void assertionSecondTrampoline() { + assertionHandler(); + } + )")); + FilesContents.push_back(std::make_pair( + "noreturn_test_defs_noretcfg.h", R"( + // will be marged as noreturn by CFG + void assertionHandler() { + for (;;) {} + } + + void assertionTrampoline() { + assertionHandler(); + } + + void trap() {} + )")); + + ASSERT_THAT_ERROR( + test::checkDataflow( + AnalysisInputs( + Code, ast_matchers::hasName("target"), + [](ASTContext &C, Environment &) { + return FunctionCallAnalysis(C); + }) + .withASTBuildArgs({"-fsyntax-only", "-std=c++17"}) + .withASTBuildVirtualMappedFiles(std::move(FilesContents)), + /*VerifyResults=*/ + [&Expectations]( + const llvm::StringMap< + DataflowAnalysisState> &Results, + const AnalysisOutputs &) { + EXPECT_THAT(Results, Expectations); + }), + llvm::Succeeded()); + } +}; + +TEST_F(AnalyzerNoreturnTest, Breathing) { + std::string Code = R"( + #include "noreturn_test_defs.h" + + void target() { + trap(); + // [[p]] + } + )"; + runDataflow(Code, UnorderedElementsAre(IsStringMapEntry( + "p", HoldsFunctionCallLattice(HasCalledFunctions( + UnorderedElementsAre("trap")))))); +} + +TEST_F(AnalyzerNoreturnTest, DirectNoReturnCall) { + std::string Code = R"( + #include "noreturn_test_defs.h" + + void target() { + assertionHandler(); + trap(); + // [[p]] + } + )"; + runDataflow(Code, Not(UnorderedElementsAre(IsStringMapEntry( + "p", HoldsFunctionCallLattice(HasCalledFunctions( + UnorderedElementsAre("trap"))))))); +} + +TEST_F(AnalyzerNoreturnTest, IndirectNoReturnCall) { + std::string Code = R"( + #include "noreturn_test_defs.h" + + void target() { + assertionTrampoline(); + trap(); + // [[p]] + } + )"; + runDataflow(Code, Not(UnorderedElementsAre(IsStringMapEntry( + "p", HoldsFunctionCallLattice(HasCalledFunctions( + UnorderedElementsAre("trap"))))))); +} + +TEST_F(AnalyzerNoreturnTest, CanonicalDeclCallCheck) { + std::string Code = R"( + #include "noreturn_test_defs.h" + #include "noreturn_test_defs_canonical.h" + + void target() { + assertionSecondTrampoline(); + trap(); + // [[p]] + } + )"; + runDataflow(Code, Not(UnorderedElementsAre(IsStringMapEntry( + "p", HoldsFunctionCallLattice(HasCalledFunctions( + UnorderedElementsAre("trap"))))))); +} + +TEST_F(AnalyzerNoreturnTest, NoReturnFromCFGCheck) { + std::string Code = R"( + #include "noreturn_test_defs_noretcfg.h" + + void target() { + assertionTrampoline(); + trap(); + // [[p]] + } + )"; + runDataflow(Code, Not(UnorderedElementsAre(IsStringMapEntry( + "p", HoldsFunctionCallLattice(HasCalledFunctions( + UnorderedElementsAre("trap"))))))); +} + +TEST_F(AnalyzerNoreturnTest, InfiniteLoop) { + std::string Code = R"( + #include "noreturn_test_defs.h" + + void target() { + while(true){} + trap(); + // [[p]] + } + )"; + runDataflow(Code, Not(UnorderedElementsAre(IsStringMapEntry( + "p", HoldsFunctionCallLattice(HasCalledFunctions( + UnorderedElementsAre("trap"))))))); +} + // Models an analysis that uses flow conditions. class SpecialBoolAnalysis final : public DataflowAnalysis {