[clang] [Clang] Fix -Wunused-private-field false negative with defaulted comparison operators (PR #116871)

via cfe-commits cfe-commits at lists.llvm.org
Tue Nov 19 12:36:48 PST 2024


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-clang

Author: Chris White (whiteio)

<details>
<summary>Changes</summary>

Fix -Wunused-private-field incorrectly suppressing warnings for friend defaulted comparison operators. The warning should only be suppressed when the defaulted comparison is a class member function.

Fixes #<!-- -->116270

---
Full diff: https://github.com/llvm/llvm-project/pull/116871.diff


2 Files Affected:

- (modified) clang/lib/Sema/SemaDeclCXX.cpp (+1-1) 
- (modified) clang/test/SemaCXX/warn-unused-private-field.cpp (+11) 


``````````diff
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 26041e53de5061..e115eb0a3d7e10 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -7535,7 +7535,7 @@ void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
     return;
   }
 
-  if (DefKind.isComparison())
+  if (DefKind.isComparison() && isa<CXXRecordDecl>(FD->getDeclContext()))
     UnusedPrivateFields.clear();
 
   if (DefKind.isSpecialMember()
diff --git a/clang/test/SemaCXX/warn-unused-private-field.cpp b/clang/test/SemaCXX/warn-unused-private-field.cpp
index 1128eacc309d9f..bdd66807dca35f 100644
--- a/clang/test/SemaCXX/warn-unused-private-field.cpp
+++ b/clang/test/SemaCXX/warn-unused-private-field.cpp
@@ -20,6 +20,17 @@ class SpaceShipDefaultCompare {
   int operator<=>(const SpaceShipDefaultCompare &) const = default;
 };
 
+class UnusedConstPrivateField {
+ public:
+  UnusedConstPrivateField() : unused_(0) {}
+ private:
+  const int unused_; // expected-warning{{private field 'unused_' is not used}}
+};
+
+class FriendEqDefaultCompare {
+  friend auto operator==(FriendEqDefaultCompare, FriendEqDefaultCompare) -> bool = default;
+};
+
 #endif
 
 class NotFullyDefined {

``````````

</details>


https://github.com/llvm/llvm-project/pull/116871


More information about the cfe-commits mailing list