See attached patch. In Andrew's tests, a function result passed to
another function was finalized in s = get(make(1)) and in
call sub(make(1)), but not in s = 1 + get(make(1)) or in an IF
condition, and with a defined-assignment component in its type, not
at all. Each missed finalization is also a leak when the final
procedure frees memory. With the patch every context in the report
finalizes once, an intrinsic assignment such as a = make(1) still
finalizes the variable and the result once each, and valgrind shows
no leak for s = s + get(make(i)) in a loop.

A result in an IF condition, a SELECT CASE selector or a DO WHILE
condition is now finalized right after the expression is evaluated,
because gfc_conv_expr_val already moves the post block there. The
standard says after the innermost executable construct, but holding
it until END IF would also hold the frees in the post block, which a
RETURN or EXIT from the construct would then skip.

Regression tested on x86_64.

I plan to commit this in a few days unless there are comments.

Regards,

Jerry

---

fortran: [PR128856] Finalize function results passed as arguments

A nonpointer function result passed as an actual argument was not
finalized when the call was an operand or in a condition, and never
when its type had a component with a defined assignment, although
F2023 7.5.6.3 requires it.

gfc_conv_procedure_call collects the finalization of such results in
the finalblock of the enclosing call, but only assignments, subroutine
calls and I/O emit that block; operators, intrinsic functions and
conditions drop it.  gfc_finalize_tree_expr also skips every function
result of a type with a defined-assignment component, although
generate_component_assignments handles only a result that is the
right-hand side of an intrinsic assignment.

For a function result not returned by reference, move the
finalization of the arguments to the front of the post block, which
every enclosing expression keeps.  Count the nesting of actual
argument evaluation in actual_arg_level and apply the skip only
outside it.  move_alloc_20.f03 counted only the finalization in the
assignment inside GET_U; it now also counts that of its result.

Assisted-by: Claude Opus 5.5

        PR fortran/128856

gcc/fortran/ChangeLog:

        * trans-expr.cc (gfc_conv_procedure_call): Increment
        actual_arg_level while evaluating the arguments.  For a function
        result not returned by reference, move the finalization of the
        arguments to the post block.
        * trans.cc (actual_arg_level): New.
        (gfc_finalize_tree_expr): Do not skip a type with a
        defined-assignment component for an actual argument.
        * trans.h (actual_arg_level): Declare.

gcc/testsuite/ChangeLog:

        * gfortran.dg/move_alloc_20.f03: Count the finalization of the
        result of GET_U.
        * gfortran.dg/finalize_65.f90: New test.
>From 89bfa65169ccc665bc23ecc8346c42daad957155 Mon Sep 17 00:00:00 2001
From: Jerry DeLisle <[email protected]>
Date: Sat, 21 Nov 2026 19:30:41 -0800
Subject: [PATCH] fortran: [PR128856] Finalize function results passed as
 arguments

A nonpointer function result passed as an actual argument was not
finalized when the call was an operand or in a condition, and never
when its type had a component with a defined assignment, although
F2023 7.5.6.3 requires it.

gfc_conv_procedure_call collects the finalization of such results in
the finalblock of the enclosing call, but only assignments, subroutine
calls and I/O emit that block; operators, intrinsic functions and
conditions drop it.  gfc_finalize_tree_expr also skips every function
result of a type with a defined-assignment component, although
generate_component_assignments handles only a result that is the
right-hand side of an intrinsic assignment.

For a function result not returned by reference, move the
finalization of the arguments to the front of the post block, which
every enclosing expression keeps.  Count the nesting of actual
argument evaluation in actual_arg_level and apply the skip only
outside it.  move_alloc_20.f03 counted only the finalization in the
assignment inside GET_U; it now also counts that of its result.

Assisted-by: Claude Opus 5.5

	PR fortran/128856

gcc/fortran/ChangeLog:

	* trans-expr.cc (gfc_conv_procedure_call): Increment
	actual_arg_level while evaluating the arguments.  For a function
	result not returned by reference, move the finalization of the
	arguments to the post block.
	* trans.cc (actual_arg_level): New.
	(gfc_finalize_tree_expr): Do not skip a type with a
	defined-assignment component for an actual argument.
	* trans.h (actual_arg_level): Declare.

gcc/testsuite/ChangeLog:

	* gfortran.dg/move_alloc_20.f03: Count the finalization of the
	result of GET_U.
	* gfortran.dg/finalize_65.f90: New test.
