Optimize comparisons of masked values for improved code generation
Simplify comparisons involving masked arithmetic operations to generate more efficient code.
This commit enhances the match.pd component to fold certain comparisons involving masked values and arithmetic operations. It transforms expressions like ((X + C1) & LOWMASK) ==/!= C2 into simpler forms, reducing the number of instructions generated. This optimization is particularly beneficial for code generation on architectures like AArch64, as demonstrated by a significant reduction in instruction count for a sample function. New tests are added to cover these folding rules.
In Details
The match.pd pattern matching system now folds two classes of comparisons involving masked arithmetic. The first, ((X + C1) & LOWMASK) ==/!= C2, simplifies by moving the constant C1 across the comparison and removing the addition, as only the low bits of the sum are relevant after masking. The second, (X & HIGHMASK) >/<= C, simplifies by adjusting the constant C based on the mask. These rewrites are applied by the pattern matcher and aim to produce more efficient conditional branches and comparisons, especially for loop guards and conditional logic.
- match.pd
- A file within GCC that contains pattern-matching definitions used by various optimization passes to recognize and transform specific code structures in the intermediate representation (IR).
- MASK
- A bitmask is a value used to select or deselect specific bits within another value. Bitwise AND operations with a mask are common for isolating or clearing certain bits.
- Folding
- In compiler optimization, folding refers to the process of replacing an expression with its computed value at compile time, often simplifying the intermediate representation.
- Intermediate Representation (IR)
- A representation of the program that is between the source code and the machine code. GCC uses several forms of IR, such as GIMPLE, for performing optimizations.