]> git.ipfire.org Git - thirdparty/gcc.git/commitdiff
c++: NRV and goto [PR92407]
authorJason Merrill <jason@redhat.com>
Sun, 4 Jun 2023 16:00:55 +0000 (12:00 -0400)
committerJason Merrill <jason@redhat.com>
Wed, 7 Jun 2023 01:30:59 +0000 (21:30 -0400)
Here our named return value optimization was breaking the required
destructor when the goto takes 'a' out of scope.  The simplest fix is to
disable the optimization in the presence of user labels.

We could do better by disabling the optimization only if there is a backward
goto across the variable declaration, but we don't currently track that.

PR c++/92407

gcc/cp/ChangeLog:

* typeck.cc (check_return_expr): Prevent NRV in the presence of
named labels.

gcc/testsuite/ChangeLog:

* g++.dg/opt/nrv22.C: New test.

gcc/cp/typeck.cc
gcc/testsuite/g++.dg/opt/nrv22.C [new file with mode: 0644]

index 11fcc7fcd3b35df92906e0bd72811dac43ae9e9c..6618c6a20218a8110efcfb790931ee8e37f8b460 100644 (file)
@@ -11155,6 +11155,9 @@ check_return_expr (tree retval, bool *no_warning)
   if (fn_returns_value_p && flag_elide_constructors)
     {
       if (named_return_value_okay_p
+         /* The current NRV implementation breaks if a backward goto needs to
+            destroy the object (PR92407).  */
+         && !cp_function_chain->x_named_labels
           && (current_function_return_value == NULL_TREE
              || current_function_return_value == bare_retval))
        current_function_return_value = bare_retval;
diff --git a/gcc/testsuite/g++.dg/opt/nrv22.C b/gcc/testsuite/g++.dg/opt/nrv22.C
new file mode 100644 (file)
index 0000000..eb889fa
--- /dev/null
@@ -0,0 +1,30 @@
+// PR c++/92407
+// { dg-do run }
+
+struct A
+{
+  A () { a++; }
+  A (const A &) { a++; }
+  ~A () { a--; }
+  static int a;
+};
+int A::a = 0;
+
+A
+foo ()
+{
+  int cnt = 10;
+lab:
+  A a;
+  if (cnt--)
+    goto lab;
+  return a;
+}
+
+int
+main ()
+{
+  foo ();
+  if (A::a)
+    __builtin_abort ();
+}