[clang] c4092d3 - [Clang] warn on discarded [[nodiscard]] function results after casting in C (#104677)
via cfe-commits
cfe-commits at lists.llvm.org
Sun Aug 18 03:45:23 PDT 2024
Author: Oleksandr T.
Date: 2024-08-18T12:45:20+02:00
New Revision: c4092d326ae4989f54c5f01d3a077841fd76bc2f
URL: https://github.com/llvm/llvm-project/commit/c4092d326ae4989f54c5f01d3a077841fd76bc2f
DIFF: https://github.com/llvm/llvm-project/commit/c4092d326ae4989f54c5f01d3a077841fd76bc2f.diff
LOG: [Clang] warn on discarded [[nodiscard]] function results after casting in C (#104677)
Fixes #104391
Added:
Modified:
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaStmt.cpp
clang/test/Sema/c2x-nodiscard.c
Removed:
################################################################################
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 12a3707db8a39f..11301e4c7dc4a2 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -218,6 +218,8 @@ Improvements to Clang's diagnostics
- Clang now diagnoses the use of ``main`` in an ``extern`` context as invalid according to [basic.start.main] p3. Fixes #GH101512.
+- Clang now diagnoses when the result of a [[nodiscard]] function is discarded after being cast in C. Fixes #GH104391.
+
Improvements to Clang's time-trace
----------------------------------
diff --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp
index d283eaa511011b..ba681671eb3290 100644
--- a/clang/lib/Sema/SemaStmt.cpp
+++ b/clang/lib/Sema/SemaStmt.cpp
@@ -281,7 +281,8 @@ void Sema::DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID) {
E = WarnExpr;
if (const auto *Cast = dyn_cast<CastExpr>(E))
if (Cast->getCastKind() == CK_NoOp ||
- Cast->getCastKind() == CK_ConstructorConversion)
+ Cast->getCastKind() == CK_ConstructorConversion ||
+ Cast->getCastKind() == CK_IntegralCast)
E = Cast->getSubExpr()->IgnoreImpCasts();
if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
diff --git a/clang/test/Sema/c2x-nodiscard.c b/clang/test/Sema/c2x-nodiscard.c
index cb33c0c242e7db..f8b0567366465d 100644
--- a/clang/test/Sema/c2x-nodiscard.c
+++ b/clang/test/Sema/c2x-nodiscard.c
@@ -54,3 +54,9 @@ void test_missiles(void) {
launch_missiles();
}
+[[nodiscard]] int f3();
+
+void GH104391() {
+#define M (unsigned int) f3()
+ M; // expected-warning {{ignoring return value of function declared with 'nodiscard' attribute}}
+}
More information about the cfe-commits
mailing list