Bug 96693

Summary: [11 Regression] GCC produces incorrect code with -O2 for loops
Product: gcc Reporter: Vsevolod Livinskii <vsevolod.livinskiy>
Component: tree-optimizationAssignee: Richard Biener <rguenth>
Status: RESOLVED DUPLICATE    
Severity: normal CC: babokin, regehr, vsevolod.livinskiy
Priority: P3 Keywords: wrong-code
Version: 11.0   
Target Milestone: 11.0   
Host: Target:
Build: Known to work:
Known to fail: Last reconfirmed: 2020-08-25 00:00:00
Bug Depends on:    
Bug Blocks: 103035    

Description Vsevolod Livinskii 2020-08-18 22:34:36 UTC
Error:
>$ g++ -O2 driver.cpp func.cpp && ./a.out
0
>$ g++ -O0 driver.cpp func.cpp && ./a.out
42

Reproducer:
//func.cpp
extern char var_20;
extern short var_22;
void test(unsigned a,
          bool b,
          long long p12[23]) {
  for (int c = 0; c < 2;) {
    if (b) {
      for (int d = 0; d < 4082; d += 2)
        for (int e = 0; e < a; e = 2)
          var_20 = 0;
      var_22 = 0;
    }
    c = p12[c];
  }
}

//driver.cpp 
#include <stdio.h>

unsigned int var_4 = 140810747U;
bool var_7 = (bool)0;
unsigned char var_20 = (unsigned char)82;
unsigned short var_22 = 42;
long long int arr_9 [23] ;

void test(unsigned int var_4, bool var_7, long long int arr_9 [23]);

int main() {
    for (size_t i_0 = 0; i_0 < 23; ++i_0) 
        arr_9 [i_0] = -722784397873599555LL;
    test(var_4, var_7, arr_9);
    printf("%d\n", var_22);
}

GCC version:
11.0.0 20200816 (23747614cc8fc137c1f2ca64c8e224125a72fae5) + fix proposed in bug 95396
Comment 1 Richard Biener 2020-08-25 10:58:26 UTC
Confirmed.  Looks like caused by my store-motion rewrite.
Comment 2 Richard Biener 2020-08-25 10:59:21 UTC
unsigned int var_4 = 140810747U;
bool var_7 = (bool)0;
unsigned char var_20 = (unsigned char)82;
unsigned short var_22 = 42;
long long int arr_9 [23] ;

void __attribute__((noipa)) test(unsigned a, bool b, long long p12[23])
{
  for (int c = 0; c < 2;) {
      if (b) {
          for (int d = 0; d < 4082; d += 2)
            for (int e = 0; e < a; e = 2)
              var_20 = 0;
          var_22 = 0;
      }
      c = p12[c];
  }
}

int main()
{
  for (unsigned long i_0 = 0; i_0 < 23; ++i_0)
    arr_9 [i_0] = -722784397873599555LL;
  test(var_4, var_7, arr_9);
  if (var_22 != 42)
    __builtin_abort ();
}
Comment 3 Richard Biener 2020-08-25 12:47:04 UTC
Actually the same as PR96760, too.

*** This bug has been marked as a duplicate of bug 96760 ***