Skip to content

Reapply "[clang][Sema] Check -Wunused-private-field at template instantiation instead of definition" (#243997) - #244396

Open
nickdesaulniers wants to merge 7 commits into
llvm:mainfrom
nickdesaulniers:reland_unused_private_field
Open

nickdesaulniers wants to merge 7 commits into
llvm:mainfrom
nickdesaulniers:reland_unused_private_field

Conversation

@nickdesaulniers

Copy link
Copy Markdown
Member
  1. Fix a false positive to not warn when a private field of a
    [[gnu::warn_unused]] type in a class template is used by a templated
    function.
  2. Fix a false negative to warn when an instantiated class template has
    an unused private field.

Reland: add additional unit tests and fixes for:

  1. __builtin_offsetof
  2. friend member templates
  3. discarded if constexpr branches

Fixes: #237370
Assisted-by: Gemini

…ntiation instead of definition" (llvm#243997)

1. Fix a false positive to not warn when a private field of a
   [[gnu::warn_unused]] type in a class template is used by a templated
   function.
2. Fix a false negative to warn when an instantiated class template has
   an unused private field.

Fixes: llvm#237370
Assisted-by: Gemini
…e for -Wunused-private-field

Assisted-by: Gemini
@llvmorg-github-actions llvmorg-github-actions Bot added clang Clang issues not falling into any other category clang:frontend Language frontend issues, e.g. anything involving "Sema" labels Nov 19, 2026
@llvmorg-github-actions

Copy link
Copy Markdown

@llvm/pr-subscribers-clang

Author: Nick Desaulniers (nickdesaulniers)

Changes
  1. Fix a false positive to not warn when a private field of a
    [[gnu::warn_unused]] type in a class template is used by a templated
    function.
  2. Fix a false negative to warn when an instantiated class template has
    an unused private field.

Reland: add additional unit tests and fixes for:

  1. __builtin_offsetof
  2. friend member templates
  3. discarded if constexpr branches

Fixes: #237370
Assisted-by: Gemini


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

8 Files Affected:

  • (modified) clang/include/clang/AST/Decl.h (+2)
  • (modified) clang/lib/AST/Decl.cpp (+28)
  • (modified) clang/lib/Sema/Sema.cpp (+10-2)
  • (modified) clang/lib/Sema/SemaDeclCXX.cpp (+1-33)
  • (modified) clang/lib/Sema/SemaExpr.cpp (+6-3)
  • (modified) clang/lib/Sema/SemaTemplateInstantiateDecl.cpp (+5)
  • (modified) clang/test/SemaCXX/uninitialized.cpp (+1-1)
  • (modified) clang/test/SemaCXX/warn-unused-private-field.cpp (+84)
diff --git a/clang/include/clang/AST/Decl.h b/clang/include/clang/AST/Decl.h
index 4104ddc89c50f9..69d0cd27c6fcc7 100644
--- a/clang/include/clang/AST/Decl.h
+++ b/clang/include/clang/AST/Decl.h
@@ -3540,6 +3540,8 @@ class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> {
   /// \p nullptr if either the attribute or the field doesn't exist.
   const FieldDecl *findCountedByField() const;
 
+  bool isUnusedPrivateField() const;
+
 private:
   void setLazyInClassInitializer(LazyDeclStmtPtr NewInit);
 
diff --git a/clang/lib/AST/Decl.cpp b/clang/lib/AST/Decl.cpp
index e89938d230dbbf..3147cdf8afab86 100644
--- a/clang/lib/AST/Decl.cpp
+++ b/clang/lib/AST/Decl.cpp
@@ -4974,6 +4974,34 @@ const FieldDecl *FieldDecl::findCountedByField() const {
   return dyn_cast<FieldDecl>(CountDecl);
 }
 
+static bool initializationHasSideEffects(const FieldDecl &FD) {
+  const Type *T = FD.getType()->getBaseElementTypeUnsafe();
+  // FIXME: Destruction of ObjC lifetime types has side-effects.
+  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
+    return !RD->isCompleteDefinition() || !RD->hasTrivialDefaultConstructor() ||
+           !RD->hasTrivialDestructor();
+  return false;
+}
+
+template <typename AttrType> static bool hasAttribute(QualType T) {
+  if (const TagDecl *TD = T->getAsTagDecl())
+    return TD->hasAttr<AttrType>();
+  if (const TypedefType *TDT = T->getAs<TypedefType>())
+    return TDT->getDecl()->hasAttr<AttrType>();
+  return false;
+}
+
+bool FieldDecl::isUnusedPrivateField() const {
+  if (isImplicit() || !getDeclName() || getAccess() != AS_private ||
+      hasAttr<UnusedAttr>() || getParent()->isDependentContext())
+    return false;
+
+  QualType FieldType = getType();
+  return !hasAttribute<UnusedAttr>(FieldType) &&
+         (hasAttribute<WarnUnusedAttr>(FieldType) ||
+          !initializationHasSideEffects(*this));
+}
+
 //===----------------------------------------------------------------------===//
 // TagDecl Implementation
 //===----------------------------------------------------------------------===//
diff --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp
index ebc8b85cf8a628..6df5c5f495919b 100644
--- a/clang/lib/Sema/Sema.cpp
+++ b/clang/lib/Sema/Sema.cpp
@@ -1179,9 +1179,17 @@ static bool IsRecordFullyDefined(const CXXRecordDecl *RD,
     // Check if friend classes and methods are complete.
     if (TypeSourceInfo *TSI = Friend->getFriendType()) {
       // Friend classes are available as the TypeSourceInfo of the FriendDecl.
-      if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
+      if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl()) {
         Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
-      else
+        // A friend class with member function templates may instantiate
+        // specializations in other TUs that access RD's private fields.
+        for (const Decl *D : FriendD->decls()) {
+          if (isa<FunctionTemplateDecl>(D)) {
+            Complete = false;
+            break;
+          }
+        }
+      } else
         Complete = false;
     } else {
       // Friend functions are available through the NamedDecl of FriendDecl.
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index fb57ccb5598716..efe8d3fd7f3d43 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -3415,15 +3415,6 @@ bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
   return true;
 }
 
-static bool InitializationHasSideEffects(const FieldDecl &FD) {
-  const Type *T = FD.getType()->getBaseElementTypeUnsafe();
-  // FIXME: Destruction of ObjC lifetime types has side-effects.
-  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
-    return !RD->isCompleteDefinition() || !RD->hasTrivialDefaultConstructor() ||
-           !RD->hasTrivialDestructor();
-  return false;
-}
-
 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
                                       DeclarationName FieldName,
                                       const CXXRecordDecl *RD,
@@ -3474,29 +3465,6 @@ void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
   }
 }
 
