Skip to content

[clang]: Propagate *noreturn attributes in CFG #146355

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 19 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,39 @@ void nullable_value_after_swap(BloombergLP::bdlb::NullableValue<int> &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<int>& 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<int>& opt)
{
if (!opt) {
halt();
}

*opt; // no-warning: The previous condition guards this dereference.
}

template <typename T>
void function_template_without_user(const absl::optional<T> &opt) {
opt.value(); // no-warning
Expand Down
8 changes: 8 additions & 0 deletions clang/include/clang/AST/Decl.h
Original file line number Diff line number Diff line change
Expand Up @@ -2668,6 +2668,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<bool> getAnalyzerNoReturn() const;
Comment on lines +2671 to +2677
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The name of this function would suggest that it only checks the presence of analyzer_noreturn.
How about if we would rename this to something like isNoreturnForAnalyses?

BTW, how about other callables that are not FunctionDecls?
Such as ObjCMethodDecl or BlockDecl?


/// True if the function was a definition but its body was skipped.
bool hasSkippedBody() const { return FunctionDeclBits.HasSkippedBody; }
void setHasSkippedBody(bool Skipped = true) {
Expand Down
3 changes: 2 additions & 1 deletion clang/include/clang/Basic/Attr.td
Original file line number Diff line number Diff line change
Expand Up @@ -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]>;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we could attach this attribute to ObjCMethodDecl and BlockDecl too.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we could attach this attribute to ObjCMethodDecl and BlockDecl too.

I'd prefer not to overcomplicate things right now and just focus on the core approach and C++ implementation - mainly because I'm completely clueless about testing ObjC code =)

let Documentation = [Undocumented];
}

Expand Down
10 changes: 10 additions & 0 deletions clang/lib/AST/Decl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3596,6 +3596,16 @@ bool FunctionDecl::isNoReturn() const {
return false;
}

std::optional<bool> FunctionDecl::getAnalyzerNoReturn() const {
if (isNoReturn())
return true;

if (auto *Attr = getAttr<AnalyzerNoReturnAttr>())
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]
Expand Down
66 changes: 61 additions & 5 deletions clang/lib/Analysis/CFG.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<NoThrowAttr>())
AddEHEdge = false;
if (isBuiltinAssumeWithSideEffects(FD->getASTContext(), C) ||
Expand Down Expand Up @@ -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;
Expand All @@ -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<CFGStmt> StmtElm = Elm.getAs<CFGStmt>())
return isa<CXXThrowExpr>(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<FunctionDecl *>(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 =
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While performance-wise this is a big step ahead, we might still end up building the CFG twice for large functions. Once when we first do this inter-procedural no-return analysis and once when we run the actual analysis on them. Did you do any benchmarking if this has any affect on the compilation with some of the frequently used configurations? (default warnings, -Wall, -Wall -Wextra)

In case there is a measurable regression, we might want to move this behind a flag.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've discussed this with @Xazax-hun and I agree with him that we should have a look at the performance of some warnings. I think they live under the AnalysisBasedWarnings.cpp file.
There could be many, but I can recall one which is the noreturn analysis, like CheckFallThrough.

Another problem with the use of this analyzer_noreturn(bool) attribute is that it will basically touch/pollute every FunctionDecl in the AST - if I understand it correctly.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@steakhal @Xazax-hun I'm thinking about making this feature configurable through a flag. It will clearly have significant performance implications, but it's really only required for specific use cases (like clang-tidy checkers). It might be safer to explicitly opt-in only where necessary and where performance drops are more acceptable (e.g., in the unchecked-optional-access checker)

CFG::buildCFG(DefFD, DefFD->getBody(), &DefFD->getASTContext(), {});

NoReturn = CalleeCFG && CalleeCFG->getEntry().isInevitablySinking();

// Override to `analyzer_noreturn(true)`
if (NoReturn) {
MutCD->dropAttr<AnalyzerNoReturnAttr>();
MutCD->addAttr(AnalyzerNoReturnAttr::CreateImplicit(
CanCD->getASTContext(), NoReturn, CanCD->getLocation()));
Comment on lines +6347 to +6349
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another problem with this attribute that we drop the previous one.
In essence, subsequently we wouldn't be able to tell if this was a deduced attribute or one that was spelled in source.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We will drop this attribute only if we've created it before:

    auto *CanCD = FD->getCanonicalDecl();
    auto *DefFD = CanCD->getDefinition();
    auto NoRetAttrOpt = CanCD->getAnalyzerNoReturn();
    auto NoReturn = false;
    
    if (!NoRetAttrOpt && DefFD && DefFD->getBody()) {
        ...
        // Override to `analyzer_noreturn(true)`
        if (NoReturn) {
    

}

} else if (NoRetAttrOpt)
NoReturn = *NoRetAttrOpt;

return NoReturn;
};

if (llvm::any_of(*Blk, [&](const CFGElement &Elm) {
if (std::optional<CFGStmt> StmtElm = Elm.getAs<CFGStmt>())
if (isa<CXXThrowExpr>(StmtElm->getStmt()))
return true;
return HasNoReturnCall(dyn_cast<CallExpr>(StmtElm->getStmt()));
return false;
}))
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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);
Expand Down
18 changes: 17 additions & 1 deletion clang/lib/Sema/SemaDeclAttr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
16 changes: 13 additions & 3 deletions clang/unittests/Analysis/FlowSensitive/TransferTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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]]
}
}
Expand All @@ -5950,16 +5960,16 @@ TEST(TransferTest, ForStmtBranchWithoutConditionDoesNotExtendFlowCondition) {
Code,
[](const llvm::StringMap<DataflowAnalysisState<NoopLattice>> &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) {
Expand Down
Loading