GCC Newspaper
OCTOBER 6, 2026
Date
/
Architectures
Components
Topics
News & Policy
Other
match Performance Win

Remove casts for `(int)-(unsigned)a`

Optimizes negation of unsigned integers cast to signed types by removing redundant casts.

This commit optimizes the negation of unsigned integers cast to signed types, specifically targeting expressions like (int)-(unsigned)a. It introduces checks to remove redundant casts when signed integer overflow occurs, aligning with the behavior of -fwrapv. The optimization is achieved by refining pattern matching rules to recognize and simplify these expressions, including handling cases where the result of the negation might be INT_MIN. New test cases are provided.

In Details

The match.pd optimization pass is enhanced to better handle the negation of unsigned integers cast to signed types. Previously, a patch that introduced casts for signed integer overflow handling sometimes resulted in redundant casts in expressions like (int)-(unsigned)a. This update refines the matching rules to identify such patterns, particularly when TYPE_OVERFLOW_WRAPS is set (indicating wrap-around behavior), and simplifies them by removing unnecessary casts. It leverages expr_not_equal_to and specific checks for INT_MIN to ensure correctness across different scenarios.

For Context
match.pd
A file containing pattern matching rules used by GCC's optimization passes to recognize and transform specific code sequences.
cast
An explicit conversion from one data type to another.
signed integer overflow
Occurs when the result of an arithmetic operation on signed integers exceeds the maximum representable value or goes below the minimum representable value for that type. The behavior is undefined by the C standard unless -fwrapv is used, which specifies wrap-around behavior.
-fwrapv
A GCC flag that specifies that signed integer overflow and division by zero should wrap around, rather than producing undefined behavior.
INT_MIN
The minimum representable value for a signed integer type (e.g., INT_MIN for int).
Filed Under: optimizationtype conversionpattern matching