-template <typename AttrType>
-inline static bool HasAttribute(const QualType &T) {
-  if (const TagDecl *TD = T->getAsTagDecl())
-    return TD->hasAttr<AttrType>();
-  if (const TypedefType *TDT = T->getAs<TypedefType>())
-    return TDT->getDecl()->hasAttr<AttrType>();
-  return false;
-}
-
-static bool IsUnusedPrivateField(const FieldDecl *FD) {
-  if (FD->getAccess() == AS_private && FD->getDeclName()) {
-    QualType FieldType = FD->getType();
-    if (HasAttribute<WarnUnusedAttr>(FieldType))
-      return true;
-
-    return !FD->isImplicit() && !FD->hasAttr<UnusedAttr>() &&
-           !FD->getParent()->isDependentContext() &&
-           !HasAttribute<UnusedAttr>(FieldType) &&
-           !InitializationHasSideEffects(*FD);
-  }
-  return false;
-}
-
 NamedDecl *
 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
                                MultiTemplateParamsArg TemplateParameterLists,
@@ -3790,7 +3758,7 @@ Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
     FieldCollector->Add(FD);
 
     if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation()) &&
-        IsUnusedPrivateField(FD)) {
+        FD->isUnusedPrivateField()) {
       // Remember all explicit private FieldDecls that have a name, no side
       // effects and are not part of a dependent type declaration.
       UnusedPrivateFields.insert(FD);
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 571ef6ea6b19eb..14c9265d9a86bf 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -17235,11 +17235,14 @@ ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
     if (IndirectMemberDecl) {
       for (auto *FI : IndirectMemberDecl->chain()) {
         assert(isa<FieldDecl>(FI));
-        Comps.push_back(
-            OffsetOfNode(D.getBeginLoc(), cast<FieldDecl>(FI), D.getEndLoc()));
+        auto *FD = cast<FieldDecl>(FI);
+        UnusedPrivateFields.remove(FD);
+        Comps.push_back(OffsetOfNode(D.getBeginLoc(), FD, D.getEndLoc()));
       }
-    } else
+    } else {
+      UnusedPrivateFields.remove(MemberDecl);
       Comps.push_back(OffsetOfNode(D.getBeginLoc(), MemberDecl, D.getEndLoc()));
+    }
 
     CurrentType = MemberDecl->getType().getNonReferenceType();
   }