---
 gcc/fortran/trans-expr.cc                   |  10 ++
 gcc/fortran/trans.cc                        |   9 +-
 gcc/fortran/trans.h                         |   2 +
 gcc/testsuite/gfortran.dg/finalize_65.f90   | 122 ++++++++++++++++++++
 gcc/testsuite/gfortran.dg/move_alloc_20.f03 |   5 +-
 5 files changed, 144 insertions(+), 4 deletions(-)
 create mode 100644 gcc/testsuite/gfortran.dg/finalize_65.f90

diff --git a/gcc/fortran/trans-expr.cc b/gcc/fortran/trans-expr.cc
index fe3608351ef..f9360d6ff1d 100644
--- a/gcc/fortran/trans-expr.cc
+++ b/gcc/fortran/trans-expr.cc
@@ -7462,6 +7462,7 @@ gfc_conv_procedure_call (gfc_se * se, gfc_symbol * sym,
     }
 
   /* Evaluate the arguments.  */
+  actual_arg_level++;
   for (arg = args, argc = 0; arg != NULL;
        arg = arg->next, formal = formal ? formal->next : NULL, ++argc)
     {
@@ -9120,6 +9121,7 @@ gfc_conv_procedure_call (gfc_se * se, gfc_symbol * sym,
 	}
       vec_safe_push (arglist, parmse.expr);
     }
+  actual_arg_level--;
 
   gfc_add_block_to_block (&se->pre, &dealloc_blk);
   gfc_add_block_to_block (&se->pre, &clobbers);
