<table border="1" cellspacing="0" cellpadding="8">
    <tr>
        <th>Issue</th>
        <td>
            <a href=https://github.com/llvm/llvm-project/issues/126391>126391</a>
        </td>
    </tr>

    <tr>
        <th>Summary</th>
        <td>
            [Flang] Missing finalization on `MOVE_ALLOC`
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            flang:runtime
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
      </td>
    </tr>

    <tr>
      <th>Reporter</th>
      <td>
          DanielCChen
      </td>
    </tr>
</table>

<pre>
    Consider the following code
```
module m
    integer  :: numA = 0, numB = 0

 type A
        integer :: iA
        contains
            final :: finalA
    end type

    type, extends(A) :: B
        integer :: iB
 type(A) :: x
        contains
            final :: finalB
    end type

    contains
        subroutine finalA(a1)
            type(A), intent(in) :: a1
            numA = numA + 1
        end subroutine

 subroutine finalB(b1)
            type(B), intent(in) :: b1
 numB = numB + 1
        end subroutine
end module


program main
use m

    class(A), allocatable :: to(:)
    class(B), allocatable :: from(:)

    allocate(B :: to(1))
    allocate(B :: from (0:-1) )

 select type (to)
      type is (B)
        to(1) = B(iA = 101, iB = 102, x= A(11))      !! Finalize 'to' as of type B
    end select

    if ( numA /= 2 ) error stop 11
    if ( numB /= 1 ) error stop 13

    ! to is rank-1 array
    call move_alloc(from, to )                            !! Finalize 'to' again as of type B

    if ( numA /= 4 ) error stop 41
    if ( numB /= 2 ) error stop 43

   end

```

Flang currently failed at `error stop 41` because the counter of `finalA` is 3 instead of 4. 
Polymorphic allocatable variable `to` has dynamic type of `B` at the point before `move_alloc` is called, so it should call `finalB` once more and `finalA` twice more.

</pre>
<img width="1" height="1" alt="" src="http://email.email.llvm.org/o/eJycVcFy4ygQ_Rp86YoLkCJbBx0kZ32aqdnTXqeQhCx2EbgAZeL9-q0Wkq04cbZqXKkKCF6_97obEN6rk5GyIM8VeX7ZiDH01hUvwiipD4demk1t20txsMarVjoIvYTOam1_KXOCxraS0JJkdP6j5WDbUUsYCC0BAJQJ8iQdAElKkpR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