[Bug tree-optimization/113896] [12 Regression] Assigning array elements in the wrong order after floating point optimization since r12-8841

2024-02-14 Thread noobie-iv at mail dot ru via Gcc-bugs
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=113896

--- Comment #9 from noobie-iv at mail dot ru ---
I confirm that the original bug in the scantailor-experimental project was also
fixed by commit 2f16c53558d01135f0f78cf78a2f722b774684d7.

[Bug c++/113896] New: Assigning array elements in the wrong order after floating point optimization

2024-02-12 Thread noobie-iv at mail dot ru via Gcc-bugs
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=113896

Bug ID: 113896
   Summary: Assigning array elements in the wrong order after
floating point optimization
   Product: gcc
   Version: 12.3.1
Status: UNCONFIRMED
  Severity: normal
  Priority: P3
 Component: c++
  Assignee: unassigned at gcc dot gnu.org
  Reporter: noobie-iv at mail dot ru
  Target Milestone: ---

Created attachment 57404
  --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=57404=edit
Test program and build_and_run script

/* file: f.cpp */
extern double a1; // 1.0
extern double a2; // 1.0

void f(double K[2], bool b)
{
double A[] = {
b ? a1 : a2,
0,
0,
0
};

double sum{};
for(double  a : A) sum += a;
for(double& a : A) a /= sum;

if (b) {
K[0] = A[0]; // 1.0
K[1] = A[1]; // 0.0
} else {
K[0] = A[0] + A[1];
}
}

/* file: main.cpp */
#include 

double a1 = 1.0;
double a2 = 1.0;

void f(double K[2], bool b);

int main()
{
double K[2]{};
f(K, true);
std::cout << K[0] << "\t" << K[1] << "\n";
}

Bug: Returns different results when compiled with different optimization
settings:
g++ -O2 -ffast-math f.cpp main.cpp -o good
g++ -O3 -ffast-math f.cpp main.cpp -o bad
./good outputs "1 0"
./bad outputs "0 1"

The bug is reproduced in systems:
* Fedora-37-1.7 x64 with latest gcc autoupdate (12.3.1 20230508)
* Debian-12.2.0 x64 with gcc-12.3.1 build from sources

In the gcc-12 branch:
* Last good commit: d127348d7711e148e5ddd205a8c3409b37fae64c (12.2.1 20221017)
* First bad commit: fe7d74313736b8e1c30812bc49419f419bdf1c53 (12.2.1 20221017)
* Last tested bad commit: 4ced4ca95001f1583623c801c9c3642224a2c4f0 (12.3.1
20240210)

In the gcc-13 branch - There is no bug:
* Last tested good commit: c891d8dc23e1a46ad9f3e757d09e57b500d40044 (13.2.0)
In the gcc-14 branch - There is no bug:
* Last tested good commit: cff174fabd6c980c09aee95db1d9d5c22421761f (14.0.1
20240210)

Note: Function f() is a simplified version of the
XSpline::linearCombinationFor() function from the scantailor-experimental
project:
https://github.com/ImageProcessing-ElectronicPublications/scantailor-experimental/blob/main/src/math/XSpline.cpp
Now the bug has been temporarily resolved by declaring array A volatile.