@@ -9459,6 +9461,14 @@ gfc_conv_procedure_call (gfc_se * se, gfc_symbol * sym,
   bool finalizable = der != NULL && der->ns->proc_name
 			    && gfc_is_finalizable (der, NULL);
 
+  /* Finalize the function results passed as arguments with the post code
+     of the arguments, so that any enclosing expression keeps them.  */
+  if (!byref && (comp ? comp->attr.function : sym->attr.function))
+    {
+      gfc_add_block_to_block (&se->finalblock, &post);
+      gfc_add_block_to_block (&post, &se->finalblock);
+    }
+
   if (!byref && finalizable)
     gfc_finalize_tree_expr (se, der, attr, expr->rank);
 
diff --git a/gcc/fortran/trans.cc b/gcc/fortran/trans.cc
index 642162b54c5..7d6183a6c64 100644
--- a/gcc/fortran/trans.cc
+++ b/gcc/fortran/trans.cc
@@ -48,6 +48,10 @@ const char gfc_msg_fault[] = N_("Array reference out of bounds");
 /* Nonzero if we're translating a defined assignment call. */
 int is_assign_call = 0;
 
+/* Incremented by gfc_conv_procedure_call while it evaluates actual
+   arguments.  */
+int actual_arg_level = 0;
+
 /* Advance along TREE_CHAIN n times.  */
 
 tree
@@ -1669,8 +1673,9 @@ gfc_finalize_tree_expr (gfc_se *se, gfc_symbol *derived,
   /* Derived type function results with components that have defined
      assignments are handled in resolve.cc(generate_component_assignments),
      unless the assignment was replaced by a subroutine call to the
-     subroutine associated with the assignment operator. */
-  if ( ! is_assign_call
+     subroutine associated with the assignment operator.  An actual
+     argument is never the right-hand side of such an assignment.  */
+  if ( ! is_assign_call && ! actual_arg_level
        && derived && (derived->attr.is_c_interop
        || derived->attr.is_iso_c
        || derived->attr.is_bind_c
diff --git a/gcc/fortran/trans.h b/gcc/fortran/trans.h
index ea6b75ae93f..d0241dd0ce7 100644
--- a/gcc/fortran/trans.h
+++ b/gcc/fortran/trans.h
@@ -1242,4 +1242,6 @@ extern const char gfc_msg_fault[];
 #define OMPWS_NOWAIT		16	/* Use NOWAIT on OMP_FOR.  */
 extern int ompws_flags;
 
+extern int actual_arg_level;
+
 #endif /* GFC_TRANS_H */
diff --git a/gcc/testsuite/gfortran.dg/finalize_65.f90 b/gcc/testsuite/gfortran.dg/finalize_65.f90
new file mode 100644
index 00000000000..ee1b32f0217
--- /dev/null
+++ b/gcc/testsuite/gfortran.dg/finalize_65.f90
@@ -0,0 +1,122 @@
+! { dg-do run }
+!
+! PR 128856
+
+module m
+  implicit none
+  integer :: nfin = 0
+  type :: c
+    integer :: j = 0
+  contains
+    procedure :: asg
+    generic :: assignment(=) => asg
+  end type
+  type :: t
+    integer :: i = 0
+  contains
+    final :: fin_t
+  end type
+  type :: u
+    type(c) :: comp
+    integer :: i = 0
+  contains
+    final :: fin_u
+  end type
+contains
+  subroutine asg (a, b)
+    class(c), intent(out) :: a
+    class(c), intent(in) :: b
+    a%j = b%j
+  end subroutine
+  subroutine fin_t (x)
+    type(t), intent(inout) :: x
+    nfin = nfin + 1
+  end subroutine
+  subroutine fin_u (x)
+    type(u), intent(inout) :: x
+    nfin = nfin + 1
+  end subroutine
+  function make_t (i) result (r)
+    integer, intent(in) :: i
+    type(t) :: r
+    r%i = i
+  end function
+  function make_u (i) result (r)
+    integer, intent(in) :: i
+    type(u) :: r
+    r%i = i
+  end function
+  integer function get_t (x)
+    type(t), intent(in) :: x
+    get_t = x%i
+  end function
+  integer function get_u (x)
+    type(u), intent(in) :: x
+    get_u = x%i
+  end function
+  subroutine sub_t (x)
+    type(t), intent(in) :: x
+  end subroutine
+  subroutine sub_u (x)
+    type(u), intent(in) :: x
+  end subroutine
+end module
+
+program p
+  use m
+  implicit none
+  integer :: s, k
+  type(u) :: a
+  character(8) :: buf
+
+  nfin = 0
+  s = get_t (make_t (1))
+  if (nfin /= 1) stop 1
+  nfin = 0
+  s = 1 + get_t (make_t (1))
+  if (nfin /= 1) stop 2
+  nfin = 0
+  call sub_t (make_t (1))
+  if (nfin /= 1) stop 3
+  nfin = 0
+  if (get_t (make_t (1)) /= 1) stop 4
+  if (nfin /= 1) stop 5
+  nfin = 0
+  if (get_t (make_t (1)) == 1) then
+    s = 0
+  end if
+  if (nfin /= 1) stop 7
+  nfin = 0
+  k = 0
+  do while (get_t (make_t (k)) < 2)
+    k = k + 1
+  end do
+  if (nfin /= 3) stop 8
+  nfin = 0
+  select case (get_t (make_t (2)))
+  case (2)
+    s = 0
+  case default
+    stop 10
+  end select
+  if (nfin /= 1) stop 11
+  nfin = 0
+  write (buf, '(i0)') get_t (make_t (1))
+  if (nfin /= 1) stop 12
+
+  nfin = 0
+  s = get_u (make_u (1))
+  if (nfin /= 1) stop 13
+  nfin = 0
+  s = 1 + get_u (make_u (1))
+  if (nfin /= 1) stop 14
+  nfin = 0
+  call sub_u (make_u (1))
+  if (nfin /= 1) stop 15
+  nfin = 0
+  if (get_u (make_u (1)) /= 1) stop 16
+  if (nfin /= 1) stop 17
+  nfin = 0
+  a = make_u (1)
+  if (nfin /= 2) stop 18
+end program
diff --git a/gcc/testsuite/gfortran.dg/move_alloc_20.f03 b/gcc/testsuite/gfortran.dg/move_alloc_20.f03
index 20403c30028..3c0acea63e6 100644
--- a/gcc/testsuite/gfortran.dg/move_alloc_20.f03
+++ b/gcc/testsuite/gfortran.dg/move_alloc_20.f03
@@ -105,6 +105,7 @@ contains
 
     ! Check that the cleanup code for the evaluation of TO is properly
     ! executed after MOVE_ALLOC: the result of GET_U should be finalized.
+    ! GET_U also finalizes its result variable on assignment.
     call move_alloc(tmp, x(idx(get_u(y)))%a)
 
     do i=1,n
@@ -115,7 +116,7 @@ contains
     if (any(shape(x(2)%a) /= [1])) error stop 23
     if (any(x(2)%a /= [37])) error stop 24
     if (allocated(tmp)) error stop 25
-    if (finalization_count /= 1) error stop 26
+    if (finalization_count /= 2) error stop 26
 
     ! Check that the cleanup code for the evaluation of FROM is properly
     ! executed after MOVE_ALLOC: the result of GET_U should be finalized.
@@ -124,7 +125,7 @@ contains
     if (.not. allocated(tmp)) error stop 31
     if (any(shape(tmp) /= [1])) error stop 32
     if (any(tmp /= [37])) error stop 33
-    if (finalization_count /= 2) error stop 34
+    if (finalization_count /= 4) error stop 34
     do i=1,n
       if (allocated(x(i)%a)) error stop 35
     end do
-- 
2.56.1

Reply via email to