Bug 106542 - -O2 sign-extended uint32 to uint64
Summary: -O2 sign-extended uint32 to uint64
Status: RESOLVED INVALID
Alias: None
Product: gcc
Classification: Unclassified
Component: c++ (show other bugs)
Version: 9.3.1
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2022-08-06 02:46 UTC by wuz73
Modified: 2022-08-06 03:58 UTC (History)
0 users

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description wuz73 2022-08-06 02:46:34 UTC
#include <iostream>

unsigned Msb(uint64_t x) { return 63 - __builtin_clzl(x); }

template<typename T>
void f(T r, T p)
{
    if (p > r)
    {
        auto d = p - r;
        unsigned k = Msb(sizeof(T) == 4 ? unsigned(d) : d);
        std::cout << sizeof(T) << " k=" << k << "\n";
    }
}

int main()
{
  int data[] = {-1610499096,2086724600};
  f(data[0],data[1]);
}

When compiled with "g++ -O2" the output is "4 k=63". Apparently before calling Msb(), g++ sign-extended unsigned(d). static_cast<unsigend>(d) yields the same result. However, "g++ -O0" is correct (k=31), so are earlier versions of g++ such as 4.8.5 and 5.3.1.
Comment 1 Andrew Pinski 2022-08-06 03:32:31 UTC
The code is undefined and can be detected with -fsanitize=undefined:

/app/example.cpp:15:14: runtime error: signed integer overflow: 2086724600 - -1610499096 cannot be represented in type 'int'
Comment 2 wuz73 2022-08-06 03:51:13 UTC
(In reply to Andrew Pinski from comment #1)
> The code is undefined and can be detected with -fsanitize=undefined:
> 
> /app/example.cpp:15:14: runtime error: signed integer overflow: 2086724600 -
> -1610499096 cannot be represented in type 'int'

I'm only interested in the lower 32 bits, hence the unsigned(d).
Comment 3 Andrew Pinski 2022-08-06 03:58:23 UTC
The code is undefined as the subtraction is done in the int type.
You either need to use -fwrapv or cast to an unsigned type before doing the subtraction.