diff --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index b72864aec8d51c..468d435033bfb7 100644
--- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -1967,6 +1967,11 @@ Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
   Field->setAccess(D->getAccess());
   Owner->addDecl(Field);
 
+  if (!SemaRef.Diags.isIgnored(diag::warn_unused_private_field,
+                               Field->getLocation()) &&
+      !D->isReferenced() && Field->isUnusedPrivateField())
+    SemaRef.UnusedPrivateFields.insert(Field);
+
   return Field;
 }
 
diff --git a/clang/test/SemaCXX/uninitialized.cpp b/clang/test/SemaCXX/uninitialized.cpp
index 9ecea1ac4cc3bd..0e90bb67840ad3 100644
--- a/clang/test/SemaCXX/uninitialized.cpp
+++ b/clang/test/SemaCXX/uninitialized.cpp
@@ -593,7 +593,7 @@ namespace rdar10398199 {
   };
   void stuff();
   template <typename T> class FooImpl : public Foo {
-    T val;
+    T val; // expected-warning 2{{private field 'val' is not used}}
   public:
     FooImpl(const T &x) : val(x) {}
     ~FooImpl() { stuff(); }
diff --git a/clang/test/SemaCXX/warn-unused-private-field.cpp b/clang/test/SemaCXX/warn-unused-private-field.cpp
index 0bcca6b82227f9..dafba65f40c421 100644
--- a/clang/test/SemaCXX/warn-unused-private-field.cpp
+++ b/clang/test/SemaCXX/warn-unused-private-field.cpp
@@ -354,3 +354,87 @@ 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);
+}
+
+template <typename T>
+struct Outer2 {
+  class Inner {
+    WarnUnusedType field_; // expected-warning {{private field 'field_' is not used}}
+  };
+};
+void test2() {
+  Outer2<int> o;
+  Outer2<int>::Inner i;
+  (void)o;
+  (void)i;
+}
+} // namespace warn_unused_template
+
+#if __cplusplus >= 201402L
+namespace offsetof_template {
+template <int>
+class Slab {
+ public:
+  static constexpr auto offset() { return __builtin_offsetof(Slab, node_); }
+ private:
+  int node_;
+};
+auto kOff = Slab<0>::offset();
+} // namespace offsetof_template
+#endif
+
+namespace friend_member_template {
+class Base {
+ public:
+  template <class T> T& Cast();
+};
+template <class T>
+class Holder : public Base {
+ public:
+  explicit Holder(T v) : value_(v) {}
+ private:
+  friend class Base;
+  T value_;
+};
+template <class T>
+T& Base::Cast() { return static_cast<Holder<T>*>(this)->value_; }
+void make() { Holder<int> h(1); }
+} // namespace friend_member_template
+
+#if __cplusplus >= 201703L
+namespace if_constexpr_template {
+template <class T>
+class Tracker {
+ public:
+  T Get() {
+    if constexpr (sizeof(T) == 8) {
+      x_ = 1;
+      return x_;
+    }
+    return 0;
+  }
+ private:
+  long x_;
+};
+int f() { return Tracker<int>().Get(); }
+} // namespace if_constexpr_template
+#endif

nickdesaulniers added a commit that referenced this pull request Nov 19, 2026
-Wunused-private-field will soon be able to flag fields in instantiated
class templates. Land this in preparation.

Link: #237374
Link: #244396
@nickdesaulniers

nickdesaulniers commented Nov 20, 2026 •

Copy link
Copy Markdown
Member Author

Reland of #237374

@nickdesaulniers

