[PATCH] c++: Don't complain about [[maybe_unused]] on non-static data members

Jakub Jelinek jakub@redhat.com
Fri Jun 11 21:44:34 GMT 2021


On Fri, Jun 11, 2021 at 10:35:58PM +0200, Jakub Jelinek wrote:
> > But I also agree that GCC shouldn't warn here.
> 
> We could do that by using a wrapper around handle_unused_attribute
> for the maybe_unused attribute, that way warn on unused attribute on
> FIELD_DECLs, but not for maybe_unused (until we actually implement some
> warning that uses it).

Here it is in patch form.
Ok for trunk if it passes bootstrap/regtest?

2021-06-11  Jakub Jelinek  <jakub@redhat.com>

	* tree.c (handle_maybe_unused_attribute): New function.
	(std_attribute_table): Use it as handler for maybe_unused attribute.

	* g++.dg/cpp1z/maybe_unused2.C: New test.

--- gcc/cp/tree.c.jj	2021-05-28 11:03:19.490884332 +0200
+++ gcc/cp/tree.c	2021-06-11 23:41:36.503413441 +0200
@@ -4872,6 +4872,23 @@ handle_likeliness_attribute (tree *node,
     return error_mark_node;
 }
 
+/* The C++17 [[maybe_unused]] attribute maps to GNU unused attribute,
+   except that we don't want -Wattributes to warn for [[maybe_unused]]
+   on non-static data members.  */
+
+static tree
+handle_maybe_unused_attribute (tree *node, tree name, tree args,
+			       int flags, bool *no_add_attrs)
+{
+  if (TREE_CODE (*node) == FIELD_DECL)
+    {
+      *no_add_attrs = true;
+      return NULL_TREE;
+    }
+  else
+    return handle_unused_attribute (node, name, args, flags, no_add_attrs);
+}
+
 /* Table of valid C++ attributes.  */
 const struct attribute_spec cxx_attribute_table[] =
 {
@@ -4890,7 +4907,7 @@ const struct attribute_spec std_attribut
   /* { name, min_len, max_len, decl_req, type_req, fn_type_req,
        affects_type_identity, handler, exclude } */
   { "maybe_unused", 0, 0, false, false, false, false,
-    handle_unused_attribute, NULL },
+    handle_maybe_unused_attribute, NULL },
   { "nodiscard", 0, 1, false, false, false, false,
     handle_nodiscard_attribute, NULL },
   { "no_unique_address", 0, 0, true, false, false, false,
--- gcc/testsuite/g++.dg/cpp1z/maybe_unused2.C.jj	2021-06-11 23:40:51.742027943 +0200
+++ gcc/testsuite/g++.dg/cpp1z/maybe_unused2.C	2021-06-11 23:40:47.642084225 +0200
@@ -0,0 +1,7 @@
+// { dg-do compile { target c++11 } }
+// { dg-options "-Wunused -Wextra" }
+
+struct [[maybe_unused]] A {
+  [[maybe_unused]] static int i;
+  [[maybe_unused]] int a;
+};


	Jakub



More information about the Gcc-patches mailing list