Prevent overflow when simplifying conditional expressions involving addition
Fixes an optimization that could introduce signed integer overflow by checking for overflow before simplifying conditional expressions.
An optimization in match.pd has been corrected to prevent the introduction of signed integer overflow. The simplification x != CST1 ? x + CST2 : CST3 -> x + CST2 could previously create overflow scenarios. The fix now checks if CST1 + CST2 overflows; if it does and the type does not wrap around, the simplification is rewritten using unsigned addition to maintain correctness.
In Details
The match.pd pattern (x != CST1 ? x + CST2 : CST3 -> x + CST2) has been updated. Previously, it could introduce signed overflow if CST1 + CST2 overflowed and the target type's overflow behavior was not defined as wrapping. The corrected logic checks for this overflow condition. If TYPE_OVERFLOW_WRAPS is true or if CST1 + CST2 does not overflow, the original simplification is applied. Otherwise, it's transformed into an equivalent unsigned addition to avoid undefined behavior.
- match.pd
- A file in GCC that defines patterns for the pattern-matching engine, used for tree-based optimizations. It allows defining complex transformations based on the structure of the intermediate representation.
- signed integer overflow
- An arithmetic condition that occurs when the result of an operation on signed integers exceeds the maximum representable value or goes below the minimum representable value for that type. In C++, signed integer overflow results in undefined behavior.
- CST1, CST2, CST3
- Placeholders within
match.pdpatterns representing constant values used in the expression being matched. - TYPE_OVERFLOW_WRAPS
- A flag or condition associated with a data type that indicates whether signed integer overflow results in wrapping behavior (similar to unsigned integers) or undefined behavior.