https://gcc.gnu.org/g:7d383a7343af052798a52d575a0f0205c4a82c9c

commit r15-7663-g7d383a7343af052798a52d575a0f0205c4a82c9c
Author: Harald Anlauf <anl...@gmx.de>
Date:   Thu Feb 20 21:22:56 2025 +0100

    Fortran: initialize non-saved pointers with -fcheck=pointer [PR48958]
    
            PR fortran/48958
    
    gcc/fortran/ChangeLog:
    
            * trans-array.cc (gfc_trans_deferred_array): Initialize the data
            component of non-saved pointers when -fcheck=pointer is set.
    
    gcc/testsuite/ChangeLog:
    
            * gfortran.dg/pointer_init_13.f90: New test.

Diff:
---
 gcc/fortran/trans-array.cc                    |  7 +++++--
 gcc/testsuite/gfortran.dg/pointer_init_13.f90 | 24 ++++++++++++++++++++++++
 2 files changed, 29 insertions(+), 2 deletions(-)

diff --git a/gcc/fortran/trans-array.cc b/gcc/fortran/trans-array.cc
index 92e933add8a8..8f76870b286a 100644
--- a/gcc/fortran/trans-array.cc
+++ b/gcc/fortran/trans-array.cc
@@ -12123,8 +12123,11 @@ gfc_trans_deferred_array (gfc_symbol * sym, 
gfc_wrapped_block * block)
       type = TREE_TYPE (descriptor);
     }
 
-  /* NULLIFY the data pointer, for non-saved allocatables.  */
-  if (GFC_DESCRIPTOR_TYPE_P (type) && !sym->attr.save && sym->attr.allocatable)
+  /* NULLIFY the data pointer for non-saved allocatables, or for non-saved
+     pointers when -fcheck=pointer is specified.  */
+  if (GFC_DESCRIPTOR_TYPE_P (type) && !sym->attr.save
+      && (sym->attr.allocatable
+         || (sym->attr.pointer && (gfc_option.rtcheck & GFC_RTCHECK_POINTER))))
     {
       gfc_conv_descriptor_data_set (&init, descriptor, null_pointer_node);
       if (flag_coarray == GFC_FCOARRAY_LIB && sym->attr.codimension)
diff --git a/gcc/testsuite/gfortran.dg/pointer_init_13.f90 
b/gcc/testsuite/gfortran.dg/pointer_init_13.f90
new file mode 100644
index 000000000000..ece423a9db6d
--- /dev/null
+++ b/gcc/testsuite/gfortran.dg/pointer_init_13.f90
@@ -0,0 +1,24 @@
+! { dg-do compile }
+! { dg-options "-fcheck=pointer -fdump-tree-optimized -O -fno-inline" }
+!
+! PR fortran/48958
+!
+! Initialize non-saved pointers with -fcheck=pointer to support runtime checks
+! of uses of possibly undefined pointers
+
+program p
+  implicit none
+  call s
+contains
+  subroutine s
+    integer, pointer :: a(:)
+    integer, pointer :: b(:) => NULL()
+    if (size (a) /= 0) stop 1
+    if (size (b) /= 0) stop 2
+    print *, size (a)
+    print *, size (b)
+  end
+end
+
+! { dg-final { scan-tree-dump-times "_gfortran_runtime_error_at" 1 "optimized" 
} }
+! { dg-final { scan-tree-dump-not "_gfortran_stop_numeric" "optimized" } }

Reply via email to