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

            Bug ID: 93184
           Summary: Incorrect result of right shift bit operation if
                    compile-time constant shift amount exceeds type width
           Product: gcc
           Version: 7.4.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: rtl-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: wojtek.golf at interia dot pl
  Target Milestone: ---

GCC version: 7.4.0 (but seen in other versions as well, including trunk on
godbolt)
System: Ubuntu 18.04 LTS, godbolt online compiler, coliru online compiler
GCC build: stock version supplied with Ubuntu or either of the online compilers
mentioned
Command line: g++ -std=c++1z -O2 -Wall -Wextra main.cpp && ./a.out
Compiler output: nothing wrong with it

static
unsigned long long mask(const unsigned long long sz)
{
    auto const rv = (unsigned long long)-1 >> (8 - sz) * 8;
    return rv;
}

void pub(unsigned long long & out1, unsigned long long & out2, unsigned long
long const sz)
{
    auto const first = mask(9);
    out1 = first;

    auto const second = mask(sz); // sz equals 9 at runtime
    out2 = second;
}

Problem description:
There is a difference in the result of bit right shift operation applied to an
all-1s 64-bit unsigned integer when the code is generated based on the shift
amount that is derived from either a compile-time constant expression or a
runtime value.

The problem appears only when optimization leval is > 0;

Example on godbolt: https://godbolt.org/z/nENczm
Example on coliru: http://coliru.stacked-crooked.com/a/857711a4a7cf8416

When the shift amount is derived from a compile time constant the result of the
shift generated by the compiler is 0, which is different from the one that the
machine code generated for the runtime shift amount calculates.

For the code above executed program (see coliru example) for -O0 gives correct
output:

255
255

When optimization is enabled the output (incorrect) is

0
255

Reply via email to