c++: implement [[gnu::no_dangling]] [PR110358]
commitc7607c4cf18986025430ca8626abfe56bfe87106
authorMarek Polacek <polacek@redhat.com>
Thu, 25 Jan 2024 21:38:51 +0000 (25 16:38 -0500)
committerMarek Polacek <polacek@redhat.com>
Fri, 1 Mar 2024 20:51:18 +0000 (1 15:51 -0500)
tree82735e54b7629fb311837575b04ec961dafe5d9b
parent64221c7bffbdd399e49554b0fb08b38325657596
c++: implement [[gnu::no_dangling]] [PR110358]

Since -Wdangling-reference has false positives that can't be
prevented, we should offer an easy way to suppress the warning.
Currently, that is only possible by using a #pragma, either around the
enclosing class or around the call site.  But #pragma GCC diagnostic tend
to be onerous.  A better solution would be to have an attribute.

To that end, this patch adds a new attribute, [[gnu::no_dangling]].
This attribute takes an optional bool argument to support cases like:

  template <typename T>
  struct [[gnu::no_dangling(std::is_reference_v<T>)]] S {
     // ...
  };

PR c++/110358
PR c++/109642

gcc/cp/ChangeLog:

* call.cc (no_dangling_p): New.
(reference_like_class_p): Use it.
(do_warn_dangling_reference): Use it.  Don't warn when the function
or its enclosing class has attribute gnu::no_dangling.
* tree.cc (cxx_gnu_attributes): Add gnu::no_dangling.
(handle_no_dangling_attribute): New.

gcc/ChangeLog:

* doc/extend.texi: Document gnu::no_dangling.
* doc/invoke.texi: Mention that gnu::no_dangling disables
-Wdangling-reference.

gcc/testsuite/ChangeLog:

* g++.dg/ext/attr-no-dangling1.C: New test.
* g++.dg/ext/attr-no-dangling2.C: New test.
* g++.dg/ext/attr-no-dangling3.C: New test.
* g++.dg/ext/attr-no-dangling4.C: New test.
* g++.dg/ext/attr-no-dangling5.C: New test.
* g++.dg/ext/attr-no-dangling6.C: New test.
* g++.dg/ext/attr-no-dangling7.C: New test.
* g++.dg/ext/attr-no-dangling8.C: New test.
* g++.dg/ext/attr-no-dangling9.C: New test.
13 files changed:
gcc/cp/call.cc
gcc/cp/tree.cc
gcc/doc/extend.texi
gcc/doc/invoke.texi
gcc/testsuite/g++.dg/ext/attr-no-dangling1.C [new file with mode: 0644]
gcc/testsuite/g++.dg/ext/attr-no-dangling2.C [new file with mode: 0644]
gcc/testsuite/g++.dg/ext/attr-no-dangling3.C [new file with mode: 0644]
gcc/testsuite/g++.dg/ext/attr-no-dangling4.C [new file with mode: 0644]
gcc/testsuite/g++.dg/ext/attr-no-dangling5.C [new file with mode: 0644]
gcc/testsuite/g++.dg/ext/attr-no-dangling6.C [new file with mode: 0644]
gcc/testsuite/g++.dg/ext/attr-no-dangling7.C [new file with mode: 0644]
gcc/testsuite/g++.dg/ext/attr-no-dangling8.C [new file with mode: 0644]
gcc/testsuite/g++.dg/ext/attr-no-dangling9.C [new file with mode: 0644]