https://gcc.gnu.org/bugzilla/show_bug.cgi?id=128872
Bug ID: 128872
Summary: [15/16/17 Regression] wrong code at -O2 and above:
unsigned saturating subtraction (a >= b ? a - b : 0)
on unsigned char/short is sign-extended when widened
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: haoxintu at gmail dot com
Target Milestone: ---
Hi,
$cat repro.c
[[gnu::noipa]] short f (unsigned char b, unsigned char c)
{
return (c >= b) * (unsigned char) (c - b);
}
int main (void)
{
/* c >= b, c - b == 200: the unsigned char product is 200, so f must return
200. */
if (f (0, 200) != 200)
__builtin_abort ();
return 0;
}
$ gcc -O2 repro.c && ./a.out # also -O3, -Os; -O0 / -O1 fine
Aborted
(c >= b) * (unsigned char)(c - b) is an unsigned char saturating subtraction;
its value is in [0, 255], so
f (0, 200) must be 200. At -O2 the result is sign-extended to short (f returns
-56):
## Checked Versions
- gcc 13: correct
- gcc 15.2, gcc 16, trunk 9571dd0b721 (2026-11-17): wrong at -O2/-O3/-Os
- clang: correct
Reproduced in Godbolt: https://godbolt.org/z/6YPKefc7Y
Thanks.