Issue 151894
Summary [Flang] allocated status of a saved ALLOCATABLE variable is lost when subprograms are executed starting from an ENTRY statement under -O2 optimization
Labels flang
Assignees
Reporter ohno-fj
    ```
Version of flang : 22.0.0(9e5f9ff82f2f060aac73a965ab37fdbb6b53cfe0)/AArch64
```

In the attached test program (`short.f90`), a saved `ALLOCATABLE` variable `x` is declared in a subprogram `sub`, and accessed from its latter part separated by the entry point `ent`. The `allocated(x)` status is checked inside the latter part.  

According to the Fortran standard 2023, section 8.5.16 SAVE attribute, a local variable of a subprogram with the `SAVE` attribute retains its association status, allocation status, definition status, and value after execution of a `RETURN` or `END` statement—except when it is a pointer whose target becomes undefined. Furthermore, if the variable belongs to a subprogram, it is shared across all entry points of that subprogram.  

Therefore, using `x` when subprograms are executed starting from an ENTRY statement the latter part is standard-compliant and should behave consistently regardless of optimization level.  

However, when compiled with Flang using `-O2` or higher, `allocated(x)` incorrectly returns `.false.` inside the latter part, resulting in a premature `STOP`. This behavior does not occur with `-O0` or `-O1`, nor with other compilers such as `gfortran` and `ifx`.

The following are the test program, Flang, Gfortran and ifx compilation/execution results.

short.f90:
```fortran
call sub
call ent
end

subroutine sub
  integer, allocatable, dimension(:), save :: x
  allocate(x(10))
  return

entry ent
  if (.not. allocated(x)) then
    stop
  end if
  if ( x(5) .ne. 4 ) then
     print *,'pass'
  end if
end subroutine sub
```

```
$ flang short.f90 -O0
$ ./a.out
 pass
```
```
$ flang short.f90 -O1
$ ./a.out
 pass
```
```
$ flang short.f90 -O2
$ ./a.out
Fortran STOP
```

```
$ gfortran short.f90 -O0
$ ./a.out
 pass
```
```
$ gfortran short.f90 -O1
$ ./a.out
 pass
```
```
$ gfortran short.f90 -O2
$ ./a.out
 pass
```

```
$ ifx short.f90 -O0
$ ./a.out
 pass
```
```
$ ifx short.f90 -O1
$ ./a.out
 pass
```
```
$ ifx short.f90 -O2
$ ./a.out
 pass
```

_______________________________________________
llvm-bugs mailing list
llvm-bugs@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to