Repository navigation
[clang][Sema] Check -Wunused-private-field at template instantiation instead of definition - #237374
Conversation
|
@llvm/pr-subscribers-compiler-rt-sanitizer @llvm/pr-subscribers-clang Author: Nick Desaulniers (nickdesaulniers) ChangesDon't warn when the use is in a templated function. Fixes: #237370 2 Files Affected:
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 0fe0daa71c1bcf..90f6f54a41fb5c 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -3494,17 +3494,14 @@ inline static bool HasAttribute(const QualType &T) {
}
static bool IsUnusedPrivateField(const FieldDecl *FD) {
- if (FD->getAccess() == AS_private && FD->getDeclName()) {
- QualType FieldType = FD->getType();
- if (HasAttribute<WarnUnusedAttr>(FieldType))
- return true;
+ if (FD->isImplicit() || !FD->getDeclName() || FD->getAccess() != AS_private ||
+ FD->hasAttr<UnusedAttr>() || FD->getParent()->isDependentContext())
+ return false;
- return !FD->isImplicit() && !FD->hasAttr<UnusedAttr>() &&
- !FD->getParent()->isDependentContext() &&
- !HasAttribute<UnusedAttr>(FieldType) &&
- !InitializationHasSideEffects(*FD);
- }
- return false;
+ QualType FieldType = FD->getType();
+ return !HasAttribute<UnusedAttr>(FieldType) &&
+ (HasAttribute<WarnUnusedAttr>(FieldType) ||
+ !InitializationHasSideEffects(*FD));
}
NamedDecl *
diff --git a/clang/test/SemaCXX/warn-unused-private-field.cpp b/clang/test/SemaCXX/warn-unused-private-field.cpp
index 0bcca6b82227f9..e8e6130801d560 100644
--- a/clang/test/SemaCXX/warn-unused-private-field.cpp
+++ b/clang/test/SemaCXX/warn-unused-private-field.cpp
@@ -354,3 +354,25 @@ class C {
T t2; // ok
};
}
+
+namespace warn_unused_template {
+struct [[gnu::warn_unused]] WarnUnusedType {};
+
+template <typename T>
+struct Outer {
+ class Inner {
+ friend struct Outer<T>;
+ WarnUnusedType field_;
+ };
+
+ WarnUnusedType use(Inner &i) {
+ return i.field_;
+ }
+};
+
+WarnUnusedType test() {
+ Outer<int> o;
+ Outer<int>::Inner i;
+ return o.use(i);
+}
+} // namespace warn_unused_template
|
|
cc @llvm/android-maintainers |
| namespace warn_unused_template { | ||
| struct [[gnu::warn_unused]] WarnUnusedType {}; | ||
|
|
||
| template <typename T> |
There was a problem hiding this comment.
Imagine we had Outer2 for this. where there is NOT a use of it. Will we still diagnose this on instantiation? So:
template<typename T>
struct Outer2 {
class Inner {
WarnUnusedType field_;
};
};
I would imagine that any instantiation of Outer2 that caused Inner to be instantiated would diagnose, right?
There was a problem hiding this comment.
ah, good point. In fixing the false-positive, I regressed the true positive case. Added exactly the case you described, and fixed that regression in fac498d.
There was a problem hiding this comment.
Sorry, it's not that I regressed the true positive case. As of fac498d, we now diagnose -Wunused-private-field at instantiation rather than definition, making this diagnostics better (IMO) overall. Let me rephrase the PR description (now that it's no longer just fixing a false positive) and send out pre-commits for compiler-rt and libc++.
There was a problem hiding this comment.
Hmmm...I think tackling this opened a can of worms. It led to:
- a revert Revert "[clang][Sema] Check -Wunused-private-field at template instantiation instead of definition" #243997
- a growing tail of template-instantiation edge cases Reapply "[clang][Sema] Check -Wunused-private-field at template instantiation instead of definition" (#243997) #244396 (comment)
As @kazutakahirata suggests, I think we should split this into smaller and more focused improvements.
Specifically, I think we should fix the false positive in #237370 first (restoring the isDependentContext() / UnusedAttr / isImplicit() checks before WarnUnusedAttr in IsUnusedPrivateField(), like the initial revision of this PR) — at the cost of losing true-positive coverage for unused [[gnu::warn_unused]] private fields inside class templates (Outer2) until we can land smaller, targeted follow-up PRs improving -Wunused-private-field for templates in general.
Two reasons that tradeoff seems worthwhile for now:
- Clang already skips -Wunused-private-field in dependent contexts for all other types (e.g., int) — Outer2 only warned by accident because 5dab5bf checked WarnUnusedAttr before isDependentContext() on the uninstantiated pattern, which is the exact bug causing -Wunused-private-field false positive on template instantiated uses #237370.
- Even restricting instantiation-time checking (VisitFieldDecl) to just [[gnu::warn_unused]] types runs into the same false positives (if constexpr, friend member/nested templates, explicit member specializations, offsetof, etc.), since libc++ now annotates std::vector/std::string/std::mutex with [[gnu::warn_unused]].
@erichkeane , would you be okay with landing the minimal false-positive fix first so [[gnu::warn_unused]] matches the rest of -Wunused-private-field in dependent contexts, and leaving instantiation-time checking for class templates (Outer2, etc.) to smaller, targeted follow-up PRs?
There was a problem hiding this comment.
I am behind mentally on all of this, and am not going to cathc myself back up :D But replacing the 'false positive' problems with a touch of 'false negatives' is typically acceptable.
|
✅ With the latest revision this PR passed the C/C++ code formatter. |
🐧 Linux x64 Test Results
✅ The build succeeded and all tests passed. |
| return dyn_cast<FieldDecl>(CountDecl); | ||
| } | ||
|
|
||
| static bool InitializationHasSideEffects(const FieldDecl &FD) { |
There was a problem hiding this comment.
| static bool InitializationHasSideEffects(const FieldDecl &FD) { | |
| static bool initializationHasSideEffects(const FieldDecl &FD) { |
| return false; | ||
| } | ||
|
|
||
| template <typename AttrType> static bool HasAttribute(const QualType &T) { |
There was a problem hiding this comment.
| template <typename AttrType> static bool HasAttribute(const QualType &T) { | |
| template <typename AttrType> static bool hasAttribute(QualType T) { |
|
Presubmit failure: I need to clean up compiler-rt/lib/sanitizer_common/sanitizer_quarantine.h in this PR. |
|
libc++ needs some fixes, too: (many more, might split that out into its own patch for libc++) |
-Wunused-private-field will soon be able to flag fields in instantiated class templates. Land this in preparation. Link: #237374
-Wunused-private-field will soon be able to flag fields in instantiated class templates. Land this in preparation. Link: #237374
9f6b968 to
754f259
Compare
|
Landed the fixups in compiler-rt and libc++, rebased, squashed, and forced pushed. Assuming presubmit doesn't find any other instances across the llvm-project/ I need to go fix first, will carry the sticky approval from @erichkeane and land this tomorrow, unless there's further feedback before then. |
ah, missed one in libc++abi, brb |
In the 2026-11-14 nightly run both Clang-SNAPSHOT jobs failed in the build step. The snapshot had moved from LLVM commit 382aa9e364b7 to ab5a8378416f, which brought two changes that diagnose code in Bitcoin Core's master branch: - llvm/llvm-project#180955 makes `-Wunsequenced` report two unsequenced reads of a volatile object, which occur 14 times in src/secp256k1/src/modinv32_impl.h and modinv64_impl.h; - llvm/llvm-project#237374 makes `-Wunused-private-field` check instantiated class templates, which flags the STL node helper structs in src/memusage.h. With `CMAKE_COMPILE_WARNING_AS_ERROR=ON` both are errors, so the build stopped at about 20% and no tests ran. Downgrade the two diagnostics back to warnings with `APPEND_CFLAGS` and `APPEND_CXXFLAGS`, so that the jobs build and test again while the warnings stay visible on CDash. Every other warning remains an error. The fixes are pending in bitcoin-core/secp256k1#1998 and bitcoin/bitcoin#36869; each flag is to be dropped once its fix has reached Bitcoin Core's master branch. Co-Authored-By: Claude Fable 5.2 <[email protected]> Claude-Session: https://claude.ai/code/session_01VSoBw5FaujuSeyXxkmHWRf
The `stl_tree_node`, `list_node` and `unordered_node` class templates only mimic the layout of the standard library's container nodes, so that `sizeof` yields an estimate of the memory they use. Their fields are never accessed. Since llvm/llvm-project#237374, Clang 24 diagnoses these fields with `-Wunused-private-field`. This change drops the `private:` access specifiers. It does not affect the size or alignment of the structs, as all their fields keep the same access control, and it is consistent with `stl_shared_counter`.
…ublic b9a6b0c memusage: Make fields of STL helper structs public (Hennadii Stepanov) Pull request description: The `stl_tree_node`, `list_node` and `unordered_node` class templates only mimic the layout of the standard library's container nodes, so that `sizeof` yields an estimate of the memory they use. Their fields are never accessed. Since llvm/llvm-project#237374, Clang 24 diagnoses these fields with `-Wunused-private-field`: ```console $ cmake --build build [308/655] Building CXX object src/util/CMakeFiles/bitcoin_util.dir/__/logging.cpp.o In file included from ../src/logging.cpp:7: ../src/memusage.h:169:11: warning: private field 'ptr_next' is not used [-Wunused-private-field] 169 | void* ptr_next; | ^ ../src/memusage.h:170:11: warning: private field 'ptr_prev' is not used [-Wunused-private-field] 170 | void* ptr_prev; | ^ 2 warnings generated. [355/655] Building CXX object src/CMakeFiles/bitcoin_node.dir/kernel/disconnected_transactions.cpp.o In file included from ../src/kernel/disconnected_transactions.cpp:8: In file included from ../src/core_memusage.h:10: ../src/memusage.h:184:11: warning: private field 'ptr' is not used [-Wunused-private-field] 184 | void* ptr; | ^ ../src/memusage.h:169:11: warning: private field 'ptr_next' is not used [-Wunused-private-field] 169 | void* ptr_next; | ^ ../src/memusage.h:170:11: warning: private field 'ptr_prev' is not used [-Wunused-private-field] 170 | void* ptr_prev; | ^ 3 warnings generated. [424/655] Building CXX object src/CMakeFiles/bitcoin_node.dir/txgraph.cpp.o In file included from ../src/txgraph.cpp:7: In file included from ../src/cluster_linearize.h:17: ../src/memusage.h:72:9: warning: private field 'color' is not used [-Wunused-private-field] 72 | int color; | ^ ../src/memusage.h:73:11: warning: private field 'parent' is not used [-Wunused-private-field] 73 | void* parent; | ^ ../src/memusage.h:74:11: warning: private field 'left' is not used [-Wunused-private-field] 74 | void* left; | ^ ../src/memusage.h:75:11: warning: private field 'right' is not used [-Wunused-private-field] 75 | void* right; | ^ 4 warnings generated. [425/655] Building CXX object src/CMakeFiles/bitcoin_node.dir/txmempool.cpp.o In file included from ../src/txmempool.cpp:6: In file included from ../src/txmempool.h:9: In file included from ../src/coins.h:11: In file included from ../src/core_memusage.h:10: ../src/memusage.h:72:9: warning: private field 'color' is not used [-Wunused-private-field] 72 | int color; | ^ ../src/memusage.h:73:11: warning: private field 'parent' is not used [-Wunused-private-field] 73 | void* parent; | ^ ../src/memusage.h:74:11: warning: private field 'left' is not used [-Wunused-private-field] 74 | void* left; | ^ ../src/memusage.h:75:11: warning: private field 'right' is not used [-Wunused-private-field] 75 | void* right; | ^ ../src/memusage.h:72:9: warning: private field 'color' is not used [-Wunused-private-field] 72 | int color; | ^ ../src/memusage.h:73:11: warning: private field 'parent' is not used [-Wunused-private-field] 73 | void* parent; | ^ ../src/memusage.h:74:11: warning: private field 'left' is not used [-Wunused-private-field] 74 | void* left; | ^ ../src/memusage.h:75:11: warning: private field 'right' is not used [-Wunused-private-field] 75 | void* right; | ^ ../src/memusage.h:72:9: warning: private field 'color' is not used [-Wunused-private-field] 72 | int color; | ^ ../src/memusage.h:73:11: warning: private field 'parent' is not used [-Wunused-private-field] 73 | void* parent; | ^ ../src/memusage.h:74:11: warning: private field 'left' is not used [-Wunused-private-field] 74 | void* left; | ^ ../src/memusage.h:75:11: warning: private field 'right' is not used [-Wunused-private-field] 75 | void* right; | ^ 12 warnings generated. [535/655] Building CXX object src/test/CMakeFiles/test_bitcoin.dir/disconnected_transactions.cpp.o In file included from ../src/test/disconnected_transactions.cpp:6: In file included from ../src/core_memusage.h:10: ../src/memusage.h:184:11: warning: private field 'ptr' is not used [-Wunused-private-field] 184 | void* ptr; | ^ 1 warning generated. [566/655] Building CXX object src/test/CMakeFiles/test_bitcoin.dir/pool_tests.cpp.o In file included from ../src/test/pool_tests.cpp:5: ../src/memusage.h:184:11: warning: private field 'ptr' is not used [-Wunused-private-field] 184 | void* ptr; | ^ 1 warning generated. [655/655] Linking CXX executable bin/test_bitcoin ``` This PR drops the `private:` access specifiers. It does not affect the size or alignment of the structs, as all their fields keep the same access control, and it is consistent with `stl_shared_counter`. ACKs for top commit: maflcko: lgtm ACK b9a6b0c l0rinc: ACK b9a6b0c Tree-SHA512: 380927f0302cbf7405d0f5236981c0f2b82681c0fb386d8e575be1751643a4bb1e6ffb643b999350c9cbc4579c116c2cb2f940e1c9e3655074bbcb014bf5a9c3
The `stl_tree_node`, `list_node` and `unordered_node` class templates only mimic the layout of the standard library's container nodes, so that `sizeof` yields an estimate of the memory they use. Their fields are never accessed. Since llvm/llvm-project#237374, Clang 24 diagnoses these fields with `-Wunused-private-field`. This change drops the `private:` access specifiers. It does not affect the size or alignment of the structs, as all their fields keep the same access control, and it is consistent with `stl_shared_counter`. Github-Pull: bitcoin#36869 Rebased-From: b9a6b0c
Upstream commit llvm/llvm-project@64969db fixes compiler-rt under new compiler warnings in llvm/llvm-project#237374
llvm/llvm-project#237374) strengthened the -Wunused-private-field warning. Upstream compiler-rt by fixed cases exposed by this in llvm/llvm-project@64969db so we can remove this once we roll that commit into our compiler-rt.
…15926) ## Motivation Removes the unused `se_number_total` member and its initializer from the test-local GpuSqttBuilder in `sqtt_builder_tests.cpp`. Upstream clang (llvm/llvm-project#237374, merged 2026-11-13) now checks `-Wunused-private-field` at template instantiation rather than definition, so this newly fails the `-Werror` CI build: ```error: private field 'se_number_total' is not used [-Werror,-Wunused-private-field]``` Deleted rather than `[[maybe_unused]]` because the field is never read, so removing it rather than annotate it. ## Issue Tracking JIRA ID: AIPROFSDK-1253 ## Submission Checklist - [ ] Look over the contributing guidelines at https://github.com/ROCm/rocm-systems/blob/develop/CONTRIBUTING.md.
|
a couple of false positives arising from this (found in chromium): |
|
Here's also a shorter godbolt repro: https://godbolt.org/z/bKz1M4sdh |
|
Thanks for the reports. Feel free to back out/revert. |
|
reverting in #243997 |
…tiation instead of definition" (llvm#243997) Reverts llvm#237374 Causes false positives, see llvm#237374 (comment)
…late instantiation instead of definition" (#243997) Reverts llvm/llvm-project#237374 Causes false positives, see llvm/llvm-project#237374 (comment)
…late instantiation instead of definition" (#243997) Reverts llvm/llvm-project#237374 Causes false positives, see llvm/llvm-project#237374 (comment)
|
I suppose this is a true positive. Seen when compiling the compiler with a freshly built clang (but before the revert). |
The `stl_tree_node`, `list_node` and `unordered_node` class templates only mimic the layout of the standard library's container nodes, so that `sizeof` yields an estimate of the memory they use. Their fields are never accessed. Since llvm/llvm-project#237374, Clang 24 diagnoses these fields with `-Wunused-private-field`. This change drops the `private:` access specifiers. It does not affect the size or alignment of the structs, as all their fields keep the same access control, and it is consistent with `stl_shared_counter`. Github-Pull: #36869 Rebased-From: b9a6b0c
The `stl_tree_node`, `list_node` and `unordered_node` class templates only mimic the layout of the standard library's container nodes, so that `sizeof` yields an estimate of the memory they use. Their fields are never accessed. Since llvm/llvm-project#237374, Clang 24 diagnoses these fields with `-Wunused-private-field`. This change drops the `private:` access specifiers. It does not affect the size or alignment of the structs, as all their fields keep the same access control, and it is consistent with `stl_shared_counter`. Github-Pull: #36869 Rebased-From: b9a6b0c
|
Thanks @aeubanks and @PiJoules for the revert and beautifully reduced test cases. I've posted a reland: #244396. WIP until I clean up the tree... Thanks @mikaelholmen I'll put up a fix for that (and make sure to do a full rebuild myself; I have one running and it's already flagging more instances). |
|
@mikaelholmen looks like @kazutakahirata beat me to it in 0416a3d, though I did spot one more case. |
* fix(validation): skip pruned blocks in m_blocks_unlinked LoadBlockIndex() adds to m_blocks_unlinked based only on nTx > 0, without checking BLOCK_HAVE_DATA. Pruning preserves nTx but clears BLOCK_HAVE_DATA, so a pruned block whose parent was header-only gets re-added on every restart, causing the CheckBlockIndex() assertion that entries must have data on disk to fail. Check that BLOCK_HAVE_DATA is set before inserting into m_blocks_unlinked. Fixes bitcoin#35050. Backport of bitcoin#35168 (upstream commit 0e4b0ba). (cherry picked from commit 0e4b0ba) * test: cover pruned blocks in m_blocks_unlinked A pruned stale-fork block whose parent doesn't have any transactions shouldn't be added to m_blocks_unlinked when starting up a node. Navio's create_block has an older signature, so the fork blocks are built inline in the test instead of through upstream's create_empty_fork helper, which nothing else here would use. Backport of bitcoin#35168 (upstream commit 3f44f9a). (cherry picked from commit 3f44f9a) * fix(tor): send -torpassword hex-encoded Tor's control protocol takes the password either as a QuotedString or as hex. Escaping only the quotes left a backslash in -torpassword to be read as an escape, so authentication failed for such passwords. Navio has no feature_torcontrol.py, so the upstream test is not included. Checked by hand against tor 0.4.9.17 with HashedControlPassword set for `pa\ss"word`: authentication failed before this change and succeeds after it. Backport of bitcoin#36637 (upstream commit 5a699cc). (cherry picked from commit 5a699cc) * fix(net): accept a .onion suffix in any case Navio's SetTor takes a const std::string&, so the check keeps its shape and only compares the suffix through ToLower, as SetI2P already does. Backport of bitcoin#36636 (upstream commit 0574f09). (cherry picked from commit 0574f09) * build(depends): apply upstream zeromq <new> patch See zeromq/libzmq#4911. Backport of bitcoin#35769 (upstream commit e446ea0). (cherry picked from commit e446ea0) * fix(memusage): make STL helper struct fields public The `stl_tree_node`, `list_node` and `unordered_node` class templates only mimic the layout of the standard library's container nodes, so that `sizeof` yields an estimate of the memory they use. Their fields are never accessed. Since llvm/llvm-project#237374, Clang 24 diagnoses these fields with `-Wunused-private-field`. This change drops the `private:` access specifiers. It does not affect the size or alignment of the structs, as all their fields keep the same access control, and it is consistent with `stl_shared_counter`. Backport of bitcoin#36869 (upstream commit b9a6b0c). (cherry picked from commit b9a6b0c) --------- Co-authored-by: marcofleon <[email protected]> Co-authored-by: jpk68 <[email protected]> Co-authored-by: Hennadii Stepanov <[email protected]>
[[gnu::warn_unused]]type in a class template is used by a templated function.Fixes: #237370
Assisted-by: Gemini