https://gcc.gnu.org/bugzilla/show_bug.cgi?id=118259
Bug ID: 118259 Summary: -O3 optimisation bug fixed with -fno-inline Product: gcc Version: 14.1.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: fortran Assignee: unassigned at gcc dot gnu.org Reporter: mjr19 at cam dot ac.uk Target Milestone: --- Created attachment 60012 --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=60012&action=edit Module-free test case The following code, which is a poor random number generator, is expected to print 29 25 38 21 20 40 35 9 28 12 but with gfortran -O3 it produces 29 25 7 39 7 39 7 39 7 39 Tested on x86_64 and gfortran 13.2, 14.1, 15.0 (July 7th snapshot). If the write statement is uncommented, it gives the expected result. If compiled with "-O3 -fno-inline" it gives the expected result. "-Wall -Wextra" makes no complaint. It appears to me that gfortran is attempting to optimise a call to an impure subroutine too aggressively. module spin contains subroutine myrand(rnd) real::rnd integer,save::seed=42 seed=iand(seed*1103515245+12345,z'7fffffff') rnd=seed/2147483648.0 ! write(*,*)'R',rnd end subroutine myrand subroutine myrand_v(rnd) real::rnd(:) integer i do i=1,size(rnd) call myrand(rnd(i)) end do end subroutine myrand_v end module spin program test use spin implicit none integer::index1,index2,i ! real::rnd(2) ! gives a different result real::rnd(3) do i=1,5 call myrand_v(rnd) index1=int(50*rnd(1)) index2=int(50*rnd(2)) write(*,*)index1,index2 end do end program test I add as an attachment the same code but written to be module free. It behaves in the same way.