
# Test if the Fortran compiler supports OpenMP 4.5 features used in Elmer

message(STATUS "Checking whether ${CMAKE_Fortran_COMPILER} supports OpenMP 4.5")

file(WRITE ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/testFortranOpenMP45.F90
"
#if (_OPENMP >= 201511)
MODULE TESTOPENMP45MODULE
CONTAINS
SUBROUTINE MINIMAL(u)
REAL :: U
!$OMP DECLARE SIMD LINEAR(REF(u))
END SUBROUTINE
END MODULE

PROGRAM TESTOPENMP45
USE TESTOPENMP45MODULE
IMPLICIT NONE
INTEGER, PARAMETER :: N = 1000
REAL :: A(N), B(N), C(N)
A=1
B=1
CALL COMPUTE(N, A, B, C)
WRITE (*,*) C(1), C(N)

CONTAINS

SUBROUTINE COMPUTE(N,X,Y,Z)
IMPLICIT NONE
INTEGER, INTENT(IN) :: N
REAL, INTENT(IN) :: X(N), Y(N)
REAL, INTENT(OUT) :: Z(N)
INTEGER :: I

INTERFACE
SUBROUTINE PLUSV_LINEAR_SUBR(X,Y,Z)
IMPLICIT NONE
REAL,INTENT(IN) :: X,Y
REAL,INTENT(OUT) :: Z
!$OMP DECLARE SIMD LINEAR(REF(X)) LINEAR(REF(Y)) &
!$OMP              LINEAR(REF(Z)) NOTINBRANCH
END SUBROUTINE PLUSV_LINEAR_SUBR
FUNCTION PLUSV_LINEAR_FUNC(X,Y) RESULT(Z)
IMPLICIT NONE
REAL,INTENT(IN) :: X,Y
REAL :: Z
!$OMP DECLARE SIMD LINEAR(REF(X)) LINEAR(REF(Y)) &
!$OMP              NOTINBRANCH
END FUNCTION PLUSV_LINEAR_FUNC
END INTERFACE
  
!$OMP SIMD
DO I=1,N
CALL PLUSV_LINEAR_SUBR(X(I),Y(I),Z(I))
END DO
!$OMP SIMD
DO I=1,N
Z(I)=Z(I)+PLUSV_LINEAR_FUNC(X(I),Y(I))
END DO
END SUBROUTINE COMPUTE
END PROGRAM TESTOPENMP45

SUBROUTINE PLUSV_LINEAR_SUBR(X,Y,Z)
IMPLICIT NONE
REAL,INTENT(IN) :: X,Y
REAL,INTENT(OUT) :: Z
!$OMP DECLARE SIMD LINEAR(REF(X)) LINEAR(REF(Y)) &
!$OMP              LINEAR(REF(Z)) NOTINBRANCH
Z=X+Y
END SUBROUTINE PLUSV_LINEAR_SUBR

FUNCTION PLUSV_LINEAR_FUNC(X,Y) RESULT(Z)
IMPLICIT NONE
REAL,INTENT(IN) :: X,Y
REAL :: Z
!$OMP DECLARE SIMD LINEAR(REF(X)) LINEAR(REF(Y)) &
!$OMP              NOTINBRANCH
Z=X+Y
END FUNCTION PLUSV_LINEAR_FUNC
#else
! Supported OpenMP standard revision < 201511
#error Supported OpenMP standard revision < 201511
#endif
")

try_compile(FC_HAS_OPENMP_45 ${CMAKE_BINARY_DIR}
  ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/testFortranOpenMP45.F90
  OUTPUT_VARIABLE OUTPUT)
if(FC_HAS_OPENMP_45)
  message(STATUS "Checking whether ${CMAKE_Fortran_COMPILER} supports OpenMP 4.5 -- yes")
  set(CMAKE_Fortran_COMPILER_SUPPORTS_OPENMP45 1 CACHE BOOL "")
else(FC_HAS_OPENMP_45)
  message(STATUS "Checking whether ${CMAKE_Fortran_COMPILER} supports OpenMP 4.5 -- no")
  set(CMAKE_Fortran_COMPILER_SUPPORTS_OPENMP45 0 CACHE BOOL "")
endif(FC_HAS_OPENMP_45)
MARK_AS_ADVANCED(CMAKE_Fortran_COMPILER_SUPPORTS_OPENMP45)
