https://gcc.gnu.org/bugzilla/show_bug.cgi?id=129310

            Bug ID: 129310
           Summary: wrong code at -O3 with -ftrapv: a defined integer
                    reduction aborts
           Product: gcc
           Version: 17.0
            Status: UNCONFIRMED
          Keywords: wrong-code
          Severity: normal
          Priority: P3
         Component: tree-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: kyuwoncho18 at gmail dot com
  Target Milestone: ---
            Target: x86_64-pc-linux-gnu

#include <stdio.h>
#include <limits.h>

static int a[4][4];
static int b[4][4];
static volatile int requested = 2;

__attribute__((noinline)) static int get_n(void) { return requested; }

__attribute__((noinline))
static int reduce(int n)
{
  int sum = 0;
  for (int j = 0; j < n; ++j)
    for (int i = 0; i < n; ++i)
      sum += a[i][j] * b[i][j];
  return sum;
}

int main(void)
{
  a[0][0] = 1500000000; b[0][0] = 1;
  a[1][0] = -1500000000; b[1][0] = 1;
  a[0][1] = 1500000000; b[0][1] = 1;
  a[1][1] = 0; b[1][1] = 1;
  int n = get_n();
  printf("%d\n", reduce(n));
  return 0;
}

godbolt: https://godbolt.org/z/a44ETzro1

At -O0 -ftrapv the program prints 1500000000 and exits successfully, while at
-O3 -ftrapv it aborts. The source-order additions never overflow, so 1500000000
is the correct result and no overflow trap should occur. GCC documents that
-ftrapv generates traps for signed addition, subtraction, and multiplication
overflow: https://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html

Reply via email to