[clang] [clang] Generate note on declaration for nodiscard-related attributes (PR #112289)
Yihe Li via cfe-commits
cfe-commits at lists.llvm.org
Tue Oct 15 08:36:16 PDT 2024
================
@@ -204,23 +205,29 @@ static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
return true;
}
-static bool DiagnoseNoDiscard(Sema &S, const WarnUnusedResultAttr *A,
- SourceLocation Loc, SourceRange R1,
- SourceRange R2, bool IsCtor) {
+static bool DiagnoseNoDiscard(Sema &S, const NamedDecl *OffendingDecl,
+ const WarnUnusedResultAttr *A, SourceLocation Loc,
+ SourceRange R1, SourceRange R2, bool IsCtor) {
if (!A)
return false;
StringRef Msg = A->getMessage();
+ bool result;
if (Msg.empty()) {
if (IsCtor)
- return S.Diag(Loc, diag::warn_unused_constructor) << A << R1 << R2;
- return S.Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
- }
+ result = S.Diag(Loc, diag::warn_unused_constructor) << A << R1 << R2;
+ else
+ result = S.Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
+ } else if (IsCtor)
+ result = S.Diag(Loc, diag::warn_unused_constructor_msg)
+ << A << Msg << R1 << R2;
+ else
+ result = S.Diag(Loc, diag::warn_unused_result_msg) << A << Msg << R1 << R2;
- if (IsCtor)
- return S.Diag(Loc, diag::warn_unused_constructor_msg) << A << Msg << R1
- << R2;
- return S.Diag(Loc, diag::warn_unused_result_msg) << A << Msg << R1 << R2;
+ if (OffendingDecl)
----------------
Mick235711 wrote:
Well, the initial motivation for that if is the following call site:
```cpp
const NamedDecl *OffendingDecl;
const Attr *A;
std::tie(OffendingDecl, A) = CE->getUnusedResultAttr(Context);
if (DiagnoseNoDiscard(*this, OffendingDecl,
cast_or_null<WarnUnusedResultAttr>(A), Loc, R1, R2,
/*isCtor=*/false))
return;
```
In `CallExpr::getUnusedResultAttr` we tried to see if the callee is marked nodiscard and if so, returns that instead. However `getCalleeDecl()` returns a `const Decl *`, but the diagnostic requires a `const NamedDecl *`, so I dyn_cast it down. If the actual dynamic type is always NamedDecl or its subclass, maybe here the return value cannot ever be `nullptr` to begin with? I was not sure about this so I added the check.
https://github.com/llvm/llvm-project/pull/112289
More information about the cfe-commits
mailing list