This is an attempt to move one pattern from fold-const.c to match.pd. It ought to be 1:1, but is not, e.g. with this patch we won't fold e.g.
int f (int a, int b) { return a - (unsigned) ((a / b) * b) } anymore, but we're able to fold int ff (int a, unsigned int b) { return a - ((a / b) * b); } and fold-const.c is not. I played around with converts, but didn't find anything that would work well. Any suggestions how to make this pattern better? More to come... Bootstrapped/regtested on x86_64-linux, ok for trunk? 2015-06-26 Marek Polacek <pola...@redhat.com> * fold-const.c (fold_binary_loc): Move X - (X / Y) * Y -> X % Y to ... * match.pd: ... pattern here. diff --git gcc/fold-const.c gcc/fold-const.c index 6f12dd0..01e3983 100644 --- gcc/fold-const.c +++ gcc/fold-const.c @@ -10509,19 +10509,6 @@ fold_binary_loc (location_t loc, fold_convert_loc (loc, type, TREE_OPERAND (arg0, 0))); - /* X - (X / Y) * Y is X % Y. */ - if ((INTEGRAL_TYPE_P (type) || VECTOR_INTEGER_TYPE_P (type)) - && TREE_CODE (arg1) == MULT_EXPR - && TREE_CODE (TREE_OPERAND (arg1, 0)) == TRUNC_DIV_EXPR - && operand_equal_p (arg0, - TREE_OPERAND (TREE_OPERAND (arg1, 0), 0), 0) - && operand_equal_p (TREE_OPERAND (TREE_OPERAND (arg1, 0), 1), - TREE_OPERAND (arg1, 1), 0)) - return - fold_convert_loc (loc, type, - fold_build2_loc (loc, TRUNC_MOD_EXPR, TREE_TYPE (arg0), - arg0, TREE_OPERAND (arg1, 1))); - if (! FLOAT_TYPE_P (type)) { /* Fold A - (A & B) into ~B & A. */ diff --git gcc/match.pd gcc/match.pd index b2f8429..2bc158b 100644 --- gcc/match.pd +++ gcc/match.pd @@ -238,6 +238,12 @@ along with GCC; see the file COPYING3. If not see && tree_nop_conversion_p (type, TREE_TYPE (@1))) (trunc_mod @0 (convert @1)))) +/* X - (X / Y) * Y is the same as X % Y. */ +(simplify + (minus @0 (mult (trunc_div @0 @1) @1)) + (if (INTEGRAL_TYPE_P (type) || VECTOR_INTEGER_TYPE_P (type)) + (trunc_mod @0 @1))) + /* Optimize TRUNC_MOD_EXPR by a power of two into a BIT_AND_EXPR, i.e. "X % C" into "X & (C - 1)", if X and C are positive. Also optimize A % (C << N) where C is a power of 2, Marek