Skip to content

Commit 1cdc7f8

Browse files
authored
[clang] [Sema] Suggest [[noreturn]] for void functions that always throw (#146234)
Implements #146223.
1 parent d1ba269 commit 1cdc7f8

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

clang/lib/Sema/SemaDeclAttr.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1979,6 +1979,10 @@ void clang::inferNoReturnAttr(Sema &S, const Decl *D) {
19791979
if (!FD->hasAttr<NoReturnAttr>() && !FD->hasAttr<InferredNoReturnAttr>() &&
19801980
isKnownToAlwaysThrow(FD)) {
19811981
NonConstFD->addAttr(InferredNoReturnAttr::CreateImplicit(S.Context));
1982+
1983+
// Emit a diagnostic suggesting the function being marked [[noreturn]].
1984+
S.Diag(FD->getLocation(), diag::warn_suggest_noreturn_function)
1985+
<< /*isFunction=*/0 << FD;
19821986
}
19831987
}
19841988

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// RUN: %clang_cc1 -fsyntax-only -fcxx-exceptions -fexceptions -Wreturn-type -Wmissing-noreturn -verify %s
2+
3+
namespace std {
4+
class string {
5+
public:
6+
string(const char*);
7+
};
8+
class runtime_error {
9+
public:
10+
runtime_error(const string&);
11+
};
12+
}
13+
14+
// This function always throws. Suggest [[noreturn]].
15+
void throwError(const std::string& msg) { // expected-warning {{function 'throwError' could be declared with attribute 'noreturn'}}
16+
throw std::runtime_error(msg);
17+
}
18+
19+
// The non-void caller should not warn about missing return.
20+
int ensureZero(int i) {
21+
if (i == 0) return 0;
22+
throwError("ERROR"); // no-warning
23+
}

0 commit comments

Comments
 (0)