!
! Copyright (C) 2022, MaX CoE
! Distributed under the MIT License 
! (license terms are at http://opensource.org/licenses/MIT).
!
!--
!
! Utility functions to perform memory deallocation on the device
! using CUDA-Fortran, OpenACC or OpenMP Offload
!
!==================================================================
!==================================================================
! *DO NOT EDIT*: automatically generated from devxlib_malloc_free.jf90
!==================================================================
!==================================================================
!
#include<devxlib_macros.h>
#include<devxlib_defs.h>
!
!=======================================
!
submodule (devxlib_malloc) devxlib_malloc_free

   implicit none

   contains
{%- for t in types %}
{%- for p in kinds[t] %}
{%- for d in range(1,dimensions+1) %}
!
      module subroutine {{p.name}}_devxlib_malloc_free_{{t[0]|lower}}{{d}}d(dev_ptr, device_id)
          implicit none
          !
          {{t}}({{p.val}}), pointer, contiguous, intent(inout) DEV_ATTR :: dev_ptr({% for dd in range(d) %}:{% if not loop.last %}, {%- endif %}{% endfor %})
          integer, optional, intent(in)  :: device_id
#if defined __DXL_CUDAF
          integer :: istat
          integer(kind=c_int) :: info
#endif
#if defined __DXL_OPENMP_GPU
          integer :: device_id_local
#endif
          !
#if defined __DXL_CUDAF
          if (present(device_id)) istat = cudaSetDevice(device_id)
#elif defined __DXL_OPENMP_GPU
          if (present(device_id)) then
             device_id_local= device_id
          else
             device_id_local = omp_get_default_device()
          endif
#endif
          !
#if defined __DXL_CUDAF || defined __DXL_OPENACC || defined __DXL_OPENMP_GPU
          if (associated(dev_ptr)) then
#if defined __DXL_CUDAF
             info = cudaFree_f(c_loc(dev_ptr))
#elif defined __DXL_OPENACC
             call acc_free_f(c_loc(dev_ptr))
#elif defined __DXL_OPENMP_GPU
             call omp_target_free(c_loc(dev_ptr), device_id_local)
#endif
             nullify(dev_ptr)
          endif
#else
          if (associated(dev_ptr)) deallocate( dev_ptr)
#endif
          !
      end subroutine {{p.name}}_devxlib_malloc_free_{{t[0]|lower}}{{d}}d
      !
{%- endfor %}
{%- endfor %}
{%- endfor %}

endsubmodule devxlib_malloc_free