Copy link
Copy Markdown
Member Author

cc @llvm/android-maintainers @aeubanks @PiJoules @kazutakahirata @tbaederr

@kazutakahirata

Copy link
Copy Markdown
Contributor

I haven't looked closely at the implementation side of this PR, so please take this with a grain of salt. My LLM came up with the standalone lit testcases below, and each one currently fails -verify with an unexpected -Wunused-private-field warning when dropped into clang/test/SemaCXX/ with this PR applied. You might want to look into these cases:

__builtin_offsetof in a discarded if constexpr branch:

// RUN: %clang_cc1 -fsyntax-only -Wunused-private-field -verify -std=c++17 %s
// expected-no-diagnostics

namespace offsetof_if_constexpr {
template <bool B>
class Slab {
 public:
  static int offset() {
    if constexpr (B)
      return __builtin_offsetof(Slab, node_);
    return 0;
  }

 private:
  int node_;
};

int k = Slab<true>::offset() + Slab<false>::offset();
} // namespace offsetof_if_constexpr

Nested class field in a discarded if constexpr branch:

// RUN: %clang_cc1 -fsyntax-only -Wunused-private-field -verify -std=c++17 %s
// expected-no-diagnostics

namespace nested_if_constexpr {
template <bool B>
struct Outer {
  class Inner {
    friend struct Outer;
    int field_;
  };

  static int use(Inner &i) {
    if constexpr (B)
      return i.field_;
    return 0;
  }
};

int test() {
  Outer<true>::Inner i1;
  Outer<false>::Inner i2;
  return Outer<true>::use(i1) + Outer<false>::use(i2);
}
} // namespace nested_if_constexpr

Structured binding in a discarded if constexpr branch:

// RUN: %clang_cc1 -fsyntax-only -Wunused-private-field -verify -std=c++17 %s
// expected-no-diagnostics

namespace structured_binding_if_constexpr {
template <bool B>
class Box {
 public:
  int get() const {
    if constexpr (B) {
      auto [x] = *this;
      return x;
    }
    return 0;
  }

 private:
  int x_ = 0;
};

int k = Box<true>().get() + Box<false>().get();
} // namespace structured_binding_if_constexpr

Member template inside a friend class's nested class:

// RUN: %clang_cc1 -fsyntax-only -Wunused-private-field -verify -std=c++11 %s
// expected-no-diagnostics

namespace friend_nested_template {
struct Friend {
  struct Nested {
    template <class T>
    static int get(const T &x) { return x.value_; }
  };
};

template <class>
class Holder {
  friend struct Friend;
  int value_;
};

Holder<int> h;
} // namespace friend_nested_template

Field used by one explicit member specialization and not another:

// RUN: %clang_cc1 -fsyntax-only -Wunused-private-field -verify -std=c++11 %s
// expected-no-diagnostics

namespace explicit_member_spec {
template <class>
class Packet {
  int header_;
  int read();
};

template <> int Packet<int>::read() { return header_; }
template <> int Packet<void>::read() { return 0; }
} // namespace explicit_member_spec

@kazutakahirata

Copy link
Copy Markdown
Contributor

I may be totally off here since I am not familiar with Clang's AST, so please feel free to ignore this if it does not make sense. Would it make sense to initially target a small, conservative subset of cases where we can warn without false positives, and then gradually expand the scope in follow-up PRs?

Teemperor added a commit that referenced this pull request Nov 24, 2026
@Teemperor
Teemperor self-requested a review November 24, 2026 12:01
llvm-upstreamsync Bot pushed a commit to qualcomm/cpullvm-toolchain that referenced this pull request Nov 24, 2026
…warnings (#245337)

See llvm/llvm-project#244396 which makes unused
private fields a warning.
llvm-sync Bot pushed a commit to arm/arm-toolchain that referenced this pull request Nov 24, 2026
…warnings (#245337)

See llvm/llvm-project#244396 which makes unused
private fields a warning.
@nickdesaulniers

Copy link
Copy Markdown
Member Author

#237374 (comment)

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

clang:frontend Language frontend issues, e.g. anything involving "Sema" clang Clang issues not falling into any other category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

-Wunused-private-field false positive on template instantiated uses

2 participants