Drop clamp expressions where bounds cross
GCC now removes redundant clamping operations where the bounds are logically inverted.
GCC’s pattern matching system can now eliminate certain redundant ‘clamp’ expressions. Specifically, expressions like MIN(MAX(X, Y + CST), Y) where CST is positive, or its dual MAX(MIN(X, Y + CST), Y) with a negative CST, are simplified away. These patterns arise after inlining when a clamp’s bounds are already satisfied by prior operations, making the clamp itself unnecessary and reducible to a simple assignment of one of the bounds.
In Details
A new pattern in match.pd handles the simplification of nested min/max operations that effectively act as clamps. The patterns MIN(MAX(X, Y + CST), Y) for CST > 0 and MAX(MIN(X, Y + CST), Y) for CST < 0 are recognized. In the first case, Y + CST is always greater than Y, so MAX(X, Y + CST) results in a value that is at least Y + CST. The outer MIN then selects Y, effectively making the entire expression equal to Y. Similarly, the dual pattern simplifies to Y. This rule simplifies code generated from inlined clamp helpers where bounds have already been established.
- match.pd
- A file within GCC that defines pattern matching rules for simplifying intermediate code representations. It allows the compiler to recognize common code sequences and replace them with more efficient equivalents.
- clamp
- An operation that restricts a value to be within a specified range [min, max]. If the value is below min, it becomes min; if it's above max, it becomes max; otherwise, it remains unchanged.
- inlining
- A compiler optimization technique where a function call is replaced by the body of the function itself. This can reduce function call overhead but may increase code size.
- CST
- Abbreviation for 'constant' often used in compiler source code to refer to a constant value.