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

Fold A - MIN (B, C) to A + MAX (-B, -C) in match.pd.

GCC's pattern matching now optimizes subtraction with min/max, improving code generation.

This commit introduces new patterns to GCC’s match.pd that optimize expressions of the form A - MIN (B, C) and A - MAX (B, C) into additions with negated max/min respectively. This transformation, A - MIN(B, C) -> A + MAX(-B, -C), requires that B and C are negatable and accounts for potential overflow in wrapping types, leading to more efficient code generation.

In Details

This patch adds two new patterns to match.pd to simplify arithmetic involving MIN/MAX. Specifically, it handles A - MIN(B, C) and A - MAX(B, C) by transforming them into A + MAX(-B, -C) and A + MIN(-B, -C), respectively. This requires the operand types to support negation (negate_expr_p) and uses TYPE_OVERFLOW_UNDEFINED to correctly handle cases where the intermediate negation might overflow for wrapping types. This optimization is part of a larger effort to improve the compiler's ability to generate efficient code for common arithmetic idioms.

For Context
match.pd
A file containing pattern definitions used by GCC's GIMPLE (Generic Intermediate Language) pattern matcher to simplify and optimize code.
GIMPLE
GCC's three-address intermediate representation, used internally for performing optimizations before code generation.
fold
An optimization where an expression is replaced by its computed value if the value is known at compile time.
negate_expr_p
A predicate function that checks if an expression can be safely negated, considering the type's properties and potential overflow.
TYPE_OVERFLOW_UNDEFINED
A compiler flag or type property indicating that arithmetic operations on a type have undefined behavior on overflow, common for unsigned types or signed types with -fwrapv.
Filed Under: optimizationgcc