tree-optimization/111779 - Handle some BIT_FIELD_REFs in SRA
[official-gcc.git] / gcc / match.pd
blob51e5065d08602fde3d8c75555efde9149eabe5a6
1 /* Match-and-simplify patterns for shared GENERIC and GIMPLE folding.
2    This file is consumed by genmatch which produces gimple-match.cc
3    and generic-match.cc from it.
5    Copyright (C) 2014-2023 Free Software Foundation, Inc.
6    Contributed by Richard Biener <rguenther@suse.de>
7    and Prathamesh Kulkarni  <bilbotheelffriend@gmail.com>
9 This file is part of GCC.
11 GCC is free software; you can redistribute it and/or modify it under
12 the terms of the GNU General Public License as published by the Free
13 Software Foundation; either version 3, or (at your option) any later
14 version.
16 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
17 WARRANTY; without even the implied warranty of MERCHANTABILITY or
18 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
19 for more details.
21 You should have received a copy of the GNU General Public License
22 along with GCC; see the file COPYING3.  If not see
23 <http://www.gnu.org/licenses/>.  */
26 /* Generic tree predicates we inherit.  */
27 (define_predicates
28    integer_onep integer_zerop integer_all_onesp integer_minus_onep
29    integer_each_onep integer_truep integer_nonzerop
30    real_zerop real_onep real_minus_onep
31    zerop
32    initializer_each_zero_or_onep
33    CONSTANT_CLASS_P
34    tree_expr_nonnegative_p
35    tree_expr_nonzero_p
36    integer_valued_real_p
37    integer_pow2p
38    uniform_integer_cst_p
39    HONOR_NANS
40    uniform_vector_p
41    expand_vec_cmp_expr_p
42    bitmask_inv_cst_vector_p)
44 /* Operator lists.  */
45 (define_operator_list tcc_comparison
46   lt   le   eq ne ge   gt   unordered ordered   unlt unle ungt unge uneq ltgt)
47 (define_operator_list inverted_tcc_comparison
48   ge   gt   ne eq lt   le   ordered   unordered ge   gt   le   lt   ltgt uneq)
49 (define_operator_list inverted_tcc_comparison_with_nans
50   unge ungt ne eq unlt unle ordered   unordered ge   gt   le   lt   ltgt uneq)
51 (define_operator_list swapped_tcc_comparison
52   gt   ge   eq ne le   lt   unordered ordered   ungt unge unlt unle uneq ltgt)
53 (define_operator_list simple_comparison         lt   le   eq ne ge   gt)
54 (define_operator_list swapped_simple_comparison gt   ge   eq ne le   lt)
55 (define_operator_list BSWAP BUILT_IN_BSWAP16 BUILT_IN_BSWAP32
56             BUILT_IN_BSWAP64 BUILT_IN_BSWAP128)
58 #include "cfn-operators.pd"
60 /* Define operand lists for math rounding functions {,i,l,ll}FN,
61    where the versions prefixed with "i" return an int, those prefixed with
62    "l" return a long and those prefixed with "ll" return a long long.
64    Also define operand lists:
66      X<FN>F for all float functions, in the order i, l, ll
67      X<FN> for all double functions, in the same order
68      X<FN>L for all long double functions, in the same order.  */
69 #define DEFINE_INT_AND_FLOAT_ROUND_FN(FN) \
70   (define_operator_list X##FN##F BUILT_IN_I##FN##F \
71                                  BUILT_IN_L##FN##F \
72                                  BUILT_IN_LL##FN##F) \
73   (define_operator_list X##FN BUILT_IN_I##FN \
74                               BUILT_IN_L##FN \
75                               BUILT_IN_LL##FN) \
76   (define_operator_list X##FN##L BUILT_IN_I##FN##L \
77                                  BUILT_IN_L##FN##L \
78                                  BUILT_IN_LL##FN##L)
80 DEFINE_INT_AND_FLOAT_ROUND_FN (FLOOR)
81 DEFINE_INT_AND_FLOAT_ROUND_FN (CEIL)
82 DEFINE_INT_AND_FLOAT_ROUND_FN (ROUND)
83 DEFINE_INT_AND_FLOAT_ROUND_FN (RINT)
85 /* Unary operations and their associated IFN_COND_* function.  */
86 (define_operator_list UNCOND_UNARY
87   negate bit_not)
88 (define_operator_list COND_UNARY
89   IFN_COND_NEG IFN_COND_NOT)
91 /* Binary operations and their associated IFN_COND_* function.  */
92 (define_operator_list UNCOND_BINARY
93   plus minus
94   mult trunc_div trunc_mod rdiv
95   min max
96   IFN_FMIN IFN_FMAX
97   bit_and bit_ior bit_xor
98   lshift rshift)
99 (define_operator_list COND_BINARY
100   IFN_COND_ADD IFN_COND_SUB
101   IFN_COND_MUL IFN_COND_DIV IFN_COND_MOD IFN_COND_RDIV
102   IFN_COND_MIN IFN_COND_MAX
103   IFN_COND_FMIN IFN_COND_FMAX
104   IFN_COND_AND IFN_COND_IOR IFN_COND_XOR
105   IFN_COND_SHL IFN_COND_SHR)
107 /* Same for ternary operations.  */
108 (define_operator_list UNCOND_TERNARY
109   IFN_FMA IFN_FMS IFN_FNMA IFN_FNMS)
110 (define_operator_list COND_TERNARY
111   IFN_COND_FMA IFN_COND_FMS IFN_COND_FNMA IFN_COND_FNMS)
113 /* __atomic_fetch_or_*, __atomic_fetch_xor_*, __atomic_xor_fetch_*  */
114 (define_operator_list ATOMIC_FETCH_OR_XOR_N
115   BUILT_IN_ATOMIC_FETCH_OR_1 BUILT_IN_ATOMIC_FETCH_OR_2
116   BUILT_IN_ATOMIC_FETCH_OR_4 BUILT_IN_ATOMIC_FETCH_OR_8
117   BUILT_IN_ATOMIC_FETCH_OR_16
118   BUILT_IN_ATOMIC_FETCH_XOR_1 BUILT_IN_ATOMIC_FETCH_XOR_2
119   BUILT_IN_ATOMIC_FETCH_XOR_4 BUILT_IN_ATOMIC_FETCH_XOR_8
120   BUILT_IN_ATOMIC_FETCH_XOR_16
121   BUILT_IN_ATOMIC_XOR_FETCH_1 BUILT_IN_ATOMIC_XOR_FETCH_2
122   BUILT_IN_ATOMIC_XOR_FETCH_4 BUILT_IN_ATOMIC_XOR_FETCH_8
123   BUILT_IN_ATOMIC_XOR_FETCH_16)
124 /* __sync_fetch_and_or_*, __sync_fetch_and_xor_*, __sync_xor_and_fetch_*  */
125 (define_operator_list SYNC_FETCH_OR_XOR_N
126   BUILT_IN_SYNC_FETCH_AND_OR_1 BUILT_IN_SYNC_FETCH_AND_OR_2
127   BUILT_IN_SYNC_FETCH_AND_OR_4 BUILT_IN_SYNC_FETCH_AND_OR_8
128   BUILT_IN_SYNC_FETCH_AND_OR_16
129   BUILT_IN_SYNC_FETCH_AND_XOR_1 BUILT_IN_SYNC_FETCH_AND_XOR_2
130   BUILT_IN_SYNC_FETCH_AND_XOR_4 BUILT_IN_SYNC_FETCH_AND_XOR_8
131   BUILT_IN_SYNC_FETCH_AND_XOR_16
132   BUILT_IN_SYNC_XOR_AND_FETCH_1 BUILT_IN_SYNC_XOR_AND_FETCH_2
133   BUILT_IN_SYNC_XOR_AND_FETCH_4 BUILT_IN_SYNC_XOR_AND_FETCH_8
134   BUILT_IN_SYNC_XOR_AND_FETCH_16)
135 /* __atomic_fetch_and_*.  */
136 (define_operator_list ATOMIC_FETCH_AND_N
137   BUILT_IN_ATOMIC_FETCH_AND_1 BUILT_IN_ATOMIC_FETCH_AND_2
138   BUILT_IN_ATOMIC_FETCH_AND_4 BUILT_IN_ATOMIC_FETCH_AND_8
139   BUILT_IN_ATOMIC_FETCH_AND_16)
140 /* __sync_fetch_and_and_*.  */
141 (define_operator_list SYNC_FETCH_AND_AND_N
142   BUILT_IN_SYNC_FETCH_AND_AND_1 BUILT_IN_SYNC_FETCH_AND_AND_2
143   BUILT_IN_SYNC_FETCH_AND_AND_4 BUILT_IN_SYNC_FETCH_AND_AND_8
144   BUILT_IN_SYNC_FETCH_AND_AND_16)
146 /* With nop_convert? combine convert? and view_convert? in one pattern
147    plus conditionalize on tree_nop_conversion_p conversions.  */
148 (match (nop_convert @0)
149  (convert @0)
150  (if (tree_nop_conversion_p (type, TREE_TYPE (@0)))))
151 (match (nop_convert @0)
152  (view_convert @0)
153  (if (VECTOR_TYPE_P (type) && VECTOR_TYPE_P (TREE_TYPE (@0))
154       && known_eq (TYPE_VECTOR_SUBPARTS (type),
155                    TYPE_VECTOR_SUBPARTS (TREE_TYPE (@0)))
156       && tree_nop_conversion_p (TREE_TYPE (type), TREE_TYPE (TREE_TYPE (@0))))))
158 #if GIMPLE
159 /* These are used by gimple_bitwise_inverted_equal_p to simplify
160    detection of BIT_NOT and comparisons. */
161 (match (bit_not_with_nop @0)
162  (bit_not @0))
163 (match (bit_not_with_nop @0)
164  (convert (bit_not @0))
165  (if (tree_nop_conversion_p (type, TREE_TYPE (@0)))))
166 (for cmp (tcc_comparison)
167  (match (maybe_cmp @0)
168   (cmp@0 @1 @2))
169  (match (maybe_cmp @0)
170   (convert (cmp@0 @1 @2))
171    (if (tree_nop_conversion_p (type, TREE_TYPE (@0)))))
173 #endif
175 /* Transform likes of (char) ABS_EXPR <(int) x> into (char) ABSU_EXPR <x>
176    ABSU_EXPR returns unsigned absolute value of the operand and the operand
177    of the ABSU_EXPR will have the corresponding signed type.  */
178 (simplify (abs (convert @0))
179  (if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (@0))
180       && !TYPE_UNSIGNED (TREE_TYPE (@0))
181       && element_precision (type) > element_precision (TREE_TYPE (@0)))
182   (with { tree utype = unsigned_type_for (TREE_TYPE (@0)); }
183    (convert (absu:utype @0)))))
185 #if GIMPLE
186 /* Optimize (X + (X >> (prec - 1))) ^ (X >> (prec - 1)) into abs (X).  */
187 (simplify
188  (bit_xor:c (plus:c @0 (rshift@2 @0 INTEGER_CST@1)) @2)
189  (if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (@0))
190       && !TYPE_UNSIGNED (TREE_TYPE (@0))
191       && wi::to_widest (@1) == element_precision (TREE_TYPE (@0)) - 1)
192   (abs @0)))
193 #endif
195 /* Simplifications of operations with one constant operand and
196    simplifications to constants or single values.  */
198 (for op (plus pointer_plus minus bit_ior bit_xor)
199   (simplify
200     (op @0 integer_zerop)
201     (non_lvalue @0)))
203 /* 0 +p index -> (type)index */
204 (simplify
205  (pointer_plus integer_zerop @1)
206  (non_lvalue (convert @1)))
208 /* ptr - 0 -> (type)ptr */
209 (simplify
210  (pointer_diff @0 integer_zerop)
211  (convert @0))
213 /* See if ARG1 is zero and X + ARG1 reduces to X.
214    Likewise if the operands are reversed.  */
215 (simplify
216  (plus:c @0 real_zerop@1)
217  (if (fold_real_zero_addition_p (type, @0, @1, 0))
218   (non_lvalue @0)))
220 /* See if ARG1 is zero and X - ARG1 reduces to X.  */
221 (simplify
222  (minus @0 real_zerop@1)
223  (if (fold_real_zero_addition_p (type, @0, @1, 1))
224   (non_lvalue @0)))
226 /* Even if the fold_real_zero_addition_p can't simplify X + 0.0
227    into X, we can optimize (X + 0.0) + 0.0 or (X + 0.0) - 0.0
228    or (X - 0.0) + 0.0 into X + 0.0 and (X - 0.0) - 0.0 into X - 0.0
229    if not -frounding-math.  For sNaNs the first operation would raise
230    exceptions but turn the result into qNan, so the second operation
231    would not raise it.   */
232 (for inner_op (plus minus)
233  (for outer_op (plus minus)
234   (simplify
235    (outer_op (inner_op@3 @0 REAL_CST@1) REAL_CST@2)
236     (if (real_zerop (@1)
237          && real_zerop (@2)
238          && !HONOR_SIGN_DEPENDENT_ROUNDING (type))
239      (with { bool inner_plus = ((inner_op == PLUS_EXPR)
240                                 ^ REAL_VALUE_MINUS_ZERO (TREE_REAL_CST (@1)));
241              bool outer_plus
242                = ((outer_op == PLUS_EXPR)
243                   ^ REAL_VALUE_MINUS_ZERO (TREE_REAL_CST (@2))); }
244       (if (outer_plus && !inner_plus)
245        (outer_op @0 @2)
246        @3))))))
248 /* Simplify x - x.
249    This is unsafe for certain floats even in non-IEEE formats.
250    In IEEE, it is unsafe because it does wrong for NaNs.
251    PR middle-end/98420: x - x may be -0.0 with FE_DOWNWARD.
252    Also note that operand_equal_p is always false if an operand
253    is volatile.  */
254 (simplify
255  (minus @0 @0)
256  (if (!FLOAT_TYPE_P (type)
257       || (!tree_expr_maybe_nan_p (@0)
258           && !tree_expr_maybe_infinite_p (@0)
259           && (!HONOR_SIGN_DEPENDENT_ROUNDING (type)
260               || !HONOR_SIGNED_ZEROS (type))))
261   { build_zero_cst (type); }))
262 (simplify
263  (pointer_diff @@0 @0)
264  { build_zero_cst (type); })
266 (simplify
267  (mult @0 integer_zerop@1)
268  @1)
270 /* -x == x -> x == 0 */
271 (for cmp (eq ne)
272  (simplify
273   (cmp:c @0 (negate @0))
274    (if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (@0))
275         && !TYPE_OVERFLOW_WRAPS (TREE_TYPE(@0)))
276     (cmp @0 { build_zero_cst (TREE_TYPE(@0)); }))))
278 /* Maybe fold x * 0 to 0.  The expressions aren't the same
279    when x is NaN, since x * 0 is also NaN.  Nor are they the
280    same in modes with signed zeros, since multiplying a
281    negative value by 0 gives -0, not +0.  Nor when x is +-Inf,
282    since x * 0 is NaN.  */
283 (simplify
284  (mult @0 real_zerop@1)
285  (if (!tree_expr_maybe_nan_p (@0)
286       && (!HONOR_NANS (type) || !tree_expr_maybe_infinite_p (@0))
287       && (!HONOR_SIGNED_ZEROS (type) || tree_expr_nonnegative_p (@0)))
288   @1))
290 /* In IEEE floating point, x*1 is not equivalent to x for snans.
291    Likewise for complex arithmetic with signed zeros.  */
292 (simplify
293  (mult @0 real_onep)
294  (if (!tree_expr_maybe_signaling_nan_p (@0)
295       && (!HONOR_SIGNED_ZEROS (type)
296           || !COMPLEX_FLOAT_TYPE_P (type)))
297   (non_lvalue @0)))
299 /* Transform x * -1.0 into -x.  */
300 (simplify
301  (mult @0 real_minus_onep)
302   (if (!tree_expr_maybe_signaling_nan_p (@0)
303        && (!HONOR_SIGNED_ZEROS (type)
304            || !COMPLEX_FLOAT_TYPE_P (type)))
305    (negate @0)))
307 /* Transform x * { 0 or 1, 0 or 1, ... } into x & { 0 or -1, 0 or -1, ...},
308    unless the target has native support for the former but not the latter.  */
309 (simplify
310  (mult @0 VECTOR_CST@1)
311  (if (initializer_each_zero_or_onep (@1)
312       && !HONOR_SNANS (type)
313       && !HONOR_SIGNED_ZEROS (type))
314   (with { tree itype = FLOAT_TYPE_P (type) ? unsigned_type_for (type) : type; }
315    (if (itype
316         && (!VECTOR_MODE_P (TYPE_MODE (type))
317             || (VECTOR_MODE_P (TYPE_MODE (itype))
318                 && optab_handler (and_optab,
319                                   TYPE_MODE (itype)) != CODE_FOR_nothing)))
320     (view_convert (bit_and:itype (view_convert @0)
321                                  (ne @1 { build_zero_cst (type); })))))))
323 /* In SWAR (SIMD within a register) code a signed comparison of packed data
324    can be constructed with a particular combination of shift, bitwise and,
325    and multiplication by constants.  If that code is vectorized we can
326    convert this pattern into a more efficient vector comparison.  */
327 (simplify
328  (mult (bit_and (rshift @0 uniform_integer_cst_p@1)
329             uniform_integer_cst_p@2)
330     uniform_integer_cst_p@3)
331  (with {
332    tree rshift_cst = uniform_integer_cst_p (@1);
333    tree bit_and_cst = uniform_integer_cst_p (@2);
334    tree mult_cst = uniform_integer_cst_p (@3);
335   }
336   /* Make sure we're working with vectors and uniform vector constants.  */
337   (if (VECTOR_TYPE_P (type)
338        && tree_fits_uhwi_p (rshift_cst)
339        && tree_fits_uhwi_p (mult_cst)
340        && tree_fits_uhwi_p (bit_and_cst))
341    /* Compute what constants would be needed for this to represent a packed
342       comparison based on the shift amount denoted by RSHIFT_CST.  */
343    (with {
344      HOST_WIDE_INT vec_elem_bits = vector_element_bits (type);
345      poly_int64 vec_nelts = TYPE_VECTOR_SUBPARTS (type);
346      poly_int64 vec_bits = vec_elem_bits * vec_nelts;
347      unsigned HOST_WIDE_INT cmp_bits_i, bit_and_i, mult_i;
348      unsigned HOST_WIDE_INT target_mult_i, target_bit_and_i;
349      cmp_bits_i = tree_to_uhwi (rshift_cst) + 1;
350      mult_i = tree_to_uhwi (mult_cst);
351      target_mult_i = (HOST_WIDE_INT_1U << cmp_bits_i) - 1;
352      bit_and_i = tree_to_uhwi (bit_and_cst);
353      target_bit_and_i = 0;
355      /* The bit pattern in BIT_AND_I should be a mask for the least
356         significant bit of each packed element that is CMP_BITS wide.  */
357      for (unsigned i = 0; i < vec_elem_bits / cmp_bits_i; i++)
358        target_bit_and_i = (target_bit_and_i << cmp_bits_i) | 1U;
359     }
360     (if ((exact_log2 (cmp_bits_i)) >= 0
361          && cmp_bits_i < HOST_BITS_PER_WIDE_INT
362          && multiple_p (vec_bits, cmp_bits_i)
363          && vec_elem_bits <= HOST_BITS_PER_WIDE_INT
364          && target_mult_i == mult_i
365          && target_bit_and_i == bit_and_i)
366      /* Compute the vector shape for the comparison and check if the target is
367         able to expand the comparison with that type.  */
368      (with {
369        /* We're doing a signed comparison.  */
370        tree cmp_type = build_nonstandard_integer_type (cmp_bits_i, 0);
371        poly_int64 vector_type_nelts = exact_div (vec_bits, cmp_bits_i);
372        tree vec_cmp_type = build_vector_type (cmp_type, vector_type_nelts);
373        tree vec_truth_type = truth_type_for (vec_cmp_type);
374        tree zeros = build_zero_cst (vec_cmp_type);
375        tree ones = build_all_ones_cst (vec_cmp_type);
376       }
377       (if (expand_vec_cmp_expr_p (vec_cmp_type, vec_truth_type, LT_EXPR)
378            && expand_vec_cond_expr_p (vec_cmp_type, vec_truth_type, LT_EXPR))
379        (view_convert:type (vec_cond (lt:vec_truth_type
380                                      (view_convert:vec_cmp_type @0)
381                                      { zeros; })
382                            { ones; } { zeros; })))))))))
384 (for cmp (gt ge lt le)
385      outp (convert convert negate negate)
386      outn (negate negate convert convert)
387  /* Transform X * (X > 0.0 ? 1.0 : -1.0) into abs(X). */
388  /* Transform X * (X >= 0.0 ? 1.0 : -1.0) into abs(X). */
389  /* Transform X * (X < 0.0 ? 1.0 : -1.0) into -abs(X). */
390  /* Transform X * (X <= 0.0 ? 1.0 : -1.0) into -abs(X). */
391  (simplify
392   (mult:c @0 (cond (cmp @0 real_zerop) real_onep@1 real_minus_onep))
393   (if (!tree_expr_maybe_nan_p (@0) && !HONOR_SIGNED_ZEROS (type))
394    (outp (abs @0))))
395  /* Transform X * (X > 0.0 ? -1.0 : 1.0) into -abs(X). */
396  /* Transform X * (X >= 0.0 ? -1.0 : 1.0) into -abs(X). */
397  /* Transform X * (X < 0.0 ? -1.0 : 1.0) into abs(X). */
398  /* Transform X * (X <= 0.0 ? -1.0 : 1.0) into abs(X). */
399  (simplify
400   (mult:c @0 (cond (cmp @0 real_zerop) real_minus_onep real_onep@1))
401   (if (!tree_expr_maybe_nan_p (@0) && !HONOR_SIGNED_ZEROS (type))
402    (outn (abs @0)))))
404 /* Transform X * copysign (1.0, X) into abs(X). */
405 (simplify
406  (mult:c @0 (COPYSIGN_ALL real_onep @0))
407  (if (!tree_expr_maybe_nan_p (@0) && !HONOR_SIGNED_ZEROS (type))
408   (abs @0)))
410 /* Transform X * copysign (1.0, -X) into -abs(X). */
411 (simplify
412  (mult:c @0 (COPYSIGN_ALL real_onep (negate @0)))
413  (if (!tree_expr_maybe_nan_p (@0) && !HONOR_SIGNED_ZEROS (type))
414   (negate (abs @0))))
416 /* Transform copysign (CST, X) into copysign (ABS(CST), X). */
417 (simplify
418  (COPYSIGN_ALL REAL_CST@0 @1)
419  (if (REAL_VALUE_NEGATIVE (TREE_REAL_CST (@0)))
420   (COPYSIGN_ALL (negate @0) @1)))
422 /* Transform c ? x * copysign (1, y) : z to c ? x ^ signs(y) : z.
423    tree-ssa-math-opts.cc does the corresponding optimization for
424    unconditional multiplications (via xorsign).  */
425 (simplify
426  (IFN_COND_MUL:c @0 @1 (IFN_COPYSIGN real_onep @2) @3)
427  (with { tree signs = sign_mask_for (type); }
428   (if (signs)
429    (with { tree inttype = TREE_TYPE (signs); }
430     (view_convert:type
431      (IFN_COND_XOR:inttype @0
432       (view_convert:inttype @1)
433       (bit_and (view_convert:inttype @2) { signs; })
434       (view_convert:inttype @3)))))))
436 /* (x >= 0 ? x : 0) + (x <= 0 ? -x : 0) -> abs x.  */
437 (simplify
438   (plus:c (max @0 integer_zerop) (max (negate @0) integer_zerop))
439   (abs @0))
441 /* X * 1, X / 1 -> X.  */
442 (for op (mult trunc_div ceil_div floor_div round_div exact_div)
443   (simplify
444     (op @0 integer_onep)
445     (non_lvalue @0)))
447 /* (A / (1 << B)) -> (A >> B).
448    Only for unsigned A.  For signed A, this would not preserve rounding
449    toward zero.
450    For example: (-1 / ( 1 << B)) !=  -1 >> B.
451    Also handle widening conversions, like:
452    (A / (unsigned long long) (1U << B)) -> (A >> B)
453    or
454    (A / (unsigned long long) (1 << B)) -> (A >> B).
455    If the left shift is signed, it can be done only if the upper bits
456    of A starting from shift's type sign bit are zero, as
457    (unsigned long long) (1 << 31) is -2147483648ULL, not 2147483648ULL,
458    so it is valid only if A >> 31 is zero.  */
459 (simplify
460  (trunc_div (convert?@0 @3) (convert2? (lshift integer_onep@1 @2)))
461  (if ((TYPE_UNSIGNED (type) || tree_expr_nonnegative_p (@0))
462       && (!VECTOR_TYPE_P (type)
463           || target_supports_op_p (type, RSHIFT_EXPR, optab_vector)
464           || target_supports_op_p (type, RSHIFT_EXPR, optab_scalar))
465       && (useless_type_conversion_p (type, TREE_TYPE (@1))
466           || (element_precision (type) >= element_precision (TREE_TYPE (@1))
467               && (TYPE_UNSIGNED (TREE_TYPE (@1))
468                   || (element_precision (type)
469                       == element_precision (TREE_TYPE (@1)))
470                   || (INTEGRAL_TYPE_P (type)
471                       && (tree_nonzero_bits (@0)
472                           & wi::mask (element_precision (TREE_TYPE (@1)) - 1,
473                                       true,
474                                       element_precision (type))) == 0)))))
475    (if (!VECTOR_TYPE_P (type)
476         && useless_type_conversion_p (TREE_TYPE (@3), TREE_TYPE (@1))
477         && element_precision (TREE_TYPE (@3)) < element_precision (type))
478     (convert (rshift @3 @2))
479     (rshift @0 @2))))
481 /* Preserve explicit divisions by 0: the C++ front-end wants to detect
482    undefined behavior in constexpr evaluation, and assuming that the division
483    traps enables better optimizations than these anyway.  */
484 (for div (trunc_div ceil_div floor_div round_div exact_div)
485  /* 0 / X is always zero.  */
486  (simplify
487   (div integer_zerop@0 @1)
488   /* But not for 0 / 0 so that we can get the proper warnings and errors.  */
489   (if (!integer_zerop (@1))
490    @0))
491  /* X / -1 is -X.  */
492  (simplify
493   (div @0 integer_minus_onep@1)
494   (if (!TYPE_UNSIGNED (type))
495    (negate @0)))
496  /* X / bool_range_Y is X.  */ 
497  (simplify
498   (div @0 SSA_NAME@1)
499   (if (INTEGRAL_TYPE_P (type)
500        && ssa_name_has_boolean_range (@1)
501        && !flag_non_call_exceptions)
502    @0))
503  /* X / X is one.  */
504  (simplify
505   (div @0 @0)
506   /* But not for 0 / 0 so that we can get the proper warnings and errors.
507      And not for _Fract types where we can't build 1.  */
508   (if (!ALL_FRACT_MODE_P (TYPE_MODE (type))
509        && !integer_zerop (@0)
510        && (!flag_non_call_exceptions || tree_expr_nonzero_p (@0)))
511    { build_one_cst (type); }))
512  /* X / abs (X) is X < 0 ? -1 : 1.  */
513  (simplify
514    (div:C @0 (abs @0))
515    (if (INTEGRAL_TYPE_P (type)
516         && TYPE_OVERFLOW_UNDEFINED (type)
517         && !integer_zerop (@0)
518         && (!flag_non_call_exceptions || tree_expr_nonzero_p (@0)))
519     (cond (lt @0 { build_zero_cst (type); })
520           { build_minus_one_cst (type); } { build_one_cst (type); })))
521  /* X / -X is -1.  */
522  (simplify
523    (div:C @0 (negate @0))
524    (if ((INTEGRAL_TYPE_P (type) || VECTOR_INTEGER_TYPE_P (type))
525         && TYPE_OVERFLOW_UNDEFINED (type)
526         && !integer_zerop (@0)
527         && (!flag_non_call_exceptions || tree_expr_nonzero_p (@0)))
528     { build_minus_one_cst (type); })))
530 /* For unsigned integral types, FLOOR_DIV_EXPR is the same as
531    TRUNC_DIV_EXPR.  Rewrite into the latter in this case.  Similarly
532    for MOD instead of DIV.  */
533 (for floor_divmod (floor_div floor_mod)
534      trunc_divmod (trunc_div trunc_mod)
535  (simplify
536   (floor_divmod @0 @1)
537   (if ((INTEGRAL_TYPE_P (type) || VECTOR_INTEGER_TYPE_P (type))
538        && TYPE_UNSIGNED (type))
539    (trunc_divmod @0 @1))))
541 /* 1 / X -> X == 1 for unsigned integer X.
542    1 / X -> X >= -1 && X <= 1 ? X : 0 for signed integer X.
543    But not for 1 / 0 so that we can get proper warnings and errors,
544    and not for 1-bit integers as they are edge cases better handled
545    elsewhere.  */
546 (simplify
547  (trunc_div integer_onep@0 @1)
548  (if (INTEGRAL_TYPE_P (type)
549       && TYPE_PRECISION (type) > 1
550       && !integer_zerop (@1)
551       && (!flag_non_call_exceptions || tree_expr_nonzero_p (@1)))
552   (if (TYPE_UNSIGNED (type))
553    (convert (eq:boolean_type_node @1 { build_one_cst (type); }))
554    (with { tree utype = unsigned_type_for (type); }
555     (cond (le (plus (convert:utype @1) { build_one_cst (utype); })
556               { build_int_cst (utype, 2); })
557      @1 { build_zero_cst (type); })))))
559 /* Combine two successive divisions.  Note that combining ceil_div
560    and floor_div is trickier and combining round_div even more so.  */
561 (for div (trunc_div exact_div)
562  (simplify
563   (div (div@3 @0 INTEGER_CST@1) INTEGER_CST@2)
564   (with {
565     wi::overflow_type overflow;
566     wide_int mul = wi::mul (wi::to_wide (@1), wi::to_wide (@2),
567                             TYPE_SIGN (type), &overflow);
568    }
569    (if (div == EXACT_DIV_EXPR
570         || optimize_successive_divisions_p (@2, @3))
571     (if (!overflow)
572      (div @0 { wide_int_to_tree (type, mul); })
573      (if (TYPE_UNSIGNED (type)
574           || mul != wi::min_value (TYPE_PRECISION (type), SIGNED))
575       { build_zero_cst (type); }))))))
577 /* Combine successive multiplications.  Similar to above, but handling
578    overflow is different.  */
579 (simplify
580  (mult (mult @0 INTEGER_CST@1) INTEGER_CST@2)
581  (with {
582    wi::overflow_type overflow;
583    wide_int mul = wi::mul (wi::to_wide (@1), wi::to_wide (@2),
584                            TYPE_SIGN (type), &overflow);
585   }
586   /* Skip folding on overflow: the only special case is @1 * @2 == -INT_MIN,
587      otherwise undefined overflow implies that @0 must be zero.  */
588   (if (!overflow || TYPE_OVERFLOW_WRAPS (type))
589    (mult @0 { wide_int_to_tree (type, mul); }))))
591 /* Similar to above, but there could be an extra add/sub between
592    successive multuiplications.  */
593 (simplify
594  (mult (plus:s (mult:s@4 @0 INTEGER_CST@1) INTEGER_CST@2) INTEGER_CST@3)
595  (with {
596    bool overflowed = true;
597    wi::overflow_type ovf1, ovf2;
598    wide_int mul = wi::mul (wi::to_wide (@1), wi::to_wide (@3),
599                            TYPE_SIGN (type), &ovf1);
600    wide_int add = wi::mul (wi::to_wide (@2), wi::to_wide (@3),
601                            TYPE_SIGN (type), &ovf2);
602   if (TYPE_OVERFLOW_UNDEFINED (type))
603     {
604 #if GIMPLE
605       value_range vr0;
606       if (ovf1 == wi::OVF_NONE && ovf2 == wi::OVF_NONE
607           && get_global_range_query ()->range_of_expr (vr0, @4)
608           && !vr0.varying_p () && !vr0.undefined_p ())
609         {
610           wide_int wmin0 = vr0.lower_bound ();
611           wide_int wmax0 = vr0.upper_bound ();
612           wmin0 = wi::mul (wmin0, wi::to_wide (@3), TYPE_SIGN (type), &ovf1);
613           wmax0 = wi::mul (wmax0, wi::to_wide (@3), TYPE_SIGN (type), &ovf2);
614           if (ovf1 == wi::OVF_NONE && ovf2 == wi::OVF_NONE)
615             {
616               wi::add (wmin0, add, TYPE_SIGN (type), &ovf1);
617               wi::add (wmax0, add, TYPE_SIGN (type), &ovf2);
618               if (ovf1 == wi::OVF_NONE && ovf2 == wi::OVF_NONE)
619                 overflowed = false;
620             }
621         }
622 #endif
623     }
624   else
625    overflowed = false;
627   /* Skip folding on overflow.  */
628   (if (!overflowed)
629    (plus (mult @0 { wide_int_to_tree (type, mul); })
630          { wide_int_to_tree (type, add); }))))
632 /* Similar to above, but a multiplication between successive additions.  */
633 (simplify
634  (plus (mult:s (plus:s @0 INTEGER_CST@1) INTEGER_CST@2) INTEGER_CST@3)
635  (with {
636    bool overflowed = true;
637    wi::overflow_type ovf1;
638    wi::overflow_type ovf2;
639    wide_int mul = wi::mul (wi::to_wide (@1), wi::to_wide (@2),
640                            TYPE_SIGN (type), &ovf1);
641    wide_int add = wi::add (mul, wi::to_wide (@3),
642                            TYPE_SIGN (type), &ovf2);
643   if (TYPE_OVERFLOW_UNDEFINED (type))
644     {
645 #if GIMPLE
646       value_range vr0;
647       if (ovf1 == wi::OVF_NONE && ovf2 == wi::OVF_NONE
648           && get_global_range_query ()->range_of_expr (vr0, @0)
649           && !vr0.varying_p () && !vr0.undefined_p ())
650         {
651           wide_int wmin0 = vr0.lower_bound ();
652           wide_int wmax0 = vr0.upper_bound ();
653           wmin0 = wi::mul (wmin0, wi::to_wide (@2), TYPE_SIGN (type), &ovf1);
654           wmax0 = wi::mul (wmax0, wi::to_wide (@2), TYPE_SIGN (type), &ovf2);
655           if (ovf1 == wi::OVF_NONE && ovf2 == wi::OVF_NONE)
656             {
657               wi::add (wmin0, mul, TYPE_SIGN (type), &ovf1);
658               wi::add (wmax0, mul, TYPE_SIGN (type), &ovf2);
659               if (ovf1 == wi::OVF_NONE && ovf2 == wi::OVF_NONE)
660                 overflowed = false;
661             }
662         }
663 #endif
664     }
665   else
666    overflowed = false;
668   /* Skip folding on overflow.  */
669   (if (!overflowed)
670    (plus (mult @0 @2) { wide_int_to_tree (type, add); }))))
672 /* Optimize A / A to 1.0 if we don't care about
673    NaNs or Infinities.  */
674 (simplify
675  (rdiv @0 @0)
676  (if (FLOAT_TYPE_P (type)
677       && ! HONOR_NANS (type)
678       && ! HONOR_INFINITIES (type))
679   { build_one_cst (type); }))
681 /* Optimize -A / A to -1.0 if we don't care about
682    NaNs or Infinities.  */
683 (simplify
684  (rdiv:C @0 (negate @0))
685  (if (FLOAT_TYPE_P (type)
686       && ! HONOR_NANS (type)
687       && ! HONOR_INFINITIES (type))
688   { build_minus_one_cst (type); }))
690 /* PR71078: x / abs(x) -> copysign (1.0, x) */
691 (simplify
692  (rdiv:C (convert? @0) (convert? (abs @0)))
693   (if (SCALAR_FLOAT_TYPE_P (type)
694        && ! HONOR_NANS (type)
695        && ! HONOR_INFINITIES (type))
696    (switch
697     (if (types_match (type, float_type_node))
698      (BUILT_IN_COPYSIGNF { build_one_cst (type); } (convert @0)))
699     (if (types_match (type, double_type_node))
700      (BUILT_IN_COPYSIGN { build_one_cst (type); } (convert @0)))
701     (if (types_match (type, long_double_type_node))
702      (BUILT_IN_COPYSIGNL { build_one_cst (type); } (convert @0))))))
704 /* In IEEE floating point, x/1 is not equivalent to x for snans.  */
705 (simplify
706  (rdiv @0 real_onep)
707  (if (!tree_expr_maybe_signaling_nan_p (@0))
708   (non_lvalue @0)))
710 /* In IEEE floating point, x/-1 is not equivalent to -x for snans.  */
711 (simplify
712  (rdiv @0 real_minus_onep)
713  (if (!tree_expr_maybe_signaling_nan_p (@0))
714   (negate @0)))
716 (if (flag_reciprocal_math)
717  /* Convert (A/B)/C to A/(B*C). */
718  (simplify
719   (rdiv (rdiv:s @0 @1) @2)
720   (rdiv @0 (mult @1 @2)))
722  /* Canonicalize x / (C1 * y) to (x * C2) / y.  */
723  (simplify
724   (rdiv @0 (mult:s @1 REAL_CST@2))
725   (with
726    { tree tem = const_binop (RDIV_EXPR, type, build_one_cst (type), @2); }
727    (if (tem)
728     (rdiv (mult @0 { tem; } ) @1))))
730  /* Convert A/(B/C) to (A/B)*C  */
731  (simplify
732   (rdiv @0 (rdiv:s @1 @2))
733    (mult (rdiv @0 @1) @2)))
735 /* Simplify x / (- y) to -x / y.  */
736 (simplify
737  (rdiv @0 (negate @1))
738  (rdiv (negate @0) @1))
740 (if (flag_unsafe_math_optimizations)
741  /* Simplify (C / x op 0.0) to x op 0.0 for C != 0, C != Inf/Nan.
742     Since C / x may underflow to zero, do this only for unsafe math.  */
743  (for op (lt le gt ge)
744       neg_op (gt ge lt le)
745   (simplify
746    (op (rdiv REAL_CST@0 @1) real_zerop@2)
747    (if (!HONOR_SIGNED_ZEROS (@1) && !HONOR_INFINITIES (@1))
748     (switch
749      (if (real_less (&dconst0, TREE_REAL_CST_PTR (@0)))
750       (op @1 @2))
751      /* For C < 0, use the inverted operator.  */
752      (if (real_less (TREE_REAL_CST_PTR (@0), &dconst0))
753       (neg_op @1 @2)))))))
755 /* Optimize (X & (-A)) / A where A is a power of 2, to X >> log2(A) */
756 (for div (trunc_div ceil_div floor_div round_div exact_div)
757  (simplify
758   (div (convert? (bit_and @0 INTEGER_CST@1)) INTEGER_CST@2)
759   (if (integer_pow2p (@2)
760        && tree_int_cst_sgn (@2) > 0
761        && tree_nop_conversion_p (type, TREE_TYPE (@0))
762        && wi::to_wide (@2) + wi::to_wide (@1) == 0)
763    (rshift (convert @0)
764            { build_int_cst (integer_type_node,
765                             wi::exact_log2 (wi::to_wide (@2))); }))))
767 /* If ARG1 is a constant, we can convert this to a multiply by the
768    reciprocal.  This does not have the same rounding properties,
769    so only do this if -freciprocal-math.  We can actually
770    always safely do it if ARG1 is a power of two, but it's hard to
771    tell if it is or not in a portable manner.  */
772 (for cst (REAL_CST COMPLEX_CST VECTOR_CST)
773  (simplify
774   (rdiv @0 cst@1)
775   (if (optimize)
776    (if (flag_reciprocal_math
777         && !real_zerop (@1))
778     (with
779      { tree tem = const_binop (RDIV_EXPR, type, build_one_cst (type), @1); }
780      (if (tem)
781       (mult @0 { tem; } )))
782     (if (cst != COMPLEX_CST)
783      (with { tree inverse = exact_inverse (type, @1); }
784       (if (inverse)
785        (mult @0 { inverse; } ))))))))
787 (for mod (ceil_mod floor_mod round_mod trunc_mod)
788  /* 0 % X is always zero.  */
789  (simplify
790   (mod integer_zerop@0 @1)
791   /* But not for 0 % 0 so that we can get the proper warnings and errors.  */
792   (if (!integer_zerop (@1))
793    @0))
794  /* X % 1 is always zero.  */
795  (simplify
796   (mod @0 integer_onep)
797   { build_zero_cst (type); })
798  /* X % -1 is zero.  */
799  (simplify
800   (mod @0 integer_minus_onep@1)
801   (if (!TYPE_UNSIGNED (type))
802    { build_zero_cst (type); }))
803  /* X % X is zero.  */
804  (simplify
805   (mod @0 @0)
806   /* But not for 0 % 0 so that we can get the proper warnings and errors.  */
807   (if (!integer_zerop (@0))
808    { build_zero_cst (type); }))
809  /* (X % Y) % Y is just X % Y.  */
810  (simplify
811   (mod (mod@2 @0 @1) @1)
812   @2)
813  /* From extract_muldiv_1: (X * C1) % C2 is zero if C1 is a multiple of C2.  */
814  (simplify
815   (mod (mult @0 INTEGER_CST@1) INTEGER_CST@2)
816   (if (ANY_INTEGRAL_TYPE_P (type)
817        && TYPE_OVERFLOW_UNDEFINED (type)
818        && wi::multiple_of_p (wi::to_wide (@1), wi::to_wide (@2),
819                              TYPE_SIGN (type)))
820    { build_zero_cst (type); }))
821  /* For (X % C) == 0, if X is signed and C is power of 2, use unsigned
822     modulo and comparison, since it is simpler and equivalent.  */
823  (for cmp (eq ne)
824   (simplify
825    (cmp (mod @0 integer_pow2p@2) integer_zerop@1)
826    (if (!TYPE_UNSIGNED (TREE_TYPE (@0)))
827     (with { tree utype = unsigned_type_for (TREE_TYPE (@0)); }
828      (cmp (mod (convert:utype @0) (convert:utype @2)) (convert:utype @1)))))))
830 /* X % -C is the same as X % C.  */
831 (simplify
832  (trunc_mod @0 INTEGER_CST@1)
833   (if (TYPE_SIGN (type) == SIGNED
834        && !TREE_OVERFLOW (@1)
835        && wi::neg_p (wi::to_wide (@1))
836        && !TYPE_OVERFLOW_TRAPS (type)
837        /* Avoid this transformation if C is INT_MIN, i.e. C == -C.  */
838        && !sign_bit_p (@1, @1))
839    (trunc_mod @0 (negate @1))))
841 /* X % -Y is the same as X % Y.  */
842 (simplify
843  (trunc_mod @0 (convert? (negate @1)))
844  (if (INTEGRAL_TYPE_P (type)
845       && !TYPE_UNSIGNED (type)
846       && !TYPE_OVERFLOW_TRAPS (type)
847       && tree_nop_conversion_p (type, TREE_TYPE (@1))
848       /* Avoid this transformation if X might be INT_MIN or
849          Y might be -1, because we would then change valid
850          INT_MIN % -(-1) into invalid INT_MIN % -1.  */
851       && (expr_not_equal_to (@0, wi::to_wide (TYPE_MIN_VALUE (type)))
852           || expr_not_equal_to (@1, wi::minus_one (TYPE_PRECISION
853                                                         (TREE_TYPE (@1))))))
854   (trunc_mod @0 (convert @1))))
856 /* X - (X / Y) * Y is the same as X % Y.  */
857 (simplify
858  (minus (convert1? @0) (convert2? (mult:c (trunc_div @@0 @@1) @1)))
859  (if (INTEGRAL_TYPE_P (type) || VECTOR_INTEGER_TYPE_P (type))
860   (convert (trunc_mod @0 @1))))
862 /* x * (1 + y / x) - y -> x - y % x */
863 (simplify
864  (minus (mult:cs @0 (plus:s (trunc_div:s @1 @0) integer_onep)) @1)
865  (if (INTEGRAL_TYPE_P (type))
866   (minus @0 (trunc_mod @1 @0))))
868 /* Optimize TRUNC_MOD_EXPR by a power of two into a BIT_AND_EXPR,
869    i.e. "X % C" into "X & (C - 1)", if X and C are positive.
870    Also optimize A % (C << N)  where C is a power of 2,
871    to A & ((C << N) - 1).
872    Also optimize "A shift (B % C)", if C is a power of 2, to
873    "A shift (B & (C - 1))".  SHIFT operation include "<<" and ">>"
874    and assume (B % C) is nonnegative as shifts negative values would
875    be UB.  */
876 (match (power_of_two_cand @1)
877  INTEGER_CST@1)
878 (match (power_of_two_cand @1)
879  (lshift INTEGER_CST@1 @2))
880 (for mod (trunc_mod floor_mod)
881  (for shift (lshift rshift)
882   (simplify
883    (shift @0 (mod @1 (power_of_two_cand@2 @3)))
884    (if (integer_pow2p (@3) && tree_int_cst_sgn (@3) > 0)
885     (shift @0 (bit_and @1 (minus @2 { build_int_cst (TREE_TYPE (@2),
886                                                       1); }))))))
887  (simplify
888   (mod @0 (convert? (power_of_two_cand@1 @2)))
889   (if ((TYPE_UNSIGNED (type) || tree_expr_nonnegative_p (@0))
890        /* Allow any integral conversions of the divisor, except
891           conversion from narrower signed to wider unsigned type
892           where if @1 would be negative power of two, the divisor
893           would not be a power of two.  */
894        && INTEGRAL_TYPE_P (type)
895        && INTEGRAL_TYPE_P (TREE_TYPE (@1))
896        && (TYPE_PRECISION (type) <= TYPE_PRECISION (TREE_TYPE (@1))
897            || TYPE_UNSIGNED (TREE_TYPE (@1))
898            || !TYPE_UNSIGNED (type))
899        && integer_pow2p (@2) && tree_int_cst_sgn (@2) > 0)
900    (with { tree utype = TREE_TYPE (@1);
901            if (!TYPE_OVERFLOW_WRAPS (utype))
902              utype = unsigned_type_for (utype); }
903     (bit_and @0 (convert (minus (convert:utype @1)
904                                 { build_one_cst (utype); })))))))
906 /* Simplify (unsigned t * 2)/2 -> unsigned t & 0x7FFFFFFF.  */
907 (simplify
908  (trunc_div (mult @0 integer_pow2p@1) @1)
909  (if (INTEGRAL_TYPE_P (TREE_TYPE (@0)) && TYPE_UNSIGNED (TREE_TYPE (@0)))
910   (bit_and @0 { wide_int_to_tree
911                 (type, wi::mask (TYPE_PRECISION (type)
912                                  - wi::exact_log2 (wi::to_wide (@1)),
913                                  false, TYPE_PRECISION (type))); })))
915 /* Simplify (unsigned t / 2) * 2 -> unsigned t & ~1.  */
916 (simplify
917  (mult (trunc_div @0 integer_pow2p@1) @1)
918  (if (INTEGRAL_TYPE_P (TREE_TYPE (@0)) && TYPE_UNSIGNED (TREE_TYPE (@0)))
919   (bit_and @0 (negate @1))))
921 /* Simplify (t * 2) / 2) -> t.  */
922 (for div (trunc_div ceil_div floor_div round_div exact_div)
923  (simplify
924   (div (mult:c @0 @1) @1)
925   (if (ANY_INTEGRAL_TYPE_P (type))
926    (if (TYPE_OVERFLOW_UNDEFINED (type))
927     @0
928 #if GIMPLE
929     (with {value_range vr0, vr1;}
930      (if (INTEGRAL_TYPE_P (type)
931           && get_range_query (cfun)->range_of_expr (vr0, @0)
932           && get_range_query (cfun)->range_of_expr (vr1, @1)
933           && range_op_handler (MULT_EXPR).overflow_free_p (vr0, vr1))
934       @0))
935 #endif
936    ))))
938 #if GIMPLE
939 (for div (trunc_div exact_div)
940  /* Simplify (X + M*N) / N -> X / N + M.  */
941  (simplify
942   (div (plus:c@4 @0 (mult:c@3 @1 @2)) @2)
943   (with {value_range vr0, vr1, vr2, vr3, vr4;}
944   (if (INTEGRAL_TYPE_P (type)
945        && get_range_query (cfun)->range_of_expr (vr1, @1)
946        && get_range_query (cfun)->range_of_expr (vr2, @2)
947        /* "N*M" doesn't overflow.  */
948        && range_op_handler (MULT_EXPR).overflow_free_p (vr1, vr2)
949        && get_range_query (cfun)->range_of_expr (vr0, @0)
950        && get_range_query (cfun)->range_of_expr (vr3, @3)
951        /* "X+(N*M)" doesn't overflow.  */
952        && range_op_handler (PLUS_EXPR).overflow_free_p (vr0, vr3)
953        && get_range_query (cfun)->range_of_expr (vr4, @4)
954        && !vr4.undefined_p ()
955        /* "X+N*M" is not with opposite sign as "X".  */
956        && (TYPE_UNSIGNED (type)
957            || (vr0.nonnegative_p () && vr4.nonnegative_p ())
958            || (vr0.nonpositive_p () && vr4.nonpositive_p ())))
959   (plus (div @0 @2) @1))))
961  /* Simplify (X - M*N) / N -> X / N - M.  */
962  (simplify
963   (div (minus@4 @0 (mult:c@3 @1 @2)) @2)
964   (with {value_range vr0, vr1, vr2, vr3, vr4;}
965   (if (INTEGRAL_TYPE_P (type)
966        && get_range_query (cfun)->range_of_expr (vr1, @1)
967        && get_range_query (cfun)->range_of_expr (vr2, @2)
968        /* "N * M" doesn't overflow.  */
969        && range_op_handler (MULT_EXPR).overflow_free_p (vr1, vr2)
970        && get_range_query (cfun)->range_of_expr (vr0, @0)
971        && get_range_query (cfun)->range_of_expr (vr3, @3)
972        /* "X - (N*M)" doesn't overflow.  */
973        && range_op_handler (MINUS_EXPR).overflow_free_p (vr0, vr3)
974        && get_range_query (cfun)->range_of_expr (vr4, @4)
975        && !vr4.undefined_p ()
976        /* "X-N*M" is not with opposite sign as "X".  */
977        && (TYPE_UNSIGNED (type)
978            || (vr0.nonnegative_p () && vr4.nonnegative_p ())
979            || (vr0.nonpositive_p () && vr4.nonpositive_p ())))
980   (minus (div @0 @2) @1)))))
982 /* Simplify
983    (X + C) / N -> X / N + C / N where C is multiple of N.
984    (X + C) >> N -> X >> N + C>>N if low N bits of C is 0.  */
985 (for op (trunc_div exact_div rshift)
986  (simplify
987   (op (plus@3 @0 INTEGER_CST@1) INTEGER_CST@2)
988    (with
989     {
990       wide_int c = wi::to_wide (@1);
991       wide_int n = wi::to_wide (@2);
992       bool shift = op == RSHIFT_EXPR;
993 #define plus_op1(v) (shift ? wi::rshift (v, n, TYPE_SIGN (type)) \
994                            : wi::div_trunc (v, n, TYPE_SIGN (type)))
995 #define exact_mod(v) (shift ? wi::ctz (v) >= n.to_shwi () \
996                             : wi::multiple_of_p (v, n, TYPE_SIGN (type)))
997       value_range vr0, vr1, vr3;
998     }
999     (if (INTEGRAL_TYPE_P (type)
1000          && get_range_query (cfun)->range_of_expr (vr0, @0))
1001      (if (exact_mod (c)
1002           && get_range_query (cfun)->range_of_expr (vr1, @1)
1003           /* "X+C" doesn't overflow.  */
1004           && range_op_handler (PLUS_EXPR).overflow_free_p (vr0, vr1)
1005           && get_range_query (cfun)->range_of_expr (vr3, @3)
1006           && !vr3.undefined_p ()
1007           /* "X+C" and "X" are not of opposite sign.  */
1008           && (TYPE_UNSIGNED (type)
1009               || (vr0.nonnegative_p () && vr3.nonnegative_p ())
1010               || (vr0.nonpositive_p () && vr3.nonpositive_p ())))
1011        (plus (op @0 @2) { wide_int_to_tree (type, plus_op1 (c)); })
1012        (if (!vr0.undefined_p () && TYPE_UNSIGNED (type) && c.sign_mask () < 0
1013             && exact_mod (-c)
1014             /* unsigned "X-(-C)" doesn't underflow.  */
1015             && wi::geu_p (vr0.lower_bound (), -c))
1016          (plus (op @0 @2) { wide_int_to_tree (type, -plus_op1 (-c)); })))))))
1017 #undef plus_op1
1018 #undef exact_mod
1019 #endif
1021 /* (nop_outer_cast)-(inner_cast)var -> -(outer_cast)(var)
1022    if var is smaller in precision.
1023    This is always safe for both doing the negative in signed or unsigned
1024    as the value for undefined will not show up.  */
1025 (simplify
1026  (convert (negate:s@1 (convert:s @0)))
1027  (if (INTEGRAL_TYPE_P (type)
1028       && tree_nop_conversion_p (type, TREE_TYPE (@1))
1029       && TYPE_PRECISION (type) > TYPE_PRECISION (TREE_TYPE (@0)))
1030     (negate (convert @0))))
1032 (for op (negate abs)
1033  /* Simplify cos(-x) and cos(|x|) -> cos(x).  Similarly for cosh.  */
1034  (for coss (COS COSH)
1035   (simplify
1036    (coss (op @0))
1037     (coss @0)))
1038  /* Simplify pow(-x, y) and pow(|x|,y) -> pow(x,y) if y is an even integer.  */
1039  (for pows (POW)
1040   (simplify
1041    (pows (op @0) REAL_CST@1)
1042    (with { HOST_WIDE_INT n; }
1043     (if (real_isinteger (&TREE_REAL_CST (@1), &n) && (n & 1) == 0)
1044      (pows @0 @1)))))
1045  /* Likewise for powi.  */
1046  (for pows (POWI)
1047   (simplify
1048    (pows (op @0) INTEGER_CST@1)
1049    (if ((wi::to_wide (@1) & 1) == 0)
1050     (pows @0 @1))))
1051  /* Strip negate and abs from both operands of hypot.  */
1052  (for hypots (HYPOT)
1053   (simplify
1054    (hypots (op @0) @1)
1055    (hypots @0 @1))
1056   (simplify
1057    (hypots @0 (op @1))
1058    (hypots @0 @1)))
1059  /* copysign(-x, y) and copysign(abs(x), y) -> copysign(x, y).  */
1060  (for copysigns (COPYSIGN_ALL)
1061   (simplify
1062    (copysigns (op @0) @1)
1063    (copysigns @0 @1))))
1065 /* abs(x)*abs(x) -> x*x.  Should be valid for all types.  */
1066 (simplify
1067  (mult (abs@1 @0) @1)
1068  (mult @0 @0))
1070 /* Convert absu(x)*absu(x) -> x*x.  */
1071 (simplify
1072  (mult (absu@1 @0) @1)
1073  (mult (convert@2 @0) @2))
1075 /* cos(copysign(x, y)) -> cos(x).  Similarly for cosh.  */
1076 (for coss (COS COSH)
1077      copysigns (COPYSIGN)
1078  (simplify
1079   (coss (copysigns @0 @1))
1080    (coss @0)))
1082 /* pow(copysign(x, y), z) -> pow(x, z) if z is an even integer.  */
1083 (for pows (POW)
1084      copysigns (COPYSIGN)
1085  (simplify
1086   (pows (copysigns @0 @2) REAL_CST@1)
1087   (with { HOST_WIDE_INT n; }
1088    (if (real_isinteger (&TREE_REAL_CST (@1), &n) && (n & 1) == 0)
1089     (pows @0 @1)))))
1090 /* Likewise for powi.  */
1091 (for pows (POWI)
1092      copysigns (COPYSIGN)
1093  (simplify
1094   (pows (copysigns @0 @2) INTEGER_CST@1)
1095   (if ((wi::to_wide (@1) & 1) == 0)
1096    (pows @0 @1))))
1098 (for hypots (HYPOT)
1099      copysigns (COPYSIGN)
1100  /* hypot(copysign(x, y), z) -> hypot(x, z).  */
1101  (simplify
1102   (hypots (copysigns @0 @1) @2)
1103   (hypots @0 @2))
1104  /* hypot(x, copysign(y, z)) -> hypot(x, y).  */
1105  (simplify
1106   (hypots @0 (copysigns @1 @2))
1107   (hypots @0 @1)))
1109 /* copysign(x, CST) -> [-]abs (x).  */
1110 (for copysigns (COPYSIGN_ALL)
1111  (simplify
1112   (copysigns @0 REAL_CST@1)
1113   (if (REAL_VALUE_NEGATIVE (TREE_REAL_CST (@1)))
1114    (negate (abs @0))
1115    (abs @0))))
1117 /* copysign(copysign(x, y), z) -> copysign(x, z).  */
1118 (for copysigns (COPYSIGN_ALL)
1119  (simplify
1120   (copysigns (copysigns @0 @1) @2)
1121   (copysigns @0 @2)))
1123 /* copysign(x,y)*copysign(x,y) -> x*x.  */
1124 (for copysigns (COPYSIGN_ALL)
1125  (simplify
1126   (mult (copysigns@2 @0 @1) @2)
1127   (mult @0 @0)))
1129 /* ccos(-x) -> ccos(x).  Similarly for ccosh.  */
1130 (for ccoss (CCOS CCOSH)
1131  (simplify
1132   (ccoss (negate @0))
1133    (ccoss @0)))
1135 /* cabs(-x) and cos(conj(x)) -> cabs(x).  */
1136 (for ops (conj negate)
1137  (for cabss (CABS)
1138   (simplify
1139    (cabss (ops @0))
1140    (cabss @0))))
1142 /* Fold (a * (1 << b)) into (a << b)  */
1143 (simplify
1144  (mult:c @0 (convert? (lshift integer_onep@1 @2)))
1145   (if (! FLOAT_TYPE_P (type)
1146        && tree_nop_conversion_p (type, TREE_TYPE (@1)))
1147    (lshift @0 @2)))
1149 /* Shifts by precision or greater result in zero.  */
1150 (for shift (lshift rshift)
1151  (simplify
1152   (shift @0 uniform_integer_cst_p@1)
1153   (if ((GIMPLE || !sanitize_flags_p (SANITIZE_SHIFT_EXPONENT))
1154        /* Leave arithmetic right shifts of possibly negative values alone.  */
1155        && (TYPE_UNSIGNED (type)
1156            || shift == LSHIFT_EXPR
1157            || tree_expr_nonnegative_p (@0))
1158        /* Use a signed compare to leave negative shift counts alone.  */
1159        && wi::ges_p (wi::to_wide (uniform_integer_cst_p (@1)),
1160                      element_precision (type)))
1161    { build_zero_cst (type); })))
1163 /* Shifts by constants distribute over several binary operations,
1164    hence (X << C) + (Y << C) can be simplified to (X + Y) << C.  */
1165 (for op (plus minus)
1166   (simplify
1167     (op (lshift:s @0 @1) (lshift:s @2 @1))
1168     (if (INTEGRAL_TYPE_P (type)
1169          && TYPE_OVERFLOW_WRAPS (type)
1170          && !TYPE_SATURATING (type))
1171       (lshift (op @0 @2) @1))))
1173 (for op (bit_and bit_ior bit_xor)
1174   (simplify
1175     (op (lshift:s @0 @1) (lshift:s @2 @1))
1176     (if (INTEGRAL_TYPE_P (type))
1177       (lshift (op @0 @2) @1)))
1178   (simplify
1179     (op (rshift:s @0 @1) (rshift:s @2 @1))
1180     (if (INTEGRAL_TYPE_P (type))
1181       (rshift (op @0 @2) @1))))
1183 /* Fold (1 << (C - x)) where C = precision(type) - 1
1184    into ((1 << C) >> x). */
1185 (simplify
1186  (lshift integer_onep@0 (minus@1 INTEGER_CST@2 @3))
1187   (if (INTEGRAL_TYPE_P (type)
1188        && wi::eq_p (wi::to_wide (@2), TYPE_PRECISION (type) - 1)
1189        && single_use (@1))
1190    (if (TYPE_UNSIGNED (type))
1191      (rshift (lshift @0 @2) @3)
1192    (with
1193     { tree utype = unsigned_type_for (type); }
1194     (convert (rshift (lshift (convert:utype @0) @2) @3))))))
1196 /* Fold ((type)(a<0)) << SIGNBITOFA into ((type)a) & signbit. */
1197 (simplify
1198  (lshift (convert (lt @0 integer_zerop@1)) INTEGER_CST@2)
1199  (if (TYPE_SIGN (TREE_TYPE (@0)) == SIGNED
1200       && wi::eq_p (wi::to_wide (@2), TYPE_PRECISION (TREE_TYPE (@0)) - 1))
1201   (with { wide_int wone = wi::one (TYPE_PRECISION (type)); }
1202    (bit_and (convert @0)
1203             { wide_int_to_tree (type,
1204                                 wi::lshift (wone, wi::to_wide (@2))); }))))
1206 /* Fold (-x >> C) into -(x > 0) where C = precision(type) - 1.  */
1207 (for cst (INTEGER_CST VECTOR_CST)
1208  (simplify
1209   (rshift (negate:s @0) cst@1)
1210    (if (!TYPE_UNSIGNED (type)
1211         && TYPE_OVERFLOW_UNDEFINED (type))
1212     (with { tree stype = TREE_TYPE (@1);
1213             tree bt = truth_type_for (type);
1214             tree zeros = build_zero_cst (type);
1215             tree cst = NULL_TREE; }
1216      (switch
1217       /* Handle scalar case.  */
1218       (if (INTEGRAL_TYPE_P (type)
1219            /* If we apply the rule to the scalar type before vectorization
1220               we will enforce the result of the comparison being a bool
1221               which will require an extra AND on the result that will be
1222               indistinguishable from when the user did actually want 0
1223               or 1 as the result so it can't be removed.  */
1224            && canonicalize_math_after_vectorization_p ()
1225            && wi::eq_p (wi::to_wide (@1), TYPE_PRECISION (type) - 1))
1226        (negate (convert (gt @0 { zeros; }))))
1227       /* Handle vector case.  */
1228       (if (VECTOR_INTEGER_TYPE_P (type)
1229            /* First check whether the target has the same mode for vector
1230               comparison results as it's operands do.  */
1231            && TYPE_MODE (bt) == TYPE_MODE (type)
1232            /* Then check to see if the target is able to expand the comparison
1233               with the given type later on, otherwise we may ICE.  */
1234            && expand_vec_cmp_expr_p (type, bt, GT_EXPR)
1235            && (cst = uniform_integer_cst_p (@1)) != NULL
1236            && wi::eq_p (wi::to_wide (cst), element_precision (type) - 1))
1237        (view_convert (gt:bt @0 { zeros; }))))))))
1239 /* Fold (C1/X)*C2 into (C1*C2)/X.  */
1240 (simplify
1241  (mult (rdiv@3 REAL_CST@0 @1) REAL_CST@2)
1242   (if (flag_associative_math
1243        && single_use (@3))
1244    (with
1245     { tree tem = const_binop (MULT_EXPR, type, @0, @2); }
1246     (if (tem)
1247      (rdiv { tem; } @1)))))
1249 /* Simplify ~X & X as zero.  */
1250 (simplify
1251  (bit_and (convert? @0) (convert? @1))
1252  (with { bool wascmp; }
1253   (if (types_match (TREE_TYPE (@0), TREE_TYPE (@1))
1254        && bitwise_inverted_equal_p (@0, @1, wascmp))
1255    { wascmp ? constant_boolean_node (false, type) : build_zero_cst (type); })))
1257 /* PR71636: Transform x & ((1U << b) - 1) -> x & ~(~0U << b);  */
1258 (simplify
1259   (bit_and:c @0 (plus:s (lshift:s integer_onep @1) integer_minus_onep))
1260   (if (TYPE_UNSIGNED (type))
1261     (bit_and @0 (bit_not (lshift { build_all_ones_cst (type); } @1)))))
1263 (for bitop (bit_and bit_ior)
1264      cmp (eq ne)
1265  /* PR35691: Transform
1266     (x == 0 & y == 0) -> (x | typeof(x)(y)) == 0.
1267     (x != 0 | y != 0) -> (x | typeof(x)(y)) != 0.  */
1268  (simplify
1269   (bitop (cmp @0 integer_zerop@2) (cmp @1 integer_zerop))
1270    (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
1271         && INTEGRAL_TYPE_P (TREE_TYPE (@1))
1272         && TYPE_PRECISION (TREE_TYPE (@0)) == TYPE_PRECISION (TREE_TYPE (@1)))
1273     (cmp (bit_ior @0 (convert @1)) @2)))
1274  /* Transform:
1275     (x == -1 & y == -1) -> (x & typeof(x)(y)) == -1.
1276     (x != -1 | y != -1) -> (x & typeof(x)(y)) != -1.  */
1277  (simplify
1278   (bitop (cmp @0 integer_all_onesp@2) (cmp @1 integer_all_onesp))
1279    (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
1280         && INTEGRAL_TYPE_P (TREE_TYPE (@1))
1281         && TYPE_PRECISION (TREE_TYPE (@0)) == TYPE_PRECISION (TREE_TYPE (@1)))
1282     (cmp (bit_and @0 (convert @1)) @2))))
1284 /* Fold (A & ~B) - (A & B) into (A ^ B) - B.  */
1285 (simplify
1286  (minus (bit_and:cs @0 (bit_not @1)) (bit_and:cs @0 @1))
1287   (minus (bit_xor @0 @1) @1))
1288 (simplify
1289  (minus (bit_and:s @0 INTEGER_CST@2) (bit_and:s @0 INTEGER_CST@1))
1290  (if (~wi::to_wide (@2) == wi::to_wide (@1))
1291   (minus (bit_xor @0 @1) @1)))
1293 /* Fold (A & B) - (A & ~B) into B - (A ^ B).  */
1294 (simplify
1295  (minus (bit_and:cs @0 @1) (bit_and:cs @0 (bit_not @1)))
1296   (minus @1 (bit_xor @0 @1)))
1298 /* Simplify (X & ~Y) |^+ (~X & Y) -> X ^ Y.  */
1299 (for op (bit_ior bit_xor plus)
1300  (simplify
1301   (op (bit_and:c @0 @2) (bit_and:c @3 @1))
1302   (with { bool wascmp0, wascmp1; }
1303    (if (bitwise_inverted_equal_p (@2, @1, wascmp0)
1304         && bitwise_inverted_equal_p (@0, @3, wascmp1)
1305         && ((!wascmp0 && !wascmp1)
1306             || element_precision (type) == 1))
1307    (bit_xor @0 @1)))))
1309 /* PR53979: Transform ((a ^ b) | a) -> (a | b) */
1310 (simplify
1311   (bit_ior:c (bit_xor:c @0 @1) @0)
1312   (bit_ior @0 @1))
1314 /* (a & ~b) | (a ^ b)  -->  a ^ b  */
1315 (simplify
1316  (bit_ior:c (bit_and:c @0 (bit_not @1)) (bit_xor:c@2 @0 @1))
1317  @2)
1319 /* (a & ~b) ^ ~a  -->  ~(a & b)  */
1320 (simplify
1321  (bit_xor:c (bit_and:cs @0 (bit_not @1)) (bit_not @0))
1322  (bit_not (bit_and @0 @1)))
1324 /* (~a & b) ^ a  -->   (a | b)   */
1325 (simplify
1326  (bit_xor:c (bit_and:cs (bit_not @0) @1) @0)
1327  (bit_ior @0 @1))
1329 /* (a | b) & ~(a ^ b)  -->  a & b  */
1330 (simplify
1331  (bit_and:c (bit_ior @0 @1) (bit_not (bit_xor:c @0 @1)))
1332  (bit_and @0 @1))
1334 /* (a | b) & (a == b)  -->  a & b (boolean version of the above).  */
1335 (simplify
1336  (bit_and:c (bit_ior @0 @1) (nop_convert? (eq:c @0 @1)))
1337  (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
1338       && TYPE_PRECISION (TREE_TYPE (@0)) == 1)
1339   (bit_and @0 @1)))
1341 /* a | ~(a ^ b)  -->  a | ~b  */
1342 (simplify
1343  (bit_ior:c @0 (bit_not:s (bit_xor:c @0 @1)))
1344  (bit_ior @0 (bit_not @1)))
1346 /* a | (a == b)  -->  a | (b^1) (boolean version of the above). */
1347 (simplify
1348  (bit_ior:c @0 (nop_convert? (eq:c @0 @1)))
1349  (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
1350       && TYPE_PRECISION (TREE_TYPE (@0)) == 1)
1351   (bit_ior @0 (bit_xor @1 { build_one_cst (type); }))))
1353 /* a | ((~a) ^ b)  -->  a | (~b) (alt version of the above 2) */
1354 (simplify
1355  (bit_ior:c @0 (bit_xor:cs @1 @2))
1356  (with { bool wascmp; }
1357  (if (bitwise_inverted_equal_p (@0, @1, wascmp)
1358       && (!wascmp || element_precision (type) == 1))
1359   (bit_ior @0 (bit_not @2)))))
1361 /* a & ~(a ^ b)  -->  a & b  */
1362 (simplify
1363  (bit_and:c @0 (bit_not (bit_xor:c @0 @1)))
1364  (bit_and @0 @1))
1366 /* a & (a == b)  -->  a & b (boolean version of the above). */
1367 (simplify
1368  (bit_and:c @0 (nop_convert? (eq:c @0 @1)))
1369  (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
1370       && TYPE_PRECISION (TREE_TYPE (@0)) == 1)
1371   (bit_and @0 @1)))
1373 /* a & ((~a) ^ b)  -->  a & b (alt version of the above 2) */
1374 (simplify
1375  (bit_and:c @0 (bit_xor:c @1 @2))
1376  (with { bool wascmp; }
1377  (if (bitwise_inverted_equal_p (@0, @1, wascmp)
1378       && (!wascmp || element_precision (type) == 1))
1379   (bit_and @0 @2))))
1381 /* (a | b) | (a &^ b)  -->  a | b  */
1382 (for op (bit_and bit_xor)
1383  (simplify
1384   (bit_ior:c (bit_ior@2 @0 @1) (op:c @0 @1))
1385   @2))
1387 /* (a & b) | ~(a ^ b)  -->  ~(a ^ b)  */
1388 (simplify
1389  (bit_ior:c (bit_and:c @0 @1) (bit_not@2 (bit_xor @0 @1)))
1390  @2)
1392 /* (a & b) | (a == b)  -->  a == b  */
1393 (simplify
1394  (bit_ior:c (bit_and:c @0 @1) (nop_convert?@2 (eq @0 @1)))
1395  (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
1396       && TYPE_PRECISION (TREE_TYPE (@0)) == 1)
1397   @2))
1399 /* ~(~a & b)  -->  a | ~b  */
1400 (simplify
1401  (bit_not (bit_and:cs (bit_not @0) @1))
1402  (bit_ior @0 (bit_not @1)))
1404 /* ~(~a | b) --> a & ~b */
1405 (simplify
1406  (bit_not (bit_ior:cs (bit_not @0) @1))
1407  (bit_and @0 (bit_not @1)))
1409 /* (a ^ b) & ((b ^ c) ^ a) --> (a ^ b) & ~c */
1410 (simplify
1411  (bit_and:c (bit_xor:c@3 @0 @1) (bit_xor:cs (bit_xor:cs @1 @2) @0))
1412  (bit_and @3 (bit_not @2)))
1414 /* (a ^ b) | ((b ^ c) ^ a) --> (a ^ b) | c */
1415 (simplify
1416  (bit_ior:c (bit_xor:c@3 @0 @1) (bit_xor:c (bit_xor:c @1 @2) @0))
1417  (bit_ior @3 @2))
1419 /* (~X | C) ^ D -> (X | C) ^ (~D ^ C) if (~D ^ C) can be simplified.  */
1420 (simplify
1421  (bit_xor:c (bit_ior:cs (bit_not:s @0) @1) @2)
1422   (bit_xor (bit_ior @0 @1) (bit_xor! (bit_not! @2) @1)))
1424 /* (~X & C) ^ D -> (X & C) ^ (D ^ C) if (D ^ C) can be simplified.  */
1425 (simplify
1426  (bit_xor:c (bit_and:cs (bit_not:s @0) @1) @2)
1427   (bit_xor (bit_and @0 @1) (bit_xor! @2 @1)))
1429 /* Simplify (~X & Y) to X ^ Y if we know that (X & ~Y) is 0.  */
1430 (simplify
1431  (bit_and (bit_not SSA_NAME@0) INTEGER_CST@1)
1432  (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
1433       && wi::bit_and_not (get_nonzero_bits (@0), wi::to_wide (@1)) == 0)
1434   (bit_xor @0 @1)))
1436 /* For constants M and N, if M == (1LL << cst) - 1 && (N & M) == M,
1437    ((A & N) + B) & M -> (A + B) & M
1438    Similarly if (N & M) == 0,
1439    ((A | N) + B) & M -> (A + B) & M
1440    and for - instead of + (or unary - instead of +)
1441    and/or ^ instead of |.
1442    If B is constant and (B & M) == 0, fold into A & M.  */
1443 (for op (plus minus)
1444  (for bitop (bit_and bit_ior bit_xor)
1445   (simplify
1446    (bit_and (op:s (bitop:s@0 @3 INTEGER_CST@4) @1) INTEGER_CST@2)
1447     (with
1448      { tree pmop[2];
1449        tree utype = fold_bit_and_mask (TREE_TYPE (@0), @2, op, @0, bitop,
1450                                        @3, @4, @1, ERROR_MARK, NULL_TREE,
1451                                        NULL_TREE, pmop); }
1452      (if (utype)
1453       (convert (bit_and (op (convert:utype { pmop[0]; })
1454                             (convert:utype { pmop[1]; }))
1455                         (convert:utype @2))))))
1456   (simplify
1457    (bit_and (op:s @0 (bitop:s@1 @3 INTEGER_CST@4)) INTEGER_CST@2)
1458     (with
1459      { tree pmop[2];
1460        tree utype = fold_bit_and_mask (TREE_TYPE (@0), @2, op, @0, ERROR_MARK,
1461                                        NULL_TREE, NULL_TREE, @1, bitop, @3,
1462                                        @4, pmop); }
1463      (if (utype)
1464       (convert (bit_and (op (convert:utype { pmop[0]; })
1465                             (convert:utype { pmop[1]; }))
1466                         (convert:utype @2)))))))
1467  (simplify
1468   (bit_and (op:s @0 @1) INTEGER_CST@2)
1469    (with
1470     { tree pmop[2];
1471       tree utype = fold_bit_and_mask (TREE_TYPE (@0), @2, op, @0, ERROR_MARK,
1472                                       NULL_TREE, NULL_TREE, @1, ERROR_MARK,
1473                                       NULL_TREE, NULL_TREE, pmop); }
1474     (if (utype)
1475      (convert (bit_and (op (convert:utype { pmop[0]; })
1476                            (convert:utype { pmop[1]; }))
1477                        (convert:utype @2)))))))
1478 (for bitop (bit_and bit_ior bit_xor)
1479  (simplify
1480   (bit_and (negate:s (bitop:s@0 @2 INTEGER_CST@3)) INTEGER_CST@1)
1481    (with
1482     { tree pmop[2];
1483       tree utype = fold_bit_and_mask (TREE_TYPE (@0), @1, NEGATE_EXPR, @0,
1484                                       bitop, @2, @3, NULL_TREE, ERROR_MARK,
1485                                       NULL_TREE, NULL_TREE, pmop); }
1486     (if (utype)
1487      (convert (bit_and (negate (convert:utype { pmop[0]; }))
1488                        (convert:utype @1)))))))
1490 /* X % Y is smaller than Y.  */
1491 (for cmp (lt ge)
1492  (simplify
1493   (cmp:c (trunc_mod @0 @1) @1)
1494   (if (TYPE_UNSIGNED (TREE_TYPE (@0)))
1495    { constant_boolean_node (cmp == LT_EXPR, type); })))
1497 /* x | ~0 -> ~0  */
1498 (simplify
1499  (bit_ior @0 integer_all_onesp@1)
1500  @1)
1502 /* x | 0 -> x  */
1503 (simplify
1504  (bit_ior @0 integer_zerop)
1505  @0)
1507 /* x & 0 -> 0  */
1508 (simplify
1509  (bit_and @0 integer_zerop@1)
1510  @1)
1512 /* ~x | x -> -1 */
1513 /* ~x ^ x -> -1 */
1514 (for op (bit_ior bit_xor)
1515  (simplify
1516   (op (convert? @0) (convert? @1))
1517   (with { bool wascmp; }
1518    (if (types_match (TREE_TYPE (@0), TREE_TYPE (@1))
1519         && bitwise_inverted_equal_p (@0, @1, wascmp))
1520     (convert
1521      { wascmp
1522         ? constant_boolean_node (true, type)
1523         : build_all_ones_cst (TREE_TYPE (@0)); })))))
1525 /* x ^ x -> 0 */
1526 (simplify
1527   (bit_xor @0 @0)
1528   { build_zero_cst (type); })
1530 /* Canonicalize X ^ ~0 to ~X.  */
1531 (simplify
1532   (bit_xor @0 integer_all_onesp@1)
1533   (bit_not @0))
1535 /* x & ~0 -> x  */
1536 (simplify
1537  (bit_and @0 integer_all_onesp)
1538   (non_lvalue @0))
1540 /* x & x -> x,  x | x -> x  */
1541 (for bitop (bit_and bit_ior)
1542  (simplify
1543   (bitop @0 @0)
1544   (non_lvalue @0)))
1546 /* x & C -> x if we know that x & ~C == 0.  */
1547 #if GIMPLE
1548 (simplify
1549  (bit_and SSA_NAME@0 INTEGER_CST@1)
1550  (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
1551       && wi::bit_and_not (get_nonzero_bits (@0), wi::to_wide (@1)) == 0)
1552   @0))
1553 /* x | C -> C if we know that x & ~C == 0.  */
1554 (simplify
1555  (bit_ior SSA_NAME@0 INTEGER_CST@1)
1556  (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
1557       && wi::bit_and_not (get_nonzero_bits (@0), wi::to_wide (@1)) == 0)
1558   @1))
1559 #endif
1561 /* ~(~X - Y) -> X + Y and ~(~X + Y) -> X - Y.  */
1562 (simplify
1563  (bit_not (minus (bit_not @0) @1))
1564  (plus @0 @1))
1565 (simplify
1566  (bit_not (plus:c (bit_not @0) @1))
1567  (minus @0 @1))
1568 /* (~X - ~Y) -> Y - X.  */
1569 (simplify
1570  (minus (bit_not @0) (bit_not @1))
1571   (if (!TYPE_OVERFLOW_SANITIZED (type))
1572    (with { tree utype = unsigned_type_for (type); }
1573     (convert (minus (convert:utype @1) (convert:utype @0))))))
1575 /* ~(X - Y) -> ~X + Y.  */
1576 (simplify
1577  (bit_not (minus:s @0 @1))
1578  (plus (bit_not @0) @1))
1579 (simplify
1580  (bit_not (plus:s @0 INTEGER_CST@1))
1581  (if ((INTEGRAL_TYPE_P (type)
1582        && TYPE_UNSIGNED (type))
1583       || (!TYPE_OVERFLOW_SANITIZED (type)
1584           && may_negate_without_overflow_p (@1)))
1585   (plus (bit_not @0) { const_unop (NEGATE_EXPR, type, @1); })))
1587 #if GIMPLE
1588 /* ~X + Y -> (Y - X) - 1.  */
1589 (simplify
1590  (plus:c (bit_not @0) @1)
1591   (if (ANY_INTEGRAL_TYPE_P (type)
1592        && TYPE_OVERFLOW_WRAPS (type)
1593        /* -1 - X is folded to ~X, so we'd recurse endlessly.  */
1594        && !integer_all_onesp (@1))
1595    (plus (minus @1 @0) { build_minus_one_cst (type); })
1596    (if (INTEGRAL_TYPE_P (type)
1597         && TREE_CODE (@1) == INTEGER_CST
1598         && wi::to_wide (@1) != wi::min_value (TYPE_PRECISION (type),
1599                                               SIGNED))
1600     (minus (plus @1 { build_minus_one_cst (type); }) @0))))
1601 #endif
1603 /* ~(X >> Y) -> ~X >> Y if ~X can be simplified.  */
1604 (simplify
1605  (bit_not (rshift:s @0 @1))
1606   (if (!TYPE_UNSIGNED (TREE_TYPE (@0)))
1607    (rshift (bit_not! @0) @1)
1608    /* For logical right shifts, this is possible only if @0 doesn't
1609       have MSB set and the logical right shift is changed into
1610       arithmetic shift.  */
1611    (if (INTEGRAL_TYPE_P (type)
1612         && !wi::neg_p (tree_nonzero_bits (@0)))
1613     (with { tree stype = signed_type_for (TREE_TYPE (@0)); }
1614      (convert (rshift (bit_not! (convert:stype @0)) @1))))))
1616 /* x + (x & 1) -> (x + 1) & ~1 */
1617 (simplify
1618  (plus:c @0 (bit_and:s @0 integer_onep@1))
1619  (bit_and (plus @0 @1) (bit_not @1)))
1621 /* x & ~(x & y) -> x & ~y */
1622 /* x | ~(x | y) -> x | ~y  */
1623 (for bitop (bit_and bit_ior)
1624  (simplify
1625   (bitop:c @0 (bit_not (bitop:cs @0 @1)))
1626   (bitop @0 (bit_not @1))))
1628 /* (~x & y) | ~(x | y) -> ~x */
1629 (simplify
1630  (bit_ior:c (bit_and:c (bit_not@2 @0) @1) (bit_not (bit_ior:c @0 @1)))
1631  @2)
1633 /* (x | y) ^ (x | ~y) -> ~x */
1634 (simplify
1635  (bit_xor:c (bit_ior:c @0 @1) (bit_ior:c @0 (bit_not @1)))
1636  (bit_not @0))
1638 /* (x & y) | ~(x | y) -> ~(x ^ y) */
1639 (simplify
1640  (bit_ior:c (bit_and:s @0 @1) (bit_not:s (bit_ior:s @0 @1)))
1641  (bit_not (bit_xor @0 @1)))
1643 /* (~x | y) ^ (x ^ y) -> x | ~y */
1644 (simplify
1645  (bit_xor:c (bit_ior:cs (bit_not @0) @1) (bit_xor:s @0 @1))
1646  (bit_ior @0 (bit_not @1)))
1648 /* (x ^ y) | ~(x | y) -> ~(x & y) */
1649 (simplify
1650  (bit_ior:c (bit_xor:s @0 @1) (bit_not:s (bit_ior:s @0 @1)))
1651  (bit_not (bit_and @0 @1)))
1653 /* (x & y) ^ (x | y) -> x ^ y */
1654 (simplify
1655  (bit_xor:c (bit_and @0 @1) (bit_ior @0 @1))
1656  (bit_xor @0 @1))
1658 /* (x ^ y) ^ (x | y) -> x & y */
1659 (simplify
1660  (bit_xor:c (bit_xor @0 @1) (bit_ior @0 @1))
1661  (bit_and @0 @1))
1663 /* (x & y) + (x ^ y) -> x | y */
1664 /* (x & y) | (x ^ y) -> x | y */
1665 /* (x & y) ^ (x ^ y) -> x | y */
1666 (for op (plus bit_ior bit_xor)
1667  (simplify
1668   (op:c (bit_and @0 @1) (bit_xor @0 @1))
1669   (bit_ior @0 @1)))
1671 /* (x & y) + (x | y) -> x + y */
1672 (simplify
1673  (plus:c (bit_and @0 @1) (bit_ior @0 @1))
1674  (plus @0 @1))
1676 /* (x + y) - (x | y) -> x & y */
1677 (simplify
1678  (minus (plus @0 @1) (bit_ior @0 @1))
1679  (if (!TYPE_OVERFLOW_SANITIZED (type) && !TYPE_OVERFLOW_TRAPS (type)
1680       && !TYPE_SATURATING (type))
1681   (bit_and @0 @1)))
1683 /* (x + y) - (x & y) -> x | y */
1684 (simplify
1685  (minus (plus @0 @1) (bit_and @0 @1))
1686  (if (!TYPE_OVERFLOW_SANITIZED (type) && !TYPE_OVERFLOW_TRAPS (type)
1687       && !TYPE_SATURATING (type))
1688   (bit_ior @0 @1)))
1690 /* (x | y) - y -> (x & ~y) */
1691 (simplify
1692  (minus (bit_ior:cs @0 @1) @1)
1693  (bit_and @0 (bit_not @1)))
1695 /* (x | y) - (x ^ y) -> x & y */
1696 (simplify
1697  (minus (bit_ior @0 @1) (bit_xor @0 @1))
1698  (bit_and @0 @1))
1700 /* (x | y) - (x & y) -> x ^ y */
1701 (simplify
1702  (minus (bit_ior @0 @1) (bit_and @0 @1))
1703  (bit_xor @0 @1))
1705 /* (x | y) & ~(x & y) -> x ^ y */
1706 (simplify
1707  (bit_and:c (bit_ior @0 @1) (bit_not (bit_and @0 @1)))
1708  (bit_xor @0 @1))
1710 /* (x | y) & (~x ^ y) -> x & y */
1711 (simplify
1712  (bit_and:c (bit_ior:c @0 @1) (bit_xor:c @1 @2))
1713  (with { bool wascmp; }
1714   (if (bitwise_inverted_equal_p (@0, @2, wascmp)
1715        && (!wascmp || element_precision (type) == 1))
1716    (bit_and @0 @1))))
1718 /* (~x | y) & (x | ~y) -> ~(x ^ y) */
1719 (simplify
1720  (bit_and (bit_ior:cs (bit_not @0) @1) (bit_ior:cs @0 (bit_not @1)))
1721  (bit_not (bit_xor @0 @1)))
1723 /* (~x | y) ^ (x | ~y) -> x ^ y */
1724 (simplify
1725  (bit_xor (bit_ior:c (bit_not @0) @1) (bit_ior:c @0 (bit_not @1)))
1726  (bit_xor @0 @1))
1728 /* ((x & y) - (x | y)) - 1 -> ~(x ^ y) */
1729 (simplify
1730  (plus (nop_convert1? (minus@2 (nop_convert2? (bit_and:c @0 @1))
1731                               (nop_convert2? (bit_ior @0 @1))))
1732        integer_all_onesp)
1733  (if (!TYPE_OVERFLOW_SANITIZED (type) && !TYPE_OVERFLOW_TRAPS (type)
1734       && !TYPE_SATURATING (type) && !TYPE_OVERFLOW_SANITIZED (TREE_TYPE (@2))
1735       && !TYPE_OVERFLOW_TRAPS (TREE_TYPE (@2))
1736       && !TYPE_SATURATING (TREE_TYPE (@2)))
1737  (bit_not (convert (bit_xor @0 @1)))))
1738 (simplify
1739  (minus (nop_convert1? (plus@2 (nop_convert2? (bit_and:c @0 @1))
1740                                integer_all_onesp))
1741        (nop_convert3? (bit_ior @0 @1)))
1742  (if (!TYPE_OVERFLOW_SANITIZED (type) && !TYPE_OVERFLOW_TRAPS (type)
1743       && !TYPE_SATURATING (type) && !TYPE_OVERFLOW_SANITIZED (TREE_TYPE (@2))
1744       && !TYPE_OVERFLOW_TRAPS (TREE_TYPE (@2))
1745       && !TYPE_SATURATING (TREE_TYPE (@2)))
1746  (bit_not (convert (bit_xor @0 @1)))))
1747 (simplify
1748  (minus (nop_convert1? (bit_and @0 @1))
1749        (nop_convert2? (plus@2 (nop_convert3? (bit_ior:c @0 @1))
1750                                integer_onep)))
1751  (if (!TYPE_OVERFLOW_SANITIZED (type) && !TYPE_OVERFLOW_TRAPS (type)
1752       && !TYPE_SATURATING (type) && !TYPE_OVERFLOW_SANITIZED (TREE_TYPE (@2))
1753       && !TYPE_OVERFLOW_TRAPS (TREE_TYPE (@2))
1754       && !TYPE_SATURATING (TREE_TYPE (@2)))
1755  (bit_not (convert (bit_xor @0 @1)))))
1757 /* ~x & ~y -> ~(x | y)
1758    ~x | ~y -> ~(x & y) */
1759 (for op (bit_and bit_ior)
1760      rop (bit_ior bit_and)
1761  (simplify
1762   (op (convert1? (bit_not @0)) (convert2? (bit_not @1)))
1763   (if (element_precision (type) <= element_precision (TREE_TYPE (@0))
1764        && element_precision (type) <= element_precision (TREE_TYPE (@1)))
1765    (bit_not (rop (convert @0) (convert @1))))))
1767 /* If we are XORing or adding two BIT_AND_EXPR's, both of which are and'ing
1768    with a constant, and the two constants have no bits in common,
1769    we should treat this as a BIT_IOR_EXPR since this may produce more
1770    simplifications.  */
1771 (for op (bit_xor plus)
1772  (simplify
1773   (op (convert1? (bit_and@4 @0 INTEGER_CST@1))
1774       (convert2? (bit_and@5 @2 INTEGER_CST@3)))
1775   (if (tree_nop_conversion_p (type, TREE_TYPE (@0))
1776        && tree_nop_conversion_p (type, TREE_TYPE (@2))
1777        && (wi::to_wide (@1) & wi::to_wide (@3)) == 0)
1778    (bit_ior (convert @4) (convert @5)))))
1780 /* (X | Y) ^ X -> Y & ~ X*/
1781 (simplify
1782  (bit_xor:c (convert1? (bit_ior:c @@0 @1)) (convert2? @0))
1783  (if (tree_nop_conversion_p (type, TREE_TYPE (@0)))
1784   (convert (bit_and @1 (bit_not @0)))))
1786 /* (~X | Y) ^ X -> ~(X & Y).  */
1787 (simplify
1788  (bit_xor:c (nop_convert1? (bit_ior:c (nop_convert2? (bit_not @0)) @1)) @2)
1789  (if (bitwise_equal_p (@0, @2))
1790   (convert (bit_not (bit_and @0 (convert @1))))))
1792 /* Convert ~X ^ ~Y to X ^ Y.  */
1793 (simplify
1794  (bit_xor (convert1? (bit_not @0)) (convert2? (bit_not @1)))
1795  (if (element_precision (type) <= element_precision (TREE_TYPE (@0))
1796       && element_precision (type) <= element_precision (TREE_TYPE (@1)))
1797   (bit_xor (convert @0) (convert @1))))
1799 /* Convert ~X ^ C to X ^ ~C.  */
1800 (simplify
1801  (bit_xor (convert? (bit_not @0)) INTEGER_CST@1)
1802  (if (tree_nop_conversion_p (type, TREE_TYPE (@0)))
1803   (bit_xor (convert @0) (bit_not @1))))
1805 /* Fold (X & Y) ^ Y and (X ^ Y) & Y as ~X & Y.  */
1806 (for opo (bit_and bit_xor)
1807      opi (bit_xor bit_and)
1808  (simplify
1809   (opo:c (opi:cs @0 @1) @1)
1810   (bit_and (bit_not @0) @1)))
1812 /* Given a bit-wise operation CODE applied to ARG0 and ARG1, see if both
1813    operands are another bit-wise operation with a common input.  If so,
1814    distribute the bit operations to save an operation and possibly two if
1815    constants are involved.  For example, convert
1816      (A | B) & (A | C) into A | (B & C)
1817    Further simplification will occur if B and C are constants.  */
1818 (for op (bit_and bit_ior bit_xor)
1819      rop (bit_ior bit_and bit_and)
1820  (simplify
1821   (op (convert? (rop:c @@0 @1)) (convert? (rop:c @0 @2)))
1822   (if (tree_nop_conversion_p (type, TREE_TYPE (@1))
1823        && tree_nop_conversion_p (type, TREE_TYPE (@2)))
1824    (rop (convert @0) (op (convert @1) (convert @2))))))
1826 /* Some simple reassociation for bit operations, also handled in reassoc.  */
1827 /* (X & Y) & Y -> X & Y
1828    (X | Y) | Y -> X | Y  */
1829 (for op (bit_and bit_ior)
1830  (simplify
1831   (op:c (convert1?@2 (op:c @0 @@1)) (convert2? @1))
1832   @2))
1833 /* (X ^ Y) ^ Y -> X  */
1834 (simplify
1835  (bit_xor:c (convert1? (bit_xor:c @0 @@1)) (convert2? @1))
1836  (convert @0))
1838 /* (X & ~Y) & Y -> 0 */
1839 (simplify
1840  (bit_and:c (bit_and @0 @1) @2)
1841  (with { bool wascmp; }
1842   (if (bitwise_inverted_equal_p (@0, @2, wascmp)
1843        || bitwise_inverted_equal_p (@1, @2, wascmp))
1844    { wascmp ? constant_boolean_node (false, type) : build_zero_cst (type); })))
1845 /* (X | ~Y) | Y -> -1 */
1846 (simplify
1847  (bit_ior:c (bit_ior @0 @1) @2)
1848  (with { bool wascmp; }
1849   (if ((bitwise_inverted_equal_p (@0, @2, wascmp)
1850         || bitwise_inverted_equal_p (@1, @2, wascmp))
1851        && (!wascmp || element_precision (type) == 1))
1852    { build_all_ones_cst (TREE_TYPE (@0)); })))
1854 /* (X & Y) & (X & Z) -> (X & Y) & Z
1855    (X | Y) | (X | Z) -> (X | Y) | Z  */
1856 (for op (bit_and bit_ior)
1857  (simplify
1858   (op (convert1?@3 (op:c@4 @0 @1)) (convert2?@5 (op:c@6 @0 @2)))
1859   (if (tree_nop_conversion_p (type, TREE_TYPE (@1))
1860        && tree_nop_conversion_p (type, TREE_TYPE (@2)))
1861    (if (single_use (@5) && single_use (@6))
1862     (op @3 (convert @2))
1863     (if (single_use (@3) && single_use (@4))
1864      (op (convert @1) @5))))))
1865 /* (X ^ Y) ^ (X ^ Z) -> Y ^ Z  */
1866 (simplify
1867  (bit_xor (convert1? (bit_xor:c @0 @1)) (convert2? (bit_xor:c @0 @2)))
1868  (if (tree_nop_conversion_p (type, TREE_TYPE (@1))
1869       && tree_nop_conversion_p (type, TREE_TYPE (@2)))
1870   (bit_xor (convert @1) (convert @2))))
1872 /* Convert abs (abs (X)) into abs (X).
1873    also absu (absu (X)) into absu (X).  */
1874 (simplify
1875  (abs (abs@1 @0))
1876  @1)
1878 (simplify
1879  (absu (convert@2 (absu@1 @0)))
1880  (if (tree_nop_conversion_p (TREE_TYPE (@2), TREE_TYPE (@1)))
1881   @1))
1883 /* Convert abs[u] (-X) -> abs[u] (X).  */
1884 (simplify
1885  (abs (negate @0))
1886  (abs @0))
1888 (simplify
1889  (absu (negate @0))
1890  (absu @0))
1892 /* Convert abs[u] (X)  where X is nonnegative -> (X).  */
1893 (simplify
1894  (abs tree_expr_nonnegative_p@0)
1895  @0)
1897 (simplify
1898  (absu tree_expr_nonnegative_p@0)
1899  (convert @0))
1901 /* Simplify (-(X < 0) | 1) * X into abs (X) or absu(X).  */
1902 (simplify
1903  (mult:c (nop_convert1?
1904           (bit_ior (nop_convert2? (negate (convert? (lt @0 integer_zerop))))
1905                     integer_onep))
1906          (nop_convert3? @0))
1907  (if (INTEGRAL_TYPE_P (type)
1908       && INTEGRAL_TYPE_P (TREE_TYPE (@0))
1909       && !TYPE_UNSIGNED (TREE_TYPE (@0)))
1910   (if (TYPE_UNSIGNED (type))
1911    (absu @0)
1912    (abs @0)
1913   )
1917 /* A few cases of fold-const.cc negate_expr_p predicate.  */
1918 (match negate_expr_p
1919  INTEGER_CST
1920  (if ((INTEGRAL_TYPE_P (type)
1921        && TYPE_UNSIGNED (type))
1922       || (!TYPE_OVERFLOW_SANITIZED (type)
1923           && may_negate_without_overflow_p (t)))))
1924 (match negate_expr_p
1925  FIXED_CST)
1926 (match negate_expr_p
1927  (negate @0)
1928  (if (!TYPE_OVERFLOW_SANITIZED (type))))
1929 (match negate_expr_p
1930  REAL_CST
1931  (if (REAL_VALUE_NEGATIVE (TREE_REAL_CST (t)))))
1932 /* VECTOR_CST handling of non-wrapping types would recurse in unsupported
1933    ways.  */
1934 (match negate_expr_p
1935  VECTOR_CST
1936  (if (FLOAT_TYPE_P (TREE_TYPE (type)) || TYPE_OVERFLOW_WRAPS (type))))
1937 (match negate_expr_p
1938  (minus @0 @1)
1939  (if ((ANY_INTEGRAL_TYPE_P (type) && TYPE_OVERFLOW_WRAPS (type))
1940       || (FLOAT_TYPE_P (type)
1941           && !HONOR_SIGN_DEPENDENT_ROUNDING (type)
1942           && !HONOR_SIGNED_ZEROS (type)))))
1944 /* (-A) * (-B) -> A * B  */
1945 (simplify
1946  (mult:c (convert1? (negate @0)) (convert2? negate_expr_p@1))
1947   (if (tree_nop_conversion_p (type, TREE_TYPE (@0))
1948        && tree_nop_conversion_p (type, TREE_TYPE (@1)))
1949    (mult (convert @0) (convert (negate @1)))))
1951 /* -(A + B) -> (-B) - A.  */
1952 (simplify
1953  (negate (plus:c @0 negate_expr_p@1))
1954  (if (!HONOR_SIGN_DEPENDENT_ROUNDING (type)
1955       && !HONOR_SIGNED_ZEROS (type))
1956   (minus (negate @1) @0)))
1958 /* -(A - B) -> B - A.  */
1959 (simplify
1960  (negate (minus @0 @1))
1961  (if ((ANY_INTEGRAL_TYPE_P (type) && !TYPE_OVERFLOW_SANITIZED (type))
1962       || (FLOAT_TYPE_P (type)
1963           && !HONOR_SIGN_DEPENDENT_ROUNDING (type)
1964           && !HONOR_SIGNED_ZEROS (type)))
1965   (minus @1 @0)))
1966 (simplify
1967  (negate (pointer_diff @0 @1))
1968  (if (TYPE_OVERFLOW_UNDEFINED (type))
1969   (pointer_diff @1 @0)))
1971 /* A - B -> A + (-B) if B is easily negatable.  */
1972 (simplify
1973  (minus @0 negate_expr_p@1)
1974  (if (!FIXED_POINT_TYPE_P (type))
1975  (plus @0 (negate @1))))
1977 /* 1 - a is a ^ 1 if a had a bool range. */
1978 /* This is only enabled for gimple as sometimes
1979    cfun is not set for the function which contains
1980    the SSA_NAME (e.g. while IPA passes are happening,
1981    fold might be called).  */
1982 (simplify
1983  (minus integer_onep@0 SSA_NAME@1)
1984   (if (INTEGRAL_TYPE_P (type)
1985        && ssa_name_has_boolean_range (@1))
1986    (bit_xor @1 @0)))
1988 /* Other simplifications of negation (c.f. fold_negate_expr_1).  */
1989 (simplify
1990  (negate (mult:c@0 @1 negate_expr_p@2))
1991  (if (! TYPE_UNSIGNED (type)
1992       && ! HONOR_SIGN_DEPENDENT_ROUNDING (type)
1993       && single_use (@0))
1994   (mult @1 (negate @2))))
1996 (simplify
1997  (negate (rdiv@0 @1 negate_expr_p@2))
1998  (if (! HONOR_SIGN_DEPENDENT_ROUNDING (type)
1999       && single_use (@0))
2000   (rdiv @1 (negate @2))))
2002 (simplify
2003  (negate (rdiv@0 negate_expr_p@1 @2))
2004  (if (! HONOR_SIGN_DEPENDENT_ROUNDING (type)
2005       && single_use (@0))
2006   (rdiv (negate @1) @2)))
2008 /* Fold -((int)x >> (prec - 1)) into (unsigned)x >> (prec - 1).  */
2009 (simplify
2010  (negate (convert? (rshift @0 INTEGER_CST@1)))
2011  (if (tree_nop_conversion_p (type, TREE_TYPE (@0))
2012       && wi::to_wide (@1) == element_precision (type) - 1)
2013   (with { tree stype = TREE_TYPE (@0);
2014           tree ntype = TYPE_UNSIGNED (stype) ? signed_type_for (stype)
2015                                              : unsigned_type_for (stype); }
2016    (if (VECTOR_TYPE_P (type))
2017     (view_convert (rshift (view_convert:ntype @0) @1))
2018     (convert (rshift (convert:ntype @0) @1))))))
2020 /* Try to fold (type) X op CST -> (type) (X op ((type-x) CST))
2021    when profitable.
2022    For bitwise binary operations apply operand conversions to the
2023    binary operation result instead of to the operands.  This allows
2024    to combine successive conversions and bitwise binary operations.
2025    We combine the above two cases by using a conditional convert.  */
2026 (for bitop (bit_and bit_ior bit_xor)
2027  (simplify
2028   (bitop (convert@2 @0) (convert?@3 @1))
2029   (if (((TREE_CODE (@1) == INTEGER_CST
2030          && INTEGRAL_TYPE_P (TREE_TYPE (@0))
2031          && (int_fits_type_p (@1, TREE_TYPE (@0))
2032              || tree_nop_conversion_p (TREE_TYPE (@0), type)))
2033         || types_match (@0, @1))
2034        && !POINTER_TYPE_P (TREE_TYPE (@0))
2035        && !VECTOR_TYPE_P (TREE_TYPE (@0))
2036        && TREE_CODE (TREE_TYPE (@0)) != OFFSET_TYPE
2037        /* ???  This transform conflicts with fold-const.cc doing
2038           Convert (T)(x & c) into (T)x & (T)c, if c is an integer
2039           constants (if x has signed type, the sign bit cannot be set
2040           in c).  This folds extension into the BIT_AND_EXPR.
2041           Restrict it to GIMPLE to avoid endless recursions.  */
2042        && (bitop != BIT_AND_EXPR || GIMPLE)
2043        && (/* That's a good idea if the conversion widens the operand, thus
2044               after hoisting the conversion the operation will be narrower.
2045               It is also a good if the conversion is a nop as moves the
2046               conversion to one side; allowing for combining of the conversions.  */
2047            TYPE_PRECISION (TREE_TYPE (@0)) < TYPE_PRECISION (type)
2048            /* The conversion check for being a nop can only be done at the gimple
2049               level as fold_binary has some re-association code which can conflict
2050               with this if there is a "constant" which is not a full INTEGER_CST.  */
2051            || (GIMPLE && TYPE_PRECISION (TREE_TYPE (@0)) == TYPE_PRECISION (type))
2052            /* It's also a good idea if the conversion is to a non-integer
2053               mode.  */
2054            || GET_MODE_CLASS (TYPE_MODE (type)) != MODE_INT
2055            /* Or if the precision of TO is not the same as the precision
2056               of its mode.  */
2057            || !type_has_mode_precision_p (type)
2058            /* In GIMPLE, getting rid of 2 conversions for one new results
2059               in smaller IL.  */
2060            || (GIMPLE
2061                && TREE_CODE (@1) != INTEGER_CST
2062                && tree_nop_conversion_p (type, TREE_TYPE (@0))
2063                && single_use (@2)
2064                && single_use (@3))))
2065    (convert (bitop @0 (convert @1)))))
2066  /* In GIMPLE, getting rid of 2 conversions for one new results
2067     in smaller IL.  */
2068  (simplify
2069   (convert (bitop:cs@2 (nop_convert:s @0) @1))
2070   (if (GIMPLE
2071        && TREE_CODE (@1) != INTEGER_CST
2072        && tree_nop_conversion_p (type, TREE_TYPE (@2))
2073        && types_match (type, @0)
2074        && !POINTER_TYPE_P (TREE_TYPE (@0))
2075        && TREE_CODE (TREE_TYPE (@0)) != OFFSET_TYPE)
2076    (bitop @0 (convert @1)))))
2078 (for bitop (bit_and bit_ior)
2079      rbitop (bit_ior bit_and)
2080   /* (x | y) & x -> x */
2081   /* (x & y) | x -> x */
2082  (simplify
2083   (bitop:c (rbitop:c @0 @1) @0)
2084   @0)
2085  /* (~x | y) & x -> x & y */
2086  /* (~x & y) | x -> x | y */
2087  (simplify
2088   (bitop:c (rbitop:c @2 @1) @0)
2089   (with { bool wascmp; }
2090    (if (bitwise_inverted_equal_p (@0, @2, wascmp)
2091         && (!wascmp || element_precision (type) == 1))
2092     (bitop @0 @1))))
2093   /* (x | y) & (x & z) -> (x & z) */
2094   /* (x & y) | (x | z) -> (x | z) */
2095  (simplify
2096   (bitop:c (rbitop:c @0 @1) (bitop:c@3 @0 @2))
2097   @3)
2098  /* (x | c) & ~(y | c) -> x & ~(y | c) */
2099  /* (x & c) | ~(y & c) -> x | ~(y & c) */
2100  (simplify
2101   (bitop:c (rbitop:c @0 @1) (bit_not@3 (rbitop:c @1 @2)))
2102   (bitop @0 @3))
2103  /* x & ~(y | x) -> 0 */
2104  /* x | ~(y & x) -> -1 */
2105  (simplify
2106   (bitop:c @0 (bit_not (rbitop:c @0 @1)))
2107   (if (bitop == BIT_AND_EXPR)
2108    { build_zero_cst (type); }
2109    { build_minus_one_cst (type); })))
2111 /* ((x | y) & z) | x -> (z & y) | x
2112    ((x ^ y) & z) | x -> (z & y) | x  */
2113 (for op (bit_ior bit_xor)
2114  (simplify
2115   (bit_ior:c (nop_convert1?:s
2116                (bit_and:cs (nop_convert2?:s (op:cs @0 @1)) @2)) @3)
2117   (if (bitwise_equal_p (@0, @3))
2118    (convert (bit_ior (bit_and @1 (convert @2)) (convert @0))))))
2120 /* (x | CST1) & CST2 -> (x & CST2) | (CST1 & CST2) */
2121 (simplify
2122   (bit_and (bit_ior @0 CONSTANT_CLASS_P@1) CONSTANT_CLASS_P@2)
2123   (bit_ior (bit_and @0 @2) (bit_and! @1 @2)))
2125 /* Combine successive equal operations with constants.  */
2126 (for bitop (bit_and bit_ior bit_xor)
2127  (simplify
2128   (bitop (bitop @0 CONSTANT_CLASS_P@1) CONSTANT_CLASS_P@2)
2129   (if (!CONSTANT_CLASS_P (@0))
2130    /* This is the canonical form regardless of whether (bitop @1 @2) can be
2131       folded to a constant.  */
2132    (bitop @0 (bitop! @1 @2))
2133    /* In this case we have three constants and (bitop @0 @1) doesn't fold
2134       to a constant.  This can happen if @0 or @1 is a POLY_INT_CST and if
2135       the values involved are such that the operation can't be decided at
2136       compile time.  Try folding one of @0 or @1 with @2 to see whether
2137       that combination can be decided at compile time.
2139       Keep the existing form if both folds fail, to avoid endless
2140       oscillation.  */
2141    (with { tree cst1 = const_binop (bitop, type, @0, @2); }
2142     (if (cst1)
2143      (bitop @1 { cst1; })
2144      (with { tree cst2 = const_binop (bitop, type, @1, @2); }
2145       (if (cst2)
2146        (bitop @0 { cst2; }))))))))
2148 /* Try simple folding for X op !X, and X op X with the help
2149    of the truth_valued_p and logical_inverted_value predicates.  */
2150 (match truth_valued_p
2151  @0
2152  (if (INTEGRAL_TYPE_P (type) && TYPE_PRECISION (type) == 1)))
2153 (for op (tcc_comparison truth_and truth_andif truth_or truth_orif truth_xor)
2154  (match truth_valued_p
2155   (op @0 @1)))
2156 (match truth_valued_p
2157   (truth_not @0))
2159 (match (logical_inverted_value @0)
2160  (truth_not @0))
2161 (match (logical_inverted_value @0)
2162  (bit_not truth_valued_p@0))
2163 (match (logical_inverted_value @0)
2164  (eq @0 integer_zerop))
2165 (match (logical_inverted_value @0)
2166  (ne truth_valued_p@0 integer_truep))
2167 (match (logical_inverted_value @0)
2168  (bit_xor truth_valued_p@0 integer_truep))
2170 /* X & !X -> 0.  */
2171 (simplify
2172  (bit_and:c @0 (logical_inverted_value @0))
2173  { build_zero_cst (type); })
2174 /* X | !X and X ^ !X -> 1, , if X is truth-valued.  */
2175 (for op (bit_ior bit_xor)
2176  (simplify
2177   (op:c truth_valued_p@0 (logical_inverted_value @0))
2178   { constant_boolean_node (true, type); }))
2179 /* X ==/!= !X is false/true.  */
2180 (for op (eq ne)
2181  (simplify
2182   (op:c truth_valued_p@0 (logical_inverted_value @0))
2183   { constant_boolean_node (op == NE_EXPR ? true : false, type); }))
2185 /* ~~x -> x */
2186 (simplify
2187   (bit_not (bit_not @0))
2188   @0)
2190 /* zero_one_valued_p will match when a value is known to be either
2191    0 or 1 including constants 0 or 1.
2192    Signed 1-bits includes -1 so they cannot match here. */
2193 (match zero_one_valued_p
2194  @0
2195  (if (INTEGRAL_TYPE_P (type)
2196       && (TYPE_UNSIGNED (type)
2197           || TYPE_PRECISION (type) > 1)
2198       && wi::leu_p (tree_nonzero_bits (@0), 1))))
2199 (match zero_one_valued_p
2200  truth_valued_p@0
2201  (if (INTEGRAL_TYPE_P (type)
2202       && (TYPE_UNSIGNED (type)
2203           || TYPE_PRECISION (type) > 1))))
2205 /* (a&1) is always [0,1] too. This is useful again when
2206    the range is not known. */
2207 /* Note this can't be recursive due to VN handling of equivalents,
2208    VN and would cause an infinite recursion. */
2209 (match zero_one_valued_p
2210  (bit_and:c@0 @1 integer_onep)
2211  (if (INTEGRAL_TYPE_P (type))))
2213 /* A conversion from an zero_one_valued_p is still a [0,1].
2214    This is useful when the range of a variable is not known */
2215 /* Note this matches can't be recursive because of the way VN handles
2216    nop conversions being equivalent and then recursive between them. */
2217 (match zero_one_valued_p
2218  (convert@0 @1)
2219  (if (INTEGRAL_TYPE_P (TREE_TYPE (@1))
2220       && (TYPE_UNSIGNED (TREE_TYPE (@1))
2221           || TYPE_PRECISION (TREE_TYPE (@1)) > 1)
2222       && wi::leu_p (tree_nonzero_bits (@1), 1))))
2224 /* Transform { 0 or 1 } * { 0 or 1 } into { 0 or 1 } & { 0 or 1 }.  */
2225 (simplify
2226  (mult zero_one_valued_p@0 zero_one_valued_p@1)
2227  (if (INTEGRAL_TYPE_P (type))
2228   (bit_and @0 @1)))
2230 (for cmp (tcc_comparison)
2231      icmp (inverted_tcc_comparison)
2232  /* Fold (((a < b) & c) | ((a >= b) & d)) into (a < b ? c : d) & 1.  */
2233  (simplify
2234   (bit_ior
2235    (bit_and:c (convert? (cmp@0  @01 @02)) @3)
2236    (bit_and:c (convert? (icmp@4 @01 @02)) @5))
2237     (if (INTEGRAL_TYPE_P (type)
2238          && invert_tree_comparison (cmp, HONOR_NANS (@01)) == icmp
2239          /* The scalar version has to be canonicalized after vectorization
2240             because it makes unconditional loads conditional ones, which
2241             means we lose vectorization because the loads may trap.  */
2242          && canonicalize_math_after_vectorization_p ())
2243      (bit_and (cond @0 @3 @5) { build_one_cst (type); })))
2245  /* Fold ((-(a < b) & c) | (-(a >= b) & d)) into a < b ? c : d.  This is
2246     canonicalized further and we recognize the conditional form:
2247     (a < b ? c : 0) | (a >= b ? d : 0) into a < b ? c : d.  */
2248  (simplify
2249   (bit_ior
2250    (cond (cmp@0  @01 @02) @3 zerop)
2251    (cond (icmp@4 @01 @02) @5 zerop))
2252     (if (INTEGRAL_TYPE_P (type)
2253          && invert_tree_comparison (cmp, HONOR_NANS (@01)) == icmp
2254          /* The scalar version has to be canonicalized after vectorization
2255             because it makes unconditional loads conditional ones, which
2256             means we lose vectorization because the loads may trap.  */
2257          && canonicalize_math_after_vectorization_p ())
2258     (cond @0 @3 @5)))
2260  /* Vector Fold (((a < b) & c) | ((a >= b) & d)) into a < b ? c : d. 
2261     and ((~(a < b) & c) | (~(a >= b) & d)) into a < b ? c : d.  */
2262  (simplify
2263   (bit_ior
2264    (bit_and:c (vec_cond:s (cmp@0 @6 @7) @4 @5) @2)
2265    (bit_and:c (vec_cond:s (icmp@1 @6 @7) @4 @5) @3))
2266     (if (integer_zerop (@5)
2267          && invert_tree_comparison (cmp, HONOR_NANS (@6)) == icmp)
2268      (switch
2269       (if (integer_onep (@4))
2270        (bit_and (vec_cond @0 @2 @3) @4))
2271         (if (integer_minus_onep (@4))
2272          (vec_cond @0 @2 @3)))
2273     (if (integer_zerop (@4)
2274          && invert_tree_comparison (cmp, HONOR_NANS (@6)) == icmp)
2275      (switch
2276       (if (integer_onep (@5))
2277        (bit_and (vec_cond @0 @3 @2) @5))
2278       (if (integer_minus_onep (@5))
2279        (vec_cond @0 @3 @2))))))
2281  /* Scalar Vectorized Fold ((-(a < b) & c) | (-(a >= b) & d))
2282     into a < b ? d : c.  */
2283  (simplify
2284   (bit_ior
2285    (vec_cond:s (cmp@0 @4 @5) @2 integer_zerop)
2286    (vec_cond:s (icmp@1 @4 @5) @3 integer_zerop))
2287   (if (invert_tree_comparison (cmp, HONOR_NANS (@4)) == icmp)
2288    (vec_cond @0 @2 @3))))
2290 /* Transform X & -Y into X * Y when Y is { 0 or 1 }.  */
2291 (simplify
2292  (bit_and:c (convert? (negate zero_one_valued_p@0)) @1)
2293  (if (INTEGRAL_TYPE_P (type)
2294       && INTEGRAL_TYPE_P (TREE_TYPE (@0))
2295       && TREE_CODE (TREE_TYPE (@0)) != BOOLEAN_TYPE
2296       /* Sign extending of the neg or a truncation of the neg
2297          is needed. */
2298       && (!TYPE_UNSIGNED (TREE_TYPE (@0))
2299           || TYPE_PRECISION (type) <= TYPE_PRECISION (TREE_TYPE (@0))))
2300   (mult (convert @0) @1)))
2302 /* Narrow integer multiplication by a zero_one_valued_p operand.
2303    Multiplication by [0,1] is guaranteed not to overflow.  */
2304 (simplify
2305  (convert (mult@0 zero_one_valued_p@1 INTEGER_CST@2))
2306  (if (INTEGRAL_TYPE_P (type)
2307       && INTEGRAL_TYPE_P (TREE_TYPE (@0))
2308       && TYPE_PRECISION (type) < TYPE_PRECISION (TREE_TYPE (@0)))
2309   (mult (convert @1) (convert @2))))
2311 /* (X << C) != 0 can be simplified to X, when C is zero_one_valued_p.
2312    Check that the shift is well-defined (C is less than TYPE_PRECISION)
2313    as some targets (such as x86's SSE) may return zero for larger C.  */
2314 (simplify
2315   (ne (lshift zero_one_valued_p@0 INTEGER_CST@1) integer_zerop@2)
2316   (if (tree_fits_shwi_p (@1)
2317        && tree_to_shwi (@1) > 0
2318        && tree_to_shwi (@1) < TYPE_PRECISION (TREE_TYPE (@0)))
2319     (convert @0)))
2321 /* (X << C) == 0 can be simplified to X == 0, when C is zero_one_valued_p.
2322    Check that the shift is well-defined (C is less than TYPE_PRECISION)
2323    as some targets (such as x86's SSE) may return zero for larger C.  */
2324 (simplify
2325   (eq (lshift zero_one_valued_p@0 INTEGER_CST@1) integer_zerop@2)
2326   (if (tree_fits_shwi_p (@1)
2327        && tree_to_shwi (@1) > 0
2328        && tree_to_shwi (@1) < TYPE_PRECISION (TREE_TYPE (@0)))
2329     (eq @0 @2)))
2331 /* Convert ~ (-A) to A - 1.  */
2332 (simplify
2333  (bit_not (convert? (negate @0)))
2334  (if (element_precision (type) <= element_precision (TREE_TYPE (@0))
2335       || !TYPE_UNSIGNED (TREE_TYPE (@0)))
2336   (convert (minus @0 { build_each_one_cst (TREE_TYPE (@0)); }))))
2338 /* Convert - (~A) to A + 1.  */
2339 (simplify
2340  (negate (nop_convert? (bit_not @0)))
2341  (plus (view_convert @0) { build_each_one_cst (type); }))
2343 /* (a & b) ^ (a == b) -> !(a | b) */
2344 /* (a & b) == (a ^ b) -> !(a | b) */
2345 (for first_op (bit_xor eq)
2346      second_op (eq bit_xor)
2347  (simplify
2348   (first_op:c (bit_and:c truth_valued_p@0 truth_valued_p@1) (second_op:c @0 @1))
2349     (bit_not (bit_ior @0 @1))))
2351 /* Convert ~ (A - 1) or ~ (A + -1) to -A.  */
2352 (simplify
2353  (bit_not (convert? (minus @0 integer_each_onep)))
2354  (if (element_precision (type) <= element_precision (TREE_TYPE (@0))
2355       || !TYPE_UNSIGNED (TREE_TYPE (@0)))
2356   (convert (negate @0))))
2357 (simplify
2358  (bit_not (convert? (plus @0 integer_all_onesp)))
2359  (if (element_precision (type) <= element_precision (TREE_TYPE (@0))
2360       || !TYPE_UNSIGNED (TREE_TYPE (@0)))
2361   (convert (negate @0))))
2363 /* Part of convert ~(X ^ Y) to ~X ^ Y or X ^ ~Y if ~X or ~Y simplify.  */
2364 (simplify
2365  (bit_not (convert? (bit_xor @0 INTEGER_CST@1)))
2366  (if (tree_nop_conversion_p (type, TREE_TYPE (@0)))
2367   (convert (bit_xor @0 (bit_not @1)))))
2368 (simplify
2369  (bit_not (convert? (bit_xor:c (bit_not @0) @1)))
2370  (if (tree_nop_conversion_p (type, TREE_TYPE (@0)))
2371   (convert (bit_xor @0 @1))))
2373 /* Otherwise prefer ~(X ^ Y) to ~X ^ Y as more canonical.  */
2374 (simplify
2375  (bit_xor:c (nop_convert?:s (bit_not:s @0)) @1)
2376  (if (tree_nop_conversion_p (type, TREE_TYPE (@0)))
2377   (bit_not (bit_xor (view_convert @0) @1))))
2379 /* ~(a ^ b) is a == b for truth valued a and b.  */
2380 (simplify
2381  (bit_not (bit_xor:s truth_valued_p@0 truth_valued_p@1))
2382  (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
2383       && TYPE_PRECISION (TREE_TYPE (@0)) == 1)
2384   (convert (eq @0 @1))))
2386 /* (~a) == b is a ^ b for truth valued a and b.  */
2387 (simplify
2388  (eq:c (bit_not:s truth_valued_p@0) truth_valued_p@1)
2389  (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
2390       && TYPE_PRECISION (TREE_TYPE (@0)) == 1)
2391   (convert (bit_xor @0 @1))))
2393 /* (x & ~m) | (y & m) -> ((x ^ y) & m) ^ x */
2394 (simplify
2395  (bit_ior:c (bit_and:cs @0 (bit_not @2)) (bit_and:cs @1 @2))
2396  (bit_xor (bit_and (bit_xor @0 @1) @2) @0))
2398 /* Fold A - (A & B) into ~B & A.  */
2399 (simplify
2400  (minus (convert1? @0) (convert2?:s (bit_and:cs @@0 @1)))
2401  (if (tree_nop_conversion_p (type, TREE_TYPE (@0))
2402       && tree_nop_conversion_p (type, TREE_TYPE (@1)))
2403   (convert (bit_and (bit_not @1) @0))))
2405 /* (m1 CMP m2) * d -> (m1 CMP m2) ? d : 0  */
2406 (if (!canonicalize_math_p ())
2407  (for cmp (tcc_comparison)
2408   (simplify
2409    (mult:c (convert (cmp@0 @1 @2)) @3)
2410    (if (INTEGRAL_TYPE_P (type)
2411         && INTEGRAL_TYPE_P (TREE_TYPE (@0)))
2412      (cond @0 @3 { build_zero_cst (type); })))
2413 /* (-(m1 CMP m2)) & d -> (m1 CMP m2) ? d : 0  */
2414   (simplify
2415    (bit_and:c (negate (convert (cmp@0 @1 @2))) @3)
2416    (if (INTEGRAL_TYPE_P (type)
2417         && INTEGRAL_TYPE_P (TREE_TYPE (@0)))
2418      (cond @0 @3 { build_zero_cst (type); })))
2422 /* For integral types with undefined overflow and C != 0 fold
2423    x * C EQ/NE y * C into x EQ/NE y.  */
2424 (for cmp (eq ne)
2425  (simplify
2426   (cmp (mult:c @0 @1) (mult:c @2 @1))
2427   (if (INTEGRAL_TYPE_P (TREE_TYPE (@1))
2428        && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (@0))
2429        && tree_expr_nonzero_p (@1))
2430    (cmp @0 @2))))
2432 /* For integral types with wrapping overflow and C odd fold
2433    x * C EQ/NE y * C into x EQ/NE y.  */
2434 (for cmp (eq ne)
2435  (simplify
2436   (cmp (mult @0 INTEGER_CST@1) (mult @2 @1))
2437   (if (INTEGRAL_TYPE_P (TREE_TYPE (@1))
2438        && TYPE_OVERFLOW_WRAPS (TREE_TYPE (@0))
2439        && (TREE_INT_CST_LOW (@1) & 1) != 0)
2440    (cmp @0 @2))))
2442 /* For integral types with undefined overflow and C != 0 fold
2443    x * C RELOP y * C into:
2445    x RELOP y for nonnegative C
2446    y RELOP x for negative C  */
2447 (for cmp (lt gt le ge)
2448  (simplify
2449   (cmp (mult:c @0 @1) (mult:c @2 @1))
2450   (if (INTEGRAL_TYPE_P (TREE_TYPE (@1))
2451        && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (@0)))
2452    (if (tree_expr_nonnegative_p (@1) && tree_expr_nonzero_p (@1))
2453     (cmp @0 @2)
2454    (if (TREE_CODE (@1) == INTEGER_CST
2455         && wi::neg_p (wi::to_wide (@1), TYPE_SIGN (TREE_TYPE (@1))))
2456     (cmp @2 @0))))))
2458 /* (X - 1U) <= INT_MAX-1U into (int) X > 0.  */
2459 (for cmp (le gt)
2460      icmp (gt le)
2461  (simplify
2462   (cmp (plus @0 integer_minus_onep@1) INTEGER_CST@2)
2463    (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
2464         && TYPE_UNSIGNED (TREE_TYPE (@0))
2465         && TYPE_PRECISION (TREE_TYPE (@0)) > 1
2466         && (wi::to_wide (@2)
2467             == wi::max_value (TYPE_PRECISION (TREE_TYPE (@0)), SIGNED) - 1))
2468     (with { tree stype = signed_type_for (TREE_TYPE (@0)); }
2469      (icmp (convert:stype @0) { build_int_cst (stype, 0); })))))
2471 /* X / 4 < Y / 4 iff X < Y when the division is known to be exact.  */
2472 (for cmp (simple_comparison)
2473  (simplify
2474   (cmp (convert?@3 (exact_div @0 INTEGER_CST@2)) (convert? (exact_div @1 @2)))
2475   (if (element_precision (@3) >= element_precision (@0)
2476        && types_match (@0, @1))
2477    (if (wi::lt_p (wi::to_wide (@2), 0, TYPE_SIGN (TREE_TYPE (@2))))
2478     (if (!TYPE_UNSIGNED (TREE_TYPE (@3)))
2479      (cmp @1 @0)
2480      (if (tree_expr_nonzero_p (@0) && tree_expr_nonzero_p (@1))
2481       (with
2482        {
2483         tree utype = unsigned_type_for (TREE_TYPE (@0));
2484        }
2485        (cmp (convert:utype @1) (convert:utype @0)))))
2486     (if (wi::gt_p (wi::to_wide (@2), 1, TYPE_SIGN (TREE_TYPE (@2))))
2487      (if (TYPE_UNSIGNED (TREE_TYPE (@0)) || !TYPE_UNSIGNED (TREE_TYPE (@3)))
2488       (cmp @0 @1)
2489       (with
2490        {
2491         tree utype = unsigned_type_for (TREE_TYPE (@0));
2492        }
2493        (cmp (convert:utype @0) (convert:utype @1)))))))))
2495 /* X / C1 op C2 into a simple range test.  */
2496 (for cmp (simple_comparison)
2497  (simplify
2498   (cmp (trunc_div:s @0 INTEGER_CST@1) INTEGER_CST@2)
2499   (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
2500        && integer_nonzerop (@1)
2501        && !TREE_OVERFLOW (@1)
2502        && !TREE_OVERFLOW (@2))
2503    (with { tree lo, hi; bool neg_overflow;
2504            enum tree_code code = fold_div_compare (cmp, @1, @2, &lo, &hi,
2505                                                    &neg_overflow); }
2506     (switch
2507      (if (code == LT_EXPR || code == GE_EXPR)
2508        (if (TREE_OVERFLOW (lo))
2509         { build_int_cst (type, (code == LT_EXPR) ^ neg_overflow); }
2510         (if (code == LT_EXPR)
2511          (lt @0 { lo; })
2512          (ge @0 { lo; }))))
2513      (if (code == LE_EXPR || code == GT_EXPR)
2514        (if (TREE_OVERFLOW (hi))
2515         { build_int_cst (type, (code == LE_EXPR) ^ neg_overflow); }
2516         (if (code == LE_EXPR)
2517          (le @0 { hi; })
2518          (gt @0 { hi; }))))
2519      (if (!lo && !hi)
2520       { build_int_cst (type, code == NE_EXPR); })
2521      (if (code == EQ_EXPR && !hi)
2522       (ge @0 { lo; }))
2523      (if (code == EQ_EXPR && !lo)
2524       (le @0 { hi; }))
2525      (if (code == NE_EXPR && !hi)
2526       (lt @0 { lo; }))
2527      (if (code == NE_EXPR && !lo)
2528       (gt @0 { hi; }))
2529      (if (GENERIC)
2530       { build_range_check (UNKNOWN_LOCATION, type, @0, code == EQ_EXPR,
2531                            lo, hi); })
2532      (with
2533       {
2534         tree etype = range_check_type (TREE_TYPE (@0));
2535         if (etype)
2536           {
2537             hi = fold_convert (etype, hi);
2538             lo = fold_convert (etype, lo);
2539             hi = const_binop (MINUS_EXPR, etype, hi, lo);
2540           }
2541       }
2542       (if (etype && hi && !TREE_OVERFLOW (hi))
2543        (if (code == EQ_EXPR)
2544         (le (minus (convert:etype @0) { lo; }) { hi; })
2545         (gt (minus (convert:etype @0) { lo; }) { hi; })))))))))
2547 /* X + Z < Y + Z is the same as X < Y when there is no overflow.  */
2548 (for op (lt le ge gt)
2549  (simplify
2550   (op (plus:c @0 @2) (plus:c @1 @2))
2551   (if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (@0))
2552        && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (@0)))
2553    (op @0 @1))))
2555 /* As a special case, X + C < Y + C is the same as (signed) X < (signed) Y
2556    when C is an unsigned integer constant with only the MSB set, and X and
2557    Y have types of equal or lower integer conversion rank than C's.  */
2558 (for op (lt le ge gt)
2559  (simplify
2560   (op (plus @1 INTEGER_CST@0) (plus @2 @0))
2561   (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
2562        && TYPE_UNSIGNED (TREE_TYPE (@0))
2563        && wi::only_sign_bit_p (wi::to_wide (@0)))
2564    (with { tree stype = signed_type_for (TREE_TYPE (@0)); }
2565     (op (convert:stype @1) (convert:stype @2))))))
2567 /* For equality and subtraction, this is also true with wrapping overflow.  */
2568 (for op (eq ne minus)
2569  (simplify
2570   (op (plus:c @0 @2) (plus:c @1 @2))
2571   (if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (@0))
2572        && (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (@0))
2573            || TYPE_OVERFLOW_WRAPS (TREE_TYPE (@0))))
2574    (op @0 @1))))
2576 /* X - Z < Y - Z is the same as X < Y when there is no overflow.  */
2577 (for op (lt le ge gt)
2578  (simplify
2579   (op (minus @0 @2) (minus @1 @2))
2580   (if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (@0))
2581        && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (@0)))
2582    (op @0 @1))))
2583 /* For equality and subtraction, this is also true with wrapping overflow.  */
2584 (for op (eq ne minus)
2585  (simplify
2586   (op (minus @0 @2) (minus @1 @2))
2587   (if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (@0))
2588        && (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (@0))
2589            || TYPE_OVERFLOW_WRAPS (TREE_TYPE (@0))))
2590    (op @0 @1))))
2591 /* And for pointers...  */
2592 (for op (simple_comparison)
2593  (simplify
2594   (op (pointer_diff@3 @0 @2) (pointer_diff @1 @2))
2595   (if (!TYPE_OVERFLOW_SANITIZED (TREE_TYPE (@2)))
2596    (op @0 @1))))
2597 (simplify
2598  (minus (pointer_diff@3 @0 @2) (pointer_diff @1 @2))
2599  (if (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (@3))
2600       && !TYPE_OVERFLOW_SANITIZED (TREE_TYPE (@2)))
2601   (pointer_diff @0 @1)))
2603 /* Z - X < Z - Y is the same as Y < X when there is no overflow.  */
2604 (for op (lt le ge gt)
2605  (simplify
2606   (op (minus @2 @0) (minus @2 @1))
2607   (if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (@0))
2608        && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (@0)))
2609    (op @1 @0))))
2610 /* For equality and subtraction, this is also true with wrapping overflow.  */
2611 (for op (eq ne minus)
2612  (simplify
2613   (op (minus @2 @0) (minus @2 @1))
2614   (if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (@0))
2615        && (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (@0))
2616            || TYPE_OVERFLOW_WRAPS (TREE_TYPE (@0))))
2617    (op @1 @0))))
2618 /* And for pointers...  */
2619 (for op (simple_comparison)
2620  (simplify
2621   (op (pointer_diff@3 @2 @0) (pointer_diff @2 @1))
2622   (if (!TYPE_OVERFLOW_SANITIZED (TREE_TYPE (@2)))
2623    (op @1 @0))))
2624 (simplify
2625  (minus (pointer_diff@3 @2 @0) (pointer_diff @2 @1))
2626  (if (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (@3))
2627       && !TYPE_OVERFLOW_SANITIZED (TREE_TYPE (@2)))
2628   (pointer_diff @1 @0)))
2630 /* X + Y < Y is the same as X < 0 when there is no overflow.  */
2631 (for op (lt le gt ge)
2632  (simplify
2633   (op:c (plus:c@2 @0 @1) @1)
2634   (if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (@0))
2635        && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (@0))
2636        && !TYPE_OVERFLOW_SANITIZED (TREE_TYPE (@0))
2637        && (CONSTANT_CLASS_P (@0) || single_use (@2)))
2638    (op @0 { build_zero_cst (TREE_TYPE (@0)); }))))
2639 /* For equality, this is also true with wrapping overflow.  */
2640 (for op (eq ne)
2641  (simplify
2642   (op:c (nop_convert?@3 (plus:c@2 @0 (convert1? @1))) (convert2? @1))
2643   (if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (@0))
2644        && (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (@0))
2645            || TYPE_OVERFLOW_WRAPS (TREE_TYPE (@0)))
2646        && (CONSTANT_CLASS_P (@0) || (single_use (@2) && single_use (@3)))
2647        && tree_nop_conversion_p (TREE_TYPE (@3), TREE_TYPE (@2))
2648        && tree_nop_conversion_p (TREE_TYPE (@3), TREE_TYPE (@1)))
2649    (op @0 { build_zero_cst (TREE_TYPE (@0)); })))
2650  (simplify
2651   (op:c (nop_convert?@3 (pointer_plus@2 (convert1? @0) @1)) (convert2? @0))
2652   (if (tree_nop_conversion_p (TREE_TYPE (@2), TREE_TYPE (@0))
2653        && tree_nop_conversion_p (TREE_TYPE (@3), TREE_TYPE (@0))
2654        && (CONSTANT_CLASS_P (@1) || (single_use (@2) && single_use (@3))))
2655    (op @1 { build_zero_cst (TREE_TYPE (@1)); }))))
2657 /* (&a + b) !=/== (&a[1] + c) -> (&a[0] - &a[1]) + b !=/== c */
2658 (for neeq (ne eq)
2659  (simplify
2660   (neeq:c ADDR_EXPR@0 (pointer_plus @2 @3))
2661    (with { poly_int64 diff; tree inner_type = TREE_TYPE (@3);}
2662     (if (ptr_difference_const (@0, @2, &diff))
2663      (neeq { build_int_cst_type (inner_type, diff); } @3))))
2664  (simplify
2665   (neeq (pointer_plus ADDR_EXPR@0 @1) (pointer_plus ADDR_EXPR@2 @3))
2666    (with { poly_int64 diff; tree inner_type = TREE_TYPE (@1);}
2667     (if (ptr_difference_const (@0, @2, &diff))
2668      (neeq (plus { build_int_cst_type (inner_type, diff); } @1) @3)))))
2670 /* X - Y < X is the same as Y > 0 when there is no overflow.
2671    For equality, this is also true with wrapping overflow.  */
2672 (for op (simple_comparison)
2673  (simplify
2674   (op:c @0 (minus@2 @0 @1))
2675   (if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (@0))
2676        && (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (@0))
2677            || ((op == EQ_EXPR || op == NE_EXPR)
2678                && TYPE_OVERFLOW_WRAPS (TREE_TYPE (@0))))
2679        && (CONSTANT_CLASS_P (@1) || single_use (@2)))
2680    (op @1 { build_zero_cst (TREE_TYPE (@1)); }))))
2682 /* Transform:
2683    (X / Y) == 0 -> X < Y if X, Y are unsigned.
2684    (X / Y) != 0 -> X >= Y, if X, Y are unsigned.  */
2685 (for cmp (eq ne)
2686      ocmp (lt ge)
2687  (simplify
2688   (cmp (trunc_div @0 @1) integer_zerop)
2689   (if (TYPE_UNSIGNED (TREE_TYPE (@0))
2690        /* Complex ==/!= is allowed, but not </>=.  */
2691        && TREE_CODE (TREE_TYPE (@0)) != COMPLEX_TYPE
2692        && (VECTOR_TYPE_P (type) || !VECTOR_TYPE_P (TREE_TYPE (@0))))
2693    (ocmp @0 @1))))
2695 /* X == C - X can never be true if C is odd.  */
2696 (for cmp (eq ne)
2697  (simplify
2698   (cmp:c (convert? @0) (convert1? (minus INTEGER_CST@1 (convert2? @0))))
2699   (if (TREE_INT_CST_LOW (@1) & 1)
2700    { constant_boolean_node (cmp == NE_EXPR, type); })))
2702 /* Arguments on which one can call get_nonzero_bits to get the bits
2703    possibly set.  */
2704 (match with_possible_nonzero_bits
2705  INTEGER_CST@0)
2706 (match with_possible_nonzero_bits
2707  SSA_NAME@0
2708  (if (INTEGRAL_TYPE_P (TREE_TYPE (@0)) || POINTER_TYPE_P (TREE_TYPE (@0)))))
2709 /* Slightly extended version, do not make it recursive to keep it cheap.  */
2710 (match (with_possible_nonzero_bits2 @0)
2711  with_possible_nonzero_bits@0)
2712 (match (with_possible_nonzero_bits2 @0)
2713  (bit_and:c with_possible_nonzero_bits@0 @2))
2715 /* Same for bits that are known to be set, but we do not have
2716    an equivalent to get_nonzero_bits yet.  */
2717 (match (with_certain_nonzero_bits2 @0)
2718  INTEGER_CST@0)
2719 (match (with_certain_nonzero_bits2 @0)
2720  (bit_ior @1 INTEGER_CST@0))
2722 /* X == C (or X & Z == Y | C) is impossible if ~nonzero(X) & C != 0.  */
2723 (for cmp (eq ne)
2724  (simplify
2725   (cmp:c (with_possible_nonzero_bits2 @0) (with_certain_nonzero_bits2 @1))
2726   (if (wi::bit_and_not (wi::to_wide (@1), get_nonzero_bits (@0)) != 0)
2727    { constant_boolean_node (cmp == NE_EXPR, type); })))
2729 /* ((X inner_op C0) outer_op C1)
2730    With X being a tree where value_range has reasoned certain bits to always be
2731    zero throughout its computed value range,
2732    inner_op = {|,^}, outer_op = {|,^} and inner_op != outer_op
2733    where zero_mask has 1's for all bits that are sure to be 0 in
2734    and 0's otherwise.
2735    if (inner_op == '^') C0 &= ~C1;
2736    if ((C0 & ~zero_mask) == 0) then emit (X outer_op (C0 outer_op C1)
2737    if ((C1 & ~zero_mask) == 0) then emit (X inner_op (C0 outer_op C1)
2739 (for inner_op (bit_ior bit_xor)
2740      outer_op (bit_xor bit_ior)
2741 (simplify
2742  (outer_op
2743   (inner_op:s @2 INTEGER_CST@0) INTEGER_CST@1)
2744  (with
2745   {
2746     bool fail = false;
2747     wide_int zero_mask_not;
2748     wide_int C0;
2749     wide_int cst_emit;
2751     if (TREE_CODE (@2) == SSA_NAME)
2752       zero_mask_not = get_nonzero_bits (@2);
2753     else
2754       fail = true;
2756     if (inner_op == BIT_XOR_EXPR)
2757       {
2758         C0 = wi::bit_and_not (wi::to_wide (@0), wi::to_wide (@1));
2759         cst_emit = C0 | wi::to_wide (@1);
2760       }
2761     else
2762       {
2763         C0 = wi::to_wide (@0);
2764         cst_emit = C0 ^ wi::to_wide (@1);
2765       }
2766   }
2767   (if (!fail && (C0 & zero_mask_not) == 0)
2768    (outer_op @2 { wide_int_to_tree (type, cst_emit); })
2769    (if (!fail && (wi::to_wide (@1) & zero_mask_not) == 0)
2770     (inner_op @2 { wide_int_to_tree (type, cst_emit); }))))))
2772 /* Associate (p +p off1) +p off2 as (p +p (off1 + off2)).  */
2773 (simplify
2774   (pointer_plus (pointer_plus:s @0 @1) @3)
2775   (pointer_plus @0 (plus @1 @3)))
2776 #if GENERIC
2777 (simplify
2778   (pointer_plus (convert:s (pointer_plus:s @0 @1)) @3)
2779   (convert:type (pointer_plus @0 (plus @1 @3))))
2780 #endif
2782 /* Pattern match
2783      tem1 = (long) ptr1;
2784      tem2 = (long) ptr2;
2785      tem3 = tem2 - tem1;
2786      tem4 = (unsigned long) tem3;
2787      tem5 = ptr1 + tem4;
2788    and produce
2789      tem5 = ptr2;  */
2790 (simplify
2791   (pointer_plus @0 (convert?@2 (minus@3 (convert @1) (convert @0))))
2792   /* Conditionally look through a sign-changing conversion.  */
2793   (if (TYPE_PRECISION (TREE_TYPE (@2)) == TYPE_PRECISION (TREE_TYPE (@3))
2794        && ((GIMPLE && useless_type_conversion_p (type, TREE_TYPE (@1)))
2795             || (GENERIC && type == TREE_TYPE (@1))))
2796    @1))
2797 (simplify
2798   (pointer_plus @0 (convert?@2 (pointer_diff@3 @1 @@0)))
2799   (if (TYPE_PRECISION (TREE_TYPE (@2)) >= TYPE_PRECISION (TREE_TYPE (@3)))
2800    (convert @1)))
2802 /* Pattern match
2803      tem = (sizetype) ptr;
2804      tem = tem & algn;
2805      tem = -tem;
2806      ... = ptr p+ tem;
2807    and produce the simpler and easier to analyze with respect to alignment
2808      ... = ptr & ~algn;  */
2809 (simplify
2810   (pointer_plus @0 (negate (bit_and (convert @0) INTEGER_CST@1)))
2811   (with { tree algn = wide_int_to_tree (TREE_TYPE (@0), ~wi::to_wide (@1)); }
2812    (bit_and @0 { algn; })))
2814 /* Try folding difference of addresses.  */
2815 (simplify
2816  (minus (convert ADDR_EXPR@0) (convert (pointer_plus @1 @2)))
2817  (if (tree_nop_conversion_p (type, TREE_TYPE (@0)))
2818   (with { poly_int64 diff; }
2819    (if (ptr_difference_const (@0, @1, &diff))
2820     (minus { build_int_cst_type (type, diff); } (convert @2))))))
2821 (simplify
2822  (minus (convert (pointer_plus @0 @2)) (convert ADDR_EXPR@1))
2823  (if (tree_nop_conversion_p (type, TREE_TYPE (@0)))
2824   (with { poly_int64 diff; }
2825    (if (ptr_difference_const (@0, @1, &diff))
2826     (plus (convert @2) { build_int_cst_type (type, diff); })))))
2827 (simplify
2828  (minus (convert ADDR_EXPR@0) (convert @1))
2829  (if (tree_nop_conversion_p (type, TREE_TYPE (@0)))
2830   (with { poly_int64 diff; }
2831    (if (ptr_difference_const (@0, @1, &diff))
2832     { build_int_cst_type (type, diff); }))))
2833 (simplify
2834  (minus (convert @0) (convert ADDR_EXPR@1))
2835  (if (tree_nop_conversion_p (type, TREE_TYPE (@0)))
2836   (with { poly_int64 diff; }
2837    (if (ptr_difference_const (@0, @1, &diff))
2838     { build_int_cst_type (type, diff); }))))
2839 (simplify
2840  (pointer_diff (convert?@2 ADDR_EXPR@0) (convert1?@3 @1))
2841  (if (tree_nop_conversion_p (TREE_TYPE(@2), TREE_TYPE (@0))
2842       && tree_nop_conversion_p (TREE_TYPE(@3), TREE_TYPE (@1)))
2843   (with { poly_int64 diff; }
2844    (if (ptr_difference_const (@0, @1, &diff))
2845     { build_int_cst_type (type, diff); }))))
2846 (simplify
2847  (pointer_diff (convert?@2 @0) (convert1?@3 ADDR_EXPR@1))
2848  (if (tree_nop_conversion_p (TREE_TYPE(@2), TREE_TYPE (@0))
2849       && tree_nop_conversion_p (TREE_TYPE(@3), TREE_TYPE (@1)))
2850   (with { poly_int64 diff; }
2851    (if (ptr_difference_const (@0, @1, &diff))
2852     { build_int_cst_type (type, diff); }))))
2854 /* (&a+b) - (&a[1] + c) -> sizeof(a[0]) + (b - c) */
2855 (simplify
2856  (pointer_diff (pointer_plus ADDR_EXPR@0 @1) (pointer_plus ADDR_EXPR@2 @3))
2857  (with { poly_int64 diff; }
2858    (if (ptr_difference_const (@0, @2, &diff))
2859     (plus { build_int_cst_type (type, diff); } (convert (minus @1 @3))))))
2860 /* (p + b) - &p->d -> offsetof (*p, d) + b */
2861 (simplify
2862  (pointer_diff (pointer_plus @0 @1) ADDR_EXPR@2)
2863  (with { poly_int64 diff; }
2864    (if (ptr_difference_const (@0, @2, &diff))
2865     (plus { build_int_cst_type (type, diff); } (convert @1)))))
2866 (simplify
2867  (pointer_diff ADDR_EXPR@0 (pointer_plus @1 @2))
2868  (with { poly_int64 diff; }
2869    (if (ptr_difference_const (@0, @1, &diff))
2870     (minus { build_int_cst_type (type, diff); } (convert @2)))))
2872 /* Canonicalize (T *)(ptr - ptr-cst) to &MEM[ptr + -ptr-cst].  */
2873 (simplify
2874  (convert (pointer_diff @0 INTEGER_CST@1))
2875  (if (POINTER_TYPE_P (type))
2876   { build_fold_addr_expr_with_type
2877       (build2 (MEM_REF, char_type_node, @0,
2878                wide_int_to_tree (ptr_type_node, wi::neg (wi::to_wide (@1)))),
2879                type); }))
2881 /* If arg0 is derived from the address of an object or function, we may
2882    be able to fold this expression using the object or function's
2883    alignment.  */
2884 (simplify
2885  (bit_and (convert? @0) INTEGER_CST@1)
2886  (if (POINTER_TYPE_P (TREE_TYPE (@0))
2887       && tree_nop_conversion_p (type, TREE_TYPE (@0)))
2888   (with
2889    {
2890      unsigned int align;
2891      unsigned HOST_WIDE_INT bitpos;
2892      get_pointer_alignment_1 (@0, &align, &bitpos);
2893    }
2894    (if (wi::ltu_p (wi::to_wide (@1), align / BITS_PER_UNIT))
2895     { wide_int_to_tree (type, (wi::to_wide (@1)
2896                                & (bitpos / BITS_PER_UNIT))); }))))
2898 (match min_value
2899  uniform_integer_cst_p
2900  (with {
2901    tree int_cst = uniform_integer_cst_p (t);
2902    tree inner_type = TREE_TYPE (int_cst);
2903   }
2904   (if ((INTEGRAL_TYPE_P (inner_type)
2905         || POINTER_TYPE_P (inner_type))
2906        && wi::eq_p (wi::to_wide (int_cst), wi::min_value (inner_type))))))
2908 (match max_value
2909  uniform_integer_cst_p
2910  (with {
2911    tree int_cst = uniform_integer_cst_p (t);
2912    tree itype = TREE_TYPE (int_cst);
2913   }
2914  (if ((INTEGRAL_TYPE_P (itype)
2915        || POINTER_TYPE_P (itype))
2916       && wi::eq_p (wi::to_wide (int_cst), wi::max_value (itype))))))
2918 /* x >  y  &&  x != XXX_MIN  -->  x > y
2919    x >  y  &&  x == XXX_MIN  -->  false . */
2920 (for eqne (eq ne)
2921  (simplify
2922   (bit_and:c (gt:c@2 @0 @1) (eqne @0 min_value))
2923    (switch
2924     (if (eqne == EQ_EXPR)
2925      { constant_boolean_node (false, type); })
2926     (if (eqne == NE_EXPR)
2927      @2)
2928     )))
2930 /* x <  y  &&  x != XXX_MAX  -->  x < y
2931    x <  y  &&  x == XXX_MAX  -->  false.  */
2932 (for eqne (eq ne)
2933  (simplify
2934   (bit_and:c (lt:c@2 @0 @1) (eqne @0 max_value))
2935    (switch
2936     (if (eqne == EQ_EXPR)
2937      { constant_boolean_node (false, type); })
2938     (if (eqne == NE_EXPR)
2939      @2)
2940     )))
2942 /* x <=  y  &&  x == XXX_MIN  -->  x == XXX_MIN.  */
2943 (simplify
2944  (bit_and:c (le:c @0 @1) (eq@2 @0 min_value))
2945   @2)
2947 /* x >=  y  &&  x == XXX_MAX  -->  x == XXX_MAX.  */
2948 (simplify
2949  (bit_and:c (ge:c @0 @1) (eq@2 @0 max_value))
2950   @2)
2952 /* x >  y  ||  x != XXX_MIN   -->  x != XXX_MIN.  */
2953 (simplify
2954  (bit_ior:c (gt:c @0 @1) (ne@2 @0 min_value))
2955   @2)
2957 /* x <=  y  ||  x != XXX_MIN   -->  true.  */
2958 (simplify
2959  (bit_ior:c (le:c @0 @1) (ne @0 min_value))
2960   { constant_boolean_node (true, type); })
2962 /* x <=  y  ||  x == XXX_MIN   -->  x <= y.  */
2963 (simplify
2964  (bit_ior:c (le:c@2 @0 @1) (eq @0 min_value))
2965   @2)
2967 /* x <  y  ||  x != XXX_MAX   -->  x != XXX_MAX.  */
2968 (simplify
2969  (bit_ior:c (lt:c @0 @1) (ne@2 @0 max_value))
2970   @2)
2972 /* x >=  y  ||  x != XXX_MAX   -->  true
2973    x >=  y  ||  x == XXX_MAX   -->  x >= y.  */
2974 (for eqne (eq ne)
2975  (simplify
2976   (bit_ior:c (ge:c@2 @0 @1) (eqne @0 max_value))
2977    (switch
2978     (if (eqne == EQ_EXPR)
2979      @2)
2980     (if (eqne == NE_EXPR)
2981      { constant_boolean_node (true, type); }))))
2983 /* y == XXX_MIN || x < y --> x <= y - 1 */
2984 (simplify
2985  (bit_ior:c (eq:s @1 min_value) (lt:cs @0 @1))
2986   (if (INTEGRAL_TYPE_P (TREE_TYPE (@1))
2987        && TYPE_OVERFLOW_WRAPS (TREE_TYPE (@1)))
2988   (le @0 (minus @1 { build_int_cst (TREE_TYPE (@1), 1); }))))
2990 /* y != XXX_MIN && x >= y --> x > y - 1 */
2991 (simplify
2992  (bit_and:c (ne:s @1 min_value) (ge:cs @0 @1))
2993   (if (INTEGRAL_TYPE_P (TREE_TYPE (@1))
2994        && TYPE_OVERFLOW_WRAPS (TREE_TYPE (@1)))
2995   (gt @0 (minus @1 { build_int_cst (TREE_TYPE (@1), 1); }))))
2997 /* Convert (X == CST1) && ((other)X OP2 CST2) to a known value
2998    based on CST1 OP2 CST2.  Similarly for (X != CST1).  */
2999 /* Convert (X == Y) && (X OP2 Y) to a known value if X is an integral type.
3000    Similarly for (X != Y).  */
3002 (for code1 (eq ne)
3003  (for code2 (eq ne lt gt le ge)
3004   (simplify
3005    (bit_and:c (code1:c@3 @0 @1) (code2:c@4 (convert?@c0 @0) @2))
3006    (if ((TREE_CODE (@1) == INTEGER_CST
3007          && TREE_CODE (@2) == INTEGER_CST)
3008         || ((INTEGRAL_TYPE_P (TREE_TYPE (@1))
3009              || POINTER_TYPE_P (TREE_TYPE (@1)))
3010             && bitwise_equal_p (@1, @2)))
3011     (with
3012      {
3013       bool one_before = false;
3014       bool one_after = false;
3015       int cmp = 0;
3016       bool allbits = true;
3017       if (TREE_CODE (@1) == INTEGER_CST
3018           && TREE_CODE (@2) == INTEGER_CST)
3019         {
3020           allbits = TYPE_PRECISION (TREE_TYPE (@1)) <= TYPE_PRECISION (TREE_TYPE (@2));
3021           auto t1 = wi::to_wide (fold_convert (TREE_TYPE (@2), @1));
3022           auto t2 = wi::to_wide (@2);
3023           cmp = wi::cmp (t1, t2, TYPE_SIGN (TREE_TYPE (@2)));
3024           if (cmp < 0
3025               && t1 == t2 - 1)
3026             one_before = true;
3027           if (cmp > 0
3028               && t1 == t2 + 1)
3029             one_after = true;
3030         }
3031       bool val;
3032       switch (code2)
3033          {
3034         case EQ_EXPR: val = (cmp == 0); break;
3035         case NE_EXPR: val = (cmp != 0); break;
3036         case LT_EXPR: val = (cmp < 0); break;
3037         case GT_EXPR: val = (cmp > 0); break;
3038         case LE_EXPR: val = (cmp <= 0); break;
3039         case GE_EXPR: val = (cmp >= 0); break;
3040         default: gcc_unreachable ();
3041         }
3042      }
3043      (switch
3044       (if (code1 == EQ_EXPR && val) @3)
3045       (if (code1 == EQ_EXPR && !val) { constant_boolean_node (false, type); })
3046       (if (code1 == NE_EXPR && !val && allbits) @4)
3047       (if (code1 == NE_EXPR
3048            && code2 == GE_EXPR
3049            && cmp == 0
3050            && allbits)
3051        (gt @c0 (convert @1)))
3052       (if (code1 == NE_EXPR
3053            && code2 == LE_EXPR
3054            && cmp == 0
3055            && allbits)
3056        (lt @c0 (convert @1)))
3057       /* (a != (b+1)) & (a > b) -> a > (b+1) */
3058       (if (code1 == NE_EXPR
3059            && code2 == GT_EXPR
3060            && one_after
3061            && allbits)
3062        (gt @c0 (convert @1)))
3063       /* (a != (b-1)) & (a < b) -> a < (b-1) */
3064       (if (code1 == NE_EXPR
3065            && code2 == LT_EXPR
3066            && one_before
3067            && allbits)
3068        (lt @c0 (convert @1)))
3069      )
3070     )
3071    )
3072   )
3076 /* Convert (X OP1 CST1) && (X OP2 CST2).
3077    Convert (X OP1 Y) && (X OP2 Y).  */
3079 (for code1 (lt le gt ge)
3080  (for code2 (lt le gt ge)
3081   (simplify
3082   (bit_and (code1:c@3 @0 @1) (code2:c@4 @0 @2))
3083   (if ((TREE_CODE (@1) == INTEGER_CST
3084         && TREE_CODE (@2) == INTEGER_CST)
3085        || ((INTEGRAL_TYPE_P (TREE_TYPE (@1))
3086             || POINTER_TYPE_P (TREE_TYPE (@1)))
3087            && operand_equal_p (@1, @2)))
3088    (with
3089     {
3090      int cmp = 0;
3091      if (TREE_CODE (@1) == INTEGER_CST
3092          && TREE_CODE (@2) == INTEGER_CST)
3093        cmp = tree_int_cst_compare (@1, @2);
3094     }
3095     (switch
3096      /* Choose the more restrictive of two < or <= comparisons.  */
3097      (if ((code1 == LT_EXPR || code1 == LE_EXPR)
3098           && (code2 == LT_EXPR || code2 == LE_EXPR))
3099       (if ((cmp < 0) || (cmp == 0 && code1 == LT_EXPR))
3100        @3
3101        @4))
3102      /* Likewise chose the more restrictive of two > or >= comparisons.  */
3103      (if ((code1 == GT_EXPR || code1 == GE_EXPR)
3104           && (code2 == GT_EXPR || code2 == GE_EXPR))
3105       (if ((cmp > 0) || (cmp == 0 && code1 == GT_EXPR))
3106        @3
3107        @4))
3108      /* Check for singleton ranges.  */
3109      (if (cmp == 0
3110           && ((code1 == LE_EXPR && code2 == GE_EXPR)
3111             || (code1 == GE_EXPR && code2 == LE_EXPR)))
3112       (eq @0 @1))
3113      /* Check for disjoint ranges.  */
3114      (if (cmp <= 0
3115           && (code1 == LT_EXPR || code1 == LE_EXPR)
3116           && (code2 == GT_EXPR || code2 == GE_EXPR))
3117       { constant_boolean_node (false, type); })
3118      (if (cmp >= 0
3119           && (code1 == GT_EXPR || code1 == GE_EXPR)
3120           && (code2 == LT_EXPR || code2 == LE_EXPR))
3121       { constant_boolean_node (false, type); })
3122      ))))))
3124 /* Convert (X == CST1) || (X OP2 CST2) to a known value
3125    based on CST1 OP2 CST2.  Similarly for (X != CST1).  */
3126 /* Convert (X == Y) || (X OP2 Y) to a known value if X is an integral type.
3127    Similarly for (X != Y).  */
3129 (for code1 (eq ne)
3130  (for code2 (eq ne lt gt le ge)
3131   (simplify
3132    (bit_ior:c (code1:c@3 @0 @1) (code2:c@4 (convert?@c0 @0) @2))
3133    (if ((TREE_CODE (@1) == INTEGER_CST
3134          && TREE_CODE (@2) == INTEGER_CST)
3135         || ((INTEGRAL_TYPE_P (TREE_TYPE (@1))
3136             || POINTER_TYPE_P (TREE_TYPE (@1)))
3137             && bitwise_equal_p (@1, @2)))
3138     (with
3139      {
3140       bool one_before = false;
3141       bool one_after = false;
3142       int cmp = 0;
3143       bool allbits = true;
3144       if (TREE_CODE (@1) == INTEGER_CST
3145           && TREE_CODE (@2) == INTEGER_CST)
3146         {
3147           allbits = TYPE_PRECISION (TREE_TYPE (@1)) <= TYPE_PRECISION (TREE_TYPE (@2));
3148           auto t1 = wi::to_wide (fold_convert (TREE_TYPE (@2), @1));
3149           auto t2 = wi::to_wide (@2);
3150           cmp = wi::cmp (t1, t2, TYPE_SIGN (TREE_TYPE (@2)));
3151           if (cmp < 0
3152               && t1 == t2 - 1)
3153             one_before = true;
3154           if (cmp > 0
3155               && t1 == t2 + 1)
3156             one_after = true;
3157         }
3158       bool val;
3159       switch (code2)
3160         {
3161         case EQ_EXPR: val = (cmp == 0); break;
3162         case NE_EXPR: val = (cmp != 0); break;
3163         case LT_EXPR: val = (cmp < 0); break;
3164         case GT_EXPR: val = (cmp > 0); break;
3165         case LE_EXPR: val = (cmp <= 0); break;
3166         case GE_EXPR: val = (cmp >= 0); break;
3167         default: gcc_unreachable ();
3168         }
3169      }
3170      (switch
3171       (if (code1 == EQ_EXPR && val) @4)
3172       (if (code1 == NE_EXPR && val && allbits) { constant_boolean_node (true, type); })
3173       (if (code1 == NE_EXPR && !val && allbits) @3)
3174       (if (code1 == EQ_EXPR
3175            && code2 == GT_EXPR
3176            && cmp == 0
3177            && allbits)
3178        (ge @c0 @2))
3179       (if (code1 == EQ_EXPR
3180            && code2 == LT_EXPR
3181            && cmp == 0
3182            && allbits)
3183        (le @c0 @2))
3184       /* (a == (b-1)) | (a >= b) -> a >= (b-1) */
3185       (if (code1 == EQ_EXPR
3186            && code2 == GE_EXPR
3187            && one_before
3188            && allbits)
3189        (ge @c0 (convert @1)))
3190       /* (a == (b+1)) | (a <= b) -> a <= (b-1) */
3191       (if (code1 == EQ_EXPR
3192            && code2 == LE_EXPR
3193            && one_after
3194            && allbits)
3195        (le @c0 (convert @1)))
3196      )
3197     )
3198    )
3199   )
3203 /* Convert (X OP1 CST1) || (X OP2 CST2).
3204    Convert (X OP1 Y)    || (X OP2 Y).  */
3206 (for code1 (lt le gt ge)
3207  (for code2 (lt le gt ge)
3208   (simplify
3209   (bit_ior (code1@3 @0 @1) (code2@4 @0 @2))
3210   (if ((TREE_CODE (@1) == INTEGER_CST
3211         && TREE_CODE (@2) == INTEGER_CST)
3212        || ((INTEGRAL_TYPE_P (TREE_TYPE (@1))
3213             || POINTER_TYPE_P (TREE_TYPE (@1)))
3214            && operand_equal_p (@1, @2)))
3215    (with
3216     {
3217      int cmp = 0;
3218      if (TREE_CODE (@1) == INTEGER_CST
3219          && TREE_CODE (@2) == INTEGER_CST)
3220        cmp = tree_int_cst_compare (@1, @2);
3221     }
3222     (switch
3223      /* Choose the more restrictive of two < or <= comparisons.  */
3224      (if ((code1 == LT_EXPR || code1 == LE_EXPR)
3225           && (code2 == LT_EXPR || code2 == LE_EXPR))
3226       (if ((cmp < 0) || (cmp == 0 && code1 == LT_EXPR))
3227        @4
3228        @3))
3229      /* Likewise chose the more restrictive of two > or >= comparisons.  */
3230      (if ((code1 == GT_EXPR || code1 == GE_EXPR)
3231           && (code2 == GT_EXPR || code2 == GE_EXPR))
3232       (if ((cmp > 0) || (cmp == 0 && code1 == GT_EXPR))
3233        @4
3234        @3))
3235      /* Check for singleton ranges.  */
3236      (if (cmp == 0
3237           && ((code1 == LT_EXPR && code2 == GT_EXPR)
3238               || (code1 == GT_EXPR && code2 == LT_EXPR)))
3239       (ne @0 @2))
3240      /* Check for disjoint ranges.  */
3241      (if (cmp >= 0
3242           && (code1 == LT_EXPR || code1 == LE_EXPR)
3243           && (code2 == GT_EXPR || code2 == GE_EXPR))
3244       { constant_boolean_node (true, type); })
3245      (if (cmp <= 0
3246           && (code1 == GT_EXPR || code1 == GE_EXPR)
3247           && (code2 == LT_EXPR || code2 == LE_EXPR))
3248       { constant_boolean_node (true, type); })
3249      ))))))
3251 /* Optimize (a CMP b) ^ (a CMP b)  */
3252 /* Optimize (a CMP b) != (a CMP b)  */
3253 (for op (bit_xor ne)
3254  (for cmp1 (lt lt lt le le le)
3255       cmp2 (gt eq ne ge eq ne)
3256       rcmp (ne le gt ne lt ge)
3257   (simplify
3258    (op:c (cmp1:c @0 @1) (cmp2:c @0 @1))
3259    (if (INTEGRAL_TYPE_P (TREE_TYPE (@0)) || POINTER_TYPE_P (TREE_TYPE (@0)))
3260     (rcmp @0 @1)))))
3262 /* Optimize (a CMP b) == (a CMP b)  */
3263 (for cmp1 (lt lt lt le le le)
3264      cmp2 (gt eq ne ge eq ne)
3265      rcmp (eq gt le eq ge lt)
3266  (simplify
3267   (eq:c (cmp1:c @0 @1) (cmp2:c @0 @1))
3268   (if (INTEGRAL_TYPE_P (TREE_TYPE (@0)) || POINTER_TYPE_P (TREE_TYPE (@0)))
3269     (rcmp @0 @1))))
3271 /* We can't reassociate at all for saturating types.  */
3272 (if (!TYPE_SATURATING (type))
3274  /* Contract negates.  */
3275  /* A + (-B) -> A - B */
3276  (simplify
3277   (plus:c @0 (convert? (negate @1)))
3278   /* Apply STRIP_NOPS on the negate.  */
3279   (if (tree_nop_conversion_p (type, TREE_TYPE (@1))
3280        && !TYPE_OVERFLOW_SANITIZED (type))
3281    (with
3282     {
3283      tree t1 = type;
3284      if (INTEGRAL_TYPE_P (type)
3285          && TYPE_OVERFLOW_WRAPS (type) != TYPE_OVERFLOW_WRAPS (TREE_TYPE (@1)))
3286        t1 = TYPE_OVERFLOW_WRAPS (type) ? type : TREE_TYPE (@1);
3287     }
3288     (convert (minus (convert:t1 @0) (convert:t1 @1))))))
3289  /* A - (-B) -> A + B */
3290  (simplify
3291   (minus @0 (convert? (negate @1)))
3292   (if (tree_nop_conversion_p (type, TREE_TYPE (@1))
3293        && !TYPE_OVERFLOW_SANITIZED (type))
3294    (with
3295     {
3296      tree t1 = type;
3297      if (INTEGRAL_TYPE_P (type)
3298          && TYPE_OVERFLOW_WRAPS (type) != TYPE_OVERFLOW_WRAPS (TREE_TYPE (@1)))
3299        t1 = TYPE_OVERFLOW_WRAPS (type) ? type : TREE_TYPE (@1);
3300     }
3301     (convert (plus (convert:t1 @0) (convert:t1 @1))))))
3302  /* -(T)(-A) -> (T)A
3303     Sign-extension is ok except for INT_MIN, which thankfully cannot
3304     happen without overflow.  */
3305  (simplify
3306   (negate (convert (negate @1)))
3307   (if (INTEGRAL_TYPE_P (type)
3308        && (TYPE_PRECISION (type) <= TYPE_PRECISION (TREE_TYPE (@1))
3309            || (!TYPE_UNSIGNED (TREE_TYPE (@1))
3310                && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (@1))))
3311        && !TYPE_OVERFLOW_SANITIZED (type)
3312        && !TYPE_OVERFLOW_SANITIZED (TREE_TYPE (@1)))
3313    (convert @1)))
3314  (simplify
3315   (negate (convert negate_expr_p@1))
3316   (if (SCALAR_FLOAT_TYPE_P (type)
3317        && ((DECIMAL_FLOAT_TYPE_P (type)
3318             == DECIMAL_FLOAT_TYPE_P (TREE_TYPE (@1))
3319             && TYPE_PRECISION (type) >= TYPE_PRECISION (TREE_TYPE (@1)))
3320            || !HONOR_SIGN_DEPENDENT_ROUNDING (type)))
3321    (convert (negate @1))))
3322  (simplify
3323   (negate (nop_convert? (negate @1)))
3324   (if (!TYPE_OVERFLOW_SANITIZED (type)
3325        && !TYPE_OVERFLOW_SANITIZED (TREE_TYPE (@1)))
3326    (view_convert @1)))
3328  /* We can't reassociate floating-point unless -fassociative-math
3329     or fixed-point plus or minus because of saturation to +-Inf.  */
3330  (if ((!FLOAT_TYPE_P (type) || flag_associative_math)
3331       && !FIXED_POINT_TYPE_P (type))
3333   /* Match patterns that allow contracting a plus-minus pair
3334      irrespective of overflow issues.  */
3335   /* (A +- B) - A       ->  +- B */
3336   /* (A +- B) -+ B      ->  A */
3337   /* A - (A +- B)       -> -+ B */
3338   /* A +- (B -+ A)      ->  +- B */
3339   (simplify
3340    (minus (nop_convert1? (plus:c (nop_convert2? @0) @1)) @0)
3341    (view_convert @1))
3342   (simplify
3343    (minus (nop_convert1? (minus (nop_convert2? @0) @1)) @0)
3344    (if (!ANY_INTEGRAL_TYPE_P (type)
3345         || TYPE_OVERFLOW_WRAPS (type))
3346    (negate (view_convert @1))
3347    (view_convert (negate @1))))
3348   (simplify
3349    (plus:c (nop_convert1? (minus @0 (nop_convert2? @1))) @1)
3350    (view_convert @0))
3351   (simplify
3352    (minus @0 (nop_convert1? (plus:c (nop_convert2? @0) @1)))
3353     (if (!ANY_INTEGRAL_TYPE_P (type)
3354          || TYPE_OVERFLOW_WRAPS (type))
3355      (negate (view_convert @1))
3356      (view_convert (negate @1))))
3357   (simplify
3358    (minus @0 (nop_convert1? (minus (nop_convert2? @0) @1)))
3359    (view_convert @1))
3360   /* (A +- B) + (C - A)   -> C +- B */
3361   /* (A +  B) - (A - C)   -> B + C */
3362   /* More cases are handled with comparisons.  */
3363   (simplify
3364    (plus:c (plus:c @0 @1) (minus @2 @0))
3365    (plus @2 @1))
3366   (simplify
3367    (plus:c (minus @0 @1) (minus @2 @0))
3368    (minus @2 @1))
3369   (simplify
3370    (plus:c (pointer_diff @0 @1) (pointer_diff @2 @0))
3371    (if (TYPE_OVERFLOW_UNDEFINED (type)
3372         && !TYPE_OVERFLOW_SANITIZED (TREE_TYPE (@0)))
3373     (pointer_diff @2 @1)))
3374   (simplify
3375    (minus (plus:c @0 @1) (minus @0 @2))
3376    (plus @1 @2))
3378   /* (A +- CST1) +- CST2 -> A + CST3
3379      Use view_convert because it is safe for vectors and equivalent for
3380      scalars.  */
3381   (for outer_op (plus minus)
3382    (for inner_op (plus minus)
3383         neg_inner_op (minus plus)
3384     (simplify
3385      (outer_op (nop_convert? (inner_op @0 CONSTANT_CLASS_P@1))
3386                CONSTANT_CLASS_P@2)
3387      /* If one of the types wraps, use that one.  */
3388      (if (!ANY_INTEGRAL_TYPE_P (type) || TYPE_OVERFLOW_WRAPS (type))
3389       /* If all 3 captures are CONSTANT_CLASS_P, punt, as we might recurse
3390          forever if something doesn't simplify into a constant.  */
3391       (if (!CONSTANT_CLASS_P (@0))
3392        (if (outer_op == PLUS_EXPR)
3393         (plus (view_convert @0) (inner_op! @2 (view_convert @1)))
3394         (minus (view_convert @0) (neg_inner_op! @2 (view_convert @1)))))
3395       (if (!ANY_INTEGRAL_TYPE_P (TREE_TYPE (@0))
3396            || TYPE_OVERFLOW_WRAPS (TREE_TYPE (@0)))
3397        (if (outer_op == PLUS_EXPR)
3398         (view_convert (plus @0 (inner_op! (view_convert @2) @1)))
3399         (view_convert (minus @0 (neg_inner_op! (view_convert @2) @1))))
3400        /* If the constant operation overflows we cannot do the transform
3401           directly as we would introduce undefined overflow, for example
3402           with (a - 1) + INT_MIN.  */
3403        (if (types_match (type, @0) && !TYPE_OVERFLOW_SANITIZED (type))
3404         (with { tree cst = const_binop (outer_op == inner_op
3405                                         ? PLUS_EXPR : MINUS_EXPR,
3406                                         type, @1, @2); }
3407          (if (cst)
3408           (if (INTEGRAL_TYPE_P (type) && !TREE_OVERFLOW (cst))
3409            (inner_op @0 { cst; } )
3410            /* X+INT_MAX+1 is X-INT_MIN.  */
3411            (if (INTEGRAL_TYPE_P (type)
3412                 && wi::to_wide (cst) == wi::min_value (type))
3413             (neg_inner_op @0 { wide_int_to_tree (type, wi::to_wide (cst)); })
3414             /* Last resort, use some unsigned type.  */
3415             (with { tree utype = unsigned_type_for (type); }
3416              (if (utype)
3417               (view_convert (inner_op
3418                              (view_convert:utype @0)
3419                              (view_convert:utype
3420                               { TREE_OVERFLOW (cst)
3421                                 ? drop_tree_overflow (cst) : cst; })))))))))))))))
3423   /* (CST1 - A) +- CST2 -> CST3 - A  */
3424   (for outer_op (plus minus)
3425    (simplify
3426     (outer_op (nop_convert? (minus CONSTANT_CLASS_P@1 @0)) CONSTANT_CLASS_P@2)
3427     /* If one of the types wraps, use that one.  */
3428     (if (!ANY_INTEGRAL_TYPE_P (type) || TYPE_OVERFLOW_WRAPS (type))
3429      /* If all 3 captures are CONSTANT_CLASS_P, punt, as we might recurse
3430         forever if something doesn't simplify into a constant.  */
3431      (if (!CONSTANT_CLASS_P (@0))
3432       (minus (outer_op! (view_convert @1) @2) (view_convert @0)))
3433      (if (!ANY_INTEGRAL_TYPE_P (TREE_TYPE (@0))
3434           || TYPE_OVERFLOW_WRAPS (TREE_TYPE (@0)))
3435       (view_convert (minus (outer_op! @1 (view_convert @2)) @0))
3436       (if (types_match (type, @0) && !TYPE_OVERFLOW_SANITIZED (type))
3437        (with { tree cst = const_binop (outer_op, type, @1, @2); }
3438         (if (cst && !TREE_OVERFLOW (cst))
3439          (minus { cst; } @0))))))))
3441   /* CST1 - (CST2 - A) -> CST3 + A
3442      Use view_convert because it is safe for vectors and equivalent for
3443      scalars.  */
3444   (simplify
3445    (minus CONSTANT_CLASS_P@1 (nop_convert? (minus CONSTANT_CLASS_P@2 @0)))
3446    /* If one of the types wraps, use that one.  */
3447    (if (!ANY_INTEGRAL_TYPE_P (type) || TYPE_OVERFLOW_WRAPS (type))
3448     /* If all 3 captures are CONSTANT_CLASS_P, punt, as we might recurse
3449       forever if something doesn't simplify into a constant.  */
3450     (if (!CONSTANT_CLASS_P (@0))
3451      (plus (view_convert @0) (minus! @1 (view_convert @2))))
3452     (if (!ANY_INTEGRAL_TYPE_P (TREE_TYPE (@0))
3453          || TYPE_OVERFLOW_WRAPS (TREE_TYPE (@0)))
3454      (view_convert (plus @0 (minus! (view_convert @1) @2)))
3455      (if (types_match (type, @0) && !TYPE_OVERFLOW_SANITIZED (type))
3456       (with { tree cst = const_binop (MINUS_EXPR, type, @1, @2); }
3457        (if (cst && !TREE_OVERFLOW (cst))
3458         (plus { cst; } @0)))))))
3460 /* ((T)(A)) + CST -> (T)(A + CST)  */
3461 #if GIMPLE
3462   (simplify
3463    (plus (convert:s SSA_NAME@0) INTEGER_CST@1)
3464     (if (TREE_CODE (TREE_TYPE (@0)) == INTEGER_TYPE
3465          && TREE_CODE (type) == INTEGER_TYPE
3466          && TYPE_PRECISION (type) > TYPE_PRECISION (TREE_TYPE (@0))
3467          && int_fits_type_p (@1, TREE_TYPE (@0)))
3468      /* Perform binary operation inside the cast if the constant fits
3469         and (A + CST)'s range does not overflow.  */
3470      (with
3471       {
3472         wi::overflow_type min_ovf = wi::OVF_OVERFLOW,
3473                           max_ovf = wi::OVF_OVERFLOW;
3474         tree inner_type = TREE_TYPE (@0);
3476         wide_int w1
3477           = wide_int::from (wi::to_wide (@1), TYPE_PRECISION (inner_type),
3478                             TYPE_SIGN (inner_type));
3480         value_range vr;
3481         if (get_global_range_query ()->range_of_expr (vr, @0)
3482             && !vr.varying_p () && !vr.undefined_p ())
3483           {
3484             wide_int wmin0 = vr.lower_bound ();
3485             wide_int wmax0 = vr.upper_bound ();
3486             wi::add (wmin0, w1, TYPE_SIGN (inner_type), &min_ovf);
3487             wi::add (wmax0, w1, TYPE_SIGN (inner_type), &max_ovf);
3488           }
3489       }
3490      (if (min_ovf == wi::OVF_NONE && max_ovf == wi::OVF_NONE)
3491       (convert (plus @0 { wide_int_to_tree (TREE_TYPE (@0), w1); } )))
3492      )))
3493 #endif
3495 /* ((T)(A + CST1)) + CST2 -> (T)(A) + (T)CST1 + CST2  */
3496 #if GIMPLE
3497   (for op (plus minus)
3498    (simplify
3499     (plus (convert:s (op:s @0 INTEGER_CST@1)) INTEGER_CST@2)
3500      (if (TREE_CODE (TREE_TYPE (@0)) == INTEGER_TYPE
3501           && TREE_CODE (type) == INTEGER_TYPE
3502           && TYPE_PRECISION (type) > TYPE_PRECISION (TREE_TYPE (@0))
3503           && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (@0))
3504           && !TYPE_OVERFLOW_SANITIZED (TREE_TYPE (@0))
3505           && TYPE_OVERFLOW_WRAPS (type))
3506        (plus (convert @0) (op @2 (convert @1))))))
3507 #endif
3509 /* (T)(A) +- (T)(B) -> (T)(A +- B) only when (A +- B) could be simplified
3510    to a simple value.  */
3511   (for op (plus minus)
3512    (simplify
3513     (op (convert @0) (convert @1))
3514      (if (INTEGRAL_TYPE_P (type)
3515           && INTEGRAL_TYPE_P (TREE_TYPE (@0))
3516           && TYPE_PRECISION (type) <= TYPE_PRECISION (TREE_TYPE (@0))
3517           && types_match (TREE_TYPE (@0), TREE_TYPE (@1))
3518           && !TYPE_OVERFLOW_TRAPS (type)
3519           && !TYPE_OVERFLOW_SANITIZED (type))
3520       (convert (op! @0 @1)))))
3522   /* ~A + A -> -1 */
3523   (simplify
3524    (plus:c (convert? (bit_not @0)) (convert? @0))
3525    (if (!TYPE_OVERFLOW_TRAPS (type))
3526     (convert { build_all_ones_cst (TREE_TYPE (@0)); })))
3528   /* ~A + 1 -> -A */
3529   (simplify
3530    (plus (convert? (bit_not @0)) integer_each_onep)
3531    (if (tree_nop_conversion_p (type, TREE_TYPE (@0)))
3532     (negate (convert @0))))
3534   /* -A - 1 -> ~A */
3535   (simplify
3536    (minus (convert? (negate @0)) integer_each_onep)
3537    (if (!TYPE_OVERFLOW_TRAPS (type)
3538         && TREE_CODE (type) != COMPLEX_TYPE
3539         && tree_nop_conversion_p (type, TREE_TYPE (@0)))
3540     (bit_not (convert @0))))
3542   /* -1 - A -> ~A */
3543   (simplify
3544    (minus integer_all_onesp @0)
3545    (if (TREE_CODE (type) != COMPLEX_TYPE)
3546     (bit_not @0)))
3548   /* (T)(P + A) - (T)P -> (T) A */
3549   (simplify
3550    (minus (convert (plus:c @@0 @1))
3551     (convert? @0))
3552    (if (element_precision (type) <= element_precision (TREE_TYPE (@1))
3553         /* For integer types, if A has a smaller type
3554            than T the result depends on the possible
3555            overflow in P + A.
3556            E.g. T=size_t, A=(unsigned)429497295, P>0.
3557            However, if an overflow in P + A would cause
3558            undefined behavior, we can assume that there
3559            is no overflow.  */
3560         || (INTEGRAL_TYPE_P (TREE_TYPE (@1))
3561             && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (@1))))
3562     (convert @1)))
3563   (simplify
3564    (minus (convert (pointer_plus @@0 @1))
3565     (convert @0))
3566    (if (element_precision (type) <= element_precision (TREE_TYPE (@1))
3567         /* For pointer types, if the conversion of A to the
3568            final type requires a sign- or zero-extension,
3569            then we have to punt - it is not defined which
3570            one is correct.  */
3571         || (POINTER_TYPE_P (TREE_TYPE (@0))
3572             && TREE_CODE (@1) == INTEGER_CST
3573             && tree_int_cst_sign_bit (@1) == 0))
3574     (convert @1)))
3575    (simplify
3576     (pointer_diff (pointer_plus @@0 @1) @0)
3577     /* The second argument of pointer_plus must be interpreted as signed, and
3578        thus sign-extended if necessary.  */
3579     (with { tree stype = signed_type_for (TREE_TYPE (@1)); }
3580      /* Use view_convert instead of convert here, as POINTER_PLUS_EXPR
3581         second arg is unsigned even when we need to consider it as signed,
3582         we don't want to diagnose overflow here.  */
3583      (convert (view_convert:stype @1))))
3585   /* (T)P - (T)(P + A) -> -(T) A */
3586   (simplify
3587    (minus (convert? @0)
3588     (convert (plus:c @@0 @1)))
3589    (if (INTEGRAL_TYPE_P (type)
3590         && TYPE_OVERFLOW_UNDEFINED (type)
3591         /* For integer literals, using an intermediate unsigned type to avoid
3592            an overflow at run time is counter-productive because it introduces
3593            spurious overflows at compile time, in the form of TREE_OVERFLOW on
3594            the result, which may be problematic in GENERIC for some front-ends:
3595              (T)P - (T)(P + 4) -> (T)(-(U)4) -> (T)(4294967292) -> -4(OVF)
3596            so we use the direct path for them.  */
3597         && TREE_CODE (@1) != INTEGER_CST
3598         && element_precision (type) <= element_precision (TREE_TYPE (@1)))
3599     (with { tree utype = unsigned_type_for (type); }
3600      (convert (negate (convert:utype @1))))
3601     (if (element_precision (type) <= element_precision (TREE_TYPE (@1))
3602          /* For integer types, if A has a smaller type
3603             than T the result depends on the possible
3604             overflow in P + A.
3605             E.g. T=size_t, A=(unsigned)429497295, P>0.
3606             However, if an overflow in P + A would cause
3607             undefined behavior, we can assume that there
3608             is no overflow.  */
3609          || (INTEGRAL_TYPE_P (TREE_TYPE (@1))
3610              && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (@1))))
3611      (negate (convert @1)))))
3612   (simplify
3613    (minus (convert @0)
3614     (convert (pointer_plus @@0 @1)))
3615    (if (INTEGRAL_TYPE_P (type)
3616         && TYPE_OVERFLOW_UNDEFINED (type)
3617         /* See above the rationale for this condition.  */
3618         && TREE_CODE (@1) != INTEGER_CST
3619         && element_precision (type) <= element_precision (TREE_TYPE (@1)))
3620     (with { tree utype = unsigned_type_for (type); }
3621      (convert (negate (convert:utype @1))))
3622     (if (element_precision (type) <= element_precision (TREE_TYPE (@1))
3623          /* For pointer types, if the conversion of A to the
3624             final type requires a sign- or zero-extension,
3625             then we have to punt - it is not defined which
3626             one is correct.  */
3627          || (POINTER_TYPE_P (TREE_TYPE (@0))
3628              && TREE_CODE (@1) == INTEGER_CST
3629              && tree_int_cst_sign_bit (@1) == 0))
3630      (negate (convert @1)))))
3631    (simplify
3632     (pointer_diff @0 (pointer_plus @@0 @1))
3633     /* The second argument of pointer_plus must be interpreted as signed, and
3634        thus sign-extended if necessary.  */
3635     (with { tree stype = signed_type_for (TREE_TYPE (@1)); }
3636      /* Use view_convert instead of convert here, as POINTER_PLUS_EXPR
3637         second arg is unsigned even when we need to consider it as signed,
3638         we don't want to diagnose overflow here.  */
3639      (negate (convert (view_convert:stype @1)))))
3641   /* (T)(P + A) - (T)(P + B) -> (T)A - (T)B */
3642   (simplify
3643    (minus (convert (plus:c @@0 @1))
3644     (convert (plus:c @0 @2)))
3645    (if (INTEGRAL_TYPE_P (type)
3646         && TYPE_OVERFLOW_UNDEFINED (type)
3647         && element_precision (type) <= element_precision (TREE_TYPE (@1))
3648         && element_precision (type) <= element_precision (TREE_TYPE (@2)))
3649     (with { tree utype = unsigned_type_for (type); }
3650      (convert (minus (convert:utype @1) (convert:utype @2))))
3651     (if (((element_precision (type) <= element_precision (TREE_TYPE (@1)))
3652           == (element_precision (type) <= element_precision (TREE_TYPE (@2))))
3653          && (element_precision (type) <= element_precision (TREE_TYPE (@1))
3654              /* For integer types, if A has a smaller type
3655                 than T the result depends on the possible
3656                 overflow in P + A.
3657                 E.g. T=size_t, A=(unsigned)429497295, P>0.
3658                 However, if an overflow in P + A would cause
3659                 undefined behavior, we can assume that there
3660                 is no overflow.  */
3661              || (INTEGRAL_TYPE_P (TREE_TYPE (@1))
3662                  && INTEGRAL_TYPE_P (TREE_TYPE (@2))
3663                  && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (@1))
3664                  && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (@2)))))
3665      (minus (convert @1) (convert @2)))))
3666   (simplify
3667    (minus (convert (pointer_plus @@0 @1))
3668     (convert (pointer_plus @0 @2)))
3669    (if (INTEGRAL_TYPE_P (type)
3670         && TYPE_OVERFLOW_UNDEFINED (type)
3671         && element_precision (type) <= element_precision (TREE_TYPE (@1)))
3672     (with { tree utype = unsigned_type_for (type); }
3673      (convert (minus (convert:utype @1) (convert:utype @2))))
3674     (if (element_precision (type) <= element_precision (TREE_TYPE (@1))
3675          /* For pointer types, if the conversion of A to the
3676             final type requires a sign- or zero-extension,
3677             then we have to punt - it is not defined which
3678             one is correct.  */
3679          || (POINTER_TYPE_P (TREE_TYPE (@0))
3680              && TREE_CODE (@1) == INTEGER_CST
3681              && tree_int_cst_sign_bit (@1) == 0
3682              && TREE_CODE (@2) == INTEGER_CST
3683              && tree_int_cst_sign_bit (@2) == 0))
3684      (minus (convert @1) (convert @2)))))
3685    (simplify
3686     (pointer_diff (pointer_plus @0 @2) (pointer_plus @1 @2))
3687      (pointer_diff @0 @1))
3688    (simplify
3689     (pointer_diff (pointer_plus @@0 @1) (pointer_plus @0 @2))
3690     /* The second argument of pointer_plus must be interpreted as signed, and
3691        thus sign-extended if necessary.  */
3692     (with { tree stype = signed_type_for (TREE_TYPE (@1)); }
3693      /* Use view_convert instead of convert here, as POINTER_PLUS_EXPR
3694         second arg is unsigned even when we need to consider it as signed,
3695         we don't want to diagnose overflow here.  */
3696      (minus (convert (view_convert:stype @1))
3697             (convert (view_convert:stype @2)))))))
3699 /* (A * C) +- (B * C) -> (A+-B) * C and (A * C) +- A -> A * (C+-1).
3700     Modeled after fold_plusminus_mult_expr.  */
3701 (if (!TYPE_SATURATING (type)
3702      && (!FLOAT_TYPE_P (type) || flag_associative_math))
3703  (for plusminus (plus minus)
3704   (simplify
3705    (plusminus (mult:cs@3 @0 @1) (mult:cs@4 @0 @2))
3706    (if (!ANY_INTEGRAL_TYPE_P (type)
3707         || TYPE_OVERFLOW_WRAPS (type)
3708         || (INTEGRAL_TYPE_P (type)
3709             && tree_expr_nonzero_p (@0)
3710             && expr_not_equal_to (@0, wi::minus_one (TYPE_PRECISION (type)))))
3711     (if (single_use (@3) || single_use (@4))
3712      /* If @1 +- @2 is constant require a hard single-use on either
3713         original operand (but not on both).  */
3714      (mult (plusminus @1 @2) @0)
3715      (mult! (plusminus @1 @2) @0)
3716   )))
3717   /* We cannot generate constant 1 for fract.  */
3718   (if (!ALL_FRACT_MODE_P (TYPE_MODE (type)))
3719    (simplify
3720     (plusminus @0 (mult:c@3 @0 @2))
3721     (if ((!ANY_INTEGRAL_TYPE_P (type)
3722           || TYPE_OVERFLOW_WRAPS (type)
3723           /* For @0 + @0*@2 this transformation would introduce UB
3724              (where there was none before) for @0 in [-1,0] and @2 max.
3725              For @0 - @0*@2 this transformation would introduce UB
3726              for @0 0 and @2 in [min,min+1] or @0 -1 and @2 min+1.  */
3727           || (INTEGRAL_TYPE_P (type)
3728               && ((tree_expr_nonzero_p (@0)
3729                    && expr_not_equal_to (@0,
3730                                 wi::minus_one (TYPE_PRECISION (type))))
3731                   || (plusminus == PLUS_EXPR
3732                       ? expr_not_equal_to (@2,
3733                             wi::max_value (TYPE_PRECISION (type), SIGNED))
3734                       /* Let's ignore the @0 -1 and @2 min case.  */
3735                       : (expr_not_equal_to (@2,
3736                             wi::min_value (TYPE_PRECISION (type), SIGNED))
3737                          && expr_not_equal_to (@2,
3738                                 wi::min_value (TYPE_PRECISION (type), SIGNED)
3739                                 + 1))))))
3740          && single_use (@3))
3741      (mult (plusminus { build_one_cst (type); } @2) @0)))
3742    (simplify
3743     (plusminus (mult:c@3 @0 @2) @0)
3744     (if ((!ANY_INTEGRAL_TYPE_P (type)
3745           || TYPE_OVERFLOW_WRAPS (type)
3746           /* For @0*@2 + @0 this transformation would introduce UB
3747              (where there was none before) for @0 in [-1,0] and @2 max.
3748              For @0*@2 - @0 this transformation would introduce UB
3749              for @0 0 and @2 min.  */
3750           || (INTEGRAL_TYPE_P (type)
3751               && ((tree_expr_nonzero_p (@0)
3752                    && (plusminus == MINUS_EXPR
3753                        || expr_not_equal_to (@0,
3754                                 wi::minus_one (TYPE_PRECISION (type)))))
3755                   || expr_not_equal_to (@2,
3756                         (plusminus == PLUS_EXPR
3757                          ? wi::max_value (TYPE_PRECISION (type), SIGNED)
3758                          : wi::min_value (TYPE_PRECISION (type), SIGNED))))))
3759          && single_use (@3))
3760      (mult (plusminus @2 { build_one_cst (type); }) @0))))))
3762 #if GIMPLE
3763 /* Canonicalize X + (X << C) into X * (1 + (1 << C)) and
3764    (X << C1) + (X << C2) into X * ((1 << C1) + (1 << C2)).  */
3765 (simplify
3766  (plus:c @0 (lshift:s @0 INTEGER_CST@1))
3767   (if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (@0))
3768        && tree_fits_uhwi_p (@1)
3769        && tree_to_uhwi (@1) < element_precision (type)
3770        && (INTEGRAL_TYPE_P (TREE_TYPE (@0))
3771            || optab_handler (smul_optab,
3772                              TYPE_MODE (type)) != CODE_FOR_nothing))
3773    (with { tree t = type;
3774            if (!TYPE_OVERFLOW_WRAPS (t)) t = unsigned_type_for (t);
3775            wide_int w = wi::set_bit_in_zero (tree_to_uhwi (@1),
3776                                              element_precision (type));
3777            w += 1;
3778            tree cst = wide_int_to_tree (VECTOR_TYPE_P (t) ? TREE_TYPE (t)
3779                                         : t, w);
3780            cst = build_uniform_cst (t, cst); }
3781     (convert (mult (convert:t @0) { cst; })))))
3782 (simplify
3783  (plus (lshift:s @0 INTEGER_CST@1) (lshift:s @0 INTEGER_CST@2))
3784   (if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (@0))
3785        && tree_fits_uhwi_p (@1)
3786        && tree_to_uhwi (@1) < element_precision (type)
3787        && tree_fits_uhwi_p (@2)
3788        && tree_to_uhwi (@2) < element_precision (type)
3789        && (INTEGRAL_TYPE_P (TREE_TYPE (@0))
3790            || optab_handler (smul_optab,
3791                              TYPE_MODE (type)) != CODE_FOR_nothing))
3792    (with { tree t = type;
3793            if (!TYPE_OVERFLOW_WRAPS (t)) t = unsigned_type_for (t);
3794            unsigned int prec = element_precision (type);
3795            wide_int w = wi::set_bit_in_zero (tree_to_uhwi (@1), prec);
3796            w += wi::set_bit_in_zero (tree_to_uhwi (@2), prec);
3797            tree cst = wide_int_to_tree (VECTOR_TYPE_P (t) ? TREE_TYPE (t)
3798                                         : t, w);
3799            cst = build_uniform_cst (t, cst); }
3800     (convert (mult (convert:t @0) { cst; })))))
3801 #endif
3803 /* Canonicalize (X*C1)|(X*C2) and (X*C1)^(X*C2) to (C1+C2)*X when
3804    tree_nonzero_bits allows IOR and XOR to be treated like PLUS.
3805    Likewise, handle (X<<C3) and X as legitimate variants of X*C.  */
3806 (for op (bit_ior bit_xor)
3807  (simplify
3808   (op (mult:s@0 @1 INTEGER_CST@2)
3809       (mult:s@3 @1 INTEGER_CST@4))
3810   (if (INTEGRAL_TYPE_P (type) && TYPE_OVERFLOW_WRAPS (type)
3811        && (tree_nonzero_bits (@0) & tree_nonzero_bits (@3)) == 0)
3812    (mult @1
3813          { wide_int_to_tree (type, wi::to_wide (@2) + wi::to_wide (@4)); })))
3814  (simplify
3815   (op:c (mult:s@0 @1 INTEGER_CST@2)
3816         (lshift:s@3 @1 INTEGER_CST@4))
3817   (if (INTEGRAL_TYPE_P (type) && TYPE_OVERFLOW_WRAPS (type)
3818        && tree_int_cst_sgn (@4) > 0
3819        && (tree_nonzero_bits (@0) & tree_nonzero_bits (@3)) == 0)
3820    (with { wide_int wone = wi::one (TYPE_PRECISION (type));
3821            wide_int c = wi::add (wi::to_wide (@2),
3822                                  wi::lshift (wone, wi::to_wide (@4))); }
3823     (mult @1 { wide_int_to_tree (type, c); }))))
3824  (simplify
3825   (op:c (mult:s@0 @1 INTEGER_CST@2)
3826         @1)
3827   (if (INTEGRAL_TYPE_P (type) && TYPE_OVERFLOW_WRAPS (type)
3828        && (tree_nonzero_bits (@0) & tree_nonzero_bits (@1)) == 0)
3829    (mult @1
3830          { wide_int_to_tree (type,
3831                              wi::add (wi::to_wide (@2), 1)); })))
3832  (simplify
3833   (op (lshift:s@0 @1 INTEGER_CST@2)
3834       (lshift:s@3 @1 INTEGER_CST@4))
3835   (if (INTEGRAL_TYPE_P (type)
3836        && tree_int_cst_sgn (@2) > 0
3837        && tree_int_cst_sgn (@4) > 0
3838        && (tree_nonzero_bits (@0) & tree_nonzero_bits (@3)) == 0)
3839    (with { tree t = type;
3840            if (!TYPE_OVERFLOW_WRAPS (t))
3841              t = unsigned_type_for (t);
3842            wide_int wone = wi::one (TYPE_PRECISION (t));
3843            wide_int c = wi::add (wi::lshift (wone, wi::to_wide (@2)),
3844                                  wi::lshift (wone, wi::to_wide (@4))); }
3845     (convert (mult:t (convert:t @1) { wide_int_to_tree (t,c); })))))
3846  (simplify
3847   (op:c (lshift:s@0 @1 INTEGER_CST@2)
3848         @1)
3849   (if (INTEGRAL_TYPE_P (type)
3850        && tree_int_cst_sgn (@2) > 0
3851        && (tree_nonzero_bits (@0) & tree_nonzero_bits (@1)) == 0)
3852    (with { tree t = type;
3853            if (!TYPE_OVERFLOW_WRAPS (t))
3854              t = unsigned_type_for (t);
3855            wide_int wone = wi::one (TYPE_PRECISION (t));
3856            wide_int c = wi::add (wi::lshift (wone, wi::to_wide (@2)), wone); }
3857     (convert (mult:t (convert:t @1) { wide_int_to_tree (t, c); }))))))
3859 /* Simplifications of MIN_EXPR, MAX_EXPR, fmin() and fmax().  */
3861 (for minmax (min max)
3862  (simplify
3863   (minmax @0 @0)
3864   @0)
3865 /* max(max(x,y),x) -> max(x,y)  */
3866  (simplify
3867   (minmax:c (minmax:c@2 @0 @1) @0)
3868   @2))
3869 /* For fmin() and fmax(), skip folding when both are sNaN.  */
3870 (for minmax (FMIN_ALL FMAX_ALL)
3871  (simplify
3872   (minmax @0 @0)
3873   (if (!tree_expr_maybe_signaling_nan_p (@0))
3874     @0)))
3875 /* min(max(x,y),y) -> y.  */
3876 (simplify
3877  (min:c (max:c @0 @1) @1)
3878  @1)
3879 /* max(min(x,y),y) -> y.  */
3880 (simplify
3881  (max:c (min:c @0 @1) @1)
3882  @1)
3883 /* max(a,-a) -> abs(a).  */
3884 (simplify
3885  (max:c @0 (negate @0))
3886  (if (TREE_CODE (type) != COMPLEX_TYPE
3887       && (! ANY_INTEGRAL_TYPE_P (type)
3888           || TYPE_OVERFLOW_UNDEFINED (type)))
3889   (abs @0)))
3890 /* min(a,-a) -> -abs(a).  */
3891 (simplify
3892  (min:c @0 (negate @0))
3893  (if (TREE_CODE (type) != COMPLEX_TYPE
3894       && (! ANY_INTEGRAL_TYPE_P (type)
3895           || TYPE_OVERFLOW_UNDEFINED (type)))
3896   (negate (abs @0))))
3897 (simplify
3898  (min @0 @1)
3899  (switch
3900   (if (INTEGRAL_TYPE_P (type)
3901        && TYPE_MIN_VALUE (type)
3902        && operand_equal_p (@1, TYPE_MIN_VALUE (type), OEP_ONLY_CONST))
3903    @1)
3904   (if (INTEGRAL_TYPE_P (type)
3905        && TYPE_MAX_VALUE (type)
3906        && operand_equal_p (@1, TYPE_MAX_VALUE (type), OEP_ONLY_CONST))
3907    @0)))
3908 (simplify
3909  (max @0 @1)
3910  (switch
3911   (if (INTEGRAL_TYPE_P (type)
3912        && TYPE_MAX_VALUE (type)
3913        && operand_equal_p (@1, TYPE_MAX_VALUE (type), OEP_ONLY_CONST))
3914    @1)
3915   (if (INTEGRAL_TYPE_P (type)
3916        && TYPE_MIN_VALUE (type)
3917        && operand_equal_p (@1, TYPE_MIN_VALUE (type), OEP_ONLY_CONST))
3918    @0)))
3920 /* max (a, a + CST) -> a + CST where CST is positive.  */
3921 /* max (a, a + CST) -> a where CST is negative.  */
3922 (simplify
3923  (max:c @0 (plus@2 @0 INTEGER_CST@1))
3924   (if (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (@0)))
3925    (if (tree_int_cst_sgn (@1) > 0)
3926     @2
3927     @0)))
3929 /* min (a, a + CST) -> a where CST is positive.  */
3930 /* min (a, a + CST) -> a + CST where CST is negative. */
3931 (simplify
3932  (min:c @0 (plus@2 @0 INTEGER_CST@1))
3933   (if (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (@0)))
3934    (if (tree_int_cst_sgn (@1) > 0)
3935     @0
3936     @2)))
3938 /* Simplify min (&var[off0], &var[off1]) etc. depending on whether
3939    the addresses are known to be less, equal or greater.  */
3940 (for minmax (min max)
3941      cmp (lt gt)
3942  (simplify
3943   (minmax (convert1?@2 addr@0) (convert2?@3 addr@1))
3944   (with
3945    {
3946      poly_int64 off0, off1;
3947      tree base0, base1;
3948      int equal = address_compare (cmp, TREE_TYPE (@2), @0, @1, base0, base1,
3949                                   off0, off1, GENERIC);
3950    }
3951    (if (equal == 1)
3952     (if (minmax == MIN_EXPR)
3953      (if (known_le (off0, off1))
3954       @2
3955       (if (known_gt (off0, off1))
3956        @3))
3957      (if (known_ge (off0, off1))
3958       @2
3959       (if (known_lt (off0, off1))
3960        @3)))))))
3962 /* (convert (minmax ((convert (x) c)))) -> minmax (x c) if x is promoted
3963    and the outer convert demotes the expression back to x's type.  */
3964 (for minmax (min max)
3965  (simplify
3966   (convert (minmax@0 (convert @1) INTEGER_CST@2))
3967   (if (INTEGRAL_TYPE_P (type)
3968        && types_match (@1, type) && int_fits_type_p (@2, type)
3969        && TYPE_SIGN (TREE_TYPE (@0)) == TYPE_SIGN (type)
3970        && TYPE_PRECISION (TREE_TYPE (@0)) > TYPE_PRECISION (type))
3971    (minmax @1 (convert @2)))))
3973 (for minmax (FMIN_ALL FMAX_ALL)
3974  /* If either argument is NaN and other one is not sNaN, return the other
3975     one.  Avoid the transformation if we get (and honor) a signalling NaN.  */
3976  (simplify
3977   (minmax:c @0 REAL_CST@1)
3978    (if (real_isnan (TREE_REAL_CST_PTR (@1))
3979        && (!HONOR_SNANS (@1) || !TREE_REAL_CST (@1).signalling)
3980        && !tree_expr_maybe_signaling_nan_p (@0))
3981    @0)))
3982 /* Convert fmin/fmax to MIN_EXPR/MAX_EXPR.  C99 requires these
3983    functions to return the numeric arg if the other one is NaN.
3984    MIN and MAX don't honor that, so only transform if -ffinite-math-only
3985    is set.  C99 doesn't require -0.0 to be handled, so we don't have to
3986    worry about it either.  */
3987 (if (flag_finite_math_only)
3988  (simplify
3989   (FMIN_ALL @0 @1)
3990   (min @0 @1))
3991  (simplify
3992   (FMAX_ALL @0 @1)
3993   (max @0 @1)))
3994 /* min (-A, -B) -> -max (A, B)  */
3995 (for minmax (min max FMIN_ALL FMAX_ALL)
3996      maxmin (max min FMAX_ALL FMIN_ALL)
3997  (simplify
3998   (minmax (negate:s@2 @0) (negate:s@3 @1))
3999   (if (FLOAT_TYPE_P (TREE_TYPE (@0))
4000        || (ANY_INTEGRAL_TYPE_P (TREE_TYPE (@0))
4001            && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (@0))))
4002    (negate (maxmin @0 @1)))))
4003 /* MIN (~X, ~Y) -> ~MAX (X, Y)
4004    MAX (~X, ~Y) -> ~MIN (X, Y)  */
4005 (for minmax (min max)
4006  maxmin (max min)
4007  (simplify
4008   (minmax (bit_not:s@2 @0) (bit_not:s@3 @1))
4009   (bit_not (maxmin @0 @1)))
4010 /* ~MAX(~X, Y) --> MIN(X, ~Y) */
4011 /* ~MIN(~X, Y) --> MAX(X, ~Y) */
4012  (simplify
4013   (bit_not (minmax:cs (bit_not @0) @1))
4014   (maxmin @0 (bit_not @1))))
4016 /* MIN (X, Y) == X -> X <= Y  */
4017 /* MIN (X, Y) < X -> X > Y  */
4018 /* MIN (X, Y) >= X -> X <= Y  */
4019 (for minmax (min min min min max max max max)
4020      cmp    (eq  ne  lt  ge  eq  ne  gt  le )
4021      out    (le  gt  gt  le  ge  lt  lt  ge )
4022  (simplify
4023   (cmp:c (minmax:c @0 @1) @0)
4024   (if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (@0)))
4025    (out @0 @1))))
4026 /* MIN (X, 5) == 0 -> X == 0
4027    MIN (X, 5) == 7 -> false  */
4028 (for cmp (eq ne)
4029  (simplify
4030   (cmp (min @0 INTEGER_CST@1) INTEGER_CST@2)
4031   (if (wi::lt_p (wi::to_wide (@1), wi::to_wide (@2),
4032                  TYPE_SIGN (TREE_TYPE (@0))))
4033    { constant_boolean_node (cmp == NE_EXPR, type); }
4034    (if (wi::gt_p (wi::to_wide (@1), wi::to_wide (@2),
4035                   TYPE_SIGN (TREE_TYPE (@0))))
4036     (cmp @0 @2)))))
4037 (for cmp (eq ne)
4038  (simplify
4039   (cmp (max @0 INTEGER_CST@1) INTEGER_CST@2)
4040   (if (wi::gt_p (wi::to_wide (@1), wi::to_wide (@2),
4041                  TYPE_SIGN (TREE_TYPE (@0))))
4042    { constant_boolean_node (cmp == NE_EXPR, type); }
4043    (if (wi::lt_p (wi::to_wide (@1), wi::to_wide (@2),
4044                   TYPE_SIGN (TREE_TYPE (@0))))
4045     (cmp @0 @2)))))
4047 /* X <= MAX(X, Y) -> true
4048    X > MAX(X, Y) -> false 
4049    X >= MIN(X, Y) -> true
4050    X < MIN(X, Y) -> false */
4051 (for minmax (min     min     max     max     )
4052      cmp    (ge      lt      le      gt      )
4053  (simplify
4054   (cmp:c @0 (minmax:c @0 @1))
4055   { constant_boolean_node (cmp == GE_EXPR || cmp == LE_EXPR, type); } ))
4057 /* MIN (X, C1) < C2 -> X < C2 || C1 < C2  */
4058 (for minmax (min     min     max     max     min     min     max     max    )
4059      cmp    (lt      le      gt      ge      gt      ge      lt      le     )
4060      comb   (bit_ior bit_ior bit_ior bit_ior bit_and bit_and bit_and bit_and)
4061  (simplify
4062   (cmp (minmax @0 INTEGER_CST@1) INTEGER_CST@2)
4063   (comb (cmp @0 @2) (cmp @1 @2))))
4065 /* Undo fancy ways of writing max/min or other ?: expressions, like
4066    a - ((a - b) & -(a < b))  and  a - (a - b) * (a < b) into (a < b) ? b : a.
4067    People normally use ?: and that is what we actually try to optimize.  */
4068 /* Transform A + (B-A)*cmp into cmp ? B : A.  */
4069 (simplify
4070  (plus:c @0 (mult:c (minus @1 @0) zero_one_valued_p@2))
4071  (if (INTEGRAL_TYPE_P (type)
4072       && (GIMPLE || !TREE_SIDE_EFFECTS (@1)))
4073   (cond (convert:boolean_type_node @2) @1 @0)))
4074 /* Transform A - (A-B)*cmp into cmp ? B : A.  */
4075 (simplify
4076  (minus @0 (mult:c (minus @0 @1) zero_one_valued_p@2))
4077  (if (INTEGRAL_TYPE_P (type)
4078       && (GIMPLE || !TREE_SIDE_EFFECTS (@1)))
4079   (cond (convert:boolean_type_node @2) @1 @0)))
4080 /* Transform A ^ (A^B)*cmp into cmp ? B : A.  */
4081 (simplify
4082  (bit_xor:c @0 (mult:c (bit_xor:c @0 @1) zero_one_valued_p@2))
4083  (if (INTEGRAL_TYPE_P (type)
4084       && (GIMPLE || !TREE_SIDE_EFFECTS (@1)))
4085   (cond (convert:boolean_type_node @2) @1 @0)))
4087 /* (x <= 0 ? -x : 0) -> max(-x, 0).  */
4088 (simplify
4089   (cond (le @0 integer_zerop@1) (negate@2 @0) integer_zerop@1)
4090   (max @2 @1))
4092 /* (zero_one == 0) ? y : z <op> y -> ((typeof(y))zero_one * z) <op> y */
4093 (for op (bit_xor bit_ior plus)
4094  (simplify
4095   (cond (eq zero_one_valued_p@0
4096             integer_zerop)
4097         @1
4098         (op:c @2 @1))
4099   (if (INTEGRAL_TYPE_P (type)
4100        && TYPE_PRECISION (type) > 1
4101        && (INTEGRAL_TYPE_P (TREE_TYPE (@0))))
4102        (op (mult (convert:type @0) @2) @1))))
4104 /* (zero_one != 0) ? z <op> y : y -> ((typeof(y))zero_one * z) <op> y */
4105 (for op (bit_xor bit_ior plus)
4106  (simplify
4107   (cond (ne zero_one_valued_p@0
4108             integer_zerop)
4109        (op:c @2 @1)
4110         @1)
4111   (if (INTEGRAL_TYPE_P (type)
4112        && TYPE_PRECISION (type) > 1
4113        && (INTEGRAL_TYPE_P (TREE_TYPE (@0))))
4114        (op (mult (convert:type @0) @2) @1))))
4116 /* Simplifications of shift and rotates.  */
4118 (for rotate (lrotate rrotate)
4119  (simplify
4120   (rotate integer_all_onesp@0 @1)
4121   @0))
4123 /* Optimize -1 >> x for arithmetic right shifts.  */
4124 (simplify
4125  (rshift integer_all_onesp@0 @1)
4126  (if (!TYPE_UNSIGNED (type))
4127   @0))
4129 /* Optimize (x >> c) << c into x & (-1<<c).  */
4130 (simplify
4131  (lshift (nop_convert? (rshift @0 INTEGER_CST@1)) @1)
4132  (if (wi::ltu_p (wi::to_wide (@1), element_precision (type)))
4133   /* It doesn't matter if the right shift is arithmetic or logical.  */
4134   (bit_and (view_convert @0) (lshift { build_minus_one_cst (type); } @1))))
4136 (simplify
4137  (lshift (convert (convert@2 (rshift @0 INTEGER_CST@1))) @1)
4138  (if (wi::ltu_p (wi::to_wide (@1), element_precision (type))
4139       /* Allow intermediate conversion to integral type with whatever sign, as
4140          long as the low TYPE_PRECISION (type)
4141          - TYPE_PRECISION (TREE_TYPE (@2)) bits are preserved.  */
4142       && INTEGRAL_TYPE_P (type)
4143       && INTEGRAL_TYPE_P (TREE_TYPE (@2))
4144       && INTEGRAL_TYPE_P (TREE_TYPE (@0))
4145       && TYPE_PRECISION (type) == TYPE_PRECISION (TREE_TYPE (@0))
4146       && (TYPE_PRECISION (TREE_TYPE (@2)) >= TYPE_PRECISION (type)
4147           || wi::geu_p (wi::to_wide (@1),
4148                         TYPE_PRECISION (type)
4149                         - TYPE_PRECISION (TREE_TYPE (@2)))))
4150   (bit_and (convert @0) (lshift { build_minus_one_cst (type); } @1))))
4152 /* For (x << c) >> c, optimize into x & ((unsigned)-1 >> c) for
4153    unsigned x OR truncate into the precision(type) - c lowest bits
4154    of signed x (if they have mode precision or a precision of 1).  */
4155 (simplify
4156  (rshift (nop_convert? (lshift @0 INTEGER_CST@1)) @@1)
4157  (if (wi::ltu_p (wi::to_wide (@1), element_precision (type)))
4158   (if (TYPE_UNSIGNED (type))
4159    (bit_and (convert @0) (rshift { build_minus_one_cst (type); } @1))
4160    (if (INTEGRAL_TYPE_P (type))
4161     (with {
4162       int width = element_precision (type) - tree_to_uhwi (@1);
4163       tree stype = NULL_TREE;
4164       if (width <= MAX_FIXED_MODE_SIZE)
4165         stype = build_nonstandard_integer_type (width, 0);
4166      }
4167      (if (stype && (width == 1 || type_has_mode_precision_p (stype)))
4168       (convert (convert:stype @0))))))))
4170 /* Optimize x >> x into 0 */
4171 (simplify
4172  (rshift @0 @0)
4173   { build_zero_cst (type); })
4175 (for shiftrotate (lrotate rrotate lshift rshift)
4176  (simplify
4177   (shiftrotate @0 integer_zerop)
4178   (non_lvalue @0))
4179  (simplify
4180   (shiftrotate integer_zerop@0 @1)
4181   @0)
4182  /* Prefer vector1 << scalar to vector1 << vector2
4183     if vector2 is uniform.  */
4184  (for vec (VECTOR_CST CONSTRUCTOR)
4185   (simplify
4186    (shiftrotate @0 vec@1)
4187    (with { tree tem = uniform_vector_p (@1); }
4188     (if (tem)
4189      (shiftrotate @0 { tem; }))))))
4191 /* Simplify X << Y where Y's low width bits are 0 to X, as only valid
4192    Y is 0.  Similarly for X >> Y.  */
4193 #if GIMPLE
4194 (for shift (lshift rshift)
4195  (simplify
4196   (shift @0 SSA_NAME@1)
4197    (if (INTEGRAL_TYPE_P (TREE_TYPE (@1)))
4198     (with {
4199       int width = ceil_log2 (element_precision (TREE_TYPE (@0)));
4200       int prec = TYPE_PRECISION (TREE_TYPE (@1));
4201      }
4202      (if ((get_nonzero_bits (@1) & wi::mask (width, false, prec)) == 0)
4203       @0)))))
4204 #endif
4206 /* Rewrite an LROTATE_EXPR by a constant into an
4207    RROTATE_EXPR by a new constant.  */
4208 (simplify
4209  (lrotate @0 INTEGER_CST@1)
4210  (rrotate @0 { const_binop (MINUS_EXPR, TREE_TYPE (@1),
4211                             build_int_cst (TREE_TYPE (@1),
4212                                            element_precision (type)), @1); }))
4214 /* Turn (a OP c1) OP c2 into a OP (c1+c2).  */
4215 (for op (lrotate rrotate rshift lshift)
4216  (simplify
4217   (op (op @0 INTEGER_CST@1) INTEGER_CST@2)
4218   (with { unsigned int prec = element_precision (type); }
4219    (if (wi::ge_p (wi::to_wide (@1), 0, TYPE_SIGN (TREE_TYPE (@1)))
4220         && wi::lt_p (wi::to_wide (@1), prec, TYPE_SIGN (TREE_TYPE (@1)))
4221         && wi::ge_p (wi::to_wide (@2), 0, TYPE_SIGN (TREE_TYPE (@2)))
4222         && wi::lt_p (wi::to_wide (@2), prec, TYPE_SIGN (TREE_TYPE (@2))))
4223     (with { unsigned int low = (tree_to_uhwi (@1)
4224                                 + tree_to_uhwi (@2)); }
4225      /* Deal with a OP (c1 + c2) being undefined but (a OP c1) OP c2
4226         being well defined.  */
4227      (if (low >= prec)
4228       (if (op == LROTATE_EXPR || op == RROTATE_EXPR)
4229        (op @0 { build_int_cst (TREE_TYPE (@1), low % prec); })
4230        (if (TYPE_UNSIGNED (type) || op == LSHIFT_EXPR)
4231         { build_zero_cst (type); }
4232         (op @0 { build_int_cst (TREE_TYPE (@1), prec - 1); })))
4233       (op @0 { build_int_cst (TREE_TYPE (@1), low); })))))))
4236 /* Simplify (CST << x) & 1 to 0 if CST is even or to x == 0 if it is odd.  */
4237 (simplify
4238  (bit_and (lshift INTEGER_CST@1 @0) integer_onep)
4239   (if ((wi::to_wide (@1) & 1) != 0)
4240    (convert (eq:boolean_type_node @0 { build_zero_cst (TREE_TYPE (@0)); }))
4241    { build_zero_cst (type); }))
4243 /* Simplify ((C << x) & D) != 0 where C and D are power of two constants,
4244    either to false if D is smaller (unsigned comparison) than C, or to
4245    x == log2 (D) - log2 (C).  Similarly for right shifts.
4246    Note for `(1 >> x)`, the & 1 has been removed so matching that seperately. */
4247 (for cmp (ne eq)
4248      icmp (eq ne)
4249  (simplify
4250   (cmp (bit_and (lshift integer_pow2p@1 @0) integer_pow2p@2) integer_zerop)
4251    (with { int c1 = wi::clz (wi::to_wide (@1));
4252            int c2 = wi::clz (wi::to_wide (@2)); }
4253     (if (c1 < c2)
4254      { constant_boolean_node (cmp == NE_EXPR ? false : true, type); }
4255      (icmp @0 { build_int_cst (TREE_TYPE (@0), c1 - c2); }))))
4256  (simplify
4257   (cmp (bit_and (rshift integer_pow2p@1 @0) integer_pow2p@2) integer_zerop)
4258    (if (tree_int_cst_sgn (@1) > 0)
4259     (with { int c1 = wi::clz (wi::to_wide (@1));
4260             int c2 = wi::clz (wi::to_wide (@2)); }
4261      (if (c1 > c2)
4262       { constant_boolean_node (cmp == NE_EXPR ? false : true, type); }
4263       (icmp @0 { build_int_cst (TREE_TYPE (@0), c2 - c1); })))))
4264  /* `(1 >> X) != 0` -> `X == 0` */
4265  /* `(1 >> X) == 0` -> `X != 0` */
4266  (simplify
4267   (cmp (rshift integer_onep@1 @0) integer_zerop)
4268    (if (INTEGRAL_TYPE_P (TREE_TYPE (@1)))
4269     (icmp @0 { build_zero_cst (TREE_TYPE (@0)); }))))
4271 /* (CST1 << A) == CST2 -> A == ctz (CST2) - ctz (CST1)
4272    (CST1 << A) != CST2 -> A != ctz (CST2) - ctz (CST1)
4273    if CST2 != 0.  */
4274 (for cmp (ne eq)
4275  (simplify
4276   (cmp (lshift INTEGER_CST@0 @1) INTEGER_CST@2)
4277   (with { int cand = wi::ctz (wi::to_wide (@2)) - wi::ctz (wi::to_wide (@0)); }
4278    (if (cand < 0
4279         || (!integer_zerop (@2)
4280             && wi::lshift (wi::to_wide (@0), cand) != wi::to_wide (@2)))
4281     { constant_boolean_node (cmp == NE_EXPR, type); }
4282     (if (!integer_zerop (@2)
4283          && wi::lshift (wi::to_wide (@0), cand) == wi::to_wide (@2))
4284      (cmp @1 { build_int_cst (TREE_TYPE (@1), cand); }))))))
4286 /* Fold ((X << C1) & C2) cmp C3 into (X & (C2 >> C1)) cmp (C3 >> C1)
4287         ((X >> C1) & C2) cmp C3 into (X & (C2 << C1)) cmp (C3 << C1).  */
4288 (for cmp (ne eq)
4289  (simplify
4290   (cmp (bit_and:s (lshift:s @0 INTEGER_CST@1) INTEGER_CST@2) INTEGER_CST@3)
4291   (if (tree_fits_shwi_p (@1)
4292        && tree_to_shwi (@1) > 0
4293        && tree_to_shwi (@1) < TYPE_PRECISION (TREE_TYPE (@0)))
4294     (if (tree_to_shwi (@1) > wi::ctz (wi::to_wide (@3)))
4295       { constant_boolean_node (cmp == NE_EXPR, type); }
4296       (with { wide_int c1 = wi::to_wide (@1);
4297               wide_int c2 = wi::lrshift (wi::to_wide (@2), c1);
4298               wide_int c3 = wi::lrshift (wi::to_wide (@3), c1); }
4299         (cmp (bit_and @0 { wide_int_to_tree (TREE_TYPE (@0), c2); })
4300              { wide_int_to_tree (TREE_TYPE (@0), c3); })))))
4301  (simplify
4302   (cmp (bit_and:s (rshift:s @0 INTEGER_CST@1) INTEGER_CST@2) INTEGER_CST@3)
4303   (if (tree_fits_shwi_p (@1)
4304        && tree_to_shwi (@1) > 0
4305        && tree_to_shwi (@1) < TYPE_PRECISION (TREE_TYPE (@0)))
4306     (with { tree t0 = TREE_TYPE (@0);
4307             unsigned int prec = TYPE_PRECISION (t0);
4308             wide_int c1 = wi::to_wide (@1);
4309             wide_int c2 = wi::to_wide (@2);
4310             wide_int c3 = wi::to_wide (@3);
4311             wide_int sb = wi::set_bit_in_zero (prec - 1, prec); }
4312       (if ((c2 & c3) != c3)
4313         { constant_boolean_node (cmp == NE_EXPR, type); }
4314         (if (TYPE_UNSIGNED (t0))
4315           (if ((c3 & wi::arshift (sb, c1 - 1)) != 0)
4316             { constant_boolean_node (cmp == NE_EXPR, type); }
4317             (cmp (bit_and @0 { wide_int_to_tree (t0, c2 << c1); })
4318                  { wide_int_to_tree (t0, c3 << c1); }))
4319           (with { wide_int smask = wi::arshift (sb, c1); }
4320             (switch
4321               (if ((c2 & smask) == 0)
4322                 (cmp (bit_and @0 { wide_int_to_tree (t0, c2 << c1); })
4323                      { wide_int_to_tree (t0, c3 << c1); }))
4324               (if ((c3 & smask) == 0)
4325                 (cmp (bit_and @0 { wide_int_to_tree (t0, (c2 << c1) | sb); })
4326                      { wide_int_to_tree (t0, c3 << c1); }))
4327               (if ((c2 & smask) != (c3 & smask))
4328                 { constant_boolean_node (cmp == NE_EXPR, type); })
4329               (cmp (bit_and @0 { wide_int_to_tree (t0, (c2 << c1) | sb); })
4330                    { wide_int_to_tree (t0, (c3 << c1) | sb); })))))))))
4332 /* Fold (X << C1) & C2 into (X << C1) & (C2 | ((1 << C1) - 1))
4333         (X >> C1) & C2 into (X >> C1) & (C2 | ~((type) -1 >> C1))
4334    if the new mask might be further optimized.  */
4335 (for shift (lshift rshift)
4336  (simplify
4337   (bit_and (convert?:s@4 (shift:s@5 (convert1?@3 @0) INTEGER_CST@1))
4338            INTEGER_CST@2)
4339    (if (tree_nop_conversion_p (TREE_TYPE (@4), TREE_TYPE (@5))
4340         && TYPE_PRECISION (type) <= HOST_BITS_PER_WIDE_INT
4341         && tree_fits_uhwi_p (@1)
4342         && tree_to_uhwi (@1) > 0
4343         && tree_to_uhwi (@1) < TYPE_PRECISION (type))
4344     (with
4345      {
4346        unsigned int shiftc = tree_to_uhwi (@1);
4347        unsigned HOST_WIDE_INT mask = TREE_INT_CST_LOW (@2);
4348        unsigned HOST_WIDE_INT newmask, zerobits = 0;
4349        tree shift_type = TREE_TYPE (@3);
4350        unsigned int prec;
4352        if (shift == LSHIFT_EXPR)
4353          zerobits = ((HOST_WIDE_INT_1U << shiftc) - 1);
4354        else if (shift == RSHIFT_EXPR
4355                 && type_has_mode_precision_p (shift_type))
4356          {
4357            prec = TYPE_PRECISION (TREE_TYPE (@3));
4358            tree arg00 = @0;
4359            /* See if more bits can be proven as zero because of
4360               zero extension.  */
4361            if (@3 != @0
4362                && TYPE_UNSIGNED (TREE_TYPE (@0)))
4363              {
4364                tree inner_type = TREE_TYPE (@0);
4365                if (type_has_mode_precision_p (inner_type)
4366                    && TYPE_PRECISION (inner_type) < prec)
4367                  {
4368                    prec = TYPE_PRECISION (inner_type);
4369                    /* See if we can shorten the right shift.  */
4370                    if (shiftc < prec)
4371                      shift_type = inner_type;
4372                    /* Otherwise X >> C1 is all zeros, so we'll optimize
4373                       it into (X, 0) later on by making sure zerobits
4374                       is all ones.  */
4375                  }
4376              }
4377            zerobits = HOST_WIDE_INT_M1U;
4378            if (shiftc < prec)
4379              {
4380                zerobits >>= HOST_BITS_PER_WIDE_INT - shiftc;
4381                zerobits <<= prec - shiftc;
4382              }
4383            /* For arithmetic shift if sign bit could be set, zerobits
4384               can contain actually sign bits, so no transformation is
4385               possible, unless MASK masks them all away.  In that
4386               case the shift needs to be converted into logical shift.  */
4387            if (!TYPE_UNSIGNED (TREE_TYPE (@3))
4388                && prec == TYPE_PRECISION (TREE_TYPE (@3)))
4389              {
4390                if ((mask & zerobits) == 0)
4391                  shift_type = unsigned_type_for (TREE_TYPE (@3));
4392                else
4393                  zerobits = 0;
4394              }
4395          }
4396      }
4397      /* ((X << 16) & 0xff00) is (X, 0).  */
4398      (if ((mask & zerobits) == mask)
4399       { build_int_cst (type, 0); }
4400       (with { newmask = mask | zerobits; }
4401        (if (newmask != mask && (newmask & (newmask + 1)) == 0)
4402         (with
4403          {
4404            /* Only do the transformation if NEWMASK is some integer
4405               mode's mask.  */
4406            for (prec = BITS_PER_UNIT;
4407                 prec < HOST_BITS_PER_WIDE_INT; prec <<= 1)
4408              if (newmask == (HOST_WIDE_INT_1U << prec) - 1)
4409                break;
4410          }
4411          (if (prec < HOST_BITS_PER_WIDE_INT
4412               || newmask == HOST_WIDE_INT_M1U)
4413           (with
4414            { tree newmaskt = build_int_cst_type (TREE_TYPE (@2), newmask); }
4415            (if (!tree_int_cst_equal (newmaskt, @2))
4416             (if (shift_type != TREE_TYPE (@3))
4417              (bit_and (convert (shift:shift_type (convert @3) @1)) { newmaskt; })
4418              (bit_and @4 { newmaskt; })))))))))))))
4420 /* ((1 << n) & M) != 0  -> n == log2 (M) */
4421 (for cmp (ne eq)
4422        icmp (eq ne)
4423  (simplify
4424   (cmp
4425    (bit_and
4426     (nop_convert? (lshift integer_onep @0)) integer_pow2p@1) integer_zerop)
4427   (if (INTEGRAL_TYPE_P (TREE_TYPE (@0)))
4428    (icmp @0 { wide_int_to_tree (TREE_TYPE (@0),
4429                                 wi::exact_log2 (wi::to_wide (@1))); }))))
4431 /* Fold (X {&,^,|} C2) << C1 into (X << C1) {&,^,|} (C2 << C1)
4432    (X {&,^,|} C2) >> C1 into (X >> C1) & (C2 >> C1).  */
4433 (for shift (lshift rshift)
4434  (for bit_op (bit_and bit_xor bit_ior)
4435   (simplify
4436    (shift (convert?:s (bit_op:s @0 INTEGER_CST@2)) INTEGER_CST@1)
4437    (if (tree_nop_conversion_p (type, TREE_TYPE (@0)))
4438     (with { tree mask = int_const_binop (shift, fold_convert (type, @2), @1); }
4439      (if (mask)
4440       (bit_op (shift (convert @0) @1) { mask; })))))))
4442 /* ~(~X >> Y) -> X >> Y (for arithmetic shift).  */
4443 (simplify
4444  (bit_not (convert1?:s (rshift:s (convert2?@0 (bit_not @1)) @2)))
4445   (if (!TYPE_UNSIGNED (TREE_TYPE (@0))
4446        && (element_precision (TREE_TYPE (@0))
4447            <= element_precision (TREE_TYPE (@1))
4448            || !TYPE_UNSIGNED (TREE_TYPE (@1))))
4449    (with
4450     { tree shift_type = TREE_TYPE (@0); }
4451      (convert (rshift (convert:shift_type @1) @2)))))
4453 /* ~(~X >>r Y) -> X >>r Y
4454    ~(~X <<r Y) -> X <<r Y */
4455 (for rotate (lrotate rrotate)
4456  (simplify
4457   (bit_not (convert1?:s (rotate:s (convert2?@0 (bit_not @1)) @2)))
4458    (if ((element_precision (TREE_TYPE (@0))
4459          <= element_precision (TREE_TYPE (@1))
4460          || !TYPE_UNSIGNED (TREE_TYPE (@1)))
4461         && (element_precision (type) <= element_precision (TREE_TYPE (@0))
4462             || !TYPE_UNSIGNED (TREE_TYPE (@0))))
4463     (with
4464      { tree rotate_type = TREE_TYPE (@0); }
4465       (convert (rotate (convert:rotate_type @1) @2))))))
4467 (for cmp (eq ne)
4468  (for rotate (lrotate rrotate)
4469       invrot (rrotate lrotate)
4470   /* (X >>r Y) cmp (Z >>r Y) may simplify to X cmp Y. */
4471   (simplify
4472    (cmp (rotate @1 @0) (rotate @2 @0))
4473    (cmp @1 @2))
4474   /* (X >>r C1) cmp C2 may simplify to X cmp C3. */
4475   (simplify
4476    (cmp (rotate @0 INTEGER_CST@1) INTEGER_CST@2)
4477    (cmp @0 { const_binop (invrot, TREE_TYPE (@0), @2, @1); }))
4478   /* (X >>r Y) cmp C where C is 0 or ~0, may simplify to X cmp C.  */
4479   (simplify
4480    (cmp (rotate @0 @1) INTEGER_CST@2)
4481     (if (integer_zerop (@2) || integer_all_onesp (@2))
4482      (cmp @0 @2)))))
4484 /* Narrow a lshift by constant.  */
4485 (simplify
4486  (convert (lshift:s@0 @1 INTEGER_CST@2))
4487  (if (INTEGRAL_TYPE_P (type)
4488       && INTEGRAL_TYPE_P (TREE_TYPE (@0))
4489       && !integer_zerop (@2)
4490       && TYPE_PRECISION (type) <= TYPE_PRECISION (TREE_TYPE (@0)))
4491   (if (TYPE_PRECISION (type) == TYPE_PRECISION (TREE_TYPE (@0))
4492        || wi::ltu_p (wi::to_wide (@2), TYPE_PRECISION (type)))
4493    (lshift (convert @1) @2)
4494    (if (wi::ltu_p (wi::to_wide (@2), TYPE_PRECISION (TREE_TYPE (@0))))
4495     { build_zero_cst (type); }))))
4497 /* Simplifications of conversions.  */
4499 /* Basic strip-useless-type-conversions / strip_nops.  */
4500 (for cvt (convert view_convert float fix_trunc)
4501  (simplify
4502   (cvt @0)
4503   (if ((GIMPLE && useless_type_conversion_p (type, TREE_TYPE (@0)))
4504        || (GENERIC && type == TREE_TYPE (@0)))
4505    @0)))
4507 /* Contract view-conversions.  */
4508 (simplify
4509   (view_convert (view_convert @0))
4510   (view_convert @0))
4512 /* For integral conversions with the same precision or pointer
4513    conversions use a NOP_EXPR instead.  */
4514 (simplify
4515   (view_convert @0)
4516   (if ((INTEGRAL_TYPE_P (type) || POINTER_TYPE_P (type))
4517        && (INTEGRAL_TYPE_P (TREE_TYPE (@0)) || POINTER_TYPE_P (TREE_TYPE (@0)))
4518        && TYPE_PRECISION (type) == TYPE_PRECISION (TREE_TYPE (@0)))
4519    (convert @0)))
4521 /* Strip inner integral conversions that do not change precision or size, or
4522    zero-extend while keeping the same size (for bool-to-char).  */
4523 (simplify
4524   (view_convert (convert@0 @1))
4525   (if ((INTEGRAL_TYPE_P (TREE_TYPE (@0)) || POINTER_TYPE_P (TREE_TYPE (@0)))
4526        && (INTEGRAL_TYPE_P (TREE_TYPE (@1)) || POINTER_TYPE_P (TREE_TYPE (@1)))
4527        && TYPE_SIZE (TREE_TYPE (@0)) == TYPE_SIZE (TREE_TYPE (@1))
4528        && (TYPE_PRECISION (TREE_TYPE (@0)) == TYPE_PRECISION (TREE_TYPE (@1))
4529            || (TYPE_PRECISION (TREE_TYPE (@0)) > TYPE_PRECISION (TREE_TYPE (@1))
4530                && TYPE_UNSIGNED (TREE_TYPE (@1)))))
4531    (view_convert @1)))
4533 /* Simplify a view-converted empty or single-element constructor.  */
4534 (simplify
4535   (view_convert CONSTRUCTOR@0)
4536   (with
4537    { tree ctor = (TREE_CODE (@0) == SSA_NAME
4538                   ? gimple_assign_rhs1 (SSA_NAME_DEF_STMT (@0)) : @0); }
4539    (switch
4540     (if (CONSTRUCTOR_NELTS (ctor) == 0)
4541      { build_zero_cst (type); })
4542     (if (CONSTRUCTOR_NELTS (ctor) == 1
4543          && VECTOR_TYPE_P (TREE_TYPE (ctor))
4544          && operand_equal_p (TYPE_SIZE (type),
4545                              TYPE_SIZE (TREE_TYPE
4546                                (CONSTRUCTOR_ELT (ctor, 0)->value))))
4547      (view_convert { CONSTRUCTOR_ELT (ctor, 0)->value; })))))
4549 /* Re-association barriers around constants and other re-association
4550    barriers can be removed.  */
4551 (simplify
4552  (paren CONSTANT_CLASS_P@0)
4553  @0)
4554 (simplify
4555  (paren (paren@1 @0))
4556  @1)
4558 /* Handle cases of two conversions in a row.  */
4559 (for ocvt (convert float fix_trunc)
4560  (for icvt (convert float)
4561   (simplify
4562    (ocvt (icvt@1 @0))
4563    (with
4564     {
4565       tree inside_type = TREE_TYPE (@0);
4566       tree inter_type = TREE_TYPE (@1);
4567       int inside_int = INTEGRAL_TYPE_P (inside_type);
4568       int inside_ptr = POINTER_TYPE_P (inside_type);
4569       int inside_float = FLOAT_TYPE_P (inside_type);
4570       int inside_vec = VECTOR_TYPE_P (inside_type);
4571       unsigned int inside_prec = element_precision (inside_type);
4572       int inside_unsignedp = TYPE_UNSIGNED (inside_type);
4573       int inter_int = INTEGRAL_TYPE_P (inter_type);
4574       int inter_ptr = POINTER_TYPE_P (inter_type);
4575       int inter_float = FLOAT_TYPE_P (inter_type);
4576       int inter_vec = VECTOR_TYPE_P (inter_type);
4577       unsigned int inter_prec = element_precision (inter_type);
4578       int inter_unsignedp = TYPE_UNSIGNED (inter_type);
4579       int final_int = INTEGRAL_TYPE_P (type);
4580       int final_ptr = POINTER_TYPE_P (type);
4581       int final_float = FLOAT_TYPE_P (type);
4582       int final_vec = VECTOR_TYPE_P (type);
4583       unsigned int final_prec = element_precision (type);
4584       int final_unsignedp = TYPE_UNSIGNED (type);
4585     }
4586    (switch
4587     /* In addition to the cases of two conversions in a row
4588        handled below, if we are converting something to its own
4589        type via an object of identical or wider precision, neither
4590        conversion is needed.  */
4591     (if (((GIMPLE && useless_type_conversion_p (type, inside_type))
4592           || (GENERIC
4593               && TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (inside_type)))
4594          && (((inter_int || inter_ptr) && final_int)
4595              || (inter_float && final_float))
4596          && inter_prec >= final_prec)
4597      (ocvt @0))
4599     /* Likewise, if the intermediate and initial types are either both
4600        float or both integer, we don't need the middle conversion if the
4601        former is wider than the latter and doesn't change the signedness
4602        (for integers).  Avoid this if the final type is a pointer since
4603        then we sometimes need the middle conversion.  */
4604     (if (((inter_int && inside_int) || (inter_float && inside_float))
4605          && (final_int || final_float)
4606          && inter_prec >= inside_prec
4607          && (inter_float || inter_unsignedp == inside_unsignedp))
4608      (ocvt @0))
4610     /* If we have a sign-extension of a zero-extended value, we can
4611        replace that by a single zero-extension.  Likewise if the
4612        final conversion does not change precision we can drop the
4613        intermediate conversion.  */
4614     (if (inside_int && inter_int && final_int
4615          && ((inside_prec < inter_prec && inter_prec < final_prec
4616               && inside_unsignedp && !inter_unsignedp)
4617              || final_prec == inter_prec))
4618      (ocvt @0))
4620     /* Two conversions in a row are not needed unless:
4621         - some conversion is floating-point (overstrict for now), or
4622         - some conversion is a vector (overstrict for now), or
4623         - the intermediate type is narrower than both initial and
4624           final, or
4625         - the intermediate type and innermost type differ in signedness,
4626           and the outermost type is wider than the intermediate, or
4627         - the initial type is a pointer type and the precisions of the
4628           intermediate and final types differ, or
4629         - the final type is a pointer type and the precisions of the
4630           initial and intermediate types differ.  */
4631     (if (! inside_float && ! inter_float && ! final_float
4632          && ! inside_vec && ! inter_vec && ! final_vec
4633          && (inter_prec >= inside_prec || inter_prec >= final_prec)
4634          && ! (inside_int && inter_int
4635                && inter_unsignedp != inside_unsignedp
4636                && inter_prec < final_prec)
4637          && ((inter_unsignedp && inter_prec > inside_prec)
4638              == (final_unsignedp && final_prec > inter_prec))
4639          && ! (inside_ptr && inter_prec != final_prec)
4640          && ! (final_ptr && inside_prec != inter_prec))
4641      (ocvt @0))
4643    /* `(outer:M)(inter:N) a:O`
4644       can be converted to `(outer:M) a`
4645       if M <= O && N >= O. No matter what signedness of the casts,
4646       as the final is either a truncation from the original or just
4647       a sign change of the type. */
4648    (if (inside_int && inter_int && final_int
4649         && final_prec <= inside_prec
4650         && inter_prec >= inside_prec)
4651     (convert @0))
4653     /* A truncation to an unsigned type (a zero-extension) should be
4654        canonicalized as bitwise and of a mask.  */
4655     (if (GIMPLE /* PR70366: doing this in GENERIC breaks -Wconversion.  */
4656          && final_int && inter_int && inside_int
4657          && final_prec == inside_prec
4658          && final_prec > inter_prec
4659          && inter_unsignedp)
4660      (convert (bit_and @0 { wide_int_to_tree
4661                               (inside_type,
4662                                wi::mask (inter_prec, false,
4663                                          TYPE_PRECISION (inside_type))); })))
4665     /* If we are converting an integer to a floating-point that can
4666        represent it exactly and back to an integer, we can skip the
4667        floating-point conversion.  */
4668     (if (GIMPLE /* PR66211 */
4669          && inside_int && inter_float && final_int &&
4670          (unsigned) significand_size (TYPE_MODE (inter_type))
4671          >= inside_prec - !inside_unsignedp)
4672      (convert @0)))))))
4674 /* (float_type)(integer_type) x -> trunc (x) if the type of x matches
4675    float_type.  Only do the transformation if we do not need to preserve
4676    trapping behaviour, so require !flag_trapping_math. */
4677 #if GIMPLE
4678 (simplify
4679    (float (fix_trunc @0))
4680    (if (!flag_trapping_math
4681         && types_match (type, TREE_TYPE (@0))
4682         && direct_internal_fn_supported_p (IFN_TRUNC, type,
4683                                           OPTIMIZE_FOR_BOTH))
4684       (IFN_TRUNC @0)))
4685 #endif
4687 /* If we have a narrowing conversion to an integral type that is fed by a
4688    BIT_AND_EXPR, we might be able to remove the BIT_AND_EXPR if it merely
4689    masks off bits outside the final type (and nothing else).  */
4690 (simplify
4691   (convert (bit_and @0 INTEGER_CST@1))
4692   (if (INTEGRAL_TYPE_P (type)
4693        && INTEGRAL_TYPE_P (TREE_TYPE (@0))
4694        && TYPE_PRECISION (type) <= TYPE_PRECISION (TREE_TYPE (@0))
4695        && operand_equal_p (@1, build_low_bits_mask (TREE_TYPE (@1),
4696                                                     TYPE_PRECISION (type)), 0))
4697    (convert @0)))
4700 /* (X /[ex] A) * A -> X.  */
4701 (simplify
4702   (mult (convert1? (exact_div @0 @@1)) (convert2? @1))
4703   (convert @0))
4705 /* Simplify (A / B) * B + (A % B) -> A.  */
4706 (for div (trunc_div ceil_div floor_div round_div)
4707      mod (trunc_mod ceil_mod floor_mod round_mod)
4708   (simplify
4709    (plus:c (mult:c (div @0 @1) @1) (mod @0 @1))
4710    @0))
4712 /* x / y * y == x -> x % y == 0.  */
4713 (simplify
4714   (eq:c (mult:c (trunc_div:s @0 @1) @1) @0)
4715   (if (TREE_CODE (TREE_TYPE (@0)) != COMPLEX_TYPE)
4716     (eq (trunc_mod @0 @1) { build_zero_cst (TREE_TYPE (@0)); })))
4718 /* ((X /[ex] A) +- B) * A  -->  X +- A * B.  */
4719 (for op (plus minus)
4720  (simplify
4721   (mult (convert1? (op (convert2? (exact_div @0 INTEGER_CST@@1)) INTEGER_CST@2)) @1)
4722   (if (tree_nop_conversion_p (type, TREE_TYPE (@2))
4723        && tree_nop_conversion_p (TREE_TYPE (@0), TREE_TYPE (@2)))
4724    (with
4725      {
4726        wi::overflow_type overflow;
4727        wide_int mul = wi::mul (wi::to_wide (@1), wi::to_wide (@2),
4728                                TYPE_SIGN (type), &overflow);
4729      }
4730      (if (types_match (type, TREE_TYPE (@2))
4731          && types_match (TREE_TYPE (@0), TREE_TYPE (@2)) && !overflow)
4732       (op @0 { wide_int_to_tree (type, mul); })
4733       (with { tree utype = unsigned_type_for (type); }
4734        (convert (op (convert:utype @0)
4735                     (mult (convert:utype @1) (convert:utype @2))))))))))
4737 /* Canonicalization of binary operations.  */
4739 /* Convert X + -C into X - C.  */
4740 (simplify
4741  (plus @0 REAL_CST@1)
4742  (if (REAL_VALUE_NEGATIVE (TREE_REAL_CST (@1)))
4743   (with { tree tem = const_unop (NEGATE_EXPR, type, @1); }
4744    (if (!TREE_OVERFLOW (tem) || !flag_trapping_math)
4745     (minus @0 { tem; })))))
4747 /* Convert x+x into x*2.  */
4748 (simplify
4749  (plus @0 @0)
4750  (if (SCALAR_FLOAT_TYPE_P (type))
4751   (mult @0 { build_real (type, dconst2); })
4752   (if (INTEGRAL_TYPE_P (type))
4753    (mult @0 { build_int_cst (type, 2); }))))
4755 /* 0 - X  ->  -X.  */
4756 (simplify
4757  (minus integer_zerop @1)
4758  (negate @1))
4759 (simplify
4760  (pointer_diff integer_zerop @1)
4761  (negate (convert @1)))
4763 /* (ARG0 - ARG1) is the same as (-ARG1 + ARG0).  So check whether
4764    ARG0 is zero and X + ARG0 reduces to X, since that would mean
4765    (-ARG1 + ARG0) reduces to -ARG1.  */
4766 (simplify
4767  (minus real_zerop@0 @1)
4768  (if (fold_real_zero_addition_p (type, @1, @0, 0))
4769   (negate @1)))
4771 /* Transform x * -1 into -x.  */
4772 (simplify
4773  (mult @0 integer_minus_onep)
4774  (negate @0))
4776 /* Reassociate (X * CST) * Y to (X * Y) * CST.  This does not introduce
4777    signed overflow for CST != 0 && CST != -1.  */
4778 (simplify
4779  (mult:c (mult:s@3 @0 INTEGER_CST@1) @2)
4780  (if (TREE_CODE (@2) != INTEGER_CST
4781       && single_use (@3)
4782       && !integer_zerop (@1) && !integer_minus_onep (@1))
4783   (mult (mult @0 @2) @1)))
4785 /* True if we can easily extract the real and imaginary parts of a complex
4786    number.  */
4787 (match compositional_complex
4788  (convert? (complex @0 @1)))
4790 /* COMPLEX_EXPR and REALPART/IMAGPART_EXPR cancellations.  */
4791 (simplify
4792  (complex (realpart @0) (imagpart @0))
4793  @0)
4794 (simplify
4795  (realpart (complex @0 @1))
4796  @0)
4797 (simplify
4798  (imagpart (complex @0 @1))
4799  @1)
4801 /* Sometimes we only care about half of a complex expression.  */
4802 (simplify
4803  (realpart (convert?:s (conj:s @0)))
4804  (convert (realpart @0)))
4805 (simplify
4806  (imagpart (convert?:s (conj:s @0)))
4807  (convert (negate (imagpart @0))))
4808 (for part (realpart imagpart)
4809  (for op (plus minus)
4810   (simplify
4811    (part (convert?:s@2 (op:s @0 @1)))
4812    (convert (op (part @0) (part @1))))))
4813 (simplify
4814  (realpart (convert?:s (CEXPI:s @0)))
4815  (convert (COS @0)))
4816 (simplify
4817  (imagpart (convert?:s (CEXPI:s @0)))
4818  (convert (SIN @0)))
4820 /* conj(conj(x)) -> x  */
4821 (simplify
4822  (conj (convert? (conj @0)))
4823  (if (tree_nop_conversion_p (TREE_TYPE (@0), type))
4824   (convert @0)))
4826 /* conj({x,y}) -> {x,-y}  */
4827 (simplify
4828  (conj (convert?:s (complex:s @0 @1)))
4829  (with { tree itype = TREE_TYPE (type); }
4830   (complex (convert:itype @0) (negate (convert:itype @1)))))
4832 /* BSWAP simplifications, transforms checked by gcc.dg/builtin-bswap-8.c.  */
4833 (for bswap (BSWAP)
4834  (simplify
4835   (bswap (bswap @0))
4836   @0)
4837  (simplify
4838   (bswap (bit_not (bswap @0)))
4839   (bit_not @0))
4840  (for bitop (bit_xor bit_ior bit_and)
4841   (simplify
4842    (bswap (bitop:c (bswap @0) @1))
4843    (bitop @0 (bswap @1))))
4844  (for cmp (eq ne)
4845   (simplify
4846    (cmp (bswap@2 @0) (bswap @1))
4847    (with { tree ctype = TREE_TYPE (@2); }
4848     (cmp (convert:ctype @0) (convert:ctype @1))))
4849   (simplify
4850    (cmp (bswap @0) INTEGER_CST@1)
4851    (with { tree ctype = TREE_TYPE (@1); }
4852     (cmp (convert:ctype @0) (bswap! @1)))))
4853  /* (bswap(x) >> C1) & C2 can sometimes be simplified to (x >> C3) & C2.  */
4854  (simplify
4855   (bit_and (convert1? (rshift@0 (convert2? (bswap@4 @1)) INTEGER_CST@2))
4856            INTEGER_CST@3)
4857    (if (BITS_PER_UNIT == 8
4858         && tree_fits_uhwi_p (@2)
4859         && tree_fits_uhwi_p (@3))
4860     (with
4861      {
4862       unsigned HOST_WIDE_INT prec = TYPE_PRECISION (TREE_TYPE (@4));
4863       unsigned HOST_WIDE_INT bits = tree_to_uhwi (@2);
4864       unsigned HOST_WIDE_INT mask = tree_to_uhwi (@3);
4865       unsigned HOST_WIDE_INT lo = bits & 7;
4866       unsigned HOST_WIDE_INT hi = bits - lo;
4867      }
4868      (if (bits < prec
4869           && mask < (256u>>lo)
4870           && bits < TYPE_PRECISION (TREE_TYPE(@0)))
4871       (with { unsigned HOST_WIDE_INT ns = (prec - (hi + 8)) + lo; }
4872        (if (ns == 0)
4873         (bit_and (convert @1) @3)
4874         (with
4875          {
4876           tree utype = unsigned_type_for (TREE_TYPE (@1));
4877           tree nst = build_int_cst (integer_type_node, ns);
4878          }
4879          (bit_and (convert (rshift:utype (convert:utype @1) {nst;})) @3))))))))
4880  /* bswap(x) >> C1 can sometimes be simplified to (T)x >> C2.  */
4881  (simplify
4882   (rshift (convert? (bswap@2 @0)) INTEGER_CST@1)
4883    (if (BITS_PER_UNIT == 8
4884         && CHAR_TYPE_SIZE == 8
4885         && tree_fits_uhwi_p (@1))
4886     (with
4887      {
4888       unsigned HOST_WIDE_INT prec = TYPE_PRECISION (TREE_TYPE (@2));
4889       unsigned HOST_WIDE_INT bits = tree_to_uhwi (@1);
4890       /* If the bswap was extended before the original shift, this
4891          byte (shift) has the sign of the extension, not the sign of
4892          the original shift.  */
4893       tree st = TYPE_PRECISION (type) > prec ? TREE_TYPE (@2) : type;
4894      }
4895      /* Special case: logical right shift of sign-extended bswap.
4896         (unsigned)(short)bswap16(x)>>12 is (unsigned)((short)x<<8)>>12. */
4897      (if (TYPE_PRECISION (type) > prec
4898           && !TYPE_UNSIGNED (TREE_TYPE (@2))
4899           && TYPE_UNSIGNED (type)
4900           && bits < prec && bits + 8 >= prec)
4901       (with { tree nst = build_int_cst (integer_type_node, prec - 8); }
4902        (rshift (convert (lshift:st (convert:st @0) {nst;})) @1))
4903       (if (bits + 8 == prec)
4904        (if (TYPE_UNSIGNED (st))
4905         (convert (convert:unsigned_char_type_node @0))
4906         (convert (convert:signed_char_type_node @0)))
4907        (if (bits < prec && bits + 8 > prec)
4908         (with 
4909          {
4910           tree nst = build_int_cst (integer_type_node, bits & 7);
4911           tree bt = TYPE_UNSIGNED (st) ? unsigned_char_type_node
4912                                        : signed_char_type_node;
4913          }
4914          (convert (rshift:bt (convert:bt @0) {nst;})))))))))
4915  /* bswap(x) & C1 can sometimes be simplified to (x >> C2) & C1.  */
4916  (simplify
4917   (bit_and (convert? (bswap@2 @0)) INTEGER_CST@1)
4918    (if (BITS_PER_UNIT == 8
4919         && tree_fits_uhwi_p (@1)
4920         && tree_to_uhwi (@1) < 256)
4921     (with
4922      {
4923       unsigned HOST_WIDE_INT prec = TYPE_PRECISION (TREE_TYPE (@2));
4924       tree utype = unsigned_type_for (TREE_TYPE (@0));
4925       tree nst = build_int_cst (integer_type_node, prec - 8);
4926      }
4927      (bit_and (convert (rshift:utype (convert:utype @0) {nst;})) @1)))))
4930 /* Combine COND_EXPRs and VEC_COND_EXPRs.  */
4932 /* Simplify constant conditions.
4933    Only optimize constant conditions when the selected branch
4934    has the same type as the COND_EXPR.  This avoids optimizing
4935    away "c ? x : throw", where the throw has a void type.
4936    Note that we cannot throw away the fold-const.cc variant nor
4937    this one as we depend on doing this transform before possibly
4938    A ? B : B -> B triggers and the fold-const.cc one can optimize
4939    0 ? A : B to B even if A has side-effects.  Something
4940    genmatch cannot handle.  */
4941 (simplify
4942  (cond INTEGER_CST@0 @1 @2)
4943  (if (integer_zerop (@0))
4944   (if (!VOID_TYPE_P (TREE_TYPE (@2)) || VOID_TYPE_P (type))
4945    @2)
4946   (if (!VOID_TYPE_P (TREE_TYPE (@1)) || VOID_TYPE_P (type))
4947    @1)))
4948 (simplify
4949  (vec_cond VECTOR_CST@0 @1 @2)
4950  (if (integer_all_onesp (@0))
4951   @1
4952   (if (integer_zerop (@0))
4953    @2)))
4955 /* Sink unary operations to branches, but only if we do fold both.  */
4956 (for op (negate bit_not abs absu)
4957  (simplify
4958   (op (vec_cond:s @0 @1 @2))
4959   (vec_cond @0 (op! @1) (op! @2))))
4961 /* Sink unary conversions to branches, but only if we do fold both
4962    and the target's truth type is the same as we already have.  */
4963 (simplify
4964  (convert (vec_cond:s @0 @1 @2))
4965  (if (VECTOR_TYPE_P (type)
4966       && types_match (TREE_TYPE (@0), truth_type_for (type)))
4967   (vec_cond @0 (convert! @1) (convert! @2))))
4969 /* Likewise for view_convert of nop_conversions. */
4970 (simplify
4971  (view_convert (vec_cond:s @0 @1 @2))
4972  (if (VECTOR_TYPE_P (type) && VECTOR_TYPE_P (TREE_TYPE (@1))
4973       && known_eq (TYPE_VECTOR_SUBPARTS (type),
4974                    TYPE_VECTOR_SUBPARTS (TREE_TYPE (@1)))
4975       && tree_nop_conversion_p (TREE_TYPE (type), TREE_TYPE (TREE_TYPE (@1))))
4976   (vec_cond @0 (view_convert! @1) (view_convert! @2))))
4978 /* Sink binary operation to branches, but only if we can fold it.  */
4979 (for op (tcc_comparison plus minus mult bit_and bit_ior bit_xor
4980          lshift rshift rdiv trunc_div ceil_div floor_div round_div
4981          trunc_mod ceil_mod floor_mod round_mod min max)
4982 /* (c ? a : b) op (c ? d : e)  -->  c ? (a op d) : (b op e) */
4983  (simplify
4984   (op (vec_cond:s @0 @1 @2) (vec_cond:s @0 @3 @4))
4985   (vec_cond @0 (op! @1 @3) (op! @2 @4)))
4987 /* (c ? a : b) op d  -->  c ? (a op d) : (b op d) */
4988  (simplify
4989   (op (vec_cond:s @0 @1 @2) @3)
4990   (vec_cond @0 (op! @1 @3) (op! @2 @3)))
4991  (simplify
4992   (op @3 (vec_cond:s @0 @1 @2))
4993   (vec_cond @0 (op! @3 @1) (op! @3 @2))))
4995 #if GIMPLE
4996 (match (nop_atomic_bit_test_and_p @0 @1 @4)
4997  (bit_and (convert?@4 (ATOMIC_FETCH_OR_XOR_N @2 INTEGER_CST@0 @3))
4998            INTEGER_CST@1)
4999  (with {
5000          int ibit = tree_log2 (@0);
5001          int ibit2 = tree_log2 (@1);
5002        }
5003   (if (ibit == ibit2
5004       && ibit >= 0
5005       && TYPE_PRECISION (type) <= TYPE_PRECISION (TREE_TYPE (@0))))))
5007 (match (nop_atomic_bit_test_and_p @0 @1 @3)
5008  (bit_and (convert?@3 (SYNC_FETCH_OR_XOR_N @2 INTEGER_CST@0))
5009           INTEGER_CST@1)
5010  (with {
5011          int ibit = tree_log2 (@0);
5012          int ibit2 = tree_log2 (@1);
5013        }
5014   (if (ibit == ibit2
5015       && ibit >= 0
5016       && TYPE_PRECISION (type) <= TYPE_PRECISION (TREE_TYPE (@0))))))
5018 (match (nop_atomic_bit_test_and_p @0 @0 @4)
5019  (bit_and:c
5020   (convert1?@4
5021    (ATOMIC_FETCH_OR_XOR_N @2 (nop_convert? (lshift@0 integer_onep@5 @6)) @3))
5022   (convert2? @0))
5023  (if (TYPE_PRECISION (type) <= TYPE_PRECISION (TREE_TYPE (@0)))))
5025 (match (nop_atomic_bit_test_and_p @0 @0 @4)
5026  (bit_and:c
5027   (convert1?@4
5028    (SYNC_FETCH_OR_XOR_N @2 (nop_convert? (lshift@0 integer_onep@3 @5))))
5029   (convert2? @0))
5030  (if (TYPE_PRECISION (type) <= TYPE_PRECISION (TREE_TYPE (@0)))))
5032 (match (nop_atomic_bit_test_and_p @0 @1 @3)
5033  (bit_and@4 (convert?@3 (ATOMIC_FETCH_AND_N @2 INTEGER_CST@0 @5))
5034             INTEGER_CST@1)
5035  (with {
5036          int ibit = wi::exact_log2 (wi::zext (wi::bit_not (wi::to_wide (@0)),
5037                                               TYPE_PRECISION(type)));
5038          int ibit2 = tree_log2 (@1);
5039        }
5040   (if (ibit == ibit2
5041       && ibit >= 0
5042       && TYPE_PRECISION (type) <= TYPE_PRECISION (TREE_TYPE (@0))))))
5044 (match (nop_atomic_bit_test_and_p @0 @1 @3)
5045  (bit_and@4
5046   (convert?@3 (SYNC_FETCH_AND_AND_N @2 INTEGER_CST@0))
5047   INTEGER_CST@1)
5048  (with {
5049          int ibit = wi::exact_log2 (wi::zext (wi::bit_not (wi::to_wide (@0)),
5050                                               TYPE_PRECISION(type)));
5051          int ibit2 = tree_log2 (@1);
5052        }
5053   (if (ibit == ibit2
5054       && ibit >= 0
5055       && TYPE_PRECISION (type) <= TYPE_PRECISION (TREE_TYPE (@0))))))
5057 (match (nop_atomic_bit_test_and_p @4 @0 @3)
5058  (bit_and:c
5059   (convert1?@3
5060    (ATOMIC_FETCH_AND_N @2 (nop_convert?@4 (bit_not (lshift@0 integer_onep@6 @7))) @5))
5061   (convert2? @0))
5062  (if (TYPE_PRECISION (type) <= TYPE_PRECISION (TREE_TYPE (@4)))))
5064 (match (nop_atomic_bit_test_and_p @4 @0 @3)
5065  (bit_and:c
5066   (convert1?@3
5067    (SYNC_FETCH_AND_AND_N @2 (nop_convert?@4 (bit_not (lshift@0 integer_onep@6 @7)))))
5068   (convert2? @0))
5069   (if (TYPE_PRECISION (type) <= TYPE_PRECISION (TREE_TYPE (@4)))))
5071 #endif
5073 /* (v ? w : 0) ? a : b is just (v & w) ? a : b
5074    Currently disabled after pass lvec because ARM understands
5075    VEC_COND_EXPR<v==w,-1,0> but not a plain v==w fed to BIT_IOR_EXPR.  */
5076 #if GIMPLE
5077 /* These can only be done in gimple as fold likes to convert:
5078    (CMP) & N into (CMP) ? N : 0
5079    and we try to match the same pattern again and again. */
5080 (simplify
5081  (vec_cond (vec_cond:s @0 @3 integer_zerop) @1 @2)
5082  (if (optimize_vectors_before_lowering_p () && types_match (@0, @3))
5083   (vec_cond (bit_and @0 @3) @1 @2)))
5084 (simplify
5085  (vec_cond (vec_cond:s @0 integer_all_onesp @3) @1 @2)
5086  (if (optimize_vectors_before_lowering_p () && types_match (@0, @3))
5087   (vec_cond (bit_ior @0 @3) @1 @2)))
5088 (simplify
5089  (vec_cond (vec_cond:s @0 integer_zerop @3) @1 @2)
5090  (if (optimize_vectors_before_lowering_p () && types_match (@0, @3))
5091   (vec_cond (bit_ior @0 (bit_not @3)) @2 @1)))
5092 (simplify
5093  (vec_cond (vec_cond:s @0 @3 integer_all_onesp) @1 @2)
5094  (if (optimize_vectors_before_lowering_p () && types_match (@0, @3))
5095   (vec_cond (bit_and @0 (bit_not @3)) @2 @1)))
5097 /* c1 ? c2 ? a : b : b  -->  (c1 & c2) ? a : b  */
5098 (simplify
5099  (vec_cond @0 (vec_cond:s @1 @2 @3) @3)
5100  (if (optimize_vectors_before_lowering_p () && types_match (@0, @1))
5101   (vec_cond (bit_and @0 @1) @2 @3)))
5102 (simplify
5103  (vec_cond @0 @2 (vec_cond:s @1 @2 @3))
5104  (if (optimize_vectors_before_lowering_p () && types_match (@0, @1))
5105   (vec_cond (bit_ior @0 @1) @2 @3)))
5106 (simplify
5107  (vec_cond @0 (vec_cond:s @1 @2 @3) @2)
5108  (if (optimize_vectors_before_lowering_p () && types_match (@0, @1))
5109   (vec_cond (bit_ior (bit_not @0) @1) @2 @3)))
5110 (simplify
5111  (vec_cond @0 @3 (vec_cond:s @1 @2 @3))
5112  (if (optimize_vectors_before_lowering_p () && types_match (@0, @1))
5113   (vec_cond (bit_and (bit_not @0) @1) @2 @3)))
5114 #endif
5116 /* Canonicalize mask ? { 0, ... } : { -1, ...} to ~mask if the mask
5117    types are compatible.  */
5118 (simplify
5119  (vec_cond @0 VECTOR_CST@1 VECTOR_CST@2)
5120  (if (VECTOR_BOOLEAN_TYPE_P (type)
5121       && types_match (type, TREE_TYPE (@0)))
5122   (if (integer_zerop (@1) && integer_all_onesp (@2))
5123    (bit_not @0)
5124    (if (integer_all_onesp (@1) && integer_zerop (@2))
5125     @0))))
5127 /* A few simplifications of "a ? CST1 : CST2". */
5128 /* NOTE: Only do this on gimple as the if-chain-to-switch
5129    optimization depends on the gimple to have if statements in it. */
5130 #if GIMPLE
5131 (simplify
5132  (cond @0 INTEGER_CST@1 INTEGER_CST@2)
5133  (switch
5134   (if (integer_zerop (@2))
5135    (switch
5136     /* a ? 1 : 0 -> a if 0 and 1 are integral types.  */
5137     (if (integer_onep (@1))
5138      (convert (convert:boolean_type_node @0)))
5139     /* a ? -1 : 0 -> -a.  */
5140     (if (INTEGRAL_TYPE_P (type) && integer_all_onesp (@1))
5141      (if (TYPE_PRECISION (type) == 1)
5142       /* For signed 1-bit precision just cast bool to the type.  */
5143       (convert (convert:boolean_type_node @0))
5144       (if (TREE_CODE (type) == BOOLEAN_TYPE)
5145        (with {
5146           tree intt = build_nonstandard_integer_type (TYPE_PRECISION (type),
5147                                                       TYPE_UNSIGNED (type));
5148         }
5149         (convert (negate (convert:intt (convert:boolean_type_node @0)))))
5150        (negate (convert:type (convert:boolean_type_node @0))))))
5151     /* a ? powerof2cst : 0 -> a << (log2(powerof2cst)) */
5152     (if (INTEGRAL_TYPE_P (type) && integer_pow2p (@1))
5153      (with {
5154        tree shift = build_int_cst (integer_type_node, tree_log2 (@1));
5155       }
5156       (lshift (convert (convert:boolean_type_node @0)) { shift; })))))
5157   (if (integer_zerop (@1))
5158    (switch
5159     /* a ? 0 : 1 -> !a.  */
5160     (if (integer_onep (@2))
5161      (convert (bit_xor (convert:boolean_type_node @0) { boolean_true_node; })))
5162     /* a ? 0 : -1 -> -(!a).  */
5163     (if (INTEGRAL_TYPE_P (type) && integer_all_onesp (@2))
5164      (if (TYPE_PRECISION (type) == 1)
5165       /* For signed 1-bit precision just cast bool to the type.  */
5166       (convert (bit_xor (convert:boolean_type_node @0) { boolean_true_node; }))
5167       (if (TREE_CODE (type) == BOOLEAN_TYPE)
5168        (with {
5169           tree intt = build_nonstandard_integer_type (TYPE_PRECISION (type),
5170                                                       TYPE_UNSIGNED (type));
5171         }
5172         (convert (negate (convert:intt (bit_xor (convert:boolean_type_node @0)
5173                                                 { boolean_true_node; })))))
5174        (negate (convert:type (bit_xor (convert:boolean_type_node @0)
5175                                       { boolean_true_node; }))))))
5176     /* a ? 0 : powerof2cst -> (!a) << (log2(powerof2cst)) */
5177     (if (INTEGRAL_TYPE_P (type) && integer_pow2p (@2))
5178      (with {
5179        tree shift = build_int_cst (integer_type_node, tree_log2 (@2));
5180       }
5181       (lshift (convert (bit_xor (convert:boolean_type_node @0)
5182                                 { boolean_true_node; })) { shift; })))))))
5184 /* (a > 1) ? 0 : (cast)a is the same as (cast)(a == 1)
5185    for unsigned types. */
5186 (simplify
5187  (cond (gt @0 integer_onep@1) integer_zerop (convert? @2))
5188  (if (TYPE_UNSIGNED (TREE_TYPE (@0))
5189       && bitwise_equal_p (@0, @2))
5190   (convert (eq @0 @1))
5194 /* (a <= 1) & (cast)a is the same as (cast)(a == 1)
5195    for unsigned types. */
5196 (simplify
5197  (bit_and:c (convert1? (le @0 integer_onep@1)) (convert2? @2))
5198  (if (TYPE_UNSIGNED (TREE_TYPE (@0))
5199       && bitwise_equal_p (@0, @2))
5200   (convert (eq @0 @1))
5204 /* `(a == CST) & a` can be simplified to `0` or `(a == CST)` depending
5205    on the first bit of the CST.  */
5206 (simplify
5207  (bit_and:c (convert@2 (eq @0 INTEGER_CST@1)) (convert? @0))
5208  (if ((wi::to_wide (@1) & 1) != 0)
5209   @2
5210   { build_zero_cst (type); }))
5212 /* Optimize
5213    # x_5 in range [cst1, cst2] where cst2 = cst1 + 1
5214    x_5 == cstN ? cst4 : cst3
5215    # op is == or != and N is 1 or 2
5216    to r_6 = x_5 + (min (cst3, cst4) - cst1) or
5217    r_6 = (min (cst3, cst4) + cst1) - x_5 depending on op, N and which
5218    of cst3 and cst4 is smaller.
5219    This was originally done by two_value_replacement in phiopt (PR 88676).  */
5220 (for eqne (ne eq)
5221  (simplify
5222   (cond (eqne SSA_NAME@0 INTEGER_CST@1) INTEGER_CST@2 INTEGER_CST@3)
5223   (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
5224        && INTEGRAL_TYPE_P (type)
5225        && (wi::to_widest (@2) + 1 == wi::to_widest (@3)
5226            || wi::to_widest (@2) == wi::to_widest (@3) + 1))
5227    (with {
5228      value_range r;
5229      get_range_query (cfun)->range_of_expr (r, @0);
5230      if (r.undefined_p ())
5231        r.set_varying (TREE_TYPE (@0));
5233      wide_int min = r.lower_bound ();
5234      wide_int max = r.upper_bound ();
5235     }
5236     (if (min + 1 == max
5237          && (wi::to_wide (@1) == min
5238              || wi::to_wide (@1) == max))
5239      (with {
5240        tree arg0 = @2, arg1 = @3;
5241        tree type1;
5242        if ((eqne == EQ_EXPR) ^ (wi::to_wide (@1) == min))
5243          std::swap (arg0, arg1);
5244        if (TYPE_PRECISION (TREE_TYPE (@0)) > TYPE_PRECISION (type))
5245          type1 = TREE_TYPE (@0);
5246        else
5247          type1 = type;
5248        auto prec = TYPE_PRECISION (type1);
5249        auto unsign = TYPE_UNSIGNED (type1);
5250        if (TREE_CODE (type1) == BOOLEAN_TYPE)
5251         type1 = build_nonstandard_integer_type (prec, unsign);
5252        min = wide_int::from (min, prec,
5253                              TYPE_SIGN (TREE_TYPE (@0)));
5254        wide_int a = wide_int::from (wi::to_wide (arg0), prec,
5255                                     TYPE_SIGN (type));
5256        enum tree_code code;
5257        wi::overflow_type ovf;
5258        if (tree_int_cst_lt (arg0, arg1))
5259          {
5260            code = PLUS_EXPR;
5261            a -= min;
5262            if (!unsign)
5263              {
5264                /* lhs is known to be in range [min, min+1] and we want to add a
5265                   to it.  Check if that operation can overflow for those 2 values
5266                   and if yes, force unsigned type.  */
5267                wi::add (min + (wi::neg_p (a) ? 0 : 1), a, SIGNED, &ovf);
5268                if (ovf)
5269                  type1 = unsigned_type_for (type1);
5270              }
5271          }
5272        else
5273          {
5274            code = MINUS_EXPR;
5275            a += min;
5276            if (!unsign)
5277              {
5278                /* lhs is known to be in range [min, min+1] and we want to subtract
5279                   it from a.  Check if that operation can overflow for those 2
5280                   values and if yes, force unsigned type.  */
5281                wi::sub (a, min + (wi::neg_p (min) ? 0 : 1), SIGNED, &ovf);
5282                if (ovf)
5283                 type1 = unsigned_type_for (type1);
5284              }
5285          }
5286        tree arg = wide_int_to_tree (type1, a);
5287       }
5288       (if (code == PLUS_EXPR)
5289        (convert (plus (convert:type1 @0) { arg; }))
5290        (convert (minus { arg; } (convert:type1 @0))))))))))
5291 #endif
5293 (simplify
5294  (convert (cond@0 @1 INTEGER_CST@2 INTEGER_CST@3))
5295  (if (INTEGRAL_TYPE_P (type)
5296       && INTEGRAL_TYPE_P (TREE_TYPE (@0)))
5297   (cond @1 (convert @2) (convert @3))))
5299 /* Simplification moved from fold_cond_expr_with_comparison.  It may also
5300    be extended.  */
5301 /* This pattern implements two kinds simplification:
5303    Case 1)
5304    (cond (cmp (convert1? x) c1) (convert2? x) c2) -> (minmax (x c)) if:
5305      1) Conversions are type widening from smaller type.
5306      2) Const c1 equals to c2 after canonicalizing comparison.
5307      3) Comparison has tree code LT, LE, GT or GE.
5308    This specific pattern is needed when (cmp (convert x) c) may not
5309    be simplified by comparison patterns because of multiple uses of
5310    x.  It also makes sense here because simplifying across multiple
5311    referred var is always benefitial for complicated cases.
5313    Case 2)
5314    (cond (eq (convert1? x) c1) (convert2? x) c2) -> (cond (eq x c1) c1 c2).  */
5315 (for cmp (lt le gt ge eq ne)
5316  (simplify
5317   (cond (cmp (convert1? @1) INTEGER_CST@3) (convert2? @1) INTEGER_CST@2)
5318   (with
5319    {
5320      tree from_type = TREE_TYPE (@1);
5321      tree c1_type = TREE_TYPE (@3), c2_type = TREE_TYPE (@2);
5322      enum tree_code code = ERROR_MARK;
5324      if (INTEGRAL_TYPE_P (from_type)
5325          && int_fits_type_p (@2, from_type)
5326          && (types_match (c1_type, from_type)
5327              || (TYPE_PRECISION (c1_type) > TYPE_PRECISION (from_type)
5328                  && (TYPE_UNSIGNED (from_type)
5329                      || TYPE_SIGN (c1_type) == TYPE_SIGN (from_type))))
5330          && (types_match (c2_type, from_type)
5331              || (TYPE_PRECISION (c2_type) > TYPE_PRECISION (from_type)
5332                  && (TYPE_UNSIGNED (from_type)
5333                      || TYPE_SIGN (c2_type) == TYPE_SIGN (from_type)))))
5334        {
5335          if (cmp != EQ_EXPR)
5336            code = minmax_from_comparison (cmp, @1, @3, @1, @2);
5337          /* Can do A == C1 ? A : C2  ->  A == C1 ? C1 : C2?  */
5338          else if (int_fits_type_p (@3, from_type))
5339            code = EQ_EXPR;
5340        }
5341    }
5342    (if (code == MAX_EXPR)
5343     (convert (max @1 (convert @2)))
5344     (if (code == MIN_EXPR)
5345      (convert (min @1 (convert @2)))
5346      (if (code == EQ_EXPR)
5347       (convert (cond (eq @1 (convert @3))
5348                      (convert:from_type @3) (convert:from_type @2)))))))))
5350 /* (cond (cmp (convert? x) c1) (op x c2) c3) -> (op (minmax x c1) c2) if:
5352      1) OP is PLUS or MINUS.
5353      2) CMP is LT, LE, GT or GE.
5354      3) C3 == (C1 op C2), and computation doesn't have undefined behavior.
5356    This pattern also handles special cases like:
5358      A) Operand x is a unsigned to signed type conversion and c1 is
5359         integer zero.  In this case,
5360           (signed type)x  < 0  <=>  x  > MAX_VAL(signed type)
5361           (signed type)x >= 0  <=>  x <= MAX_VAL(signed type)
5362      B) Const c1 may not equal to (C3 op' C2).  In this case we also
5363         check equality for (c1+1) and (c1-1) by adjusting comparison
5364         code.
5366    TODO: Though signed type is handled by this pattern, it cannot be
5367    simplified at the moment because C standard requires additional
5368    type promotion.  In order to match&simplify it here, the IR needs
5369    to be cleaned up by other optimizers, i.e, VRP.  */
5370 (for op (plus minus)
5371  (for cmp (lt le gt ge)
5372   (simplify
5373    (cond (cmp (convert? @X) INTEGER_CST@1) (op @X INTEGER_CST@2) INTEGER_CST@3)
5374    (with { tree from_type = TREE_TYPE (@X), to_type = TREE_TYPE (@1); }
5375     (if (types_match (from_type, to_type)
5376          /* Check if it is special case A).  */
5377          || (TYPE_UNSIGNED (from_type)
5378              && !TYPE_UNSIGNED (to_type)
5379              && TYPE_PRECISION (from_type) == TYPE_PRECISION (to_type)
5380              && integer_zerop (@1)
5381              && (cmp == LT_EXPR || cmp == GE_EXPR)))
5382      (with
5383       {
5384         wi::overflow_type overflow = wi::OVF_NONE;
5385         enum tree_code code, cmp_code = cmp;
5386         wide_int real_c1;
5387         wide_int c1 = wi::to_wide (@1);
5388         wide_int c2 = wi::to_wide (@2);
5389         wide_int c3 = wi::to_wide (@3);
5390         signop sgn = TYPE_SIGN (from_type);
5392         /* Handle special case A), given x of unsigned type:
5393             ((signed type)x  < 0) <=> (x  > MAX_VAL(signed type))
5394             ((signed type)x >= 0) <=> (x <= MAX_VAL(signed type))  */
5395         if (!types_match (from_type, to_type))
5396           {
5397             if (cmp_code == LT_EXPR)
5398               cmp_code = GT_EXPR;
5399             if (cmp_code == GE_EXPR)
5400               cmp_code = LE_EXPR;
5401             c1 = wi::max_value (to_type);
5402           }
5403         /* To simplify this pattern, we require c3 = (c1 op c2).  Here we
5404            compute (c3 op' c2) and check if it equals to c1 with op' being
5405            the inverted operator of op.  Make sure overflow doesn't happen
5406            if it is undefined.  */
5407         if (op == PLUS_EXPR)
5408           real_c1 = wi::sub (c3, c2, sgn, &overflow);
5409         else
5410           real_c1 = wi::add (c3, c2, sgn, &overflow);
5412         code = cmp_code;
5413         if (!overflow || !TYPE_OVERFLOW_UNDEFINED (from_type))
5414           {
5415             /* Check if c1 equals to real_c1.  Boundary condition is handled
5416                by adjusting comparison operation if necessary.  */
5417             if (!wi::cmp (wi::sub (real_c1, 1, sgn, &overflow), c1, sgn)
5418                 && !overflow)
5419               {
5420                 /* X <= Y - 1 equals to X < Y.  */
5421                 if (cmp_code == LE_EXPR)
5422                   code = LT_EXPR;
5423                 /* X > Y - 1 equals to X >= Y.  */
5424                 if (cmp_code == GT_EXPR)
5425                   code = GE_EXPR;
5426               }
5427             if (!wi::cmp (wi::add (real_c1, 1, sgn, &overflow), c1, sgn)
5428                 && !overflow)
5429               {
5430                 /* X < Y + 1 equals to X <= Y.  */
5431                 if (cmp_code == LT_EXPR)
5432                   code = LE_EXPR;
5433                 /* X >= Y + 1 equals to X > Y.  */
5434                 if (cmp_code == GE_EXPR)
5435                   code = GT_EXPR;
5436               }
5437             if (code != cmp_code || !wi::cmp (real_c1, c1, sgn))
5438               {
5439                 if (cmp_code == LT_EXPR || cmp_code == LE_EXPR)
5440                   code = MIN_EXPR;
5441                 if (cmp_code == GT_EXPR || cmp_code == GE_EXPR)
5442                   code = MAX_EXPR;
5443               }
5444           }
5445       }
5446       (if (code == MAX_EXPR)
5447        (op (max @X { wide_int_to_tree (from_type, real_c1); })
5448            { wide_int_to_tree (from_type, c2); })
5449        (if (code == MIN_EXPR)
5450         (op (min @X { wide_int_to_tree (from_type, real_c1); })
5451             { wide_int_to_tree (from_type, c2); })))))))))
5453 #if GIMPLE
5454 /* A >= B ? A : B -> max (A, B) and friends.  The code is still
5455    in fold_cond_expr_with_comparison for GENERIC folding with
5456    some extra constraints.  */
5457 (for cmp (eq ne le lt unle unlt ge gt unge ungt uneq ltgt)
5458  (simplify
5459   (cond (cmp:c (nop_convert1?@c0 @0) (nop_convert2?@c1 @1))
5460         (convert3? @0) (convert4? @1))
5461   (if (!HONOR_SIGNED_ZEROS (type)
5462        && (/* Allow widening conversions of the compare operands as data.  */
5463            (INTEGRAL_TYPE_P (type)
5464             && types_match (TREE_TYPE (@c0), TREE_TYPE (@0))
5465             && types_match (TREE_TYPE (@c1), TREE_TYPE (@1))
5466             && TYPE_PRECISION (TREE_TYPE (@0)) <= TYPE_PRECISION (type)
5467             && TYPE_PRECISION (TREE_TYPE (@1)) <= TYPE_PRECISION (type))
5468            /* Or sign conversions for the comparison.  */
5469            || (types_match (type, TREE_TYPE (@0))
5470                && types_match (type, TREE_TYPE (@1)))))
5471    (switch
5472     (if (cmp == EQ_EXPR)
5473      (if (VECTOR_TYPE_P (type))
5474       (view_convert @c1)
5475       (convert @c1)))
5476     (if (cmp == NE_EXPR)
5477      (if (VECTOR_TYPE_P (type))
5478       (view_convert @c0)
5479       (convert @c0)))
5480     (if (cmp == LE_EXPR || cmp == UNLE_EXPR || cmp == LT_EXPR || cmp == UNLT_EXPR)
5481      (if (!HONOR_NANS (type))
5482       (if (VECTOR_TYPE_P (type))
5483        (view_convert (min @c0 @c1))
5484        (convert (min @c0 @c1)))))
5485     (if (cmp == GE_EXPR || cmp == UNGE_EXPR || cmp == GT_EXPR || cmp == UNGT_EXPR)
5486      (if (!HONOR_NANS (type))
5487       (if (VECTOR_TYPE_P (type))
5488        (view_convert (max @c0 @c1))
5489        (convert (max @c0 @c1)))))
5490     (if (cmp == UNEQ_EXPR)
5491      (if (!HONOR_NANS (type))
5492       (if (VECTOR_TYPE_P (type))
5493        (view_convert @c1)
5494        (convert @c1))))
5495     (if (cmp == LTGT_EXPR)
5496      (if (!HONOR_NANS (type))
5497       (if (VECTOR_TYPE_P (type))
5498        (view_convert @c0)
5499        (convert @c0))))))))
5500 #endif
5502 (for cnd (cond vec_cond)
5503  /* (a != b) ? (a - b) : 0 -> (a - b) */
5504  (simplify
5505   (cnd (ne:c @0 @1) (minus@2 @0 @1) integer_zerop)
5506   @2)
5507  /* (a != b) ? (a ^ b) : 0 -> (a ^ b) */
5508  (simplify
5509   (cnd (ne:c @0 @1) (bit_xor:c@2 @0 @1) integer_zerop)
5510   @2)
5511  /* (a != b) ? (a & b) : a -> (a & b) */
5512  /* (a != b) ? (a | b) : a -> (a | b) */
5513  /* (a != b) ? min(a,b) : a -> min(a,b) */
5514  /* (a != b) ? max(a,b) : a -> max(a,b) */
5515  (for op (bit_and bit_ior min max)
5516   (simplify
5517    (cnd (ne:c @0 @1) (op:c@2 @0 @1) @0)
5518    @2))
5519  /* (a != b) ? (a * b) : (a * a) -> (a * b) */
5520  /* (a != b) ? (a + b) : (a + a) -> (a + b) */
5521  (for op (mult plus)
5522   (simplify
5523    (cnd (ne:c @0 @1) (op@2 @0 @1) (op @0 @0))
5524    (if (ANY_INTEGRAL_TYPE_P (type))
5525     @2)))
5526  /* (a != b) ? (a + b) : (2 * a) -> (a + b) */
5527  (simplify
5528   (cnd (ne:c @0 @1) (plus@2 @0 @1) (mult @0 uniform_integer_cst_p@3))
5529   (if (wi::to_wide (uniform_integer_cst_p (@3)) == 2)
5530    @2))
5533 /* These was part of minmax phiopt.  */
5534 /* Optimize (a CMP b) ? minmax<a, c> : minmax<b, c>
5535    to minmax<min/max<a, b>, c> */
5536 (for minmax (min max)
5537  (for cmp (lt le gt ge ne)
5538   (simplify
5539    (cond (cmp:c @1 @3) (minmax:c @1 @4) (minmax:c @2 @4))
5540    (with
5541     {
5542       tree_code code = minmax_from_comparison (cmp, @1, @2, @1, @3);
5543     }
5544     (if (code == MIN_EXPR)
5545      (minmax (min @1 @2) @4)
5546      (if (code == MAX_EXPR)
5547       (minmax (max @1 @2) @4)))))))
5549 /* Optimize (a CMP CST1) ? max<a,CST2> : a */
5550 (for cmp    (gt  ge  lt  le)
5551      minmax (min min max max)
5552  (simplify
5553   (cond (cmp:c @0 @1) (minmax:c@2 @0 @3) @4)
5554    (with
5555     {
5556       tree_code code = minmax_from_comparison (cmp, @0, @1, @0, @4);
5557     }
5558     (if ((cmp == LT_EXPR || cmp == LE_EXPR)
5559          && code == MIN_EXPR
5560          && integer_nonzerop (fold_build2 (LE_EXPR, boolean_type_node, @3, @4)))
5561      (min @2 @4)
5562      (if ((cmp == GT_EXPR || cmp == GE_EXPR)
5563           && code == MAX_EXPR
5564           && integer_nonzerop (fold_build2 (GE_EXPR, boolean_type_node, @3, @4)))
5565       (max @2 @4))))))
5567 #if GIMPLE
5568 /* These patterns should be after min/max detection as simplifications
5569    of `(type)(zero_one ==/!= 0)` to `(type)(zero_one)`
5570    and `(type)(zero_one^1)` are not done yet.  See PR 110637.
5571    Even without those, reaching min/max/and/ior faster is better.  */
5572 (simplify
5573  (cond @0 zero_one_valued_p@1 zero_one_valued_p@2)
5574  (switch
5575   /* bool0 ? bool1 : 0 -> bool0 & bool1 */
5576   (if (integer_zerop (@2))
5577    (bit_and (convert @0) @1))
5578   /* bool0 ? 0 : bool2 -> (bool0^1) & bool2 */
5579   (if (integer_zerop (@1))
5580    (bit_and (bit_xor (convert @0) { build_one_cst (type); } ) @2))
5581   /* bool0 ? 1 : bool2 -> bool0 | bool2 */
5582   (if (integer_onep (@1))
5583    (bit_ior (convert @0) @2))
5584   /* bool0 ? bool1 : 1 -> (bool0^1) | bool1 */
5585   (if (integer_onep (@2))
5586    (bit_ior (bit_xor (convert @0) @2) @1))
5589 #endif
5591 /* X != C1 ? -X : C2 simplifies to -X when -C1 == C2.  */
5592 (simplify
5593  (cond (ne @0 INTEGER_CST@1) (negate@3 @0) INTEGER_CST@2)
5594  (if (!TYPE_SATURATING (type)
5595       && (TYPE_OVERFLOW_WRAPS (type)
5596           || !wi::only_sign_bit_p (wi::to_wide (@1)))
5597       && wi::eq_p (wi::neg (wi::to_wide (@1)), wi::to_wide (@2)))
5598   @3))
5600 /* X != C1 ? ~X : C2 simplifies to ~X when ~C1 == C2.  */
5601 (simplify
5602  (cond (ne @0 INTEGER_CST@1) (bit_not@3 @0) INTEGER_CST@2)
5603  (if (wi::eq_p (wi::bit_not (wi::to_wide (@1)), wi::to_wide (@2)))
5604   @3))
5606 /* (X + 1) > Y ? -X : 1 simplifies to X >= Y ? -X : 1 when
5607    X is unsigned, as when X + 1 overflows, X is -1, so -X == 1.  */
5608 (simplify
5609  (cond (gt (plus @0 integer_onep) @1) (negate @0) integer_onep@2)
5610  (if (TYPE_UNSIGNED (type))
5611   (cond (ge @0 @1) (negate @0) @2)))
5613 (for cnd (cond vec_cond)
5614  /* A ? B : (A ? X : C) -> A ? B : C.  */
5615  (simplify
5616   (cnd @0 (cnd @0 @1 @2) @3)
5617   (cnd @0 @1 @3))
5618  (simplify
5619   (cnd @0 @1 (cnd @0 @2 @3))
5620   (cnd @0 @1 @3))
5621  /* A ? B : (!A ? C : X) -> A ? B : C.  */
5622  /* ???  This matches embedded conditions open-coded because genmatch
5623     would generate matching code for conditions in separate stmts only.
5624     The following is still important to merge then and else arm cases
5625     from if-conversion.  */
5626  (simplify
5627   (cnd @0 @1 (cnd @2 @3 @4))
5628   (if (inverse_conditions_p (@0, @2))
5629    (cnd @0 @1 @3)))
5630  (simplify
5631   (cnd @0 (cnd @1 @2 @3) @4)
5632   (if (inverse_conditions_p (@0, @1))
5633    (cnd @0 @3 @4)))
5635  /* A ? B : B -> B.  */
5636  (simplify
5637   (cnd @0 @1 @1)
5638   @1)
5640  /* !A ? B : C -> A ? C : B.  */
5641  (simplify
5642   (cnd (logical_inverted_value truth_valued_p@0) @1 @2)
5643   (cnd @0 @2 @1)))
5645 /* abs/negative simplifications moved from fold_cond_expr_with_comparison,
5646    Need to handle (A - B) case as fold_cond_expr_with_comparison does.
5647    Need to handle UN* comparisons.
5649    None of these transformations work for modes with signed
5650    zeros.  If A is +/-0, the first two transformations will
5651    change the sign of the result (from +0 to -0, or vice
5652    versa).  The last four will fix the sign of the result,
5653    even though the original expressions could be positive or
5654    negative, depending on the sign of A.
5656    Note that all these transformations are correct if A is
5657    NaN, since the two alternatives (A and -A) are also NaNs.  */
5659 (for cnd (cond vec_cond)
5660  /* A == 0 ? A : -A    same as -A */
5661  (for cmp (eq uneq)
5662   (simplify
5663    (cnd (cmp @0 zerop) @0 (negate@1 @0))
5664     (if (!HONOR_SIGNED_ZEROS (type))
5665      @1))
5666   (simplify
5667    (cnd (cmp @0 zerop) zerop (negate@1 @0))
5668     (if (!HONOR_SIGNED_ZEROS (type))
5669      @1))
5671  /* A != 0 ? A : -A    same as A */
5672  (for cmp (ne ltgt)
5673   (simplify
5674    (cnd (cmp @0 zerop) @0 (negate @0))
5675     (if (!HONOR_SIGNED_ZEROS (type))
5676      @0))
5677   (simplify
5678    (cnd (cmp @0 zerop) @0 integer_zerop)
5679     (if (!HONOR_SIGNED_ZEROS (type))
5680      @0))
5682  /* A >=/> 0 ? A : -A    same as abs (A) */
5683  (for cmp (ge gt)
5684   (simplify
5685    (cnd (cmp @0 zerop) @0 (negate @0))
5686     (if (!HONOR_SIGNED_ZEROS (type)
5687          && !TYPE_UNSIGNED (type))
5688      (abs @0))))
5689  /* A <=/< 0 ? A : -A    same as -abs (A) */
5690  (for cmp (le lt)
5691   (simplify
5692    (cnd (cmp @0 zerop) @0 (negate @0))
5693     (if (!HONOR_SIGNED_ZEROS (type)
5694          && !TYPE_UNSIGNED (type))
5695      (if (ANY_INTEGRAL_TYPE_P (type)
5696           && !TYPE_OVERFLOW_WRAPS (type))
5697       (with {
5698         tree utype = unsigned_type_for (type);
5699        }
5700        (convert (negate (absu:utype @0))))
5701        (negate (abs @0)))))
5705 /* -(type)!A -> (type)A - 1.  */
5706 (simplify
5707  (negate (convert?:s (logical_inverted_value:s @0)))
5708  (if (INTEGRAL_TYPE_P (type)
5709       && TREE_CODE (type) != BOOLEAN_TYPE
5710       && TYPE_PRECISION (type) > 1
5711       && TREE_CODE (@0) == SSA_NAME
5712       && ssa_name_has_boolean_range (@0))
5713   (plus (convert:type @0) { build_all_ones_cst (type); })))
5715 /* A + (B vcmp C ? 1 : 0) -> A - (B vcmp C ? -1 : 0), since vector comparisons
5716    return all -1 or all 0 results.  */
5717 /* ??? We could instead convert all instances of the vec_cond to negate,
5718    but that isn't necessarily a win on its own.  */
5719 (simplify
5720  (plus:c @3 (view_convert? (vec_cond:s @0 integer_each_onep@1 integer_zerop@2)))
5721  (if (VECTOR_TYPE_P (type)
5722       && known_eq (TYPE_VECTOR_SUBPARTS (type),
5723                    TYPE_VECTOR_SUBPARTS (TREE_TYPE (@1)))
5724       && (TYPE_MODE (TREE_TYPE (type))
5725           == TYPE_MODE (TREE_TYPE (TREE_TYPE (@1)))))
5726   (minus @3 (view_convert (vec_cond @0 (negate @1) @2)))))
5728 /* ... likewise A - (B vcmp C ? 1 : 0) -> A + (B vcmp C ? -1 : 0).  */
5729 (simplify
5730  (minus @3 (view_convert? (vec_cond:s @0 integer_each_onep@1 integer_zerop@2)))
5731  (if (VECTOR_TYPE_P (type)
5732       && known_eq (TYPE_VECTOR_SUBPARTS (type),
5733                    TYPE_VECTOR_SUBPARTS (TREE_TYPE (@1)))
5734       && (TYPE_MODE (TREE_TYPE (type))
5735           == TYPE_MODE (TREE_TYPE (TREE_TYPE (@1)))))
5736   (plus @3 (view_convert (vec_cond @0 (negate @1) @2)))))
5739 /* Simplifications of comparisons.  */
5741 /* See if we can reduce the magnitude of a constant involved in a
5742    comparison by changing the comparison code.  This is a canonicalization
5743    formerly done by maybe_canonicalize_comparison_1.  */
5744 (for cmp  (le gt)
5745      acmp (lt ge)
5746  (simplify
5747   (cmp @0 uniform_integer_cst_p@1)
5748   (with { tree cst = uniform_integer_cst_p (@1); }
5749    (if (tree_int_cst_sgn (cst) == -1)
5750      (acmp @0 { build_uniform_cst (TREE_TYPE (@1),
5751                                    wide_int_to_tree (TREE_TYPE (cst),
5752                                                      wi::to_wide (cst)
5753                                                      + 1)); })))))
5754 (for cmp  (ge lt)
5755      acmp (gt le)
5756  (simplify
5757   (cmp @0 uniform_integer_cst_p@1)
5758   (with { tree cst = uniform_integer_cst_p (@1); }
5759    (if (tree_int_cst_sgn (cst) == 1)
5760     (acmp @0 { build_uniform_cst (TREE_TYPE (@1),
5761                                   wide_int_to_tree (TREE_TYPE (cst),
5762                                   wi::to_wide (cst) - 1)); })))))
5764 /* We can simplify a logical negation of a comparison to the
5765    inverted comparison.  As we cannot compute an expression
5766    operator using invert_tree_comparison we have to simulate
5767    that with expression code iteration.  */
5768 (for cmp (tcc_comparison)
5769      icmp (inverted_tcc_comparison)
5770      ncmp (inverted_tcc_comparison_with_nans)
5771  /* Ideally we'd like to combine the following two patterns
5772     and handle some more cases by using
5773       (logical_inverted_value (cmp @0 @1))
5774     here but for that genmatch would need to "inline" that.
5775     For now implement what forward_propagate_comparison did.  */
5776  (simplify
5777   (bit_not (cmp @0 @1))
5778   (if (VECTOR_TYPE_P (type)
5779        || (INTEGRAL_TYPE_P (type) && TYPE_PRECISION (type) == 1))
5780    /* Comparison inversion may be impossible for trapping math,
5781       invert_tree_comparison will tell us.  But we can't use
5782       a computed operator in the replacement tree thus we have
5783       to play the trick below.  */
5784    (with { enum tree_code ic = invert_tree_comparison
5785              (cmp, HONOR_NANS (@0)); }
5786     (if (ic == icmp)
5787      (icmp @0 @1)
5788      (if (ic == ncmp)
5789       (ncmp @0 @1))))))
5790  (simplify
5791   (bit_xor (cmp @0 @1) integer_truep)
5792   (with { enum tree_code ic = invert_tree_comparison
5793             (cmp, HONOR_NANS (@0)); }
5794    (if (ic == icmp)
5795     (icmp @0 @1)
5796     (if (ic == ncmp)
5797      (ncmp @0 @1)))))
5798  /* The following bits are handled by fold_binary_op_with_conditional_arg.  */
5799  (simplify
5800   (ne (cmp@2 @0 @1) integer_zerop)
5801   (if (types_match (type, TREE_TYPE (@2)))
5802    (cmp @0 @1)))
5803  (simplify
5804   (eq (cmp@2 @0 @1) integer_truep)
5805   (if (types_match (type, TREE_TYPE (@2)))
5806    (cmp @0 @1)))
5807  (simplify
5808   (ne (cmp@2 @0 @1) integer_truep)
5809   (if (types_match (type, TREE_TYPE (@2)))
5810    (with { enum tree_code ic = invert_tree_comparison
5811              (cmp, HONOR_NANS (@0)); }
5812     (if (ic == icmp)
5813      (icmp @0 @1)
5814      (if (ic == ncmp)
5815       (ncmp @0 @1))))))
5816  (simplify
5817   (eq (cmp@2 @0 @1) integer_zerop)
5818   (if (types_match (type, TREE_TYPE (@2)))
5819    (with { enum tree_code ic = invert_tree_comparison
5820              (cmp, HONOR_NANS (@0)); }
5821     (if (ic == icmp)
5822      (icmp @0 @1)
5823      (if (ic == ncmp)
5824       (ncmp @0 @1)))))))
5826 /* Transform comparisons of the form X - Y CMP 0 to X CMP Y.
5827    ??? The transformation is valid for the other operators if overflow
5828    is undefined for the type, but performing it here badly interacts
5829    with the transformation in fold_cond_expr_with_comparison which
5830    attempts to synthetize ABS_EXPR.  */
5831 (for cmp (eq ne)
5832  (for sub (minus pointer_diff)
5833   (simplify
5834    (cmp (sub@2 @0 @1) integer_zerop)
5835    (if (single_use (@2))
5836     (cmp @0 @1)))))
5838 /* Simplify (x < 0) ^ (y < 0) to (x ^ y) < 0 and
5839    (x >= 0) ^ (y >= 0) to (x ^ y) < 0.  */
5840 (for cmp (lt ge)
5841  (simplify
5842   (bit_xor (cmp:s @0 integer_zerop) (cmp:s @1 integer_zerop))
5843    (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
5844         && !TYPE_UNSIGNED (TREE_TYPE (@0))
5845         && types_match (TREE_TYPE (@0), TREE_TYPE (@1)))
5846     (lt (bit_xor @0 @1) { build_zero_cst (TREE_TYPE (@0)); }))))
5847 /* Simplify (x < 0) ^ (y >= 0) to (x ^ y) >= 0 and
5848    (x >= 0) ^ (y < 0) to (x ^ y) >= 0.  */
5849 (simplify
5850  (bit_xor:c (lt:s @0 integer_zerop) (ge:s @1 integer_zerop))
5851   (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
5852        && !TYPE_UNSIGNED (TREE_TYPE (@0))
5853        && types_match (TREE_TYPE (@0), TREE_TYPE (@1)))
5854    (ge (bit_xor @0 @1) { build_zero_cst (TREE_TYPE (@0)); })))
5856 /* Transform comparisons of the form X * C1 CMP 0 to X CMP 0 in the
5857    signed arithmetic case.  That form is created by the compiler
5858    often enough for folding it to be of value.  One example is in
5859    computing loop trip counts after Operator Strength Reduction.  */
5860 (for cmp (simple_comparison)
5861      scmp (swapped_simple_comparison)
5862  (simplify
5863   (cmp (mult@3 @0 INTEGER_CST@1) integer_zerop@2)
5864   /* Handle unfolded multiplication by zero.  */
5865   (if (integer_zerop (@1))
5866    (cmp @1 @2)
5867    (if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (@0))
5868         && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (@0))
5869         && single_use (@3))
5870     /* If @1 is negative we swap the sense of the comparison.  */
5871     (if (tree_int_cst_sgn (@1) < 0)
5872      (scmp @0 @2)
5873      (cmp @0 @2))))))
5875 /* For integral types with undefined overflow fold
5876    x * C1 == C2 into x == C2 / C1 or false.
5877    If overflow wraps and C1 is odd, simplify to x == C2 / C1 in the ring
5878    Z / 2^n Z.  */
5879 (for cmp (eq ne)
5880  (simplify
5881   (cmp (mult @0 INTEGER_CST@1) INTEGER_CST@2)
5882   (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
5883        && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (@0))
5884        && wi::to_wide (@1) != 0)
5885    (with { widest_int quot; }
5886     (if (wi::multiple_of_p (wi::to_widest (@2), wi::to_widest (@1),
5887                             TYPE_SIGN (TREE_TYPE (@0)), &quot))
5888      (cmp @0 { wide_int_to_tree (TREE_TYPE (@0), quot); })
5889      { constant_boolean_node (cmp == NE_EXPR, type); }))
5890    (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
5891         && TYPE_OVERFLOW_WRAPS (TREE_TYPE (@0))
5892         && (wi::bit_and (wi::to_wide (@1), 1) == 1))
5893     (cmp @0
5894      {
5895        tree itype = TREE_TYPE (@0);
5896        int p = TYPE_PRECISION (itype);
5897        wide_int m = wi::one (p + 1) << p;
5898        wide_int a = wide_int::from (wi::to_wide (@1), p + 1, UNSIGNED);
5899        wide_int i = wide_int::from (wi::mod_inv (a, m),
5900                                     p, TYPE_SIGN (itype));
5901        wide_int_to_tree (itype, wi::mul (i, wi::to_wide (@2)));
5902      })))))
5904 /* Simplify comparison of something with itself.  For IEEE
5905    floating-point, we can only do some of these simplifications.  */
5906 (for cmp (eq ge le)
5907  (simplify
5908   (cmp @0 @0)
5909   (if (! FLOAT_TYPE_P (TREE_TYPE (@0))
5910        || ! tree_expr_maybe_nan_p (@0))
5911    { constant_boolean_node (true, type); }
5912    (if (cmp != EQ_EXPR
5913         /* With -ftrapping-math conversion to EQ loses an exception.  */
5914         && (! FLOAT_TYPE_P (TREE_TYPE (@0))
5915             || ! flag_trapping_math))
5916     (eq @0 @0)))))
5917 (for cmp (ne gt lt)
5918  (simplify
5919   (cmp @0 @0)
5920   (if (cmp != NE_EXPR
5921        || ! FLOAT_TYPE_P (TREE_TYPE (@0))
5922        || ! tree_expr_maybe_nan_p (@0))
5923    { constant_boolean_node (false, type); })))
5924 (for cmp (unle unge uneq)
5925  (simplify
5926   (cmp @0 @0)
5927   { constant_boolean_node (true, type); }))
5928 (for cmp (unlt ungt)
5929  (simplify
5930   (cmp @0 @0)
5931   (unordered @0 @0)))
5932 (simplify
5933  (ltgt @0 @0)
5934  (if (!flag_trapping_math || !tree_expr_maybe_nan_p (@0))
5935   { constant_boolean_node (false, type); }))
5937 /* x == ~x -> false */
5938 /* x != ~x -> true */
5939 (for cmp (eq ne)
5940  (simplify
5941   (cmp:c @0 (bit_not @0))
5942   { constant_boolean_node (cmp == NE_EXPR, type); }))
5944 /* Fold ~X op ~Y as Y op X.  */
5945 (for cmp (simple_comparison)
5946  (simplify
5947   (cmp (bit_not@2 @0) (bit_not@3 @1))
5948   (if (single_use (@2) && single_use (@3))
5949    (cmp @1 @0))))
5951 /* Fold ~X op C as X op' ~C, where op' is the swapped comparison.  */
5952 (for cmp (simple_comparison)
5953      scmp (swapped_simple_comparison)
5954  (simplify
5955   (cmp (bit_not@2 @0) CONSTANT_CLASS_P@1)
5956   (if (single_use (@2)
5957        && (TREE_CODE (@1) == INTEGER_CST || TREE_CODE (@1) == VECTOR_CST))
5958    (scmp @0 (bit_not @1)))))
5960 (for cmp (simple_comparison)
5961  (simplify
5962   (cmp @0 REAL_CST@1)
5963   /* IEEE doesn't distinguish +0 and -0 in comparisons.  */
5964   (switch
5965    /* a CMP (-0) -> a CMP 0  */
5966    (if (REAL_VALUE_MINUS_ZERO (TREE_REAL_CST (@1)))
5967     (cmp @0 { build_real (TREE_TYPE (@1), dconst0); }))
5968    /* (-0) CMP b -> 0 CMP b.  */
5969    (if (TREE_CODE (@0) == REAL_CST
5970         && REAL_VALUE_MINUS_ZERO (TREE_REAL_CST (@0)))
5971     (cmp { build_real (TREE_TYPE (@0), dconst0); } @1))
5972    /* x != NaN is always true, other ops are always false.  */
5973    (if (REAL_VALUE_ISNAN (TREE_REAL_CST (@1))
5974         && (cmp == EQ_EXPR || cmp == NE_EXPR || !flag_trapping_math)
5975         && !tree_expr_signaling_nan_p (@1)
5976         && !tree_expr_maybe_signaling_nan_p (@0))
5977     { constant_boolean_node (cmp == NE_EXPR, type); })
5978    /* NaN != y is always true, other ops are always false.  */
5979    (if (TREE_CODE (@0) == REAL_CST
5980         && REAL_VALUE_ISNAN (TREE_REAL_CST (@0))
5981         && (cmp == EQ_EXPR || cmp == NE_EXPR || !flag_trapping_math)
5982         && !tree_expr_signaling_nan_p (@0)
5983         && !tree_expr_signaling_nan_p (@1))
5984     { constant_boolean_node (cmp == NE_EXPR, type); })
5985    /* Fold comparisons against infinity.  */
5986    (if (REAL_VALUE_ISINF (TREE_REAL_CST (@1))
5987         && MODE_HAS_INFINITIES (TYPE_MODE (TREE_TYPE (@1))))
5988     (with
5989      {
5990        REAL_VALUE_TYPE max;
5991        enum tree_code code = cmp;
5992        bool neg = REAL_VALUE_NEGATIVE (TREE_REAL_CST (@1));
5993        if (neg)
5994          code = swap_tree_comparison (code);
5995      }
5996      (switch
5997       /* x > +Inf is always false, if we ignore NaNs or exceptions.  */
5998       (if (code == GT_EXPR
5999            && !(HONOR_NANS (@0) && flag_trapping_math))
6000        { constant_boolean_node (false, type); })
6001       (if (code == LE_EXPR)
6002        /* x <= +Inf is always true, if we don't care about NaNs.  */
6003        (if (! HONOR_NANS (@0))
6004         { constant_boolean_node (true, type); }
6005         /* x <= +Inf is the same as x == x, i.e. !isnan(x), but this loses
6006            an "invalid" exception.  */
6007         (if (!flag_trapping_math)
6008          (eq @0 @0))))
6009       /* x == +Inf and x >= +Inf are always equal to x > DBL_MAX, but
6010          for == this introduces an exception for x a NaN.  */
6011       (if ((code == EQ_EXPR && !(HONOR_NANS (@0) && flag_trapping_math))
6012            || code == GE_EXPR)
6013        (with { real_maxval (&max, neg, TYPE_MODE (TREE_TYPE (@0))); }
6014         (if (neg)
6015          (lt @0 { build_real (TREE_TYPE (@0), max); })
6016          (gt @0 { build_real (TREE_TYPE (@0), max); }))))
6017       /* x < +Inf is always equal to x <= DBL_MAX.  */
6018       (if (code == LT_EXPR)
6019        (with { real_maxval (&max, neg, TYPE_MODE (TREE_TYPE (@0))); }
6020         (if (neg)
6021          (ge @0 { build_real (TREE_TYPE (@0), max); })
6022          (le @0 { build_real (TREE_TYPE (@0), max); }))))
6023       /* x != +Inf is always equal to !(x > DBL_MAX), but this introduces
6024          an exception for x a NaN so use an unordered comparison.  */
6025       (if (code == NE_EXPR)
6026        (with { real_maxval (&max, neg, TYPE_MODE (TREE_TYPE (@0))); }
6027         (if (! HONOR_NANS (@0))
6028          (if (neg)
6029           (ge @0 { build_real (TREE_TYPE (@0), max); })
6030           (le @0 { build_real (TREE_TYPE (@0), max); }))
6031          (if (neg)
6032           (unge @0 { build_real (TREE_TYPE (@0), max); })
6033           (unle @0 { build_real (TREE_TYPE (@0), max); }))))))))))
6035  /* If this is a comparison of a real constant with a PLUS_EXPR
6036     or a MINUS_EXPR of a real constant, we can convert it into a
6037     comparison with a revised real constant as long as no overflow
6038     occurs when unsafe_math_optimizations are enabled.  */
6039  (if (flag_unsafe_math_optimizations)
6040   (for op (plus minus)
6041    (simplify
6042     (cmp (op @0 REAL_CST@1) REAL_CST@2)
6043     (with
6044      {
6045        tree tem = const_binop (op == PLUS_EXPR ? MINUS_EXPR : PLUS_EXPR,
6046                                TREE_TYPE (@1), @2, @1);
6047      }
6048      (if (tem && !TREE_OVERFLOW (tem))
6049       (cmp @0 { tem; }))))))
6051  /* Likewise, we can simplify a comparison of a real constant with
6052     a MINUS_EXPR whose first operand is also a real constant, i.e.
6053     (c1 - x) < c2 becomes x > c1-c2.  Reordering is allowed on
6054     floating-point types only if -fassociative-math is set.  */
6055  (if (flag_associative_math)
6056   (simplify
6057    (cmp (minus REAL_CST@0 @1) REAL_CST@2)
6058    (with { tree tem = const_binop (MINUS_EXPR, TREE_TYPE (@1), @0, @2); }
6059     (if (tem && !TREE_OVERFLOW (tem))
6060      (cmp { tem; } @1)))))
6062  /* Fold comparisons against built-in math functions.  */
6063  (if (flag_unsafe_math_optimizations && ! flag_errno_math)
6064   (for sq (SQRT)
6065    (simplify
6066     (cmp (sq @0) REAL_CST@1)
6067     (switch
6068      (if (REAL_VALUE_NEGATIVE (TREE_REAL_CST (@1)))
6069       (switch
6070        /* sqrt(x) < y is always false, if y is negative.  */
6071        (if (cmp == EQ_EXPR || cmp == LT_EXPR || cmp == LE_EXPR)
6072         { constant_boolean_node (false, type); })
6073        /* sqrt(x) > y is always true, if y is negative and we
6074           don't care about NaNs, i.e. negative values of x.  */
6075        (if (cmp == NE_EXPR || !HONOR_NANS (@0))
6076         { constant_boolean_node (true, type); })
6077        /* sqrt(x) > y is the same as x >= 0, if y is negative.  */
6078        (ge @0 { build_real (TREE_TYPE (@0), dconst0); })))
6079      (if (real_equal (TREE_REAL_CST_PTR (@1), &dconst0))
6080       (switch
6081        /* sqrt(x) < 0 is always false.  */
6082        (if (cmp == LT_EXPR)
6083         { constant_boolean_node (false, type); })
6084        /* sqrt(x) >= 0 is always true if we don't care about NaNs.  */
6085        (if (cmp == GE_EXPR && !HONOR_NANS (@0))
6086         { constant_boolean_node (true, type); })
6087        /* sqrt(x) <= 0 -> x == 0.  */
6088        (if (cmp == LE_EXPR)
6089         (eq @0 @1))
6090        /* Otherwise sqrt(x) cmp 0 -> x cmp 0.  Here cmp can be >=, >,
6091           == or !=.  In the last case:
6093             (sqrt(x) != 0) == (NaN != 0) == true == (x != 0)
6095           if x is negative or NaN.  Due to -funsafe-math-optimizations,
6096           the results for other x follow from natural arithmetic.  */
6097        (cmp @0 @1)))
6098      (if ((cmp == LT_EXPR
6099            || cmp == LE_EXPR
6100            || cmp == GT_EXPR
6101            || cmp == GE_EXPR)
6102           && !REAL_VALUE_ISNAN (TREE_REAL_CST (@1))
6103           /* Give up for -frounding-math.  */
6104           && !HONOR_SIGN_DEPENDENT_ROUNDING (TREE_TYPE (@0)))
6105       (with
6106        {
6107          REAL_VALUE_TYPE c2;
6108          enum tree_code ncmp = cmp;
6109          const real_format *fmt
6110            = REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (@0)));
6111          real_arithmetic (&c2, MULT_EXPR,
6112                           &TREE_REAL_CST (@1), &TREE_REAL_CST (@1));
6113          real_convert (&c2, fmt, &c2);
6114          /* See PR91734: if c2 is inexact and sqrt(c2) < c (or sqrt(c2) >= c),
6115             then change LT_EXPR into LE_EXPR or GE_EXPR into GT_EXPR.  */
6116          if (!REAL_VALUE_ISINF (c2))
6117            {
6118              tree c3 = fold_const_call (CFN_SQRT, TREE_TYPE (@0),
6119                                         build_real (TREE_TYPE (@0), c2));
6120              if (c3 == NULL_TREE || TREE_CODE (c3) != REAL_CST)
6121                ncmp = ERROR_MARK;
6122              else if ((cmp == LT_EXPR || cmp == GE_EXPR)
6123                       && real_less (&TREE_REAL_CST (c3), &TREE_REAL_CST (@1)))
6124                ncmp = cmp == LT_EXPR ? LE_EXPR : GT_EXPR;
6125              else if ((cmp == LE_EXPR || cmp == GT_EXPR)
6126                       && real_less (&TREE_REAL_CST (@1), &TREE_REAL_CST (c3)))
6127                ncmp = cmp == LE_EXPR ? LT_EXPR : GE_EXPR;
6128              else
6129                {
6130                  /* With rounding to even, sqrt of up to 3 different values
6131                     gives the same normal result, so in some cases c2 needs
6132                     to be adjusted.  */
6133                  REAL_VALUE_TYPE c2alt, tow;
6134                  if (cmp == LT_EXPR || cmp == GE_EXPR)
6135                    tow = dconst0;
6136                  else
6137                    tow = dconstinf;
6138                  real_nextafter (&c2alt, fmt, &c2, &tow);
6139                  real_convert (&c2alt, fmt, &c2alt);
6140                  if (REAL_VALUE_ISINF (c2alt))
6141                    ncmp = ERROR_MARK;
6142                  else
6143                    {
6144                      c3 = fold_const_call (CFN_SQRT, TREE_TYPE (@0),
6145                                            build_real (TREE_TYPE (@0), c2alt));
6146                      if (c3 == NULL_TREE || TREE_CODE (c3) != REAL_CST)
6147                        ncmp = ERROR_MARK;
6148                      else if (real_equal (&TREE_REAL_CST (c3),
6149                                           &TREE_REAL_CST (@1)))
6150                        c2 = c2alt;
6151                    }
6152                }
6153            }
6154        }
6155        (if (cmp == GT_EXPR || cmp == GE_EXPR)
6156         (if (REAL_VALUE_ISINF (c2))
6157          /* sqrt(x) > y is x == +Inf, when y is very large.  */
6158          (if (HONOR_INFINITIES (@0))
6159           (eq @0 { build_real (TREE_TYPE (@0), c2); })
6160           { constant_boolean_node (false, type); })
6161          /* sqrt(x) > c is the same as x > c*c.  */
6162          (if (ncmp != ERROR_MARK)
6163           (if (ncmp == GE_EXPR)
6164            (ge @0 { build_real (TREE_TYPE (@0), c2); })
6165            (gt @0 { build_real (TREE_TYPE (@0), c2); }))))
6166         /* else if (cmp == LT_EXPR || cmp == LE_EXPR)  */
6167         (if (REAL_VALUE_ISINF (c2))
6168          (switch
6169           /* sqrt(x) < y is always true, when y is a very large
6170              value and we don't care about NaNs or Infinities.  */
6171           (if (! HONOR_NANS (@0) && ! HONOR_INFINITIES (@0))
6172            { constant_boolean_node (true, type); })
6173           /* sqrt(x) < y is x != +Inf when y is very large and we
6174              don't care about NaNs.  */
6175           (if (! HONOR_NANS (@0))
6176            (ne @0 { build_real (TREE_TYPE (@0), c2); }))
6177           /* sqrt(x) < y is x >= 0 when y is very large and we
6178              don't care about Infinities.  */
6179           (if (! HONOR_INFINITIES (@0))
6180            (ge @0 { build_real (TREE_TYPE (@0), dconst0); }))
6181           /* sqrt(x) < y is x >= 0 && x != +Inf, when y is large.  */
6182           (if (GENERIC)
6183            (truth_andif
6184             (ge @0 { build_real (TREE_TYPE (@0), dconst0); })
6185             (ne @0 { build_real (TREE_TYPE (@0), c2); }))))
6186          /* sqrt(x) < c is the same as x < c*c, if we ignore NaNs.  */
6187          (if (ncmp != ERROR_MARK && ! HONOR_NANS (@0))
6188           (if (ncmp == LT_EXPR)
6189            (lt @0 { build_real (TREE_TYPE (@0), c2); })
6190            (le @0 { build_real (TREE_TYPE (@0), c2); }))
6191           /* sqrt(x) < c is the same as x >= 0 && x < c*c.  */
6192           (if (ncmp != ERROR_MARK && GENERIC)
6193            (if (ncmp == LT_EXPR)
6194             (truth_andif
6195              (ge @0 { build_real (TREE_TYPE (@0), dconst0); })
6196              (lt @0 { build_real (TREE_TYPE (@0), c2); }))
6197             (truth_andif
6198              (ge @0 { build_real (TREE_TYPE (@0), dconst0); })
6199              (le @0 { build_real (TREE_TYPE (@0), c2); })))))))))))
6200    /* Transform sqrt(x) cmp sqrt(y) -> x cmp y.  */
6201    (simplify
6202     (cmp (sq @0) (sq @1))
6203       (if (! HONOR_NANS (@0))
6204         (cmp @0 @1))))))
6206 /* Optimize various special cases of (FTYPE) N CMP (FTYPE) M.  */
6207 (for cmp  (lt le eq ne ge gt unordered ordered unlt unle ungt unge uneq ltgt)
6208      icmp (lt le eq ne ge gt unordered ordered lt   le   gt   ge   eq   ne)
6209  (simplify
6210   (cmp (float@0 @1) (float @2))
6211    (if (SCALAR_FLOAT_TYPE_P (TREE_TYPE (@0))
6212         && ! DECIMAL_FLOAT_TYPE_P (TREE_TYPE (@0)))
6213     (with
6214      {
6215        format_helper fmt (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (@0))));
6216        tree type1 = TREE_TYPE (@1);
6217        bool type1_signed_p = TYPE_SIGN (type1) == SIGNED;
6218        tree type2 = TREE_TYPE (@2);
6219        bool type2_signed_p = TYPE_SIGN (type2) == SIGNED;
6220      }
6221      (if (fmt.can_represent_integral_type_p (type1)
6222           && fmt.can_represent_integral_type_p (type2))
6223       (if (cmp == ORDERED_EXPR || cmp == UNORDERED_EXPR)
6224        { constant_boolean_node (cmp == ORDERED_EXPR, type); }
6225        (if (TYPE_PRECISION (type1) > TYPE_PRECISION (type2)
6226             && type1_signed_p >= type2_signed_p)
6227         (icmp @1 (convert @2))
6228         (if (TYPE_PRECISION (type1) < TYPE_PRECISION (type2)
6229              && type1_signed_p <= type2_signed_p)
6230          (icmp (convert:type2 @1) @2)
6231          (if (TYPE_PRECISION (type1) == TYPE_PRECISION (type2)
6232               && type1_signed_p == type2_signed_p)
6233           (icmp @1 @2))))))))))
6235 /* Optimize various special cases of (FTYPE) N CMP CST.  */
6236 (for cmp  (lt le eq ne ge gt)
6237      icmp (le le eq ne ge ge)
6238  (simplify
6239   (cmp (float @0) REAL_CST@1)
6240    (if (SCALAR_FLOAT_TYPE_P (TREE_TYPE (@1))
6241         && ! DECIMAL_FLOAT_TYPE_P (TREE_TYPE (@1)))
6242     (with
6243      {
6244        tree itype = TREE_TYPE (@0);
6245        format_helper fmt (REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (@1))));
6246        const REAL_VALUE_TYPE *cst = TREE_REAL_CST_PTR (@1);
6247        /* Be careful to preserve any potential exceptions due to
6248           NaNs.  qNaNs are ok in == or != context.
6249           TODO: relax under -fno-trapping-math or
6250           -fno-signaling-nans.  */
6251        bool exception_p
6252          = real_isnan (cst) && (cst->signalling
6253                                 || (cmp != EQ_EXPR && cmp != NE_EXPR));
6254      }
6255      /* TODO: allow non-fitting itype and SNaNs when
6256         -fno-trapping-math.  */
6257      (if (fmt.can_represent_integral_type_p (itype) && ! exception_p)
6258       (with
6259        {
6260          signop isign = TYPE_SIGN (itype);
6261          REAL_VALUE_TYPE imin, imax;
6262          real_from_integer (&imin, fmt, wi::min_value (itype), isign);
6263          real_from_integer (&imax, fmt, wi::max_value (itype), isign);
6265          REAL_VALUE_TYPE icst;
6266          if (cmp == GT_EXPR || cmp == GE_EXPR)
6267            real_ceil (&icst, fmt, cst);
6268          else if (cmp == LT_EXPR || cmp == LE_EXPR)
6269            real_floor (&icst, fmt, cst);
6270          else
6271            real_trunc (&icst, fmt, cst);
6273          bool cst_int_p = !real_isnan (cst) && real_identical (&icst, cst);
6275          bool overflow_p = false;
6276          wide_int icst_val
6277            = real_to_integer (&icst, &overflow_p, TYPE_PRECISION (itype));
6278        }
6279        (switch
6280         /* Optimize cases when CST is outside of ITYPE's range.  */
6281         (if (real_compare (LT_EXPR, cst, &imin))
6282          { constant_boolean_node (cmp == GT_EXPR || cmp == GE_EXPR || cmp == NE_EXPR,
6283                                   type); })
6284         (if (real_compare (GT_EXPR, cst, &imax))
6285          { constant_boolean_node (cmp == LT_EXPR || cmp == LE_EXPR || cmp == NE_EXPR,
6286                                   type); })
6287         /* Remove cast if CST is an integer representable by ITYPE.  */
6288         (if (cst_int_p)
6289          (cmp @0 { gcc_assert (!overflow_p);
6290                    wide_int_to_tree (itype, icst_val); })
6291         )
6292         /* When CST is fractional, optimize
6293             (FTYPE) N == CST -> 0
6294             (FTYPE) N != CST -> 1.  */
6295         (if (cmp == EQ_EXPR || cmp == NE_EXPR)
6296          { constant_boolean_node (cmp == NE_EXPR, type); })
6297         /* Otherwise replace with sensible integer constant.  */
6298         (with
6299          {
6300            gcc_checking_assert (!overflow_p);
6301          }
6302          (icmp @0 { wide_int_to_tree (itype, icst_val); })))))))))
6304 /* Fold A /[ex] B CMP C to A CMP B * C.  */
6305 (for cmp (eq ne)
6306  (simplify
6307   (cmp (exact_div @0 @1) INTEGER_CST@2)
6308   (if (!integer_zerop (@1))
6309    (if (wi::to_wide (@2) == 0)
6310     (cmp @0 @2)
6311     (if (TREE_CODE (@1) == INTEGER_CST)
6312      (with
6313       {
6314         wi::overflow_type ovf;
6315         wide_int prod = wi::mul (wi::to_wide (@2), wi::to_wide (@1),
6316                                  TYPE_SIGN (TREE_TYPE (@1)), &ovf);
6317       }
6318       (if (ovf)
6319        { constant_boolean_node (cmp == NE_EXPR, type); }
6320        (cmp @0 { wide_int_to_tree (TREE_TYPE (@0), prod); }))))))))
6321 (for cmp (lt le gt ge)
6322  (simplify
6323   (cmp (exact_div @0 INTEGER_CST@1) INTEGER_CST@2)
6324   (if (wi::gt_p (wi::to_wide (@1), 0, TYPE_SIGN (TREE_TYPE (@1))))
6325    (with
6326     {
6327       wi::overflow_type ovf;
6328       wide_int prod = wi::mul (wi::to_wide (@2), wi::to_wide (@1),
6329                                TYPE_SIGN (TREE_TYPE (@1)), &ovf);
6330     }
6331     (if (ovf)
6332      { constant_boolean_node (wi::lt_p (wi::to_wide (@2), 0,
6333                                         TYPE_SIGN (TREE_TYPE (@2)))
6334                               != (cmp == LT_EXPR || cmp == LE_EXPR), type); }
6335      (cmp @0 { wide_int_to_tree (TREE_TYPE (@0), prod); }))))))
6337 /* Fold (size_t)(A /[ex] B) CMP C to (size_t)A CMP (size_t)B * C or A CMP' 0.
6339    For small C (less than max/B), this is (size_t)A CMP (size_t)B * C.
6340    For large C (more than min/B+2^size), this is also true, with the
6341    multiplication computed modulo 2^size.
6342    For intermediate C, this just tests the sign of A.  */
6343 (for cmp  (lt le gt ge)
6344      cmp2 (ge ge lt lt)
6345  (simplify
6346   (cmp (convert (exact_div @0 INTEGER_CST@1)) INTEGER_CST@2)
6347   (if (tree_nop_conversion_p (TREE_TYPE (@0), TREE_TYPE (@2))
6348        && TYPE_UNSIGNED (TREE_TYPE (@2)) && !TYPE_UNSIGNED (TREE_TYPE (@0))
6349        && wi::gt_p (wi::to_wide (@1), 0, TYPE_SIGN (TREE_TYPE (@1))))
6350    (with
6351     {
6352       tree utype = TREE_TYPE (@2);
6353       wide_int denom = wi::to_wide (@1);
6354       wide_int right = wi::to_wide (@2);
6355       wide_int smax = wi::sdiv_trunc (wi::max_value (TREE_TYPE (@0)), denom);
6356       wide_int smin = wi::sdiv_trunc (wi::min_value (TREE_TYPE (@0)), denom);
6357       bool small = wi::leu_p (right, smax);
6358       bool large = wi::geu_p (right, smin);
6359     }
6360     (if (small || large)
6361      (cmp (convert:utype @0) (mult @2 (convert @1)))
6362      (cmp2 @0 { build_zero_cst (TREE_TYPE (@0)); }))))))
6364 /* Unordered tests if either argument is a NaN.  */
6365 (simplify
6366  (bit_ior (unordered @0 @0) (unordered @1 @1))
6367  (if (types_match (@0, @1))
6368   (unordered @0 @1)))
6369 (simplify
6370  (bit_and (ordered @0 @0) (ordered @1 @1))
6371  (if (types_match (@0, @1))
6372   (ordered @0 @1)))
6373 (simplify
6374  (bit_ior:c (unordered @0 @0) (unordered:c@2 @0 @1))
6375  @2)
6376 (simplify
6377  (bit_and:c (ordered @0 @0) (ordered:c@2 @0 @1))
6378  @2)
6380 /* A & (2**N - 1) <= 2**K - 1 -> A & (2**N - 2**K) == 0
6381    A & (2**N - 1) >  2**K - 1 -> A & (2**N - 2**K) != 0
6383    Note that comparisons
6384      A & (2**N - 1) <  2**K   -> A & (2**N - 2**K) == 0
6385      A & (2**N - 1) >= 2**K   -> A & (2**N - 2**K) != 0
6386    will be canonicalized to above so there's no need to
6387    consider them here.
6388  */
6390 (for cmp (le gt)
6391      eqcmp (eq ne)
6392  (simplify
6393   (cmp (bit_and@0 @1 INTEGER_CST@2) INTEGER_CST@3)
6394   (if (INTEGRAL_TYPE_P (TREE_TYPE (@0)))
6395    (with
6396     {
6397      tree ty = TREE_TYPE (@0);
6398      unsigned prec = TYPE_PRECISION (ty);
6399      wide_int mask = wi::to_wide (@2, prec);
6400      wide_int rhs = wi::to_wide (@3, prec);
6401      signop sgn = TYPE_SIGN (ty);
6402     }
6403     (if ((mask & (mask + 1)) == 0 && wi::gt_p (rhs, 0, sgn)
6404          && (rhs & (rhs + 1)) == 0 && wi::ge_p (mask, rhs, sgn))
6405       (eqcmp (bit_and @1 { wide_int_to_tree (ty, mask - rhs); })
6406              { build_zero_cst (ty); }))))))
6408 /* -A CMP -B -> B CMP A.  */
6409 (for cmp (tcc_comparison)
6410      scmp (swapped_tcc_comparison)
6411  (simplify
6412   (cmp (negate @0) (negate @1))
6413   (if (FLOAT_TYPE_P (TREE_TYPE (@0))
6414        || (ANY_INTEGRAL_TYPE_P (TREE_TYPE (@0))
6415            && (cmp == EQ_EXPR
6416                || cmp == NE_EXPR
6417                || TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (@0)))))
6418    (scmp @0 @1)))
6419  (simplify
6420   (cmp (negate @0) CONSTANT_CLASS_P@1)
6421   (if (FLOAT_TYPE_P (TREE_TYPE (@0))
6422        || (ANY_INTEGRAL_TYPE_P (TREE_TYPE (@0))
6423            && (cmp == EQ_EXPR
6424                || cmp == NE_EXPR
6425                || TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (@0)))))
6426    (with { tree tem = const_unop (NEGATE_EXPR, TREE_TYPE (@0), @1); }
6427     (if (tem && !TREE_OVERFLOW (tem))
6428      (scmp @0 { tem; }))))))
6430 /* Convert ABS[U]_EXPR<x> == 0 or ABS[U]_EXPR<x> != 0 to x == 0 or x != 0.  */
6431 (for op (abs absu)
6432  (for eqne (eq ne)
6433   (simplify
6434    (eqne (op @0) zerop@1)
6435    (eqne @0 { build_zero_cst (TREE_TYPE (@0)); }))))
6437 /* From fold_sign_changed_comparison and fold_widened_comparison.
6438    FIXME: the lack of symmetry is disturbing.  */
6439 (for cmp (simple_comparison)
6440  (simplify
6441   (cmp (convert@0 @00) (convert?@1 @10))
6442   (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
6443        /* Disable this optimization if we're casting a function pointer
6444           type on targets that require function pointer canonicalization.  */
6445        && !(targetm.have_canonicalize_funcptr_for_compare ()
6446             && ((POINTER_TYPE_P (TREE_TYPE (@00))
6447                  && FUNC_OR_METHOD_TYPE_P (TREE_TYPE (TREE_TYPE (@00))))
6448                 || (POINTER_TYPE_P (TREE_TYPE (@10))
6449                     && FUNC_OR_METHOD_TYPE_P (TREE_TYPE (TREE_TYPE (@10))))))
6450        && single_use (@0))
6451    (if (TYPE_PRECISION (TREE_TYPE (@00)) == TYPE_PRECISION (TREE_TYPE (@0))
6452         && (TREE_CODE (@10) == INTEGER_CST
6453             || @1 != @10)
6454         && (TYPE_UNSIGNED (TREE_TYPE (@00)) == TYPE_UNSIGNED (TREE_TYPE (@0))
6455             || cmp == NE_EXPR
6456             || cmp == EQ_EXPR)
6457         && !POINTER_TYPE_P (TREE_TYPE (@00))
6458         /* (int)bool:32 != (int)uint is not the same as
6459            bool:32 != (bool:32)uint since boolean types only have two valid
6460            values independent of their precision.  */
6461         && (TREE_CODE (TREE_TYPE (@00)) != BOOLEAN_TYPE
6462             || TREE_CODE (TREE_TYPE (@10)) == BOOLEAN_TYPE))
6463     /* ???  The special-casing of INTEGER_CST conversion was in the original
6464        code and here to avoid a spurious overflow flag on the resulting
6465        constant which fold_convert produces.  */
6466     (if (TREE_CODE (@1) == INTEGER_CST)
6467      (cmp @00 { force_fit_type (TREE_TYPE (@00),
6468                                 wide_int::from (wi::to_wide (@1),
6469                                                 MAX (TYPE_PRECISION (TREE_TYPE (@1)),
6470                                                      TYPE_PRECISION (TREE_TYPE (@00))),
6471                                                 TYPE_SIGN (TREE_TYPE (@1))),
6472                                 0, TREE_OVERFLOW (@1)); })
6473      (cmp @00 (convert @1)))
6475     (if (TYPE_PRECISION (TREE_TYPE (@0)) > TYPE_PRECISION (TREE_TYPE (@00)))
6476      /* If possible, express the comparison in the shorter mode.  */
6477      (if ((cmp == EQ_EXPR || cmp == NE_EXPR
6478            || TYPE_UNSIGNED (TREE_TYPE (@0)) == TYPE_UNSIGNED (TREE_TYPE (@00))
6479            || (!TYPE_UNSIGNED (TREE_TYPE (@0))
6480                && TYPE_UNSIGNED (TREE_TYPE (@00))))
6481           && (types_match (TREE_TYPE (@10), TREE_TYPE (@00))
6482               || ((TYPE_PRECISION (TREE_TYPE (@00))
6483                    >= TYPE_PRECISION (TREE_TYPE (@10)))
6484                   && (TYPE_UNSIGNED (TREE_TYPE (@00))
6485                       == TYPE_UNSIGNED (TREE_TYPE (@10))))
6486               || (TREE_CODE (@10) == INTEGER_CST
6487                   && INTEGRAL_TYPE_P (TREE_TYPE (@00))
6488                   && int_fits_type_p (@10, TREE_TYPE (@00)))))
6489       (cmp @00 (convert @10))
6490       (if (TREE_CODE (@10) == INTEGER_CST
6491            && INTEGRAL_TYPE_P (TREE_TYPE (@00))
6492            && !int_fits_type_p (@10, TREE_TYPE (@00)))
6493        (with
6494         {
6495           tree min = lower_bound_in_type (TREE_TYPE (@10), TREE_TYPE (@00));
6496           tree max = upper_bound_in_type (TREE_TYPE (@10), TREE_TYPE (@00));
6497           bool above = integer_nonzerop (const_binop (LT_EXPR, type, max, @10));
6498           bool below = integer_nonzerop (const_binop (LT_EXPR, type, @10, min));
6499         }
6500         (if (above || below)
6501          (if (cmp == EQ_EXPR || cmp == NE_EXPR)
6502           { constant_boolean_node (cmp == EQ_EXPR ? false : true, type); }
6503           (if (cmp == LT_EXPR || cmp == LE_EXPR)
6504            { constant_boolean_node (above ? true : false, type); }
6505            (if (cmp == GT_EXPR || cmp == GE_EXPR)
6506             { constant_boolean_node (above ? false : true, type); })))))))))
6507    /* Fold (double)float1 CMP (double)float2 into float1 CMP float2.  */
6508    (if (FLOAT_TYPE_P (TREE_TYPE (@00))
6509         && (DECIMAL_FLOAT_TYPE_P (TREE_TYPE (@0))
6510             == DECIMAL_FLOAT_TYPE_P (TREE_TYPE (@00)))
6511         && (DECIMAL_FLOAT_TYPE_P (TREE_TYPE (@0))
6512             == DECIMAL_FLOAT_TYPE_P (TREE_TYPE (@10))))
6513     (with
6514      {
6515        tree type1 = TREE_TYPE (@10);
6516        if (TREE_CODE (@10) == REAL_CST && !DECIMAL_FLOAT_TYPE_P (type1))
6517          {
6518            REAL_VALUE_TYPE orig = TREE_REAL_CST (@10);
6519            if (TYPE_PRECISION (type1) > TYPE_PRECISION (float_type_node)
6520                && exact_real_truncate (TYPE_MODE (float_type_node), &orig))
6521              type1 = float_type_node;
6522            if (TYPE_PRECISION (type1) > TYPE_PRECISION (double_type_node)
6523                && exact_real_truncate (TYPE_MODE (double_type_node), &orig))
6524              type1 = double_type_node;
6525          }
6526       tree newtype
6527         = (element_precision (TREE_TYPE (@00)) > element_precision (type1)
6528            ? TREE_TYPE (@00) : type1);
6529      }
6530      (if (element_precision (TREE_TYPE (@0)) > element_precision (newtype))
6531       (cmp (convert:newtype @00) (convert:newtype @10))))))))
6534 (for cmp (eq ne)
6535  (simplify
6536   /* SSA names are canonicalized to 2nd place.  */
6537   (cmp addr@0 SSA_NAME@1)
6538   (with
6539    {
6540      poly_int64 off; tree base;
6541      tree addr = (TREE_CODE (@0) == SSA_NAME
6542                   ? gimple_assign_rhs1 (SSA_NAME_DEF_STMT (@0)) : @0);
6543    }
6544    /* A local variable can never be pointed to by
6545       the default SSA name of an incoming parameter.  */
6546    (if (SSA_NAME_IS_DEFAULT_DEF (@1)
6547         && TREE_CODE (SSA_NAME_VAR (@1)) == PARM_DECL
6548         && (base = get_base_address (TREE_OPERAND (addr, 0)))
6549         && TREE_CODE (base) == VAR_DECL
6550         && auto_var_in_fn_p (base, current_function_decl))
6551     (if (cmp == NE_EXPR)
6552      { constant_boolean_node (true, type); }
6553      { constant_boolean_node (false, type); })
6554     /* If the address is based on @1 decide using the offset.  */
6555     (if ((base = get_addr_base_and_unit_offset (TREE_OPERAND (addr, 0), &off))
6556          && TREE_CODE (base) == MEM_REF
6557          && TREE_OPERAND (base, 0) == @1)
6558      (with { off += mem_ref_offset (base).force_shwi (); }
6559       (if (known_ne (off, 0))
6560        { constant_boolean_node (cmp == NE_EXPR, type); }
6561        (if (known_eq (off, 0))
6562         { constant_boolean_node (cmp == EQ_EXPR, type); }))))))))
6564 /* Equality compare simplifications from fold_binary  */
6565 (for cmp (eq ne)
6567  /* If we have (A | C) == D where C & ~D != 0, convert this into 0.
6568     Similarly for NE_EXPR.  */
6569  (simplify
6570   (cmp (convert?@3 (bit_ior @0 INTEGER_CST@1)) INTEGER_CST@2)
6571   (if (tree_nop_conversion_p (TREE_TYPE (@3), TREE_TYPE (@0))
6572        && wi::bit_and_not (wi::to_wide (@1), wi::to_wide (@2)) != 0)
6573    { constant_boolean_node (cmp == NE_EXPR, type); }))
6575  /* (X ^ Y) == 0 becomes X == Y, and (X ^ Y) != 0 becomes X != Y.  */
6576  (simplify
6577   (cmp (bit_xor @0 @1) integer_zerop)
6578   (cmp @0 @1))
6580  /* (X ^ Y) == Y becomes X == 0.
6581     Likewise (X ^ Y) == X becomes Y == 0.  */
6582  (simplify
6583   (cmp:c (bit_xor:c @0 @1) @0)
6584   (cmp @1 { build_zero_cst (TREE_TYPE (@1)); }))
6586  /* (X & Y) == X becomes (X & ~Y) == 0.  */
6587  (simplify
6588   (cmp:c (bit_and:c @0 @1) @0)
6589   (cmp (bit_and @0 (bit_not! @1)) { build_zero_cst (TREE_TYPE (@0)); }))
6590  (simplify
6591   (cmp:c (convert@3 (bit_and (convert@2 @0) INTEGER_CST@1)) (convert @0))
6592   (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
6593        && INTEGRAL_TYPE_P (TREE_TYPE (@2))
6594        && INTEGRAL_TYPE_P (TREE_TYPE (@3))
6595        && TYPE_PRECISION (TREE_TYPE (@2)) == TYPE_PRECISION (TREE_TYPE (@0))
6596        && TYPE_PRECISION (TREE_TYPE (@3)) > TYPE_PRECISION (TREE_TYPE (@2))
6597        && !wi::neg_p (wi::to_wide (@1)))
6598    (cmp (bit_and @0 (convert (bit_not @1)))
6599         { build_zero_cst (TREE_TYPE (@0)); })))
6601  /* (X | Y) == Y becomes (X & ~Y) == 0.  */
6602  (simplify
6603   (cmp:c (bit_ior:c @0 @1) @1)
6604   (cmp (bit_and @0 (bit_not! @1)) { build_zero_cst (TREE_TYPE (@0)); }))
6606  /* (X ^ C1) op C2 can be rewritten as X op (C1 ^ C2).  */
6607  (simplify
6608   (cmp (convert?@3 (bit_xor @0 INTEGER_CST@1)) INTEGER_CST@2)
6609   (if (tree_nop_conversion_p (TREE_TYPE (@3), TREE_TYPE (@0)))
6610    (cmp @0 (bit_xor @1 (convert @2)))))
6612  (simplify
6613   (cmp (nop_convert? @0) integer_zerop)
6614   (if (tree_expr_nonzero_p (@0))
6615    { constant_boolean_node (cmp == NE_EXPR, type); }))
6617  /* (X & C) op (Y & C) into (X ^ Y) & C op 0.  */
6618  (simplify
6619   (cmp (bit_and:cs @0 @2) (bit_and:cs @1 @2))
6620   (cmp (bit_and (bit_xor @0 @1) @2) { build_zero_cst (TREE_TYPE (@2)); })))
6622 /* (X < 0) != (Y < 0) into (X ^ Y) < 0.
6623    (X >= 0) != (Y >= 0) into (X ^ Y) < 0.
6624    (X < 0) == (Y < 0) into (X ^ Y) >= 0.
6625    (X >= 0) == (Y >= 0) into (X ^ Y) >= 0.  */
6626 (for cmp (eq ne)
6627      ncmp (ge lt)
6628  (for sgncmp (ge lt)
6629   (simplify
6630    (cmp (sgncmp @0 integer_zerop@2) (sgncmp @1 integer_zerop))
6631    (if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (@0))
6632         && !TYPE_UNSIGNED (TREE_TYPE (@0))
6633         && types_match (@0, @1))
6634     (ncmp (bit_xor @0 @1) @2)))))
6635 /* (X < 0) == (Y >= 0) into (X ^ Y) < 0.
6636    (X < 0) != (Y >= 0) into (X ^ Y) >= 0.  */
6637 (for cmp (eq ne)
6638      ncmp (lt ge)
6639  (simplify
6640   (cmp:c (lt @0 integer_zerop@2) (ge @1 integer_zerop))
6641    (if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (@0))
6642         && !TYPE_UNSIGNED (TREE_TYPE (@0))
6643         && types_match (@0, @1))
6644     (ncmp (bit_xor @0 @1) @2))))
6646 /* If we have (A & C) == C where C is a power of 2, convert this into
6647    (A & C) != 0.  Similarly for NE_EXPR.  */
6648 (for cmp (eq ne)
6649      icmp (ne eq)
6650  (simplify
6651   (cmp (bit_and@2 @0 integer_pow2p@1) @1)
6652   (icmp @2 { build_zero_cst (TREE_TYPE (@0)); })))
6654 #if GIMPLE
6655 /* From fold_binary_op_with_conditional_arg handle the case of
6656    rewriting (a ? b : c) > d to a ? (b > d) : (c > d) when the
6657    compares simplify.  */
6658 (for cmp (simple_comparison)
6659  (simplify
6660   (cmp:c (cond @0 @1 @2) @3)
6661   /* Do not move possibly trapping operations into the conditional as this
6662      pessimizes code and causes gimplification issues when applied late.  */
6663   (if (!FLOAT_TYPE_P (TREE_TYPE (@3))
6664        || !operation_could_trap_p (cmp, true, false, @3))
6665    (cond @0 (cmp! @1 @3) (cmp! @2 @3)))))
6666 #endif
6668 (for cmp (ge lt)
6669 /* x < 0 ? ~y : y into (x >> (prec-1)) ^ y. */
6670 /* x >= 0 ? ~y : y into ~((x >> (prec-1)) ^ y). */
6671  (simplify
6672   (cond (cmp @0 integer_zerop) (bit_not @1) @1)
6673    (if (INTEGRAL_TYPE_P (type)
6674         && INTEGRAL_TYPE_P (TREE_TYPE (@0))
6675         && !TYPE_UNSIGNED (TREE_TYPE (@0))
6676         && TYPE_PRECISION (TREE_TYPE (@0)) == TYPE_PRECISION (type))
6677     (with
6678      {
6679        tree shifter = build_int_cst (integer_type_node, TYPE_PRECISION (type) - 1);
6680      }
6681     (if (cmp == LT_EXPR)
6682      (bit_xor (convert (rshift @0 {shifter;})) @1)
6683      (bit_not (bit_xor (convert (rshift @0 {shifter;})) @1))))))
6684 /* x < 0 ? y : ~y into ~((x >> (prec-1)) ^ y). */
6685 /* x >= 0 ? y : ~y into (x >> (prec-1)) ^ y. */
6686  (simplify
6687   (cond (cmp @0 integer_zerop) @1 (bit_not @1))
6688    (if (INTEGRAL_TYPE_P (type)
6689         && INTEGRAL_TYPE_P (TREE_TYPE (@0))
6690         && !TYPE_UNSIGNED (TREE_TYPE (@0))
6691         && TYPE_PRECISION (TREE_TYPE (@0)) == TYPE_PRECISION (type))
6692     (with
6693      {
6694        tree shifter = build_int_cst (integer_type_node, TYPE_PRECISION (type) - 1);
6695      }
6696     (if (cmp == GE_EXPR)
6697      (bit_xor (convert (rshift @0 {shifter;})) @1)
6698      (bit_not (bit_xor (convert (rshift @0 {shifter;})) @1)))))))
6700 /* If we have (A & C) != 0 ? D : 0 where C and D are powers of 2,
6701    convert this into a shift followed by ANDing with D.  */
6702 (simplify
6703  (cond
6704   (ne (bit_and @0 integer_pow2p@1) integer_zerop)
6705   INTEGER_CST@2 integer_zerop)
6706  (if (!POINTER_TYPE_P (type) && integer_pow2p (@2))
6707   (with {
6708      int shift = (wi::exact_log2 (wi::to_wide (@2))
6709                   - wi::exact_log2 (wi::to_wide (@1)));
6710    }
6711    (if (shift > 0)
6712     (bit_and
6713      (lshift (convert @0) { build_int_cst (integer_type_node, shift); }) @2)
6714     (bit_and
6715      (convert (rshift @0 { build_int_cst (integer_type_node, -shift); }))
6716      @2)))))
6718 /* If we have (A & C) != 0 where C is the sign bit of A, convert
6719    this into A < 0.  Similarly for (A & C) == 0 into A >= 0.  */
6720 (for cmp (eq ne)
6721      ncmp (ge lt)
6722  (simplify
6723   (cmp (bit_and (convert?@2 @0) integer_pow2p@1) integer_zerop)
6724   (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
6725        && type_has_mode_precision_p (TREE_TYPE (@0))
6726        && element_precision (@2) >= element_precision (@0)
6727        && wi::only_sign_bit_p (wi::to_wide (@1), element_precision (@0)))
6728    (with { tree stype = signed_type_for (TREE_TYPE (@0)); }
6729     (ncmp (convert:stype @0) { build_zero_cst (stype); })))))
6731 /* If we have A < 0 ? C : 0 where C is a power of 2, convert
6732    this into a right shift or sign extension followed by ANDing with C.  */
6733 (simplify
6734  (cond
6735   (lt @0 integer_zerop)
6736   INTEGER_CST@1 integer_zerop)
6737  (if (integer_pow2p (@1)
6738       && !TYPE_UNSIGNED (TREE_TYPE (@0)))
6739   (with {
6740     int shift = element_precision (@0) - wi::exact_log2 (wi::to_wide (@1)) - 1;
6741    }
6742    (if (shift >= 0)
6743     (bit_and
6744      (convert (rshift @0 { build_int_cst (integer_type_node, shift); }))
6745      @1)
6746     /* Otherwise ctype must be wider than TREE_TYPE (@0) and pure
6747        sign extension followed by AND with C will achieve the effect.  */
6748     (bit_and (convert @0) @1)))))
6750 /* When the addresses are not directly of decls compare base and offset.
6751    This implements some remaining parts of fold_comparison address
6752    comparisons but still no complete part of it.  Still it is good
6753    enough to make fold_stmt not regress when not dispatching to fold_binary.  */
6754 (for cmp (simple_comparison)
6755  (simplify
6756   (cmp (convert1?@2 addr@0) (convert2? addr@1))
6757   (with
6758    {
6759      poly_int64 off0, off1;
6760      tree base0, base1;
6761      int equal = address_compare (cmp, TREE_TYPE (@2), @0, @1, base0, base1,
6762                                   off0, off1, GENERIC);
6763    }
6764    (if (equal == 1)
6765     (switch
6766      (if (cmp == EQ_EXPR && (known_eq (off0, off1) || known_ne (off0, off1)))
6767       { constant_boolean_node (known_eq (off0, off1), type); })
6768      (if (cmp == NE_EXPR && (known_eq (off0, off1) || known_ne (off0, off1)))
6769       { constant_boolean_node (known_ne (off0, off1), type); })
6770      (if (cmp == LT_EXPR && (known_lt (off0, off1) || known_ge (off0, off1)))
6771       { constant_boolean_node (known_lt (off0, off1), type); })
6772      (if (cmp == LE_EXPR && (known_le (off0, off1) || known_gt (off0, off1)))
6773       { constant_boolean_node (known_le (off0, off1), type); })
6774      (if (cmp == GE_EXPR && (known_ge (off0, off1) || known_lt (off0, off1)))
6775       { constant_boolean_node (known_ge (off0, off1), type); })
6776      (if (cmp == GT_EXPR && (known_gt (off0, off1) || known_le (off0, off1)))
6777       { constant_boolean_node (known_gt (off0, off1), type); }))
6778     (if (equal == 0)
6779      (switch
6780       (if (cmp == EQ_EXPR)
6781        { constant_boolean_node (false, type); })
6782       (if (cmp == NE_EXPR)
6783        { constant_boolean_node (true, type); })))))))
6785 #if GIMPLE
6786 /* a?~t:t -> (-(a))^t */
6787 (simplify
6788  (cond @0 @1 @2)
6789  (with { bool wascmp; }
6790   (if (INTEGRAL_TYPE_P (type)
6791        && bitwise_inverted_equal_p (@1, @2, wascmp)
6792        && (!wascmp || TYPE_PRECISION (type) == 1))
6793    (if ((!TYPE_UNSIGNED (type) && TREE_CODE (type) == BOOLEAN_TYPE)
6794         || TYPE_PRECISION (type) == 1)
6795     (bit_xor (convert:type @0) @2)
6796     (bit_xor (negate (convert:type @0)) @2)))))
6797 #endif
6799 /* Simplify pointer equality compares using PTA.  */
6800 (for neeq (ne eq)
6801  (simplify
6802   (neeq @0 @1)
6803   (if (POINTER_TYPE_P (TREE_TYPE (@0))
6804        && ptrs_compare_unequal (@0, @1))
6805    { constant_boolean_node (neeq != EQ_EXPR, type); })))
6807 /* PR70920: Transform (intptr_t)x eq/ne CST to x eq/ne (typeof x) CST.
6808    and (typeof ptr_cst) x eq/ne ptr_cst to x eq/ne (typeof x) CST.
6809    Disable the transform if either operand is pointer to function.
6810    This broke pr22051-2.c for arm where function pointer
6811    canonicalizaion is not wanted.  */
6813 (for cmp (ne eq)
6814  (simplify
6815   (cmp (convert @0) INTEGER_CST@1)
6816   (if (((POINTER_TYPE_P (TREE_TYPE (@0))
6817          && !FUNC_OR_METHOD_TYPE_P (TREE_TYPE (TREE_TYPE (@0)))
6818          && INTEGRAL_TYPE_P (TREE_TYPE (@1))
6819          /* Don't perform this optimization in GENERIC if @0 has reference
6820             type when sanitizing.  See PR101210.  */
6821          && !(GENERIC
6822               && TREE_CODE (TREE_TYPE (@0)) == REFERENCE_TYPE
6823               && (flag_sanitize & (SANITIZE_NULL | SANITIZE_ALIGNMENT))))
6824         || (INTEGRAL_TYPE_P (TREE_TYPE (@0))
6825             && POINTER_TYPE_P (TREE_TYPE (@1))
6826             && !FUNC_OR_METHOD_TYPE_P (TREE_TYPE (TREE_TYPE (@1)))))
6827        && TYPE_PRECISION (TREE_TYPE (@0)) == TYPE_PRECISION (TREE_TYPE (@1)))
6828    (cmp @0 (convert @1)))))
6830 /* Non-equality compare simplifications from fold_binary  */
6831 (for cmp (lt gt le ge)
6832  /* Comparisons with the highest or lowest possible integer of
6833     the specified precision will have known values.  */
6834  (simplify
6835   (cmp (convert?@2 @0) uniform_integer_cst_p@1)
6836   (if ((INTEGRAL_TYPE_P (TREE_TYPE (@1))
6837         || POINTER_TYPE_P (TREE_TYPE (@1))
6838         || VECTOR_INTEGER_TYPE_P (TREE_TYPE (@1)))
6839        && tree_nop_conversion_p (TREE_TYPE (@2), TREE_TYPE (@0)))
6840    (with
6841     {
6842       tree cst = uniform_integer_cst_p (@1);
6843       tree arg1_type = TREE_TYPE (cst);
6844       unsigned int prec = TYPE_PRECISION (arg1_type);
6845       wide_int max = wi::max_value (arg1_type);
6846       wide_int signed_max = wi::max_value (prec, SIGNED);
6847       wide_int min = wi::min_value (arg1_type);
6848     }
6849     (switch
6850      (if (wi::to_wide (cst) == max)
6851       (switch
6852        (if (cmp == GT_EXPR)
6853         { constant_boolean_node (false, type); })
6854        (if (cmp == GE_EXPR)
6855         (eq @2 @1))
6856        (if (cmp == LE_EXPR)
6857         { constant_boolean_node (true, type); })
6858        (if (cmp == LT_EXPR)
6859         (ne @2 @1))))
6860      (if (wi::to_wide (cst) == min)
6861       (switch
6862        (if (cmp == LT_EXPR)
6863         { constant_boolean_node (false, type); })
6864        (if (cmp == LE_EXPR)
6865         (eq @2 @1))
6866        (if (cmp == GE_EXPR)
6867         { constant_boolean_node (true, type); })
6868        (if (cmp == GT_EXPR)
6869         (ne @2 @1))))
6870      (if (wi::to_wide (cst) == max - 1)
6871       (switch
6872        (if (cmp == GT_EXPR)
6873         (eq @2 { build_uniform_cst (TREE_TYPE (@1),
6874                                     wide_int_to_tree (TREE_TYPE (cst),
6875                                                       wi::to_wide (cst)
6876                                                       + 1)); }))
6877        (if (cmp == LE_EXPR)
6878         (ne @2 { build_uniform_cst (TREE_TYPE (@1),
6879                                     wide_int_to_tree (TREE_TYPE (cst),
6880                                                       wi::to_wide (cst)
6881                                                       + 1)); }))))
6882      (if (wi::to_wide (cst) == min + 1)
6883       (switch
6884        (if (cmp == GE_EXPR)
6885         (ne @2 { build_uniform_cst (TREE_TYPE (@1),
6886                                     wide_int_to_tree (TREE_TYPE (cst),
6887                                                       wi::to_wide (cst)
6888                                                       - 1)); }))
6889        (if (cmp == LT_EXPR)
6890         (eq @2 { build_uniform_cst (TREE_TYPE (@1),
6891                                     wide_int_to_tree (TREE_TYPE (cst),
6892                                                       wi::to_wide (cst)
6893                                                       - 1)); }))))
6894      (if (wi::to_wide (cst) == signed_max
6895           && TYPE_UNSIGNED (arg1_type)
6896           && TYPE_MODE (arg1_type) != BLKmode
6897           /* We will flip the signedness of the comparison operator
6898              associated with the mode of @1, so the sign bit is
6899              specified by this mode.  Check that @1 is the signed
6900              max associated with this sign bit.  */
6901           && prec == GET_MODE_PRECISION (SCALAR_INT_TYPE_MODE (arg1_type))
6902           /* signed_type does not work on pointer types.  */
6903           && INTEGRAL_TYPE_P (arg1_type))
6904       /* The following case also applies to X < signed_max+1
6905          and X >= signed_max+1 because previous transformations.  */
6906       (if (cmp == LE_EXPR || cmp == GT_EXPR)
6907        (with { tree st = signed_type_for (TREE_TYPE (@1)); }
6908         (switch
6909          (if (cst == @1 && cmp == LE_EXPR)
6910           (ge (convert:st @0) { build_zero_cst (st); }))
6911          (if (cst == @1 && cmp == GT_EXPR)
6912           (lt (convert:st @0) { build_zero_cst (st); }))
6913          (if (cmp == LE_EXPR)
6914           (ge (view_convert:st @0) { build_zero_cst (st); }))
6915          (if (cmp == GT_EXPR)
6916           (lt (view_convert:st @0) { build_zero_cst (st); })))))))))))
6918 /* unsigned < (typeof unsigned)(unsigned != 0) is always false.  */
6919 (simplify
6920  (lt:c @0 (convert (ne @0 integer_zerop)))
6921  (if (TYPE_UNSIGNED (TREE_TYPE (@0)))
6922   { constant_boolean_node (false, type); }))
6924 /* x != (typeof x)(x == CST) -> CST == 0 ? 1 : (CST == 1 ? (x!=0&&x!=1) : x != 0) */
6925 /* x != (typeof x)(x != CST) -> CST == 1 ? 1 : (CST == 0 ? (x!=0&&x!=1) : x != 1) */
6926 /* x == (typeof x)(x == CST) -> CST == 0 ? 0 : (CST == 1 ? (x==0||x==1) : x == 0) */
6927 /* x == (typeof x)(x != CST) -> CST == 1 ? 0 : (CST == 0 ? (x==0||x==1) : x == 1) */
6928 (for outer (ne eq)
6929  (for inner (ne eq)
6930   (simplify
6931    (outer:c @0 (convert (inner @0 INTEGER_CST@1)))
6932    (with {
6933      bool cst1 = integer_onep (@1);
6934      bool cst0 = integer_zerop (@1);
6935      bool innereq = inner == EQ_EXPR;
6936      bool outereq = outer == EQ_EXPR;
6937     }
6938     (switch
6939      (if (innereq ? cst0 : cst1)
6940       { constant_boolean_node (!outereq, type); })
6941      (if (innereq ? cst1 : cst0)
6942       (with {
6943         tree utype = unsigned_type_for (TREE_TYPE (@0));
6944         tree ucst1 = build_one_cst (utype);
6945        }
6946        (if (!outereq)
6947         (gt (convert:utype @0) { ucst1; })
6948         (le (convert:utype @0) { ucst1; })
6949        )
6950       )
6951      )
6952      (with {
6953        tree value = build_int_cst (TREE_TYPE (@0), !innereq);
6954       }
6955       (if (outereq)
6956        (eq @0 { value; })
6957        (ne @0 { value; })
6958       )
6959      )
6960     )
6961    )
6962   )
6966 (for cmp (unordered ordered unlt unle ungt unge uneq ltgt)
6967  /* If the second operand is NaN, the result is constant.  */
6968  (simplify
6969   (cmp @0 REAL_CST@1)
6970   (if (REAL_VALUE_ISNAN (TREE_REAL_CST (@1))
6971        && (cmp != LTGT_EXPR || ! flag_trapping_math))
6972    { constant_boolean_node (cmp == ORDERED_EXPR || cmp == LTGT_EXPR
6973                             ? false : true, type); })))
6975 /* Fold UNORDERED if either operand must be NaN, or neither can be.  */
6976 (simplify
6977   (unordered @0 @1)
6978   (switch
6979     (if (tree_expr_nan_p (@0) || tree_expr_nan_p (@1))
6980         { constant_boolean_node (true, type); })
6981     (if (!tree_expr_maybe_nan_p (@0) && !tree_expr_maybe_nan_p (@1))
6982         { constant_boolean_node (false, type); })))
6984 /* Fold ORDERED if either operand must be NaN, or neither can be.  */
6985 (simplify
6986   (ordered @0 @1)
6987   (switch
6988     (if (tree_expr_nan_p (@0) || tree_expr_nan_p (@1))
6989         { constant_boolean_node (false, type); })
6990     (if (!tree_expr_maybe_nan_p (@0) && !tree_expr_maybe_nan_p (@1))
6991         { constant_boolean_node (true, type); })))
6993 /* bool_var != 0 becomes bool_var.  */
6994 (simplify
6995  (ne @0 integer_zerop)
6996  (if (TREE_CODE (TREE_TYPE (@0)) == BOOLEAN_TYPE
6997       && types_match (type, TREE_TYPE (@0)))
6998   (non_lvalue @0)))
6999 /* bool_var == 1 becomes bool_var.  */
7000 (simplify
7001  (eq @0 integer_onep)
7002  (if (TREE_CODE (TREE_TYPE (@0)) == BOOLEAN_TYPE
7003       && types_match (type, TREE_TYPE (@0)))
7004   (non_lvalue @0)))
7005 /* Do not handle
7006    bool_var == 0 becomes !bool_var or
7007    bool_var != 1 becomes !bool_var
7008    here because that only is good in assignment context as long
7009    as we require a tcc_comparison in GIMPLE_CONDs where we'd
7010    replace if (x == 0) with tem = ~x; if (tem != 0) which is
7011    clearly less optimal and which we'll transform again in forwprop.  */
7013 /* Transform comparisons of the form (X & Y) CMP 0 to X CMP2 Z
7014    where ~Y + 1 == pow2 and Z = ~Y.  */
7015 (for cst (VECTOR_CST INTEGER_CST)
7016  (for cmp (eq ne)
7017       icmp (le gt)
7018   (simplify
7019    (cmp (bit_and:c@2 @0 cst@1) integer_zerop)
7020     (with { tree csts = bitmask_inv_cst_vector_p (@1); }
7021      (if (csts && (VECTOR_TYPE_P (TREE_TYPE (@1)) || single_use (@2)))
7022       (with { auto optab = VECTOR_TYPE_P (TREE_TYPE (@1))
7023                          ? optab_vector : optab_default;
7024               tree utype = unsigned_type_for (TREE_TYPE (@1)); }
7025        (if (target_supports_op_p (utype, icmp, optab)
7026             || (optimize_vectors_before_lowering_p ()
7027                 && (!target_supports_op_p (type, cmp, optab)
7028                     || !target_supports_op_p (type, BIT_AND_EXPR, optab))))
7029         (if (TYPE_UNSIGNED (TREE_TYPE (@1)))
7030          (icmp @0 { csts; })
7031          (icmp (view_convert:utype @0) { csts; })))))))))
7033 /* When one argument is a constant, overflow detection can be simplified.
7034    Currently restricted to single use so as not to interfere too much with
7035    ADD_OVERFLOW detection in tree-ssa-math-opts.cc.
7036    CONVERT?(CONVERT?(A) + CST) CMP A  ->  A CMP' CST' */
7037 (for cmp (lt le ge gt)
7038      out (gt gt le le)
7039  (simplify
7040   (cmp:c (convert?@3 (plus@2 (convert?@4 @0) INTEGER_CST@1)) @0)
7041   (if (TYPE_OVERFLOW_WRAPS (TREE_TYPE (@2))
7042        && types_match (TREE_TYPE (@0), TREE_TYPE (@3))
7043        && tree_nop_conversion_p (TREE_TYPE (@4), TREE_TYPE (@0))
7044        && wi::to_wide (@1) != 0
7045        && single_use (@2))
7046    (with {
7047      unsigned int prec = TYPE_PRECISION (TREE_TYPE (@0));
7048      signop sign = TYPE_SIGN (TREE_TYPE (@0));
7049     }
7050     (out @0 { wide_int_to_tree (TREE_TYPE (@0),
7051                                 wi::max_value (prec, sign)
7052                                 - wi::to_wide (@1)); })))))
7054 /* To detect overflow in unsigned A - B, A < B is simpler than A - B > A.
7055    However, the detection logic for SUB_OVERFLOW in tree-ssa-math-opts.cc
7056    expects the long form, so we restrict the transformation for now.  */
7057 (for cmp (gt le)
7058  (simplify
7059   (cmp:c (minus@2 @0 @1) @0)
7060   (if (single_use (@2)
7061        && ANY_INTEGRAL_TYPE_P (TREE_TYPE (@0))
7062        && TYPE_UNSIGNED (TREE_TYPE (@0)))
7063    (cmp @1 @0))))
7065 /* Optimize A - B + -1 >= A into B >= A for unsigned comparisons.  */
7066 (for cmp (ge lt)
7067  (simplify
7068   (cmp:c (plus (minus @0 @1) integer_minus_onep) @0)
7069    (if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (@0))
7070         && TYPE_UNSIGNED (TREE_TYPE (@0)))
7071     (cmp @1 @0))))
7073 /* Testing for overflow is unnecessary if we already know the result.  */
7074 /* A - B > A  */
7075 (for cmp (gt le)
7076      out (ne eq)
7077  (simplify
7078   (cmp:c (realpart (IFN_SUB_OVERFLOW@2 @0 @1)) @0)
7079   (if (TYPE_UNSIGNED (TREE_TYPE (@0))
7080        && types_match (TREE_TYPE (@0), TREE_TYPE (@1)))
7081    (out (imagpart @2) { build_zero_cst (TREE_TYPE (@0)); }))))
7082 /* A + B < A  */
7083 (for cmp (lt ge)
7084      out (ne eq)
7085  (simplify
7086   (cmp:c (realpart (IFN_ADD_OVERFLOW:c@2 @0 @1)) @0)
7087   (if (TYPE_UNSIGNED (TREE_TYPE (@0))
7088        && types_match (TREE_TYPE (@0), TREE_TYPE (@1)))
7089    (out (imagpart @2) { build_zero_cst (TREE_TYPE (@0)); }))))
7091 /* For unsigned operands, -1 / B < A checks whether A * B would overflow.
7092    Simplify it to __builtin_mul_overflow (A, B, <unused>).  */
7093 (for cmp (lt ge)
7094      out (ne eq)
7095  (simplify
7096   (cmp:c (trunc_div:s integer_all_onesp @1) @0)
7097   (if (TYPE_UNSIGNED (TREE_TYPE (@0)) && !VECTOR_TYPE_P (TREE_TYPE (@0)))
7098    (with { tree t = TREE_TYPE (@0), cpx = build_complex_type (t); }
7099     (out (imagpart (IFN_MUL_OVERFLOW:cpx @0 @1)) { build_zero_cst (t); })))))
7101 /* Similarly, for unsigned operands, (((type) A * B) >> prec) != 0 where type
7102    is at least twice as wide as type of A and B, simplify to
7103    __builtin_mul_overflow (A, B, <unused>).  */
7104 (for cmp (eq ne)
7105  (simplify
7106   (cmp (rshift (mult:s (convert@3 @0) (convert @1)) INTEGER_CST@2)
7107        integer_zerop)
7108   (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
7109        && INTEGRAL_TYPE_P (TREE_TYPE (@3))
7110        && TYPE_UNSIGNED (TREE_TYPE (@0))
7111        && (TYPE_PRECISION (TREE_TYPE (@3))
7112            >= 2 * TYPE_PRECISION (TREE_TYPE (@0)))
7113        && tree_fits_uhwi_p (@2)
7114        && tree_to_uhwi (@2) == TYPE_PRECISION (TREE_TYPE (@0))
7115        && types_match (@0, @1)
7116        && type_has_mode_precision_p (TREE_TYPE (@0))
7117        && (optab_handler (umulv4_optab, TYPE_MODE (TREE_TYPE (@0)))
7118            != CODE_FOR_nothing))
7119    (with { tree t = TREE_TYPE (@0), cpx = build_complex_type (t); }
7120     (cmp (imagpart (IFN_MUL_OVERFLOW:cpx @0 @1)) { build_zero_cst (t); })))))
7122 /* Demote operands of IFN_{ADD,SUB,MUL}_OVERFLOW.  */
7123 (for ovf (IFN_ADD_OVERFLOW IFN_SUB_OVERFLOW IFN_MUL_OVERFLOW)
7124  (simplify
7125   (ovf (convert@2 @0) @1)
7126   (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
7127        && INTEGRAL_TYPE_P (TREE_TYPE (@2))
7128        && TYPE_PRECISION (TREE_TYPE (@2)) > TYPE_PRECISION (TREE_TYPE (@0))
7129        && (!TYPE_UNSIGNED (TREE_TYPE (@2)) || TYPE_UNSIGNED (TREE_TYPE (@0))))
7130    (ovf @0 @1)))
7131  (simplify
7132   (ovf @1 (convert@2 @0))
7133   (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
7134        && INTEGRAL_TYPE_P (TREE_TYPE (@2))
7135        && TYPE_PRECISION (TREE_TYPE (@2)) > TYPE_PRECISION (TREE_TYPE (@0))
7136        && (!TYPE_UNSIGNED (TREE_TYPE (@2)) || TYPE_UNSIGNED (TREE_TYPE (@0))))
7137    (ovf @1 @0))))
7139 /* Optimize __builtin_mul_overflow_p (x, cst, (utype) 0) if all 3 types
7140    are unsigned to x > (umax / cst).  Similarly for signed type, but
7141    in that case it needs to be outside of a range.  */
7142 (simplify
7143  (imagpart (IFN_MUL_OVERFLOW:cs@2 @0 integer_nonzerop@1))
7144   (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
7145        && TYPE_MAX_VALUE (TREE_TYPE (@0))
7146        && types_match (TREE_TYPE (@0), TREE_TYPE (TREE_TYPE (@2)))
7147        && int_fits_type_p (@1, TREE_TYPE (@0)))
7148    (if (TYPE_UNSIGNED (TREE_TYPE (@0)))
7149     (convert (gt @0 (trunc_div! { TYPE_MAX_VALUE (TREE_TYPE (@0)); } @1)))
7150     (if (TYPE_MIN_VALUE (TREE_TYPE (@0)))
7151      (if (integer_minus_onep (@1))
7152       (convert (eq @0 { TYPE_MIN_VALUE (TREE_TYPE (@0)); }))
7153       (with
7154        {
7155          tree div = fold_convert (TREE_TYPE (@0), @1);
7156          tree lo = int_const_binop (TRUNC_DIV_EXPR,
7157                                     TYPE_MIN_VALUE (TREE_TYPE (@0)), div);
7158          tree hi = int_const_binop (TRUNC_DIV_EXPR,
7159                                     TYPE_MAX_VALUE (TREE_TYPE (@0)), div);
7160          tree etype = range_check_type (TREE_TYPE (@0));
7161          if (etype)
7162            {
7163              if (wi::neg_p (wi::to_wide (div)))
7164                std::swap (lo, hi);
7165              lo = fold_convert (etype, lo);
7166              hi = fold_convert (etype, hi);
7167              hi = int_const_binop (MINUS_EXPR, hi, lo);
7168            }
7169        }
7170        (if (etype)
7171         (convert (gt (minus (convert:etype @0) { lo; }) { hi; })))))))))
7173 /* Simplification of math builtins.  These rules must all be optimizations
7174    as well as IL simplifications.  If there is a possibility that the new
7175    form could be a pessimization, the rule should go in the canonicalization
7176    section that follows this one.
7178    Rules can generally go in this section if they satisfy one of
7179    the following:
7181    - the rule describes an identity
7183    - the rule replaces calls with something as simple as addition or
7184      multiplication
7186    - the rule contains unary calls only and simplifies the surrounding
7187      arithmetic.  (The idea here is to exclude non-unary calls in which
7188      one operand is constant and in which the call is known to be cheap
7189      when the operand has that value.)  */
7191 (if (flag_unsafe_math_optimizations)
7192  /* Simplify sqrt(x) * sqrt(x) -> x.  */
7193  (simplify
7194   (mult (SQRT_ALL@1 @0) @1)
7195   (if (!tree_expr_maybe_signaling_nan_p (@0))
7196    @0))
7198  (for op (plus minus)
7199   /* Simplify (A / C) +- (B / C) -> (A +- B) / C.  */
7200   (simplify
7201    (op (rdiv @0 @1)
7202        (rdiv @2 @1))
7203    (rdiv (op @0 @2) @1)))
7205  (for cmp (lt le gt ge)
7206       neg_cmp (gt ge lt le)
7207   /* Simplify (x * C1) cmp C2 -> x cmp (C2 / C1), where C1 != 0.  */
7208   (simplify
7209    (cmp (mult @0 REAL_CST@1) REAL_CST@2)
7210    (with
7211     { tree tem = const_binop (RDIV_EXPR, type, @2, @1); }
7212     (if (tem
7213          && !(REAL_VALUE_ISINF (TREE_REAL_CST (tem))
7214               || (real_zerop (tem) && !real_zerop (@1))))
7215      (switch
7216       (if (real_less (&dconst0, TREE_REAL_CST_PTR (@1)))
7217        (cmp @0 { tem; }))
7218       (if (real_less (TREE_REAL_CST_PTR (@1), &dconst0))
7219        (neg_cmp @0 { tem; })))))))
7221  /* Simplify sqrt(x) * sqrt(y) -> sqrt(x*y).  */
7222  (for root (SQRT CBRT)
7223   (simplify
7224    (mult (root:s @0) (root:s @1))
7225     (root (mult @0 @1))))
7227  /* Simplify expN(x) * expN(y) -> expN(x+y). */
7228  (for exps (EXP EXP2 EXP10 POW10)
7229   (simplify
7230    (mult (exps:s @0) (exps:s @1))
7231     (exps (plus @0 @1))))
7233  /* Simplify a/root(b/c) into a*root(c/b).  */
7234  (for root (SQRT CBRT)
7235   (simplify
7236    (rdiv @0 (root:s (rdiv:s @1 @2)))
7237     (mult @0 (root (rdiv @2 @1)))))
7239  /* Simplify x/expN(y) into x*expN(-y).  */
7240  (for exps (EXP EXP2 EXP10 POW10)
7241   (simplify
7242    (rdiv @0 (exps:s @1))
7243     (mult @0 (exps (negate @1)))))
7245  (for logs (LOG LOG2 LOG10 LOG10)
7246       exps (EXP EXP2 EXP10 POW10)
7247   /* logN(expN(x)) -> x.  */
7248   (simplify
7249    (logs (exps @0))
7250    @0)
7251   /* expN(logN(x)) -> x.  */
7252   (simplify
7253    (exps (logs @0))
7254    @0))
7256  /* Optimize logN(func()) for various exponential functions.  We
7257     want to determine the value "x" and the power "exponent" in
7258     order to transform logN(x**exponent) into exponent*logN(x).  */
7259  (for logs (LOG  LOG   LOG   LOG2 LOG2  LOG2  LOG10 LOG10)
7260       exps (EXP2 EXP10 POW10 EXP  EXP10 POW10 EXP   EXP2)
7261   (simplify
7262    (logs (exps @0))
7263    (if (SCALAR_FLOAT_TYPE_P (type))
7264     (with {
7265       tree x;
7266       switch (exps)
7267         {
7268         CASE_CFN_EXP:
7269           /* Prepare to do logN(exp(exponent)) -> exponent*logN(e).  */
7270           x = build_real_truncate (type, dconst_e ());
7271           break;
7272         CASE_CFN_EXP2:
7273           /* Prepare to do logN(exp2(exponent)) -> exponent*logN(2).  */
7274           x = build_real (type, dconst2);
7275           break;
7276         CASE_CFN_EXP10:
7277         CASE_CFN_POW10:
7278           /* Prepare to do logN(exp10(exponent)) -> exponent*logN(10).  */
7279           {
7280             REAL_VALUE_TYPE dconst10;
7281             real_from_integer (&dconst10, VOIDmode, 10, SIGNED);
7282             x = build_real (type, dconst10);
7283           }
7284           break;
7285         default:
7286           gcc_unreachable ();
7287         }
7288       }
7289      (mult (logs { x; }) @0)))))
7291  (for logs (LOG LOG
7292             LOG2 LOG2
7293             LOG10 LOG10)
7294       exps (SQRT CBRT)
7295   (simplify
7296    (logs (exps @0))
7297    (if (SCALAR_FLOAT_TYPE_P (type))
7298     (with {
7299       tree x;
7300       switch (exps)
7301         {
7302         CASE_CFN_SQRT:
7303           /* Prepare to do logN(sqrt(x)) -> 0.5*logN(x).  */
7304           x = build_real (type, dconsthalf);
7305           break;
7306         CASE_CFN_CBRT:
7307           /* Prepare to do logN(cbrt(x)) -> (1/3)*logN(x).  */
7308           x = build_real_truncate (type, dconst_third ());
7309           break;
7310         default:
7311           gcc_unreachable ();
7312         }
7313       }
7314      (mult { x; } (logs @0))))))
7316  /* logN(pow(x,exponent)) -> exponent*logN(x).  */
7317  (for logs (LOG LOG2 LOG10)
7318       pows (POW)
7319   (simplify
7320    (logs (pows @0 @1))
7321    (mult @1 (logs @0))))
7323  /* pow(C,x) -> exp(log(C)*x) if C > 0,
7324     or if C is a positive power of 2,
7325     pow(C,x) -> exp2(log2(C)*x).  */
7326 #if GIMPLE
7327  (for pows (POW)
7328       exps (EXP)
7329       logs (LOG)
7330       exp2s (EXP2)
7331       log2s (LOG2)
7332   (simplify
7333    (pows REAL_CST@0 @1)
7334    (if (real_compare (GT_EXPR, TREE_REAL_CST_PTR (@0), &dconst0)
7335         && real_isfinite (TREE_REAL_CST_PTR (@0))
7336         /* As libmvec doesn't have a vectorized exp2, defer optimizing
7337            the use_exp2 case until after vectorization.  It seems actually
7338            beneficial for all constants to postpone this until later,
7339            because exp(log(C)*x), while faster, will have worse precision
7340            and if x folds into a constant too, that is unnecessary
7341            pessimization.  */
7342         && canonicalize_math_after_vectorization_p ())
7343     (with {
7344        const REAL_VALUE_TYPE *const value = TREE_REAL_CST_PTR (@0);
7345        bool use_exp2 = false;
7346        if (targetm.libc_has_function (function_c99_misc, TREE_TYPE (@0))
7347            && value->cl == rvc_normal)
7348          {
7349            REAL_VALUE_TYPE frac_rvt = *value;
7350            SET_REAL_EXP (&frac_rvt, 1);
7351            if (real_equal (&frac_rvt, &dconst1))
7352              use_exp2 = true;
7353          }
7354      }
7355      (if (!use_exp2)
7356       (if (optimize_pow_to_exp (@0, @1))
7357        (exps (mult (logs @0) @1)))
7358       (exp2s (mult (log2s @0) @1)))))))
7359 #endif
7361  /* pow(C,x)*expN(y) -> expN(logN(C)*x+y) if C > 0.  */
7362  (for pows (POW)
7363       exps (EXP EXP2 EXP10 POW10)
7364       logs (LOG LOG2 LOG10 LOG10)
7365   (simplify
7366    (mult:c (pows:s REAL_CST@0 @1) (exps:s @2))
7367    (if (real_compare (GT_EXPR, TREE_REAL_CST_PTR (@0), &dconst0)
7368         && real_isfinite (TREE_REAL_CST_PTR (@0)))
7369     (exps (plus (mult (logs @0) @1) @2)))))
7371  (for sqrts (SQRT)
7372       cbrts (CBRT)
7373       pows (POW)
7374       exps (EXP EXP2 EXP10 POW10)
7375   /* sqrt(expN(x)) -> expN(x*0.5).  */
7376   (simplify
7377    (sqrts (exps @0))
7378    (exps (mult @0 { build_real (type, dconsthalf); })))
7379   /* cbrt(expN(x)) -> expN(x/3).  */
7380   (simplify
7381    (cbrts (exps @0))
7382    (exps (mult @0 { build_real_truncate (type, dconst_third ()); })))
7383   /* pow(expN(x), y) -> expN(x*y).  */
7384   (simplify
7385    (pows (exps @0) @1)
7386    (exps (mult @0 @1))))
7388  /* tan(atan(x)) -> x.  */
7389  (for tans (TAN)
7390       atans (ATAN)
7391   (simplify
7392    (tans (atans @0))
7393    @0)))
7395  /* Simplify sin(atan(x)) -> x / sqrt(x*x + 1). */
7396  (for sins (SIN)
7397       atans (ATAN)
7398       sqrts (SQRT)
7399       copysigns (COPYSIGN)
7400   (simplify
7401    (sins (atans:s @0))
7402    (with
7403      {
7404       REAL_VALUE_TYPE r_cst;
7405       build_sinatan_real (&r_cst, type);
7406       tree t_cst = build_real (type, r_cst);
7407       tree t_one = build_one_cst (type);
7408      }
7409     (if (SCALAR_FLOAT_TYPE_P (type))
7410      (cond (lt (abs @0) { t_cst; })
7411       (rdiv @0 (sqrts (plus (mult @0 @0) { t_one; })))
7412       (copysigns { t_one; } @0))))))
7414 /* Simplify cos(atan(x)) -> 1 / sqrt(x*x + 1). */
7415  (for coss (COS)
7416       atans (ATAN)
7417       sqrts (SQRT)
7418       copysigns (COPYSIGN)
7419   (simplify
7420    (coss (atans:s @0))
7421    (with
7422      {
7423       REAL_VALUE_TYPE r_cst;
7424       build_sinatan_real (&r_cst, type);
7425       tree t_cst = build_real (type, r_cst);
7426       tree t_one = build_one_cst (type);
7427       tree t_zero = build_zero_cst (type);
7428      }
7429     (if (SCALAR_FLOAT_TYPE_P (type))
7430      (cond (lt (abs @0) { t_cst; })
7431       (rdiv { t_one; } (sqrts (plus (mult @0 @0) { t_one; })))
7432       (copysigns { t_zero; } @0))))))
7434  (if (!flag_errno_math)
7435   /* Simplify sinh(atanh(x)) -> x / sqrt((1 - x)*(1 + x)). */
7436   (for sinhs (SINH)
7437        atanhs (ATANH)
7438        sqrts (SQRT)
7439    (simplify
7440     (sinhs (atanhs:s @0))
7441     (with { tree t_one = build_one_cst (type); }
7442     (rdiv @0 (sqrts (mult (minus { t_one; } @0) (plus { t_one; } @0)))))))
7444   /* Simplify cosh(atanh(x)) -> 1 / sqrt((1 - x)*(1 + x)) */
7445   (for coshs (COSH)
7446        atanhs (ATANH)
7447        sqrts (SQRT)
7448    (simplify
7449     (coshs (atanhs:s @0))
7450     (with { tree t_one = build_one_cst (type); }
7451     (rdiv { t_one; } (sqrts (mult (minus { t_one; } @0) (plus { t_one; } @0))))))))
7453 /* cabs(x+0i) or cabs(0+xi) -> abs(x).  */
7454 (simplify
7455  (CABS (complex:C @0 real_zerop@1))
7456  (abs @0))
7458 /* trunc(trunc(x)) -> trunc(x), etc.  */
7459 (for fns (TRUNC_ALL FLOOR_ALL CEIL_ALL ROUND_ALL NEARBYINT_ALL RINT_ALL)
7460  (simplify
7461   (fns (fns @0))
7462   (fns @0)))
7463 /* f(x) -> x if x is integer valued and f does nothing for such values.  */
7464 (for fns (TRUNC_ALL FLOOR_ALL CEIL_ALL ROUND_ALL NEARBYINT_ALL RINT_ALL)
7465  (simplify
7466   (fns integer_valued_real_p@0)
7467   @0))
7469 /* hypot(x,0) and hypot(0,x) -> abs(x).  */
7470 (simplify
7471  (HYPOT:c @0 real_zerop@1)
7472  (abs @0))
7474 /* pow(1,x) -> 1.  */
7475 (simplify
7476  (POW real_onep@0 @1)
7477  @0)
7479 (simplify
7480  /* copysign(x,x) -> x.  */
7481  (COPYSIGN_ALL @0 @0)
7482  @0)
7484 (simplify
7485  /* copysign(x,-x) -> -x.  */
7486  (COPYSIGN_ALL @0 (negate@1 @0))
7487  @1)
7489 (simplify
7490  /* copysign(x,y) -> fabs(x) if y is nonnegative.  */
7491  (COPYSIGN_ALL @0 tree_expr_nonnegative_p@1)
7492  (abs @0))
7494 (simplify
7495  /* fabs (copysign(x, y)) -> fabs (x).  */
7496  (abs (COPYSIGN_ALL @0 @1))
7497  (abs @0))
7499 (for scale (LDEXP SCALBN SCALBLN)
7500  /* ldexp(0, x) -> 0.  */
7501  (simplify
7502   (scale real_zerop@0 @1)
7503   @0)
7504  /* ldexp(x, 0) -> x.  */
7505  (simplify
7506   (scale @0 integer_zerop@1)
7507   @0)
7508  /* ldexp(x, y) -> x if x is +-Inf or NaN.  */
7509  (simplify
7510   (scale REAL_CST@0 @1)
7511   (if (!real_isfinite (TREE_REAL_CST_PTR (@0)))
7512    @0)))
7514 /* Canonicalization of sequences of math builtins.  These rules represent
7515    IL simplifications but are not necessarily optimizations.
7517    The sincos pass is responsible for picking "optimal" implementations
7518    of math builtins, which may be more complicated and can sometimes go
7519    the other way, e.g. converting pow into a sequence of sqrts.
7520    We only want to do these canonicalizations before the pass has run.  */
7522 (if (flag_unsafe_math_optimizations && canonicalize_math_p ())
7523  /* Simplify tan(x) * cos(x) -> sin(x). */
7524  (simplify
7525   (mult:c (TAN:s @0) (COS:s @0))
7526    (SIN @0))
7528  /* Simplify x * pow(x,c) -> pow(x,c+1). */
7529  (simplify
7530   (mult:c @0 (POW:s @0 REAL_CST@1))
7531   (if (!TREE_OVERFLOW (@1))
7532    (POW @0 (plus @1 { build_one_cst (type); }))))
7534  /* Simplify sin(x) / cos(x) -> tan(x). */
7535  (simplify
7536   (rdiv (SIN:s @0) (COS:s @0))
7537    (TAN @0))
7539  /* Simplify sinh(x) / cosh(x) -> tanh(x). */
7540  (simplify
7541   (rdiv (SINH:s @0) (COSH:s @0))
7542    (TANH @0))
7544  /* Simplify tanh (x) / sinh (x) -> 1.0 / cosh (x). */
7545  (simplify
7546    (rdiv (TANH:s @0) (SINH:s @0))
7547    (rdiv {build_one_cst (type);} (COSH @0)))
7549  /* Simplify cos(x) / sin(x) -> 1 / tan(x). */
7550  (simplify
7551   (rdiv (COS:s @0) (SIN:s @0))
7552    (rdiv { build_one_cst (type); } (TAN @0)))
7554  /* Simplify sin(x) / tan(x) -> cos(x). */
7555  (simplify
7556   (rdiv (SIN:s @0) (TAN:s @0))
7557   (if (! HONOR_NANS (@0)
7558        && ! HONOR_INFINITIES (@0))
7559    (COS @0)))
7561  /* Simplify tan(x) / sin(x) -> 1.0 / cos(x). */
7562  (simplify
7563   (rdiv (TAN:s @0) (SIN:s @0))
7564   (if (! HONOR_NANS (@0)
7565        && ! HONOR_INFINITIES (@0))
7566    (rdiv { build_one_cst (type); } (COS @0))))
7568  /* Simplify pow(x,y) * pow(x,z) -> pow(x,y+z). */
7569  (simplify
7570   (mult (POW:s @0 @1) (POW:s @0 @2))
7571    (POW @0 (plus @1 @2)))
7573  /* Simplify pow(x,y) * pow(z,y) -> pow(x*z,y). */
7574  (simplify
7575   (mult (POW:s @0 @1) (POW:s @2 @1))
7576    (POW (mult @0 @2) @1))
7578  /* Simplify powi(x,y) * powi(z,y) -> powi(x*z,y). */
7579  (simplify
7580   (mult (POWI:s @0 @1) (POWI:s @2 @1))
7581    (POWI (mult @0 @2) @1))
7583  /* Simplify pow(x,c) / x -> pow(x,c-1). */
7584  (simplify
7585   (rdiv (POW:s @0 REAL_CST@1) @0)
7586   (if (!TREE_OVERFLOW (@1))
7587    (POW @0 (minus @1 { build_one_cst (type); }))))
7589  /* Simplify x / pow (y,z) -> x * pow(y,-z). */
7590  (simplify
7591   (rdiv @0 (POW:s @1 @2))
7592    (mult @0 (POW @1 (negate @2))))
7594  (for sqrts (SQRT)
7595       cbrts (CBRT)
7596       pows (POW)
7597   /* sqrt(sqrt(x)) -> pow(x,1/4).  */
7598   (simplify
7599    (sqrts (sqrts @0))
7600    (pows @0 { build_real (type, dconst_quarter ()); }))
7601   /* sqrt(cbrt(x)) -> pow(x,1/6).  */
7602   (simplify
7603    (sqrts (cbrts @0))
7604    (pows @0 { build_real_truncate (type, dconst_sixth ()); }))
7605   /* cbrt(sqrt(x)) -> pow(x,1/6).  */
7606   (simplify
7607    (cbrts (sqrts @0))
7608    (pows @0 { build_real_truncate (type, dconst_sixth ()); }))
7609   /* cbrt(cbrt(x)) -> pow(x,1/9), iff x is nonnegative.  */
7610   (simplify
7611    (cbrts (cbrts tree_expr_nonnegative_p@0))
7612    (pows @0 { build_real_truncate (type, dconst_ninth ()); }))
7613   /* sqrt(pow(x,y)) -> pow(|x|,y*0.5).  */
7614   (simplify
7615    (sqrts (pows @0 @1))
7616    (pows (abs @0) (mult @1 { build_real (type, dconsthalf); })))
7617   /* cbrt(pow(x,y)) -> pow(x,y/3), iff x is nonnegative.  */
7618   (simplify
7619    (cbrts (pows tree_expr_nonnegative_p@0 @1))
7620    (pows @0 (mult @1 { build_real_truncate (type, dconst_third ()); })))
7621   /* pow(sqrt(x),y) -> pow(x,y*0.5).  */
7622   (simplify
7623    (pows (sqrts @0) @1)
7624    (pows @0 (mult @1 { build_real (type, dconsthalf); })))
7625   /* pow(cbrt(x),y) -> pow(x,y/3) iff x is nonnegative.  */
7626   (simplify
7627    (pows (cbrts tree_expr_nonnegative_p@0) @1)
7628    (pows @0 (mult @1 { build_real_truncate (type, dconst_third ()); })))
7629   /* pow(pow(x,y),z) -> pow(x,y*z) iff x is nonnegative.  */
7630   (simplify
7631    (pows (pows tree_expr_nonnegative_p@0 @1) @2)
7632    (pows @0 (mult @1 @2))))
7634  /* cabs(x+xi) -> fabs(x)*sqrt(2).  */
7635  (simplify
7636   (CABS (complex @0 @0))
7637   (mult (abs @0) { build_real_truncate (type, dconst_sqrt2 ()); }))
7639  /* hypot(x,x) -> fabs(x)*sqrt(2).  */
7640  (simplify
7641   (HYPOT @0 @0)
7642   (mult (abs @0) { build_real_truncate (type, dconst_sqrt2 ()); }))
7644  /* cexp(x+yi) -> exp(x)*cexpi(y).  */
7645  (for cexps (CEXP)
7646       exps (EXP)
7647       cexpis (CEXPI)
7648   (simplify
7649    (cexps compositional_complex@0)
7650    (if (targetm.libc_has_function (function_c99_math_complex, TREE_TYPE (@0)))
7651     (complex
7652      (mult (exps@1 (realpart @0)) (realpart (cexpis:type@2 (imagpart @0))))
7653      (mult @1 (imagpart @2)))))))
7655 (if (canonicalize_math_p ())
7656  /* floor(x) -> trunc(x) if x is nonnegative.  */
7657  (for floors (FLOOR_ALL)
7658       truncs (TRUNC_ALL)
7659   (simplify
7660    (floors tree_expr_nonnegative_p@0)
7661    (truncs @0))))
7663 (match double_value_p
7664  @0
7665  (if (TYPE_MAIN_VARIANT (TREE_TYPE (@0)) == double_type_node)))
7666 (for froms (BUILT_IN_TRUNCL
7667             BUILT_IN_FLOORL
7668             BUILT_IN_CEILL
7669             BUILT_IN_ROUNDL
7670             BUILT_IN_NEARBYINTL
7671             BUILT_IN_RINTL)
7672      tos (BUILT_IN_TRUNC
7673           BUILT_IN_FLOOR
7674           BUILT_IN_CEIL
7675           BUILT_IN_ROUND
7676           BUILT_IN_NEARBYINT
7677           BUILT_IN_RINT)
7678  /* truncl(extend(x)) -> extend(trunc(x)), etc., if x is a double.  */
7679  (if (optimize && canonicalize_math_p ())
7680   (simplify
7681    (froms (convert double_value_p@0))
7682    (convert (tos @0)))))
7684 (match float_value_p
7685  @0
7686  (if (TYPE_MAIN_VARIANT (TREE_TYPE (@0)) == float_type_node)))
7687 (for froms (BUILT_IN_TRUNCL BUILT_IN_TRUNC
7688             BUILT_IN_FLOORL BUILT_IN_FLOOR
7689             BUILT_IN_CEILL BUILT_IN_CEIL
7690             BUILT_IN_ROUNDL BUILT_IN_ROUND
7691             BUILT_IN_NEARBYINTL BUILT_IN_NEARBYINT
7692             BUILT_IN_RINTL BUILT_IN_RINT)
7693      tos (BUILT_IN_TRUNCF BUILT_IN_TRUNCF
7694           BUILT_IN_FLOORF BUILT_IN_FLOORF
7695           BUILT_IN_CEILF BUILT_IN_CEILF
7696           BUILT_IN_ROUNDF BUILT_IN_ROUNDF
7697           BUILT_IN_NEARBYINTF BUILT_IN_NEARBYINTF
7698           BUILT_IN_RINTF BUILT_IN_RINTF)
7699  /* truncl(extend(x)) and trunc(extend(x)) -> extend(truncf(x)), etc.,
7700     if x is a float.  */
7701  (if (optimize && canonicalize_math_p ()
7702       && targetm.libc_has_function (function_c99_misc, NULL_TREE))
7703   (simplify
7704    (froms (convert float_value_p@0))
7705    (convert (tos @0)))))
7707 #if GIMPLE
7708 (match float16_value_p
7709  @0
7710  (if (TYPE_MAIN_VARIANT (TREE_TYPE (@0)) == float16_type_node)))
7711 (for froms (BUILT_IN_TRUNCL BUILT_IN_TRUNC BUILT_IN_TRUNCF
7712             BUILT_IN_FLOORL BUILT_IN_FLOOR BUILT_IN_FLOORF
7713             BUILT_IN_CEILL BUILT_IN_CEIL BUILT_IN_CEILF
7714             BUILT_IN_ROUNDEVENL BUILT_IN_ROUNDEVEN BUILT_IN_ROUNDEVENF
7715             BUILT_IN_ROUNDL BUILT_IN_ROUND BUILT_IN_ROUNDF
7716             BUILT_IN_NEARBYINTL BUILT_IN_NEARBYINT BUILT_IN_NEARBYINTF
7717             BUILT_IN_RINTL BUILT_IN_RINT BUILT_IN_RINTF
7718             BUILT_IN_SQRTL BUILT_IN_SQRT BUILT_IN_SQRTF)
7719      tos (IFN_TRUNC IFN_TRUNC IFN_TRUNC
7720           IFN_FLOOR IFN_FLOOR IFN_FLOOR
7721           IFN_CEIL IFN_CEIL IFN_CEIL
7722           IFN_ROUNDEVEN IFN_ROUNDEVEN IFN_ROUNDEVEN
7723           IFN_ROUND IFN_ROUND IFN_ROUND
7724           IFN_NEARBYINT IFN_NEARBYINT IFN_NEARBYINT
7725           IFN_RINT IFN_RINT IFN_RINT
7726           IFN_SQRT IFN_SQRT IFN_SQRT)
7727  /* (_Float16) round ((doube) x) -> __built_in_roundf16 (x), etc.,
7728     if x is a _Float16.  */
7729  (simplify
7730    (convert (froms (convert float16_value_p@0)))
7731      (if (optimize
7732           && types_match (type, TREE_TYPE (@0))
7733           && direct_internal_fn_supported_p (as_internal_fn (tos),
7734                                              type, OPTIMIZE_FOR_BOTH))
7735        (tos @0))))
7737 /* Simplify (trunc)copysign ((extend)x, (extend)y) to copysignf (x, y),
7738    x,y is float value, similar for _Float16/double.  */
7739 (for copysigns (COPYSIGN_ALL)
7740  (simplify
7741   (convert (copysigns (convert@2 @0) (convert @1)))
7742    (if (optimize
7743        && !HONOR_SNANS (@2)
7744        && types_match (type, TREE_TYPE (@0))
7745        && types_match (type, TREE_TYPE (@1))
7746        && TYPE_PRECISION (type) < TYPE_PRECISION (TREE_TYPE (@2))
7747        && direct_internal_fn_supported_p (IFN_COPYSIGN,
7748                                           type, OPTIMIZE_FOR_BOTH))
7749     (IFN_COPYSIGN @0 @1))))
7751 (for froms (BUILT_IN_FMAF BUILT_IN_FMA BUILT_IN_FMAL)
7752      tos (IFN_FMA IFN_FMA IFN_FMA)
7753  (simplify
7754   (convert (froms (convert@3 @0) (convert @1) (convert @2)))
7755    (if (flag_unsafe_math_optimizations
7756        && optimize
7757        && FLOAT_TYPE_P (type)
7758        && FLOAT_TYPE_P (TREE_TYPE (@3))
7759        && types_match (type, TREE_TYPE (@0))
7760        && types_match (type, TREE_TYPE (@1))
7761        && types_match (type, TREE_TYPE (@2))
7762        && TYPE_PRECISION (type) < TYPE_PRECISION (TREE_TYPE (@3))
7763        && direct_internal_fn_supported_p (as_internal_fn (tos),
7764                                           type, OPTIMIZE_FOR_BOTH))
7765     (tos @0 @1 @2))))
7767 (for maxmin (max min)
7768  (simplify
7769   (convert (maxmin (convert@2 @0) (convert @1)))
7770    (if (optimize
7771        && FLOAT_TYPE_P (type)
7772        && FLOAT_TYPE_P (TREE_TYPE (@2))
7773        && types_match (type, TREE_TYPE (@0))
7774        && types_match (type, TREE_TYPE (@1))
7775        && element_precision (type) < element_precision (TREE_TYPE (@2)))
7776     (maxmin @0 @1))))
7777 #endif
7779 (for froms (XFLOORL XCEILL XROUNDL XRINTL)
7780      tos (XFLOOR XCEIL XROUND XRINT)
7781  /* llfloorl(extend(x)) -> llfloor(x), etc., if x is a double.  */
7782  (if (optimize && canonicalize_math_p ())
7783   (simplify
7784    (froms (convert double_value_p@0))
7785    (tos @0))))
7787 (for froms (XFLOORL XCEILL XROUNDL XRINTL
7788             XFLOOR XCEIL XROUND XRINT)
7789      tos (XFLOORF XCEILF XROUNDF XRINTF)
7790  /* llfloorl(extend(x)) and llfloor(extend(x)) -> llfloorf(x), etc.,
7791     if x is a float.  */
7792  (if (optimize && canonicalize_math_p ())
7793   (simplify
7794    (froms (convert float_value_p@0))
7795    (tos @0))))
7797 (if (canonicalize_math_p ())
7798  /* xfloor(x) -> fix_trunc(x) if x is nonnegative.  */
7799  (for floors (IFLOOR LFLOOR LLFLOOR)
7800   (simplify
7801    (floors tree_expr_nonnegative_p@0)
7802    (fix_trunc @0))))
7804 (if (canonicalize_math_p ())
7805  /* xfloor(x) -> fix_trunc(x), etc., if x is integer valued.  */
7806  (for fns (IFLOOR LFLOOR LLFLOOR
7807            ICEIL LCEIL LLCEIL
7808            IROUND LROUND LLROUND)
7809   (simplify
7810    (fns integer_valued_real_p@0)
7811    (fix_trunc @0)))
7812  (if (!flag_errno_math)
7813   /* xrint(x) -> fix_trunc(x), etc., if x is integer valued.  */
7814   (for rints (IRINT LRINT LLRINT)
7815    (simplify
7816     (rints integer_valued_real_p@0)
7817     (fix_trunc @0)))))
7819 (if (canonicalize_math_p ())
7820  (for ifn (IFLOOR ICEIL IROUND IRINT)
7821       lfn (LFLOOR LCEIL LROUND LRINT)
7822       llfn (LLFLOOR LLCEIL LLROUND LLRINT)
7823   /* Canonicalize iround (x) to lround (x) on ILP32 targets where
7824      sizeof (int) == sizeof (long).  */
7825   (if (TYPE_PRECISION (integer_type_node)
7826        == TYPE_PRECISION (long_integer_type_node))
7827    (simplify
7828     (ifn @0)
7829     (lfn:long_integer_type_node @0)))
7830   /* Canonicalize llround (x) to lround (x) on LP64 targets where
7831      sizeof (long long) == sizeof (long).  */
7832   (if (TYPE_PRECISION (long_long_integer_type_node)
7833        == TYPE_PRECISION (long_integer_type_node))
7834    (simplify
7835     (llfn @0)
7836     (lfn:long_integer_type_node @0)))))
7838 /* cproj(x) -> x if we're ignoring infinities.  */
7839 (simplify
7840  (CPROJ @0)
7841  (if (!HONOR_INFINITIES (type))
7842    @0))
7844 /* If the real part is inf and the imag part is known to be
7845    nonnegative, return (inf + 0i).  */
7846 (simplify
7847  (CPROJ (complex REAL_CST@0 tree_expr_nonnegative_p@1))
7848  (if (real_isinf (TREE_REAL_CST_PTR (@0)))
7849   { build_complex_inf (type, false); }))
7851 /* If the imag part is inf, return (inf+I*copysign(0,imag)).  */
7852 (simplify
7853  (CPROJ (complex @0 REAL_CST@1))
7854  (if (real_isinf (TREE_REAL_CST_PTR (@1)))
7855   { build_complex_inf (type, TREE_REAL_CST_PTR (@1)->sign); }))
7857 (for pows (POW)
7858      sqrts (SQRT)
7859      cbrts (CBRT)
7860  (simplify
7861   (pows @0 REAL_CST@1)
7862   (with {
7863     const REAL_VALUE_TYPE *value = TREE_REAL_CST_PTR (@1);
7864     REAL_VALUE_TYPE tmp;
7865    }
7866    (switch
7867     /* pow(x,0) -> 1.  */
7868     (if (real_equal (value, &dconst0))
7869      { build_real (type, dconst1); })
7870     /* pow(x,1) -> x.  */
7871     (if (real_equal (value, &dconst1))
7872      @0)
7873     /* pow(x,-1) -> 1/x.  */
7874     (if (real_equal (value, &dconstm1))
7875      (rdiv { build_real (type, dconst1); } @0))
7876     /* pow(x,0.5) -> sqrt(x).  */
7877     (if (flag_unsafe_math_optimizations
7878          && canonicalize_math_p ()
7879          && real_equal (value, &dconsthalf))
7880      (sqrts @0))
7881     /* pow(x,1/3) -> cbrt(x).  */
7882     (if (flag_unsafe_math_optimizations
7883          && canonicalize_math_p ()
7884          && (tmp = real_value_truncate (TYPE_MODE (type), dconst_third ()),
7885              real_equal (value, &tmp)))
7886      (cbrts @0))))))
7888 /* powi(1,x) -> 1.  */
7889 (simplify
7890  (POWI real_onep@0 @1)
7891  @0)
7893 (simplify
7894  (POWI @0 INTEGER_CST@1)
7895  (switch
7896   /* powi(x,0) -> 1.  */
7897   (if (wi::to_wide (@1) == 0)
7898    { build_real (type, dconst1); })
7899   /* powi(x,1) -> x.  */
7900   (if (wi::to_wide (@1) == 1)
7901    @0)
7902   /* powi(x,-1) -> 1/x.  */
7903   (if (wi::to_wide (@1) == -1)
7904    (rdiv { build_real (type, dconst1); } @0))))
7906 /* Narrowing of arithmetic and logical operations.
7908    These are conceptually similar to the transformations performed for
7909    the C/C++ front-ends by shorten_binary_op and shorten_compare.  Long
7910    term we want to move all that code out of the front-ends into here.  */
7912 /* Convert (outertype)((innertype0)a+(innertype1)b)
7913    into ((newtype)a+(newtype)b) where newtype
7914    is the widest mode from all of these.  */
7915 (for op (plus minus mult rdiv)
7916  (simplify
7917    (convert (op:s@0 (convert1?@3 @1) (convert2?@4 @2)))
7918    /* If we have a narrowing conversion of an arithmetic operation where
7919       both operands are widening conversions from the same type as the outer
7920       narrowing conversion.  Then convert the innermost operands to a
7921       suitable unsigned type (to avoid introducing undefined behavior),
7922       perform the operation and convert the result to the desired type.  */
7923    (if (INTEGRAL_TYPE_P (type)
7924         && op != MULT_EXPR
7925         && op != RDIV_EXPR
7926         /* We check for type compatibility between @0 and @1 below,
7927            so there's no need to check that @2/@4 are integral types.  */
7928         && INTEGRAL_TYPE_P (TREE_TYPE (@1))
7929         && INTEGRAL_TYPE_P (TREE_TYPE (@3))
7930         /* The precision of the type of each operand must match the
7931            precision of the mode of each operand, similarly for the
7932            result.  */
7933         && type_has_mode_precision_p (TREE_TYPE (@1))
7934         && type_has_mode_precision_p (TREE_TYPE (@2))
7935         && type_has_mode_precision_p (type)
7936         /* The inner conversion must be a widening conversion.  */
7937         && TYPE_PRECISION (TREE_TYPE (@3)) > TYPE_PRECISION (TREE_TYPE (@1))
7938         && types_match (@1, type)
7939         && (types_match (@1, @2)
7940             /* Or the second operand is const integer or converted const
7941                integer from valueize.  */
7942             || poly_int_tree_p (@4)))
7943      (if (TYPE_OVERFLOW_WRAPS (TREE_TYPE (@1)))
7944        (op @1 (convert @2))
7945        (with { tree utype = unsigned_type_for (TREE_TYPE (@1)); }
7946         (convert (op (convert:utype @1)
7947                      (convert:utype @2)))))
7948      (if (FLOAT_TYPE_P (type)
7949           && DECIMAL_FLOAT_TYPE_P (TREE_TYPE (@0))
7950                == DECIMAL_FLOAT_TYPE_P (type))
7951       (with { tree arg0 = strip_float_extensions (@1);
7952               tree arg1 = strip_float_extensions (@2);
7953               tree itype = TREE_TYPE (@0);
7954               tree ty1 = TREE_TYPE (arg0);
7955               tree ty2 = TREE_TYPE (arg1);
7956               enum tree_code code = TREE_CODE (itype); }
7957         (if (FLOAT_TYPE_P (ty1)
7958              && FLOAT_TYPE_P (ty2))
7959          (with { tree newtype = type;
7960                  if (TYPE_MODE (ty1) == SDmode
7961                      || TYPE_MODE (ty2) == SDmode
7962                      || TYPE_MODE (type) == SDmode)
7963                    newtype = dfloat32_type_node;
7964                  if (TYPE_MODE (ty1) == DDmode
7965                      || TYPE_MODE (ty2) == DDmode
7966                      || TYPE_MODE (type) == DDmode)
7967                    newtype = dfloat64_type_node;
7968                  if (TYPE_MODE (ty1) == TDmode
7969                      || TYPE_MODE (ty2) == TDmode
7970                      || TYPE_MODE (type) == TDmode)
7971                    newtype = dfloat128_type_node; }
7972           (if ((newtype == dfloat32_type_node
7973                 || newtype == dfloat64_type_node
7974                 || newtype == dfloat128_type_node)
7975               && newtype == type
7976               && types_match (newtype, type))
7977             (op (convert:newtype @1) (convert:newtype @2))
7978             (with { if (element_precision (ty1) > element_precision (newtype))
7979                       newtype = ty1;
7980                     if (element_precision (ty2) > element_precision (newtype))
7981                       newtype = ty2; }
7982                /* Sometimes this transformation is safe (cannot
7983                   change results through affecting double rounding
7984                   cases) and sometimes it is not.  If NEWTYPE is
7985                   wider than TYPE, e.g. (float)((long double)double
7986                   + (long double)double) converted to
7987                   (float)(double + double), the transformation is
7988                   unsafe regardless of the details of the types
7989                   involved; double rounding can arise if the result
7990                   of NEWTYPE arithmetic is a NEWTYPE value half way
7991                   between two representable TYPE values but the
7992                   exact value is sufficiently different (in the
7993                   right direction) for this difference to be
7994                   visible in ITYPE arithmetic.  If NEWTYPE is the
7995                   same as TYPE, however, the transformation may be
7996                   safe depending on the types involved: it is safe
7997                   if the ITYPE has strictly more than twice as many
7998                   mantissa bits as TYPE, can represent infinities
7999                   and NaNs if the TYPE can, and has sufficient
8000                   exponent range for the product or ratio of two
8001                   values representable in the TYPE to be within the
8002                   range of normal values of ITYPE.  */
8003               (if (element_precision (newtype) < element_precision (itype)
8004                    && (!VECTOR_MODE_P (TYPE_MODE (newtype))
8005                        || target_supports_op_p (newtype, op, optab_default))
8006                    && (flag_unsafe_math_optimizations
8007                        || (element_precision (newtype) == element_precision (type)
8008                            && real_can_shorten_arithmetic (element_mode (itype),
8009                                                            element_mode (type))
8010                            && !excess_precision_type (newtype)))
8011                    && !types_match (itype, newtype))
8012                  (convert:type (op (convert:newtype @1)
8013                                    (convert:newtype @2)))
8014          )))) )
8015    ))
8018 /* This is another case of narrowing, specifically when there's an outer
8019    BIT_AND_EXPR which masks off bits outside the type of the innermost
8020    operands.   Like the previous case we have to convert the operands
8021    to unsigned types to avoid introducing undefined behavior for the
8022    arithmetic operation.  */
8023 (for op (minus plus)
8024  (simplify
8025   (bit_and (op:s (convert@2 @0) (convert@3 @1)) INTEGER_CST@4)
8026   (if (INTEGRAL_TYPE_P (type)
8027        /* We check for type compatibility between @0 and @1 below,
8028           so there's no need to check that @1/@3 are integral types.  */
8029        && INTEGRAL_TYPE_P (TREE_TYPE (@0))
8030        && INTEGRAL_TYPE_P (TREE_TYPE (@2))
8031        /* The precision of the type of each operand must match the
8032           precision of the mode of each operand, similarly for the
8033           result.  */
8034        && type_has_mode_precision_p (TREE_TYPE (@0))
8035        && type_has_mode_precision_p (TREE_TYPE (@1))
8036        && type_has_mode_precision_p (type)
8037        /* The inner conversion must be a widening conversion.  */
8038        && TYPE_PRECISION (TREE_TYPE (@2)) > TYPE_PRECISION (TREE_TYPE (@0))
8039        && types_match (@0, @1)
8040        && (tree_int_cst_min_precision (@4, TYPE_SIGN (TREE_TYPE (@0)))
8041            <= TYPE_PRECISION (TREE_TYPE (@0)))
8042        && (wi::to_wide (@4)
8043            & wi::mask (TYPE_PRECISION (TREE_TYPE (@0)),
8044                        true, TYPE_PRECISION (type))) == 0)
8045    (if (TYPE_OVERFLOW_WRAPS (TREE_TYPE (@0)))
8046     (with { tree ntype = TREE_TYPE (@0); }
8047      (convert (bit_and (op @0 @1) (convert:ntype @4))))
8048     (with { tree utype = unsigned_type_for (TREE_TYPE (@0)); }
8049      (convert (bit_and (op (convert:utype @0) (convert:utype @1))
8050                (convert:utype @4))))))))
8052 /* Transform (@0 < @1 and @0 < @2) to use min,
8053    (@0 > @1 and @0 > @2) to use max */
8054 (for logic (bit_and bit_and bit_and bit_and bit_ior bit_ior bit_ior bit_ior)
8055      op    (lt      le      gt      ge      lt      le      gt      ge     )
8056      ext   (min     min     max     max     max     max     min     min    )
8057  (simplify
8058   (logic (op:cs @0 @1) (op:cs @0 @2))
8059   (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
8060        && TREE_CODE (@0) != INTEGER_CST)
8061    (op @0 (ext @1 @2)))))
8063 /* Max<bool0, bool1> -> bool0 | bool1
8064    Min<bool0, bool1> -> bool0 & bool1 */
8065 (for op    (max     min)
8066      logic (bit_ior bit_and)
8067  (simplify
8068   (op zero_one_valued_p@0 zero_one_valued_p@1)
8069   (logic @0 @1)))
8071 /* signbit(x) != 0 ? -x : x -> abs(x)
8072    signbit(x) == 0 ? -x : x -> -abs(x) */
8073 (for sign (SIGNBIT)
8074  (for neeq (ne eq)
8075   (simplify
8076    (cond (neeq (sign @0) integer_zerop) (negate @0) @0)
8077     (if (neeq == NE_EXPR)
8078      (abs @0)
8079      (negate (abs @0))))))
8081 (simplify
8082  /* signbit(x) -> 0 if x is nonnegative.  */
8083  (SIGNBIT tree_expr_nonnegative_p@0)
8084  { integer_zero_node; })
8086 (simplify
8087  /* signbit(x) -> x<0 if x doesn't have signed zeros.  */
8088  (SIGNBIT @0)
8089  (if (!HONOR_SIGNED_ZEROS (@0))
8090   (convert (lt @0 { build_real (TREE_TYPE (@0), dconst0); }))))
8092 /* Transform comparisons of the form X +- C1 CMP C2 to X CMP C2 -+ C1.  */
8093 (for cmp (eq ne)
8094  (for op (plus minus)
8095       rop (minus plus)
8096   (simplify
8097    (cmp (op@3 @0 INTEGER_CST@1) INTEGER_CST@2)
8098    (if (!TREE_OVERFLOW (@1) && !TREE_OVERFLOW (@2)
8099         && !TYPE_OVERFLOW_SANITIZED (TREE_TYPE (@0))
8100         && !TYPE_OVERFLOW_TRAPS (TREE_TYPE (@0))
8101         && !TYPE_SATURATING (TREE_TYPE (@0)))
8102     (with { tree res = int_const_binop (rop, @2, @1); }
8103      (if (TREE_OVERFLOW (res)
8104           && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (@0)))
8105       { constant_boolean_node (cmp == NE_EXPR, type); }
8106       (if (single_use (@3))
8107        (cmp @0 { TREE_OVERFLOW (res)
8108                  ? drop_tree_overflow (res) : res; }))))))))
8109 (for cmp (lt le gt ge)
8110  (for op (plus minus)
8111       rop (minus plus)
8112   (simplify
8113    (cmp (op@3 @0 INTEGER_CST@1) INTEGER_CST@2)
8114    (if (!TREE_OVERFLOW (@1) && !TREE_OVERFLOW (@2)
8115         && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (@0)))
8116     (with { tree res = int_const_binop (rop, @2, @1); }
8117      (if (TREE_OVERFLOW (res))
8118       {
8119         fold_overflow_warning (("assuming signed overflow does not occur "
8120                                 "when simplifying conditional to constant"),
8121                                WARN_STRICT_OVERFLOW_CONDITIONAL);
8122         bool less = cmp == LE_EXPR || cmp == LT_EXPR;
8123         /* wi::ges_p (@2, 0) should be sufficient for a signed type.  */
8124         bool ovf_high = wi::lt_p (wi::to_wide (@1), 0,
8125                                   TYPE_SIGN (TREE_TYPE (@1)))
8126                         != (op == MINUS_EXPR);
8127         constant_boolean_node (less == ovf_high, type);
8128       }
8129       (if (single_use (@3))
8130        (with
8131         {
8132           fold_overflow_warning (("assuming signed overflow does not occur "
8133                                   "when changing X +- C1 cmp C2 to "
8134                                   "X cmp C2 -+ C1"),
8135                                  WARN_STRICT_OVERFLOW_COMPARISON);
8136         }
8137         (cmp @0 { res; })))))))))
8139 /* Canonicalizations of BIT_FIELD_REFs.  */
8141 (simplify
8142  (BIT_FIELD_REF (BIT_FIELD_REF @0 @1 @2) @3 @4)
8143  (BIT_FIELD_REF @0 @3 { const_binop (PLUS_EXPR, bitsizetype, @2, @4); }))
8145 (simplify
8146  (BIT_FIELD_REF (view_convert @0) @1 @2)
8147  (BIT_FIELD_REF @0 @1 @2))
8149 (simplify
8150  (BIT_FIELD_REF @0 @1 integer_zerop)
8151  (if (tree_int_cst_equal (@1, TYPE_SIZE (TREE_TYPE (@0))))
8152   (view_convert @0)))
8154 (simplify
8155  (BIT_FIELD_REF @0 @1 @2)
8156  (switch
8157   (if (TREE_CODE (TREE_TYPE (@0)) == COMPLEX_TYPE
8158        && tree_int_cst_equal (@1, TYPE_SIZE (TREE_TYPE (TREE_TYPE (@0)))))
8159    (switch
8160     (if (integer_zerop (@2))
8161      (view_convert (realpart @0)))
8162     (if (tree_int_cst_equal (@2, TYPE_SIZE (TREE_TYPE (TREE_TYPE (@0)))))
8163      (view_convert (imagpart @0)))))
8164   (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
8165        && INTEGRAL_TYPE_P (type)
8166        /* On GIMPLE this should only apply to register arguments.  */
8167        && (! GIMPLE || is_gimple_reg (@0))
8168        /* A bit-field-ref that referenced the full argument can be stripped.  */
8169        && ((compare_tree_int (@1, TYPE_PRECISION (TREE_TYPE (@0))) == 0
8170             && integer_zerop (@2))
8171            /* Low-parts can be reduced to integral conversions.
8172               ???  The following doesn't work for PDP endian.  */
8173            || (BYTES_BIG_ENDIAN == WORDS_BIG_ENDIAN
8174                /* But only do this after vectorization.  */
8175                && canonicalize_math_after_vectorization_p ()
8176                /* Don't even think about BITS_BIG_ENDIAN.  */
8177                && TYPE_PRECISION (TREE_TYPE (@0)) % BITS_PER_UNIT == 0
8178                && TYPE_PRECISION (type) % BITS_PER_UNIT == 0
8179                && compare_tree_int (@2, (BYTES_BIG_ENDIAN
8180                                          ? (TYPE_PRECISION (TREE_TYPE (@0))
8181                                             - TYPE_PRECISION (type))
8182                                          : 0)) == 0)))
8183    (convert @0))))
8185 /* Simplify vector extracts.  */
8187 (simplify
8188  (BIT_FIELD_REF CONSTRUCTOR@0 @1 @2)
8189  (if (VECTOR_TYPE_P (TREE_TYPE (@0))
8190       && tree_fits_uhwi_p (TYPE_SIZE (type))
8191       && ((tree_to_uhwi (TYPE_SIZE (type))
8192            == tree_to_uhwi (TYPE_SIZE (TREE_TYPE (TREE_TYPE (@0)))))
8193           || (VECTOR_TYPE_P (type)
8194               && (tree_to_uhwi (TYPE_SIZE (TREE_TYPE (type)))
8195                   == tree_to_uhwi (TYPE_SIZE (TREE_TYPE (TREE_TYPE (@0))))))))
8196   (with
8197    {
8198      tree ctor = (TREE_CODE (@0) == SSA_NAME
8199                   ? gimple_assign_rhs1 (SSA_NAME_DEF_STMT (@0)) : @0);
8200      tree eltype = TREE_TYPE (TREE_TYPE (ctor));
8201      unsigned HOST_WIDE_INT width = tree_to_uhwi (TYPE_SIZE (eltype));
8202      unsigned HOST_WIDE_INT n = tree_to_uhwi (@1);
8203      unsigned HOST_WIDE_INT idx = tree_to_uhwi (@2);
8204    }
8205    (if (n != 0
8206         && (idx % width) == 0
8207         && (n % width) == 0
8208         && known_le ((idx + n) / width,
8209                      TYPE_VECTOR_SUBPARTS (TREE_TYPE (ctor))))
8210     (with
8211      {
8212        idx = idx / width;
8213        n = n / width;
8214        /* Constructor elements can be subvectors.  */
8215        poly_uint64 k = 1;
8216        if (CONSTRUCTOR_NELTS (ctor) != 0)
8217          {
8218            tree cons_elem = TREE_TYPE (CONSTRUCTOR_ELT (ctor, 0)->value);
8219            if (TREE_CODE (cons_elem) == VECTOR_TYPE)
8220              k = TYPE_VECTOR_SUBPARTS (cons_elem);
8221          }
8222        unsigned HOST_WIDE_INT elt, count, const_k;
8223      }
8224      (switch
8225       /* We keep an exact subset of the constructor elements.  */
8226       (if (multiple_p (idx, k, &elt) && multiple_p (n, k, &count))
8227        (if (CONSTRUCTOR_NELTS (ctor) == 0)
8228         { build_zero_cst (type); }
8229         (if (count == 1)
8230          (if (elt < CONSTRUCTOR_NELTS (ctor))
8231           (view_convert { CONSTRUCTOR_ELT (ctor, elt)->value; })
8232           { build_zero_cst (type); })
8233          /* We don't want to emit new CTORs unless the old one goes away.
8234             ???  Eventually allow this if the CTOR ends up constant or
8235             uniform.  */
8236          (if (single_use (@0))
8237           (with
8238             {
8239               vec<constructor_elt, va_gc> *vals;
8240               vec_alloc (vals, count);
8241               bool constant_p = true;
8242               tree res;
8243               for (unsigned i = 0;
8244                    i < count && elt + i < CONSTRUCTOR_NELTS (ctor); ++i)
8245                 {
8246                   tree e = CONSTRUCTOR_ELT (ctor, elt + i)->value;
8247                   CONSTRUCTOR_APPEND_ELT (vals, NULL_TREE, e);
8248                   if (!CONSTANT_CLASS_P (e))
8249                     constant_p = false;
8250                 }
8251               tree evtype = (types_match (TREE_TYPE (type),
8252                                           TREE_TYPE (TREE_TYPE (ctor)))
8253                              ? type
8254                              : build_vector_type (TREE_TYPE (TREE_TYPE (ctor)),
8255                                                   count * k));
8256               /* We used to build a CTOR in the non-constant case here
8257                  but that's not a GIMPLE value.  We'd have to expose this
8258                  operation somehow so the code generation can properly
8259                  split it out to a separate stmt.  */
8260               res = (constant_p ? build_vector_from_ctor (evtype, vals)
8261                      : (GIMPLE ? NULL_TREE : build_constructor (evtype, vals)));
8262             }
8263             (if (res)
8264              (view_convert { res; })))))))
8265       /* The bitfield references a single constructor element.  */
8266       (if (k.is_constant (&const_k)
8267            && idx + n <= (idx / const_k + 1) * const_k)
8268        (switch
8269         (if (CONSTRUCTOR_NELTS (ctor) <= idx / const_k)
8270          { build_zero_cst (type); })
8271         (if (n == const_k)
8272          (view_convert { CONSTRUCTOR_ELT (ctor, idx / const_k)->value; }))
8273         (BIT_FIELD_REF { CONSTRUCTOR_ELT (ctor, idx / const_k)->value; }
8274                        @1 { bitsize_int ((idx % const_k) * width); })))))))))
8276 /* Simplify a bit extraction from a bit insertion for the cases with
8277    the inserted element fully covering the extraction or the insertion
8278    not touching the extraction.  */
8279 (simplify
8280  (BIT_FIELD_REF (bit_insert @0 @1 @ipos) @rsize @rpos)
8281  (with
8282   {
8283     unsigned HOST_WIDE_INT isize;
8284     if (INTEGRAL_TYPE_P (TREE_TYPE (@1)))
8285       isize = TYPE_PRECISION (TREE_TYPE (@1));
8286     else
8287       isize = tree_to_uhwi (TYPE_SIZE (TREE_TYPE (@1)));
8288   }
8289   (switch
8290    (if ((!INTEGRAL_TYPE_P (TREE_TYPE (@1))
8291          || type_has_mode_precision_p (TREE_TYPE (@1)))
8292         && wi::leu_p (wi::to_wide (@ipos), wi::to_wide (@rpos))
8293         && wi::leu_p (wi::to_wide (@rpos) + wi::to_wide (@rsize),
8294                       wi::to_wide (@ipos) + isize))
8295     (BIT_FIELD_REF @1 @rsize { wide_int_to_tree (bitsizetype,
8296                                                  wi::to_wide (@rpos)
8297                                                  - wi::to_wide (@ipos)); }))
8298    (if (wi::eq_p (wi::to_wide (@ipos), wi::to_wide (@rpos))
8299         && compare_tree_int (@rsize, isize) == 0)
8300     (convert @1))
8301    (if (wi::geu_p (wi::to_wide (@ipos),
8302                    wi::to_wide (@rpos) + wi::to_wide (@rsize))
8303         || wi::geu_p (wi::to_wide (@rpos),
8304                       wi::to_wide (@ipos) + isize))
8305     (BIT_FIELD_REF @0 @rsize @rpos)))))
8307 /* Simplify vector inserts of other vector extracts to a permute.  */
8308 (simplify
8309  (bit_insert @0 (BIT_FIELD_REF@2 @1 @rsize @rpos) @ipos)
8310  (if (VECTOR_TYPE_P (type)
8311       && types_match (@0, @1)
8312       && types_match (TREE_TYPE (TREE_TYPE (@0)), TREE_TYPE (@2))
8313       && TYPE_VECTOR_SUBPARTS (type).is_constant ())
8314   (with
8315    {
8316      unsigned HOST_WIDE_INT elsz
8317        = tree_to_uhwi (TYPE_SIZE (TREE_TYPE (TREE_TYPE (@1))));
8318      poly_uint64 relt = exact_div (tree_to_poly_uint64 (@rpos), elsz);
8319      poly_uint64 ielt = exact_div (tree_to_poly_uint64 (@ipos), elsz);
8320      unsigned nunits = TYPE_VECTOR_SUBPARTS (type).to_constant ();
8321      vec_perm_builder builder;
8322      builder.new_vector (nunits, nunits, 1);
8323      for (unsigned i = 0; i < nunits; ++i)
8324        builder.quick_push (known_eq (ielt, i) ? nunits + relt : i);
8325      vec_perm_indices sel (builder, 2, nunits);
8326    }
8327    (if (!VECTOR_MODE_P (TYPE_MODE (type))
8328         || can_vec_perm_const_p (TYPE_MODE (type), TYPE_MODE (type), sel, false))
8329     (vec_perm @0 @1 { vec_perm_indices_to_tree
8330                         (build_vector_type (ssizetype, nunits), sel); })))))
8332 (if (canonicalize_math_after_vectorization_p ())
8333  (for fmas (FMA)
8334   (simplify
8335    (fmas:c (negate @0) @1 @2)
8336    (IFN_FNMA @0 @1 @2))
8337   (simplify
8338    (fmas @0 @1 (negate @2))
8339    (IFN_FMS @0 @1 @2))
8340   (simplify
8341    (fmas:c (negate @0) @1 (negate @2))
8342    (IFN_FNMS @0 @1 @2))
8343   (simplify
8344    (negate (fmas@3 @0 @1 @2))
8345    (if (single_use (@3))
8346     (IFN_FNMS @0 @1 @2))))
8348  (simplify
8349   (IFN_FMS:c (negate @0) @1 @2)
8350   (IFN_FNMS @0 @1 @2))
8351  (simplify
8352   (IFN_FMS @0 @1 (negate @2))
8353   (IFN_FMA @0 @1 @2))
8354  (simplify
8355   (IFN_FMS:c (negate @0) @1 (negate @2))
8356   (IFN_FNMA @0 @1 @2))
8357  (simplify
8358   (negate (IFN_FMS@3 @0 @1 @2))
8359    (if (single_use (@3))
8360     (IFN_FNMA @0 @1 @2)))
8362  (simplify
8363   (IFN_FNMA:c (negate @0) @1 @2)
8364   (IFN_FMA @0 @1 @2))
8365  (simplify
8366   (IFN_FNMA @0 @1 (negate @2))
8367   (IFN_FNMS @0 @1 @2))
8368  (simplify
8369   (IFN_FNMA:c (negate @0) @1 (negate @2))
8370   (IFN_FMS @0 @1 @2))
8371  (simplify
8372   (negate (IFN_FNMA@3 @0 @1 @2))
8373   (if (single_use (@3))
8374    (IFN_FMS @0 @1 @2)))
8376  (simplify
8377   (IFN_FNMS:c (negate @0) @1 @2)
8378   (IFN_FMS @0 @1 @2))
8379  (simplify
8380   (IFN_FNMS @0 @1 (negate @2))
8381   (IFN_FNMA @0 @1 @2))
8382  (simplify
8383   (IFN_FNMS:c (negate @0) @1 (negate @2))
8384   (IFN_FMA @0 @1 @2))
8385  (simplify
8386   (negate (IFN_FNMS@3 @0 @1 @2))
8387   (if (single_use (@3))
8388    (IFN_FMA @0 @1 @2))))
8390 /* CLZ simplifications.  */
8391 (for clz (CLZ)
8392  (for op (eq ne)
8393       cmp (lt ge)
8394   (simplify
8395    (op (clz:s@2 @0) INTEGER_CST@1)
8396    (if (integer_zerop (@1) && single_use (@2))
8397     /* clz(X) == 0 is (int)X < 0 and clz(X) != 0 is (int)X >= 0.  */
8398     (with { tree type0 = TREE_TYPE (@0);
8399             tree stype = signed_type_for (type0);
8400             HOST_WIDE_INT val = 0;
8401             /* Punt on hypothetical weird targets.  */
8402             if (clz == CFN_CLZ
8403                 && CLZ_DEFINED_VALUE_AT_ZERO (SCALAR_TYPE_MODE (type0),
8404                                               val) == 2
8405                 && val == 0)
8406               stype = NULL_TREE;
8407           }
8408      (if (stype)
8409       (cmp (convert:stype @0) { build_zero_cst (stype); })))
8410     /* clz(X) == (prec-1) is X == 1 and clz(X) != (prec-1) is X != 1.  */
8411     (with { bool ok = true;
8412             HOST_WIDE_INT val = 0;
8413             tree type0 = TREE_TYPE (@0);
8414             /* Punt on hypothetical weird targets.  */
8415             if (clz == CFN_CLZ
8416                 && CLZ_DEFINED_VALUE_AT_ZERO (SCALAR_TYPE_MODE (type0),
8417                                               val) == 2
8418                 && val == TYPE_PRECISION (type0) - 1)
8419               ok = false;
8420           }
8421      (if (ok && wi::to_wide (@1) == (TYPE_PRECISION (type0) - 1))
8422       (op @0 { build_one_cst (type0); })))))))
8424 /* CTZ simplifications.  */
8425 (for ctz (CTZ)
8426  (for op (ge gt le lt)
8427       cmp (eq eq ne ne)
8428   (simplify
8429    /* __builtin_ctz (x) >= C -> (x & ((1 << C) - 1)) == 0.  */
8430    (op (ctz:s @0) INTEGER_CST@1)
8431     (with { bool ok = true;
8432             HOST_WIDE_INT val = 0;
8433             if (!tree_fits_shwi_p (@1))
8434               ok = false;
8435             else
8436               {
8437                 val = tree_to_shwi (@1);
8438                 /* Canonicalize to >= or <.  */
8439                 if (op == GT_EXPR || op == LE_EXPR)
8440                   {
8441                     if (val == HOST_WIDE_INT_MAX)
8442                       ok = false;
8443                     else
8444                       val++;
8445                   }
8446               }
8447             bool zero_res = false;
8448             HOST_WIDE_INT zero_val = 0;
8449             tree type0 = TREE_TYPE (@0);
8450             int prec = TYPE_PRECISION (type0);
8451             if (ctz == CFN_CTZ
8452                 && CTZ_DEFINED_VALUE_AT_ZERO (SCALAR_TYPE_MODE (type0),
8453                                               zero_val) == 2)
8454               zero_res = true;
8455           }
8456      (if (val <= 0)
8457       (if (ok && (!zero_res || zero_val >= val))
8458        { constant_boolean_node (cmp == EQ_EXPR ? true : false, type); })
8459       (if (val >= prec)
8460        (if (ok && (!zero_res || zero_val < val))
8461         { constant_boolean_node (cmp == EQ_EXPR ? false : true, type); })
8462        (if (ok && (!zero_res || zero_val < 0 || zero_val >= prec))
8463         (cmp (bit_and @0 { wide_int_to_tree (type0,
8464                                              wi::mask (val, false, prec)); })
8465              { build_zero_cst (type0); })))))))
8466  (for op (eq ne)
8467   (simplify
8468    /* __builtin_ctz (x) == C -> (x & ((1 << (C + 1)) - 1)) == (1 << C).  */
8469    (op (ctz:s @0) INTEGER_CST@1)
8470     (with { bool zero_res = false;
8471             HOST_WIDE_INT zero_val = 0;
8472             tree type0 = TREE_TYPE (@0);
8473             int prec = TYPE_PRECISION (type0);
8474             if (ctz == CFN_CTZ
8475                 && CTZ_DEFINED_VALUE_AT_ZERO (SCALAR_TYPE_MODE (type0),
8476                                               zero_val) == 2)
8477               zero_res = true;
8478           }
8479      (if (tree_int_cst_sgn (@1) < 0 || wi::to_widest (@1) >= prec)
8480       (if (!zero_res || zero_val != wi::to_widest (@1))
8481        { constant_boolean_node (op == EQ_EXPR ? false : true, type); })
8482       (if (!zero_res || zero_val < 0 || zero_val >= prec)
8483        (op (bit_and @0 { wide_int_to_tree (type0,
8484                                            wi::mask (tree_to_uhwi (@1) + 1,
8485                                                      false, prec)); })
8486            { wide_int_to_tree (type0,
8487                                wi::shifted_mask (tree_to_uhwi (@1), 1,
8488                                                  false, prec)); })))))))
8490 /* POPCOUNT simplifications.  */
8491 /* popcount(X) + popcount(Y) is popcount(X|Y) when X&Y must be zero.  */
8492 (simplify
8493   (plus (POPCOUNT:s @0) (POPCOUNT:s @1))
8494   (if (INTEGRAL_TYPE_P (type)
8495        && wi::bit_and (tree_nonzero_bits (@0), tree_nonzero_bits (@1)) == 0)
8496     (POPCOUNT (bit_ior @0 @1))))
8498 /* popcount(X) == 0 is X == 0, and related (in)equalities.  */
8499 (for popcount (POPCOUNT)
8500   (for cmp (le eq ne gt)
8501        rep (eq eq ne ne)
8502     (simplify
8503       (cmp (popcount @0) integer_zerop)
8504       (rep @0 { build_zero_cst (TREE_TYPE (@0)); }))))
8506 /* popcount(bswap(x)) is popcount(x).  */
8507 (for popcount (POPCOUNT)
8508   (for bswap (BUILT_IN_BSWAP16 BUILT_IN_BSWAP32
8509               BUILT_IN_BSWAP64 BUILT_IN_BSWAP128)
8510     (simplify
8511       (popcount (convert?@0 (bswap:s@1 @2)))
8512       (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
8513            && INTEGRAL_TYPE_P (TREE_TYPE (@1)))
8514         (with { tree type0 = TREE_TYPE (@0);
8515                 tree type1 = TREE_TYPE (@1);
8516                 unsigned int prec0 = TYPE_PRECISION (type0);
8517                 unsigned int prec1 = TYPE_PRECISION (type1); }
8518           (if (prec0 == prec1 || (prec0 > prec1 && TYPE_UNSIGNED (type1)))
8519             (popcount (convert:type0 (convert:type1 @2)))))))))
8521 /* popcount(rotate(X Y)) is popcount(X).  */
8522 (for popcount (POPCOUNT)
8523   (for rot (lrotate rrotate)
8524     (simplify
8525       (popcount (convert?@0 (rot:s@1 @2 @3)))
8526       (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
8527            && INTEGRAL_TYPE_P (TREE_TYPE (@1))  
8528            && (GIMPLE || !TREE_SIDE_EFFECTS (@3)))
8529         (with { tree type0 = TREE_TYPE (@0);
8530                 tree type1 = TREE_TYPE (@1);
8531                 unsigned int prec0 = TYPE_PRECISION (type0);
8532                 unsigned int prec1 = TYPE_PRECISION (type1); }
8533           (if (prec0 == prec1 || (prec0 > prec1 && TYPE_UNSIGNED (type1)))
8534             (popcount (convert:type0 @2))))))))
8536 /* Canonicalize POPCOUNT(x)&1 as PARITY(X).  */
8537 (simplify
8538   (bit_and (POPCOUNT @0) integer_onep)
8539   (PARITY @0))
8541 /* popcount(X&Y) + popcount(X|Y) is popcount(x) + popcount(Y).  */
8542 (simplify
8543   (plus:c (POPCOUNT:s (bit_and:s @0 @1)) (POPCOUNT:s (bit_ior:cs @0 @1)))
8544   (plus (POPCOUNT @0) (POPCOUNT @1)))
8546 /* popcount(X) + popcount(Y) - popcount(X&Y) is popcount(X|Y).  */
8547 /* popcount(X) + popcount(Y) - popcount(X|Y) is popcount(X&Y).  */
8548 (for popcount (POPCOUNT)
8549   (for log1 (bit_and bit_ior)
8550        log2 (bit_ior bit_and)
8551     (simplify
8552       (minus (plus:s (popcount:s @0) (popcount:s @1))
8553              (popcount:s (log1:cs @0 @1)))
8554       (popcount (log2 @0 @1)))
8555     (simplify
8556       (plus:c (minus:s (popcount:s @0) (popcount:s (log1:cs @0 @1)))
8557               (popcount:s @1))
8558       (popcount (log2 @0 @1)))))
8560 /* PARITY simplifications.  */
8561 /* parity(~X) is parity(X).  */
8562 (simplify
8563   (PARITY (bit_not @0))
8564   (PARITY @0))
8566 /* parity(bswap(x)) is parity(x).  */
8567 (for parity (PARITY)
8568   (for bswap (BUILT_IN_BSWAP16 BUILT_IN_BSWAP32
8569               BUILT_IN_BSWAP64 BUILT_IN_BSWAP128)
8570     (simplify
8571       (parity (convert?@0 (bswap:s@1 @2)))
8572       (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
8573            && INTEGRAL_TYPE_P (TREE_TYPE (@1))
8574            && TYPE_PRECISION (TREE_TYPE (@0))
8575               >= TYPE_PRECISION (TREE_TYPE (@1)))
8576         (with { tree type0 = TREE_TYPE (@0);
8577                 tree type1 = TREE_TYPE (@1); }
8578           (parity (convert:type0 (convert:type1 @2))))))))
8580 /* parity(rotate(X Y)) is parity(X).  */
8581 (for parity (PARITY)
8582   (for rot (lrotate rrotate)
8583     (simplify
8584       (parity (convert?@0 (rot:s@1 @2 @3)))
8585       (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
8586            && INTEGRAL_TYPE_P (TREE_TYPE (@1))
8587            && (GIMPLE || !TREE_SIDE_EFFECTS (@3))
8588            && TYPE_PRECISION (TREE_TYPE (@0))
8589               >= TYPE_PRECISION (TREE_TYPE (@1)))
8590         (with { tree type0 = TREE_TYPE (@0); }
8591           (parity (convert:type0 @2)))))))
8593 /* parity(X)^parity(Y) is parity(X^Y).  */
8594 (simplify
8595   (bit_xor (PARITY:s @0) (PARITY:s @1))
8596   (PARITY (bit_xor @0 @1)))
8598 /* a != 0 ? FUN(a) : 0 -> Fun(a) for some builtin functions. */
8599 (for func (POPCOUNT BSWAP FFS PARITY)
8600  (simplify
8601   (cond (ne @0 integer_zerop@1) (func@3 (convert? @0)) integer_zerop@2)
8602   @3))
8604 /* a != 0 ? FUN(a) : CST -> Fun(a) for some CLRSB builtins
8605    where CST is precision-1. */
8606 (for func (CLRSB)
8607  (simplify
8608   (cond (ne @0 integer_zerop@1) (func@4 (convert?@3 @0)) INTEGER_CST@2)
8609   (if (wi::to_widest (@2) == TYPE_PRECISION (TREE_TYPE (@3)) - 1)
8610    @4)))
8612 #if GIMPLE
8613 /* a != 0 ? CLZ(a) : CST -> .CLZ(a) where CST is the result of the internal function for 0. */
8614 (for func (CLZ)
8615  (simplify
8616   (cond (ne @0 integer_zerop@1) (func (convert?@3 @0)) INTEGER_CST@2)
8617   (with { int val;
8618           internal_fn ifn = IFN_LAST;
8619           if (direct_internal_fn_supported_p (IFN_CLZ, type, OPTIMIZE_FOR_BOTH)
8620               && CLZ_DEFINED_VALUE_AT_ZERO (SCALAR_INT_TYPE_MODE (type),
8621                                             val) == 2)
8622             ifn = IFN_CLZ;
8623         }
8624    (if (ifn == IFN_CLZ && wi::to_widest (@2) == val)
8625     (IFN_CLZ @3)))))
8627 /* a != 0 ? CTZ(a) : CST -> .CTZ(a) where CST is the result of the internal function for 0. */
8628 (for func (CTZ)
8629  (simplify
8630   (cond (ne @0 integer_zerop@1) (func (convert?@3 @0)) INTEGER_CST@2)
8631   (with { int val;
8632           internal_fn ifn = IFN_LAST;
8633           if (direct_internal_fn_supported_p (IFN_CTZ, type, OPTIMIZE_FOR_BOTH)
8634               && CTZ_DEFINED_VALUE_AT_ZERO (SCALAR_INT_TYPE_MODE (type),
8635                                             val) == 2)
8636             ifn = IFN_CTZ;
8637         }
8638    (if (ifn == IFN_CTZ && wi::to_widest (@2) == val)
8639     (IFN_CTZ @3)))))
8640 #endif
8642 /* Common POPCOUNT/PARITY simplifications.  */
8643 /* popcount(X&C1) is (X>>C2)&1 when C1 == 1<<C2.  Same for parity(X&C1).  */
8644 (for pfun (POPCOUNT PARITY)
8645   (simplify
8646     (pfun @0)
8647     (if (INTEGRAL_TYPE_P (type))
8648      (with { wide_int nz = tree_nonzero_bits (@0); }
8649        (switch
8650          (if (nz == 1)
8651            (convert @0))
8652          (if (wi::popcount (nz) == 1)
8653            (with { tree utype = unsigned_type_for (TREE_TYPE (@0)); }
8654              (convert (rshift:utype (convert:utype @0)
8655                                     { build_int_cst (integer_type_node,
8656                                                      wi::ctz (nz)); })))))))))
8658 #if GIMPLE
8659 /* 64- and 32-bits branchless implementations of popcount are detected:
8661    int popcount64c (uint64_t x)
8662    {
8663      x -= (x >> 1) & 0x5555555555555555ULL;
8664      x = (x & 0x3333333333333333ULL) + ((x >> 2) & 0x3333333333333333ULL);
8665      x = (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0fULL;
8666      return (x * 0x0101010101010101ULL) >> 56;
8667    }
8669    int popcount32c (uint32_t x)
8670    {
8671      x -= (x >> 1) & 0x55555555;
8672      x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
8673      x = (x + (x >> 4)) & 0x0f0f0f0f;
8674      return (x * 0x01010101) >> 24;
8675    }  */
8676 (simplify
8677  (rshift
8678   (mult
8679    (bit_and
8680     (plus:c
8681      (rshift @8 INTEGER_CST@5)
8682       (plus:c@8
8683        (bit_and @6 INTEGER_CST@7)
8684         (bit_and
8685          (rshift
8686           (minus@6 @0
8687            (bit_and (rshift @0 INTEGER_CST@4) INTEGER_CST@11))
8688           INTEGER_CST@10)
8689          INTEGER_CST@9)))
8690     INTEGER_CST@3)
8691    INTEGER_CST@2)
8692   INTEGER_CST@1)
8693   /* Check constants and optab.  */
8694   (with { unsigned prec = TYPE_PRECISION (type);
8695           int shift = (64 - prec) & 63;
8696           unsigned HOST_WIDE_INT c1
8697             = HOST_WIDE_INT_UC (0x0101010101010101) >> shift;
8698           unsigned HOST_WIDE_INT c2
8699             = HOST_WIDE_INT_UC (0x0F0F0F0F0F0F0F0F) >> shift;
8700           unsigned HOST_WIDE_INT c3
8701             = HOST_WIDE_INT_UC (0x3333333333333333) >> shift;
8702           unsigned HOST_WIDE_INT c4
8703             = HOST_WIDE_INT_UC (0x5555555555555555) >> shift;
8704    }
8705    (if (prec >= 16
8706         && prec <= 64
8707         && pow2p_hwi (prec)
8708         && TYPE_UNSIGNED (type)
8709         && integer_onep (@4)
8710         && wi::to_widest (@10) == 2
8711         && wi::to_widest (@5) == 4
8712         && wi::to_widest (@1) == prec - 8
8713         && tree_to_uhwi (@2) == c1
8714         && tree_to_uhwi (@3) == c2
8715         && tree_to_uhwi (@9) == c3
8716         && tree_to_uhwi (@7) == c3
8717         && tree_to_uhwi (@11) == c4)
8718     (if (direct_internal_fn_supported_p (IFN_POPCOUNT, type,
8719                                          OPTIMIZE_FOR_BOTH))
8720      (convert (IFN_POPCOUNT:type @0))
8721      /* Try to do popcount in two halves.  PREC must be at least
8722         five bits for this to work without extension before adding.  */
8723      (with {
8724        tree half_type = NULL_TREE;
8725        opt_machine_mode m = mode_for_size ((prec + 1) / 2, MODE_INT, 1);
8726        int half_prec = 8;
8727        if (m.exists ()
8728            && m.require () != TYPE_MODE (type))
8729          {
8730            half_prec = GET_MODE_PRECISION (as_a <scalar_int_mode> (m));
8731            half_type = build_nonstandard_integer_type (half_prec, 1);
8732          }
8733        gcc_assert (half_prec > 2);
8734       }
8735       (if (half_type != NULL_TREE
8736            && direct_internal_fn_supported_p (IFN_POPCOUNT, half_type,
8737                                               OPTIMIZE_FOR_BOTH))
8738        (convert (plus
8739          (IFN_POPCOUNT:half_type (convert @0))
8740          (IFN_POPCOUNT:half_type (convert (rshift @0
8741             { build_int_cst (integer_type_node, half_prec); } )))))))))))
8743 /* __builtin_ffs needs to deal on many targets with the possible zero
8744    argument.  If we know the argument is always non-zero, __builtin_ctz + 1
8745    should lead to better code.  */
8746 (simplify
8747  (FFS tree_expr_nonzero_p@0)
8748  (if (INTEGRAL_TYPE_P (TREE_TYPE (@0))
8749       && direct_internal_fn_supported_p (IFN_CTZ, TREE_TYPE (@0),
8750                                          OPTIMIZE_FOR_SPEED))
8751   (with { tree utype = unsigned_type_for (TREE_TYPE (@0)); }
8752    (plus (CTZ:type (convert:utype @0)) { build_one_cst (type); }))))
8753 #endif
8755 (for ffs (BUILT_IN_FFS BUILT_IN_FFSL BUILT_IN_FFSLL
8756           BUILT_IN_FFSIMAX)
8757  /* __builtin_ffs (X) == 0 -> X == 0.
8758     __builtin_ffs (X) == 6 -> (X & 63) == 32.  */
8759  (for cmp (eq ne)
8760   (simplify
8761    (cmp (ffs@2 @0) INTEGER_CST@1)
8762     (with { int prec = TYPE_PRECISION (TREE_TYPE (@0)); }
8763      (switch
8764       (if (integer_zerop (@1))
8765        (cmp @0 { build_zero_cst (TREE_TYPE (@0)); }))
8766       (if (tree_int_cst_sgn (@1) < 0 || wi::to_widest (@1) > prec)
8767        { constant_boolean_node (cmp == NE_EXPR ? true : false, type); })
8768       (if (single_use (@2))
8769        (cmp (bit_and @0 { wide_int_to_tree (TREE_TYPE (@0),
8770                                             wi::mask (tree_to_uhwi (@1),
8771                                                       false, prec)); })
8772             { wide_int_to_tree (TREE_TYPE (@0),
8773                                 wi::shifted_mask (tree_to_uhwi (@1) - 1, 1,
8774                                                   false, prec)); }))))))
8776  /* __builtin_ffs (X) > 6 -> X != 0 && (X & 63) == 0.  */
8777  (for cmp (gt le)
8778       cmp2 (ne eq)
8779       cmp3 (eq ne)
8780       bit_op (bit_and bit_ior)
8781   (simplify
8782    (cmp (ffs@2 @0) INTEGER_CST@1)
8783     (with { int prec = TYPE_PRECISION (TREE_TYPE (@0)); }
8784      (switch
8785       (if (integer_zerop (@1))
8786        (cmp2 @0 { build_zero_cst (TREE_TYPE (@0)); }))
8787       (if (tree_int_cst_sgn (@1) < 0)
8788        { constant_boolean_node (cmp == GT_EXPR ? true : false, type); })
8789       (if (wi::to_widest (@1) >= prec)
8790        { constant_boolean_node (cmp == GT_EXPR ? false : true, type); })
8791       (if (wi::to_widest (@1) == prec - 1)
8792        (cmp3 @0 { wide_int_to_tree (TREE_TYPE (@0),
8793                                     wi::shifted_mask (prec - 1, 1,
8794                                                       false, prec)); }))
8795       (if (single_use (@2))
8796        (bit_op (cmp2 @0 { build_zero_cst (TREE_TYPE (@0)); })
8797                (cmp3 (bit_and @0
8798                               { wide_int_to_tree (TREE_TYPE (@0),
8799                                                   wi::mask (tree_to_uhwi (@1),
8800                                                   false, prec)); })
8801                      { build_zero_cst (TREE_TYPE (@0)); }))))))))
8803 #if GIMPLE
8805 /* Simplify:
8806      a = op a1
8807      r = cond ? a : b
8808      --> r = .COND_FN (cond, a, b)
8809 and,
8810     a = op a1
8811     r = cond ? b : a
8812     --> r = .COND_FN (~cond, b, a).  */
8814 (for uncond_op (UNCOND_UNARY)
8815      cond_op (COND_UNARY)
8816  (simplify
8817   (vec_cond @0 (view_convert? (uncond_op@3 @1)) @2)
8818    (with { tree op_type = TREE_TYPE (@3); }
8819     (if (vectorized_internal_fn_supported_p (as_internal_fn (cond_op), op_type)
8820         && is_truth_type_for (op_type, TREE_TYPE (@0)))
8821      (cond_op @0 @1 @2))))
8822  (simplify
8823   (vec_cond @0 @1 (view_convert? (uncond_op@3 @2)))
8824    (with { tree op_type = TREE_TYPE (@3); }
8825     (if (vectorized_internal_fn_supported_p (as_internal_fn (cond_op), op_type)
8826         && is_truth_type_for (op_type, TREE_TYPE (@0)))
8827      (cond_op (bit_not @0) @2 @1)))))
8829 /* `(a ? -1 : 0) ^ b` can be converted into a conditional not.  */
8830 (simplify
8831  (bit_xor:c (vec_cond @0 uniform_integer_cst_p@1 uniform_integer_cst_p@2) @3)
8832  (if (canonicalize_math_after_vectorization_p ()
8833       && vectorized_internal_fn_supported_p (IFN_COND_NOT, type)
8834       && is_truth_type_for (type, TREE_TYPE (@0)))
8835  (if (integer_all_onesp (@1) && integer_zerop (@2))
8836   (IFN_COND_NOT @0 @3 @3))
8837   (if (integer_all_onesp (@2) && integer_zerop (@1))
8838    (IFN_COND_NOT (bit_not @0) @3 @3))))
8840 /* Simplify:
8842      a = a1 op a2
8843      r = c ? a : b;
8845    to:
8847      r = c ? a1 op a2 : b;
8849    if the target can do it in one go.  This makes the operation conditional
8850    on c, so could drop potentially-trapping arithmetic, but that's a valid
8851    simplification if the result of the operation isn't needed.
8853    Avoid speculatively generating a stand-alone vector comparison
8854    on targets that might not support them.  Any target implementing
8855    conditional internal functions must support the same comparisons
8856    inside and outside a VEC_COND_EXPR.  */
8858 (for uncond_op (UNCOND_BINARY)
8859      cond_op (COND_BINARY)
8860  (simplify
8861   (vec_cond @0 (view_convert? (uncond_op@4 @1 @2)) @3)
8862   (with { tree op_type = TREE_TYPE (@4); }
8863    (if (vectorized_internal_fn_supported_p (as_internal_fn (cond_op), op_type)
8864         && is_truth_type_for (op_type, TREE_TYPE (@0))
8865         && single_use (@4))
8866     (view_convert (cond_op @0 @1 @2 (view_convert:op_type @3))))))
8867  (simplify
8868   (vec_cond @0 @1 (view_convert? (uncond_op@4 @2 @3)))
8869   (with { tree op_type = TREE_TYPE (@4); }
8870    (if (vectorized_internal_fn_supported_p (as_internal_fn (cond_op), op_type)
8871         && is_truth_type_for (op_type, TREE_TYPE (@0))
8872         && single_use (@4))
8873     (view_convert (cond_op (bit_not @0) @2 @3 (view_convert:op_type @1)))))))
8875 /* Same for ternary operations.  */
8876 (for uncond_op (UNCOND_TERNARY)
8877      cond_op (COND_TERNARY)
8878  (simplify
8879   (vec_cond @0 (view_convert? (uncond_op@5 @1 @2 @3)) @4)
8880   (with { tree op_type = TREE_TYPE (@5); }
8881    (if (vectorized_internal_fn_supported_p (as_internal_fn (cond_op), op_type)
8882         && is_truth_type_for (op_type, TREE_TYPE (@0))
8883         && single_use (@5))
8884     (view_convert (cond_op @0 @1 @2 @3 (view_convert:op_type @4))))))
8885  (simplify
8886   (vec_cond @0 @1 (view_convert? (uncond_op@5 @2 @3 @4)))
8887   (with { tree op_type = TREE_TYPE (@5); }
8888    (if (vectorized_internal_fn_supported_p (as_internal_fn (cond_op), op_type)
8889         && is_truth_type_for (op_type, TREE_TYPE (@0))
8890         && single_use (@5))
8891     (view_convert (cond_op (bit_not @0) @2 @3 @4
8892                   (view_convert:op_type @1)))))))
8893 #endif
8895 /* Detect cases in which a VEC_COND_EXPR effectively replaces the
8896    "else" value of an IFN_COND_*.  */
8897 (for cond_op (COND_BINARY)
8898  (simplify
8899   (vec_cond @0 (view_convert? (cond_op @0 @1 @2 @3)) @4)
8900   (with { tree op_type = TREE_TYPE (@3); }
8901    (if (element_precision (type) == element_precision (op_type))
8902     (view_convert (cond_op @0 @1 @2 (view_convert:op_type @4))))))
8903  (simplify
8904   (vec_cond @0 @1 (view_convert? (cond_op @2 @3 @4 @5)))
8905   (with { tree op_type = TREE_TYPE (@5); }
8906    (if (inverse_conditions_p (@0, @2)
8907         && element_precision (type) == element_precision (op_type))
8908     (view_convert (cond_op @2 @3 @4 (view_convert:op_type @1)))))))
8910 /* Same for ternary operations.  */
8911 (for cond_op (COND_TERNARY)
8912  (simplify
8913   (vec_cond @0 (view_convert? (cond_op @0 @1 @2 @3 @4)) @5)
8914   (with { tree op_type = TREE_TYPE (@4); }
8915    (if (element_precision (type) == element_precision (op_type))
8916     (view_convert (cond_op @0 @1 @2 @3 (view_convert:op_type @5))))))
8917  (simplify
8918   (vec_cond @0 @1 (view_convert? (cond_op @2 @3 @4 @5 @6)))
8919   (with { tree op_type = TREE_TYPE (@6); }
8920    (if (inverse_conditions_p (@0, @2)
8921         && element_precision (type) == element_precision (op_type))
8922     (view_convert (cond_op @2 @3 @4 @5 (view_convert:op_type @1)))))))
8924 /* Detect simplication for a conditional reduction where
8926    a = mask1 ? b : 0
8927    c = mask2 ? d + a : d
8929    is turned into
8931    c = mask1 && mask2 ? d + b : d.  */
8932 (simplify
8933   (IFN_COND_ADD @0 @1 (vec_cond @2 @3 zerop@4) @1)
8934    (if (ANY_INTEGRAL_TYPE_P (type)
8935         || (FLOAT_TYPE_P (type)
8936             && fold_real_zero_addition_p (type, NULL_TREE, @4, 0)))
8937    (IFN_COND_ADD (bit_and @0 @2) @1 @3 @1)))
8939 /* Detect simplication for a conditional length reduction where
8941    a = mask ? b : 0
8942    c = i < len + bias ? d + a : d
8944    is turned into
8946    c = mask && i < len + bias ? d + b : d.  */
8947 (simplify
8948   (IFN_COND_LEN_ADD integer_truep @0 (vec_cond @1 @2 zerop@5) @0 @3 @4)
8949    (if (ANY_INTEGRAL_TYPE_P (type)
8950         || (FLOAT_TYPE_P (type)
8951             && fold_real_zero_addition_p (type, NULL_TREE, @5, 0)))
8952     (IFN_COND_LEN_ADD @1 @0 @2 @0 @3 @4)))
8954 /* For pointers @0 and @2 and nonnegative constant offset @1, look for
8955    expressions like:
8957    A: (@0 + @1 < @2) | (@2 + @1 < @0)
8958    B: (@0 + @1 <= @2) | (@2 + @1 <= @0)
8960    If pointers are known not to wrap, B checks whether @1 bytes starting
8961    at @0 and @2 do not overlap, while A tests the same thing for @1 + 1
8962    bytes.  A is more efficiently tested as:
8964    A: (sizetype) (@0 + @1 - @2) > @1 * 2
8966    The equivalent expression for B is given by replacing @1 with @1 - 1:
8968    B: (sizetype) (@0 + (@1 - 1) - @2) > (@1 - 1) * 2
8970    @0 and @2 can be swapped in both expressions without changing the result.
8972    The folds rely on sizetype's being unsigned (which is always true)
8973    and on its being the same width as the pointer (which we have to check).
8975    The fold replaces two pointer_plus expressions, two comparisons and
8976    an IOR with a pointer_plus, a pointer_diff, and a comparison, so in
8977    the best case it's a saving of two operations.  The A fold retains one
8978    of the original pointer_pluses, so is a win even if both pointer_pluses
8979    are used elsewhere.  The B fold is a wash if both pointer_pluses are
8980    used elsewhere, since all we end up doing is replacing a comparison with
8981    a pointer_plus.  We do still apply the fold under those circumstances
8982    though, in case applying it to other conditions eventually makes one of the
8983    pointer_pluses dead.  */
8984 (for ior (truth_orif truth_or bit_ior)
8985  (for cmp (le lt)
8986   (simplify
8987    (ior (cmp:cs (pointer_plus@3 @0 INTEGER_CST@1) @2)
8988         (cmp:cs (pointer_plus@4 @2 @1) @0))
8989    (if (TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (@0))
8990         && TYPE_OVERFLOW_WRAPS (sizetype)
8991         && TYPE_PRECISION (TREE_TYPE (@0)) == TYPE_PRECISION (sizetype))
8992     /* Calculate the rhs constant.  */
8993     (with { offset_int off = wi::to_offset (@1) - (cmp == LE_EXPR ? 1 : 0);
8994             offset_int rhs = off * 2; }
8995      /* Always fails for negative values.  */
8996      (if (wi::min_precision (rhs, UNSIGNED) <= TYPE_PRECISION (sizetype))
8997       /* Since the order of @0 and @2 doesn't matter, let tree_swap_operands_p
8998          pick a canonical order.  This increases the chances of using the
8999          same pointer_plus in multiple checks.  */
9000       (with { bool swap_p = tree_swap_operands_p (@0, @2);
9001               tree rhs_tree = wide_int_to_tree (sizetype, rhs); }
9002        (if (cmp == LT_EXPR)
9003         (gt (convert:sizetype
9004              (pointer_diff:ssizetype { swap_p ? @4 : @3; }
9005                                      { swap_p ? @0 : @2; }))
9006             { rhs_tree; })
9007         (gt (convert:sizetype
9008              (pointer_diff:ssizetype
9009               (pointer_plus { swap_p ? @2 : @0; }
9010                             { wide_int_to_tree (sizetype, off); })
9011               { swap_p ? @0 : @2; }))
9012             { rhs_tree; })))))))))
9014 /* Fold REDUC (@0 & @1) -> @0[I] & @1[I] if element I is the only nonzero
9015    element of @1.  */
9016 (for reduc (IFN_REDUC_PLUS IFN_REDUC_IOR IFN_REDUC_XOR)
9017  (simplify (reduc (view_convert? (bit_and @0 VECTOR_CST@1)))
9018   (with { int i = single_nonzero_element (@1); }
9019    (if (i >= 0)
9020     (with { tree elt = vector_cst_elt (@1, i);
9021             tree elt_type = TREE_TYPE (elt);
9022             unsigned int elt_bits = tree_to_uhwi (TYPE_SIZE (elt_type));
9023             tree size = bitsize_int (elt_bits);
9024             tree pos = bitsize_int (elt_bits * i); }
9025      (view_convert
9026       (bit_and:elt_type
9027        (BIT_FIELD_REF:elt_type @0 { size; } { pos; })
9028        { elt; })))))))
9030 /* Fold reduction of a single nonzero element constructor.  */
9031 (for reduc (IFN_REDUC_PLUS IFN_REDUC_IOR IFN_REDUC_XOR)
9032   (simplify (reduc (CONSTRUCTOR@0))
9033     (with { tree ctor = (TREE_CODE (@0) == SSA_NAME
9034                          ? gimple_assign_rhs1 (SSA_NAME_DEF_STMT (@0)) : @0);
9035             tree elt = ctor_single_nonzero_element (ctor); }
9036       (if (elt
9037            && !HONOR_SNANS (type)
9038            && !HONOR_SIGNED_ZEROS (type))
9039         { elt; }))))
9041 /* Fold REDUC (@0 op VECTOR_CST) as REDUC (@0) op REDUC (VECTOR_CST).  */
9042 (for reduc (IFN_REDUC_PLUS IFN_REDUC_MAX IFN_REDUC_MIN IFN_REDUC_FMAX
9043             IFN_REDUC_FMIN IFN_REDUC_AND IFN_REDUC_IOR IFN_REDUC_XOR)
9044      op (plus max min IFN_FMAX IFN_FMIN bit_and bit_ior bit_xor)
9045   (simplify (reduc (op @0 VECTOR_CST@1))
9046     (op (reduc:type @0) (reduc:type @1))))
9048 /* Simplify vector floating point operations of alternating sub/add pairs
9049    into using an fneg of a wider element type followed by a normal add.
9050    under IEEE 754 the fneg of the wider type will negate every even entry
9051    and when doing an add we get a sub of the even and add of every odd
9052    elements.  */
9053 (for plusminus (plus minus)
9054      minusplus (minus plus)
9055  (simplify
9056   (vec_perm (plusminus @0 @1) (minusplus @2 @3) VECTOR_CST@4)
9057    (if (!VECTOR_INTEGER_TYPE_P (type)
9058         && !FLOAT_WORDS_BIG_ENDIAN
9059         /* plus is commutative, while minus is not, so :c can't be used.
9060            Do equality comparisons by hand and at the end pick the operands
9061            from the minus.  */
9062         && (operand_equal_p (@0, @2, 0)
9063             ? operand_equal_p (@1, @3, 0)
9064             : operand_equal_p (@0, @3, 0) && operand_equal_p (@1, @2, 0)))
9065    (with
9066     {
9067       /* Build a vector of integers from the tree mask.  */
9068       vec_perm_builder builder;
9069     }
9070     (if (tree_to_vec_perm_builder (&builder, @4))
9071      (with
9072       {
9073         /* Create a vec_perm_indices for the integer vector.  */
9074         poly_uint64 nelts = TYPE_VECTOR_SUBPARTS (type);
9075         vec_perm_indices sel (builder, 2, nelts);
9076         machine_mode vec_mode = TYPE_MODE (type);
9077         machine_mode wide_mode;
9078         scalar_mode wide_elt_mode;
9079         poly_uint64 wide_nunits;
9080         scalar_mode inner_mode = GET_MODE_INNER (vec_mode);
9081       }
9082       (if (VECTOR_MODE_P (vec_mode)
9083            && sel.series_p (0, 2, 0, 2)
9084            && sel.series_p (1, 2, nelts + 1, 2)
9085            && GET_MODE_2XWIDER_MODE (inner_mode).exists (&wide_elt_mode)
9086            && multiple_p (GET_MODE_NUNITS (vec_mode), 2, &wide_nunits)
9087            && related_vector_mode (vec_mode, wide_elt_mode,
9088                                    wide_nunits).exists (&wide_mode))
9089        (with
9090         {
9091           tree stype
9092             = lang_hooks.types.type_for_mode (GET_MODE_INNER (wide_mode),
9093                                               TYPE_UNSIGNED (type));
9094           tree ntype = build_vector_type_for_mode (stype, wide_mode);
9096           /* The format has to be a non-extended ieee format.  */
9097           const struct real_format *fmt_old = FLOAT_MODE_FORMAT (vec_mode);
9098           const struct real_format *fmt_new = FLOAT_MODE_FORMAT (wide_mode);
9099         }
9100         (if (TYPE_MODE (stype) != BLKmode
9101              && VECTOR_TYPE_P (ntype)
9102              && fmt_old != NULL
9103              && fmt_new != NULL)
9104          (with
9105           {
9106             /* If the target doesn't support v1xx vectors, try using
9107                scalar mode xx instead.  */
9108             if (known_eq (GET_MODE_NUNITS (wide_mode), 1)
9109                 && !target_supports_op_p (ntype, NEGATE_EXPR, optab_vector))
9110               ntype = stype;
9111           }
9112           (if (fmt_new->signbit_rw
9113                == fmt_old->signbit_rw + GET_MODE_UNIT_BITSIZE (vec_mode)
9114                && fmt_new->signbit_rw == fmt_new->signbit_ro
9115                && targetm.can_change_mode_class (TYPE_MODE (ntype),
9116                                                  TYPE_MODE (type), ALL_REGS)
9117                && ((optimize_vectors_before_lowering_p ()
9118                     && VECTOR_TYPE_P (ntype))
9119                    || target_supports_op_p (ntype, NEGATE_EXPR, optab_vector)))
9120            (if (plusminus == PLUS_EXPR)
9121             (plus (view_convert:type (negate (view_convert:ntype @3))) @2)
9122             (minus @0 (view_convert:type
9123                         (negate (view_convert:ntype @1))))))))))))))))
9125 (simplify
9126  (vec_perm @0 @1 VECTOR_CST@2)
9127  (with
9128   {
9129     tree op0 = @0, op1 = @1, op2 = @2;
9130     machine_mode result_mode = TYPE_MODE (type);
9131     machine_mode op_mode = TYPE_MODE (TREE_TYPE (op0));
9133     /* Build a vector of integers from the tree mask.  */
9134     vec_perm_builder builder;
9135   }
9136   (if (tree_to_vec_perm_builder (&builder, op2))
9137    (with
9138     {
9139       /* Create a vec_perm_indices for the integer vector.  */
9140       poly_uint64 nelts = TYPE_VECTOR_SUBPARTS (type);
9141       bool single_arg = (op0 == op1);
9142       vec_perm_indices sel (builder, single_arg ? 1 : 2, nelts);
9143     }
9144     (if (sel.series_p (0, 1, 0, 1))
9145      { op0; }
9146      (if (sel.series_p (0, 1, nelts, 1))
9147       { op1; }
9148       (with
9149        {
9150          if (!single_arg)
9151            {
9152              if (sel.all_from_input_p (0))
9153                op1 = op0;
9154              else if (sel.all_from_input_p (1))
9155                {
9156                  op0 = op1;
9157                  sel.rotate_inputs (1);
9158                }
9159              else if (known_ge (poly_uint64 (sel[0]), nelts))
9160                {
9161                  std::swap (op0, op1);
9162                  sel.rotate_inputs (1);
9163                }
9164            }
9165          gassign *def;
9166          tree cop0 = op0, cop1 = op1;
9167          if (TREE_CODE (op0) == SSA_NAME
9168              && (def = dyn_cast <gassign *> (SSA_NAME_DEF_STMT (op0)))
9169              && gimple_assign_rhs_code (def) == CONSTRUCTOR)
9170            cop0 = gimple_assign_rhs1 (def);
9171          if (TREE_CODE (op1) == SSA_NAME
9172              && (def = dyn_cast <gassign *> (SSA_NAME_DEF_STMT (op1)))
9173              && gimple_assign_rhs_code (def) == CONSTRUCTOR)
9174            cop1 = gimple_assign_rhs1 (def);
9175          tree t;
9176        }
9177        (if ((TREE_CODE (cop0) == VECTOR_CST
9178              || TREE_CODE (cop0) == CONSTRUCTOR)
9179             && (TREE_CODE (cop1) == VECTOR_CST
9180                 || TREE_CODE (cop1) == CONSTRUCTOR)
9181             && (t = fold_vec_perm (type, cop0, cop1, sel)))
9182         { t; }
9183         (with
9184          {
9185            bool changed = (op0 == op1 && !single_arg);
9186            tree ins = NULL_TREE;
9187            unsigned at = 0;
9189            /* See if the permutation is performing a single element
9190               insert from a CONSTRUCTOR or constant and use a BIT_INSERT_EXPR
9191               in that case.  But only if the vector mode is supported,
9192               otherwise this is invalid GIMPLE.  */
9193            if (op_mode != BLKmode
9194                && (TREE_CODE (cop0) == VECTOR_CST
9195                    || TREE_CODE (cop0) == CONSTRUCTOR
9196                    || TREE_CODE (cop1) == VECTOR_CST
9197                    || TREE_CODE (cop1) == CONSTRUCTOR))
9198              {
9199                bool insert_first_p = sel.series_p (1, 1, nelts + 1, 1);
9200                if (insert_first_p)
9201                  {
9202                    /* After canonicalizing the first elt to come from the
9203                       first vector we only can insert the first elt from
9204                       the first vector.  */
9205                    at = 0;
9206                    if ((ins = fold_read_from_vector (cop0, sel[0])))
9207                      op0 = op1;
9208                  }
9209                /* The above can fail for two-element vectors which always
9210                   appear to insert the first element, so try inserting
9211                   into the second lane as well.  For more than two
9212                   elements that's wasted time.  */
9213                if (!insert_first_p || (!ins && maybe_eq (nelts, 2u)))
9214                  {
9215                    unsigned int encoded_nelts = sel.encoding ().encoded_nelts ();
9216                    for (at = 0; at < encoded_nelts; ++at)
9217                      if (maybe_ne (sel[at], at))
9218                        break;
9219                    if (at < encoded_nelts
9220                        && (known_eq (at + 1, nelts)
9221                            || sel.series_p (at + 1, 1, at + 1, 1)))
9222                      {
9223                        if (known_lt (poly_uint64 (sel[at]), nelts))
9224                          ins = fold_read_from_vector (cop0, sel[at]);
9225                        else
9226                          ins = fold_read_from_vector (cop1, sel[at] - nelts);
9227                      }
9228                  }
9229              }
9231            /* Generate a canonical form of the selector.  */
9232            if (!ins && sel.encoding () != builder)
9233              {
9234                /* Some targets are deficient and fail to expand a single
9235                   argument permutation while still allowing an equivalent
9236                   2-argument version.  */
9237                tree oldop2 = op2;
9238                if (sel.ninputs () == 2
9239                    || can_vec_perm_const_p (result_mode, op_mode, sel, false))
9240                  op2 = vec_perm_indices_to_tree (TREE_TYPE (op2), sel);
9241                else
9242                  {
9243                    vec_perm_indices sel2 (builder, 2, nelts);
9244                    if (can_vec_perm_const_p (result_mode, op_mode, sel2, false))
9245                      op2 = vec_perm_indices_to_tree (TREE_TYPE (op2), sel2);
9246                    else
9247                      /* Not directly supported with either encoding,
9248                         so use the preferred form.  */
9249                      op2 = vec_perm_indices_to_tree (TREE_TYPE (op2), sel);
9250                  }
9251                if (!operand_equal_p (op2, oldop2, 0))
9252                  changed = true;
9253              }
9254          }
9255          (if (ins)
9256           (bit_insert { op0; } { ins; }
9257            { bitsize_int (at * vector_element_bits (type)); })
9258           (if (changed)
9259            (vec_perm { op0; } { op1; } { op2; }))))))))))))
9261 /* VEC_PERM_EXPR (v, v, mask) -> v where v contains same element.  */
9263 (match vec_same_elem_p
9264  (vec_duplicate @0))
9266 (match vec_same_elem_p
9267  CONSTRUCTOR@0
9268  (if (TREE_CODE (@0) == SSA_NAME
9269       && uniform_vector_p (gimple_assign_rhs1 (SSA_NAME_DEF_STMT (@0))))))
9271 (match vec_same_elem_p
9272  @0
9273  (if (uniform_vector_p (@0))))
9276 (simplify
9277  (vec_perm vec_same_elem_p@0 @0 @1)
9278  (if (types_match (type, TREE_TYPE (@0)))
9279   @0
9280   (with
9281    {
9282      tree elem = uniform_vector_p (@0);
9283    }
9284    (if (elem)
9285     { build_vector_from_val (type, elem); }))))
9287 /* Push VEC_PERM earlier if that may help FMA perception (PR101895).  */
9288 (simplify
9289  (plus:c (vec_perm:s (mult:c@0 @1 vec_same_elem_p@2) @0 @3) @4)
9290  (if (TREE_CODE (@0) == SSA_NAME && num_imm_uses (@0) == 2)
9291   (plus (mult (vec_perm @1 @1 @3) @2) @4)))
9292 (simplify
9293  (minus (vec_perm:s (mult:c@0 @1 vec_same_elem_p@2) @0 @3) @4)
9294  (if (TREE_CODE (@0) == SSA_NAME && num_imm_uses (@0) == 2)
9295   (minus (mult (vec_perm @1 @1 @3) @2) @4)))
9298 /* Merge
9299      c = VEC_PERM_EXPR <a, b, VCST0>;
9300      d = VEC_PERM_EXPR <c, c, VCST1>;
9301    to
9302      d = VEC_PERM_EXPR <a, b, NEW_VCST>;  */
9304 (simplify
9305  (vec_perm (vec_perm@0 @1 @2 VECTOR_CST@3) @0 VECTOR_CST@4)
9306  (if (TYPE_VECTOR_SUBPARTS (type).is_constant ())
9307   (with
9308    {
9309      machine_mode result_mode = TYPE_MODE (type);
9310      machine_mode op_mode = TYPE_MODE (TREE_TYPE (@1));
9311      int nelts = TYPE_VECTOR_SUBPARTS (type).to_constant ();
9312      vec_perm_builder builder0;
9313      vec_perm_builder builder1;
9314      vec_perm_builder builder2 (nelts, nelts, 1);
9315    }
9316    (if (tree_to_vec_perm_builder (&builder0, @3)
9317         && tree_to_vec_perm_builder (&builder1, @4))
9318     (with
9319      {
9320        vec_perm_indices sel0 (builder0, 2, nelts);
9321        vec_perm_indices sel1 (builder1, 1, nelts);
9323        for (int i = 0; i < nelts; i++)
9324          builder2.quick_push (sel0[sel1[i].to_constant ()]);
9326        vec_perm_indices sel2 (builder2, 2, nelts);
9328        tree op0 = NULL_TREE;
9329        /* If the new VEC_PERM_EXPR can't be handled but both
9330           original VEC_PERM_EXPRs can, punt.
9331           If one or both of the original VEC_PERM_EXPRs can't be
9332           handled and the new one can't be either, don't increase
9333           number of VEC_PERM_EXPRs that can't be handled.  */
9334        if (can_vec_perm_const_p (result_mode, op_mode, sel2, false)
9335            || (single_use (@0)
9336                ? (!can_vec_perm_const_p (result_mode, op_mode, sel0, false)
9337                   || !can_vec_perm_const_p (result_mode, op_mode, sel1, false))
9338                : !can_vec_perm_const_p (result_mode, op_mode, sel1, false)))
9339          op0 = vec_perm_indices_to_tree (TREE_TYPE (@4), sel2);
9340      }
9341      (if (op0)
9342       (vec_perm @1 @2 { op0; })))))))
9344 /* Merge
9345      c = VEC_PERM_EXPR <a, b, VCST0>;
9346      d = VEC_PERM_EXPR <x, c, VCST1>;
9347    to
9348      d = VEC_PERM_EXPR <x, {a,b}, NEW_VCST>;
9349    when all elements from a or b are replaced by the later
9350    permutation.  */
9352 (simplify
9353  (vec_perm @5 (vec_perm@0 @1 @2 VECTOR_CST@3) VECTOR_CST@4)
9354  (if (TYPE_VECTOR_SUBPARTS (type).is_constant ())
9355   (with
9356    {
9357      machine_mode result_mode = TYPE_MODE (type);
9358      machine_mode op_mode = TYPE_MODE (TREE_TYPE (@1));
9359      int nelts = TYPE_VECTOR_SUBPARTS (type).to_constant ();
9360      vec_perm_builder builder0;
9361      vec_perm_builder builder1;
9362      vec_perm_builder builder2 (nelts, nelts, 2);
9363    }
9364    (if (tree_to_vec_perm_builder (&builder0, @3)
9365         && tree_to_vec_perm_builder (&builder1, @4))
9366     (with
9367      {
9368        vec_perm_indices sel0 (builder0, 2, nelts);
9369        vec_perm_indices sel1 (builder1, 2, nelts);
9370        bool use_1 = false, use_2 = false;
9372        for (int i = 0; i < nelts; i++)
9373          {
9374            if (known_lt ((poly_uint64)sel1[i], sel1.nelts_per_input ()))
9375              builder2.quick_push (sel1[i]);
9376            else
9377              {
9378                poly_uint64 j = sel0[(sel1[i] - sel1.nelts_per_input ())
9379                                     .to_constant ()];
9380                if (known_lt (j, sel0.nelts_per_input ()))
9381                  use_1 = true;
9382                else
9383                  {
9384                    use_2 = true;
9385                    j -= sel0.nelts_per_input ();
9386                  }
9387                builder2.quick_push (j + sel1.nelts_per_input ());
9388              }
9389          }
9390      }
9391      (if (use_1 ^ use_2)
9392       (with
9393        {
9394          vec_perm_indices sel2 (builder2, 2, nelts);
9395          tree op0 = NULL_TREE;
9396          /* If the new VEC_PERM_EXPR can't be handled but both
9397             original VEC_PERM_EXPRs can, punt.
9398             If one or both of the original VEC_PERM_EXPRs can't be
9399             handled and the new one can't be either, don't increase
9400             number of VEC_PERM_EXPRs that can't be handled.  */
9401          if (can_vec_perm_const_p (result_mode, op_mode, sel2, false)
9402              || (single_use (@0)
9403                  ? (!can_vec_perm_const_p (result_mode, op_mode, sel0, false)
9404                     || !can_vec_perm_const_p (result_mode, op_mode, sel1, false))
9405                  : !can_vec_perm_const_p (result_mode, op_mode, sel1, false)))
9406            op0 = vec_perm_indices_to_tree (TREE_TYPE (@4), sel2);
9407        }
9408        (if (op0)
9409         (switch
9410          (if (use_1)
9411           (vec_perm @5 @1 { op0; }))
9412          (if (use_2)
9413           (vec_perm @5 @2 { op0; })))))))))))
9415 /* And the case with swapped outer permute sources.  */
9417 (simplify
9418  (vec_perm (vec_perm@0 @1 @2 VECTOR_CST@3) @5 VECTOR_CST@4)
9419  (if (TYPE_VECTOR_SUBPARTS (type).is_constant ())
9420   (with
9421    {
9422      machine_mode result_mode = TYPE_MODE (type);
9423      machine_mode op_mode = TYPE_MODE (TREE_TYPE (@1));
9424      int nelts = TYPE_VECTOR_SUBPARTS (type).to_constant ();
9425      vec_perm_builder builder0;
9426      vec_perm_builder builder1;
9427      vec_perm_builder builder2 (nelts, nelts, 2);
9428    }
9429    (if (tree_to_vec_perm_builder (&builder0, @3)
9430         && tree_to_vec_perm_builder (&builder1, @4))
9431     (with
9432      {
9433        vec_perm_indices sel0 (builder0, 2, nelts);
9434        vec_perm_indices sel1 (builder1, 2, nelts);
9435        bool use_1 = false, use_2 = false;
9437        for (int i = 0; i < nelts; i++)
9438          {
9439            if (known_ge ((poly_uint64)sel1[i], sel1.nelts_per_input ()))
9440              builder2.quick_push (sel1[i]);
9441            else
9442              {
9443                poly_uint64 j = sel0[sel1[i].to_constant ()];
9444                if (known_lt (j, sel0.nelts_per_input ()))
9445                  use_1 = true;
9446                else
9447                  {
9448                    use_2 = true;
9449                    j -= sel0.nelts_per_input ();
9450                  }
9451                builder2.quick_push (j);
9452              }
9453          }
9454      }
9455      (if (use_1 ^ use_2)
9456       (with
9457        {
9458          vec_perm_indices sel2 (builder2, 2, nelts);
9459          tree op0 = NULL_TREE;
9460          /* If the new VEC_PERM_EXPR can't be handled but both
9461             original VEC_PERM_EXPRs can, punt.
9462             If one or both of the original VEC_PERM_EXPRs can't be
9463             handled and the new one can't be either, don't increase
9464             number of VEC_PERM_EXPRs that can't be handled.  */
9465          if (can_vec_perm_const_p (result_mode, op_mode, sel2, false)
9466              || (single_use (@0)
9467                  ? (!can_vec_perm_const_p (result_mode, op_mode, sel0, false)
9468                     || !can_vec_perm_const_p (result_mode, op_mode, sel1, false))
9469                  : !can_vec_perm_const_p (result_mode, op_mode, sel1, false)))
9470            op0 = vec_perm_indices_to_tree (TREE_TYPE (@4), sel2);
9471        }
9472        (if (op0)
9473         (switch
9474          (if (use_1)
9475           (vec_perm @1 @5 { op0; }))
9476          (if (use_2)
9477           (vec_perm @2 @5 { op0; })))))))))))
9480 /* Match count trailing zeroes for simplify_count_trailing_zeroes in fwprop.
9481    The canonical form is array[((x & -x) * C) >> SHIFT] where C is a magic
9482    constant which when multiplied by a power of 2 contains a unique value
9483    in the top 5 or 6 bits.  This is then indexed into a table which maps it
9484    to the number of trailing zeroes.  */
9485 (match (ctz_table_index @1 @2 @3)
9486   (rshift (mult (bit_and:c (negate @1) @1) INTEGER_CST@2) INTEGER_CST@3))
9488 (match (cond_expr_convert_p @0 @2 @3 @6)
9489  (cond (simple_comparison@6 @0 @1) (convert@4 @2) (convert@5 @3))
9490   (if (INTEGRAL_TYPE_P (type)
9491        && INTEGRAL_TYPE_P (TREE_TYPE (@2))
9492        && INTEGRAL_TYPE_P (TREE_TYPE (@0))
9493        && INTEGRAL_TYPE_P (TREE_TYPE (@3))
9494        && TYPE_PRECISION (type) != TYPE_PRECISION (TREE_TYPE (@0))
9495        && TYPE_PRECISION (TREE_TYPE (@0))
9496           == TYPE_PRECISION (TREE_TYPE (@2))
9497        && TYPE_PRECISION (TREE_TYPE (@0))
9498           == TYPE_PRECISION (TREE_TYPE (@3))
9499        /* For vect_recog_cond_expr_convert_pattern, @2 and @3 can differ in
9500           signess when convert is truncation, but not ok for extension since
9501           it's sign_extend vs zero_extend.  */
9502        && (TYPE_PRECISION (TREE_TYPE (@0)) > TYPE_PRECISION (type)
9503            || (TYPE_UNSIGNED (TREE_TYPE (@2))
9504                == TYPE_UNSIGNED (TREE_TYPE (@3))))
9505        && single_use (@4)
9506        && single_use (@5))))
9508 (for bit_op (bit_and bit_ior bit_xor)
9509  (match (bitwise_induction_p @0 @2 @3)
9510   (bit_op:c
9511    (nop_convert1? (bit_not2?@0 (convert3? (lshift integer_onep@1 @2))))
9512    @3)))
9514 (match (bitwise_induction_p @0 @2 @3)
9515  (bit_not
9516   (nop_convert1? (bit_xor@0 (convert2? (lshift integer_onep@1 @2)) @3))))
9518 /* n - (((n > C1) ? n : C1) & -C2) ->  n & C1 for unsigned case.
9519    n - (((n > C1) ? n : C1) & -C2) ->  (n <= C1) ? n : (n & C1) for signed case.  */
9520 (simplify
9521   (minus @0 (bit_and (max @0 INTEGER_CST@1) INTEGER_CST@2))
9522   (with { auto i = wi::neg (wi::to_wide (@2)); }
9523   /* Check if -C2 is a power of 2 and C1 = -C2 - 1.  */
9524     (if (wi::popcount (i) == 1
9525          && (wi::to_wide (@1)) == (i - 1))
9526       (if (TYPE_UNSIGNED (TREE_TYPE (@0)))
9527         (bit_and @0 @1)
9528       (cond (le @0 @1) @0 (bit_and @0 @1))))))
9530 /* -x & 1 -> x & 1.  */
9531 (simplify 
9532  (bit_and (negate @0) integer_onep@1)
9533  (if (!TYPE_OVERFLOW_SANITIZED (type))
9534   (bit_and @0 @1)))
9536 /* `-a` is just `a` if the type is 1bit wide or when converting
9537    to a 1bit type; similar to the above transformation of `(-x)&1`.
9538    This is used mostly with the transformation of
9539    `a ? ~b : b` into `(-a)^b`.
9540    It also can show up with bitfields.  */
9541 (simplify
9542  (convert? (negate @0))
9543  (if (INTEGRAL_TYPE_P (type)
9544       && TYPE_PRECISION (type) == 1
9545       && !TYPE_OVERFLOW_SANITIZED (TREE_TYPE (@0)))
9546   (convert @0)))
9548 /* Optimize
9549    c1 = VEC_PERM_EXPR (a, a, mask)
9550    c2 = VEC_PERM_EXPR (b, b, mask)
9551    c3 = c1 op c2
9552    -->
9553    c = a op b
9554    c3 = VEC_PERM_EXPR (c, c, mask)
9555    For all integer non-div operations.  */
9556 (for op (plus minus mult bit_and bit_ior bit_xor
9557          lshift rshift)
9558  (simplify
9559   (op (vec_perm @0 @0 @2) (vec_perm @1 @1 @2))
9560    (if (VECTOR_INTEGER_TYPE_P (type))
9561     (vec_perm (op@3 @0 @1) @3 @2))))
9563 /* Similar for float arithmetic when permutation constant covers
9564    all vector elements.  */
9565 (for op (plus minus mult)
9566  (simplify
9567   (op (vec_perm @0 @0 VECTOR_CST@2) (vec_perm @1 @1 VECTOR_CST@2))
9568    (if (VECTOR_FLOAT_TYPE_P (type)
9569         && TYPE_VECTOR_SUBPARTS (type).is_constant ())
9570     (with
9571      {
9572        tree perm_cst = @2;
9573        vec_perm_builder builder;
9574        bool full_perm_p = false;
9575        if (tree_to_vec_perm_builder (&builder, perm_cst))
9576          {
9577            unsigned HOST_WIDE_INT nelts;
9579            nelts = TYPE_VECTOR_SUBPARTS (type).to_constant ();
9580            /* Create a vec_perm_indices for the VECTOR_CST.  */
9581            vec_perm_indices sel (builder, 1, nelts);
9583            /* Check if perm indices covers all vector elements.  */
9584            if (sel.encoding ().encoded_full_vector_p ())
9585              {
9586                auto_sbitmap seen (nelts);
9587                bitmap_clear (seen);
9589                unsigned HOST_WIDE_INT count = 0, i;
9591                for (i = 0; i < nelts; i++)
9592                  {
9593                    if (!bitmap_set_bit (seen, sel[i].to_constant ()))
9594                     break;
9595                    count++;
9596                  }
9597                full_perm_p = count == nelts;
9598              }
9599          }
9600       }
9601       (if (full_perm_p)
9602         (vec_perm (op@3 @0 @1) @3 @2))))))