Issue 239228
Summary [flang] OUT_OF_RANGE with a REAL(10) argument gives wrong, nondeterministic results
Labels miscompilation, flang:frontend
Assignees
Reporter eugeneepshteyn
    On x86_64, `OUT_OF_RANGE` with a REAL(10) `X` gives wrong answers that depend on leftover stack contents. Both the REAL→INTEGER and REAL→REAL forms are affected.

```fortran
program p
  implicit none
  real(10) :: x
  x = -128.5_10
  call dirty()
  call check(x)
contains
  subroutine dirty()
    integer(1), volatile :: junk(512)
    junk = -1
  end subroutine
  subroutine check(v)
    real(10), intent(in) :: v
    ! ANINT(-128.5) = -129 fits in INTEGER(8), so this must print F
    print *, out_of_range(v, 0_8, .true.)
  end subroutine
end program
```

`flang -O0 t.f90 && ./a.out` prints `T` on every run; the expected result is `F`.

```fortran
program p
  implicit none
  real(10) :: x, y
  x = 1.0e400_10
  y = 1.0_10
  call dirty()
  call check(x, y)
contains
  subroutine dirty()
    integer(1), volatile :: junk(512)
    junk = -1
  end subroutine
  subroutine check(v, w)
    real(10), intent(in) :: v, w
    ! expect T (v > HUGE(0.0_8)) and F (w fits)
    print *, out_of_range(v, 0.0_8), out_of_range(w, 0.0_8)
  end subroutine
end program
```

At `-O0` this prints `F F`; the expected result is `T F`.

These two programs give the right answer at `-O2`/`-O3`. Without the `dirty()` call the results at `-O3` vary from run to run: a program that calls `out_of_range(v, 0_8, .true.)` three times on `v = -128.5_10` printed a wrong `T` in 5 of 30 runs.

`RewriteOutOfRange` in `flang/lib/Evaluate/fold-logical.cpp` rewrites these calls into unsigned comparisons of `TRANSFER(..., mold)` results. `IntTransferMold` chooses the mold kind as `max(alignment, byte size)` of the REAL kind, which is INTEGER(16) for REAL(10). The REAL(10) value occupies only 10 bytes, and for the rest of a longer TRANSFER result "the remainder is processor dependent" (F2023 16.9.212 p5). The upper 6 bytes therefore come from whatever is in memory, and they decide the unsigned comparison.

Reproduced on x86_64 Linux with main at 1087db09497370a892a0586ffa1e5827ab9b1c4f.

(This issue was filed with the help of AI)


_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to